VirtualBox

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

Last change on this file since 33937 was 33937, checked in by vboxsync, 14 years ago

Storage/VMDK: pvDescriptor might be used uninitialized

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