VirtualBox

source: vbox/trunk/src/VBox/Storage/VMDK.cpp@ 63658

Last change on this file since 63658 was 63644, checked in by vboxsync, 8 years ago

VMDK: Fix possible endless loop when reading when processing the grain directory

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 244.6 KB
Line 
1/* $Id: VMDK.cpp 63644 2016-08-26 08:09:14Z vboxsync $ */
2/** @file
3 * VMDK disk image, core code.
4 */
5
6/*
7 * Copyright (C) 2006-2016 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#define LOG_GROUP LOG_GROUP_VD_VMDK
23#include <VBox/vd-plugin.h>
24#include <VBox/err.h>
25
26#include <VBox/log.h>
27#include <iprt/assert.h>
28#include <iprt/alloc.h>
29#include <iprt/uuid.h>
30#include <iprt/path.h>
31#include <iprt/string.h>
32#include <iprt/rand.h>
33#include <iprt/zip.h>
34#include <iprt/asm.h>
35
36#include "VDBackends.h"
37
38
39/*********************************************************************************************************************************
40* Constants And Macros, Structures and Typedefs *
41*********************************************************************************************************************************/
42
43/** Maximum encoded string size (including NUL) we allow for VMDK images.
44 * Deliberately not set high to avoid running out of descriptor space. */
45#define VMDK_ENCODED_COMMENT_MAX 1024
46
47/** VMDK descriptor DDB entry for PCHS cylinders. */
48#define VMDK_DDB_GEO_PCHS_CYLINDERS "ddb.geometry.cylinders"
49
50/** VMDK descriptor DDB entry for PCHS heads. */
51#define VMDK_DDB_GEO_PCHS_HEADS "ddb.geometry.heads"
52
53/** VMDK descriptor DDB entry for PCHS sectors. */
54#define VMDK_DDB_GEO_PCHS_SECTORS "ddb.geometry.sectors"
55
56/** VMDK descriptor DDB entry for LCHS cylinders. */
57#define VMDK_DDB_GEO_LCHS_CYLINDERS "ddb.geometry.biosCylinders"
58
59/** VMDK descriptor DDB entry for LCHS heads. */
60#define VMDK_DDB_GEO_LCHS_HEADS "ddb.geometry.biosHeads"
61
62/** VMDK descriptor DDB entry for LCHS sectors. */
63#define VMDK_DDB_GEO_LCHS_SECTORS "ddb.geometry.biosSectors"
64
65/** VMDK descriptor DDB entry for image UUID. */
66#define VMDK_DDB_IMAGE_UUID "ddb.uuid.image"
67
68/** VMDK descriptor DDB entry for image modification UUID. */
69#define VMDK_DDB_MODIFICATION_UUID "ddb.uuid.modification"
70
71/** VMDK descriptor DDB entry for parent image UUID. */
72#define VMDK_DDB_PARENT_UUID "ddb.uuid.parent"
73
74/** VMDK descriptor DDB entry for parent image modification UUID. */
75#define VMDK_DDB_PARENT_MODIFICATION_UUID "ddb.uuid.parentmodification"
76
77/** No compression for streamOptimized files. */
78#define VMDK_COMPRESSION_NONE 0
79
80/** Deflate compression for streamOptimized files. */
81#define VMDK_COMPRESSION_DEFLATE 1
82
83/** Marker that the actual GD value is stored in the footer. */
84#define VMDK_GD_AT_END 0xffffffffffffffffULL
85
86/** Marker for end-of-stream in streamOptimized images. */
87#define VMDK_MARKER_EOS 0
88
89/** Marker for grain table block in streamOptimized images. */
90#define VMDK_MARKER_GT 1
91
92/** Marker for grain directory block in streamOptimized images. */
93#define VMDK_MARKER_GD 2
94
95/** Marker for footer in streamOptimized images. */
96#define VMDK_MARKER_FOOTER 3
97
98/** Marker for unknown purpose in streamOptimized images.
99 * Shows up in very recent images created by vSphere, but only sporadically.
100 * They "forgot" to document that one in the VMDK specification. */
101#define VMDK_MARKER_UNSPECIFIED 4
102
103/** Dummy marker for "don't check the marker value". */
104#define VMDK_MARKER_IGNORE 0xffffffffU
105
106/**
107 * Magic number for hosted images created by VMware Workstation 4, VMware
108 * Workstation 5, VMware Server or VMware Player. Not necessarily sparse.
109 */
110#define VMDK_SPARSE_MAGICNUMBER 0x564d444b /* 'V' 'M' 'D' 'K' */
111
112/**
113 * VMDK hosted binary extent header. The "Sparse" is a total misnomer, as
114 * this header is also used for monolithic flat images.
115 */
116#pragma pack(1)
117typedef struct SparseExtentHeader
118{
119 uint32_t magicNumber;
120 uint32_t version;
121 uint32_t flags;
122 uint64_t capacity;
123 uint64_t grainSize;
124 uint64_t descriptorOffset;
125 uint64_t descriptorSize;
126 uint32_t numGTEsPerGT;
127 uint64_t rgdOffset;
128 uint64_t gdOffset;
129 uint64_t overHead;
130 bool uncleanShutdown;
131 char singleEndLineChar;
132 char nonEndLineChar;
133 char doubleEndLineChar1;
134 char doubleEndLineChar2;
135 uint16_t compressAlgorithm;
136 uint8_t pad[433];
137} SparseExtentHeader;
138#pragma pack()
139
140/** VMDK capacity for a single chunk when 2G splitting is turned on. Should be
141 * divisible by the default grain size (64K) */
142#define VMDK_2G_SPLIT_SIZE (2047 * 1024 * 1024)
143
144/** VMDK streamOptimized file format marker. The type field may or may not
145 * be actually valid, but there's always data to read there. */
146#pragma pack(1)
147typedef struct VMDKMARKER
148{
149 uint64_t uSector;
150 uint32_t cbSize;
151 uint32_t uType;
152} VMDKMARKER, *PVMDKMARKER;
153#pragma pack()
154
155
156#ifdef VBOX_WITH_VMDK_ESX
157
158/** @todo the ESX code is not tested, not used, and lacks error messages. */
159
160/**
161 * Magic number for images created by VMware GSX Server 3 or ESX Server 3.
162 */
163#define VMDK_ESX_SPARSE_MAGICNUMBER 0x44574f43 /* 'C' 'O' 'W' 'D' */
164
165#pragma pack(1)
166typedef struct COWDisk_Header
167{
168 uint32_t magicNumber;
169 uint32_t version;
170 uint32_t flags;
171 uint32_t numSectors;
172 uint32_t grainSize;
173 uint32_t gdOffset;
174 uint32_t numGDEntries;
175 uint32_t freeSector;
176 /* The spec incompletely documents quite a few further fields, but states
177 * that they are unused by the current format. Replace them by padding. */
178 char reserved1[1604];
179 uint32_t savedGeneration;
180 char reserved2[8];
181 uint32_t uncleanShutdown;
182 char padding[396];
183} COWDisk_Header;
184#pragma pack()
185#endif /* VBOX_WITH_VMDK_ESX */
186
187
188/** Convert sector number/size to byte offset/size. */
189#define VMDK_SECTOR2BYTE(u) ((uint64_t)(u) << 9)
190
191/** Convert byte offset/size to sector number/size. */
192#define VMDK_BYTE2SECTOR(u) ((u) >> 9)
193
194/**
195 * VMDK extent type.
196 */
197typedef enum VMDKETYPE
198{
199 /** Hosted sparse extent. */
200 VMDKETYPE_HOSTED_SPARSE = 1,
201 /** Flat extent. */
202 VMDKETYPE_FLAT,
203 /** Zero extent. */
204 VMDKETYPE_ZERO,
205 /** VMFS extent, used by ESX. */
206 VMDKETYPE_VMFS
207#ifdef VBOX_WITH_VMDK_ESX
208 ,
209 /** ESX sparse extent. */
210 VMDKETYPE_ESX_SPARSE
211#endif /* VBOX_WITH_VMDK_ESX */
212} VMDKETYPE, *PVMDKETYPE;
213
214/**
215 * VMDK access type for a extent.
216 */
217typedef enum VMDKACCESS
218{
219 /** No access allowed. */
220 VMDKACCESS_NOACCESS = 0,
221 /** Read-only access. */
222 VMDKACCESS_READONLY,
223 /** Read-write access. */
224 VMDKACCESS_READWRITE
225} VMDKACCESS, *PVMDKACCESS;
226
227/** Forward declaration for PVMDKIMAGE. */
228typedef struct VMDKIMAGE *PVMDKIMAGE;
229
230/**
231 * Extents files entry. Used for opening a particular file only once.
232 */
233typedef struct VMDKFILE
234{
235 /** Pointer to filename. Local copy. */
236 const char *pszFilename;
237 /** File open flags for consistency checking. */
238 unsigned fOpen;
239 /** Handle for sync/async file abstraction.*/
240 PVDIOSTORAGE pStorage;
241 /** Reference counter. */
242 unsigned uReferences;
243 /** Flag whether the file should be deleted on last close. */
244 bool fDelete;
245 /** Pointer to the image we belong to (for debugging purposes). */
246 PVMDKIMAGE pImage;
247 /** Pointer to next file descriptor. */
248 struct VMDKFILE *pNext;
249 /** Pointer to the previous file descriptor. */
250 struct VMDKFILE *pPrev;
251} VMDKFILE, *PVMDKFILE;
252
253/**
254 * VMDK extent data structure.
255 */
256typedef struct VMDKEXTENT
257{
258 /** File handle. */
259 PVMDKFILE pFile;
260 /** Base name of the image extent. */
261 const char *pszBasename;
262 /** Full name of the image extent. */
263 const char *pszFullname;
264 /** Number of sectors in this extent. */
265 uint64_t cSectors;
266 /** Number of sectors per block (grain in VMDK speak). */
267 uint64_t cSectorsPerGrain;
268 /** Starting sector number of descriptor. */
269 uint64_t uDescriptorSector;
270 /** Size of descriptor in sectors. */
271 uint64_t cDescriptorSectors;
272 /** Starting sector number of grain directory. */
273 uint64_t uSectorGD;
274 /** Starting sector number of redundant grain directory. */
275 uint64_t uSectorRGD;
276 /** Total number of metadata sectors. */
277 uint64_t cOverheadSectors;
278 /** Nominal size (i.e. as described by the descriptor) of this extent. */
279 uint64_t cNominalSectors;
280 /** Sector offset (i.e. as described by the descriptor) of this extent. */
281 uint64_t uSectorOffset;
282 /** Number of entries in a grain table. */
283 uint32_t cGTEntries;
284 /** Number of sectors reachable via a grain directory entry. */
285 uint32_t cSectorsPerGDE;
286 /** Number of entries in the grain directory. */
287 uint32_t cGDEntries;
288 /** Pointer to the next free sector. Legacy information. Do not use. */
289 uint32_t uFreeSector;
290 /** Number of this extent in the list of images. */
291 uint32_t uExtent;
292 /** Pointer to the descriptor (NULL if no descriptor in this extent). */
293 char *pDescData;
294 /** Pointer to the grain directory. */
295 uint32_t *pGD;
296 /** Pointer to the redundant grain directory. */
297 uint32_t *pRGD;
298 /** VMDK version of this extent. 1=1.0/1.1 */
299 uint32_t uVersion;
300 /** Type of this extent. */
301 VMDKETYPE enmType;
302 /** Access to this extent. */
303 VMDKACCESS enmAccess;
304 /** Flag whether this extent is marked as unclean. */
305 bool fUncleanShutdown;
306 /** Flag whether the metadata in the extent header needs to be updated. */
307 bool fMetaDirty;
308 /** Flag whether there is a footer in this extent. */
309 bool fFooter;
310 /** Compression type for this extent. */
311 uint16_t uCompression;
312 /** Append position for writing new grain. Only for sparse extents. */
313 uint64_t uAppendPosition;
314 /** Last grain which was accessed. Only for streamOptimized extents. */
315 uint32_t uLastGrainAccess;
316 /** Starting sector corresponding to the grain buffer. */
317 uint32_t uGrainSectorAbs;
318 /** Grain number corresponding to the grain buffer. */
319 uint32_t uGrain;
320 /** Actual size of the compressed data, only valid for reading. */
321 uint32_t cbGrainStreamRead;
322 /** Size of compressed grain buffer for streamOptimized extents. */
323 size_t cbCompGrain;
324 /** Compressed grain buffer for streamOptimized extents, with marker. */
325 void *pvCompGrain;
326 /** Decompressed grain buffer for streamOptimized extents. */
327 void *pvGrain;
328 /** Reference to the image in which this extent is used. Do not use this
329 * on a regular basis to avoid passing pImage references to functions
330 * explicitly. */
331 struct VMDKIMAGE *pImage;
332} VMDKEXTENT, *PVMDKEXTENT;
333
334/**
335 * Grain table cache size. Allocated per image.
336 */
337#define VMDK_GT_CACHE_SIZE 256
338
339/**
340 * Grain table block size. Smaller than an actual grain table block to allow
341 * more grain table blocks to be cached without having to allocate excessive
342 * amounts of memory for the cache.
343 */
344#define VMDK_GT_CACHELINE_SIZE 128
345
346
347/**
348 * Maximum number of lines in a descriptor file. Not worth the effort of
349 * making it variable. Descriptor files are generally very short (~20 lines),
350 * with the exception of sparse files split in 2G chunks, which need for the
351 * maximum size (almost 2T) exactly 1025 lines for the disk database.
352 */
353#define VMDK_DESCRIPTOR_LINES_MAX 1100U
354
355/**
356 * Parsed descriptor information. Allows easy access and update of the
357 * descriptor (whether separate file or not). Free form text files suck.
358 */
359typedef struct VMDKDESCRIPTOR
360{
361 /** Line number of first entry of the disk descriptor. */
362 unsigned uFirstDesc;
363 /** Line number of first entry in the extent description. */
364 unsigned uFirstExtent;
365 /** Line number of first disk database entry. */
366 unsigned uFirstDDB;
367 /** Total number of lines. */
368 unsigned cLines;
369 /** Total amount of memory available for the descriptor. */
370 size_t cbDescAlloc;
371 /** Set if descriptor has been changed and not yet written to disk. */
372 bool fDirty;
373 /** Array of pointers to the data in the descriptor. */
374 char *aLines[VMDK_DESCRIPTOR_LINES_MAX];
375 /** Array of line indices pointing to the next non-comment line. */
376 unsigned aNextLines[VMDK_DESCRIPTOR_LINES_MAX];
377} VMDKDESCRIPTOR, *PVMDKDESCRIPTOR;
378
379
380/**
381 * Cache entry for translating extent/sector to a sector number in that
382 * extent.
383 */
384typedef struct VMDKGTCACHEENTRY
385{
386 /** Extent number for which this entry is valid. */
387 uint32_t uExtent;
388 /** GT data block number. */
389 uint64_t uGTBlock;
390 /** Data part of the cache entry. */
391 uint32_t aGTData[VMDK_GT_CACHELINE_SIZE];
392} VMDKGTCACHEENTRY, *PVMDKGTCACHEENTRY;
393
394/**
395 * Cache data structure for blocks of grain table entries. For now this is a
396 * fixed size direct mapping cache, but this should be adapted to the size of
397 * the sparse image and maybe converted to a set-associative cache. The
398 * implementation below implements a write-through cache with write allocate.
399 */
400typedef struct VMDKGTCACHE
401{
402 /** Cache entries. */
403 VMDKGTCACHEENTRY aGTCache[VMDK_GT_CACHE_SIZE];
404 /** Number of cache entries (currently unused). */
405 unsigned cEntries;
406} VMDKGTCACHE, *PVMDKGTCACHE;
407
408/**
409 * Complete VMDK image data structure. Mainly a collection of extents and a few
410 * extra global data fields.
411 */
412typedef struct VMDKIMAGE
413{
414 /** Image name. */
415 const char *pszFilename;
416 /** Descriptor file if applicable. */
417 PVMDKFILE pFile;
418
419 /** Pointer to the per-disk VD interface list. */
420 PVDINTERFACE pVDIfsDisk;
421 /** Pointer to the per-image VD interface list. */
422 PVDINTERFACE pVDIfsImage;
423
424 /** Error interface. */
425 PVDINTERFACEERROR pIfError;
426 /** I/O interface. */
427 PVDINTERFACEIOINT pIfIo;
428
429
430 /** Pointer to the image extents. */
431 PVMDKEXTENT pExtents;
432 /** Number of image extents. */
433 unsigned cExtents;
434 /** Pointer to the files list, for opening a file referenced multiple
435 * times only once (happens mainly with raw partition access). */
436 PVMDKFILE pFiles;
437
438 /**
439 * Pointer to an array of segment entries for async I/O.
440 * This is an optimization because the task number to submit is not known
441 * and allocating/freeing an array in the read/write functions every time
442 * is too expensive.
443 */
444 PPDMDATASEG paSegments;
445 /** Entries available in the segments array. */
446 unsigned cSegments;
447
448 /** Open flags passed by VBoxHD layer. */
449 unsigned uOpenFlags;
450 /** Image flags defined during creation or determined during open. */
451 unsigned uImageFlags;
452 /** Total size of the image. */
453 uint64_t cbSize;
454 /** Physical geometry of this image. */
455 VDGEOMETRY PCHSGeometry;
456 /** Logical geometry of this image. */
457 VDGEOMETRY LCHSGeometry;
458 /** Image UUID. */
459 RTUUID ImageUuid;
460 /** Image modification UUID. */
461 RTUUID ModificationUuid;
462 /** Parent image UUID. */
463 RTUUID ParentUuid;
464 /** Parent image modification UUID. */
465 RTUUID ParentModificationUuid;
466
467 /** Pointer to grain table cache, if this image contains sparse extents. */
468 PVMDKGTCACHE pGTCache;
469 /** Pointer to the descriptor (NULL if no separate descriptor file). */
470 char *pDescData;
471 /** Allocation size of the descriptor file. */
472 size_t cbDescAlloc;
473 /** Parsed descriptor file content. */
474 VMDKDESCRIPTOR Descriptor;
475} VMDKIMAGE;
476
477
478/** State for the input/output callout of the inflate reader/deflate writer. */
479typedef struct VMDKCOMPRESSIO
480{
481 /* Image this operation relates to. */
482 PVMDKIMAGE pImage;
483 /* Current read position. */
484 ssize_t iOffset;
485 /* Size of the compressed grain buffer (available data). */
486 size_t cbCompGrain;
487 /* Pointer to the compressed grain buffer. */
488 void *pvCompGrain;
489} VMDKCOMPRESSIO;
490
491
492/** Tracks async grain allocation. */
493typedef struct VMDKGRAINALLOCASYNC
494{
495 /** Flag whether the allocation failed. */
496 bool fIoErr;
497 /** Current number of transfers pending.
498 * If reached 0 and there is an error the old state is restored. */
499 unsigned cIoXfersPending;
500 /** Sector number */
501 uint64_t uSector;
502 /** Flag whether the grain table needs to be updated. */
503 bool fGTUpdateNeeded;
504 /** Extent the allocation happens. */
505 PVMDKEXTENT pExtent;
506 /** Position of the new grain, required for the grain table update. */
507 uint64_t uGrainOffset;
508 /** Grain table sector. */
509 uint64_t uGTSector;
510 /** Backup grain table sector. */
511 uint64_t uRGTSector;
512} VMDKGRAINALLOCASYNC, *PVMDKGRAINALLOCASYNC;
513
514
515/*********************************************************************************************************************************
516* Static Variables *
517*********************************************************************************************************************************/
518
519/** NULL-terminated array of supported file extensions. */
520static const VDFILEEXTENSION s_aVmdkFileExtensions[] =
521{
522 {"vmdk", VDTYPE_HDD},
523 {NULL, VDTYPE_INVALID}
524};
525
526
527/*********************************************************************************************************************************
528* Internal Functions *
529*********************************************************************************************************************************/
530
531static void vmdkFreeStreamBuffers(PVMDKEXTENT pExtent);
532static int vmdkFreeExtentData(PVMDKIMAGE pImage, PVMDKEXTENT pExtent,
533 bool fDelete);
534
535static int vmdkCreateExtents(PVMDKIMAGE pImage, unsigned cExtents);
536static int vmdkFlushImage(PVMDKIMAGE pImage, PVDIOCTX pIoCtx);
537static int vmdkSetImageComment(PVMDKIMAGE pImage, const char *pszComment);
538static int vmdkFreeImage(PVMDKIMAGE pImage, bool fDelete);
539
540static DECLCALLBACK(int) vmdkAllocGrainComplete(void *pBackendData, PVDIOCTX pIoCtx,
541 void *pvUser, int rcReq);
542
543/**
544 * Internal: open a file (using a file descriptor cache to ensure each file
545 * is only opened once - anything else can cause locking problems).
546 */
547static int vmdkFileOpen(PVMDKIMAGE pImage, PVMDKFILE *ppVmdkFile,
548 const char *pszFilename, uint32_t fOpen)
549{
550 int rc = VINF_SUCCESS;
551 PVMDKFILE pVmdkFile;
552
553 for (pVmdkFile = pImage->pFiles;
554 pVmdkFile != NULL;
555 pVmdkFile = pVmdkFile->pNext)
556 {
557 if (!strcmp(pszFilename, pVmdkFile->pszFilename))
558 {
559 Assert(fOpen == pVmdkFile->fOpen);
560 pVmdkFile->uReferences++;
561
562 *ppVmdkFile = pVmdkFile;
563
564 return rc;
565 }
566 }
567
568 /* If we get here, there's no matching entry in the cache. */
569 pVmdkFile = (PVMDKFILE)RTMemAllocZ(sizeof(VMDKFILE));
570 if (!pVmdkFile)
571 {
572 *ppVmdkFile = NULL;
573 return VERR_NO_MEMORY;
574 }
575
576 pVmdkFile->pszFilename = RTStrDup(pszFilename);
577 if (!pVmdkFile->pszFilename)
578 {
579 RTMemFree(pVmdkFile);
580 *ppVmdkFile = NULL;
581 return VERR_NO_MEMORY;
582 }
583 pVmdkFile->fOpen = fOpen;
584
585 rc = vdIfIoIntFileOpen(pImage->pIfIo, pszFilename, fOpen,
586 &pVmdkFile->pStorage);
587 if (RT_SUCCESS(rc))
588 {
589 pVmdkFile->uReferences = 1;
590 pVmdkFile->pImage = pImage;
591 pVmdkFile->pNext = pImage->pFiles;
592 if (pImage->pFiles)
593 pImage->pFiles->pPrev = pVmdkFile;
594 pImage->pFiles = pVmdkFile;
595 *ppVmdkFile = pVmdkFile;
596 }
597 else
598 {
599 RTStrFree((char *)(void *)pVmdkFile->pszFilename);
600 RTMemFree(pVmdkFile);
601 *ppVmdkFile = NULL;
602 }
603
604 return rc;
605}
606
607/**
608 * Internal: close a file, updating the file descriptor cache.
609 */
610static int vmdkFileClose(PVMDKIMAGE pImage, PVMDKFILE *ppVmdkFile, bool fDelete)
611{
612 int rc = VINF_SUCCESS;
613 PVMDKFILE pVmdkFile = *ppVmdkFile;
614
615 AssertPtr(pVmdkFile);
616
617 pVmdkFile->fDelete |= fDelete;
618 Assert(pVmdkFile->uReferences);
619 pVmdkFile->uReferences--;
620 if (pVmdkFile->uReferences == 0)
621 {
622 PVMDKFILE pPrev;
623 PVMDKFILE pNext;
624
625 /* Unchain the element from the list. */
626 pPrev = pVmdkFile->pPrev;
627 pNext = pVmdkFile->pNext;
628
629 if (pNext)
630 pNext->pPrev = pPrev;
631 if (pPrev)
632 pPrev->pNext = pNext;
633 else
634 pImage->pFiles = pNext;
635
636 rc = vdIfIoIntFileClose(pImage->pIfIo, pVmdkFile->pStorage);
637 if (RT_SUCCESS(rc) && pVmdkFile->fDelete)
638 rc = vdIfIoIntFileDelete(pImage->pIfIo, pVmdkFile->pszFilename);
639 RTStrFree((char *)(void *)pVmdkFile->pszFilename);
640 RTMemFree(pVmdkFile);
641 }
642
643 *ppVmdkFile = NULL;
644 return rc;
645}
646
647/*#define VMDK_USE_BLOCK_DECOMP_API - test and enable */
648#ifndef VMDK_USE_BLOCK_DECOMP_API
649static DECLCALLBACK(int) vmdkFileInflateHelper(void *pvUser, void *pvBuf, size_t cbBuf, size_t *pcbBuf)
650{
651 VMDKCOMPRESSIO *pInflateState = (VMDKCOMPRESSIO *)pvUser;
652 size_t cbInjected = 0;
653
654 Assert(cbBuf);
655 if (pInflateState->iOffset < 0)
656 {
657 *(uint8_t *)pvBuf = RTZIPTYPE_ZLIB;
658 pvBuf = (uint8_t *)pvBuf + 1;
659 cbBuf--;
660 cbInjected = 1;
661 pInflateState->iOffset = RT_OFFSETOF(VMDKMARKER, uType);
662 }
663 if (!cbBuf)
664 {
665 if (pcbBuf)
666 *pcbBuf = cbInjected;
667 return VINF_SUCCESS;
668 }
669 cbBuf = RT_MIN(cbBuf, pInflateState->cbCompGrain - pInflateState->iOffset);
670 memcpy(pvBuf,
671 (uint8_t *)pInflateState->pvCompGrain + pInflateState->iOffset,
672 cbBuf);
673 pInflateState->iOffset += cbBuf;
674 Assert(pcbBuf);
675 *pcbBuf = cbBuf + cbInjected;
676 return VINF_SUCCESS;
677}
678#endif
679
680/**
681 * Internal: read from a file and inflate the compressed data,
682 * distinguishing between async and normal operation
683 */
684DECLINLINE(int) vmdkFileInflateSync(PVMDKIMAGE pImage, PVMDKEXTENT pExtent,
685 uint64_t uOffset, void *pvBuf,
686 size_t cbToRead, const void *pcvMarker,
687 uint64_t *puLBA, uint32_t *pcbMarkerData)
688{
689 int rc;
690#ifndef VMDK_USE_BLOCK_DECOMP_API
691 PRTZIPDECOMP pZip = NULL;
692#endif
693 VMDKMARKER *pMarker = (VMDKMARKER *)pExtent->pvCompGrain;
694 size_t cbCompSize, cbActuallyRead;
695
696 if (!pcvMarker)
697 {
698 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pExtent->pFile->pStorage,
699 uOffset, pMarker, RT_OFFSETOF(VMDKMARKER, uType));
700 if (RT_FAILURE(rc))
701 return rc;
702 }
703 else
704 {
705 memcpy(pMarker, pcvMarker, RT_OFFSETOF(VMDKMARKER, uType));
706 /* pcvMarker endianness has already been partially transformed, fix it */
707 pMarker->uSector = RT_H2LE_U64(pMarker->uSector);
708 pMarker->cbSize = RT_H2LE_U32(pMarker->cbSize);
709 }
710
711 cbCompSize = RT_LE2H_U32(pMarker->cbSize);
712 if (cbCompSize == 0)
713 {
714 AssertMsgFailed(("VMDK: corrupted marker\n"));
715 return VERR_VD_VMDK_INVALID_FORMAT;
716 }
717
718 /* Sanity check - the expansion ratio should be much less than 2. */
719 Assert(cbCompSize < 2 * cbToRead);
720 if (cbCompSize >= 2 * cbToRead)
721 return VERR_VD_VMDK_INVALID_FORMAT;
722
723 /* Compressed grain marker. Data follows immediately. */
724 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pExtent->pFile->pStorage,
725 uOffset + RT_OFFSETOF(VMDKMARKER, uType),
726 (uint8_t *)pExtent->pvCompGrain
727 + RT_OFFSETOF(VMDKMARKER, uType),
728 RT_ALIGN_Z( cbCompSize
729 + RT_OFFSETOF(VMDKMARKER, uType),
730 512)
731 - RT_OFFSETOF(VMDKMARKER, uType));
732
733 if (puLBA)
734 *puLBA = RT_LE2H_U64(pMarker->uSector);
735 if (pcbMarkerData)
736 *pcbMarkerData = RT_ALIGN( cbCompSize
737 + RT_OFFSETOF(VMDKMARKER, uType),
738 512);
739
740#ifdef VMDK_USE_BLOCK_DECOMP_API
741 rc = RTZipBlockDecompress(RTZIPTYPE_ZLIB, 0 /*fFlags*/,
742 pExtent->pvCompGrain, cbCompSize + RT_OFFSETOF(VMDKMARKER, uType), NULL,
743 pvBuf, cbToRead, &cbActuallyRead);
744#else
745 VMDKCOMPRESSIO InflateState;
746 InflateState.pImage = pImage;
747 InflateState.iOffset = -1;
748 InflateState.cbCompGrain = cbCompSize + RT_OFFSETOF(VMDKMARKER, uType);
749 InflateState.pvCompGrain = pExtent->pvCompGrain;
750
751 rc = RTZipDecompCreate(&pZip, &InflateState, vmdkFileInflateHelper);
752 if (RT_FAILURE(rc))
753 return rc;
754 rc = RTZipDecompress(pZip, pvBuf, cbToRead, &cbActuallyRead);
755 RTZipDecompDestroy(pZip);
756#endif /* !VMDK_USE_BLOCK_DECOMP_API */
757 if (RT_FAILURE(rc))
758 {
759 if (rc == VERR_ZIP_CORRUPTED)
760 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: Compressed image is corrupted '%s'"), pExtent->pszFullname);
761 return rc;
762 }
763 if (cbActuallyRead != cbToRead)
764 rc = VERR_VD_VMDK_INVALID_FORMAT;
765 return rc;
766}
767
768static DECLCALLBACK(int) vmdkFileDeflateHelper(void *pvUser, const void *pvBuf, size_t cbBuf)
769{
770 VMDKCOMPRESSIO *pDeflateState = (VMDKCOMPRESSIO *)pvUser;
771
772 Assert(cbBuf);
773 if (pDeflateState->iOffset < 0)
774 {
775 pvBuf = (const uint8_t *)pvBuf + 1;
776 cbBuf--;
777 pDeflateState->iOffset = RT_OFFSETOF(VMDKMARKER, uType);
778 }
779 if (!cbBuf)
780 return VINF_SUCCESS;
781 if (pDeflateState->iOffset + cbBuf > pDeflateState->cbCompGrain)
782 return VERR_BUFFER_OVERFLOW;
783 memcpy((uint8_t *)pDeflateState->pvCompGrain + pDeflateState->iOffset,
784 pvBuf, cbBuf);
785 pDeflateState->iOffset += cbBuf;
786 return VINF_SUCCESS;
787}
788
789/**
790 * Internal: deflate the uncompressed data and write to a file,
791 * distinguishing between async and normal operation
792 */
793DECLINLINE(int) vmdkFileDeflateSync(PVMDKIMAGE pImage, PVMDKEXTENT pExtent,
794 uint64_t uOffset, const void *pvBuf,
795 size_t cbToWrite, uint64_t uLBA,
796 uint32_t *pcbMarkerData)
797{
798 int rc;
799 PRTZIPCOMP pZip = NULL;
800 VMDKCOMPRESSIO DeflateState;
801
802 DeflateState.pImage = pImage;
803 DeflateState.iOffset = -1;
804 DeflateState.cbCompGrain = pExtent->cbCompGrain;
805 DeflateState.pvCompGrain = pExtent->pvCompGrain;
806
807 rc = RTZipCompCreate(&pZip, &DeflateState, vmdkFileDeflateHelper,
808 RTZIPTYPE_ZLIB, RTZIPLEVEL_DEFAULT);
809 if (RT_FAILURE(rc))
810 return rc;
811 rc = RTZipCompress(pZip, pvBuf, cbToWrite);
812 if (RT_SUCCESS(rc))
813 rc = RTZipCompFinish(pZip);
814 RTZipCompDestroy(pZip);
815 if (RT_SUCCESS(rc))
816 {
817 Assert( DeflateState.iOffset > 0
818 && (size_t)DeflateState.iOffset <= DeflateState.cbCompGrain);
819
820 /* pad with zeroes to get to a full sector size */
821 uint32_t uSize = DeflateState.iOffset;
822 if (uSize % 512)
823 {
824 uint32_t uSizeAlign = RT_ALIGN(uSize, 512);
825 memset((uint8_t *)pExtent->pvCompGrain + uSize, '\0',
826 uSizeAlign - uSize);
827 uSize = uSizeAlign;
828 }
829
830 if (pcbMarkerData)
831 *pcbMarkerData = uSize;
832
833 /* Compressed grain marker. Data follows immediately. */
834 VMDKMARKER *pMarker = (VMDKMARKER *)pExtent->pvCompGrain;
835 pMarker->uSector = RT_H2LE_U64(uLBA);
836 pMarker->cbSize = RT_H2LE_U32( DeflateState.iOffset
837 - RT_OFFSETOF(VMDKMARKER, uType));
838 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pExtent->pFile->pStorage,
839 uOffset, pMarker, uSize);
840 if (RT_FAILURE(rc))
841 return rc;
842 }
843 return rc;
844}
845
846
847/**
848 * Internal: check if all files are closed, prevent leaking resources.
849 */
850static int vmdkFileCheckAllClose(PVMDKIMAGE pImage)
851{
852 int rc = VINF_SUCCESS, rc2;
853 PVMDKFILE pVmdkFile;
854
855 Assert(pImage->pFiles == NULL);
856 for (pVmdkFile = pImage->pFiles;
857 pVmdkFile != NULL;
858 pVmdkFile = pVmdkFile->pNext)
859 {
860 LogRel(("VMDK: leaking reference to file \"%s\"\n",
861 pVmdkFile->pszFilename));
862 pImage->pFiles = pVmdkFile->pNext;
863
864 rc2 = vmdkFileClose(pImage, &pVmdkFile, pVmdkFile->fDelete);
865
866 if (RT_SUCCESS(rc))
867 rc = rc2;
868 }
869 return rc;
870}
871
872/**
873 * Internal: truncate a string (at a UTF8 code point boundary) and encode the
874 * critical non-ASCII characters.
875 */
876static char *vmdkEncodeString(const char *psz)
877{
878 char szEnc[VMDK_ENCODED_COMMENT_MAX + 3];
879 char *pszDst = szEnc;
880
881 AssertPtr(psz);
882
883 for (; *psz; psz = RTStrNextCp(psz))
884 {
885 char *pszDstPrev = pszDst;
886 RTUNICP Cp = RTStrGetCp(psz);
887 if (Cp == '\\')
888 {
889 pszDst = RTStrPutCp(pszDst, Cp);
890 pszDst = RTStrPutCp(pszDst, Cp);
891 }
892 else if (Cp == '\n')
893 {
894 pszDst = RTStrPutCp(pszDst, '\\');
895 pszDst = RTStrPutCp(pszDst, 'n');
896 }
897 else if (Cp == '\r')
898 {
899 pszDst = RTStrPutCp(pszDst, '\\');
900 pszDst = RTStrPutCp(pszDst, 'r');
901 }
902 else
903 pszDst = RTStrPutCp(pszDst, Cp);
904 if (pszDst - szEnc >= VMDK_ENCODED_COMMENT_MAX - 1)
905 {
906 pszDst = pszDstPrev;
907 break;
908 }
909 }
910 *pszDst = '\0';
911 return RTStrDup(szEnc);
912}
913
914/**
915 * Internal: decode a string and store it into the specified string.
916 */
917static int vmdkDecodeString(const char *pszEncoded, char *psz, size_t cb)
918{
919 int rc = VINF_SUCCESS;
920 char szBuf[4];
921
922 if (!cb)
923 return VERR_BUFFER_OVERFLOW;
924
925 AssertPtr(psz);
926
927 for (; *pszEncoded; pszEncoded = RTStrNextCp(pszEncoded))
928 {
929 char *pszDst = szBuf;
930 RTUNICP Cp = RTStrGetCp(pszEncoded);
931 if (Cp == '\\')
932 {
933 pszEncoded = RTStrNextCp(pszEncoded);
934 RTUNICP CpQ = RTStrGetCp(pszEncoded);
935 if (CpQ == 'n')
936 RTStrPutCp(pszDst, '\n');
937 else if (CpQ == 'r')
938 RTStrPutCp(pszDst, '\r');
939 else if (CpQ == '\0')
940 {
941 rc = VERR_VD_VMDK_INVALID_HEADER;
942 break;
943 }
944 else
945 RTStrPutCp(pszDst, CpQ);
946 }
947 else
948 pszDst = RTStrPutCp(pszDst, Cp);
949
950 /* Need to leave space for terminating NUL. */
951 if ((size_t)(pszDst - szBuf) + 1 >= cb)
952 {
953 rc = VERR_BUFFER_OVERFLOW;
954 break;
955 }
956 memcpy(psz, szBuf, pszDst - szBuf);
957 psz += pszDst - szBuf;
958 }
959 *psz = '\0';
960 return rc;
961}
962
963/**
964 * Internal: free all buffers associated with grain directories.
965 */
966static void vmdkFreeGrainDirectory(PVMDKEXTENT pExtent)
967{
968 if (pExtent->pGD)
969 {
970 RTMemFree(pExtent->pGD);
971 pExtent->pGD = NULL;
972 }
973 if (pExtent->pRGD)
974 {
975 RTMemFree(pExtent->pRGD);
976 pExtent->pRGD = NULL;
977 }
978}
979
980/**
981 * Internal: allocate the compressed/uncompressed buffers for streamOptimized
982 * images.
983 */
984static int vmdkAllocStreamBuffers(PVMDKIMAGE pImage, PVMDKEXTENT pExtent)
985{
986 int rc = VINF_SUCCESS;
987
988 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
989 {
990 /* streamOptimized extents need a compressed grain buffer, which must
991 * be big enough to hold uncompressible data (which needs ~8 bytes
992 * more than the uncompressed data), the marker and padding. */
993 pExtent->cbCompGrain = RT_ALIGN_Z( VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain)
994 + 8 + sizeof(VMDKMARKER), 512);
995 pExtent->pvCompGrain = RTMemAlloc(pExtent->cbCompGrain);
996 if (!pExtent->pvCompGrain)
997 {
998 rc = VERR_NO_MEMORY;
999 goto out;
1000 }
1001
1002 /* streamOptimized extents need a decompressed grain buffer. */
1003 pExtent->pvGrain = RTMemAlloc(VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain));
1004 if (!pExtent->pvGrain)
1005 {
1006 rc = VERR_NO_MEMORY;
1007 goto out;
1008 }
1009 }
1010
1011out:
1012 if (RT_FAILURE(rc))
1013 vmdkFreeStreamBuffers(pExtent);
1014 return rc;
1015}
1016
1017/**
1018 * Internal: allocate all buffers associated with grain directories.
1019 */
1020static int vmdkAllocGrainDirectory(PVMDKIMAGE pImage, PVMDKEXTENT pExtent)
1021{
1022 RT_NOREF1(pImage);
1023 int rc = VINF_SUCCESS;
1024 size_t cbGD = pExtent->cGDEntries * sizeof(uint32_t);
1025 /** @todo r=bird: This code is unnecessarily confusing pointer states with
1026 * (1) unnecessary initialization of locals, (2) unnecesarily wide
1027 * scoping of variables, (3) instance on goto code structure. Also,
1028 * having two initialized variables on one line decreases readability. */
1029 uint32_t *pGD = NULL, *pRGD = NULL;
1030
1031 pGD = (uint32_t *)RTMemAllocZ(cbGD);
1032 if (!pGD)
1033 {
1034 rc = VERR_NO_MEMORY;
1035 goto out;
1036 }
1037 pExtent->pGD = pGD;
1038
1039 if (pExtent->uSectorRGD)
1040 {
1041 pRGD = (uint32_t *)RTMemAllocZ(cbGD);
1042 if (!pRGD)
1043 {
1044 rc = VERR_NO_MEMORY;
1045 goto out;
1046 }
1047 pExtent->pRGD = pRGD;
1048 }
1049
1050out:
1051 if (RT_FAILURE(rc))
1052 vmdkFreeGrainDirectory(pExtent);
1053 return rc;
1054}
1055
1056static int vmdkReadGrainDirectory(PVMDKIMAGE pImage, PVMDKEXTENT pExtent)
1057{
1058 int rc = VINF_SUCCESS;
1059 size_t i;
1060 uint32_t *pGDTmp, *pRGDTmp;
1061 size_t cbGD = pExtent->cGDEntries * sizeof(uint32_t);
1062
1063 if (pExtent->enmType != VMDKETYPE_HOSTED_SPARSE)
1064 goto out;
1065
1066 if ( pExtent->uSectorGD == VMDK_GD_AT_END
1067 || pExtent->uSectorRGD == VMDK_GD_AT_END)
1068 {
1069 rc = VERR_INTERNAL_ERROR;
1070 goto out;
1071 }
1072
1073 rc = vmdkAllocGrainDirectory(pImage, pExtent);
1074 if (RT_FAILURE(rc))
1075 goto out;
1076
1077 /* The VMDK 1.1 spec seems to talk about compressed grain directories,
1078 * but in reality they are not compressed. */
1079 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pExtent->pFile->pStorage,
1080 VMDK_SECTOR2BYTE(pExtent->uSectorGD),
1081 pExtent->pGD, cbGD);
1082 AssertRC(rc);
1083 if (RT_FAILURE(rc))
1084 {
1085 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS,
1086 N_("VMDK: could not read grain directory in '%s': %Rrc"), pExtent->pszFullname, rc);
1087 goto out;
1088 }
1089 for (i = 0, pGDTmp = pExtent->pGD; i < pExtent->cGDEntries; i++, pGDTmp++)
1090 *pGDTmp = RT_LE2H_U32(*pGDTmp);
1091
1092 if ( pExtent->uSectorRGD
1093 && !(pImage->uOpenFlags & VD_OPEN_FLAGS_SKIP_CONSISTENCY_CHECKS))
1094 {
1095 /* The VMDK 1.1 spec seems to talk about compressed grain directories,
1096 * but in reality they are not compressed. */
1097 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pExtent->pFile->pStorage,
1098 VMDK_SECTOR2BYTE(pExtent->uSectorRGD),
1099 pExtent->pRGD, cbGD);
1100 AssertRC(rc);
1101 if (RT_FAILURE(rc))
1102 {
1103 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS,
1104 N_("VMDK: could not read redundant grain directory in '%s'"), pExtent->pszFullname);
1105 goto out;
1106 }
1107 for (i = 0, pRGDTmp = pExtent->pRGD; i < pExtent->cGDEntries; i++, pRGDTmp++)
1108 *pRGDTmp = RT_LE2H_U32(*pRGDTmp);
1109
1110 /* Check grain table and redundant grain table for consistency. */
1111 size_t cbGT = pExtent->cGTEntries * sizeof(uint32_t);
1112 size_t cbGTBuffers = cbGT; /* Start with space for one GT. */
1113 size_t cbGTBuffersMax = _1M;
1114
1115 uint32_t *pTmpGT1 = (uint32_t *)RTMemAlloc(cbGTBuffers);
1116 uint32_t *pTmpGT2 = (uint32_t *)RTMemAlloc(cbGTBuffers);
1117
1118 if ( !pTmpGT1
1119 || !pTmpGT2)
1120 rc = VERR_NO_MEMORY;
1121
1122 i = 0;
1123 pGDTmp = pExtent->pGD;
1124 pRGDTmp = pExtent->pRGD;
1125
1126 /* Loop through all entries. */
1127 while (i < pExtent->cGDEntries)
1128 {
1129 uint32_t uGTStart = *pGDTmp;
1130 uint32_t uRGTStart = *pRGDTmp;
1131 size_t cbGTRead = cbGT;
1132
1133 /* If no grain table is allocated skip the entry. */
1134 if (*pGDTmp == 0 && *pRGDTmp == 0)
1135 {
1136 i++;
1137 continue;
1138 }
1139
1140 if (*pGDTmp == 0 || *pRGDTmp == 0 || *pGDTmp == *pRGDTmp)
1141 {
1142 /* Just one grain directory entry refers to a not yet allocated
1143 * grain table or both grain directory copies refer to the same
1144 * grain table. Not allowed. */
1145 rc = vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: inconsistent references to grain directory in '%s'"), pExtent->pszFullname);
1146 break;
1147 }
1148
1149 i++;
1150 pGDTmp++;
1151 pRGDTmp++;
1152
1153 /*
1154 * Read a few tables at once if adjacent to decrease the number
1155 * of I/O requests. Read at maximum 1MB at once.
1156 */
1157 while ( i < pExtent->cGDEntries
1158 && cbGTRead < cbGTBuffersMax)
1159 {
1160 /* If no grain table is allocated skip the entry. */
1161 if (*pGDTmp == 0 && *pRGDTmp == 0)
1162 {
1163 i++;
1164 continue;
1165 }
1166
1167 if (*pGDTmp == 0 || *pRGDTmp == 0 || *pGDTmp == *pRGDTmp)
1168 {
1169 /* Just one grain directory entry refers to a not yet allocated
1170 * grain table or both grain directory copies refer to the same
1171 * grain table. Not allowed. */
1172 rc = vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: inconsistent references to grain directory in '%s'"), pExtent->pszFullname);
1173 break;
1174 }
1175
1176 /* Check that the start offsets are adjacent.*/
1177 if ( VMDK_SECTOR2BYTE(uGTStart) + cbGTRead != VMDK_SECTOR2BYTE(*pGDTmp)
1178 || VMDK_SECTOR2BYTE(uRGTStart) + cbGTRead != VMDK_SECTOR2BYTE(*pRGDTmp))
1179 break;
1180
1181 i++;
1182 pGDTmp++;
1183 pRGDTmp++;
1184 cbGTRead += cbGT;
1185 }
1186
1187 /* Increase buffers if required. */
1188 if ( RT_SUCCESS(rc)
1189 && cbGTBuffers < cbGTRead)
1190 {
1191 uint32_t *pTmp;
1192 pTmp = (uint32_t *)RTMemRealloc(pTmpGT1, cbGTRead);
1193 if (pTmp)
1194 {
1195 pTmpGT1 = pTmp;
1196 pTmp = (uint32_t *)RTMemRealloc(pTmpGT2, cbGTRead);
1197 if (pTmp)
1198 pTmpGT2 = pTmp;
1199 else
1200 rc = VERR_NO_MEMORY;
1201 }
1202 else
1203 rc = VERR_NO_MEMORY;
1204
1205 if (rc == VERR_NO_MEMORY)
1206 {
1207 /* Reset to the old values. */
1208 rc = VINF_SUCCESS;
1209 i -= cbGTRead / cbGT;
1210 cbGTRead = cbGT;
1211
1212 /* Don't try to increase the buffer again in the next run. */
1213 cbGTBuffersMax = cbGTBuffers;
1214 }
1215 }
1216
1217 if (RT_SUCCESS(rc))
1218 {
1219 /* The VMDK 1.1 spec seems to talk about compressed grain tables,
1220 * but in reality they are not compressed. */
1221 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pExtent->pFile->pStorage,
1222 VMDK_SECTOR2BYTE(uGTStart),
1223 pTmpGT1, cbGTRead);
1224 if (RT_FAILURE(rc))
1225 {
1226 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS,
1227 N_("VMDK: error reading grain table in '%s'"), pExtent->pszFullname);
1228 break;
1229 }
1230 /* The VMDK 1.1 spec seems to talk about compressed grain tables,
1231 * but in reality they are not compressed. */
1232 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pExtent->pFile->pStorage,
1233 VMDK_SECTOR2BYTE(uRGTStart),
1234 pTmpGT2, cbGTRead);
1235 if (RT_FAILURE(rc))
1236 {
1237 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS,
1238 N_("VMDK: error reading backup grain table in '%s'"), pExtent->pszFullname);
1239 break;
1240 }
1241 if (memcmp(pTmpGT1, pTmpGT2, cbGTRead))
1242 {
1243 rc = vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS,
1244 N_("VMDK: inconsistency between grain table and backup grain table in '%s'"), pExtent->pszFullname);
1245 break;
1246 }
1247 }
1248 } /* while (i < pExtent->cGDEntries) */
1249
1250 /** @todo figure out what to do for unclean VMDKs. */
1251 if (pTmpGT1)
1252 RTMemFree(pTmpGT1);
1253 if (pTmpGT2)
1254 RTMemFree(pTmpGT2);
1255 }
1256
1257out:
1258 if (RT_FAILURE(rc))
1259 vmdkFreeGrainDirectory(pExtent);
1260 return rc;
1261}
1262
1263static int vmdkCreateGrainDirectory(PVMDKIMAGE pImage, PVMDKEXTENT pExtent,
1264 uint64_t uStartSector, bool fPreAlloc)
1265{
1266 int rc = VINF_SUCCESS;
1267 unsigned i;
1268 size_t cbGD = pExtent->cGDEntries * sizeof(uint32_t);
1269 size_t cbGDRounded = RT_ALIGN_64(cbGD, 512);
1270 size_t cbGTRounded;
1271 uint64_t cbOverhead;
1272
1273 if (fPreAlloc)
1274 {
1275 cbGTRounded = RT_ALIGN_64(pExtent->cGDEntries * pExtent->cGTEntries * sizeof(uint32_t), 512);
1276 cbOverhead = VMDK_SECTOR2BYTE(uStartSector) + cbGDRounded
1277 + cbGTRounded;
1278 }
1279 else
1280 {
1281 /* Use a dummy start sector for layout computation. */
1282 if (uStartSector == VMDK_GD_AT_END)
1283 uStartSector = 1;
1284 cbGTRounded = 0;
1285 cbOverhead = VMDK_SECTOR2BYTE(uStartSector) + cbGDRounded;
1286 }
1287
1288 /* For streamOptimized extents there is only one grain directory,
1289 * and for all others take redundant grain directory into account. */
1290 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
1291 {
1292 cbOverhead = RT_ALIGN_64(cbOverhead,
1293 VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain));
1294 }
1295 else
1296 {
1297 cbOverhead += cbGDRounded + cbGTRounded;
1298 cbOverhead = RT_ALIGN_64(cbOverhead,
1299 VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain));
1300 rc = vdIfIoIntFileSetSize(pImage->pIfIo, pExtent->pFile->pStorage, cbOverhead);
1301 }
1302 if (RT_FAILURE(rc))
1303 goto out;
1304 pExtent->uAppendPosition = cbOverhead;
1305 pExtent->cOverheadSectors = VMDK_BYTE2SECTOR(cbOverhead);
1306
1307 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
1308 {
1309 pExtent->uSectorRGD = 0;
1310 pExtent->uSectorGD = uStartSector;
1311 }
1312 else
1313 {
1314 pExtent->uSectorRGD = uStartSector;
1315 pExtent->uSectorGD = uStartSector + VMDK_BYTE2SECTOR(cbGDRounded + cbGTRounded);
1316 }
1317
1318 rc = vmdkAllocStreamBuffers(pImage, pExtent);
1319 if (RT_FAILURE(rc))
1320 goto out;
1321
1322 rc = vmdkAllocGrainDirectory(pImage, pExtent);
1323 if (RT_FAILURE(rc))
1324 goto out;
1325
1326 if (fPreAlloc)
1327 {
1328 uint32_t uGTSectorLE;
1329 uint64_t uOffsetSectors;
1330
1331 if (pExtent->pRGD)
1332 {
1333 uOffsetSectors = pExtent->uSectorRGD + VMDK_BYTE2SECTOR(cbGDRounded);
1334 for (i = 0; i < pExtent->cGDEntries; i++)
1335 {
1336 pExtent->pRGD[i] = uOffsetSectors;
1337 uGTSectorLE = RT_H2LE_U64(uOffsetSectors);
1338 /* Write the redundant grain directory entry to disk. */
1339 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pExtent->pFile->pStorage,
1340 VMDK_SECTOR2BYTE(pExtent->uSectorRGD) + i * sizeof(uGTSectorLE),
1341 &uGTSectorLE, sizeof(uGTSectorLE));
1342 if (RT_FAILURE(rc))
1343 {
1344 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: cannot write new redundant grain directory entry in '%s'"), pExtent->pszFullname);
1345 goto out;
1346 }
1347 uOffsetSectors += VMDK_BYTE2SECTOR(pExtent->cGTEntries * sizeof(uint32_t));
1348 }
1349 }
1350
1351 uOffsetSectors = pExtent->uSectorGD + VMDK_BYTE2SECTOR(cbGDRounded);
1352 for (i = 0; i < pExtent->cGDEntries; i++)
1353 {
1354 pExtent->pGD[i] = uOffsetSectors;
1355 uGTSectorLE = RT_H2LE_U64(uOffsetSectors);
1356 /* Write the grain directory entry to disk. */
1357 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pExtent->pFile->pStorage,
1358 VMDK_SECTOR2BYTE(pExtent->uSectorGD) + i * sizeof(uGTSectorLE),
1359 &uGTSectorLE, sizeof(uGTSectorLE));
1360 if (RT_FAILURE(rc))
1361 {
1362 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: cannot write new grain directory entry in '%s'"), pExtent->pszFullname);
1363 goto out;
1364 }
1365 uOffsetSectors += VMDK_BYTE2SECTOR(pExtent->cGTEntries * sizeof(uint32_t));
1366 }
1367 }
1368
1369out:
1370 if (RT_FAILURE(rc))
1371 vmdkFreeGrainDirectory(pExtent);
1372 return rc;
1373}
1374
1375/**
1376 * @param ppszUnquoted Where to store the return value, use RTMemTmpFree to
1377 * free.
1378 */
1379static int vmdkStringUnquote(PVMDKIMAGE pImage, const char *pszStr,
1380 char **ppszUnquoted, char **ppszNext)
1381{
1382 const char *pszStart = pszStr;
1383 char *pszQ;
1384 char *pszUnquoted;
1385
1386 /* Skip over whitespace. */
1387 while (*pszStr == ' ' || *pszStr == '\t')
1388 pszStr++;
1389
1390 if (*pszStr != '"')
1391 {
1392 pszQ = (char *)pszStr;
1393 while (*pszQ && *pszQ != ' ' && *pszQ != '\t')
1394 pszQ++;
1395 }
1396 else
1397 {
1398 pszStr++;
1399 pszQ = (char *)strchr(pszStr, '"');
1400 if (pszQ == NULL)
1401 return vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: incorrectly quoted value in descriptor in '%s' (raw value %s)"),
1402 pImage->pszFilename, pszStart);
1403 }
1404
1405 pszUnquoted = (char *)RTMemTmpAlloc(pszQ - pszStr + 1);
1406 if (!pszUnquoted)
1407 return VERR_NO_MEMORY;
1408 memcpy(pszUnquoted, pszStr, pszQ - pszStr);
1409 pszUnquoted[pszQ - pszStr] = '\0';
1410 *ppszUnquoted = pszUnquoted;
1411 if (ppszNext)
1412 *ppszNext = pszQ + 1;
1413 return VINF_SUCCESS;
1414}
1415
1416static int vmdkDescInitStr(PVMDKIMAGE pImage, PVMDKDESCRIPTOR pDescriptor,
1417 const char *pszLine)
1418{
1419 char *pEnd = pDescriptor->aLines[pDescriptor->cLines];
1420 ssize_t cbDiff = strlen(pszLine) + 1;
1421
1422 if ( pDescriptor->cLines >= VMDK_DESCRIPTOR_LINES_MAX - 1
1423 && pEnd - pDescriptor->aLines[0] > (ptrdiff_t)pDescriptor->cbDescAlloc - cbDiff)
1424 return vdIfError(pImage->pIfError, VERR_BUFFER_OVERFLOW, RT_SRC_POS, N_("VMDK: descriptor too big in '%s'"), pImage->pszFilename);
1425
1426 memcpy(pEnd, pszLine, cbDiff);
1427 pDescriptor->cLines++;
1428 pDescriptor->aLines[pDescriptor->cLines] = pEnd + cbDiff;
1429 pDescriptor->fDirty = true;
1430
1431 return VINF_SUCCESS;
1432}
1433
1434static bool vmdkDescGetStr(PVMDKDESCRIPTOR pDescriptor, unsigned uStart,
1435 const char *pszKey, const char **ppszValue)
1436{
1437 size_t cbKey = strlen(pszKey);
1438 const char *pszValue;
1439
1440 while (uStart != 0)
1441 {
1442 if (!strncmp(pDescriptor->aLines[uStart], pszKey, cbKey))
1443 {
1444 /* Key matches, check for a '=' (preceded by whitespace). */
1445 pszValue = pDescriptor->aLines[uStart] + cbKey;
1446 while (*pszValue == ' ' || *pszValue == '\t')
1447 pszValue++;
1448 if (*pszValue == '=')
1449 {
1450 *ppszValue = pszValue + 1;
1451 break;
1452 }
1453 }
1454 uStart = pDescriptor->aNextLines[uStart];
1455 }
1456 return !!uStart;
1457}
1458
1459static int vmdkDescSetStr(PVMDKIMAGE pImage, PVMDKDESCRIPTOR pDescriptor,
1460 unsigned uStart,
1461 const char *pszKey, const char *pszValue)
1462{
1463 char *pszTmp = NULL; /* (MSC naturally cannot figure this isn't used uninitialized) */
1464 size_t cbKey = strlen(pszKey);
1465 unsigned uLast = 0;
1466
1467 while (uStart != 0)
1468 {
1469 if (!strncmp(pDescriptor->aLines[uStart], pszKey, cbKey))
1470 {
1471 /* Key matches, check for a '=' (preceded by whitespace). */
1472 pszTmp = pDescriptor->aLines[uStart] + cbKey;
1473 while (*pszTmp == ' ' || *pszTmp == '\t')
1474 pszTmp++;
1475 if (*pszTmp == '=')
1476 {
1477 pszTmp++;
1478 /** @todo r=bird: Doesn't skipping trailing blanks here just cause unecessary
1479 * bloat and potentially out of space error? */
1480 while (*pszTmp == ' ' || *pszTmp == '\t')
1481 pszTmp++;
1482 break;
1483 }
1484 }
1485 if (!pDescriptor->aNextLines[uStart])
1486 uLast = uStart;
1487 uStart = pDescriptor->aNextLines[uStart];
1488 }
1489 if (uStart)
1490 {
1491 if (pszValue)
1492 {
1493 /* Key already exists, replace existing value. */
1494 size_t cbOldVal = strlen(pszTmp);
1495 size_t cbNewVal = strlen(pszValue);
1496 ssize_t cbDiff = cbNewVal - cbOldVal;
1497 /* Check for buffer overflow. */
1498 if ( pDescriptor->aLines[pDescriptor->cLines] - pDescriptor->aLines[0]
1499 > (ptrdiff_t)pDescriptor->cbDescAlloc - cbDiff)
1500 return vdIfError(pImage->pIfError, VERR_BUFFER_OVERFLOW, RT_SRC_POS, N_("VMDK: descriptor too big in '%s'"), pImage->pszFilename);
1501
1502 memmove(pszTmp + cbNewVal, pszTmp + cbOldVal,
1503 pDescriptor->aLines[pDescriptor->cLines] - pszTmp - cbOldVal);
1504 memcpy(pszTmp, pszValue, cbNewVal + 1);
1505 for (unsigned i = uStart + 1; i <= pDescriptor->cLines; i++)
1506 pDescriptor->aLines[i] += cbDiff;
1507 }
1508 else
1509 {
1510 memmove(pDescriptor->aLines[uStart], pDescriptor->aLines[uStart+1],
1511 pDescriptor->aLines[pDescriptor->cLines] - pDescriptor->aLines[uStart+1] + 1);
1512 for (unsigned i = uStart + 1; i <= pDescriptor->cLines; i++)
1513 {
1514 pDescriptor->aLines[i-1] = pDescriptor->aLines[i];
1515 if (pDescriptor->aNextLines[i])
1516 pDescriptor->aNextLines[i-1] = pDescriptor->aNextLines[i] - 1;
1517 else
1518 pDescriptor->aNextLines[i-1] = 0;
1519 }
1520 pDescriptor->cLines--;
1521 /* Adjust starting line numbers of following descriptor sections. */
1522 if (uStart < pDescriptor->uFirstExtent)
1523 pDescriptor->uFirstExtent--;
1524 if (uStart < pDescriptor->uFirstDDB)
1525 pDescriptor->uFirstDDB--;
1526 }
1527 }
1528 else
1529 {
1530 /* Key doesn't exist, append after the last entry in this category. */
1531 if (!pszValue)
1532 {
1533 /* Key doesn't exist, and it should be removed. Simply a no-op. */
1534 return VINF_SUCCESS;
1535 }
1536 cbKey = strlen(pszKey);
1537 size_t cbValue = strlen(pszValue);
1538 ssize_t cbDiff = cbKey + 1 + cbValue + 1;
1539 /* Check for buffer overflow. */
1540 if ( (pDescriptor->cLines >= VMDK_DESCRIPTOR_LINES_MAX - 1)
1541 || ( pDescriptor->aLines[pDescriptor->cLines]
1542 - pDescriptor->aLines[0] > (ptrdiff_t)pDescriptor->cbDescAlloc - cbDiff))
1543 return vdIfError(pImage->pIfError, VERR_BUFFER_OVERFLOW, RT_SRC_POS, N_("VMDK: descriptor too big in '%s'"), pImage->pszFilename);
1544 for (unsigned i = pDescriptor->cLines + 1; i > uLast + 1; i--)
1545 {
1546 pDescriptor->aLines[i] = pDescriptor->aLines[i - 1];
1547 if (pDescriptor->aNextLines[i - 1])
1548 pDescriptor->aNextLines[i] = pDescriptor->aNextLines[i - 1] + 1;
1549 else
1550 pDescriptor->aNextLines[i] = 0;
1551 }
1552 uStart = uLast + 1;
1553 pDescriptor->aNextLines[uLast] = uStart;
1554 pDescriptor->aNextLines[uStart] = 0;
1555 pDescriptor->cLines++;
1556 pszTmp = pDescriptor->aLines[uStart];
1557 memmove(pszTmp + cbDiff, pszTmp,
1558 pDescriptor->aLines[pDescriptor->cLines] - pszTmp);
1559 memcpy(pDescriptor->aLines[uStart], pszKey, cbKey);
1560 pDescriptor->aLines[uStart][cbKey] = '=';
1561 memcpy(pDescriptor->aLines[uStart] + cbKey + 1, pszValue, cbValue + 1);
1562 for (unsigned i = uStart + 1; i <= pDescriptor->cLines; i++)
1563 pDescriptor->aLines[i] += cbDiff;
1564
1565 /* Adjust starting line numbers of following descriptor sections. */
1566 if (uStart <= pDescriptor->uFirstExtent)
1567 pDescriptor->uFirstExtent++;
1568 if (uStart <= pDescriptor->uFirstDDB)
1569 pDescriptor->uFirstDDB++;
1570 }
1571 pDescriptor->fDirty = true;
1572 return VINF_SUCCESS;
1573}
1574
1575static int vmdkDescBaseGetU32(PVMDKDESCRIPTOR pDescriptor, const char *pszKey,
1576 uint32_t *puValue)
1577{
1578 const char *pszValue;
1579
1580 if (!vmdkDescGetStr(pDescriptor, pDescriptor->uFirstDesc, pszKey,
1581 &pszValue))
1582 return VERR_VD_VMDK_VALUE_NOT_FOUND;
1583 return RTStrToUInt32Ex(pszValue, NULL, 10, puValue);
1584}
1585
1586/**
1587 * @param ppszValue Where to store the return value, use RTMemTmpFree to
1588 * free.
1589 */
1590static int vmdkDescBaseGetStr(PVMDKIMAGE pImage, PVMDKDESCRIPTOR pDescriptor,
1591 const char *pszKey, char **ppszValue)
1592{
1593 const char *pszValue;
1594 char *pszValueUnquoted;
1595
1596 if (!vmdkDescGetStr(pDescriptor, pDescriptor->uFirstDesc, pszKey,
1597 &pszValue))
1598 return VERR_VD_VMDK_VALUE_NOT_FOUND;
1599 int rc = vmdkStringUnquote(pImage, pszValue, &pszValueUnquoted, NULL);
1600 if (RT_FAILURE(rc))
1601 return rc;
1602 *ppszValue = pszValueUnquoted;
1603 return rc;
1604}
1605
1606static int vmdkDescBaseSetStr(PVMDKIMAGE pImage, PVMDKDESCRIPTOR pDescriptor,
1607 const char *pszKey, const char *pszValue)
1608{
1609 char *pszValueQuoted;
1610
1611 RTStrAPrintf(&pszValueQuoted, "\"%s\"", pszValue);
1612 if (!pszValueQuoted)
1613 return VERR_NO_STR_MEMORY;
1614 int rc = vmdkDescSetStr(pImage, pDescriptor, pDescriptor->uFirstDesc, pszKey,
1615 pszValueQuoted);
1616 RTStrFree(pszValueQuoted);
1617 return rc;
1618}
1619
1620static void vmdkDescExtRemoveDummy(PVMDKIMAGE pImage,
1621 PVMDKDESCRIPTOR pDescriptor)
1622{
1623 RT_NOREF1(pImage);
1624 unsigned uEntry = pDescriptor->uFirstExtent;
1625 ssize_t cbDiff;
1626
1627 if (!uEntry)
1628 return;
1629
1630 cbDiff = strlen(pDescriptor->aLines[uEntry]) + 1;
1631 /* Move everything including \0 in the entry marking the end of buffer. */
1632 memmove(pDescriptor->aLines[uEntry], pDescriptor->aLines[uEntry + 1],
1633 pDescriptor->aLines[pDescriptor->cLines] - pDescriptor->aLines[uEntry + 1] + 1);
1634 for (unsigned i = uEntry + 1; i <= pDescriptor->cLines; i++)
1635 {
1636 pDescriptor->aLines[i - 1] = pDescriptor->aLines[i] - cbDiff;
1637 if (pDescriptor->aNextLines[i])
1638 pDescriptor->aNextLines[i - 1] = pDescriptor->aNextLines[i] - 1;
1639 else
1640 pDescriptor->aNextLines[i - 1] = 0;
1641 }
1642 pDescriptor->cLines--;
1643 if (pDescriptor->uFirstDDB)
1644 pDescriptor->uFirstDDB--;
1645
1646 return;
1647}
1648
1649static int vmdkDescExtInsert(PVMDKIMAGE pImage, PVMDKDESCRIPTOR pDescriptor,
1650 VMDKACCESS enmAccess, uint64_t cNominalSectors,
1651 VMDKETYPE enmType, const char *pszBasename,
1652 uint64_t uSectorOffset)
1653{
1654 static const char *apszAccess[] = { "NOACCESS", "RDONLY", "RW" };
1655 static const char *apszType[] = { "", "SPARSE", "FLAT", "ZERO", "VMFS" };
1656 char *pszTmp;
1657 unsigned uStart = pDescriptor->uFirstExtent, uLast = 0;
1658 char szExt[1024];
1659 ssize_t cbDiff;
1660
1661 Assert((unsigned)enmAccess < RT_ELEMENTS(apszAccess));
1662 Assert((unsigned)enmType < RT_ELEMENTS(apszType));
1663
1664 /* Find last entry in extent description. */
1665 while (uStart)
1666 {
1667 if (!pDescriptor->aNextLines[uStart])
1668 uLast = uStart;
1669 uStart = pDescriptor->aNextLines[uStart];
1670 }
1671
1672 if (enmType == VMDKETYPE_ZERO)
1673 {
1674 RTStrPrintf(szExt, sizeof(szExt), "%s %llu %s ", apszAccess[enmAccess],
1675 cNominalSectors, apszType[enmType]);
1676 }
1677 else if (enmType == VMDKETYPE_FLAT)
1678 {
1679 RTStrPrintf(szExt, sizeof(szExt), "%s %llu %s \"%s\" %llu",
1680 apszAccess[enmAccess], cNominalSectors,
1681 apszType[enmType], pszBasename, uSectorOffset);
1682 }
1683 else
1684 {
1685 RTStrPrintf(szExt, sizeof(szExt), "%s %llu %s \"%s\"",
1686 apszAccess[enmAccess], cNominalSectors,
1687 apszType[enmType], pszBasename);
1688 }
1689 cbDiff = strlen(szExt) + 1;
1690
1691 /* Check for buffer overflow. */
1692 if ( (pDescriptor->cLines >= VMDK_DESCRIPTOR_LINES_MAX - 1)
1693 || ( pDescriptor->aLines[pDescriptor->cLines]
1694 - pDescriptor->aLines[0] > (ptrdiff_t)pDescriptor->cbDescAlloc - cbDiff))
1695 return vdIfError(pImage->pIfError, VERR_BUFFER_OVERFLOW, RT_SRC_POS, N_("VMDK: descriptor too big in '%s'"), pImage->pszFilename);
1696
1697 for (unsigned i = pDescriptor->cLines + 1; i > uLast + 1; i--)
1698 {
1699 pDescriptor->aLines[i] = pDescriptor->aLines[i - 1];
1700 if (pDescriptor->aNextLines[i - 1])
1701 pDescriptor->aNextLines[i] = pDescriptor->aNextLines[i - 1] + 1;
1702 else
1703 pDescriptor->aNextLines[i] = 0;
1704 }
1705 uStart = uLast + 1;
1706 pDescriptor->aNextLines[uLast] = uStart;
1707 pDescriptor->aNextLines[uStart] = 0;
1708 pDescriptor->cLines++;
1709 pszTmp = pDescriptor->aLines[uStart];
1710 memmove(pszTmp + cbDiff, pszTmp,
1711 pDescriptor->aLines[pDescriptor->cLines] - pszTmp);
1712 memcpy(pDescriptor->aLines[uStart], szExt, cbDiff);
1713 for (unsigned i = uStart + 1; i <= pDescriptor->cLines; i++)
1714 pDescriptor->aLines[i] += cbDiff;
1715
1716 /* Adjust starting line numbers of following descriptor sections. */
1717 if (uStart <= pDescriptor->uFirstDDB)
1718 pDescriptor->uFirstDDB++;
1719
1720 pDescriptor->fDirty = true;
1721 return VINF_SUCCESS;
1722}
1723
1724/**
1725 * @param ppszValue Where to store the return value, use RTMemTmpFree to
1726 * free.
1727 */
1728static int vmdkDescDDBGetStr(PVMDKIMAGE pImage, PVMDKDESCRIPTOR pDescriptor,
1729 const char *pszKey, char **ppszValue)
1730{
1731 const char *pszValue;
1732 char *pszValueUnquoted;
1733
1734 if (!vmdkDescGetStr(pDescriptor, pDescriptor->uFirstDDB, pszKey,
1735 &pszValue))
1736 return VERR_VD_VMDK_VALUE_NOT_FOUND;
1737 int rc = vmdkStringUnquote(pImage, pszValue, &pszValueUnquoted, NULL);
1738 if (RT_FAILURE(rc))
1739 return rc;
1740 *ppszValue = pszValueUnquoted;
1741 return rc;
1742}
1743
1744static int vmdkDescDDBGetU32(PVMDKIMAGE pImage, PVMDKDESCRIPTOR pDescriptor,
1745 const char *pszKey, uint32_t *puValue)
1746{
1747 const char *pszValue;
1748 char *pszValueUnquoted;
1749
1750 if (!vmdkDescGetStr(pDescriptor, pDescriptor->uFirstDDB, pszKey,
1751 &pszValue))
1752 return VERR_VD_VMDK_VALUE_NOT_FOUND;
1753 int rc = vmdkStringUnquote(pImage, pszValue, &pszValueUnquoted, NULL);
1754 if (RT_FAILURE(rc))
1755 return rc;
1756 rc = RTStrToUInt32Ex(pszValueUnquoted, NULL, 10, puValue);
1757 RTMemTmpFree(pszValueUnquoted);
1758 return rc;
1759}
1760
1761static int vmdkDescDDBGetUuid(PVMDKIMAGE pImage, PVMDKDESCRIPTOR pDescriptor,
1762 const char *pszKey, PRTUUID pUuid)
1763{
1764 const char *pszValue;
1765 char *pszValueUnquoted;
1766
1767 if (!vmdkDescGetStr(pDescriptor, pDescriptor->uFirstDDB, pszKey,
1768 &pszValue))
1769 return VERR_VD_VMDK_VALUE_NOT_FOUND;
1770 int rc = vmdkStringUnquote(pImage, pszValue, &pszValueUnquoted, NULL);
1771 if (RT_FAILURE(rc))
1772 return rc;
1773 rc = RTUuidFromStr(pUuid, pszValueUnquoted);
1774 RTMemTmpFree(pszValueUnquoted);
1775 return rc;
1776}
1777
1778static int vmdkDescDDBSetStr(PVMDKIMAGE pImage, PVMDKDESCRIPTOR pDescriptor,
1779 const char *pszKey, const char *pszVal)
1780{
1781 int rc;
1782 char *pszValQuoted;
1783
1784 if (pszVal)
1785 {
1786 RTStrAPrintf(&pszValQuoted, "\"%s\"", pszVal);
1787 if (!pszValQuoted)
1788 return VERR_NO_STR_MEMORY;
1789 }
1790 else
1791 pszValQuoted = NULL;
1792 rc = vmdkDescSetStr(pImage, pDescriptor, pDescriptor->uFirstDDB, pszKey,
1793 pszValQuoted);
1794 if (pszValQuoted)
1795 RTStrFree(pszValQuoted);
1796 return rc;
1797}
1798
1799static int vmdkDescDDBSetUuid(PVMDKIMAGE pImage, PVMDKDESCRIPTOR pDescriptor,
1800 const char *pszKey, PCRTUUID pUuid)
1801{
1802 char *pszUuid;
1803
1804 RTStrAPrintf(&pszUuid, "\"%RTuuid\"", pUuid);
1805 if (!pszUuid)
1806 return VERR_NO_STR_MEMORY;
1807 int rc = vmdkDescSetStr(pImage, pDescriptor, pDescriptor->uFirstDDB, pszKey,
1808 pszUuid);
1809 RTStrFree(pszUuid);
1810 return rc;
1811}
1812
1813static int vmdkDescDDBSetU32(PVMDKIMAGE pImage, PVMDKDESCRIPTOR pDescriptor,
1814 const char *pszKey, uint32_t uValue)
1815{
1816 char *pszValue;
1817
1818 RTStrAPrintf(&pszValue, "\"%d\"", uValue);
1819 if (!pszValue)
1820 return VERR_NO_STR_MEMORY;
1821 int rc = vmdkDescSetStr(pImage, pDescriptor, pDescriptor->uFirstDDB, pszKey,
1822 pszValue);
1823 RTStrFree(pszValue);
1824 return rc;
1825}
1826
1827static int vmdkPreprocessDescriptor(PVMDKIMAGE pImage, char *pDescData,
1828 size_t cbDescData,
1829 PVMDKDESCRIPTOR pDescriptor)
1830{
1831 int rc = VINF_SUCCESS;
1832 unsigned cLine = 0, uLastNonEmptyLine = 0;
1833 char *pTmp = pDescData;
1834
1835 pDescriptor->cbDescAlloc = cbDescData;
1836 while (*pTmp != '\0')
1837 {
1838 pDescriptor->aLines[cLine++] = pTmp;
1839 if (cLine >= VMDK_DESCRIPTOR_LINES_MAX)
1840 {
1841 rc = vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: descriptor too big in '%s'"), pImage->pszFilename);
1842 goto out;
1843 }
1844
1845 while (*pTmp != '\0' && *pTmp != '\n')
1846 {
1847 if (*pTmp == '\r')
1848 {
1849 if (*(pTmp + 1) != '\n')
1850 {
1851 rc = vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: unsupported end of line in descriptor in '%s'"), pImage->pszFilename);
1852 goto out;
1853 }
1854 else
1855 {
1856 /* Get rid of CR character. */
1857 *pTmp = '\0';
1858 }
1859 }
1860 pTmp++;
1861 }
1862 /* Get rid of LF character. */
1863 if (*pTmp == '\n')
1864 {
1865 *pTmp = '\0';
1866 pTmp++;
1867 }
1868 }
1869 pDescriptor->cLines = cLine;
1870 /* Pointer right after the end of the used part of the buffer. */
1871 pDescriptor->aLines[cLine] = pTmp;
1872
1873 if ( strcmp(pDescriptor->aLines[0], "# Disk DescriptorFile")
1874 && strcmp(pDescriptor->aLines[0], "# Disk Descriptor File"))
1875 {
1876 rc = vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: descriptor does not start as expected in '%s'"), pImage->pszFilename);
1877 goto out;
1878 }
1879
1880 /* Initialize those, because we need to be able to reopen an image. */
1881 pDescriptor->uFirstDesc = 0;
1882 pDescriptor->uFirstExtent = 0;
1883 pDescriptor->uFirstDDB = 0;
1884 for (unsigned i = 0; i < cLine; i++)
1885 {
1886 if (*pDescriptor->aLines[i] != '#' && *pDescriptor->aLines[i] != '\0')
1887 {
1888 if ( !strncmp(pDescriptor->aLines[i], "RW", 2)
1889 || !strncmp(pDescriptor->aLines[i], "RDONLY", 6)
1890 || !strncmp(pDescriptor->aLines[i], "NOACCESS", 8) )
1891 {
1892 /* An extent descriptor. */
1893 if (!pDescriptor->uFirstDesc || pDescriptor->uFirstDDB)
1894 {
1895 /* Incorrect ordering of entries. */
1896 rc = vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: incorrect ordering of entries in descriptor in '%s'"), pImage->pszFilename);
1897 goto out;
1898 }
1899 if (!pDescriptor->uFirstExtent)
1900 {
1901 pDescriptor->uFirstExtent = i;
1902 uLastNonEmptyLine = 0;
1903 }
1904 }
1905 else if (!strncmp(pDescriptor->aLines[i], "ddb.", 4))
1906 {
1907 /* A disk database entry. */
1908 if (!pDescriptor->uFirstDesc || !pDescriptor->uFirstExtent)
1909 {
1910 /* Incorrect ordering of entries. */
1911 rc = vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: incorrect ordering of entries in descriptor in '%s'"), pImage->pszFilename);
1912 goto out;
1913 }
1914 if (!pDescriptor->uFirstDDB)
1915 {
1916 pDescriptor->uFirstDDB = i;
1917 uLastNonEmptyLine = 0;
1918 }
1919 }
1920 else
1921 {
1922 /* A normal entry. */
1923 if (pDescriptor->uFirstExtent || pDescriptor->uFirstDDB)
1924 {
1925 /* Incorrect ordering of entries. */
1926 rc = vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: incorrect ordering of entries in descriptor in '%s'"), pImage->pszFilename);
1927 goto out;
1928 }
1929 if (!pDescriptor->uFirstDesc)
1930 {
1931 pDescriptor->uFirstDesc = i;
1932 uLastNonEmptyLine = 0;
1933 }
1934 }
1935 if (uLastNonEmptyLine)
1936 pDescriptor->aNextLines[uLastNonEmptyLine] = i;
1937 uLastNonEmptyLine = i;
1938 }
1939 }
1940
1941out:
1942 return rc;
1943}
1944
1945static int vmdkDescSetPCHSGeometry(PVMDKIMAGE pImage,
1946 PCVDGEOMETRY pPCHSGeometry)
1947{
1948 int rc = vmdkDescDDBSetU32(pImage, &pImage->Descriptor,
1949 VMDK_DDB_GEO_PCHS_CYLINDERS,
1950 pPCHSGeometry->cCylinders);
1951 if (RT_FAILURE(rc))
1952 return rc;
1953 rc = vmdkDescDDBSetU32(pImage, &pImage->Descriptor,
1954 VMDK_DDB_GEO_PCHS_HEADS,
1955 pPCHSGeometry->cHeads);
1956 if (RT_FAILURE(rc))
1957 return rc;
1958 rc = vmdkDescDDBSetU32(pImage, &pImage->Descriptor,
1959 VMDK_DDB_GEO_PCHS_SECTORS,
1960 pPCHSGeometry->cSectors);
1961 return rc;
1962}
1963
1964static int vmdkDescSetLCHSGeometry(PVMDKIMAGE pImage,
1965 PCVDGEOMETRY pLCHSGeometry)
1966{
1967 int rc = vmdkDescDDBSetU32(pImage, &pImage->Descriptor,
1968 VMDK_DDB_GEO_LCHS_CYLINDERS,
1969 pLCHSGeometry->cCylinders);
1970 if (RT_FAILURE(rc))
1971 return rc;
1972 rc = vmdkDescDDBSetU32(pImage, &pImage->Descriptor,
1973 VMDK_DDB_GEO_LCHS_HEADS,
1974
1975 pLCHSGeometry->cHeads);
1976 if (RT_FAILURE(rc))
1977 return rc;
1978 rc = vmdkDescDDBSetU32(pImage, &pImage->Descriptor,
1979 VMDK_DDB_GEO_LCHS_SECTORS,
1980 pLCHSGeometry->cSectors);
1981 return rc;
1982}
1983
1984static int vmdkCreateDescriptor(PVMDKIMAGE pImage, char *pDescData,
1985 size_t cbDescData, PVMDKDESCRIPTOR pDescriptor)
1986{
1987 int rc;
1988
1989 pDescriptor->uFirstDesc = 0;
1990 pDescriptor->uFirstExtent = 0;
1991 pDescriptor->uFirstDDB = 0;
1992 pDescriptor->cLines = 0;
1993 pDescriptor->cbDescAlloc = cbDescData;
1994 pDescriptor->fDirty = false;
1995 pDescriptor->aLines[pDescriptor->cLines] = pDescData;
1996 memset(pDescriptor->aNextLines, '\0', sizeof(pDescriptor->aNextLines));
1997
1998 rc = vmdkDescInitStr(pImage, pDescriptor, "# Disk DescriptorFile");
1999 if (RT_FAILURE(rc))
2000 goto out;
2001 rc = vmdkDescInitStr(pImage, pDescriptor, "version=1");
2002 if (RT_FAILURE(rc))
2003 goto out;
2004 pDescriptor->uFirstDesc = pDescriptor->cLines - 1;
2005 rc = vmdkDescInitStr(pImage, pDescriptor, "");
2006 if (RT_FAILURE(rc))
2007 goto out;
2008 rc = vmdkDescInitStr(pImage, pDescriptor, "# Extent description");
2009 if (RT_FAILURE(rc))
2010 goto out;
2011 rc = vmdkDescInitStr(pImage, pDescriptor, "NOACCESS 0 ZERO ");
2012 if (RT_FAILURE(rc))
2013 goto out;
2014 pDescriptor->uFirstExtent = pDescriptor->cLines - 1;
2015 rc = vmdkDescInitStr(pImage, pDescriptor, "");
2016 if (RT_FAILURE(rc))
2017 goto out;
2018 /* The trailing space is created by VMware, too. */
2019 rc = vmdkDescInitStr(pImage, pDescriptor, "# The disk Data Base ");
2020 if (RT_FAILURE(rc))
2021 goto out;
2022 rc = vmdkDescInitStr(pImage, pDescriptor, "#DDB");
2023 if (RT_FAILURE(rc))
2024 goto out;
2025 rc = vmdkDescInitStr(pImage, pDescriptor, "");
2026 if (RT_FAILURE(rc))
2027 goto out;
2028 rc = vmdkDescInitStr(pImage, pDescriptor, "ddb.virtualHWVersion = \"4\"");
2029 if (RT_FAILURE(rc))
2030 goto out;
2031 pDescriptor->uFirstDDB = pDescriptor->cLines - 1;
2032
2033 /* Now that the framework is in place, use the normal functions to insert
2034 * the remaining keys. */
2035 char szBuf[9];
2036 RTStrPrintf(szBuf, sizeof(szBuf), "%08x", RTRandU32());
2037 rc = vmdkDescSetStr(pImage, pDescriptor, pDescriptor->uFirstDesc,
2038 "CID", szBuf);
2039 if (RT_FAILURE(rc))
2040 goto out;
2041 rc = vmdkDescSetStr(pImage, pDescriptor, pDescriptor->uFirstDesc,
2042 "parentCID", "ffffffff");
2043 if (RT_FAILURE(rc))
2044 goto out;
2045
2046 rc = vmdkDescDDBSetStr(pImage, pDescriptor, "ddb.adapterType", "ide");
2047 if (RT_FAILURE(rc))
2048 goto out;
2049
2050out:
2051 return rc;
2052}
2053
2054static int vmdkParseDescriptor(PVMDKIMAGE pImage, char *pDescData,
2055 size_t cbDescData)
2056{
2057 int rc;
2058 unsigned cExtents;
2059 unsigned uLine;
2060 unsigned i;
2061
2062 rc = vmdkPreprocessDescriptor(pImage, pDescData, cbDescData,
2063 &pImage->Descriptor);
2064 if (RT_FAILURE(rc))
2065 return rc;
2066
2067 /* Check version, must be 1. */
2068 uint32_t uVersion;
2069 rc = vmdkDescBaseGetU32(&pImage->Descriptor, "version", &uVersion);
2070 if (RT_FAILURE(rc))
2071 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error finding key 'version' in descriptor in '%s'"), pImage->pszFilename);
2072 if (uVersion != 1)
2073 return vdIfError(pImage->pIfError, VERR_VD_VMDK_UNSUPPORTED_VERSION, RT_SRC_POS, N_("VMDK: unsupported format version in descriptor in '%s'"), pImage->pszFilename);
2074
2075 /* Get image creation type and determine image flags. */
2076 char *pszCreateType = NULL; /* initialized to make gcc shut up */
2077 rc = vmdkDescBaseGetStr(pImage, &pImage->Descriptor, "createType",
2078 &pszCreateType);
2079 if (RT_FAILURE(rc))
2080 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: cannot get image type from descriptor in '%s'"), pImage->pszFilename);
2081 if ( !strcmp(pszCreateType, "twoGbMaxExtentSparse")
2082 || !strcmp(pszCreateType, "twoGbMaxExtentFlat"))
2083 pImage->uImageFlags |= VD_VMDK_IMAGE_FLAGS_SPLIT_2G;
2084 else if ( !strcmp(pszCreateType, "partitionedDevice")
2085 || !strcmp(pszCreateType, "fullDevice"))
2086 pImage->uImageFlags |= VD_VMDK_IMAGE_FLAGS_RAWDISK;
2087 else if (!strcmp(pszCreateType, "streamOptimized"))
2088 pImage->uImageFlags |= VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED;
2089 else if (!strcmp(pszCreateType, "vmfs"))
2090 pImage->uImageFlags |= VD_IMAGE_FLAGS_FIXED | VD_VMDK_IMAGE_FLAGS_ESX;
2091 RTMemTmpFree(pszCreateType);
2092
2093 /* Count the number of extent config entries. */
2094 for (uLine = pImage->Descriptor.uFirstExtent, cExtents = 0;
2095 uLine != 0;
2096 uLine = pImage->Descriptor.aNextLines[uLine], cExtents++)
2097 /* nothing */;
2098
2099 if (!pImage->pDescData && cExtents != 1)
2100 {
2101 /* Monolithic image, must have only one extent (already opened). */
2102 return vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: monolithic image may only have one extent in '%s'"), pImage->pszFilename);
2103 }
2104
2105 if (pImage->pDescData)
2106 {
2107 /* Non-monolithic image, extents need to be allocated. */
2108 rc = vmdkCreateExtents(pImage, cExtents);
2109 if (RT_FAILURE(rc))
2110 return rc;
2111 }
2112
2113 for (i = 0, uLine = pImage->Descriptor.uFirstExtent;
2114 i < cExtents; i++, uLine = pImage->Descriptor.aNextLines[uLine])
2115 {
2116 char *pszLine = pImage->Descriptor.aLines[uLine];
2117
2118 /* Access type of the extent. */
2119 if (!strncmp(pszLine, "RW", 2))
2120 {
2121 pImage->pExtents[i].enmAccess = VMDKACCESS_READWRITE;
2122 pszLine += 2;
2123 }
2124 else if (!strncmp(pszLine, "RDONLY", 6))
2125 {
2126 pImage->pExtents[i].enmAccess = VMDKACCESS_READONLY;
2127 pszLine += 6;
2128 }
2129 else if (!strncmp(pszLine, "NOACCESS", 8))
2130 {
2131 pImage->pExtents[i].enmAccess = VMDKACCESS_NOACCESS;
2132 pszLine += 8;
2133 }
2134 else
2135 return vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: parse error in extent description in '%s'"), pImage->pszFilename);
2136 if (*pszLine++ != ' ')
2137 return vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: parse error in extent description in '%s'"), pImage->pszFilename);
2138
2139 /* Nominal size of the extent. */
2140 rc = RTStrToUInt64Ex(pszLine, &pszLine, 10,
2141 &pImage->pExtents[i].cNominalSectors);
2142 if (RT_FAILURE(rc))
2143 return vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: parse error in extent description in '%s'"), pImage->pszFilename);
2144 if (*pszLine++ != ' ')
2145 return vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: parse error in extent description in '%s'"), pImage->pszFilename);
2146
2147 /* Type of the extent. */
2148#ifdef VBOX_WITH_VMDK_ESX
2149 /** @todo Add the ESX extent types. Not necessary for now because
2150 * the ESX extent types are only used inside an ESX server. They are
2151 * automatically converted if the VMDK is exported. */
2152#endif /* VBOX_WITH_VMDK_ESX */
2153 if (!strncmp(pszLine, "SPARSE", 6))
2154 {
2155 pImage->pExtents[i].enmType = VMDKETYPE_HOSTED_SPARSE;
2156 pszLine += 6;
2157 }
2158 else if (!strncmp(pszLine, "FLAT", 4))
2159 {
2160 pImage->pExtents[i].enmType = VMDKETYPE_FLAT;
2161 pszLine += 4;
2162 }
2163 else if (!strncmp(pszLine, "ZERO", 4))
2164 {
2165 pImage->pExtents[i].enmType = VMDKETYPE_ZERO;
2166 pszLine += 4;
2167 }
2168 else if (!strncmp(pszLine, "VMFS", 4))
2169 {
2170 pImage->pExtents[i].enmType = VMDKETYPE_VMFS;
2171 pszLine += 4;
2172 }
2173 else
2174 return vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: parse error in extent description in '%s'"), pImage->pszFilename);
2175
2176 if (pImage->pExtents[i].enmType == VMDKETYPE_ZERO)
2177 {
2178 /* This one has no basename or offset. */
2179 if (*pszLine == ' ')
2180 pszLine++;
2181 if (*pszLine != '\0')
2182 return vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: parse error in extent description in '%s'"), pImage->pszFilename);
2183 pImage->pExtents[i].pszBasename = NULL;
2184 }
2185 else
2186 {
2187 /* All other extent types have basename and optional offset. */
2188 if (*pszLine++ != ' ')
2189 return vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: parse error in extent description in '%s'"), pImage->pszFilename);
2190
2191 /* Basename of the image. Surrounded by quotes. */
2192 char *pszBasename;
2193 rc = vmdkStringUnquote(pImage, pszLine, &pszBasename, &pszLine);
2194 if (RT_FAILURE(rc))
2195 return rc;
2196 pImage->pExtents[i].pszBasename = pszBasename;
2197 if (*pszLine == ' ')
2198 {
2199 pszLine++;
2200 if (*pszLine != '\0')
2201 {
2202 /* Optional offset in extent specified. */
2203 rc = RTStrToUInt64Ex(pszLine, &pszLine, 10,
2204 &pImage->pExtents[i].uSectorOffset);
2205 if (RT_FAILURE(rc))
2206 return vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: parse error in extent description in '%s'"), pImage->pszFilename);
2207 }
2208 }
2209
2210 if (*pszLine != '\0')
2211 return vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: parse error in extent description in '%s'"), pImage->pszFilename);
2212 }
2213 }
2214
2215 /* Determine PCHS geometry (autogenerate if necessary). */
2216 rc = vmdkDescDDBGetU32(pImage, &pImage->Descriptor,
2217 VMDK_DDB_GEO_PCHS_CYLINDERS,
2218 &pImage->PCHSGeometry.cCylinders);
2219 if (rc == VERR_VD_VMDK_VALUE_NOT_FOUND)
2220 pImage->PCHSGeometry.cCylinders = 0;
2221 else if (RT_FAILURE(rc))
2222 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error getting PCHS geometry from extent description in '%s'"), pImage->pszFilename);
2223 rc = vmdkDescDDBGetU32(pImage, &pImage->Descriptor,
2224 VMDK_DDB_GEO_PCHS_HEADS,
2225 &pImage->PCHSGeometry.cHeads);
2226 if (rc == VERR_VD_VMDK_VALUE_NOT_FOUND)
2227 pImage->PCHSGeometry.cHeads = 0;
2228 else if (RT_FAILURE(rc))
2229 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error getting PCHS geometry from extent description in '%s'"), pImage->pszFilename);
2230 rc = vmdkDescDDBGetU32(pImage, &pImage->Descriptor,
2231 VMDK_DDB_GEO_PCHS_SECTORS,
2232 &pImage->PCHSGeometry.cSectors);
2233 if (rc == VERR_VD_VMDK_VALUE_NOT_FOUND)
2234 pImage->PCHSGeometry.cSectors = 0;
2235 else if (RT_FAILURE(rc))
2236 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error getting PCHS geometry from extent description in '%s'"), pImage->pszFilename);
2237 if ( pImage->PCHSGeometry.cCylinders == 0
2238 || pImage->PCHSGeometry.cHeads == 0
2239 || pImage->PCHSGeometry.cHeads > 16
2240 || pImage->PCHSGeometry.cSectors == 0
2241 || pImage->PCHSGeometry.cSectors > 63)
2242 {
2243 /* Mark PCHS geometry as not yet valid (can't do the calculation here
2244 * as the total image size isn't known yet). */
2245 pImage->PCHSGeometry.cCylinders = 0;
2246 pImage->PCHSGeometry.cHeads = 16;
2247 pImage->PCHSGeometry.cSectors = 63;
2248 }
2249
2250 /* Determine LCHS geometry (set to 0 if not specified). */
2251 rc = vmdkDescDDBGetU32(pImage, &pImage->Descriptor,
2252 VMDK_DDB_GEO_LCHS_CYLINDERS,
2253 &pImage->LCHSGeometry.cCylinders);
2254 if (rc == VERR_VD_VMDK_VALUE_NOT_FOUND)
2255 pImage->LCHSGeometry.cCylinders = 0;
2256 else if (RT_FAILURE(rc))
2257 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error getting LCHS geometry from extent description in '%s'"), pImage->pszFilename);
2258 rc = vmdkDescDDBGetU32(pImage, &pImage->Descriptor,
2259 VMDK_DDB_GEO_LCHS_HEADS,
2260 &pImage->LCHSGeometry.cHeads);
2261 if (rc == VERR_VD_VMDK_VALUE_NOT_FOUND)
2262 pImage->LCHSGeometry.cHeads = 0;
2263 else if (RT_FAILURE(rc))
2264 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error getting LCHS geometry from extent description in '%s'"), pImage->pszFilename);
2265 rc = vmdkDescDDBGetU32(pImage, &pImage->Descriptor,
2266 VMDK_DDB_GEO_LCHS_SECTORS,
2267 &pImage->LCHSGeometry.cSectors);
2268 if (rc == VERR_VD_VMDK_VALUE_NOT_FOUND)
2269 pImage->LCHSGeometry.cSectors = 0;
2270 else if (RT_FAILURE(rc))
2271 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error getting LCHS geometry from extent description in '%s'"), pImage->pszFilename);
2272 if ( pImage->LCHSGeometry.cCylinders == 0
2273 || pImage->LCHSGeometry.cHeads == 0
2274 || pImage->LCHSGeometry.cSectors == 0)
2275 {
2276 pImage->LCHSGeometry.cCylinders = 0;
2277 pImage->LCHSGeometry.cHeads = 0;
2278 pImage->LCHSGeometry.cSectors = 0;
2279 }
2280
2281 /* Get image UUID. */
2282 rc = vmdkDescDDBGetUuid(pImage, &pImage->Descriptor, VMDK_DDB_IMAGE_UUID,
2283 &pImage->ImageUuid);
2284 if (rc == VERR_VD_VMDK_VALUE_NOT_FOUND)
2285 {
2286 /* Image without UUID. Probably created by VMware and not yet used
2287 * by VirtualBox. Can only be added for images opened in read/write
2288 * mode, so don't bother producing a sensible UUID otherwise. */
2289 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2290 RTUuidClear(&pImage->ImageUuid);
2291 else
2292 {
2293 rc = RTUuidCreate(&pImage->ImageUuid);
2294 if (RT_FAILURE(rc))
2295 return rc;
2296 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
2297 VMDK_DDB_IMAGE_UUID, &pImage->ImageUuid);
2298 if (RT_FAILURE(rc))
2299 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error storing image UUID in descriptor in '%s'"), pImage->pszFilename);
2300 }
2301 }
2302 else if (RT_FAILURE(rc))
2303 return rc;
2304
2305 /* Get image modification UUID. */
2306 rc = vmdkDescDDBGetUuid(pImage, &pImage->Descriptor,
2307 VMDK_DDB_MODIFICATION_UUID,
2308 &pImage->ModificationUuid);
2309 if (rc == VERR_VD_VMDK_VALUE_NOT_FOUND)
2310 {
2311 /* Image without UUID. Probably created by VMware and not yet used
2312 * by VirtualBox. Can only be added for images opened in read/write
2313 * mode, so don't bother producing a sensible UUID otherwise. */
2314 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2315 RTUuidClear(&pImage->ModificationUuid);
2316 else
2317 {
2318 rc = RTUuidCreate(&pImage->ModificationUuid);
2319 if (RT_FAILURE(rc))
2320 return rc;
2321 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
2322 VMDK_DDB_MODIFICATION_UUID,
2323 &pImage->ModificationUuid);
2324 if (RT_FAILURE(rc))
2325 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error storing image modification UUID in descriptor in '%s'"), pImage->pszFilename);
2326 }
2327 }
2328 else if (RT_FAILURE(rc))
2329 return rc;
2330
2331 /* Get UUID of parent image. */
2332 rc = vmdkDescDDBGetUuid(pImage, &pImage->Descriptor, VMDK_DDB_PARENT_UUID,
2333 &pImage->ParentUuid);
2334 if (rc == VERR_VD_VMDK_VALUE_NOT_FOUND)
2335 {
2336 /* Image without UUID. Probably created by VMware and not yet used
2337 * by VirtualBox. Can only be added for images opened in read/write
2338 * mode, so don't bother producing a sensible UUID otherwise. */
2339 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2340 RTUuidClear(&pImage->ParentUuid);
2341 else
2342 {
2343 rc = RTUuidClear(&pImage->ParentUuid);
2344 if (RT_FAILURE(rc))
2345 return rc;
2346 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
2347 VMDK_DDB_PARENT_UUID, &pImage->ParentUuid);
2348 if (RT_FAILURE(rc))
2349 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error storing parent UUID in descriptor in '%s'"), pImage->pszFilename);
2350 }
2351 }
2352 else if (RT_FAILURE(rc))
2353 return rc;
2354
2355 /* Get parent image modification UUID. */
2356 rc = vmdkDescDDBGetUuid(pImage, &pImage->Descriptor,
2357 VMDK_DDB_PARENT_MODIFICATION_UUID,
2358 &pImage->ParentModificationUuid);
2359 if (rc == VERR_VD_VMDK_VALUE_NOT_FOUND)
2360 {
2361 /* Image without UUID. Probably created by VMware and not yet used
2362 * by VirtualBox. Can only be added for images opened in read/write
2363 * mode, so don't bother producing a sensible UUID otherwise. */
2364 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2365 RTUuidClear(&pImage->ParentModificationUuid);
2366 else
2367 {
2368 RTUuidClear(&pImage->ParentModificationUuid);
2369 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
2370 VMDK_DDB_PARENT_MODIFICATION_UUID,
2371 &pImage->ParentModificationUuid);
2372 if (RT_FAILURE(rc))
2373 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error storing parent modification UUID in descriptor in '%s'"), pImage->pszFilename);
2374 }
2375 }
2376 else if (RT_FAILURE(rc))
2377 return rc;
2378
2379 return VINF_SUCCESS;
2380}
2381
2382/**
2383 * Internal : Prepares the descriptor to write to the image.
2384 */
2385static int vmdkDescriptorPrepare(PVMDKIMAGE pImage, uint64_t cbLimit,
2386 void **ppvData, size_t *pcbData)
2387{
2388 int rc = VINF_SUCCESS;
2389
2390 /*
2391 * Allocate temporary descriptor buffer.
2392 * In case there is no limit allocate a default
2393 * and increase if required.
2394 */
2395 size_t cbDescriptor = cbLimit ? cbLimit : 4 * _1K;
2396 char *pszDescriptor = (char *)RTMemAllocZ(cbDescriptor);
2397 size_t offDescriptor = 0;
2398
2399 if (!pszDescriptor)
2400 return VERR_NO_MEMORY;
2401
2402 for (unsigned i = 0; i < pImage->Descriptor.cLines; i++)
2403 {
2404 const char *psz = pImage->Descriptor.aLines[i];
2405 size_t cb = strlen(psz);
2406
2407 /*
2408 * Increase the descriptor if there is no limit and
2409 * there is not enough room left for this line.
2410 */
2411 if (offDescriptor + cb + 1 > cbDescriptor)
2412 {
2413 if (cbLimit)
2414 {
2415 rc = vdIfError(pImage->pIfError, VERR_BUFFER_OVERFLOW, RT_SRC_POS, N_("VMDK: descriptor too long in '%s'"), pImage->pszFilename);
2416 break;
2417 }
2418 else
2419 {
2420 char *pszDescriptorNew = NULL;
2421 LogFlow(("Increasing descriptor cache\n"));
2422
2423 pszDescriptorNew = (char *)RTMemRealloc(pszDescriptor, cbDescriptor + cb + 4 * _1K);
2424 if (!pszDescriptorNew)
2425 {
2426 rc = VERR_NO_MEMORY;
2427 break;
2428 }
2429 pszDescriptor = pszDescriptorNew;
2430 cbDescriptor += cb + 4 * _1K;
2431 }
2432 }
2433
2434 if (cb > 0)
2435 {
2436 memcpy(pszDescriptor + offDescriptor, psz, cb);
2437 offDescriptor += cb;
2438 }
2439
2440 memcpy(pszDescriptor + offDescriptor, "\n", 1);
2441 offDescriptor++;
2442 }
2443
2444 if (RT_SUCCESS(rc))
2445 {
2446 *ppvData = pszDescriptor;
2447 *pcbData = offDescriptor;
2448 }
2449 else if (pszDescriptor)
2450 RTMemFree(pszDescriptor);
2451
2452 return rc;
2453}
2454
2455/**
2456 * Internal: write/update the descriptor part of the image.
2457 */
2458static int vmdkWriteDescriptor(PVMDKIMAGE pImage, PVDIOCTX pIoCtx)
2459{
2460 int rc = VINF_SUCCESS;
2461 uint64_t cbLimit;
2462 uint64_t uOffset;
2463 PVMDKFILE pDescFile;
2464 void *pvDescriptor = NULL;
2465 size_t cbDescriptor;
2466
2467 if (pImage->pDescData)
2468 {
2469 /* Separate descriptor file. */
2470 uOffset = 0;
2471 cbLimit = 0;
2472 pDescFile = pImage->pFile;
2473 }
2474 else
2475 {
2476 /* Embedded descriptor file. */
2477 uOffset = VMDK_SECTOR2BYTE(pImage->pExtents[0].uDescriptorSector);
2478 cbLimit = VMDK_SECTOR2BYTE(pImage->pExtents[0].cDescriptorSectors);
2479 pDescFile = pImage->pExtents[0].pFile;
2480 }
2481 /* Bail out if there is no file to write to. */
2482 if (pDescFile == NULL)
2483 return VERR_INVALID_PARAMETER;
2484
2485 rc = vmdkDescriptorPrepare(pImage, cbLimit, &pvDescriptor, &cbDescriptor);
2486 if (RT_SUCCESS(rc))
2487 {
2488 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pDescFile->pStorage,
2489 uOffset, pvDescriptor,
2490 cbLimit ? cbLimit : cbDescriptor,
2491 pIoCtx, NULL, NULL);
2492 if ( RT_FAILURE(rc)
2493 && rc != VERR_VD_ASYNC_IO_IN_PROGRESS)
2494 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error writing descriptor in '%s'"), pImage->pszFilename);
2495 }
2496
2497 if (RT_SUCCESS(rc) && !cbLimit)
2498 {
2499 rc = vdIfIoIntFileSetSize(pImage->pIfIo, pDescFile->pStorage, cbDescriptor);
2500 if (RT_FAILURE(rc))
2501 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error truncating descriptor in '%s'"), pImage->pszFilename);
2502 }
2503
2504 if (RT_SUCCESS(rc))
2505 pImage->Descriptor.fDirty = false;
2506
2507 if (pvDescriptor)
2508 RTMemFree(pvDescriptor);
2509 return rc;
2510
2511}
2512
2513/**
2514 * Internal: validate the consistency check values in a binary header.
2515 */
2516static int vmdkValidateHeader(PVMDKIMAGE pImage, PVMDKEXTENT pExtent, const SparseExtentHeader *pHeader)
2517{
2518 int rc = VINF_SUCCESS;
2519 if (RT_LE2H_U32(pHeader->magicNumber) != VMDK_SPARSE_MAGICNUMBER)
2520 {
2521 rc = vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: incorrect magic in sparse extent header in '%s'"), pExtent->pszFullname);
2522 return rc;
2523 }
2524 if (RT_LE2H_U32(pHeader->version) != 1 && RT_LE2H_U32(pHeader->version) != 3)
2525 {
2526 rc = vdIfError(pImage->pIfError, VERR_VD_VMDK_UNSUPPORTED_VERSION, RT_SRC_POS, N_("VMDK: incorrect version in sparse extent header in '%s', not a VMDK 1.0/1.1 conforming file"), pExtent->pszFullname);
2527 return rc;
2528 }
2529 if ( (RT_LE2H_U32(pHeader->flags) & 1)
2530 && ( pHeader->singleEndLineChar != '\n'
2531 || pHeader->nonEndLineChar != ' '
2532 || pHeader->doubleEndLineChar1 != '\r'
2533 || pHeader->doubleEndLineChar2 != '\n') )
2534 {
2535 rc = vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: corrupted by CR/LF translation in '%s'"), pExtent->pszFullname);
2536 return rc;
2537 }
2538 return rc;
2539}
2540
2541/**
2542 * Internal: read metadata belonging to an extent with binary header, i.e.
2543 * as found in monolithic files.
2544 */
2545static int vmdkReadBinaryMetaExtent(PVMDKIMAGE pImage, PVMDKEXTENT pExtent,
2546 bool fMagicAlreadyRead)
2547{
2548 SparseExtentHeader Header;
2549 uint64_t cSectorsPerGDE;
2550 uint64_t cbFile = 0;
2551 int rc;
2552
2553 if (!fMagicAlreadyRead)
2554 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pExtent->pFile->pStorage, 0,
2555 &Header, sizeof(Header));
2556 else
2557 {
2558 Header.magicNumber = RT_H2LE_U32(VMDK_SPARSE_MAGICNUMBER);
2559 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pExtent->pFile->pStorage,
2560 RT_OFFSETOF(SparseExtentHeader, version),
2561 &Header.version,
2562 sizeof(Header)
2563 - RT_OFFSETOF(SparseExtentHeader, version));
2564 }
2565 AssertRC(rc);
2566 if (RT_FAILURE(rc))
2567 {
2568 vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error reading extent header in '%s'"), pExtent->pszFullname);
2569 rc = VERR_VD_VMDK_INVALID_HEADER;
2570 goto out;
2571 }
2572 rc = vmdkValidateHeader(pImage, pExtent, &Header);
2573 if (RT_FAILURE(rc))
2574 goto out;
2575
2576 if ( (RT_LE2H_U32(Header.flags) & RT_BIT(17))
2577 && RT_LE2H_U64(Header.gdOffset) == VMDK_GD_AT_END)
2578 pExtent->fFooter = true;
2579
2580 if ( !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2581 || ( pExtent->fFooter
2582 && !(pImage->uOpenFlags & VD_OPEN_FLAGS_SEQUENTIAL)))
2583 {
2584 rc = vdIfIoIntFileGetSize(pImage->pIfIo, pExtent->pFile->pStorage, &cbFile);
2585 AssertRC(rc);
2586 if (RT_FAILURE(rc))
2587 {
2588 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: cannot get size of '%s'"), pExtent->pszFullname);
2589 goto out;
2590 }
2591 }
2592
2593 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
2594 pExtent->uAppendPosition = RT_ALIGN_64(cbFile, 512);
2595
2596 if ( pExtent->fFooter
2597 && ( !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2598 || !(pImage->uOpenFlags & VD_OPEN_FLAGS_SEQUENTIAL)))
2599 {
2600 /* Read the footer, which comes before the end-of-stream marker. */
2601 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pExtent->pFile->pStorage,
2602 cbFile - 2*512, &Header,
2603 sizeof(Header));
2604 AssertRC(rc);
2605 if (RT_FAILURE(rc))
2606 {
2607 vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error reading extent footer in '%s'"), pExtent->pszFullname);
2608 rc = VERR_VD_VMDK_INVALID_HEADER;
2609 goto out;
2610 }
2611 rc = vmdkValidateHeader(pImage, pExtent, &Header);
2612 if (RT_FAILURE(rc))
2613 goto out;
2614 /* Prohibit any writes to this extent. */
2615 pExtent->uAppendPosition = 0;
2616 }
2617
2618 pExtent->uVersion = RT_LE2H_U32(Header.version);
2619 pExtent->enmType = VMDKETYPE_HOSTED_SPARSE; /* Just dummy value, changed later. */
2620 pExtent->cSectors = RT_LE2H_U64(Header.capacity);
2621 pExtent->cSectorsPerGrain = RT_LE2H_U64(Header.grainSize);
2622 pExtent->uDescriptorSector = RT_LE2H_U64(Header.descriptorOffset);
2623 pExtent->cDescriptorSectors = RT_LE2H_U64(Header.descriptorSize);
2624 if (pExtent->uDescriptorSector && !pExtent->cDescriptorSectors)
2625 {
2626 rc = vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: inconsistent embedded descriptor config in '%s'"), pExtent->pszFullname);
2627 goto out;
2628 }
2629 pExtent->cGTEntries = RT_LE2H_U32(Header.numGTEsPerGT);
2630 if (RT_LE2H_U32(Header.flags) & RT_BIT(1))
2631 {
2632 pExtent->uSectorRGD = RT_LE2H_U64(Header.rgdOffset);
2633 pExtent->uSectorGD = RT_LE2H_U64(Header.gdOffset);
2634 }
2635 else
2636 {
2637 pExtent->uSectorGD = RT_LE2H_U64(Header.gdOffset);
2638 pExtent->uSectorRGD = 0;
2639 }
2640 if ( ( pExtent->uSectorGD == VMDK_GD_AT_END
2641 || pExtent->uSectorRGD == VMDK_GD_AT_END)
2642 && ( !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2643 || !(pImage->uOpenFlags & VD_OPEN_FLAGS_SEQUENTIAL)))
2644 {
2645 rc = vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: cannot resolve grain directory offset in '%s'"), pExtent->pszFullname);
2646 goto out;
2647 }
2648 pExtent->cOverheadSectors = RT_LE2H_U64(Header.overHead);
2649 pExtent->fUncleanShutdown = !!Header.uncleanShutdown;
2650 pExtent->uCompression = RT_LE2H_U16(Header.compressAlgorithm);
2651 cSectorsPerGDE = pExtent->cGTEntries * pExtent->cSectorsPerGrain;
2652 if (!cSectorsPerGDE || cSectorsPerGDE > UINT32_MAX)
2653 {
2654 rc = vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: incorrect grain directory size in '%s'"), pExtent->pszFullname);
2655 goto out;
2656 }
2657 pExtent->cSectorsPerGDE = cSectorsPerGDE;
2658 pExtent->cGDEntries = (pExtent->cSectors + cSectorsPerGDE - 1) / cSectorsPerGDE;
2659
2660 /* Fix up the number of descriptor sectors, as some flat images have
2661 * really just one, and this causes failures when inserting the UUID
2662 * values and other extra information. */
2663 if (pExtent->cDescriptorSectors != 0 && pExtent->cDescriptorSectors < 4)
2664 {
2665 /* Do it the easy way - just fix it for flat images which have no
2666 * other complicated metadata which needs space too. */
2667 if ( pExtent->uDescriptorSector + 4 < pExtent->cOverheadSectors
2668 && pExtent->cGTEntries * pExtent->cGDEntries == 0)
2669 pExtent->cDescriptorSectors = 4;
2670 }
2671
2672out:
2673 if (RT_FAILURE(rc))
2674 vmdkFreeExtentData(pImage, pExtent, false);
2675
2676 return rc;
2677}
2678
2679/**
2680 * Internal: read additional metadata belonging to an extent. For those
2681 * extents which have no additional metadata just verify the information.
2682 */
2683static int vmdkReadMetaExtent(PVMDKIMAGE pImage, PVMDKEXTENT pExtent)
2684{
2685 int rc = VINF_SUCCESS;
2686
2687/* disabled the check as there are too many truncated vmdk images out there */
2688#ifdef VBOX_WITH_VMDK_STRICT_SIZE_CHECK
2689 uint64_t cbExtentSize;
2690 /* The image must be a multiple of a sector in size and contain the data
2691 * area (flat images only). If not, it means the image is at least
2692 * truncated, or even seriously garbled. */
2693 rc = vdIfIoIntFileGetSize(pImage->pIfIo, pExtent->pFile->pStorage, &cbExtentSize);
2694 if (RT_FAILURE(rc))
2695 {
2696 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error getting size in '%s'"), pExtent->pszFullname);
2697 goto out;
2698 }
2699 if ( cbExtentSize != RT_ALIGN_64(cbExtentSize, 512)
2700 && (pExtent->enmType != VMDKETYPE_FLAT || pExtent->cNominalSectors + pExtent->uSectorOffset > VMDK_BYTE2SECTOR(cbExtentSize)))
2701 {
2702 rc = vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: file size is not a multiple of 512 in '%s', file is truncated or otherwise garbled"), pExtent->pszFullname);
2703 goto out;
2704 }
2705#endif /* VBOX_WITH_VMDK_STRICT_SIZE_CHECK */
2706 if (pExtent->enmType != VMDKETYPE_HOSTED_SPARSE)
2707 goto out;
2708
2709 /* The spec says that this must be a power of two and greater than 8,
2710 * but probably they meant not less than 8. */
2711 if ( (pExtent->cSectorsPerGrain & (pExtent->cSectorsPerGrain - 1))
2712 || pExtent->cSectorsPerGrain < 8)
2713 {
2714 rc = vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: invalid extent grain size %u in '%s'"), pExtent->cSectorsPerGrain, pExtent->pszFullname);
2715 goto out;
2716 }
2717
2718 /* This code requires that a grain table must hold a power of two multiple
2719 * of the number of entries per GT cache entry. */
2720 if ( (pExtent->cGTEntries & (pExtent->cGTEntries - 1))
2721 || pExtent->cGTEntries < VMDK_GT_CACHELINE_SIZE)
2722 {
2723 rc = vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: grain table cache size problem in '%s'"), pExtent->pszFullname);
2724 goto out;
2725 }
2726
2727 rc = vmdkAllocStreamBuffers(pImage, pExtent);
2728 if (RT_FAILURE(rc))
2729 goto out;
2730
2731 /* Prohibit any writes to this streamOptimized extent. */
2732 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
2733 pExtent->uAppendPosition = 0;
2734
2735 if ( !(pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
2736 || !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2737 || !(pImage->uOpenFlags & VD_OPEN_FLAGS_SEQUENTIAL))
2738 rc = vmdkReadGrainDirectory(pImage, pExtent);
2739 else
2740 {
2741 pExtent->uGrainSectorAbs = pExtent->cOverheadSectors;
2742 pExtent->cbGrainStreamRead = 0;
2743 }
2744
2745out:
2746 if (RT_FAILURE(rc))
2747 vmdkFreeExtentData(pImage, pExtent, false);
2748
2749 return rc;
2750}
2751
2752/**
2753 * Internal: write/update the metadata for a sparse extent.
2754 */
2755static int vmdkWriteMetaSparseExtent(PVMDKIMAGE pImage, PVMDKEXTENT pExtent,
2756 uint64_t uOffset, PVDIOCTX pIoCtx)
2757{
2758 SparseExtentHeader Header;
2759
2760 memset(&Header, '\0', sizeof(Header));
2761 Header.magicNumber = RT_H2LE_U32(VMDK_SPARSE_MAGICNUMBER);
2762 Header.version = RT_H2LE_U32(pExtent->uVersion);
2763 Header.flags = RT_H2LE_U32(RT_BIT(0));
2764 if (pExtent->pRGD)
2765 Header.flags |= RT_H2LE_U32(RT_BIT(1));
2766 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
2767 Header.flags |= RT_H2LE_U32(RT_BIT(16) | RT_BIT(17));
2768 Header.capacity = RT_H2LE_U64(pExtent->cSectors);
2769 Header.grainSize = RT_H2LE_U64(pExtent->cSectorsPerGrain);
2770 Header.descriptorOffset = RT_H2LE_U64(pExtent->uDescriptorSector);
2771 Header.descriptorSize = RT_H2LE_U64(pExtent->cDescriptorSectors);
2772 Header.numGTEsPerGT = RT_H2LE_U32(pExtent->cGTEntries);
2773 if (pExtent->fFooter && uOffset == 0)
2774 {
2775 if (pExtent->pRGD)
2776 {
2777 Assert(pExtent->uSectorRGD);
2778 Header.rgdOffset = RT_H2LE_U64(VMDK_GD_AT_END);
2779 Header.gdOffset = RT_H2LE_U64(VMDK_GD_AT_END);
2780 }
2781 else
2782 {
2783 Header.gdOffset = RT_H2LE_U64(VMDK_GD_AT_END);
2784 }
2785 }
2786 else
2787 {
2788 if (pExtent->pRGD)
2789 {
2790 Assert(pExtent->uSectorRGD);
2791 Header.rgdOffset = RT_H2LE_U64(pExtent->uSectorRGD);
2792 Header.gdOffset = RT_H2LE_U64(pExtent->uSectorGD);
2793 }
2794 else
2795 {
2796 Header.gdOffset = RT_H2LE_U64(pExtent->uSectorGD);
2797 }
2798 }
2799 Header.overHead = RT_H2LE_U64(pExtent->cOverheadSectors);
2800 Header.uncleanShutdown = pExtent->fUncleanShutdown;
2801 Header.singleEndLineChar = '\n';
2802 Header.nonEndLineChar = ' ';
2803 Header.doubleEndLineChar1 = '\r';
2804 Header.doubleEndLineChar2 = '\n';
2805 Header.compressAlgorithm = RT_H2LE_U16(pExtent->uCompression);
2806
2807 int rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pExtent->pFile->pStorage,
2808 uOffset, &Header, sizeof(Header),
2809 pIoCtx, NULL, NULL);
2810 if (RT_FAILURE(rc) && (rc != VERR_VD_ASYNC_IO_IN_PROGRESS))
2811 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error writing extent header in '%s'"), pExtent->pszFullname);
2812 return rc;
2813}
2814
2815#ifdef VBOX_WITH_VMDK_ESX
2816/**
2817 * Internal: unused code to read the metadata of a sparse ESX extent.
2818 *
2819 * Such extents never leave ESX server, so this isn't ever used.
2820 */
2821static int vmdkReadMetaESXSparseExtent(PVMDKEXTENT pExtent)
2822{
2823 COWDisk_Header Header;
2824 uint64_t cSectorsPerGDE;
2825
2826 int rc = vdIfIoIntFileReadSync(pImage->pIfIo, pExtent->pFile->pStorage, 0,
2827 &Header, sizeof(Header));
2828 AssertRC(rc);
2829 if (RT_FAILURE(rc))
2830 {
2831 vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error reading ESX sparse extent header in '%s'"), pExtent->pszFullname);
2832 rc = VERR_VD_VMDK_INVALID_HEADER;
2833 goto out;
2834 }
2835 if ( RT_LE2H_U32(Header.magicNumber) != VMDK_ESX_SPARSE_MAGICNUMBER
2836 || RT_LE2H_U32(Header.version) != 1
2837 || RT_LE2H_U32(Header.flags) != 3)
2838 {
2839 rc = VERR_VD_VMDK_INVALID_HEADER;
2840 goto out;
2841 }
2842 pExtent->enmType = VMDKETYPE_ESX_SPARSE;
2843 pExtent->cSectors = RT_LE2H_U32(Header.numSectors);
2844 pExtent->cSectorsPerGrain = RT_LE2H_U32(Header.grainSize);
2845 /* The spec says that this must be between 1 sector and 1MB. This code
2846 * assumes it's a power of two, so check that requirement, too. */
2847 if ( (pExtent->cSectorsPerGrain & (pExtent->cSectorsPerGrain - 1))
2848 || pExtent->cSectorsPerGrain == 0
2849 || pExtent->cSectorsPerGrain > 2048)
2850 {
2851 rc = VERR_VD_VMDK_INVALID_HEADER;
2852 goto out;
2853 }
2854 pExtent->uDescriptorSector = 0;
2855 pExtent->cDescriptorSectors = 0;
2856 pExtent->uSectorGD = RT_LE2H_U32(Header.gdOffset);
2857 pExtent->uSectorRGD = 0;
2858 pExtent->cOverheadSectors = 0;
2859 pExtent->cGTEntries = 4096;
2860 cSectorsPerGDE = pExtent->cGTEntries * pExtent->cSectorsPerGrain;
2861 if (!cSectorsPerGDE || cSectorsPerGDE > UINT32_MAX)
2862 {
2863 rc = VERR_VD_VMDK_INVALID_HEADER;
2864 goto out;
2865 }
2866 pExtent->cSectorsPerGDE = cSectorsPerGDE;
2867 pExtent->cGDEntries = (pExtent->cSectors + cSectorsPerGDE - 1) / cSectorsPerGDE;
2868 if (pExtent->cGDEntries != RT_LE2H_U32(Header.numGDEntries))
2869 {
2870 /* Inconsistency detected. Computed number of GD entries doesn't match
2871 * stored value. Better be safe than sorry. */
2872 rc = VERR_VD_VMDK_INVALID_HEADER;
2873 goto out;
2874 }
2875 pExtent->uFreeSector = RT_LE2H_U32(Header.freeSector);
2876 pExtent->fUncleanShutdown = !!Header.uncleanShutdown;
2877
2878 rc = vmdkReadGrainDirectory(pImage, pExtent);
2879
2880out:
2881 if (RT_FAILURE(rc))
2882 vmdkFreeExtentData(pImage, pExtent, false);
2883
2884 return rc;
2885}
2886#endif /* VBOX_WITH_VMDK_ESX */
2887
2888/**
2889 * Internal: free the buffers used for streamOptimized images.
2890 */
2891static void vmdkFreeStreamBuffers(PVMDKEXTENT pExtent)
2892{
2893 if (pExtent->pvCompGrain)
2894 {
2895 RTMemFree(pExtent->pvCompGrain);
2896 pExtent->pvCompGrain = NULL;
2897 }
2898 if (pExtent->pvGrain)
2899 {
2900 RTMemFree(pExtent->pvGrain);
2901 pExtent->pvGrain = NULL;
2902 }
2903}
2904
2905/**
2906 * Internal: free the memory used by the extent data structure, optionally
2907 * deleting the referenced files.
2908 *
2909 * @returns VBox status code.
2910 * @param pImage Pointer to the image instance data.
2911 * @param pExtent The extent to free.
2912 * @param fDelete Flag whether to delete the backing storage.
2913 */
2914static int vmdkFreeExtentData(PVMDKIMAGE pImage, PVMDKEXTENT pExtent,
2915 bool fDelete)
2916{
2917 int rc = VINF_SUCCESS;
2918
2919 vmdkFreeGrainDirectory(pExtent);
2920 if (pExtent->pDescData)
2921 {
2922 RTMemFree(pExtent->pDescData);
2923 pExtent->pDescData = NULL;
2924 }
2925 if (pExtent->pFile != NULL)
2926 {
2927 /* Do not delete raw extents, these have full and base names equal. */
2928 rc = vmdkFileClose(pImage, &pExtent->pFile,
2929 fDelete
2930 && pExtent->pszFullname
2931 && pExtent->pszBasename
2932 && strcmp(pExtent->pszFullname, pExtent->pszBasename));
2933 }
2934 if (pExtent->pszBasename)
2935 {
2936 RTMemTmpFree((void *)pExtent->pszBasename);
2937 pExtent->pszBasename = NULL;
2938 }
2939 if (pExtent->pszFullname)
2940 {
2941 RTStrFree((char *)(void *)pExtent->pszFullname);
2942 pExtent->pszFullname = NULL;
2943 }
2944 vmdkFreeStreamBuffers(pExtent);
2945
2946 return rc;
2947}
2948
2949/**
2950 * Internal: allocate grain table cache if necessary for this image.
2951 */
2952static int vmdkAllocateGrainTableCache(PVMDKIMAGE pImage)
2953{
2954 PVMDKEXTENT pExtent;
2955
2956 /* Allocate grain table cache if any sparse extent is present. */
2957 for (unsigned i = 0; i < pImage->cExtents; i++)
2958 {
2959 pExtent = &pImage->pExtents[i];
2960 if ( pExtent->enmType == VMDKETYPE_HOSTED_SPARSE
2961#ifdef VBOX_WITH_VMDK_ESX
2962 || pExtent->enmType == VMDKETYPE_ESX_SPARSE
2963#endif /* VBOX_WITH_VMDK_ESX */
2964 )
2965 {
2966 /* Allocate grain table cache. */
2967 pImage->pGTCache = (PVMDKGTCACHE)RTMemAllocZ(sizeof(VMDKGTCACHE));
2968 if (!pImage->pGTCache)
2969 return VERR_NO_MEMORY;
2970 for (unsigned j = 0; j < VMDK_GT_CACHE_SIZE; j++)
2971 {
2972 PVMDKGTCACHEENTRY pGCE = &pImage->pGTCache->aGTCache[j];
2973 pGCE->uExtent = UINT32_MAX;
2974 }
2975 pImage->pGTCache->cEntries = VMDK_GT_CACHE_SIZE;
2976 break;
2977 }
2978 }
2979
2980 return VINF_SUCCESS;
2981}
2982
2983/**
2984 * Internal: allocate the given number of extents.
2985 */
2986static int vmdkCreateExtents(PVMDKIMAGE pImage, unsigned cExtents)
2987{
2988 int rc = VINF_SUCCESS;
2989 PVMDKEXTENT pExtents = (PVMDKEXTENT)RTMemAllocZ(cExtents * sizeof(VMDKEXTENT));
2990 if (pExtents)
2991 {
2992 for (unsigned i = 0; i < cExtents; i++)
2993 {
2994 pExtents[i].pFile = NULL;
2995 pExtents[i].pszBasename = NULL;
2996 pExtents[i].pszFullname = NULL;
2997 pExtents[i].pGD = NULL;
2998 pExtents[i].pRGD = NULL;
2999 pExtents[i].pDescData = NULL;
3000 pExtents[i].uVersion = 1;
3001 pExtents[i].uCompression = VMDK_COMPRESSION_NONE;
3002 pExtents[i].uExtent = i;
3003 pExtents[i].pImage = pImage;
3004 }
3005 pImage->pExtents = pExtents;
3006 pImage->cExtents = cExtents;
3007 }
3008 else
3009 rc = VERR_NO_MEMORY;
3010
3011 return rc;
3012}
3013
3014/**
3015 * Internal: Open an image, constructing all necessary data structures.
3016 */
3017static int vmdkOpenImage(PVMDKIMAGE pImage, unsigned uOpenFlags)
3018{
3019 int rc;
3020 uint32_t u32Magic;
3021 PVMDKFILE pFile;
3022 PVMDKEXTENT pExtent;
3023
3024 pImage->uOpenFlags = uOpenFlags;
3025
3026 pImage->pIfError = VDIfErrorGet(pImage->pVDIfsDisk);
3027 pImage->pIfIo = VDIfIoIntGet(pImage->pVDIfsImage);
3028 AssertPtrReturn(pImage->pIfIo, VERR_INVALID_PARAMETER);
3029
3030 /*
3031 * Open the image.
3032 * We don't have to check for asynchronous access because
3033 * we only support raw access and the opened file is a description
3034 * file were no data is stored.
3035 */
3036
3037 rc = vmdkFileOpen(pImage, &pFile, pImage->pszFilename,
3038 VDOpenFlagsToFileOpenFlags(uOpenFlags, false /* fCreate */));
3039 if (RT_FAILURE(rc))
3040 {
3041 /* Do NOT signal an appropriate error here, as the VD layer has the
3042 * choice of retrying the open if it failed. */
3043 goto out;
3044 }
3045 pImage->pFile = pFile;
3046
3047 /* Read magic (if present). */
3048 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pFile->pStorage, 0,
3049 &u32Magic, sizeof(u32Magic));
3050 if (RT_FAILURE(rc))
3051 {
3052 vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error reading the magic number in '%s'"), pImage->pszFilename);
3053 rc = VERR_VD_VMDK_INVALID_HEADER;
3054 goto out;
3055 }
3056
3057 /* Handle the file according to its magic number. */
3058 if (RT_LE2H_U32(u32Magic) == VMDK_SPARSE_MAGICNUMBER)
3059 {
3060 /* It's a hosted single-extent image. */
3061 rc = vmdkCreateExtents(pImage, 1);
3062 if (RT_FAILURE(rc))
3063 goto out;
3064 /* The opened file is passed to the extent. No separate descriptor
3065 * file, so no need to keep anything open for the image. */
3066 pExtent = &pImage->pExtents[0];
3067 pExtent->pFile = pFile;
3068 pImage->pFile = NULL;
3069 pExtent->pszFullname = RTPathAbsDup(pImage->pszFilename);
3070 if (!pExtent->pszFullname)
3071 {
3072 rc = VERR_NO_MEMORY;
3073 goto out;
3074 }
3075 rc = vmdkReadBinaryMetaExtent(pImage, pExtent, true /* fMagicAlreadyRead */);
3076 if (RT_FAILURE(rc))
3077 goto out;
3078
3079 /* As we're dealing with a monolithic image here, there must
3080 * be a descriptor embedded in the image file. */
3081 if (!pExtent->uDescriptorSector || !pExtent->cDescriptorSectors)
3082 {
3083 rc = vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: monolithic image without descriptor in '%s'"), pImage->pszFilename);
3084 goto out;
3085 }
3086 /* HACK: extend the descriptor if it is unusually small and it fits in
3087 * the unused space after the image header. Allows opening VMDK files
3088 * with extremely small descriptor in read/write mode.
3089 *
3090 * The previous version introduced a possible regression for VMDK stream
3091 * optimized images from VMware which tend to have only a single sector sized
3092 * descriptor. Increasing the descriptor size resulted in adding the various uuid
3093 * entries required to make it work with VBox but for stream optimized images
3094 * the updated binary header wasn't written to the disk creating a mismatch
3095 * between advertised and real descriptor size.
3096 *
3097 * The descriptor size will be increased even if opened readonly now if there
3098 * enough room but the new value will not be written back to the image.
3099 */
3100 if ( pExtent->cDescriptorSectors < 3
3101 && (int64_t)pExtent->uSectorGD - pExtent->uDescriptorSector >= 4
3102 && (!pExtent->uSectorRGD || (int64_t)pExtent->uSectorRGD - pExtent->uDescriptorSector >= 4))
3103 {
3104 uint64_t cDescriptorSectorsOld = pExtent->cDescriptorSectors;
3105
3106 pExtent->cDescriptorSectors = 4;
3107 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
3108 {
3109 /*
3110 * Update the on disk number now to make sure we don't introduce inconsistencies
3111 * in case of stream optimized images from VMware where the descriptor is just
3112 * one sector big (the binary header is not written to disk for complete
3113 * stream optimized images in vmdkFlushImage()).
3114 */
3115 uint64_t u64DescSizeNew = RT_H2LE_U64(pExtent->cDescriptorSectors);
3116 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pFile->pStorage, RT_OFFSETOF(SparseExtentHeader, descriptorSize),
3117 &u64DescSizeNew, sizeof(u64DescSizeNew));
3118 if (RT_FAILURE(rc))
3119 {
3120 LogFlowFunc(("Increasing the descriptor size failed with %Rrc\n", rc));
3121 /* Restore the old size and carry on. */
3122 pExtent->cDescriptorSectors = cDescriptorSectorsOld;
3123 }
3124 }
3125 }
3126 /* Read the descriptor from the extent. */
3127 pExtent->pDescData = (char *)RTMemAllocZ(VMDK_SECTOR2BYTE(pExtent->cDescriptorSectors));
3128 if (!pExtent->pDescData)
3129 {
3130 rc = VERR_NO_MEMORY;
3131 goto out;
3132 }
3133 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pExtent->pFile->pStorage,
3134 VMDK_SECTOR2BYTE(pExtent->uDescriptorSector),
3135 pExtent->pDescData,
3136 VMDK_SECTOR2BYTE(pExtent->cDescriptorSectors));
3137 AssertRC(rc);
3138 if (RT_FAILURE(rc))
3139 {
3140 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: read error for descriptor in '%s'"), pExtent->pszFullname);
3141 goto out;
3142 }
3143
3144 rc = vmdkParseDescriptor(pImage, pExtent->pDescData,
3145 VMDK_SECTOR2BYTE(pExtent->cDescriptorSectors));
3146 if (RT_FAILURE(rc))
3147 goto out;
3148
3149 if ( pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED
3150 && uOpenFlags & VD_OPEN_FLAGS_ASYNC_IO)
3151 {
3152 rc = VERR_NOT_SUPPORTED;
3153 goto out;
3154 }
3155
3156 rc = vmdkReadMetaExtent(pImage, pExtent);
3157 if (RT_FAILURE(rc))
3158 goto out;
3159
3160 /* Mark the extent as unclean if opened in read-write mode. */
3161 if ( !(uOpenFlags & VD_OPEN_FLAGS_READONLY)
3162 && !(pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED))
3163 {
3164 pExtent->fUncleanShutdown = true;
3165 pExtent->fMetaDirty = true;
3166 }
3167 }
3168 else
3169 {
3170 /* Allocate at least 10K, and make sure that there is 5K free space
3171 * in case new entries need to be added to the descriptor. Never
3172 * allocate more than 128K, because that's no valid descriptor file
3173 * and will result in the correct "truncated read" error handling. */
3174 uint64_t cbFileSize;
3175 rc = vdIfIoIntFileGetSize(pImage->pIfIo, pFile->pStorage, &cbFileSize);
3176 if (RT_FAILURE(rc))
3177 goto out;
3178
3179 /* If the descriptor file is shorter than 50 bytes it can't be valid. */
3180 if (cbFileSize < 50)
3181 {
3182 rc = vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: descriptor in '%s' is too short"), pImage->pszFilename);
3183 goto out;
3184 }
3185
3186 uint64_t cbSize = cbFileSize;
3187 if (cbSize % VMDK_SECTOR2BYTE(10))
3188 cbSize += VMDK_SECTOR2BYTE(20) - cbSize % VMDK_SECTOR2BYTE(10);
3189 else
3190 cbSize += VMDK_SECTOR2BYTE(10);
3191 cbSize = RT_MIN(cbSize, _128K);
3192 pImage->cbDescAlloc = RT_MAX(VMDK_SECTOR2BYTE(20), cbSize);
3193 pImage->pDescData = (char *)RTMemAllocZ(pImage->cbDescAlloc);
3194 if (!pImage->pDescData)
3195 {
3196 rc = VERR_NO_MEMORY;
3197 goto out;
3198 }
3199
3200 /* Don't reread the place where the magic would live in a sparse
3201 * image if it's a descriptor based one. */
3202 memcpy(pImage->pDescData, &u32Magic, sizeof(u32Magic));
3203 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pFile->pStorage, sizeof(u32Magic),
3204 pImage->pDescData + sizeof(u32Magic),
3205 RT_MIN(pImage->cbDescAlloc - sizeof(u32Magic),
3206 cbFileSize - sizeof(u32Magic)));
3207 if (RT_FAILURE(rc))
3208 {
3209 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: read error for descriptor in '%s'"), pImage->pszFilename);
3210 goto out;
3211 }
3212
3213#if 0 /** @todo Revisit */
3214 cbRead += sizeof(u32Magic);
3215 if (cbRead == pImage->cbDescAlloc)
3216 {
3217 /* Likely the read is truncated. Better fail a bit too early
3218 * (normally the descriptor is much smaller than our buffer). */
3219 rc = vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: cannot read descriptor in '%s'"), pImage->pszFilename);
3220 goto out;
3221 }
3222#endif
3223
3224 rc = vmdkParseDescriptor(pImage, pImage->pDescData,
3225 pImage->cbDescAlloc);
3226 if (RT_FAILURE(rc))
3227 goto out;
3228
3229 for (unsigned i = 0; i < pImage->cExtents; i++)
3230 {
3231 pExtent = &pImage->pExtents[i];
3232
3233 if (pExtent->pszBasename)
3234 {
3235 /* Hack to figure out whether the specified name in the
3236 * extent descriptor is absolute. Doesn't always work, but
3237 * should be good enough for now. */
3238 char *pszFullname;
3239 /** @todo implement proper path absolute check. */
3240 if (pExtent->pszBasename[0] == RTPATH_SLASH)
3241 {
3242 pszFullname = RTStrDup(pExtent->pszBasename);
3243 if (!pszFullname)
3244 {
3245 rc = VERR_NO_MEMORY;
3246 goto out;
3247 }
3248 }
3249 else
3250 {
3251 char *pszDirname = RTStrDup(pImage->pszFilename);
3252 if (!pszDirname)
3253 {
3254 rc = VERR_NO_MEMORY;
3255 goto out;
3256 }
3257 RTPathStripFilename(pszDirname);
3258 pszFullname = RTPathJoinA(pszDirname, pExtent->pszBasename);
3259 RTStrFree(pszDirname);
3260 if (!pszFullname)
3261 {
3262 rc = VERR_NO_STR_MEMORY;
3263 goto out;
3264 }
3265 }
3266 pExtent->pszFullname = pszFullname;
3267 }
3268 else
3269 pExtent->pszFullname = NULL;
3270
3271 switch (pExtent->enmType)
3272 {
3273 case VMDKETYPE_HOSTED_SPARSE:
3274 rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszFullname,
3275 VDOpenFlagsToFileOpenFlags(uOpenFlags | ((pExtent->enmAccess == VMDKACCESS_READONLY) ? VD_OPEN_FLAGS_READONLY : 0),
3276 false /* fCreate */));
3277 if (RT_FAILURE(rc))
3278 {
3279 /* Do NOT signal an appropriate error here, as the VD
3280 * layer has the choice of retrying the open if it
3281 * failed. */
3282 goto out;
3283 }
3284 rc = vmdkReadBinaryMetaExtent(pImage, pExtent,
3285 false /* fMagicAlreadyRead */);
3286 if (RT_FAILURE(rc))
3287 goto out;
3288 rc = vmdkReadMetaExtent(pImage, pExtent);
3289 if (RT_FAILURE(rc))
3290 goto out;
3291
3292 /* Mark extent as unclean if opened in read-write mode. */
3293 if (!(uOpenFlags & VD_OPEN_FLAGS_READONLY))
3294 {
3295 pExtent->fUncleanShutdown = true;
3296 pExtent->fMetaDirty = true;
3297 }
3298 break;
3299 case VMDKETYPE_VMFS:
3300 case VMDKETYPE_FLAT:
3301 rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszFullname,
3302 VDOpenFlagsToFileOpenFlags(uOpenFlags | ((pExtent->enmAccess == VMDKACCESS_READONLY) ? VD_OPEN_FLAGS_READONLY : 0),
3303 false /* fCreate */));
3304 if (RT_FAILURE(rc))
3305 {
3306 /* Do NOT signal an appropriate error here, as the VD
3307 * layer has the choice of retrying the open if it
3308 * failed. */
3309 goto out;
3310 }
3311 break;
3312 case VMDKETYPE_ZERO:
3313 /* Nothing to do. */
3314 break;
3315 default:
3316 AssertMsgFailed(("unknown vmdk extent type %d\n", pExtent->enmType));
3317 }
3318 }
3319 }
3320
3321 /* Make sure this is not reached accidentally with an error status. */
3322 AssertRC(rc);
3323
3324 /* Determine PCHS geometry if not set. */
3325 if (pImage->PCHSGeometry.cCylinders == 0)
3326 {
3327 uint64_t cCylinders = VMDK_BYTE2SECTOR(pImage->cbSize)
3328 / pImage->PCHSGeometry.cHeads
3329 / pImage->PCHSGeometry.cSectors;
3330 pImage->PCHSGeometry.cCylinders = (unsigned)RT_MIN(cCylinders, 16383);
3331 if ( !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
3332 && !(pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED))
3333 {
3334 rc = vmdkDescSetPCHSGeometry(pImage, &pImage->PCHSGeometry);
3335 AssertRC(rc);
3336 }
3337 }
3338
3339 /* Update the image metadata now in case has changed. */
3340 rc = vmdkFlushImage(pImage, NULL);
3341 if (RT_FAILURE(rc))
3342 goto out;
3343
3344 /* Figure out a few per-image constants from the extents. */
3345 pImage->cbSize = 0;
3346 for (unsigned i = 0; i < pImage->cExtents; i++)
3347 {
3348 pExtent = &pImage->pExtents[i];
3349 if ( pExtent->enmType == VMDKETYPE_HOSTED_SPARSE
3350#ifdef VBOX_WITH_VMDK_ESX
3351 || pExtent->enmType == VMDKETYPE_ESX_SPARSE
3352#endif /* VBOX_WITH_VMDK_ESX */
3353 )
3354 {
3355 /* Here used to be a check whether the nominal size of an extent
3356 * is a multiple of the grain size. The spec says that this is
3357 * always the case, but unfortunately some files out there in the
3358 * wild violate the spec (e.g. ReactOS 0.3.1). */
3359 }
3360 pImage->cbSize += VMDK_SECTOR2BYTE(pExtent->cNominalSectors);
3361 }
3362
3363 for (unsigned i = 0; i < pImage->cExtents; i++)
3364 {
3365 pExtent = &pImage->pExtents[i];
3366 if ( pImage->pExtents[i].enmType == VMDKETYPE_FLAT
3367 || pImage->pExtents[i].enmType == VMDKETYPE_ZERO)
3368 {
3369 pImage->uImageFlags |= VD_IMAGE_FLAGS_FIXED;
3370 break;
3371 }
3372 }
3373
3374 if ( !(pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
3375 || !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
3376 || !(pImage->uOpenFlags & VD_OPEN_FLAGS_SEQUENTIAL))
3377 rc = vmdkAllocateGrainTableCache(pImage);
3378
3379out:
3380 if (RT_FAILURE(rc))
3381 vmdkFreeImage(pImage, false);
3382 return rc;
3383}
3384
3385/**
3386 * Internal: create VMDK images for raw disk/partition access.
3387 */
3388static int vmdkCreateRawImage(PVMDKIMAGE pImage, const PVBOXHDDRAW pRaw,
3389 uint64_t cbSize)
3390{
3391 int rc = VINF_SUCCESS;
3392 PVMDKEXTENT pExtent;
3393
3394 if (pRaw->uFlags & VBOXHDDRAW_DISK)
3395 {
3396 /* Full raw disk access. This requires setting up a descriptor
3397 * file and open the (flat) raw disk. */
3398 rc = vmdkCreateExtents(pImage, 1);
3399 if (RT_FAILURE(rc))
3400 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not create new extent list in '%s'"), pImage->pszFilename);
3401 pExtent = &pImage->pExtents[0];
3402 /* Create raw disk descriptor file. */
3403 rc = vmdkFileOpen(pImage, &pImage->pFile, pImage->pszFilename,
3404 VDOpenFlagsToFileOpenFlags(pImage->uOpenFlags,
3405 true /* fCreate */));
3406 if (RT_FAILURE(rc))
3407 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not create new file '%s'"), pImage->pszFilename);
3408
3409 /* Set up basename for extent description. Cannot use StrDup. */
3410 size_t cbBasename = strlen(pRaw->pszRawDisk) + 1;
3411 char *pszBasename = (char *)RTMemTmpAlloc(cbBasename);
3412 if (!pszBasename)
3413 return VERR_NO_MEMORY;
3414 memcpy(pszBasename, pRaw->pszRawDisk, cbBasename);
3415 pExtent->pszBasename = pszBasename;
3416 /* For raw disks the full name is identical to the base name. */
3417 pExtent->pszFullname = RTStrDup(pszBasename);
3418 if (!pExtent->pszFullname)
3419 return VERR_NO_MEMORY;
3420 pExtent->enmType = VMDKETYPE_FLAT;
3421 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(cbSize);
3422 pExtent->uSectorOffset = 0;
3423 pExtent->enmAccess = (pRaw->uFlags & VBOXHDDRAW_READONLY) ? VMDKACCESS_READONLY : VMDKACCESS_READWRITE;
3424 pExtent->fMetaDirty = false;
3425
3426 /* Open flat image, the raw disk. */
3427 rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszFullname,
3428 VDOpenFlagsToFileOpenFlags(pImage->uOpenFlags | ((pExtent->enmAccess == VMDKACCESS_READONLY) ? VD_OPEN_FLAGS_READONLY : 0),
3429 false /* fCreate */));
3430 if (RT_FAILURE(rc))
3431 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not open raw disk file '%s'"), pExtent->pszFullname);
3432 }
3433 else
3434 {
3435 /* Raw partition access. This requires setting up a descriptor
3436 * file, write the partition information to a flat extent and
3437 * open all the (flat) raw disk partitions. */
3438
3439 /* First pass over the partition data areas to determine how many
3440 * extents we need. One data area can require up to 2 extents, as
3441 * it might be necessary to skip over unpartitioned space. */
3442 unsigned cExtents = 0;
3443 uint64_t uStart = 0;
3444 for (unsigned i = 0; i < pRaw->cPartDescs; i++)
3445 {
3446 PVBOXHDDRAWPARTDESC pPart = &pRaw->pPartDescs[i];
3447 if (uStart > pPart->uStart)
3448 return vdIfError(pImage->pIfError, VERR_INVALID_PARAMETER, RT_SRC_POS, N_("VMDK: incorrect partition data area ordering set up by the caller in '%s'"), pImage->pszFilename);
3449
3450 if (uStart < pPart->uStart)
3451 cExtents++;
3452 uStart = pPart->uStart + pPart->cbData;
3453 cExtents++;
3454 }
3455 /* Another extent for filling up the rest of the image. */
3456 if (uStart != cbSize)
3457 cExtents++;
3458
3459 rc = vmdkCreateExtents(pImage, cExtents);
3460 if (RT_FAILURE(rc))
3461 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not create new extent list in '%s'"), pImage->pszFilename);
3462
3463 /* Create raw partition descriptor file. */
3464 rc = vmdkFileOpen(pImage, &pImage->pFile, pImage->pszFilename,
3465 VDOpenFlagsToFileOpenFlags(pImage->uOpenFlags,
3466 true /* fCreate */));
3467 if (RT_FAILURE(rc))
3468 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not create new file '%s'"), pImage->pszFilename);
3469
3470 /* Create base filename for the partition table extent. */
3471 /** @todo remove fixed buffer without creating memory leaks. */
3472 char pszPartition[1024];
3473 const char *pszBase = RTPathFilename(pImage->pszFilename);
3474 const char *pszSuff = RTPathSuffix(pszBase);
3475 if (pszSuff == NULL)
3476 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: invalid filename '%s'"), pImage->pszFilename);
3477 char *pszBaseBase = RTStrDup(pszBase);
3478 if (!pszBaseBase)
3479 return VERR_NO_MEMORY;
3480 RTPathStripSuffix(pszBaseBase);
3481 RTStrPrintf(pszPartition, sizeof(pszPartition), "%s-pt%s",
3482 pszBaseBase, pszSuff);
3483 RTStrFree(pszBaseBase);
3484
3485 /* Second pass over the partitions, now define all extents. */
3486 uint64_t uPartOffset = 0;
3487 cExtents = 0;
3488 uStart = 0;
3489 for (unsigned i = 0; i < pRaw->cPartDescs; i++)
3490 {
3491 PVBOXHDDRAWPARTDESC pPart = &pRaw->pPartDescs[i];
3492 pExtent = &pImage->pExtents[cExtents++];
3493
3494 if (uStart < pPart->uStart)
3495 {
3496 pExtent->pszBasename = NULL;
3497 pExtent->pszFullname = NULL;
3498 pExtent->enmType = VMDKETYPE_ZERO;
3499 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(pPart->uStart - uStart);
3500 pExtent->uSectorOffset = 0;
3501 pExtent->enmAccess = VMDKACCESS_READWRITE;
3502 pExtent->fMetaDirty = false;
3503 /* go to next extent */
3504 pExtent = &pImage->pExtents[cExtents++];
3505 }
3506 uStart = pPart->uStart + pPart->cbData;
3507
3508 if (pPart->pvPartitionData)
3509 {
3510 /* Set up basename for extent description. Can't use StrDup. */
3511 size_t cbBasename = strlen(pszPartition) + 1;
3512 char *pszBasename = (char *)RTMemTmpAlloc(cbBasename);
3513 if (!pszBasename)
3514 return VERR_NO_MEMORY;
3515 memcpy(pszBasename, pszPartition, cbBasename);
3516 pExtent->pszBasename = pszBasename;
3517
3518 /* Set up full name for partition extent. */
3519 char *pszDirname = RTStrDup(pImage->pszFilename);
3520 if (!pszDirname)
3521 return VERR_NO_STR_MEMORY;
3522 RTPathStripFilename(pszDirname);
3523 char *pszFullname = RTPathJoinA(pszDirname, pExtent->pszBasename);
3524 RTStrFree(pszDirname);
3525 if (!pszFullname)
3526 return VERR_NO_STR_MEMORY;
3527 pExtent->pszFullname = pszFullname;
3528 pExtent->enmType = VMDKETYPE_FLAT;
3529 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(pPart->cbData);
3530 pExtent->uSectorOffset = uPartOffset;
3531 pExtent->enmAccess = VMDKACCESS_READWRITE;
3532 pExtent->fMetaDirty = false;
3533
3534 /* Create partition table flat image. */
3535 rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszFullname,
3536 VDOpenFlagsToFileOpenFlags(pImage->uOpenFlags | ((pExtent->enmAccess == VMDKACCESS_READONLY) ? VD_OPEN_FLAGS_READONLY : 0),
3537 true /* fCreate */));
3538 if (RT_FAILURE(rc))
3539 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not create new partition data file '%s'"), pExtent->pszFullname);
3540 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pExtent->pFile->pStorage,
3541 VMDK_SECTOR2BYTE(uPartOffset),
3542 pPart->pvPartitionData,
3543 pPart->cbData);
3544 if (RT_FAILURE(rc))
3545 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not write partition data to '%s'"), pExtent->pszFullname);
3546 uPartOffset += VMDK_BYTE2SECTOR(pPart->cbData);
3547 }
3548 else
3549 {
3550 if (pPart->pszRawDevice)
3551 {
3552 /* Set up basename for extent descr. Can't use StrDup. */
3553 size_t cbBasename = strlen(pPart->pszRawDevice) + 1;
3554 char *pszBasename = (char *)RTMemTmpAlloc(cbBasename);
3555 if (!pszBasename)
3556 return VERR_NO_MEMORY;
3557 memcpy(pszBasename, pPart->pszRawDevice, cbBasename);
3558 pExtent->pszBasename = pszBasename;
3559 /* For raw disks full name is identical to base name. */
3560 pExtent->pszFullname = RTStrDup(pszBasename);
3561 if (!pExtent->pszFullname)
3562 return VERR_NO_MEMORY;
3563 pExtent->enmType = VMDKETYPE_FLAT;
3564 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(pPart->cbData);
3565 pExtent->uSectorOffset = VMDK_BYTE2SECTOR(pPart->uStartOffset);
3566 pExtent->enmAccess = (pPart->uFlags & VBOXHDDRAW_READONLY) ? VMDKACCESS_READONLY : VMDKACCESS_READWRITE;
3567 pExtent->fMetaDirty = false;
3568
3569 /* Open flat image, the raw partition. */
3570 rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszFullname,
3571 VDOpenFlagsToFileOpenFlags(pImage->uOpenFlags | ((pExtent->enmAccess == VMDKACCESS_READONLY) ? VD_OPEN_FLAGS_READONLY : 0),
3572 false /* fCreate */));
3573 if (RT_FAILURE(rc))
3574 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not open raw partition file '%s'"), pExtent->pszFullname);
3575 }
3576 else
3577 {
3578 pExtent->pszBasename = NULL;
3579 pExtent->pszFullname = NULL;
3580 pExtent->enmType = VMDKETYPE_ZERO;
3581 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(pPart->cbData);
3582 pExtent->uSectorOffset = 0;
3583 pExtent->enmAccess = VMDKACCESS_READWRITE;
3584 pExtent->fMetaDirty = false;
3585 }
3586 }
3587 }
3588 /* Another extent for filling up the rest of the image. */
3589 if (uStart != cbSize)
3590 {
3591 pExtent = &pImage->pExtents[cExtents++];
3592 pExtent->pszBasename = NULL;
3593 pExtent->pszFullname = NULL;
3594 pExtent->enmType = VMDKETYPE_ZERO;
3595 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(cbSize - uStart);
3596 pExtent->uSectorOffset = 0;
3597 pExtent->enmAccess = VMDKACCESS_READWRITE;
3598 pExtent->fMetaDirty = false;
3599 }
3600 }
3601
3602 rc = vmdkDescBaseSetStr(pImage, &pImage->Descriptor, "createType",
3603 (pRaw->uFlags & VBOXHDDRAW_DISK) ?
3604 "fullDevice" : "partitionedDevice");
3605 if (RT_FAILURE(rc))
3606 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not set the image type in '%s'"), pImage->pszFilename);
3607 return rc;
3608}
3609
3610/**
3611 * Internal: create a regular (i.e. file-backed) VMDK image.
3612 */
3613static int vmdkCreateRegularImage(PVMDKIMAGE pImage, uint64_t cbSize,
3614 unsigned uImageFlags,
3615 PFNVDPROGRESS pfnProgress, void *pvUser,
3616 unsigned uPercentStart, unsigned uPercentSpan)
3617{
3618 int rc = VINF_SUCCESS;
3619 unsigned cExtents = 1;
3620 uint64_t cbOffset = 0;
3621 uint64_t cbRemaining = cbSize;
3622
3623 if (uImageFlags & VD_VMDK_IMAGE_FLAGS_SPLIT_2G)
3624 {
3625 cExtents = cbSize / VMDK_2G_SPLIT_SIZE;
3626 /* Do proper extent computation: need one smaller extent if the total
3627 * size isn't evenly divisible by the split size. */
3628 if (cbSize % VMDK_2G_SPLIT_SIZE)
3629 cExtents++;
3630 }
3631 rc = vmdkCreateExtents(pImage, cExtents);
3632 if (RT_FAILURE(rc))
3633 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not create new extent list in '%s'"), pImage->pszFilename);
3634
3635 /* Basename strings needed for constructing the extent names. */
3636 char *pszBasenameSubstr = RTPathFilename(pImage->pszFilename);
3637 AssertPtr(pszBasenameSubstr);
3638 size_t cbBasenameSubstr = strlen(pszBasenameSubstr) + 1;
3639
3640 /* Create separate descriptor file if necessary. */
3641 if (cExtents != 1 || (uImageFlags & VD_IMAGE_FLAGS_FIXED))
3642 {
3643 rc = vmdkFileOpen(pImage, &pImage->pFile, pImage->pszFilename,
3644 VDOpenFlagsToFileOpenFlags(pImage->uOpenFlags,
3645 true /* fCreate */));
3646 if (RT_FAILURE(rc))
3647 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not create new sparse descriptor file '%s'"), pImage->pszFilename);
3648 }
3649 else
3650 pImage->pFile = NULL;
3651
3652 /* Set up all extents. */
3653 for (unsigned i = 0; i < cExtents; i++)
3654 {
3655 PVMDKEXTENT pExtent = &pImage->pExtents[i];
3656 uint64_t cbExtent = cbRemaining;
3657
3658 /* Set up fullname/basename for extent description. Cannot use StrDup
3659 * for basename, as it is not guaranteed that the memory can be freed
3660 * with RTMemTmpFree, which must be used as in other code paths
3661 * StrDup is not usable. */
3662 if (cExtents == 1 && !(uImageFlags & VD_IMAGE_FLAGS_FIXED))
3663 {
3664 char *pszBasename = (char *)RTMemTmpAlloc(cbBasenameSubstr);
3665 if (!pszBasename)
3666 return VERR_NO_MEMORY;
3667 memcpy(pszBasename, pszBasenameSubstr, cbBasenameSubstr);
3668 pExtent->pszBasename = pszBasename;
3669 }
3670 else
3671 {
3672 char *pszBasenameSuff = RTPathSuffix(pszBasenameSubstr);
3673 char *pszBasenameBase = RTStrDup(pszBasenameSubstr);
3674 RTPathStripSuffix(pszBasenameBase);
3675 char *pszTmp;
3676 size_t cbTmp;
3677 if (uImageFlags & VD_IMAGE_FLAGS_FIXED)
3678 {
3679 if (cExtents == 1)
3680 RTStrAPrintf(&pszTmp, "%s-flat%s", pszBasenameBase,
3681 pszBasenameSuff);
3682 else
3683 RTStrAPrintf(&pszTmp, "%s-f%03d%s", pszBasenameBase,
3684 i+1, pszBasenameSuff);
3685 }
3686 else
3687 RTStrAPrintf(&pszTmp, "%s-s%03d%s", pszBasenameBase, i+1,
3688 pszBasenameSuff);
3689 RTStrFree(pszBasenameBase);
3690 if (!pszTmp)
3691 return VERR_NO_STR_MEMORY;
3692 cbTmp = strlen(pszTmp) + 1;
3693 char *pszBasename = (char *)RTMemTmpAlloc(cbTmp);
3694 if (!pszBasename)
3695 {
3696 RTStrFree(pszTmp);
3697 return VERR_NO_MEMORY;
3698 }
3699 memcpy(pszBasename, pszTmp, cbTmp);
3700 RTStrFree(pszTmp);
3701 pExtent->pszBasename = pszBasename;
3702 if (uImageFlags & VD_VMDK_IMAGE_FLAGS_SPLIT_2G)
3703 cbExtent = RT_MIN(cbRemaining, VMDK_2G_SPLIT_SIZE);
3704 }
3705 char *pszBasedirectory = RTStrDup(pImage->pszFilename);
3706 if (!pszBasedirectory)
3707 return VERR_NO_STR_MEMORY;
3708 RTPathStripFilename(pszBasedirectory);
3709 char *pszFullname = RTPathJoinA(pszBasedirectory, pExtent->pszBasename);
3710 RTStrFree(pszBasedirectory);
3711 if (!pszFullname)
3712 return VERR_NO_STR_MEMORY;
3713 pExtent->pszFullname = pszFullname;
3714
3715 /* Create file for extent. */
3716 rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszFullname,
3717 VDOpenFlagsToFileOpenFlags(pImage->uOpenFlags,
3718 true /* fCreate */));
3719 if (RT_FAILURE(rc))
3720 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not create new file '%s'"), pExtent->pszFullname);
3721 if (uImageFlags & VD_IMAGE_FLAGS_FIXED)
3722 {
3723 rc = vdIfIoIntFileSetAllocationSize(pImage->pIfIo, pExtent->pFile->pStorage, cbExtent,
3724 0 /* fFlags */, pfnProgress, pvUser, uPercentStart + cbOffset * uPercentSpan / cbSize,
3725 cbExtent * uPercentSpan / cbSize);
3726 if (RT_FAILURE(rc))
3727 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not set size of new file '%s'"), pExtent->pszFullname);
3728 }
3729
3730 /* Place descriptor file information (where integrated). */
3731 if (cExtents == 1 && !(uImageFlags & VD_IMAGE_FLAGS_FIXED))
3732 {
3733 pExtent->uDescriptorSector = 1;
3734 pExtent->cDescriptorSectors = VMDK_BYTE2SECTOR(pImage->cbDescAlloc);
3735 /* The descriptor is part of the (only) extent. */
3736 pExtent->pDescData = pImage->pDescData;
3737 pImage->pDescData = NULL;
3738 }
3739
3740 if (!(uImageFlags & VD_IMAGE_FLAGS_FIXED))
3741 {
3742 uint64_t cSectorsPerGDE, cSectorsPerGD;
3743 pExtent->enmType = VMDKETYPE_HOSTED_SPARSE;
3744 pExtent->cSectors = VMDK_BYTE2SECTOR(RT_ALIGN_64(cbExtent, _64K));
3745 pExtent->cSectorsPerGrain = VMDK_BYTE2SECTOR(_64K);
3746 pExtent->cGTEntries = 512;
3747 cSectorsPerGDE = pExtent->cGTEntries * pExtent->cSectorsPerGrain;
3748 pExtent->cSectorsPerGDE = cSectorsPerGDE;
3749 pExtent->cGDEntries = (pExtent->cSectors + cSectorsPerGDE - 1) / cSectorsPerGDE;
3750 cSectorsPerGD = (pExtent->cGDEntries + (512 / sizeof(uint32_t) - 1)) / (512 / sizeof(uint32_t));
3751 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
3752 {
3753 /* The spec says version is 1 for all VMDKs, but the vast
3754 * majority of streamOptimized VMDKs actually contain
3755 * version 3 - so go with the majority. Both are accepted. */
3756 pExtent->uVersion = 3;
3757 pExtent->uCompression = VMDK_COMPRESSION_DEFLATE;
3758 }
3759 }
3760 else
3761 {
3762 if (uImageFlags & VD_VMDK_IMAGE_FLAGS_ESX)
3763 pExtent->enmType = VMDKETYPE_VMFS;
3764 else
3765 pExtent->enmType = VMDKETYPE_FLAT;
3766 }
3767
3768 pExtent->enmAccess = VMDKACCESS_READWRITE;
3769 pExtent->fUncleanShutdown = true;
3770 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(cbExtent);
3771 pExtent->uSectorOffset = 0;
3772 pExtent->fMetaDirty = true;
3773
3774 if (!(uImageFlags & VD_IMAGE_FLAGS_FIXED))
3775 {
3776 /* fPreAlloc should never be false because VMware can't use such images. */
3777 rc = vmdkCreateGrainDirectory(pImage, pExtent,
3778 RT_MAX( pExtent->uDescriptorSector
3779 + pExtent->cDescriptorSectors,
3780 1),
3781 true /* fPreAlloc */);
3782 if (RT_FAILURE(rc))
3783 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not create new grain directory in '%s'"), pExtent->pszFullname);
3784 }
3785
3786 cbOffset += cbExtent;
3787
3788 if (RT_SUCCESS(rc) && pfnProgress)
3789 pfnProgress(pvUser, uPercentStart + cbOffset * uPercentSpan / cbSize);
3790
3791 cbRemaining -= cbExtent;
3792 }
3793
3794 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_ESX)
3795 {
3796 /* VirtualBox doesn't care, but VMWare ESX freaks out if the wrong
3797 * controller type is set in an image. */
3798 rc = vmdkDescDDBSetStr(pImage, &pImage->Descriptor, "ddb.adapterType", "lsilogic");
3799 if (RT_FAILURE(rc))
3800 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not set controller type to lsilogic in '%s'"), pImage->pszFilename);
3801 }
3802
3803 const char *pszDescType = NULL;
3804 if (uImageFlags & VD_IMAGE_FLAGS_FIXED)
3805 {
3806 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_ESX)
3807 pszDescType = "vmfs";
3808 else
3809 pszDescType = (cExtents == 1)
3810 ? "monolithicFlat" : "twoGbMaxExtentFlat";
3811 }
3812 else
3813 {
3814 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
3815 pszDescType = "streamOptimized";
3816 else
3817 {
3818 pszDescType = (cExtents == 1)
3819 ? "monolithicSparse" : "twoGbMaxExtentSparse";
3820 }
3821 }
3822 rc = vmdkDescBaseSetStr(pImage, &pImage->Descriptor, "createType",
3823 pszDescType);
3824 if (RT_FAILURE(rc))
3825 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not set the image type in '%s'"), pImage->pszFilename);
3826 return rc;
3827}
3828
3829/**
3830 * Internal: Create a real stream optimized VMDK using only linear writes.
3831 */
3832static int vmdkCreateStreamImage(PVMDKIMAGE pImage, uint64_t cbSize,
3833 unsigned uImageFlags,
3834 PFNVDPROGRESS pfnProgress, void *pvUser,
3835 unsigned uPercentStart, unsigned uPercentSpan)
3836{
3837 RT_NOREF5(uImageFlags, pfnProgress, pvUser, uPercentStart, uPercentSpan);
3838 int rc;
3839
3840 rc = vmdkCreateExtents(pImage, 1);
3841 if (RT_FAILURE(rc))
3842 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not create new extent list in '%s'"), pImage->pszFilename);
3843
3844 /* Basename strings needed for constructing the extent names. */
3845 const char *pszBasenameSubstr = RTPathFilename(pImage->pszFilename);
3846 AssertPtr(pszBasenameSubstr);
3847 size_t cbBasenameSubstr = strlen(pszBasenameSubstr) + 1;
3848
3849 /* No separate descriptor file. */
3850 pImage->pFile = NULL;
3851
3852 /* Set up all extents. */
3853 PVMDKEXTENT pExtent = &pImage->pExtents[0];
3854
3855 /* Set up fullname/basename for extent description. Cannot use StrDup
3856 * for basename, as it is not guaranteed that the memory can be freed
3857 * with RTMemTmpFree, which must be used as in other code paths
3858 * StrDup is not usable. */
3859 char *pszBasename = (char *)RTMemTmpAlloc(cbBasenameSubstr);
3860 if (!pszBasename)
3861 return VERR_NO_MEMORY;
3862 memcpy(pszBasename, pszBasenameSubstr, cbBasenameSubstr);
3863 pExtent->pszBasename = pszBasename;
3864
3865 char *pszBasedirectory = RTStrDup(pImage->pszFilename);
3866 RTPathStripFilename(pszBasedirectory);
3867 char *pszFullname = RTPathJoinA(pszBasedirectory, pExtent->pszBasename);
3868 RTStrFree(pszBasedirectory);
3869 if (!pszFullname)
3870 return VERR_NO_STR_MEMORY;
3871 pExtent->pszFullname = pszFullname;
3872
3873 /* Create file for extent. Make it write only, no reading allowed. */
3874 rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszFullname,
3875 VDOpenFlagsToFileOpenFlags(pImage->uOpenFlags,
3876 true /* fCreate */)
3877 & ~RTFILE_O_READ);
3878 if (RT_FAILURE(rc))
3879 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not create new file '%s'"), pExtent->pszFullname);
3880
3881 /* Place descriptor file information. */
3882 pExtent->uDescriptorSector = 1;
3883 pExtent->cDescriptorSectors = VMDK_BYTE2SECTOR(pImage->cbDescAlloc);
3884 /* The descriptor is part of the (only) extent. */
3885 pExtent->pDescData = pImage->pDescData;
3886 pImage->pDescData = NULL;
3887
3888 uint64_t cSectorsPerGDE, cSectorsPerGD;
3889 pExtent->enmType = VMDKETYPE_HOSTED_SPARSE;
3890 pExtent->cSectors = VMDK_BYTE2SECTOR(RT_ALIGN_64(cbSize, _64K));
3891 pExtent->cSectorsPerGrain = VMDK_BYTE2SECTOR(_64K);
3892 pExtent->cGTEntries = 512;
3893 cSectorsPerGDE = pExtent->cGTEntries * pExtent->cSectorsPerGrain;
3894 pExtent->cSectorsPerGDE = cSectorsPerGDE;
3895 pExtent->cGDEntries = (pExtent->cSectors + cSectorsPerGDE - 1) / cSectorsPerGDE;
3896 cSectorsPerGD = (pExtent->cGDEntries + (512 / sizeof(uint32_t) - 1)) / (512 / sizeof(uint32_t));
3897
3898 /* The spec says version is 1 for all VMDKs, but the vast
3899 * majority of streamOptimized VMDKs actually contain
3900 * version 3 - so go with the majority. Both are accepted. */
3901 pExtent->uVersion = 3;
3902 pExtent->uCompression = VMDK_COMPRESSION_DEFLATE;
3903 pExtent->fFooter = true;
3904
3905 pExtent->enmAccess = VMDKACCESS_READONLY;
3906 pExtent->fUncleanShutdown = false;
3907 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(cbSize);
3908 pExtent->uSectorOffset = 0;
3909 pExtent->fMetaDirty = true;
3910
3911 /* Create grain directory, without preallocating it straight away. It will
3912 * be constructed on the fly when writing out the data and written when
3913 * closing the image. The end effect is that the full grain directory is
3914 * allocated, which is a requirement of the VMDK specs. */
3915 rc = vmdkCreateGrainDirectory(pImage, pExtent, VMDK_GD_AT_END,
3916 false /* fPreAlloc */);
3917 if (RT_FAILURE(rc))
3918 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not create new grain directory in '%s'"), pExtent->pszFullname);
3919
3920 rc = vmdkDescBaseSetStr(pImage, &pImage->Descriptor, "createType",
3921 "streamOptimized");
3922 if (RT_FAILURE(rc))
3923 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not set the image type in '%s'"), pImage->pszFilename);
3924
3925 return rc;
3926}
3927
3928/**
3929 * Internal: The actual code for creating any VMDK variant currently in
3930 * existence on hosted environments.
3931 */
3932static int vmdkCreateImage(PVMDKIMAGE pImage, uint64_t cbSize,
3933 unsigned uImageFlags, const char *pszComment,
3934 PCVDGEOMETRY pPCHSGeometry,
3935 PCVDGEOMETRY pLCHSGeometry, PCRTUUID pUuid,
3936 PFNVDPROGRESS pfnProgress, void *pvUser,
3937 unsigned uPercentStart, unsigned uPercentSpan)
3938{
3939 int rc;
3940
3941 pImage->uImageFlags = uImageFlags;
3942
3943 pImage->pIfError = VDIfErrorGet(pImage->pVDIfsDisk);
3944 pImage->pIfIo = VDIfIoIntGet(pImage->pVDIfsImage);
3945 AssertPtrReturn(pImage->pIfIo, VERR_INVALID_PARAMETER);
3946
3947 rc = vmdkCreateDescriptor(pImage, pImage->pDescData, pImage->cbDescAlloc,
3948 &pImage->Descriptor);
3949 if (RT_FAILURE(rc))
3950 {
3951 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not create new descriptor in '%s'"), pImage->pszFilename);
3952 goto out;
3953 }
3954
3955 if ( (uImageFlags & VD_IMAGE_FLAGS_FIXED)
3956 && (uImageFlags & VD_VMDK_IMAGE_FLAGS_RAWDISK))
3957 {
3958 /* Raw disk image (includes raw partition). */
3959 const PVBOXHDDRAW pRaw = (const PVBOXHDDRAW)pszComment;
3960 /* As the comment is misused, zap it so that no garbage comment
3961 * is set below. */
3962 pszComment = NULL;
3963 rc = vmdkCreateRawImage(pImage, pRaw, cbSize);
3964 }
3965 else
3966 {
3967 if (uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
3968 {
3969 /* Stream optimized sparse image (monolithic). */
3970 rc = vmdkCreateStreamImage(pImage, cbSize, uImageFlags,
3971 pfnProgress, pvUser, uPercentStart,
3972 uPercentSpan * 95 / 100);
3973 }
3974 else
3975 {
3976 /* Regular fixed or sparse image (monolithic or split). */
3977 rc = vmdkCreateRegularImage(pImage, cbSize, uImageFlags,
3978 pfnProgress, pvUser, uPercentStart,
3979 uPercentSpan * 95 / 100);
3980 }
3981 }
3982
3983 if (RT_FAILURE(rc))
3984 goto out;
3985
3986 if (RT_SUCCESS(rc) && pfnProgress)
3987 pfnProgress(pvUser, uPercentStart + uPercentSpan * 98 / 100);
3988
3989 pImage->cbSize = cbSize;
3990
3991 for (unsigned i = 0; i < pImage->cExtents; i++)
3992 {
3993 PVMDKEXTENT pExtent = &pImage->pExtents[i];
3994
3995 rc = vmdkDescExtInsert(pImage, &pImage->Descriptor, pExtent->enmAccess,
3996 pExtent->cNominalSectors, pExtent->enmType,
3997 pExtent->pszBasename, pExtent->uSectorOffset);
3998 if (RT_FAILURE(rc))
3999 {
4000 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not insert the extent list into descriptor in '%s'"), pImage->pszFilename);
4001 goto out;
4002 }
4003 }
4004 vmdkDescExtRemoveDummy(pImage, &pImage->Descriptor);
4005
4006 if ( pPCHSGeometry->cCylinders != 0
4007 && pPCHSGeometry->cHeads != 0
4008 && pPCHSGeometry->cSectors != 0)
4009 {
4010 rc = vmdkDescSetPCHSGeometry(pImage, pPCHSGeometry);
4011 if (RT_FAILURE(rc))
4012 goto out;
4013 }
4014 if ( pLCHSGeometry->cCylinders != 0
4015 && pLCHSGeometry->cHeads != 0
4016 && pLCHSGeometry->cSectors != 0)
4017 {
4018 rc = vmdkDescSetLCHSGeometry(pImage, pLCHSGeometry);
4019 if (RT_FAILURE(rc))
4020 goto out;
4021 }
4022
4023 pImage->LCHSGeometry = *pLCHSGeometry;
4024 pImage->PCHSGeometry = *pPCHSGeometry;
4025
4026 pImage->ImageUuid = *pUuid;
4027 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
4028 VMDK_DDB_IMAGE_UUID, &pImage->ImageUuid);
4029 if (RT_FAILURE(rc))
4030 {
4031 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error storing image UUID in new descriptor in '%s'"), pImage->pszFilename);
4032 goto out;
4033 }
4034 RTUuidClear(&pImage->ParentUuid);
4035 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
4036 VMDK_DDB_PARENT_UUID, &pImage->ParentUuid);
4037 if (RT_FAILURE(rc))
4038 {
4039 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error storing parent image UUID in new descriptor in '%s'"), pImage->pszFilename);
4040 goto out;
4041 }
4042 RTUuidClear(&pImage->ModificationUuid);
4043 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
4044 VMDK_DDB_MODIFICATION_UUID,
4045 &pImage->ModificationUuid);
4046 if (RT_FAILURE(rc))
4047 {
4048 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error storing modification UUID in new descriptor in '%s'"), pImage->pszFilename);
4049 goto out;
4050 }
4051 RTUuidClear(&pImage->ParentModificationUuid);
4052 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
4053 VMDK_DDB_PARENT_MODIFICATION_UUID,
4054 &pImage->ParentModificationUuid);
4055 if (RT_FAILURE(rc))
4056 {
4057 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error storing parent modification UUID in new descriptor in '%s'"), pImage->pszFilename);
4058 goto out;
4059 }
4060
4061 rc = vmdkAllocateGrainTableCache(pImage);
4062 if (RT_FAILURE(rc))
4063 goto out;
4064
4065 rc = vmdkSetImageComment(pImage, pszComment);
4066 if (RT_FAILURE(rc))
4067 {
4068 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: cannot set image comment in '%s'"), pImage->pszFilename);
4069 goto out;
4070 }
4071
4072 if (RT_SUCCESS(rc) && pfnProgress)
4073 pfnProgress(pvUser, uPercentStart + uPercentSpan * 99 / 100);
4074
4075 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
4076 {
4077 /* streamOptimized is a bit special, we cannot trigger the flush
4078 * until all data has been written. So we write the necessary
4079 * information explicitly. */
4080 pImage->pExtents[0].cDescriptorSectors = VMDK_BYTE2SECTOR(RT_ALIGN_64( pImage->Descriptor.aLines[pImage->Descriptor.cLines]
4081 - pImage->Descriptor.aLines[0], 512));
4082 rc = vmdkWriteMetaSparseExtent(pImage, &pImage->pExtents[0], 0, NULL);
4083 if (RT_FAILURE(rc))
4084 {
4085 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: cannot write VMDK header in '%s'"), pImage->pszFilename);
4086 goto out;
4087 }
4088
4089 rc = vmdkWriteDescriptor(pImage, NULL);
4090 if (RT_FAILURE(rc))
4091 {
4092 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: cannot write VMDK descriptor in '%s'"), pImage->pszFilename);
4093 goto out;
4094 }
4095 }
4096 else
4097 rc = vmdkFlushImage(pImage, NULL);
4098
4099out:
4100 if (RT_SUCCESS(rc) && pfnProgress)
4101 pfnProgress(pvUser, uPercentStart + uPercentSpan);
4102
4103 if (RT_FAILURE(rc))
4104 vmdkFreeImage(pImage, rc != VERR_ALREADY_EXISTS);
4105 return rc;
4106}
4107
4108/**
4109 * Internal: Update image comment.
4110 */
4111static int vmdkSetImageComment(PVMDKIMAGE pImage, const char *pszComment)
4112{
4113 char *pszCommentEncoded;
4114 if (pszComment)
4115 {
4116 pszCommentEncoded = vmdkEncodeString(pszComment);
4117 if (!pszCommentEncoded)
4118 return VERR_NO_MEMORY;
4119 }
4120 else
4121 pszCommentEncoded = NULL;
4122 int rc = vmdkDescDDBSetStr(pImage, &pImage->Descriptor,
4123 "ddb.comment", pszCommentEncoded);
4124 if (pszComment)
4125 RTStrFree(pszCommentEncoded);
4126 if (RT_FAILURE(rc))
4127 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error storing image comment in descriptor in '%s'"), pImage->pszFilename);
4128 return VINF_SUCCESS;
4129}
4130
4131/**
4132 * Internal. Clear the grain table buffer for real stream optimized writing.
4133 */
4134static void vmdkStreamClearGT(PVMDKIMAGE pImage, PVMDKEXTENT pExtent)
4135{
4136 uint32_t cCacheLines = RT_ALIGN(pExtent->cGTEntries, VMDK_GT_CACHELINE_SIZE) / VMDK_GT_CACHELINE_SIZE;
4137 for (uint32_t i = 0; i < cCacheLines; i++)
4138 memset(&pImage->pGTCache->aGTCache[i].aGTData[0], '\0',
4139 VMDK_GT_CACHELINE_SIZE * sizeof(uint32_t));
4140}
4141
4142/**
4143 * Internal. Flush the grain table buffer for real stream optimized writing.
4144 */
4145static int vmdkStreamFlushGT(PVMDKIMAGE pImage, PVMDKEXTENT pExtent,
4146 uint32_t uGDEntry)
4147{
4148 int rc = VINF_SUCCESS;
4149 uint32_t cCacheLines = RT_ALIGN(pExtent->cGTEntries, VMDK_GT_CACHELINE_SIZE) / VMDK_GT_CACHELINE_SIZE;
4150
4151 /* VMware does not write out completely empty grain tables in the case
4152 * of streamOptimized images, which according to my interpretation of
4153 * the VMDK 1.1 spec is bending the rules. Since they do it and we can
4154 * handle it without problems do it the same way and save some bytes. */
4155 bool fAllZero = true;
4156 for (uint32_t i = 0; i < cCacheLines; i++)
4157 {
4158 /* Convert the grain table to little endian in place, as it will not
4159 * be used at all after this function has been called. */
4160 uint32_t *pGTTmp = &pImage->pGTCache->aGTCache[i].aGTData[0];
4161 for (uint32_t j = 0; j < VMDK_GT_CACHELINE_SIZE; j++, pGTTmp++)
4162 if (*pGTTmp)
4163 {
4164 fAllZero = false;
4165 break;
4166 }
4167 if (!fAllZero)
4168 break;
4169 }
4170 if (fAllZero)
4171 return VINF_SUCCESS;
4172
4173 uint64_t uFileOffset = pExtent->uAppendPosition;
4174 if (!uFileOffset)
4175 return VERR_INTERNAL_ERROR;
4176 /* Align to sector, as the previous write could have been any size. */
4177 uFileOffset = RT_ALIGN_64(uFileOffset, 512);
4178
4179 /* Grain table marker. */
4180 uint8_t aMarker[512];
4181 PVMDKMARKER pMarker = (PVMDKMARKER)&aMarker[0];
4182 memset(pMarker, '\0', sizeof(aMarker));
4183 pMarker->uSector = RT_H2LE_U64(VMDK_BYTE2SECTOR((uint64_t)pExtent->cGTEntries * sizeof(uint32_t)));
4184 pMarker->uType = RT_H2LE_U32(VMDK_MARKER_GT);
4185 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pExtent->pFile->pStorage, uFileOffset,
4186 aMarker, sizeof(aMarker));
4187 AssertRC(rc);
4188 uFileOffset += 512;
4189
4190 if (!pExtent->pGD || pExtent->pGD[uGDEntry])
4191 return VERR_INTERNAL_ERROR;
4192
4193 pExtent->pGD[uGDEntry] = VMDK_BYTE2SECTOR(uFileOffset);
4194
4195 for (uint32_t i = 0; i < cCacheLines; i++)
4196 {
4197 /* Convert the grain table to little endian in place, as it will not
4198 * be used at all after this function has been called. */
4199 uint32_t *pGTTmp = &pImage->pGTCache->aGTCache[i].aGTData[0];
4200 for (uint32_t j = 0; j < VMDK_GT_CACHELINE_SIZE; j++, pGTTmp++)
4201 *pGTTmp = RT_H2LE_U32(*pGTTmp);
4202
4203 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pExtent->pFile->pStorage, uFileOffset,
4204 &pImage->pGTCache->aGTCache[i].aGTData[0],
4205 VMDK_GT_CACHELINE_SIZE * sizeof(uint32_t));
4206 uFileOffset += VMDK_GT_CACHELINE_SIZE * sizeof(uint32_t);
4207 if (RT_FAILURE(rc))
4208 break;
4209 }
4210 Assert(!(uFileOffset % 512));
4211 pExtent->uAppendPosition = RT_ALIGN_64(uFileOffset, 512);
4212 return rc;
4213}
4214
4215/**
4216 * Internal. Free all allocated space for representing an image, and optionally
4217 * delete the image from disk.
4218 */
4219static int vmdkFreeImage(PVMDKIMAGE pImage, bool fDelete)
4220{
4221 int rc = VINF_SUCCESS;
4222
4223 /* Freeing a never allocated image (e.g. because the open failed) is
4224 * not signalled as an error. After all nothing bad happens. */
4225 if (pImage)
4226 {
4227 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
4228 {
4229 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
4230 {
4231 /* Check if all extents are clean. */
4232 for (unsigned i = 0; i < pImage->cExtents; i++)
4233 {
4234 Assert(!pImage->pExtents[i].fUncleanShutdown);
4235 }
4236 }
4237 else
4238 {
4239 /* Mark all extents as clean. */
4240 for (unsigned i = 0; i < pImage->cExtents; i++)
4241 {
4242 if ( ( pImage->pExtents[i].enmType == VMDKETYPE_HOSTED_SPARSE
4243#ifdef VBOX_WITH_VMDK_ESX
4244 || pImage->pExtents[i].enmType == VMDKETYPE_ESX_SPARSE
4245#endif /* VBOX_WITH_VMDK_ESX */
4246 )
4247 && pImage->pExtents[i].fUncleanShutdown)
4248 {
4249 pImage->pExtents[i].fUncleanShutdown = false;
4250 pImage->pExtents[i].fMetaDirty = true;
4251 }
4252
4253 /* From now on it's not safe to append any more data. */
4254 pImage->pExtents[i].uAppendPosition = 0;
4255 }
4256 }
4257 }
4258
4259 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
4260 {
4261 /* No need to write any pending data if the file will be deleted
4262 * or if the new file wasn't successfully created. */
4263 if ( !fDelete && pImage->pExtents
4264 && pImage->pExtents[0].cGTEntries
4265 && pImage->pExtents[0].uAppendPosition)
4266 {
4267 PVMDKEXTENT pExtent = &pImage->pExtents[0];
4268 uint32_t uLastGDEntry = pExtent->uLastGrainAccess / pExtent->cGTEntries;
4269 rc = vmdkStreamFlushGT(pImage, pExtent, uLastGDEntry);
4270 AssertRC(rc);
4271 vmdkStreamClearGT(pImage, pExtent);
4272 for (uint32_t i = uLastGDEntry + 1; i < pExtent->cGDEntries; i++)
4273 {
4274 rc = vmdkStreamFlushGT(pImage, pExtent, i);
4275 AssertRC(rc);
4276 }
4277
4278 uint64_t uFileOffset = pExtent->uAppendPosition;
4279 if (!uFileOffset)
4280 return VERR_INTERNAL_ERROR;
4281 uFileOffset = RT_ALIGN_64(uFileOffset, 512);
4282
4283 /* From now on it's not safe to append any more data. */
4284 pExtent->uAppendPosition = 0;
4285
4286 /* Grain directory marker. */
4287 uint8_t aMarker[512];
4288 PVMDKMARKER pMarker = (PVMDKMARKER)&aMarker[0];
4289 memset(pMarker, '\0', sizeof(aMarker));
4290 pMarker->uSector = VMDK_BYTE2SECTOR(RT_ALIGN_64(RT_H2LE_U64((uint64_t)pExtent->cGDEntries * sizeof(uint32_t)), 512));
4291 pMarker->uType = RT_H2LE_U32(VMDK_MARKER_GD);
4292 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pExtent->pFile->pStorage, uFileOffset,
4293 aMarker, sizeof(aMarker));
4294 AssertRC(rc);
4295 uFileOffset += 512;
4296
4297 /* Write grain directory in little endian style. The array will
4298 * not be used after this, so convert in place. */
4299 uint32_t *pGDTmp = pExtent->pGD;
4300 for (uint32_t i = 0; i < pExtent->cGDEntries; i++, pGDTmp++)
4301 *pGDTmp = RT_H2LE_U32(*pGDTmp);
4302 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pExtent->pFile->pStorage,
4303 uFileOffset, pExtent->pGD,
4304 pExtent->cGDEntries * sizeof(uint32_t));
4305 AssertRC(rc);
4306
4307 pExtent->uSectorGD = VMDK_BYTE2SECTOR(uFileOffset);
4308 pExtent->uSectorRGD = VMDK_BYTE2SECTOR(uFileOffset);
4309 uFileOffset = RT_ALIGN_64( uFileOffset
4310 + pExtent->cGDEntries * sizeof(uint32_t),
4311 512);
4312
4313 /* Footer marker. */
4314 memset(pMarker, '\0', sizeof(aMarker));
4315 pMarker->uSector = VMDK_BYTE2SECTOR(512);
4316 pMarker->uType = RT_H2LE_U32(VMDK_MARKER_FOOTER);
4317 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pExtent->pFile->pStorage,
4318 uFileOffset, aMarker, sizeof(aMarker));
4319 AssertRC(rc);
4320
4321 uFileOffset += 512;
4322 rc = vmdkWriteMetaSparseExtent(pImage, pExtent, uFileOffset, NULL);
4323 AssertRC(rc);
4324
4325 uFileOffset += 512;
4326 /* End-of-stream marker. */
4327 memset(pMarker, '\0', sizeof(aMarker));
4328 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pExtent->pFile->pStorage,
4329 uFileOffset, aMarker, sizeof(aMarker));
4330 AssertRC(rc);
4331 }
4332 }
4333 else if (!fDelete)
4334 vmdkFlushImage(pImage, NULL);
4335
4336 if (pImage->pExtents != NULL)
4337 {
4338 for (unsigned i = 0 ; i < pImage->cExtents; i++)
4339 {
4340 int rc2 = vmdkFreeExtentData(pImage, &pImage->pExtents[i], fDelete);
4341 if (RT_SUCCESS(rc))
4342 rc = rc2; /* Propogate any error when closing the file. */
4343 }
4344 RTMemFree(pImage->pExtents);
4345 pImage->pExtents = NULL;
4346 }
4347 pImage->cExtents = 0;
4348 if (pImage->pFile != NULL)
4349 {
4350 int rc2 = vmdkFileClose(pImage, &pImage->pFile, fDelete);
4351 if (RT_SUCCESS(rc))
4352 rc = rc2; /* Propogate any error when closing the file. */
4353 }
4354 int rc2 = vmdkFileCheckAllClose(pImage);
4355 if (RT_SUCCESS(rc))
4356 rc = rc2; /* Propogate any error when closing the file. */
4357
4358 if (pImage->pGTCache)
4359 {
4360 RTMemFree(pImage->pGTCache);
4361 pImage->pGTCache = NULL;
4362 }
4363 if (pImage->pDescData)
4364 {
4365 RTMemFree(pImage->pDescData);
4366 pImage->pDescData = NULL;
4367 }
4368 }
4369
4370 LogFlowFunc(("returns %Rrc\n", rc));
4371 return rc;
4372}
4373
4374/**
4375 * Internal. Flush image data (and metadata) to disk.
4376 */
4377static int vmdkFlushImage(PVMDKIMAGE pImage, PVDIOCTX pIoCtx)
4378{
4379 PVMDKEXTENT pExtent;
4380 int rc = VINF_SUCCESS;
4381
4382 /* Update descriptor if changed. */
4383 if (pImage->Descriptor.fDirty)
4384 {
4385 rc = vmdkWriteDescriptor(pImage, pIoCtx);
4386 if (RT_FAILURE(rc))
4387 goto out;
4388 }
4389
4390 for (unsigned i = 0; i < pImage->cExtents; i++)
4391 {
4392 pExtent = &pImage->pExtents[i];
4393 if (pExtent->pFile != NULL && pExtent->fMetaDirty)
4394 {
4395 switch (pExtent->enmType)
4396 {
4397 case VMDKETYPE_HOSTED_SPARSE:
4398 if (!pExtent->fFooter)
4399 {
4400 rc = vmdkWriteMetaSparseExtent(pImage, pExtent, 0, pIoCtx);
4401 if (RT_FAILURE(rc))
4402 goto out;
4403 }
4404 else
4405 {
4406 uint64_t uFileOffset = pExtent->uAppendPosition;
4407 /* Simply skip writing anything if the streamOptimized
4408 * image hasn't been just created. */
4409 if (!uFileOffset)
4410 break;
4411 uFileOffset = RT_ALIGN_64(uFileOffset, 512);
4412 rc = vmdkWriteMetaSparseExtent(pImage, pExtent,
4413 uFileOffset, pIoCtx);
4414 if (RT_FAILURE(rc))
4415 goto out;
4416 }
4417 break;
4418#ifdef VBOX_WITH_VMDK_ESX
4419 case VMDKETYPE_ESX_SPARSE:
4420 /** @todo update the header. */
4421 break;
4422#endif /* VBOX_WITH_VMDK_ESX */
4423 case VMDKETYPE_VMFS:
4424 case VMDKETYPE_FLAT:
4425 /* Nothing to do. */
4426 break;
4427 case VMDKETYPE_ZERO:
4428 default:
4429 AssertMsgFailed(("extent with type %d marked as dirty\n",
4430 pExtent->enmType));
4431 break;
4432 }
4433 }
4434 switch (pExtent->enmType)
4435 {
4436 case VMDKETYPE_HOSTED_SPARSE:
4437#ifdef VBOX_WITH_VMDK_ESX
4438 case VMDKETYPE_ESX_SPARSE:
4439#endif /* VBOX_WITH_VMDK_ESX */
4440 case VMDKETYPE_VMFS:
4441 case VMDKETYPE_FLAT:
4442 /** @todo implement proper path absolute check. */
4443 if ( pExtent->pFile != NULL
4444 && !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
4445 && !(pExtent->pszBasename[0] == RTPATH_SLASH))
4446 rc = vdIfIoIntFileFlush(pImage->pIfIo, pExtent->pFile->pStorage, pIoCtx,
4447 NULL, NULL);
4448 break;
4449 case VMDKETYPE_ZERO:
4450 /* No need to do anything for this extent. */
4451 break;
4452 default:
4453 AssertMsgFailed(("unknown extent type %d\n", pExtent->enmType));
4454 break;
4455 }
4456 }
4457
4458out:
4459 return rc;
4460}
4461
4462/**
4463 * Internal. Find extent corresponding to the sector number in the disk.
4464 */
4465static int vmdkFindExtent(PVMDKIMAGE pImage, uint64_t offSector,
4466 PVMDKEXTENT *ppExtent, uint64_t *puSectorInExtent)
4467{
4468 PVMDKEXTENT pExtent = NULL;
4469 int rc = VINF_SUCCESS;
4470
4471 for (unsigned i = 0; i < pImage->cExtents; i++)
4472 {
4473 if (offSector < pImage->pExtents[i].cNominalSectors)
4474 {
4475 pExtent = &pImage->pExtents[i];
4476 *puSectorInExtent = offSector + pImage->pExtents[i].uSectorOffset;
4477 break;
4478 }
4479 offSector -= pImage->pExtents[i].cNominalSectors;
4480 }
4481
4482 if (pExtent)
4483 *ppExtent = pExtent;
4484 else
4485 rc = VERR_IO_SECTOR_NOT_FOUND;
4486
4487 return rc;
4488}
4489
4490/**
4491 * Internal. Hash function for placing the grain table hash entries.
4492 */
4493static uint32_t vmdkGTCacheHash(PVMDKGTCACHE pCache, uint64_t uSector,
4494 unsigned uExtent)
4495{
4496 /** @todo this hash function is quite simple, maybe use a better one which
4497 * scrambles the bits better. */
4498 return (uSector + uExtent) % pCache->cEntries;
4499}
4500
4501/**
4502 * Internal. Get sector number in the extent file from the relative sector
4503 * number in the extent.
4504 */
4505static int vmdkGetSector(PVMDKIMAGE pImage, PVDIOCTX pIoCtx,
4506 PVMDKEXTENT pExtent, uint64_t uSector,
4507 uint64_t *puExtentSector)
4508{
4509 PVMDKGTCACHE pCache = pImage->pGTCache;
4510 uint64_t uGDIndex, uGTSector, uGTBlock;
4511 uint32_t uGTHash, uGTBlockIndex;
4512 PVMDKGTCACHEENTRY pGTCacheEntry;
4513 uint32_t aGTDataTmp[VMDK_GT_CACHELINE_SIZE];
4514 int rc;
4515
4516 /* For newly created and readonly/sequentially opened streamOptimized
4517 * images this must be a no-op, as the grain directory is not there. */
4518 if ( ( pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED
4519 && pExtent->uAppendPosition)
4520 || ( pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED
4521 && pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY
4522 && pImage->uOpenFlags & VD_OPEN_FLAGS_SEQUENTIAL))
4523 {
4524 *puExtentSector = 0;
4525 return VINF_SUCCESS;
4526 }
4527
4528 uGDIndex = uSector / pExtent->cSectorsPerGDE;
4529 if (uGDIndex >= pExtent->cGDEntries)
4530 return VERR_OUT_OF_RANGE;
4531 uGTSector = pExtent->pGD[uGDIndex];
4532 if (!uGTSector)
4533 {
4534 /* There is no grain table referenced by this grain directory
4535 * entry. So there is absolutely no data in this area. */
4536 *puExtentSector = 0;
4537 return VINF_SUCCESS;
4538 }
4539
4540 uGTBlock = uSector / (pExtent->cSectorsPerGrain * VMDK_GT_CACHELINE_SIZE);
4541 uGTHash = vmdkGTCacheHash(pCache, uGTBlock, pExtent->uExtent);
4542 pGTCacheEntry = &pCache->aGTCache[uGTHash];
4543 if ( pGTCacheEntry->uExtent != pExtent->uExtent
4544 || pGTCacheEntry->uGTBlock != uGTBlock)
4545 {
4546 /* Cache miss, fetch data from disk. */
4547 PVDMETAXFER pMetaXfer;
4548 rc = vdIfIoIntFileReadMeta(pImage->pIfIo, pExtent->pFile->pStorage,
4549 VMDK_SECTOR2BYTE(uGTSector) + (uGTBlock % (pExtent->cGTEntries / VMDK_GT_CACHELINE_SIZE)) * sizeof(aGTDataTmp),
4550 aGTDataTmp, sizeof(aGTDataTmp), pIoCtx, &pMetaXfer, NULL, NULL);
4551 if (RT_FAILURE(rc))
4552 return rc;
4553 /* We can release the metadata transfer immediately. */
4554 vdIfIoIntMetaXferRelease(pImage->pIfIo, pMetaXfer);
4555 pGTCacheEntry->uExtent = pExtent->uExtent;
4556 pGTCacheEntry->uGTBlock = uGTBlock;
4557 for (unsigned i = 0; i < VMDK_GT_CACHELINE_SIZE; i++)
4558 pGTCacheEntry->aGTData[i] = RT_LE2H_U32(aGTDataTmp[i]);
4559 }
4560 uGTBlockIndex = (uSector / pExtent->cSectorsPerGrain) % VMDK_GT_CACHELINE_SIZE;
4561 uint32_t uGrainSector = pGTCacheEntry->aGTData[uGTBlockIndex];
4562 if (uGrainSector)
4563 *puExtentSector = uGrainSector + uSector % pExtent->cSectorsPerGrain;
4564 else
4565 *puExtentSector = 0;
4566 return VINF_SUCCESS;
4567}
4568
4569/**
4570 * Internal. Writes the grain and also if necessary the grain tables.
4571 * Uses the grain table cache as a true grain table.
4572 */
4573static int vmdkStreamAllocGrain(PVMDKIMAGE pImage, PVMDKEXTENT pExtent,
4574 uint64_t uSector, PVDIOCTX pIoCtx,
4575 uint64_t cbWrite)
4576{
4577 uint32_t uGrain;
4578 uint32_t uGDEntry, uLastGDEntry;
4579 uint32_t cbGrain = 0;
4580 uint32_t uCacheLine, uCacheEntry;
4581 const void *pData;
4582 int rc;
4583
4584 /* Very strict requirements: always write at least one full grain, with
4585 * proper alignment. Everything else would require reading of already
4586 * written data, which we don't support for obvious reasons. The only
4587 * exception is the last grain, and only if the image size specifies
4588 * that only some portion holds data. In any case the write must be
4589 * within the image limits, no "overshoot" allowed. */
4590 if ( cbWrite == 0
4591 || ( cbWrite < VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain)
4592 && pExtent->cNominalSectors - uSector >= pExtent->cSectorsPerGrain)
4593 || uSector % pExtent->cSectorsPerGrain
4594 || uSector + VMDK_BYTE2SECTOR(cbWrite) > pExtent->cNominalSectors)
4595 return VERR_INVALID_PARAMETER;
4596
4597 /* Clip write range to at most the rest of the grain. */
4598 cbWrite = RT_MIN(cbWrite, VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain - uSector % pExtent->cSectorsPerGrain));
4599
4600 /* Do not allow to go back. */
4601 uGrain = uSector / pExtent->cSectorsPerGrain;
4602 uCacheLine = uGrain % pExtent->cGTEntries / VMDK_GT_CACHELINE_SIZE;
4603 uCacheEntry = uGrain % VMDK_GT_CACHELINE_SIZE;
4604 uGDEntry = uGrain / pExtent->cGTEntries;
4605 uLastGDEntry = pExtent->uLastGrainAccess / pExtent->cGTEntries;
4606 if (uGrain < pExtent->uLastGrainAccess)
4607 return VERR_VD_VMDK_INVALID_WRITE;
4608
4609 /* Zero byte write optimization. Since we don't tell VBoxHDD that we need
4610 * to allocate something, we also need to detect the situation ourself. */
4611 if ( !(pImage->uOpenFlags & VD_OPEN_FLAGS_HONOR_ZEROES)
4612 && vdIfIoIntIoCtxIsZero(pImage->pIfIo, pIoCtx, cbWrite, true /* fAdvance */))
4613 return VINF_SUCCESS;
4614
4615 if (uGDEntry != uLastGDEntry)
4616 {
4617 rc = vmdkStreamFlushGT(pImage, pExtent, uLastGDEntry);
4618 if (RT_FAILURE(rc))
4619 return rc;
4620 vmdkStreamClearGT(pImage, pExtent);
4621 for (uint32_t i = uLastGDEntry + 1; i < uGDEntry; i++)
4622 {
4623 rc = vmdkStreamFlushGT(pImage, pExtent, i);
4624 if (RT_FAILURE(rc))
4625 return rc;
4626 }
4627 }
4628
4629 uint64_t uFileOffset;
4630 uFileOffset = pExtent->uAppendPosition;
4631 if (!uFileOffset)
4632 return VERR_INTERNAL_ERROR;
4633 /* Align to sector, as the previous write could have been any size. */
4634 uFileOffset = RT_ALIGN_64(uFileOffset, 512);
4635
4636 /* Paranoia check: extent type, grain table buffer presence and
4637 * grain table buffer space. Also grain table entry must be clear. */
4638 if ( pExtent->enmType != VMDKETYPE_HOSTED_SPARSE
4639 || !pImage->pGTCache
4640 || pExtent->cGTEntries > VMDK_GT_CACHE_SIZE * VMDK_GT_CACHELINE_SIZE
4641 || pImage->pGTCache->aGTCache[uCacheLine].aGTData[uCacheEntry])
4642 return VERR_INTERNAL_ERROR;
4643
4644 /* Update grain table entry. */
4645 pImage->pGTCache->aGTCache[uCacheLine].aGTData[uCacheEntry] = VMDK_BYTE2SECTOR(uFileOffset);
4646
4647 if (cbWrite != VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain))
4648 {
4649 vdIfIoIntIoCtxCopyFrom(pImage->pIfIo, pIoCtx, pExtent->pvGrain, cbWrite);
4650 memset((char *)pExtent->pvGrain + cbWrite, '\0',
4651 VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain) - cbWrite);
4652 pData = pExtent->pvGrain;
4653 }
4654 else
4655 {
4656 RTSGSEG Segment;
4657 unsigned cSegments = 1;
4658 size_t cbSeg = 0;
4659
4660 cbSeg = vdIfIoIntIoCtxSegArrayCreate(pImage->pIfIo, pIoCtx, &Segment,
4661 &cSegments, VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain));
4662 Assert(cbSeg == VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain));
4663 pData = Segment.pvSeg;
4664 }
4665 rc = vmdkFileDeflateSync(pImage, pExtent, uFileOffset, pData,
4666 VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain),
4667 uSector, &cbGrain);
4668 if (RT_FAILURE(rc))
4669 {
4670 pExtent->uGrainSectorAbs = 0;
4671 AssertRC(rc);
4672 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: cannot write compressed data block in '%s'"), pExtent->pszFullname);
4673 }
4674 pExtent->uLastGrainAccess = uGrain;
4675 pExtent->uAppendPosition += cbGrain;
4676
4677 return rc;
4678}
4679
4680/**
4681 * Internal: Updates the grain table during grain allocation.
4682 */
4683static int vmdkAllocGrainGTUpdate(PVMDKIMAGE pImage, PVMDKEXTENT pExtent, PVDIOCTX pIoCtx,
4684 PVMDKGRAINALLOCASYNC pGrainAlloc)
4685{
4686 int rc = VINF_SUCCESS;
4687 PVMDKGTCACHE pCache = pImage->pGTCache;
4688 uint32_t aGTDataTmp[VMDK_GT_CACHELINE_SIZE];
4689 uint32_t uGTHash, uGTBlockIndex;
4690 uint64_t uGTSector, uRGTSector, uGTBlock;
4691 uint64_t uSector = pGrainAlloc->uSector;
4692 PVMDKGTCACHEENTRY pGTCacheEntry;
4693
4694 LogFlowFunc(("pImage=%#p pExtent=%#p pCache=%#p pIoCtx=%#p pGrainAlloc=%#p\n",
4695 pImage, pExtent, pCache, pIoCtx, pGrainAlloc));
4696
4697 uGTSector = pGrainAlloc->uGTSector;
4698 uRGTSector = pGrainAlloc->uRGTSector;
4699 LogFlow(("uGTSector=%llu uRGTSector=%llu\n", uGTSector, uRGTSector));
4700
4701 /* Update the grain table (and the cache). */
4702 uGTBlock = uSector / (pExtent->cSectorsPerGrain * VMDK_GT_CACHELINE_SIZE);
4703 uGTHash = vmdkGTCacheHash(pCache, uGTBlock, pExtent->uExtent);
4704 pGTCacheEntry = &pCache->aGTCache[uGTHash];
4705 if ( pGTCacheEntry->uExtent != pExtent->uExtent
4706 || pGTCacheEntry->uGTBlock != uGTBlock)
4707 {
4708 /* Cache miss, fetch data from disk. */
4709 LogFlow(("Cache miss, fetch data from disk\n"));
4710 PVDMETAXFER pMetaXfer = NULL;
4711 rc = vdIfIoIntFileReadMeta(pImage->pIfIo, pExtent->pFile->pStorage,
4712 VMDK_SECTOR2BYTE(uGTSector) + (uGTBlock % (pExtent->cGTEntries / VMDK_GT_CACHELINE_SIZE)) * sizeof(aGTDataTmp),
4713 aGTDataTmp, sizeof(aGTDataTmp), pIoCtx,
4714 &pMetaXfer, vmdkAllocGrainComplete, pGrainAlloc);
4715 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
4716 {
4717 pGrainAlloc->cIoXfersPending++;
4718 pGrainAlloc->fGTUpdateNeeded = true;
4719 /* Leave early, we will be called again after the read completed. */
4720 LogFlowFunc(("Metadata read in progress, leaving\n"));
4721 return rc;
4722 }
4723 else if (RT_FAILURE(rc))
4724 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: cannot read allocated grain table entry in '%s'"), pExtent->pszFullname);
4725 vdIfIoIntMetaXferRelease(pImage->pIfIo, pMetaXfer);
4726 pGTCacheEntry->uExtent = pExtent->uExtent;
4727 pGTCacheEntry->uGTBlock = uGTBlock;
4728 for (unsigned i = 0; i < VMDK_GT_CACHELINE_SIZE; i++)
4729 pGTCacheEntry->aGTData[i] = RT_LE2H_U32(aGTDataTmp[i]);
4730 }
4731 else
4732 {
4733 /* Cache hit. Convert grain table block back to disk format, otherwise
4734 * the code below will write garbage for all but the updated entry. */
4735 for (unsigned i = 0; i < VMDK_GT_CACHELINE_SIZE; i++)
4736 aGTDataTmp[i] = RT_H2LE_U32(pGTCacheEntry->aGTData[i]);
4737 }
4738 pGrainAlloc->fGTUpdateNeeded = false;
4739 uGTBlockIndex = (uSector / pExtent->cSectorsPerGrain) % VMDK_GT_CACHELINE_SIZE;
4740 aGTDataTmp[uGTBlockIndex] = RT_H2LE_U32(VMDK_BYTE2SECTOR(pGrainAlloc->uGrainOffset));
4741 pGTCacheEntry->aGTData[uGTBlockIndex] = VMDK_BYTE2SECTOR(pGrainAlloc->uGrainOffset);
4742 /* Update grain table on disk. */
4743 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pExtent->pFile->pStorage,
4744 VMDK_SECTOR2BYTE(uGTSector) + (uGTBlock % (pExtent->cGTEntries / VMDK_GT_CACHELINE_SIZE)) * sizeof(aGTDataTmp),
4745 aGTDataTmp, sizeof(aGTDataTmp), pIoCtx,
4746 vmdkAllocGrainComplete, pGrainAlloc);
4747 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
4748 pGrainAlloc->cIoXfersPending++;
4749 else if (RT_FAILURE(rc))
4750 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: cannot write updated grain table in '%s'"), pExtent->pszFullname);
4751 if (pExtent->pRGD)
4752 {
4753 /* Update backup grain table on disk. */
4754 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pExtent->pFile->pStorage,
4755 VMDK_SECTOR2BYTE(uRGTSector) + (uGTBlock % (pExtent->cGTEntries / VMDK_GT_CACHELINE_SIZE)) * sizeof(aGTDataTmp),
4756 aGTDataTmp, sizeof(aGTDataTmp), pIoCtx,
4757 vmdkAllocGrainComplete, pGrainAlloc);
4758 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
4759 pGrainAlloc->cIoXfersPending++;
4760 else if (RT_FAILURE(rc))
4761 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: cannot write updated backup grain table in '%s'"), pExtent->pszFullname);
4762 }
4763#ifdef VBOX_WITH_VMDK_ESX
4764 if (RT_SUCCESS(rc) && pExtent->enmType == VMDKETYPE_ESX_SPARSE)
4765 {
4766 pExtent->uFreeSector = uGTSector + VMDK_BYTE2SECTOR(cbWrite);
4767 pExtent->fMetaDirty = true;
4768 }
4769#endif /* VBOX_WITH_VMDK_ESX */
4770
4771 LogFlowFunc(("leaving rc=%Rrc\n", rc));
4772
4773 return rc;
4774}
4775
4776/**
4777 * Internal - complete the grain allocation by updating disk grain table if required.
4778 */
4779static int vmdkAllocGrainComplete(void *pBackendData, PVDIOCTX pIoCtx, void *pvUser, int rcReq)
4780{
4781 RT_NOREF1(rcReq);
4782 int rc = VINF_SUCCESS;
4783 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
4784 PVMDKGRAINALLOCASYNC pGrainAlloc = (PVMDKGRAINALLOCASYNC)pvUser;
4785
4786 LogFlowFunc(("pBackendData=%#p pIoCtx=%#p pvUser=%#p rcReq=%Rrc\n",
4787 pBackendData, pIoCtx, pvUser, rcReq));
4788
4789 pGrainAlloc->cIoXfersPending--;
4790 if (!pGrainAlloc->cIoXfersPending && pGrainAlloc->fGTUpdateNeeded)
4791 rc = vmdkAllocGrainGTUpdate(pImage, pGrainAlloc->pExtent, pIoCtx, pGrainAlloc);
4792
4793 if (!pGrainAlloc->cIoXfersPending)
4794 {
4795 /* Grain allocation completed. */
4796 RTMemFree(pGrainAlloc);
4797 }
4798
4799 LogFlowFunc(("Leaving rc=%Rrc\n", rc));
4800 return rc;
4801}
4802
4803/**
4804 * Internal. Allocates a new grain table (if necessary).
4805 */
4806static int vmdkAllocGrain(PVMDKIMAGE pImage, PVMDKEXTENT pExtent, PVDIOCTX pIoCtx,
4807 uint64_t uSector, uint64_t cbWrite)
4808{
4809 PVMDKGTCACHE pCache = pImage->pGTCache; NOREF(pCache);
4810 uint64_t uGDIndex, uGTSector, uRGTSector;
4811 uint64_t uFileOffset;
4812 PVMDKGRAINALLOCASYNC pGrainAlloc = NULL;
4813 int rc;
4814
4815 LogFlowFunc(("pCache=%#p pExtent=%#p pIoCtx=%#p uSector=%llu cbWrite=%llu\n",
4816 pCache, pExtent, pIoCtx, uSector, cbWrite));
4817
4818 pGrainAlloc = (PVMDKGRAINALLOCASYNC)RTMemAllocZ(sizeof(VMDKGRAINALLOCASYNC));
4819 if (!pGrainAlloc)
4820 return VERR_NO_MEMORY;
4821
4822 pGrainAlloc->pExtent = pExtent;
4823 pGrainAlloc->uSector = uSector;
4824
4825 uGDIndex = uSector / pExtent->cSectorsPerGDE;
4826 if (uGDIndex >= pExtent->cGDEntries)
4827 {
4828 RTMemFree(pGrainAlloc);
4829 return VERR_OUT_OF_RANGE;
4830 }
4831 uGTSector = pExtent->pGD[uGDIndex];
4832 if (pExtent->pRGD)
4833 uRGTSector = pExtent->pRGD[uGDIndex];
4834 else
4835 uRGTSector = 0; /**< avoid compiler warning */
4836 if (!uGTSector)
4837 {
4838 LogFlow(("Allocating new grain table\n"));
4839
4840 /* There is no grain table referenced by this grain directory
4841 * entry. So there is absolutely no data in this area. Allocate
4842 * a new grain table and put the reference to it in the GDs. */
4843 uFileOffset = pExtent->uAppendPosition;
4844 if (!uFileOffset)
4845 {
4846 RTMemFree(pGrainAlloc);
4847 return VERR_INTERNAL_ERROR;
4848 }
4849 Assert(!(uFileOffset % 512));
4850
4851 uFileOffset = RT_ALIGN_64(uFileOffset, 512);
4852 uGTSector = VMDK_BYTE2SECTOR(uFileOffset);
4853
4854 /* Normally the grain table is preallocated for hosted sparse extents
4855 * that support more than 32 bit sector numbers. So this shouldn't
4856 * ever happen on a valid extent. */
4857 if (uGTSector > UINT32_MAX)
4858 {
4859 RTMemFree(pGrainAlloc);
4860 return VERR_VD_VMDK_INVALID_HEADER;
4861 }
4862
4863 /* Write grain table by writing the required number of grain table
4864 * cache chunks. Allocate memory dynamically here or we flood the
4865 * metadata cache with very small entries. */
4866 size_t cbGTDataTmp = pExtent->cGTEntries * sizeof(uint32_t);
4867 uint32_t *paGTDataTmp = (uint32_t *)RTMemTmpAllocZ(cbGTDataTmp);
4868
4869 if (!paGTDataTmp)
4870 {
4871 RTMemFree(pGrainAlloc);
4872 return VERR_NO_MEMORY;
4873 }
4874
4875 memset(paGTDataTmp, '\0', cbGTDataTmp);
4876 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pExtent->pFile->pStorage,
4877 VMDK_SECTOR2BYTE(uGTSector),
4878 paGTDataTmp, cbGTDataTmp, pIoCtx,
4879 vmdkAllocGrainComplete, pGrainAlloc);
4880 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
4881 pGrainAlloc->cIoXfersPending++;
4882 else if (RT_FAILURE(rc))
4883 {
4884 RTMemTmpFree(paGTDataTmp);
4885 RTMemFree(pGrainAlloc);
4886 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: cannot write grain table allocation in '%s'"), pExtent->pszFullname);
4887 }
4888 pExtent->uAppendPosition = RT_ALIGN_64( pExtent->uAppendPosition
4889 + cbGTDataTmp, 512);
4890
4891 if (pExtent->pRGD)
4892 {
4893 AssertReturn(!uRGTSector, VERR_VD_VMDK_INVALID_HEADER);
4894 uFileOffset = pExtent->uAppendPosition;
4895 if (!uFileOffset)
4896 return VERR_INTERNAL_ERROR;
4897 Assert(!(uFileOffset % 512));
4898 uRGTSector = VMDK_BYTE2SECTOR(uFileOffset);
4899
4900 /* Normally the redundant grain table is preallocated for hosted
4901 * sparse extents that support more than 32 bit sector numbers. So
4902 * this shouldn't ever happen on a valid extent. */
4903 if (uRGTSector > UINT32_MAX)
4904 {
4905 RTMemTmpFree(paGTDataTmp);
4906 return VERR_VD_VMDK_INVALID_HEADER;
4907 }
4908
4909 /* Write grain table by writing the required number of grain table
4910 * cache chunks. Allocate memory dynamically here or we flood the
4911 * metadata cache with very small entries. */
4912 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pExtent->pFile->pStorage,
4913 VMDK_SECTOR2BYTE(uRGTSector),
4914 paGTDataTmp, cbGTDataTmp, pIoCtx,
4915 vmdkAllocGrainComplete, pGrainAlloc);
4916 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
4917 pGrainAlloc->cIoXfersPending++;
4918 else if (RT_FAILURE(rc))
4919 {
4920 RTMemTmpFree(paGTDataTmp);
4921 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: cannot write backup grain table allocation in '%s'"), pExtent->pszFullname);
4922 }
4923
4924 pExtent->uAppendPosition = pExtent->uAppendPosition + cbGTDataTmp;
4925 }
4926
4927 RTMemTmpFree(paGTDataTmp);
4928
4929 /* Update the grain directory on disk (doing it before writing the
4930 * grain table will result in a garbled extent if the operation is
4931 * aborted for some reason. Otherwise the worst that can happen is
4932 * some unused sectors in the extent. */
4933 uint32_t uGTSectorLE = RT_H2LE_U64(uGTSector);
4934 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pExtent->pFile->pStorage,
4935 VMDK_SECTOR2BYTE(pExtent->uSectorGD) + uGDIndex * sizeof(uGTSectorLE),
4936 &uGTSectorLE, sizeof(uGTSectorLE), pIoCtx,
4937 vmdkAllocGrainComplete, pGrainAlloc);
4938 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
4939 pGrainAlloc->cIoXfersPending++;
4940 else if (RT_FAILURE(rc))
4941 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: cannot write grain directory entry in '%s'"), pExtent->pszFullname);
4942 if (pExtent->pRGD)
4943 {
4944 uint32_t uRGTSectorLE = RT_H2LE_U64(uRGTSector);
4945 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pExtent->pFile->pStorage,
4946 VMDK_SECTOR2BYTE(pExtent->uSectorRGD) + uGDIndex * sizeof(uGTSectorLE),
4947 &uRGTSectorLE, sizeof(uRGTSectorLE), pIoCtx,
4948 vmdkAllocGrainComplete, pGrainAlloc);
4949 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
4950 pGrainAlloc->cIoXfersPending++;
4951 else if (RT_FAILURE(rc))
4952 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: cannot write backup grain directory entry in '%s'"), pExtent->pszFullname);
4953 }
4954
4955 /* As the final step update the in-memory copy of the GDs. */
4956 pExtent->pGD[uGDIndex] = uGTSector;
4957 if (pExtent->pRGD)
4958 pExtent->pRGD[uGDIndex] = uRGTSector;
4959 }
4960
4961 LogFlow(("uGTSector=%llu uRGTSector=%llu\n", uGTSector, uRGTSector));
4962 pGrainAlloc->uGTSector = uGTSector;
4963 pGrainAlloc->uRGTSector = uRGTSector;
4964
4965 uFileOffset = pExtent->uAppendPosition;
4966 if (!uFileOffset)
4967 return VERR_INTERNAL_ERROR;
4968 Assert(!(uFileOffset % 512));
4969
4970 pGrainAlloc->uGrainOffset = uFileOffset;
4971
4972 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
4973 {
4974 AssertMsgReturn(vdIfIoIntIoCtxIsSynchronous(pImage->pIfIo, pIoCtx),
4975 ("Accesses to stream optimized images must be synchronous\n"),
4976 VERR_INVALID_STATE);
4977
4978 if (cbWrite != VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain))
4979 return vdIfError(pImage->pIfError, VERR_INTERNAL_ERROR, RT_SRC_POS, N_("VMDK: not enough data for a compressed data block in '%s'"), pExtent->pszFullname);
4980
4981 /* Invalidate cache, just in case some code incorrectly allows mixing
4982 * of reads and writes. Normally shouldn't be needed. */
4983 pExtent->uGrainSectorAbs = 0;
4984
4985 /* Write compressed data block and the markers. */
4986 uint32_t cbGrain = 0;
4987 size_t cbSeg = 0;
4988 RTSGSEG Segment;
4989 unsigned cSegments = 1;
4990
4991 cbSeg = vdIfIoIntIoCtxSegArrayCreate(pImage->pIfIo, pIoCtx, &Segment,
4992 &cSegments, cbWrite);
4993 Assert(cbSeg == cbWrite);
4994
4995 rc = vmdkFileDeflateSync(pImage, pExtent, uFileOffset,
4996 Segment.pvSeg, cbWrite, uSector, &cbGrain);
4997 if (RT_FAILURE(rc))
4998 {
4999 AssertRC(rc);
5000 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: cannot write allocated compressed data block in '%s'"), pExtent->pszFullname);
5001 }
5002 pExtent->uLastGrainAccess = uSector / pExtent->cSectorsPerGrain;
5003 pExtent->uAppendPosition += cbGrain;
5004 }
5005 else
5006 {
5007 /* Write the data. Always a full grain, or we're in big trouble. */
5008 rc = vdIfIoIntFileWriteUser(pImage->pIfIo, pExtent->pFile->pStorage,
5009 uFileOffset, pIoCtx, cbWrite,
5010 vmdkAllocGrainComplete, pGrainAlloc);
5011 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
5012 pGrainAlloc->cIoXfersPending++;
5013 else if (RT_FAILURE(rc))
5014 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: cannot write allocated data block in '%s'"), pExtent->pszFullname);
5015
5016 pExtent->uAppendPosition += cbWrite;
5017 }
5018
5019 rc = vmdkAllocGrainGTUpdate(pImage, pExtent, pIoCtx, pGrainAlloc);
5020
5021 if (!pGrainAlloc->cIoXfersPending)
5022 {
5023 /* Grain allocation completed. */
5024 RTMemFree(pGrainAlloc);
5025 }
5026
5027 LogFlowFunc(("leaving rc=%Rrc\n", rc));
5028
5029 return rc;
5030}
5031
5032/**
5033 * Internal. Reads the contents by sequentially going over the compressed
5034 * grains (hoping that they are in sequence).
5035 */
5036static int vmdkStreamReadSequential(PVMDKIMAGE pImage, PVMDKEXTENT pExtent,
5037 uint64_t uSector, PVDIOCTX pIoCtx,
5038 uint64_t cbRead)
5039{
5040 int rc;
5041
5042 LogFlowFunc(("pImage=%#p pExtent=%#p uSector=%llu pIoCtx=%#p cbRead=%llu\n",
5043 pImage, pExtent, uSector, pIoCtx, cbRead));
5044
5045 AssertMsgReturn(vdIfIoIntIoCtxIsSynchronous(pImage->pIfIo, pIoCtx),
5046 ("Async I/O not supported for sequential stream optimized images\n"),
5047 VERR_INVALID_STATE);
5048
5049 /* Do not allow to go back. */
5050 uint32_t uGrain = uSector / pExtent->cSectorsPerGrain;
5051 if (uGrain < pExtent->uLastGrainAccess)
5052 return VERR_VD_VMDK_INVALID_STATE;
5053 pExtent->uLastGrainAccess = uGrain;
5054
5055 /* After a previous error do not attempt to recover, as it would need
5056 * seeking (in the general case backwards which is forbidden). */
5057 if (!pExtent->uGrainSectorAbs)
5058 return VERR_VD_VMDK_INVALID_STATE;
5059
5060 /* Check if we need to read something from the image or if what we have
5061 * in the buffer is good to fulfill the request. */
5062 if (!pExtent->cbGrainStreamRead || uGrain > pExtent->uGrain)
5063 {
5064 uint32_t uGrainSectorAbs = pExtent->uGrainSectorAbs
5065 + VMDK_BYTE2SECTOR(pExtent->cbGrainStreamRead);
5066
5067 /* Get the marker from the next data block - and skip everything which
5068 * is not a compressed grain. If it's a compressed grain which is for
5069 * the requested sector (or after), read it. */
5070 VMDKMARKER Marker;
5071 do
5072 {
5073 RT_ZERO(Marker);
5074 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pExtent->pFile->pStorage,
5075 VMDK_SECTOR2BYTE(uGrainSectorAbs),
5076 &Marker, RT_OFFSETOF(VMDKMARKER, uType));
5077 if (RT_FAILURE(rc))
5078 return rc;
5079 Marker.uSector = RT_LE2H_U64(Marker.uSector);
5080 Marker.cbSize = RT_LE2H_U32(Marker.cbSize);
5081
5082 if (Marker.cbSize == 0)
5083 {
5084 /* A marker for something else than a compressed grain. */
5085 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pExtent->pFile->pStorage,
5086 VMDK_SECTOR2BYTE(uGrainSectorAbs)
5087 + RT_OFFSETOF(VMDKMARKER, uType),
5088 &Marker.uType, sizeof(Marker.uType));
5089 if (RT_FAILURE(rc))
5090 return rc;
5091 Marker.uType = RT_LE2H_U32(Marker.uType);
5092 switch (Marker.uType)
5093 {
5094 case VMDK_MARKER_EOS:
5095 uGrainSectorAbs++;
5096 /* Read (or mostly skip) to the end of file. Uses the
5097 * Marker (LBA sector) as it is unused anyway. This
5098 * makes sure that really everything is read in the
5099 * success case. If this read fails it means the image
5100 * is truncated, but this is harmless so ignore. */
5101 vdIfIoIntFileReadSync(pImage->pIfIo, pExtent->pFile->pStorage,
5102 VMDK_SECTOR2BYTE(uGrainSectorAbs)
5103 + 511,
5104 &Marker.uSector, 1);
5105 break;
5106 case VMDK_MARKER_GT:
5107 uGrainSectorAbs += 1 + VMDK_BYTE2SECTOR(pExtent->cGTEntries * sizeof(uint32_t));
5108 break;
5109 case VMDK_MARKER_GD:
5110 uGrainSectorAbs += 1 + VMDK_BYTE2SECTOR(RT_ALIGN(pExtent->cGDEntries * sizeof(uint32_t), 512));
5111 break;
5112 case VMDK_MARKER_FOOTER:
5113 uGrainSectorAbs += 2;
5114 break;
5115 case VMDK_MARKER_UNSPECIFIED:
5116 /* Skip over the contents of the unspecified marker
5117 * type 4 which exists in some vSphere created files. */
5118 /** @todo figure out what the payload means. */
5119 uGrainSectorAbs += 1;
5120 break;
5121 default:
5122 AssertMsgFailed(("VMDK: corrupted marker, type=%#x\n", Marker.uType));
5123 pExtent->uGrainSectorAbs = 0;
5124 return VERR_VD_VMDK_INVALID_STATE;
5125 }
5126 pExtent->cbGrainStreamRead = 0;
5127 }
5128 else
5129 {
5130 /* A compressed grain marker. If it is at/after what we're
5131 * interested in read and decompress data. */
5132 if (uSector > Marker.uSector + pExtent->cSectorsPerGrain)
5133 {
5134 uGrainSectorAbs += VMDK_BYTE2SECTOR(RT_ALIGN(Marker.cbSize + RT_OFFSETOF(VMDKMARKER, uType), 512));
5135 continue;
5136 }
5137 uint64_t uLBA = 0;
5138 uint32_t cbGrainStreamRead = 0;
5139 rc = vmdkFileInflateSync(pImage, pExtent,
5140 VMDK_SECTOR2BYTE(uGrainSectorAbs),
5141 pExtent->pvGrain,
5142 VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain),
5143 &Marker, &uLBA, &cbGrainStreamRead);
5144 if (RT_FAILURE(rc))
5145 {
5146 pExtent->uGrainSectorAbs = 0;
5147 return rc;
5148 }
5149 if ( pExtent->uGrain
5150 && uLBA / pExtent->cSectorsPerGrain <= pExtent->uGrain)
5151 {
5152 pExtent->uGrainSectorAbs = 0;
5153 return VERR_VD_VMDK_INVALID_STATE;
5154 }
5155 pExtent->uGrain = uLBA / pExtent->cSectorsPerGrain;
5156 pExtent->cbGrainStreamRead = cbGrainStreamRead;
5157 break;
5158 }
5159 } while (Marker.uType != VMDK_MARKER_EOS);
5160
5161 pExtent->uGrainSectorAbs = uGrainSectorAbs;
5162
5163 if (!pExtent->cbGrainStreamRead && Marker.uType == VMDK_MARKER_EOS)
5164 {
5165 pExtent->uGrain = UINT32_MAX;
5166 /* Must set a non-zero value for pExtent->cbGrainStreamRead or
5167 * the next read would try to get more data, and we're at EOF. */
5168 pExtent->cbGrainStreamRead = 1;
5169 }
5170 }
5171
5172 if (pExtent->uGrain > uSector / pExtent->cSectorsPerGrain)
5173 {
5174 /* The next data block we have is not for this area, so just return
5175 * that there is no data. */
5176 LogFlowFunc(("returns VERR_VD_BLOCK_FREE\n"));
5177 return VERR_VD_BLOCK_FREE;
5178 }
5179
5180 uint32_t uSectorInGrain = uSector % pExtent->cSectorsPerGrain;
5181 vdIfIoIntIoCtxCopyTo(pImage->pIfIo, pIoCtx,
5182 (uint8_t *)pExtent->pvGrain + VMDK_SECTOR2BYTE(uSectorInGrain),
5183 cbRead);
5184 LogFlowFunc(("returns VINF_SUCCESS\n"));
5185 return VINF_SUCCESS;
5186}
5187
5188/**
5189 * Replaces a fragment of a string with the specified string.
5190 *
5191 * @returns Pointer to the allocated UTF-8 string.
5192 * @param pszWhere UTF-8 string to search in.
5193 * @param pszWhat UTF-8 string to search for.
5194 * @param pszByWhat UTF-8 string to replace the found string with.
5195 */
5196static char *vmdkStrReplace(const char *pszWhere, const char *pszWhat,
5197 const char *pszByWhat)
5198{
5199 AssertPtr(pszWhere);
5200 AssertPtr(pszWhat);
5201 AssertPtr(pszByWhat);
5202 const char *pszFoundStr = strstr(pszWhere, pszWhat);
5203 if (!pszFoundStr)
5204 return NULL;
5205 size_t cFinal = strlen(pszWhere) + 1 + strlen(pszByWhat) - strlen(pszWhat);
5206 char *pszNewStr = (char *)RTMemAlloc(cFinal);
5207 if (pszNewStr)
5208 {
5209 char *pszTmp = pszNewStr;
5210 memcpy(pszTmp, pszWhere, pszFoundStr - pszWhere);
5211 pszTmp += pszFoundStr - pszWhere;
5212 memcpy(pszTmp, pszByWhat, strlen(pszByWhat));
5213 pszTmp += strlen(pszByWhat);
5214 strcpy(pszTmp, pszFoundStr + strlen(pszWhat));
5215 }
5216 return pszNewStr;
5217}
5218
5219
5220/** @copydoc VBOXHDDBACKEND::pfnCheckIfValid */
5221static DECLCALLBACK(int) vmdkCheckIfValid(const char *pszFilename, PVDINTERFACE pVDIfsDisk,
5222 PVDINTERFACE pVDIfsImage, VDTYPE *penmType)
5223{
5224 LogFlowFunc(("pszFilename=\"%s\" pVDIfsDisk=%#p pVDIfsImage=%#p penmType=%#p\n",
5225 pszFilename, pVDIfsDisk, pVDIfsImage, penmType));
5226 int rc = VINF_SUCCESS;
5227 PVMDKIMAGE pImage;
5228
5229 if ( !pszFilename
5230 || !*pszFilename
5231 || strchr(pszFilename, '"'))
5232 {
5233 rc = VERR_INVALID_PARAMETER;
5234 goto out;
5235 }
5236
5237 pImage = (PVMDKIMAGE)RTMemAllocZ(sizeof(VMDKIMAGE));
5238 if (!pImage)
5239 {
5240 rc = VERR_NO_MEMORY;
5241 goto out;
5242 }
5243 pImage->pszFilename = pszFilename;
5244 pImage->pFile = NULL;
5245 pImage->pExtents = NULL;
5246 pImage->pFiles = NULL;
5247 pImage->pGTCache = NULL;
5248 pImage->pDescData = NULL;
5249 pImage->pVDIfsDisk = pVDIfsDisk;
5250 pImage->pVDIfsImage = pVDIfsImage;
5251 /** @todo speed up this test open (VD_OPEN_FLAGS_INFO) by skipping as
5252 * much as possible in vmdkOpenImage. */
5253 rc = vmdkOpenImage(pImage, VD_OPEN_FLAGS_INFO | VD_OPEN_FLAGS_READONLY);
5254 vmdkFreeImage(pImage, false);
5255 RTMemFree(pImage);
5256
5257 if (RT_SUCCESS(rc))
5258 *penmType = VDTYPE_HDD;
5259
5260out:
5261 LogFlowFunc(("returns %Rrc\n", rc));
5262 return rc;
5263}
5264
5265/** @copydoc VBOXHDDBACKEND::pfnOpen */
5266static DECLCALLBACK(int) vmdkOpen(const char *pszFilename, unsigned uOpenFlags,
5267 PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
5268 VDTYPE enmType, void **ppBackendData)
5269{
5270 LogFlowFunc(("pszFilename=\"%s\" uOpenFlags=%#x pVDIfsDisk=%#p pVDIfsImage=%#p enmType=%u ppBackendData=%#p\n", pszFilename, uOpenFlags, pVDIfsDisk, pVDIfsImage, enmType, ppBackendData));
5271 int rc;
5272 PVMDKIMAGE pImage;
5273
5274 NOREF(enmType); /**< @todo r=klaus make use of the type info. */
5275
5276 /* Check open flags. All valid flags are supported. */
5277 if (uOpenFlags & ~VD_OPEN_FLAGS_MASK)
5278 {
5279 rc = VERR_INVALID_PARAMETER;
5280 goto out;
5281 }
5282
5283 /* Check remaining arguments. */
5284 if ( !VALID_PTR(pszFilename)
5285 || !*pszFilename
5286 || strchr(pszFilename, '"'))
5287 {
5288 rc = VERR_INVALID_PARAMETER;
5289 goto out;
5290 }
5291
5292 pImage = (PVMDKIMAGE)RTMemAllocZ(sizeof(VMDKIMAGE));
5293 if (!pImage)
5294 {
5295 rc = VERR_NO_MEMORY;
5296 goto out;
5297 }
5298 pImage->pszFilename = pszFilename;
5299 pImage->pFile = NULL;
5300 pImage->pExtents = NULL;
5301 pImage->pFiles = NULL;
5302 pImage->pGTCache = NULL;
5303 pImage->pDescData = NULL;
5304 pImage->pVDIfsDisk = pVDIfsDisk;
5305 pImage->pVDIfsImage = pVDIfsImage;
5306
5307 rc = vmdkOpenImage(pImage, uOpenFlags);
5308 if (RT_SUCCESS(rc))
5309 *ppBackendData = pImage;
5310 else
5311 RTMemFree(pImage);
5312
5313out:
5314 LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
5315 return rc;
5316}
5317
5318/** @copydoc VBOXHDDBACKEND::pfnCreate */
5319static DECLCALLBACK(int) vmdkCreate(const char *pszFilename, uint64_t cbSize,
5320 unsigned uImageFlags, const char *pszComment,
5321 PCVDGEOMETRY pPCHSGeometry, PCVDGEOMETRY pLCHSGeometry,
5322 PCRTUUID pUuid, unsigned uOpenFlags,
5323 unsigned uPercentStart, unsigned uPercentSpan,
5324 PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
5325 PVDINTERFACE pVDIfsOperation, VDTYPE enmType,
5326 void **ppBackendData)
5327{
5328 LogFlowFunc(("pszFilename=\"%s\" cbSize=%llu uImageFlags=%#x pszComment=\"%s\" pPCHSGeometry=%#p pLCHSGeometry=%#p Uuid=%RTuuid uOpenFlags=%#x uPercentStart=%u uPercentSpan=%u pVDIfsDisk=%#p pVDIfsImage=%#p pVDIfsOperation=%#p enmType=%u ppBackendData=%#p\n",
5329 pszFilename, cbSize, uImageFlags, pszComment, pPCHSGeometry, pLCHSGeometry, pUuid, uOpenFlags, uPercentStart, uPercentSpan, pVDIfsDisk, pVDIfsImage, pVDIfsOperation, enmType, ppBackendData));
5330 int rc;
5331 PVMDKIMAGE pImage;
5332
5333 PFNVDPROGRESS pfnProgress = NULL;
5334 void *pvUser = NULL;
5335 PVDINTERFACEPROGRESS pIfProgress = VDIfProgressGet(pVDIfsOperation);
5336 if (pIfProgress)
5337 {
5338 pfnProgress = pIfProgress->pfnProgress;
5339 pvUser = pIfProgress->Core.pvUser;
5340 }
5341
5342 /* Check the image flags. */
5343 if ((uImageFlags & ~VD_VMDK_IMAGE_FLAGS_MASK) != 0)
5344 {
5345 rc = VERR_VD_INVALID_TYPE;
5346 goto out;
5347 }
5348
5349 /* Check the VD container type. */
5350 if (enmType != VDTYPE_HDD)
5351 {
5352 rc = VERR_VD_INVALID_TYPE;
5353 goto out;
5354 }
5355
5356 /* Check open flags. All valid flags are supported. */
5357 if (uOpenFlags & ~VD_OPEN_FLAGS_MASK)
5358 {
5359 rc = VERR_INVALID_PARAMETER;
5360 goto out;
5361 }
5362
5363 /* Check size. Maximum 256TB-64K for sparse images, otherwise unlimited. */
5364 if ( !cbSize
5365 || (!(uImageFlags & VD_IMAGE_FLAGS_FIXED) && cbSize >= _1T * 256 - _64K))
5366 {
5367 rc = VERR_VD_INVALID_SIZE;
5368 goto out;
5369 }
5370
5371 /* Check remaining arguments. */
5372 if ( !VALID_PTR(pszFilename)
5373 || !*pszFilename
5374 || strchr(pszFilename, '"')
5375 || !VALID_PTR(pPCHSGeometry)
5376 || !VALID_PTR(pLCHSGeometry)
5377#ifndef VBOX_WITH_VMDK_ESX
5378 || ( uImageFlags & VD_VMDK_IMAGE_FLAGS_ESX
5379 && !(uImageFlags & VD_IMAGE_FLAGS_FIXED))
5380#endif
5381 || ( (uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
5382 && (uImageFlags & ~(VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED | VD_IMAGE_FLAGS_DIFF))))
5383 {
5384 rc = VERR_INVALID_PARAMETER;
5385 goto out;
5386 }
5387
5388 pImage = (PVMDKIMAGE)RTMemAllocZ(sizeof(VMDKIMAGE));
5389 if (!pImage)
5390 {
5391 rc = VERR_NO_MEMORY;
5392 goto out;
5393 }
5394 pImage->pszFilename = pszFilename;
5395 pImage->pFile = NULL;
5396 pImage->pExtents = NULL;
5397 pImage->pFiles = NULL;
5398 pImage->pGTCache = NULL;
5399 pImage->pDescData = NULL;
5400 pImage->pVDIfsDisk = pVDIfsDisk;
5401 pImage->pVDIfsImage = pVDIfsImage;
5402 /* Descriptors for split images can be pretty large, especially if the
5403 * filename is long. So prepare for the worst, and allocate quite some
5404 * memory for the descriptor in this case. */
5405 if (uImageFlags & VD_VMDK_IMAGE_FLAGS_SPLIT_2G)
5406 pImage->cbDescAlloc = VMDK_SECTOR2BYTE(200);
5407 else
5408 pImage->cbDescAlloc = VMDK_SECTOR2BYTE(20);
5409 pImage->pDescData = (char *)RTMemAllocZ(pImage->cbDescAlloc);
5410 if (!pImage->pDescData)
5411 {
5412 RTMemFree(pImage);
5413 rc = VERR_NO_MEMORY;
5414 goto out;
5415 }
5416
5417 rc = vmdkCreateImage(pImage, cbSize, uImageFlags, pszComment,
5418 pPCHSGeometry, pLCHSGeometry, pUuid,
5419 pfnProgress, pvUser, uPercentStart, uPercentSpan);
5420 if (RT_SUCCESS(rc))
5421 {
5422 /* So far the image is opened in read/write mode. Make sure the
5423 * image is opened in read-only mode if the caller requested that. */
5424 if (uOpenFlags & VD_OPEN_FLAGS_READONLY)
5425 {
5426 vmdkFreeImage(pImage, false);
5427 rc = vmdkOpenImage(pImage, uOpenFlags);
5428 if (RT_FAILURE(rc))
5429 goto out;
5430 }
5431 *ppBackendData = pImage;
5432 }
5433 else
5434 {
5435 RTMemFree(pImage->pDescData);
5436 RTMemFree(pImage);
5437 }
5438
5439out:
5440 LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
5441 return rc;
5442}
5443
5444/** @copydoc VBOXHDDBACKEND::pfnRename */
5445static DECLCALLBACK(int) vmdkRename(void *pBackendData, const char *pszFilename)
5446{
5447 LogFlowFunc(("pBackendData=%#p pszFilename=%#p\n", pBackendData, pszFilename));
5448
5449 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5450 int rc = VINF_SUCCESS;
5451 char **apszOldName = NULL;
5452 char **apszNewName = NULL;
5453 char **apszNewLines = NULL;
5454 char *pszOldDescName = NULL;
5455 bool fImageFreed = false;
5456 bool fEmbeddedDesc = false;
5457 unsigned cExtents = 0;
5458 char *pszNewBaseName = NULL;
5459 char *pszOldBaseName = NULL;
5460 char *pszNewFullName = NULL;
5461 char *pszOldFullName = NULL;
5462 const char *pszOldImageName;
5463 unsigned i, line;
5464 VMDKDESCRIPTOR DescriptorCopy;
5465 VMDKEXTENT ExtentCopy;
5466
5467 memset(&DescriptorCopy, 0, sizeof(DescriptorCopy));
5468
5469 /* Check arguments. */
5470 if ( !pImage
5471 || (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_RAWDISK)
5472 || !VALID_PTR(pszFilename)
5473 || !*pszFilename)
5474 {
5475 rc = VERR_INVALID_PARAMETER;
5476 goto out;
5477 }
5478
5479 cExtents = pImage->cExtents;
5480
5481 /*
5482 * Allocate an array to store both old and new names of renamed files
5483 * in case we have to roll back the changes. Arrays are initialized
5484 * with zeros. We actually save stuff when and if we change it.
5485 */
5486 apszOldName = (char **)RTMemTmpAllocZ((cExtents + 1) * sizeof(char*));
5487 apszNewName = (char **)RTMemTmpAllocZ((cExtents + 1) * sizeof(char*));
5488 apszNewLines = (char **)RTMemTmpAllocZ((cExtents) * sizeof(char*));
5489 if (!apszOldName || !apszNewName || !apszNewLines)
5490 {
5491 rc = VERR_NO_MEMORY;
5492 goto out;
5493 }
5494
5495 /* Save the descriptor size and position. */
5496 if (pImage->pDescData)
5497 {
5498 /* Separate descriptor file. */
5499 fEmbeddedDesc = false;
5500 }
5501 else
5502 {
5503 /* Embedded descriptor file. */
5504 ExtentCopy = pImage->pExtents[0];
5505 fEmbeddedDesc = true;
5506 }
5507 /* Save the descriptor content. */
5508 DescriptorCopy.cLines = pImage->Descriptor.cLines;
5509 for (i = 0; i < DescriptorCopy.cLines; i++)
5510 {
5511 DescriptorCopy.aLines[i] = RTStrDup(pImage->Descriptor.aLines[i]);
5512 if (!DescriptorCopy.aLines[i])
5513 {
5514 rc = VERR_NO_MEMORY;
5515 goto out;
5516 }
5517 }
5518
5519 /* Prepare both old and new base names used for string replacement. */
5520 pszNewBaseName = RTStrDup(RTPathFilename(pszFilename));
5521 RTPathStripSuffix(pszNewBaseName);
5522 pszOldBaseName = RTStrDup(RTPathFilename(pImage->pszFilename));
5523 RTPathStripSuffix(pszOldBaseName);
5524 /* Prepare both old and new full names used for string replacement. */
5525 pszNewFullName = RTStrDup(pszFilename);
5526 RTPathStripSuffix(pszNewFullName);
5527 pszOldFullName = RTStrDup(pImage->pszFilename);
5528 RTPathStripSuffix(pszOldFullName);
5529
5530 /* --- Up to this point we have not done any damage yet. --- */
5531
5532 /* Save the old name for easy access to the old descriptor file. */
5533 pszOldDescName = RTStrDup(pImage->pszFilename);
5534 /* Save old image name. */
5535 pszOldImageName = pImage->pszFilename;
5536
5537 /* Update the descriptor with modified extent names. */
5538 for (i = 0, line = pImage->Descriptor.uFirstExtent;
5539 i < cExtents;
5540 i++, line = pImage->Descriptor.aNextLines[line])
5541 {
5542 /* Assume that vmdkStrReplace will fail. */
5543 rc = VERR_NO_MEMORY;
5544 /* Update the descriptor. */
5545 apszNewLines[i] = vmdkStrReplace(pImage->Descriptor.aLines[line],
5546 pszOldBaseName, pszNewBaseName);
5547 if (!apszNewLines[i])
5548 goto rollback;
5549 pImage->Descriptor.aLines[line] = apszNewLines[i];
5550 }
5551 /* Make sure the descriptor gets written back. */
5552 pImage->Descriptor.fDirty = true;
5553 /* Flush the descriptor now, in case it is embedded. */
5554 vmdkFlushImage(pImage, NULL);
5555
5556 /* Close and rename/move extents. */
5557 for (i = 0; i < cExtents; i++)
5558 {
5559 PVMDKEXTENT pExtent = &pImage->pExtents[i];
5560 /* Compose new name for the extent. */
5561 apszNewName[i] = vmdkStrReplace(pExtent->pszFullname,
5562 pszOldFullName, pszNewFullName);
5563 if (!apszNewName[i])
5564 goto rollback;
5565 /* Close the extent file. */
5566 rc = vmdkFileClose(pImage, &pExtent->pFile, false);
5567 if (RT_FAILURE(rc))
5568 goto rollback;
5569
5570 /* Rename the extent file. */
5571 rc = vdIfIoIntFileMove(pImage->pIfIo, pExtent->pszFullname, apszNewName[i], 0);
5572 if (RT_FAILURE(rc))
5573 goto rollback;
5574 /* Remember the old name. */
5575 apszOldName[i] = RTStrDup(pExtent->pszFullname);
5576 }
5577 /* Release all old stuff. */
5578 rc = vmdkFreeImage(pImage, false);
5579 if (RT_FAILURE(rc))
5580 goto rollback;
5581
5582 fImageFreed = true;
5583
5584 /* Last elements of new/old name arrays are intended for
5585 * storing descriptor's names.
5586 */
5587 apszNewName[cExtents] = RTStrDup(pszFilename);
5588 /* Rename the descriptor file if it's separate. */
5589 if (!fEmbeddedDesc)
5590 {
5591 rc = vdIfIoIntFileMove(pImage->pIfIo, pImage->pszFilename, apszNewName[cExtents], 0);
5592 if (RT_FAILURE(rc))
5593 goto rollback;
5594 /* Save old name only if we may need to change it back. */
5595 apszOldName[cExtents] = RTStrDup(pszFilename);
5596 }
5597
5598 /* Update pImage with the new information. */
5599 pImage->pszFilename = pszFilename;
5600
5601 /* Open the new image. */
5602 rc = vmdkOpenImage(pImage, pImage->uOpenFlags);
5603 if (RT_SUCCESS(rc))
5604 goto out;
5605
5606rollback:
5607 /* Roll back all changes in case of failure. */
5608 if (RT_FAILURE(rc))
5609 {
5610 int rrc;
5611 if (!fImageFreed)
5612 {
5613 /*
5614 * Some extents may have been closed, close the rest. We will
5615 * re-open the whole thing later.
5616 */
5617 vmdkFreeImage(pImage, false);
5618 }
5619 /* Rename files back. */
5620 for (i = 0; i <= cExtents; i++)
5621 {
5622 if (apszOldName[i])
5623 {
5624 rrc = vdIfIoIntFileMove(pImage->pIfIo, apszNewName[i], apszOldName[i], 0);
5625 AssertRC(rrc);
5626 }
5627 }
5628 /* Restore the old descriptor. */
5629 PVMDKFILE pFile;
5630 rrc = vmdkFileOpen(pImage, &pFile, pszOldDescName,
5631 VDOpenFlagsToFileOpenFlags(VD_OPEN_FLAGS_NORMAL,
5632 false /* fCreate */));
5633 AssertRC(rrc);
5634 if (fEmbeddedDesc)
5635 {
5636 ExtentCopy.pFile = pFile;
5637 pImage->pExtents = &ExtentCopy;
5638 }
5639 else
5640 {
5641 /* Shouldn't be null for separate descriptor.
5642 * There will be no access to the actual content.
5643 */
5644 pImage->pDescData = pszOldDescName;
5645 pImage->pFile = pFile;
5646 }
5647 pImage->Descriptor = DescriptorCopy;
5648 vmdkWriteDescriptor(pImage, NULL);
5649 vmdkFileClose(pImage, &pFile, false);
5650 /* Get rid of the stuff we implanted. */
5651 pImage->pExtents = NULL;
5652 pImage->pFile = NULL;
5653 pImage->pDescData = NULL;
5654 /* Re-open the image back. */
5655 pImage->pszFilename = pszOldImageName;
5656 rrc = vmdkOpenImage(pImage, pImage->uOpenFlags);
5657 AssertRC(rrc);
5658 }
5659
5660out:
5661 for (i = 0; i < DescriptorCopy.cLines; i++)
5662 if (DescriptorCopy.aLines[i])
5663 RTStrFree(DescriptorCopy.aLines[i]);
5664 if (apszOldName)
5665 {
5666 for (i = 0; i <= cExtents; i++)
5667 if (apszOldName[i])
5668 RTStrFree(apszOldName[i]);
5669 RTMemTmpFree(apszOldName);
5670 }
5671 if (apszNewName)
5672 {
5673 for (i = 0; i <= cExtents; i++)
5674 if (apszNewName[i])
5675 RTStrFree(apszNewName[i]);
5676 RTMemTmpFree(apszNewName);
5677 }
5678 if (apszNewLines)
5679 {
5680 for (i = 0; i < cExtents; i++)
5681 if (apszNewLines[i])
5682 RTStrFree(apszNewLines[i]);
5683 RTMemTmpFree(apszNewLines);
5684 }
5685 if (pszOldDescName)
5686 RTStrFree(pszOldDescName);
5687 if (pszOldBaseName)
5688 RTStrFree(pszOldBaseName);
5689 if (pszNewBaseName)
5690 RTStrFree(pszNewBaseName);
5691 if (pszOldFullName)
5692 RTStrFree(pszOldFullName);
5693 if (pszNewFullName)
5694 RTStrFree(pszNewFullName);
5695 LogFlowFunc(("returns %Rrc\n", rc));
5696 return rc;
5697}
5698
5699/** @copydoc VBOXHDDBACKEND::pfnClose */
5700static DECLCALLBACK(int) vmdkClose(void *pBackendData, bool fDelete)
5701{
5702 LogFlowFunc(("pBackendData=%#p fDelete=%d\n", pBackendData, fDelete));
5703 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5704 int rc;
5705
5706 rc = vmdkFreeImage(pImage, fDelete);
5707 RTMemFree(pImage);
5708
5709 LogFlowFunc(("returns %Rrc\n", rc));
5710 return rc;
5711}
5712
5713/** @copydoc VBOXHDDBACKEND::pfnRead */
5714static DECLCALLBACK(int) vmdkRead(void *pBackendData, uint64_t uOffset, size_t cbToRead,
5715 PVDIOCTX pIoCtx, size_t *pcbActuallyRead)
5716{
5717 LogFlowFunc(("pBackendData=%#p uOffset=%llu pIoCtx=%#p cbToRead=%zu pcbActuallyRead=%#p\n",
5718 pBackendData, uOffset, pIoCtx, cbToRead, pcbActuallyRead));
5719 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5720 PVMDKEXTENT pExtent;
5721 uint64_t uSectorExtentRel;
5722 uint64_t uSectorExtentAbs;
5723 int rc;
5724
5725 AssertPtr(pImage);
5726 Assert(uOffset % 512 == 0);
5727 Assert(cbToRead % 512 == 0);
5728
5729 if ( uOffset + cbToRead > pImage->cbSize
5730 || cbToRead == 0)
5731 {
5732 rc = VERR_INVALID_PARAMETER;
5733 goto out;
5734 }
5735
5736 rc = vmdkFindExtent(pImage, VMDK_BYTE2SECTOR(uOffset),
5737 &pExtent, &uSectorExtentRel);
5738 if (RT_FAILURE(rc))
5739 goto out;
5740
5741 /* Check access permissions as defined in the extent descriptor. */
5742 if (pExtent->enmAccess == VMDKACCESS_NOACCESS)
5743 {
5744 rc = VERR_VD_VMDK_INVALID_STATE;
5745 goto out;
5746 }
5747
5748 /* Clip read range to remain in this extent. */
5749 cbToRead = RT_MIN(cbToRead, VMDK_SECTOR2BYTE(pExtent->uSectorOffset + pExtent->cNominalSectors - uSectorExtentRel));
5750
5751 /* Handle the read according to the current extent type. */
5752 switch (pExtent->enmType)
5753 {
5754 case VMDKETYPE_HOSTED_SPARSE:
5755#ifdef VBOX_WITH_VMDK_ESX
5756 case VMDKETYPE_ESX_SPARSE:
5757#endif /* VBOX_WITH_VMDK_ESX */
5758 rc = vmdkGetSector(pImage, pIoCtx, pExtent, uSectorExtentRel, &uSectorExtentAbs);
5759 if (RT_FAILURE(rc))
5760 goto out;
5761 /* Clip read range to at most the rest of the grain. */
5762 cbToRead = RT_MIN(cbToRead, VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain - uSectorExtentRel % pExtent->cSectorsPerGrain));
5763 Assert(!(cbToRead % 512));
5764 if (uSectorExtentAbs == 0)
5765 {
5766 if ( !(pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
5767 || !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
5768 || !(pImage->uOpenFlags & VD_OPEN_FLAGS_SEQUENTIAL))
5769 rc = VERR_VD_BLOCK_FREE;
5770 else
5771 rc = vmdkStreamReadSequential(pImage, pExtent,
5772 uSectorExtentRel,
5773 pIoCtx, cbToRead);
5774 }
5775 else
5776 {
5777 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
5778 {
5779 AssertMsg(vdIfIoIntIoCtxIsSynchronous(pImage->pIfIo, pIoCtx),
5780 ("Async I/O is not supported for stream optimized VMDK's\n"));
5781
5782 uint32_t uSectorInGrain = uSectorExtentRel % pExtent->cSectorsPerGrain;
5783 uSectorExtentAbs -= uSectorInGrain;
5784 if (pExtent->uGrainSectorAbs != uSectorExtentAbs)
5785 {
5786 uint64_t uLBA = 0; /* gcc maybe uninitialized */
5787 rc = vmdkFileInflateSync(pImage, pExtent,
5788 VMDK_SECTOR2BYTE(uSectorExtentAbs),
5789 pExtent->pvGrain,
5790 VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain),
5791 NULL, &uLBA, NULL);
5792 if (RT_FAILURE(rc))
5793 {
5794 pExtent->uGrainSectorAbs = 0;
5795 AssertRC(rc);
5796 goto out;
5797 }
5798 pExtent->uGrainSectorAbs = uSectorExtentAbs;
5799 pExtent->uGrain = uSectorExtentRel / pExtent->cSectorsPerGrain;
5800 Assert(uLBA == uSectorExtentRel);
5801 }
5802 vdIfIoIntIoCtxCopyTo(pImage->pIfIo, pIoCtx,
5803 (uint8_t *)pExtent->pvGrain
5804 + VMDK_SECTOR2BYTE(uSectorInGrain),
5805 cbToRead);
5806 }
5807 else
5808 rc = vdIfIoIntFileReadUser(pImage->pIfIo, pExtent->pFile->pStorage,
5809 VMDK_SECTOR2BYTE(uSectorExtentAbs),
5810 pIoCtx, cbToRead);
5811 }
5812 break;
5813 case VMDKETYPE_VMFS:
5814 case VMDKETYPE_FLAT:
5815 rc = vdIfIoIntFileReadUser(pImage->pIfIo, pExtent->pFile->pStorage,
5816 VMDK_SECTOR2BYTE(uSectorExtentRel),
5817 pIoCtx, cbToRead);
5818 break;
5819 case VMDKETYPE_ZERO:
5820 size_t cbSet;
5821
5822 cbSet = vdIfIoIntIoCtxSet(pImage->pIfIo, pIoCtx, 0, cbToRead);
5823 Assert(cbSet == cbToRead);
5824
5825 rc = VINF_SUCCESS;
5826 break;
5827 }
5828 if (pcbActuallyRead)
5829 *pcbActuallyRead = cbToRead;
5830
5831out:
5832 LogFlowFunc(("returns %Rrc\n", rc));
5833 return rc;
5834}
5835
5836/** @copydoc VBOXHDDBACKEND::pfnWrite */
5837static DECLCALLBACK(int) vmdkWrite(void *pBackendData, uint64_t uOffset, size_t cbToWrite,
5838 PVDIOCTX pIoCtx, size_t *pcbWriteProcess, size_t *pcbPreRead,
5839 size_t *pcbPostRead, unsigned fWrite)
5840{
5841 LogFlowFunc(("pBackendData=%#p uOffset=%llu pIoCtx=%#p cbToWrite=%zu pcbWriteProcess=%#p pcbPreRead=%#p pcbPostRead=%#p\n",
5842 pBackendData, uOffset, pIoCtx, cbToWrite, pcbWriteProcess, pcbPreRead, pcbPostRead));
5843 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5844 PVMDKEXTENT pExtent;
5845 uint64_t uSectorExtentRel;
5846 uint64_t uSectorExtentAbs;
5847 int rc;
5848
5849 AssertPtr(pImage);
5850 Assert(uOffset % 512 == 0);
5851 Assert(cbToWrite % 512 == 0);
5852
5853 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
5854 {
5855 rc = VERR_VD_IMAGE_READ_ONLY;
5856 goto out;
5857 }
5858
5859 if (cbToWrite == 0)
5860 {
5861 rc = VERR_INVALID_PARAMETER;
5862 goto out;
5863 }
5864
5865 /* No size check here, will do that later when the extent is located.
5866 * There are sparse images out there which according to the spec are
5867 * invalid, because the total size is not a multiple of the grain size.
5868 * Also for sparse images which are stitched together in odd ways (not at
5869 * grain boundaries, and with the nominal size not being a multiple of the
5870 * grain size), this would prevent writing to the last grain. */
5871
5872 rc = vmdkFindExtent(pImage, VMDK_BYTE2SECTOR(uOffset),
5873 &pExtent, &uSectorExtentRel);
5874 if (RT_FAILURE(rc))
5875 goto out;
5876
5877 /* Check access permissions as defined in the extent descriptor. */
5878 if ( pExtent->enmAccess != VMDKACCESS_READWRITE
5879 && ( !(pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
5880 && !pImage->pExtents[0].uAppendPosition
5881 && pExtent->enmAccess != VMDKACCESS_READONLY))
5882 {
5883 rc = VERR_VD_VMDK_INVALID_STATE;
5884 goto out;
5885 }
5886
5887 /* Handle the write according to the current extent type. */
5888 switch (pExtent->enmType)
5889 {
5890 case VMDKETYPE_HOSTED_SPARSE:
5891#ifdef VBOX_WITH_VMDK_ESX
5892 case VMDKETYPE_ESX_SPARSE:
5893#endif /* VBOX_WITH_VMDK_ESX */
5894 rc = vmdkGetSector(pImage, pIoCtx, pExtent, uSectorExtentRel, &uSectorExtentAbs);
5895 if (RT_FAILURE(rc))
5896 goto out;
5897 /* Clip write range to at most the rest of the grain. */
5898 cbToWrite = RT_MIN(cbToWrite, VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain - uSectorExtentRel % pExtent->cSectorsPerGrain));
5899 if ( pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED
5900 && uSectorExtentRel < (uint64_t)pExtent->uLastGrainAccess * pExtent->cSectorsPerGrain)
5901 {
5902 rc = VERR_VD_VMDK_INVALID_WRITE;
5903 goto out;
5904 }
5905 if (uSectorExtentAbs == 0)
5906 {
5907 if (!(pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED))
5908 {
5909 if (cbToWrite == VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain))
5910 {
5911 /* Full block write to a previously unallocated block.
5912 * Check if the caller wants to avoid the automatic alloc. */
5913 if (!(fWrite & VD_WRITE_NO_ALLOC))
5914 {
5915 /* Allocate GT and find out where to store the grain. */
5916 rc = vmdkAllocGrain(pImage, pExtent, pIoCtx,
5917 uSectorExtentRel, cbToWrite);
5918 }
5919 else
5920 rc = VERR_VD_BLOCK_FREE;
5921 *pcbPreRead = 0;
5922 *pcbPostRead = 0;
5923 }
5924 else
5925 {
5926 /* Clip write range to remain in this extent. */
5927 cbToWrite = RT_MIN(cbToWrite, VMDK_SECTOR2BYTE(pExtent->uSectorOffset + pExtent->cNominalSectors - uSectorExtentRel));
5928 *pcbPreRead = VMDK_SECTOR2BYTE(uSectorExtentRel % pExtent->cSectorsPerGrain);
5929 *pcbPostRead = VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain) - cbToWrite - *pcbPreRead;
5930 rc = VERR_VD_BLOCK_FREE;
5931 }
5932 }
5933 else
5934 {
5935 rc = vmdkStreamAllocGrain(pImage, pExtent,
5936 uSectorExtentRel,
5937 pIoCtx, cbToWrite);
5938 }
5939 }
5940 else
5941 {
5942 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
5943 {
5944 /* A partial write to a streamOptimized image is simply
5945 * invalid. It requires rewriting already compressed data
5946 * which is somewhere between expensive and impossible. */
5947 rc = VERR_VD_VMDK_INVALID_STATE;
5948 pExtent->uGrainSectorAbs = 0;
5949 AssertRC(rc);
5950 }
5951 else
5952 {
5953 Assert(!(pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED));
5954 rc = vdIfIoIntFileWriteUser(pImage->pIfIo, pExtent->pFile->pStorage,
5955 VMDK_SECTOR2BYTE(uSectorExtentAbs),
5956 pIoCtx, cbToWrite, NULL, NULL);
5957 }
5958 }
5959 break;
5960 case VMDKETYPE_VMFS:
5961 case VMDKETYPE_FLAT:
5962 /* Clip write range to remain in this extent. */
5963 cbToWrite = RT_MIN(cbToWrite, VMDK_SECTOR2BYTE(pExtent->uSectorOffset + pExtent->cNominalSectors - uSectorExtentRel));
5964 rc = vdIfIoIntFileWriteUser(pImage->pIfIo, pExtent->pFile->pStorage,
5965 VMDK_SECTOR2BYTE(uSectorExtentRel),
5966 pIoCtx, cbToWrite, NULL, NULL);
5967 break;
5968 case VMDKETYPE_ZERO:
5969 /* Clip write range to remain in this extent. */
5970 cbToWrite = RT_MIN(cbToWrite, VMDK_SECTOR2BYTE(pExtent->uSectorOffset + pExtent->cNominalSectors - uSectorExtentRel));
5971 break;
5972 }
5973
5974 if (pcbWriteProcess)
5975 *pcbWriteProcess = cbToWrite;
5976
5977out:
5978 LogFlowFunc(("returns %Rrc\n", rc));
5979 return rc;
5980}
5981
5982/** @copydoc VBOXHDDBACKEND::pfnFlush */
5983static DECLCALLBACK(int) vmdkFlush(void *pBackendData, PVDIOCTX pIoCtx)
5984{
5985 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5986
5987 return vmdkFlushImage(pImage, pIoCtx);
5988}
5989
5990/** @copydoc VBOXHDDBACKEND::pfnGetVersion */
5991static DECLCALLBACK(unsigned) vmdkGetVersion(void *pBackendData)
5992{
5993 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
5994 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5995
5996 AssertPtr(pImage);
5997
5998 if (pImage)
5999 return VMDK_IMAGE_VERSION;
6000 else
6001 return 0;
6002}
6003
6004/** @copydoc VBOXHDDBACKEND::pfnGetSectorSize */
6005static DECLCALLBACK(uint32_t) vmdkGetSectorSize(void *pBackendData)
6006{
6007 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
6008 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6009
6010 AssertPtr(pImage);
6011
6012 if (pImage)
6013 return 512;
6014 else
6015 return 0;
6016}
6017
6018/** @copydoc VBOXHDDBACKEND::pfnGetSize */
6019static DECLCALLBACK(uint64_t) vmdkGetSize(void *pBackendData)
6020{
6021 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
6022 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6023
6024 AssertPtr(pImage);
6025
6026 if (pImage)
6027 return pImage->cbSize;
6028 else
6029 return 0;
6030}
6031
6032/** @copydoc VBOXHDDBACKEND::pfnGetFileSize */
6033static DECLCALLBACK(uint64_t) vmdkGetFileSize(void *pBackendData)
6034{
6035 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
6036 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6037 uint64_t cb = 0;
6038
6039 AssertPtr(pImage);
6040
6041 if (pImage)
6042 {
6043 uint64_t cbFile;
6044 if (pImage->pFile != NULL)
6045 {
6046 int rc = vdIfIoIntFileGetSize(pImage->pIfIo, pImage->pFile->pStorage, &cbFile);
6047 if (RT_SUCCESS(rc))
6048 cb += cbFile;
6049 }
6050 for (unsigned i = 0; i < pImage->cExtents; i++)
6051 {
6052 if (pImage->pExtents[i].pFile != NULL)
6053 {
6054 int rc = vdIfIoIntFileGetSize(pImage->pIfIo, pImage->pExtents[i].pFile->pStorage, &cbFile);
6055 if (RT_SUCCESS(rc))
6056 cb += cbFile;
6057 }
6058 }
6059 }
6060
6061 LogFlowFunc(("returns %lld\n", cb));
6062 return cb;
6063}
6064
6065/** @copydoc VBOXHDDBACKEND::pfnGetPCHSGeometry */
6066static DECLCALLBACK(int) vmdkGetPCHSGeometry(void *pBackendData, PVDGEOMETRY pPCHSGeometry)
6067{
6068 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p\n", pBackendData, pPCHSGeometry));
6069 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6070 int rc;
6071
6072 AssertPtr(pImage);
6073
6074 if (pImage)
6075 {
6076 if (pImage->PCHSGeometry.cCylinders)
6077 {
6078 *pPCHSGeometry = pImage->PCHSGeometry;
6079 rc = VINF_SUCCESS;
6080 }
6081 else
6082 rc = VERR_VD_GEOMETRY_NOT_SET;
6083 }
6084 else
6085 rc = VERR_VD_NOT_OPENED;
6086
6087 LogFlowFunc(("returns %Rrc (PCHS=%u/%u/%u)\n", rc, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
6088 return rc;
6089}
6090
6091/** @copydoc VBOXHDDBACKEND::pfnSetPCHSGeometry */
6092static DECLCALLBACK(int) vmdkSetPCHSGeometry(void *pBackendData, PCVDGEOMETRY pPCHSGeometry)
6093{
6094 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p PCHS=%u/%u/%u\n", pBackendData, pPCHSGeometry, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
6095 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6096 int rc;
6097
6098 AssertPtr(pImage);
6099
6100 if (pImage)
6101 {
6102 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
6103 {
6104 rc = VERR_VD_IMAGE_READ_ONLY;
6105 goto out;
6106 }
6107 if (pImage->uOpenFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
6108 {
6109 rc = VERR_NOT_SUPPORTED;
6110 goto out;
6111 }
6112 rc = vmdkDescSetPCHSGeometry(pImage, pPCHSGeometry);
6113 if (RT_FAILURE(rc))
6114 goto out;
6115
6116 pImage->PCHSGeometry = *pPCHSGeometry;
6117 rc = VINF_SUCCESS;
6118 }
6119 else
6120 rc = VERR_VD_NOT_OPENED;
6121
6122out:
6123 LogFlowFunc(("returns %Rrc\n", rc));
6124 return rc;
6125}
6126
6127/** @copydoc VBOXHDDBACKEND::pfnGetLCHSGeometry */
6128static DECLCALLBACK(int) vmdkGetLCHSGeometry(void *pBackendData, PVDGEOMETRY pLCHSGeometry)
6129{
6130 LogFlowFunc(("pBackendData=%#p pLCHSGeometry=%#p\n", pBackendData, pLCHSGeometry));
6131 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6132 int rc;
6133
6134 AssertPtr(pImage);
6135
6136 if (pImage)
6137 {
6138 if (pImage->LCHSGeometry.cCylinders)
6139 {
6140 *pLCHSGeometry = pImage->LCHSGeometry;
6141 rc = VINF_SUCCESS;
6142 }
6143 else
6144 rc = VERR_VD_GEOMETRY_NOT_SET;
6145 }
6146 else
6147 rc = VERR_VD_NOT_OPENED;
6148
6149 LogFlowFunc(("returns %Rrc (LCHS=%u/%u/%u)\n", rc, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
6150 return rc;
6151}
6152
6153/** @copydoc VBOXHDDBACKEND::pfnSetLCHSGeometry */
6154static DECLCALLBACK(int) vmdkSetLCHSGeometry(void *pBackendData, PCVDGEOMETRY pLCHSGeometry)
6155{
6156 LogFlowFunc(("pBackendData=%#p pLCHSGeometry=%#p LCHS=%u/%u/%u\n", pBackendData, pLCHSGeometry, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
6157 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6158 int rc;
6159
6160 AssertPtr(pImage);
6161
6162 if (pImage)
6163 {
6164 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
6165 {
6166 rc = VERR_VD_IMAGE_READ_ONLY;
6167 goto out;
6168 }
6169 if (pImage->uOpenFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
6170 {
6171 rc = VERR_NOT_SUPPORTED;
6172 goto out;
6173 }
6174 rc = vmdkDescSetLCHSGeometry(pImage, pLCHSGeometry);
6175 if (RT_FAILURE(rc))
6176 goto out;
6177
6178 pImage->LCHSGeometry = *pLCHSGeometry;
6179 rc = VINF_SUCCESS;
6180 }
6181 else
6182 rc = VERR_VD_NOT_OPENED;
6183
6184out:
6185 LogFlowFunc(("returns %Rrc\n", rc));
6186 return rc;
6187}
6188
6189/** @copydoc VBOXHDDBACKEND::pfnGetImageFlags */
6190static DECLCALLBACK(unsigned) vmdkGetImageFlags(void *pBackendData)
6191{
6192 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
6193 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6194 unsigned uImageFlags;
6195
6196 AssertPtr(pImage);
6197
6198 if (pImage)
6199 uImageFlags = pImage->uImageFlags;
6200 else
6201 uImageFlags = 0;
6202
6203 LogFlowFunc(("returns %#x\n", uImageFlags));
6204 return uImageFlags;
6205}
6206
6207/** @copydoc VBOXHDDBACKEND::pfnGetOpenFlags */
6208static DECLCALLBACK(unsigned) vmdkGetOpenFlags(void *pBackendData)
6209{
6210 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
6211 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6212 unsigned uOpenFlags;
6213
6214 AssertPtr(pImage);
6215
6216 if (pImage)
6217 uOpenFlags = pImage->uOpenFlags;
6218 else
6219 uOpenFlags = 0;
6220
6221 LogFlowFunc(("returns %#x\n", uOpenFlags));
6222 return uOpenFlags;
6223}
6224
6225/** @copydoc VBOXHDDBACKEND::pfnSetOpenFlags */
6226static DECLCALLBACK(int) vmdkSetOpenFlags(void *pBackendData, unsigned uOpenFlags)
6227{
6228 LogFlowFunc(("pBackendData=%#p uOpenFlags=%#x\n", pBackendData, uOpenFlags));
6229 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6230 int rc;
6231
6232 /* Image must be opened and the new flags must be valid. */
6233 if (!pImage || (uOpenFlags & ~( VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO
6234 | VD_OPEN_FLAGS_ASYNC_IO | VD_OPEN_FLAGS_SHAREABLE
6235 | VD_OPEN_FLAGS_SEQUENTIAL | VD_OPEN_FLAGS_SKIP_CONSISTENCY_CHECKS)))
6236 {
6237 rc = VERR_INVALID_PARAMETER;
6238 goto out;
6239 }
6240
6241 /* StreamOptimized images need special treatment: reopen is prohibited. */
6242 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
6243 {
6244 if (pImage->uOpenFlags == uOpenFlags)
6245 rc = VINF_SUCCESS;
6246 else
6247 rc = VERR_INVALID_PARAMETER;
6248 }
6249 else
6250 {
6251 /* Implement this operation via reopening the image. */
6252 vmdkFreeImage(pImage, false);
6253 rc = vmdkOpenImage(pImage, uOpenFlags);
6254 }
6255
6256out:
6257 LogFlowFunc(("returns %Rrc\n", rc));
6258 return rc;
6259}
6260
6261/** @copydoc VBOXHDDBACKEND::pfnGetComment */
6262static DECLCALLBACK(int) vmdkGetComment(void *pBackendData, char *pszComment,
6263 size_t cbComment)
6264{
6265 LogFlowFunc(("pBackendData=%#p pszComment=%#p cbComment=%zu\n", pBackendData, pszComment, cbComment));
6266 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6267 int rc;
6268
6269 AssertPtr(pImage);
6270
6271 if (pImage)
6272 {
6273 char *pszCommentEncoded = NULL;
6274 rc = vmdkDescDDBGetStr(pImage, &pImage->Descriptor,
6275 "ddb.comment", &pszCommentEncoded);
6276 if (rc == VERR_VD_VMDK_VALUE_NOT_FOUND)
6277 pszCommentEncoded = NULL;
6278 else if (RT_FAILURE(rc))
6279 goto out;
6280
6281 if (pszComment && pszCommentEncoded)
6282 rc = vmdkDecodeString(pszCommentEncoded, pszComment, cbComment);
6283 else
6284 {
6285 if (pszComment)
6286 *pszComment = '\0';
6287 rc = VINF_SUCCESS;
6288 }
6289 RTMemTmpFree(pszCommentEncoded);
6290 }
6291 else
6292 rc = VERR_VD_NOT_OPENED;
6293
6294out:
6295 LogFlowFunc(("returns %Rrc comment='%s'\n", rc, pszComment));
6296 return rc;
6297}
6298
6299/** @copydoc VBOXHDDBACKEND::pfnSetComment */
6300static DECLCALLBACK(int) vmdkSetComment(void *pBackendData, const char *pszComment)
6301{
6302 LogFlowFunc(("pBackendData=%#p pszComment=\"%s\"\n", pBackendData, pszComment));
6303 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6304 int rc;
6305
6306 AssertPtr(pImage);
6307
6308 if (pImage)
6309 {
6310 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
6311 {
6312 rc = VERR_VD_IMAGE_READ_ONLY;
6313 goto out;
6314 }
6315 if (pImage->uOpenFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
6316 {
6317 rc = VERR_NOT_SUPPORTED;
6318 goto out;
6319 }
6320
6321 rc = vmdkSetImageComment(pImage, pszComment);
6322 }
6323 else
6324 rc = VERR_VD_NOT_OPENED;
6325
6326out:
6327 LogFlowFunc(("returns %Rrc\n", rc));
6328 return rc;
6329}
6330
6331/** @copydoc VBOXHDDBACKEND::pfnGetUuid */
6332static DECLCALLBACK(int) vmdkGetUuid(void *pBackendData, PRTUUID pUuid)
6333{
6334 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
6335 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6336 int rc;
6337
6338 AssertPtr(pImage);
6339
6340 if (pImage)
6341 {
6342 *pUuid = pImage->ImageUuid;
6343 rc = VINF_SUCCESS;
6344 }
6345 else
6346 rc = VERR_VD_NOT_OPENED;
6347
6348 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
6349 return rc;
6350}
6351
6352/** @copydoc VBOXHDDBACKEND::pfnSetUuid */
6353static DECLCALLBACK(int) vmdkSetUuid(void *pBackendData, PCRTUUID pUuid)
6354{
6355 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
6356 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6357 int rc;
6358
6359 LogFlowFunc(("%RTuuid\n", pUuid));
6360 AssertPtr(pImage);
6361
6362 if (pImage)
6363 {
6364 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
6365 {
6366 if (!(pImage->uOpenFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED))
6367 {
6368 pImage->ImageUuid = *pUuid;
6369 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
6370 VMDK_DDB_IMAGE_UUID, pUuid);
6371 if (RT_FAILURE(rc))
6372 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error storing image UUID in descriptor in '%s'"), pImage->pszFilename);
6373 rc = VINF_SUCCESS;
6374 }
6375 else
6376 rc = VERR_NOT_SUPPORTED;
6377 }
6378 else
6379 rc = VERR_VD_IMAGE_READ_ONLY;
6380 }
6381 else
6382 rc = VERR_VD_NOT_OPENED;
6383
6384 LogFlowFunc(("returns %Rrc\n", rc));
6385 return rc;
6386}
6387
6388/** @copydoc VBOXHDDBACKEND::pfnGetModificationUuid */
6389static DECLCALLBACK(int) vmdkGetModificationUuid(void *pBackendData, PRTUUID pUuid)
6390{
6391 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
6392 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6393 int rc;
6394
6395 AssertPtr(pImage);
6396
6397 if (pImage)
6398 {
6399 *pUuid = pImage->ModificationUuid;
6400 rc = VINF_SUCCESS;
6401 }
6402 else
6403 rc = VERR_VD_NOT_OPENED;
6404
6405 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
6406 return rc;
6407}
6408
6409/** @copydoc VBOXHDDBACKEND::pfnSetModificationUuid */
6410static DECLCALLBACK(int) vmdkSetModificationUuid(void *pBackendData, PCRTUUID pUuid)
6411{
6412 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
6413 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6414 int rc;
6415
6416 AssertPtr(pImage);
6417
6418 if (pImage)
6419 {
6420 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
6421 {
6422 if (!(pImage->uOpenFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED))
6423 {
6424 /* Only touch the modification uuid if it changed. */
6425 if (RTUuidCompare(&pImage->ModificationUuid, pUuid))
6426 {
6427 pImage->ModificationUuid = *pUuid;
6428 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
6429 VMDK_DDB_MODIFICATION_UUID, pUuid);
6430 if (RT_FAILURE(rc))
6431 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error storing modification UUID in descriptor in '%s'"), pImage->pszFilename);
6432 }
6433 rc = VINF_SUCCESS;
6434 }
6435 else
6436 rc = VERR_NOT_SUPPORTED;
6437 }
6438 else
6439 rc = VERR_VD_IMAGE_READ_ONLY;
6440 }
6441 else
6442 rc = VERR_VD_NOT_OPENED;
6443
6444 LogFlowFunc(("returns %Rrc\n", rc));
6445 return rc;
6446}
6447
6448/** @copydoc VBOXHDDBACKEND::pfnGetParentUuid */
6449static DECLCALLBACK(int) vmdkGetParentUuid(void *pBackendData, PRTUUID pUuid)
6450{
6451 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
6452 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6453 int rc;
6454
6455 AssertPtr(pImage);
6456
6457 if (pImage)
6458 {
6459 *pUuid = pImage->ParentUuid;
6460 rc = VINF_SUCCESS;
6461 }
6462 else
6463 rc = VERR_VD_NOT_OPENED;
6464
6465 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
6466 return rc;
6467}
6468
6469/** @copydoc VBOXHDDBACKEND::pfnSetParentUuid */
6470static DECLCALLBACK(int) vmdkSetParentUuid(void *pBackendData, PCRTUUID pUuid)
6471{
6472 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
6473 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6474 int rc;
6475
6476 AssertPtr(pImage);
6477
6478 if (pImage)
6479 {
6480 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
6481 {
6482 if (!(pImage->uOpenFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED))
6483 {
6484 pImage->ParentUuid = *pUuid;
6485 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
6486 VMDK_DDB_PARENT_UUID, pUuid);
6487 if (RT_FAILURE(rc))
6488 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error storing parent image UUID in descriptor in '%s'"), pImage->pszFilename);
6489 rc = VINF_SUCCESS;
6490 }
6491 else
6492 rc = VERR_NOT_SUPPORTED;
6493 }
6494 else
6495 rc = VERR_VD_IMAGE_READ_ONLY;
6496 }
6497 else
6498 rc = VERR_VD_NOT_OPENED;
6499
6500 LogFlowFunc(("returns %Rrc\n", rc));
6501 return rc;
6502}
6503
6504/** @copydoc VBOXHDDBACKEND::pfnGetParentModificationUuid */
6505static DECLCALLBACK(int) vmdkGetParentModificationUuid(void *pBackendData, PRTUUID pUuid)
6506{
6507 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
6508 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6509 int rc;
6510
6511 AssertPtr(pImage);
6512
6513 if (pImage)
6514 {
6515 *pUuid = pImage->ParentModificationUuid;
6516 rc = VINF_SUCCESS;
6517 }
6518 else
6519 rc = VERR_VD_NOT_OPENED;
6520
6521 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
6522 return rc;
6523}
6524
6525/** @copydoc VBOXHDDBACKEND::pfnSetParentModificationUuid */
6526static DECLCALLBACK(int) vmdkSetParentModificationUuid(void *pBackendData, PCRTUUID pUuid)
6527{
6528 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
6529 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6530 int rc;
6531
6532 AssertPtr(pImage);
6533
6534 if (pImage)
6535 {
6536 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
6537 {
6538 if (!(pImage->uOpenFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED))
6539 {
6540 pImage->ParentModificationUuid = *pUuid;
6541 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
6542 VMDK_DDB_PARENT_MODIFICATION_UUID, pUuid);
6543 if (RT_FAILURE(rc))
6544 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error storing parent image UUID in descriptor in '%s'"), pImage->pszFilename);
6545 rc = VINF_SUCCESS;
6546 }
6547 else
6548 rc = VERR_NOT_SUPPORTED;
6549 }
6550 else
6551 rc = VERR_VD_IMAGE_READ_ONLY;
6552 }
6553 else
6554 rc = VERR_VD_NOT_OPENED;
6555
6556 LogFlowFunc(("returns %Rrc\n", rc));
6557 return rc;
6558}
6559
6560/** @copydoc VBOXHDDBACKEND::pfnDump */
6561static DECLCALLBACK(void) vmdkDump(void *pBackendData)
6562{
6563 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6564
6565 AssertPtr(pImage);
6566 if (pImage)
6567 {
6568 vdIfErrorMessage(pImage->pIfError, "Header: Geometry PCHS=%u/%u/%u LCHS=%u/%u/%u cbSector=%llu\n",
6569 pImage->PCHSGeometry.cCylinders, pImage->PCHSGeometry.cHeads, pImage->PCHSGeometry.cSectors,
6570 pImage->LCHSGeometry.cCylinders, pImage->LCHSGeometry.cHeads, pImage->LCHSGeometry.cSectors,
6571 VMDK_BYTE2SECTOR(pImage->cbSize));
6572 vdIfErrorMessage(pImage->pIfError, "Header: uuidCreation={%RTuuid}\n", &pImage->ImageUuid);
6573 vdIfErrorMessage(pImage->pIfError, "Header: uuidModification={%RTuuid}\n", &pImage->ModificationUuid);
6574 vdIfErrorMessage(pImage->pIfError, "Header: uuidParent={%RTuuid}\n", &pImage->ParentUuid);
6575 vdIfErrorMessage(pImage->pIfError, "Header: uuidParentModification={%RTuuid}\n", &pImage->ParentModificationUuid);
6576 }
6577}
6578
6579
6580
6581const VBOXHDDBACKEND g_VmdkBackend =
6582{
6583 /* pszBackendName */
6584 "VMDK",
6585 /* cbSize */
6586 sizeof(VBOXHDDBACKEND),
6587 /* uBackendCaps */
6588 VD_CAP_UUID | VD_CAP_CREATE_FIXED | VD_CAP_CREATE_DYNAMIC
6589 | VD_CAP_CREATE_SPLIT_2G | VD_CAP_DIFF | VD_CAP_FILE | VD_CAP_ASYNC
6590 | VD_CAP_VFS | VD_CAP_PREFERRED,
6591 /* paFileExtensions */
6592 s_aVmdkFileExtensions,
6593 /* paConfigInfo */
6594 NULL,
6595 /* pfnCheckIfValid */
6596 vmdkCheckIfValid,
6597 /* pfnOpen */
6598 vmdkOpen,
6599 /* pfnCreate */
6600 vmdkCreate,
6601 /* pfnRename */
6602 vmdkRename,
6603 /* pfnClose */
6604 vmdkClose,
6605 /* pfnRead */
6606 vmdkRead,
6607 /* pfnWrite */
6608 vmdkWrite,
6609 /* pfnFlush */
6610 vmdkFlush,
6611 /* pfnDiscard */
6612 NULL,
6613 /* pfnGetVersion */
6614 vmdkGetVersion,
6615 /* pfnGetSectorSize */
6616 vmdkGetSectorSize,
6617 /* pfnGetSize */
6618 vmdkGetSize,
6619 /* pfnGetFileSize */
6620 vmdkGetFileSize,
6621 /* pfnGetPCHSGeometry */
6622 vmdkGetPCHSGeometry,
6623 /* pfnSetPCHSGeometry */
6624 vmdkSetPCHSGeometry,
6625 /* pfnGetLCHSGeometry */
6626 vmdkGetLCHSGeometry,
6627 /* pfnSetLCHSGeometry */
6628 vmdkSetLCHSGeometry,
6629 /* pfnGetImageFlags */
6630 vmdkGetImageFlags,
6631 /* pfnGetOpenFlags */
6632 vmdkGetOpenFlags,
6633 /* pfnSetOpenFlags */
6634 vmdkSetOpenFlags,
6635 /* pfnGetComment */
6636 vmdkGetComment,
6637 /* pfnSetComment */
6638 vmdkSetComment,
6639 /* pfnGetUuid */
6640 vmdkGetUuid,
6641 /* pfnSetUuid */
6642 vmdkSetUuid,
6643 /* pfnGetModificationUuid */
6644 vmdkGetModificationUuid,
6645 /* pfnSetModificationUuid */
6646 vmdkSetModificationUuid,
6647 /* pfnGetParentUuid */
6648 vmdkGetParentUuid,
6649 /* pfnSetParentUuid */
6650 vmdkSetParentUuid,
6651 /* pfnGetParentModificationUuid */
6652 vmdkGetParentModificationUuid,
6653 /* pfnSetParentModificationUuid */
6654 vmdkSetParentModificationUuid,
6655 /* pfnDump */
6656 vmdkDump,
6657 /* pfnGetTimestamp */
6658 NULL,
6659 /* pfnGetParentTimestamp */
6660 NULL,
6661 /* pfnSetParentTimestamp */
6662 NULL,
6663 /* pfnGetParentFilename */
6664 NULL,
6665 /* pfnSetParentFilename */
6666 NULL,
6667 /* pfnComposeLocation */
6668 genericFileComposeLocation,
6669 /* pfnComposeName */
6670 genericFileComposeName,
6671 /* pfnCompact */
6672 NULL,
6673 /* pfnResize */
6674 NULL,
6675 /* pfnRepair */
6676 NULL,
6677 /* pfnTraverseMetadata */
6678 NULL
6679};
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette