VirtualBox

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

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

VMDK: Reject VD_OPEN_FLAGS_ASYNC_IO for stream optimized images

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 269.7 KB
Line 
1/* $Id: VMDK.cpp 36514 2011-04-01 17:07:15Z 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 RTUuidClear(&pImage->ParentModificationUuid);
2455 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
2456 VMDK_DDB_PARENT_MODIFICATION_UUID,
2457 &pImage->ParentModificationUuid);
2458 if (RT_FAILURE(rc))
2459 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error storing parent modification UUID in descriptor in '%s'"), pImage->pszFilename);
2460 }
2461 }
2462 else if (RT_FAILURE(rc))
2463 return rc;
2464
2465 return VINF_SUCCESS;
2466}
2467
2468/**
2469 * Internal : Prepares the descriptor to write to the image.
2470 */
2471static int vmdkDescriptorPrepare(PVMDKIMAGE pImage, uint64_t cbLimit,
2472 void **ppvData, size_t *pcbData)
2473{
2474 int rc = VINF_SUCCESS;
2475
2476 /*
2477 * Allocate temporary descriptor buffer.
2478 * In case there is no limit allocate a default
2479 * and increase if required.
2480 */
2481 size_t cbDescriptor = cbLimit ? cbLimit : 4 * _1K;
2482 char *pszDescriptor = (char *)RTMemAllocZ(cbDescriptor);
2483 unsigned offDescriptor = 0;
2484
2485 if (!pszDescriptor)
2486 return VERR_NO_MEMORY;
2487
2488 for (unsigned i = 0; i < pImage->Descriptor.cLines; i++)
2489 {
2490 const char *psz = pImage->Descriptor.aLines[i];
2491 size_t cb = strlen(psz);
2492
2493 /*
2494 * Increase the descriptor if there is no limit and
2495 * there is not enough room left for this line.
2496 */
2497 if (offDescriptor + cb + 1 > cbDescriptor)
2498 {
2499 if (cbLimit)
2500 {
2501 rc = vmdkError(pImage, VERR_BUFFER_OVERFLOW, RT_SRC_POS, N_("VMDK: descriptor too long in '%s'"), pImage->pszFilename);
2502 break;
2503 }
2504 else
2505 {
2506 char *pszDescriptorNew = NULL;
2507 LogFlow(("Increasing descriptor cache\n"));
2508
2509 pszDescriptorNew = (char *)RTMemRealloc(pszDescriptor, cbDescriptor + cb + 4 * _1K);
2510 if (!pszDescriptorNew)
2511 {
2512 rc = VERR_NO_MEMORY;
2513 break;
2514 }
2515 pszDescriptor = pszDescriptorNew;
2516 cbDescriptor += cb + 4 * _1K;
2517 }
2518 }
2519
2520 if (cb > 0)
2521 {
2522 memcpy(pszDescriptor + offDescriptor, psz, cb);
2523 offDescriptor += cb;
2524 }
2525
2526 memcpy(pszDescriptor + offDescriptor, "\n", 1);
2527 offDescriptor++;
2528 }
2529
2530 if (RT_SUCCESS(rc))
2531 {
2532 *ppvData = pszDescriptor;
2533 *pcbData = offDescriptor;
2534 }
2535 else if (pszDescriptor)
2536 RTMemFree(pszDescriptor);
2537
2538 return rc;
2539}
2540
2541/**
2542 * Internal: write/update the descriptor part of the image.
2543 */
2544static int vmdkWriteDescriptor(PVMDKIMAGE pImage)
2545{
2546 int rc = VINF_SUCCESS;
2547 uint64_t cbLimit;
2548 uint64_t uOffset;
2549 PVMDKFILE pDescFile;
2550 void *pvDescriptor;
2551 size_t cbDescriptor;
2552
2553 if (pImage->pDescData)
2554 {
2555 /* Separate descriptor file. */
2556 uOffset = 0;
2557 cbLimit = 0;
2558 pDescFile = pImage->pFile;
2559 }
2560 else
2561 {
2562 /* Embedded descriptor file. */
2563 uOffset = VMDK_SECTOR2BYTE(pImage->pExtents[0].uDescriptorSector);
2564 cbLimit = VMDK_SECTOR2BYTE(pImage->pExtents[0].cDescriptorSectors);
2565 pDescFile = pImage->pExtents[0].pFile;
2566 }
2567 /* Bail out if there is no file to write to. */
2568 if (pDescFile == NULL)
2569 return VERR_INVALID_PARAMETER;
2570
2571 rc = vmdkDescriptorPrepare(pImage, cbLimit, &pvDescriptor, &cbDescriptor);
2572 if (RT_SUCCESS(rc))
2573 {
2574 rc = vmdkFileWriteSync(pImage, pDescFile, uOffset, pvDescriptor, cbLimit ? cbLimit : cbDescriptor, NULL);
2575 if (RT_FAILURE(rc))
2576 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error writing descriptor in '%s'"), pImage->pszFilename);
2577
2578 if (RT_SUCCESS(rc) && !cbLimit)
2579 {
2580 rc = vmdkFileSetSize(pImage, pDescFile, cbDescriptor);
2581 if (RT_FAILURE(rc))
2582 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error truncating descriptor in '%s'"), pImage->pszFilename);
2583 }
2584
2585 if (RT_SUCCESS(rc))
2586 pImage->Descriptor.fDirty = false;
2587
2588 RTMemFree(pvDescriptor);
2589 }
2590
2591 return rc;
2592}
2593
2594/**
2595 * Internal: write/update the descriptor part of the image - async version.
2596 */
2597static int vmdkWriteDescriptorAsync(PVMDKIMAGE pImage, PVDIOCTX pIoCtx)
2598{
2599 int rc = VINF_SUCCESS;
2600 uint64_t cbLimit;
2601 uint64_t uOffset;
2602 PVMDKFILE pDescFile;
2603 void *pvDescriptor;
2604 size_t cbDescriptor;
2605
2606 if (pImage->pDescData)
2607 {
2608 /* Separate descriptor file. */
2609 uOffset = 0;
2610 cbLimit = 0;
2611 pDescFile = pImage->pFile;
2612 }
2613 else
2614 {
2615 /* Embedded descriptor file. */
2616 uOffset = VMDK_SECTOR2BYTE(pImage->pExtents[0].uDescriptorSector);
2617 cbLimit = VMDK_SECTOR2BYTE(pImage->pExtents[0].cDescriptorSectors);
2618 pDescFile = pImage->pExtents[0].pFile;
2619 }
2620 /* Bail out if there is no file to write to. */
2621 if (pDescFile == NULL)
2622 return VERR_INVALID_PARAMETER;
2623
2624 rc = vmdkDescriptorPrepare(pImage, cbLimit, &pvDescriptor, &cbDescriptor);
2625 if (RT_SUCCESS(rc))
2626 {
2627 rc = vmdkFileWriteMetaAsync(pImage, pDescFile, uOffset, pvDescriptor, cbLimit ? cbLimit : cbDescriptor, pIoCtx, NULL, NULL);
2628 if ( RT_FAILURE(rc)
2629 && rc != VERR_VD_ASYNC_IO_IN_PROGRESS)
2630 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error writing descriptor in '%s'"), pImage->pszFilename);
2631 }
2632
2633 if (RT_SUCCESS(rc) && !cbLimit)
2634 {
2635 rc = vmdkFileSetSize(pImage, pDescFile, cbDescriptor);
2636 if (RT_FAILURE(rc))
2637 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error truncating descriptor in '%s'"), pImage->pszFilename);
2638 }
2639
2640 if (RT_SUCCESS(rc))
2641 pImage->Descriptor.fDirty = false;
2642
2643 RTMemFree(pvDescriptor);
2644 return rc;
2645
2646}
2647
2648/**
2649 * Internal: validate the consistency check values in a binary header.
2650 */
2651static int vmdkValidateHeader(PVMDKIMAGE pImage, PVMDKEXTENT pExtent, const SparseExtentHeader *pHeader)
2652{
2653 int rc = VINF_SUCCESS;
2654 if (RT_LE2H_U32(pHeader->magicNumber) != VMDK_SPARSE_MAGICNUMBER)
2655 {
2656 rc = vmdkError(pImage, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: incorrect magic in sparse extent header in '%s'"), pExtent->pszFullname);
2657 return rc;
2658 }
2659 if (RT_LE2H_U32(pHeader->version) != 1 && RT_LE2H_U32(pHeader->version) != 3)
2660 {
2661 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);
2662 return rc;
2663 }
2664 if ( (RT_LE2H_U32(pHeader->flags) & 1)
2665 && ( pHeader->singleEndLineChar != '\n'
2666 || pHeader->nonEndLineChar != ' '
2667 || pHeader->doubleEndLineChar1 != '\r'
2668 || pHeader->doubleEndLineChar2 != '\n') )
2669 {
2670 rc = vmdkError(pImage, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: corrupted by CR/LF translation in '%s'"), pExtent->pszFullname);
2671 return rc;
2672 }
2673 return rc;
2674}
2675
2676/**
2677 * Internal: read metadata belonging to an extent with binary header, i.e.
2678 * as found in monolithic files.
2679 */
2680static int vmdkReadBinaryMetaExtent(PVMDKIMAGE pImage, PVMDKEXTENT pExtent,
2681 bool fMagicAlreadyRead)
2682{
2683 SparseExtentHeader Header;
2684 uint64_t cSectorsPerGDE;
2685 uint64_t cbFile = 0;
2686 int rc;
2687
2688 if (!fMagicAlreadyRead)
2689 rc = vmdkFileReadSync(pImage, pExtent->pFile, 0, &Header,
2690 sizeof(Header), NULL);
2691 else
2692 {
2693 Header.magicNumber = RT_H2LE_U32(VMDK_SPARSE_MAGICNUMBER);
2694 rc = vmdkFileReadSync(pImage, pExtent->pFile,
2695 RT_OFFSETOF(SparseExtentHeader, version),
2696 &Header.version,
2697 sizeof(Header)
2698 - RT_OFFSETOF(SparseExtentHeader, version),
2699 NULL);
2700 }
2701 AssertRC(rc);
2702 if (RT_FAILURE(rc))
2703 {
2704 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error reading extent header in '%s'"), pExtent->pszFullname);
2705 goto out;
2706 }
2707 rc = vmdkValidateHeader(pImage, pExtent, &Header);
2708 if (RT_FAILURE(rc))
2709 goto out;
2710
2711 if ( RT_LE2H_U32(Header.flags & RT_BIT(17))
2712 && RT_LE2H_U64(Header.gdOffset) == VMDK_GD_AT_END)
2713 pExtent->fFooter = true;
2714
2715 if ( !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2716 || ( pExtent->fFooter
2717 && !(pImage->uOpenFlags & VD_OPEN_FLAGS_SEQUENTIAL)))
2718 {
2719 rc = vmdkFileGetSize(pImage, pExtent->pFile, &cbFile);
2720 AssertRC(rc);
2721 if (RT_FAILURE(rc))
2722 {
2723 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: cannot get size of '%s'"), pExtent->pszFullname);
2724 goto out;
2725 }
2726 }
2727
2728 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
2729 pExtent->uAppendPosition = RT_ALIGN_64(cbFile, 512);
2730
2731 if ( pExtent->fFooter
2732 && ( !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2733 || !(pImage->uOpenFlags & VD_OPEN_FLAGS_SEQUENTIAL)))
2734 {
2735 /* Read the footer, which comes before the end-of-stream marker. */
2736 rc = vmdkFileReadSync(pImage, pExtent->pFile,
2737 cbFile - 2*512, &Header,
2738 sizeof(Header), NULL);
2739 AssertRC(rc);
2740 if (RT_FAILURE(rc))
2741 {
2742 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error reading extent footer in '%s'"), pExtent->pszFullname);
2743 goto out;
2744 }
2745 rc = vmdkValidateHeader(pImage, pExtent, &Header);
2746 if (RT_FAILURE(rc))
2747 goto out;
2748 /* Prohibit any writes to this extent. */
2749 pExtent->uAppendPosition = 0;
2750 }
2751
2752 pExtent->uVersion = RT_LE2H_U32(Header.version);
2753 pExtent->enmType = VMDKETYPE_HOSTED_SPARSE; /* Just dummy value, changed later. */
2754 pExtent->cSectors = RT_LE2H_U64(Header.capacity);
2755 pExtent->cSectorsPerGrain = RT_LE2H_U64(Header.grainSize);
2756 pExtent->uDescriptorSector = RT_LE2H_U64(Header.descriptorOffset);
2757 pExtent->cDescriptorSectors = RT_LE2H_U64(Header.descriptorSize);
2758 if (pExtent->uDescriptorSector && !pExtent->cDescriptorSectors)
2759 {
2760 rc = vmdkError(pImage, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: inconsistent embedded descriptor config in '%s'"), pExtent->pszFullname);
2761 goto out;
2762 }
2763 pExtent->cGTEntries = RT_LE2H_U32(Header.numGTEsPerGT);
2764 if (RT_LE2H_U32(Header.flags) & RT_BIT(1))
2765 {
2766 pExtent->uSectorRGD = RT_LE2H_U64(Header.rgdOffset);
2767 pExtent->uSectorGD = RT_LE2H_U64(Header.gdOffset);
2768 }
2769 else
2770 {
2771 pExtent->uSectorGD = RT_LE2H_U64(Header.gdOffset);
2772 pExtent->uSectorRGD = 0;
2773 }
2774 if ( ( pExtent->uSectorGD == VMDK_GD_AT_END
2775 || pExtent->uSectorRGD == VMDK_GD_AT_END)
2776 && ( !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2777 || !(pImage->uOpenFlags & VD_OPEN_FLAGS_SEQUENTIAL)))
2778 {
2779 rc = vmdkError(pImage, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: cannot resolve grain directory offset in '%s'"), pExtent->pszFullname);
2780 goto out;
2781 }
2782 pExtent->cOverheadSectors = RT_LE2H_U64(Header.overHead);
2783 pExtent->fUncleanShutdown = !!Header.uncleanShutdown;
2784 pExtent->uCompression = RT_LE2H_U16(Header.compressAlgorithm);
2785 cSectorsPerGDE = pExtent->cGTEntries * pExtent->cSectorsPerGrain;
2786 if (!cSectorsPerGDE || cSectorsPerGDE > UINT32_MAX)
2787 {
2788 rc = vmdkError(pImage, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: incorrect grain directory size in '%s'"), pExtent->pszFullname);
2789 goto out;
2790 }
2791 pExtent->cSectorsPerGDE = cSectorsPerGDE;
2792 pExtent->cGDEntries = (pExtent->cSectors + cSectorsPerGDE - 1) / cSectorsPerGDE;
2793
2794 /* Fix up the number of descriptor sectors, as some flat images have
2795 * really just one, and this causes failures when inserting the UUID
2796 * values and other extra information. */
2797 if (pExtent->cDescriptorSectors != 0 && pExtent->cDescriptorSectors < 4)
2798 {
2799 /* Do it the easy way - just fix it for flat images which have no
2800 * other complicated metadata which needs space too. */
2801 if ( pExtent->uDescriptorSector + 4 < pExtent->cOverheadSectors
2802 && pExtent->cGTEntries * pExtent->cGDEntries == 0)
2803 pExtent->cDescriptorSectors = 4;
2804 }
2805
2806out:
2807 if (RT_FAILURE(rc))
2808 vmdkFreeExtentData(pImage, pExtent, false);
2809
2810 return rc;
2811}
2812
2813/**
2814 * Internal: read additional metadata belonging to an extent. For those
2815 * extents which have no additional metadata just verify the information.
2816 */
2817static int vmdkReadMetaExtent(PVMDKIMAGE pImage, PVMDKEXTENT pExtent)
2818{
2819 int rc = VINF_SUCCESS;
2820
2821/* disabled the check as there are too many truncated vmdk images out there */
2822#ifdef VBOX_WITH_VMDK_STRICT_SIZE_CHECK
2823 uint64_t cbExtentSize;
2824 /* The image must be a multiple of a sector in size and contain the data
2825 * area (flat images only). If not, it means the image is at least
2826 * truncated, or even seriously garbled. */
2827 rc = vmdkFileGetSize(pImage, pExtent->pFile, &cbExtentSize);
2828 if (RT_FAILURE(rc))
2829 {
2830 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error getting size in '%s'"), pExtent->pszFullname);
2831 goto out;
2832 }
2833 if ( cbExtentSize != RT_ALIGN_64(cbExtentSize, 512)
2834 && (pExtent->enmType != VMDKETYPE_FLAT || pExtent->cNominalSectors + pExtent->uSectorOffset > VMDK_BYTE2SECTOR(cbExtentSize)))
2835 {
2836 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);
2837 goto out;
2838 }
2839#endif /* VBOX_WITH_VMDK_STRICT_SIZE_CHECK */
2840 if (pExtent->enmType != VMDKETYPE_HOSTED_SPARSE)
2841 goto out;
2842
2843 /* The spec says that this must be a power of two and greater than 8,
2844 * but probably they meant not less than 8. */
2845 if ( (pExtent->cSectorsPerGrain & (pExtent->cSectorsPerGrain - 1))
2846 || pExtent->cSectorsPerGrain < 8)
2847 {
2848 rc = vmdkError(pImage, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: invalid extent grain size %u in '%s'"), pExtent->cSectorsPerGrain, pExtent->pszFullname);
2849 goto out;
2850 }
2851
2852 /* This code requires that a grain table must hold a power of two multiple
2853 * of the number of entries per GT cache entry. */
2854 if ( (pExtent->cGTEntries & (pExtent->cGTEntries - 1))
2855 || pExtent->cGTEntries < VMDK_GT_CACHELINE_SIZE)
2856 {
2857 rc = vmdkError(pImage, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: grain table cache size problem in '%s'"), pExtent->pszFullname);
2858 goto out;
2859 }
2860
2861 rc = vmdkAllocStreamBuffers(pImage, pExtent);
2862 if (RT_FAILURE(rc))
2863 goto out;
2864
2865 /* Prohibit any writes to this streamOptimized extent. */
2866 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
2867 pExtent->uAppendPosition = 0;
2868
2869 if ( !(pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
2870 || !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2871 || !(pImage->uOpenFlags & VD_OPEN_FLAGS_SEQUENTIAL))
2872 rc = vmdkReadGrainDirectory(pImage, pExtent);
2873 else
2874 {
2875 pExtent->uGrainSectorAbs = pExtent->cOverheadSectors;
2876 pExtent->cbGrainStreamRead = 0;
2877 }
2878
2879out:
2880 if (RT_FAILURE(rc))
2881 vmdkFreeExtentData(pImage, pExtent, false);
2882
2883 return rc;
2884}
2885
2886/**
2887 * Internal: write/update the metadata for a sparse extent.
2888 */
2889static int vmdkWriteMetaSparseExtent(PVMDKIMAGE pImage, PVMDKEXTENT pExtent,
2890 uint64_t uOffset)
2891{
2892 SparseExtentHeader Header;
2893
2894 memset(&Header, '\0', sizeof(Header));
2895 Header.magicNumber = RT_H2LE_U32(VMDK_SPARSE_MAGICNUMBER);
2896 Header.version = RT_H2LE_U32(pExtent->uVersion);
2897 Header.flags = RT_H2LE_U32(RT_BIT(0));
2898 if (pExtent->pRGD)
2899 Header.flags |= RT_H2LE_U32(RT_BIT(1));
2900 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
2901 Header.flags |= RT_H2LE_U32(RT_BIT(16) | RT_BIT(17));
2902 Header.capacity = RT_H2LE_U64(pExtent->cSectors);
2903 Header.grainSize = RT_H2LE_U64(pExtent->cSectorsPerGrain);
2904 Header.descriptorOffset = RT_H2LE_U64(pExtent->uDescriptorSector);
2905 Header.descriptorSize = RT_H2LE_U64(pExtent->cDescriptorSectors);
2906 Header.numGTEsPerGT = RT_H2LE_U32(pExtent->cGTEntries);
2907 if (pExtent->fFooter && uOffset == 0)
2908 {
2909 if (pExtent->pRGD)
2910 {
2911 Assert(pExtent->uSectorRGD);
2912 Header.rgdOffset = RT_H2LE_U64(VMDK_GD_AT_END);
2913 Header.gdOffset = RT_H2LE_U64(VMDK_GD_AT_END);
2914 }
2915 else
2916 {
2917 Header.gdOffset = RT_H2LE_U64(VMDK_GD_AT_END);
2918 }
2919 }
2920 else
2921 {
2922 if (pExtent->pRGD)
2923 {
2924 Assert(pExtent->uSectorRGD);
2925 Header.rgdOffset = RT_H2LE_U64(pExtent->uSectorRGD);
2926 Header.gdOffset = RT_H2LE_U64(pExtent->uSectorGD);
2927 }
2928 else
2929 {
2930 Header.gdOffset = RT_H2LE_U64(pExtent->uSectorGD);
2931 }
2932 }
2933 Header.overHead = RT_H2LE_U64(pExtent->cOverheadSectors);
2934 Header.uncleanShutdown = pExtent->fUncleanShutdown;
2935 Header.singleEndLineChar = '\n';
2936 Header.nonEndLineChar = ' ';
2937 Header.doubleEndLineChar1 = '\r';
2938 Header.doubleEndLineChar2 = '\n';
2939 Header.compressAlgorithm = RT_H2LE_U16(pExtent->uCompression);
2940
2941 int rc = vmdkFileWriteSync(pImage, pExtent->pFile, uOffset, &Header, sizeof(Header), NULL);
2942 AssertRC(rc);
2943 if (RT_FAILURE(rc))
2944 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error writing extent header in '%s'"), pExtent->pszFullname);
2945 return rc;
2946}
2947
2948/**
2949 * Internal: write/update the metadata for a sparse extent - async version.
2950 */
2951static int vmdkWriteMetaSparseExtentAsync(PVMDKIMAGE pImage, PVMDKEXTENT pExtent,
2952 uint64_t uOffset, PVDIOCTX pIoCtx)
2953{
2954 SparseExtentHeader Header;
2955
2956 memset(&Header, '\0', sizeof(Header));
2957 Header.magicNumber = RT_H2LE_U32(VMDK_SPARSE_MAGICNUMBER);
2958 Header.version = RT_H2LE_U32(pExtent->uVersion);
2959 Header.flags = RT_H2LE_U32(RT_BIT(0));
2960 if (pExtent->pRGD)
2961 Header.flags |= RT_H2LE_U32(RT_BIT(1));
2962 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
2963 Header.flags |= RT_H2LE_U32(RT_BIT(16) | RT_BIT(17));
2964 Header.capacity = RT_H2LE_U64(pExtent->cSectors);
2965 Header.grainSize = RT_H2LE_U64(pExtent->cSectorsPerGrain);
2966 Header.descriptorOffset = RT_H2LE_U64(pExtent->uDescriptorSector);
2967 Header.descriptorSize = RT_H2LE_U64(pExtent->cDescriptorSectors);
2968 Header.numGTEsPerGT = RT_H2LE_U32(pExtent->cGTEntries);
2969 if (pExtent->fFooter && uOffset == 0)
2970 {
2971 if (pExtent->pRGD)
2972 {
2973 Assert(pExtent->uSectorRGD);
2974 Header.rgdOffset = RT_H2LE_U64(VMDK_GD_AT_END);
2975 Header.gdOffset = RT_H2LE_U64(VMDK_GD_AT_END);
2976 }
2977 else
2978 {
2979 Header.gdOffset = RT_H2LE_U64(VMDK_GD_AT_END);
2980 }
2981 }
2982 else
2983 {
2984 if (pExtent->pRGD)
2985 {
2986 Assert(pExtent->uSectorRGD);
2987 Header.rgdOffset = RT_H2LE_U64(pExtent->uSectorRGD);
2988 Header.gdOffset = RT_H2LE_U64(pExtent->uSectorGD);
2989 }
2990 else
2991 {
2992 Header.gdOffset = RT_H2LE_U64(pExtent->uSectorGD);
2993 }
2994 }
2995 Header.overHead = RT_H2LE_U64(pExtent->cOverheadSectors);
2996 Header.uncleanShutdown = pExtent->fUncleanShutdown;
2997 Header.singleEndLineChar = '\n';
2998 Header.nonEndLineChar = ' ';
2999 Header.doubleEndLineChar1 = '\r';
3000 Header.doubleEndLineChar2 = '\n';
3001 Header.compressAlgorithm = RT_H2LE_U16(pExtent->uCompression);
3002
3003 int rc = vmdkFileWriteMetaAsync(pImage, pExtent->pFile,
3004 uOffset, &Header, sizeof(Header),
3005 pIoCtx, NULL, NULL);
3006 if (RT_FAILURE(rc) && (rc != VERR_VD_ASYNC_IO_IN_PROGRESS))
3007 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error writing extent header in '%s'"), pExtent->pszFullname);
3008 return rc;
3009}
3010
3011#ifdef VBOX_WITH_VMDK_ESX
3012/**
3013 * Internal: unused code to read the metadata of a sparse ESX extent.
3014 *
3015 * Such extents never leave ESX server, so this isn't ever used.
3016 */
3017static int vmdkReadMetaESXSparseExtent(PVMDKEXTENT pExtent)
3018{
3019 COWDisk_Header Header;
3020 uint64_t cSectorsPerGDE;
3021
3022 int rc = vmdkFileReadSync(pImage, pExtent->pFile, 0, &Header, sizeof(Header), NULL);
3023 AssertRC(rc);
3024 if (RT_FAILURE(rc))
3025 goto out;
3026 if ( RT_LE2H_U32(Header.magicNumber) != VMDK_ESX_SPARSE_MAGICNUMBER
3027 || RT_LE2H_U32(Header.version) != 1
3028 || RT_LE2H_U32(Header.flags) != 3)
3029 {
3030 rc = VERR_VD_VMDK_INVALID_HEADER;
3031 goto out;
3032 }
3033 pExtent->enmType = VMDKETYPE_ESX_SPARSE;
3034 pExtent->cSectors = RT_LE2H_U32(Header.numSectors);
3035 pExtent->cSectorsPerGrain = RT_LE2H_U32(Header.grainSize);
3036 /* The spec says that this must be between 1 sector and 1MB. This code
3037 * assumes it's a power of two, so check that requirement, too. */
3038 if ( (pExtent->cSectorsPerGrain & (pExtent->cSectorsPerGrain - 1))
3039 || pExtent->cSectorsPerGrain == 0
3040 || pExtent->cSectorsPerGrain > 2048)
3041 {
3042 rc = VERR_VD_VMDK_INVALID_HEADER;
3043 goto out;
3044 }
3045 pExtent->uDescriptorSector = 0;
3046 pExtent->cDescriptorSectors = 0;
3047 pExtent->uSectorGD = RT_LE2H_U32(Header.gdOffset);
3048 pExtent->uSectorRGD = 0;
3049 pExtent->cOverheadSectors = 0;
3050 pExtent->cGTEntries = 4096;
3051 cSectorsPerGDE = pExtent->cGTEntries * pExtent->cSectorsPerGrain;
3052 if (!cSectorsPerGDE || cSectorsPerGDE > UINT32_MAX)
3053 {
3054 rc = VERR_VD_VMDK_INVALID_HEADER;
3055 goto out;
3056 }
3057 pExtent->cSectorsPerGDE = cSectorsPerGDE;
3058 pExtent->cGDEntries = (pExtent->cSectors + cSectorsPerGDE - 1) / cSectorsPerGDE;
3059 if (pExtent->cGDEntries != RT_LE2H_U32(Header.numGDEntries))
3060 {
3061 /* Inconsistency detected. Computed number of GD entries doesn't match
3062 * stored value. Better be safe than sorry. */
3063 rc = VERR_VD_VMDK_INVALID_HEADER;
3064 goto out;
3065 }
3066 pExtent->uFreeSector = RT_LE2H_U32(Header.freeSector);
3067 pExtent->fUncleanShutdown = !!Header.uncleanShutdown;
3068
3069 rc = vmdkReadGrainDirectory(pImage, pExtent);
3070
3071out:
3072 if (RT_FAILURE(rc))
3073 vmdkFreeExtentData(pImage, pExtent, false);
3074
3075 return rc;
3076}
3077#endif /* VBOX_WITH_VMDK_ESX */
3078
3079/**
3080 * Internal: free the buffers used for streamOptimized images.
3081 */
3082static void vmdkFreeStreamBuffers(PVMDKEXTENT pExtent)
3083{
3084 if (pExtent->pvCompGrain)
3085 {
3086 RTMemFree(pExtent->pvCompGrain);
3087 pExtent->pvCompGrain = NULL;
3088 }
3089 if (pExtent->pvGrain)
3090 {
3091 RTMemFree(pExtent->pvGrain);
3092 pExtent->pvGrain = NULL;
3093 }
3094}
3095
3096/**
3097 * Internal: free the memory used by the extent data structure, optionally
3098 * deleting the referenced files.
3099 */
3100static void vmdkFreeExtentData(PVMDKIMAGE pImage, PVMDKEXTENT pExtent,
3101 bool fDelete)
3102{
3103 vmdkFreeGrainDirectory(pExtent);
3104 if (pExtent->pDescData)
3105 {
3106 RTMemFree(pExtent->pDescData);
3107 pExtent->pDescData = NULL;
3108 }
3109 if (pExtent->pFile != NULL)
3110 {
3111 /* Do not delete raw extents, these have full and base names equal. */
3112 vmdkFileClose(pImage, &pExtent->pFile,
3113 fDelete
3114 && pExtent->pszFullname
3115 && strcmp(pExtent->pszFullname, pExtent->pszBasename));
3116 }
3117 if (pExtent->pszBasename)
3118 {
3119 RTMemTmpFree((void *)pExtent->pszBasename);
3120 pExtent->pszBasename = NULL;
3121 }
3122 if (pExtent->pszFullname)
3123 {
3124 RTStrFree((char *)(void *)pExtent->pszFullname);
3125 pExtent->pszFullname = NULL;
3126 }
3127 vmdkFreeStreamBuffers(pExtent);
3128}
3129
3130/**
3131 * Internal: allocate grain table cache if necessary for this image.
3132 */
3133static int vmdkAllocateGrainTableCache(PVMDKIMAGE pImage)
3134{
3135 PVMDKEXTENT pExtent;
3136
3137 /* Allocate grain table cache if any sparse extent is present. */
3138 for (unsigned i = 0; i < pImage->cExtents; i++)
3139 {
3140 pExtent = &pImage->pExtents[i];
3141 if ( pExtent->enmType == VMDKETYPE_HOSTED_SPARSE
3142#ifdef VBOX_WITH_VMDK_ESX
3143 || pExtent->enmType == VMDKETYPE_ESX_SPARSE
3144#endif /* VBOX_WITH_VMDK_ESX */
3145 )
3146 {
3147 /* Allocate grain table cache. */
3148 pImage->pGTCache = (PVMDKGTCACHE)RTMemAllocZ(sizeof(VMDKGTCACHE));
3149 if (!pImage->pGTCache)
3150 return VERR_NO_MEMORY;
3151 for (unsigned j = 0; j < VMDK_GT_CACHE_SIZE; j++)
3152 {
3153 PVMDKGTCACHEENTRY pGCE = &pImage->pGTCache->aGTCache[j];
3154 pGCE->uExtent = UINT32_MAX;
3155 }
3156 pImage->pGTCache->cEntries = VMDK_GT_CACHE_SIZE;
3157 break;
3158 }
3159 }
3160
3161 return VINF_SUCCESS;
3162}
3163
3164/**
3165 * Internal: allocate the given number of extents.
3166 */
3167static int vmdkCreateExtents(PVMDKIMAGE pImage, unsigned cExtents)
3168{
3169 int rc = VINF_SUCCESS;
3170 PVMDKEXTENT pExtents = (PVMDKEXTENT)RTMemAllocZ(cExtents * sizeof(VMDKEXTENT));
3171 if (pExtents)
3172 {
3173 for (unsigned i = 0; i < cExtents; i++)
3174 {
3175 pExtents[i].pFile = NULL;
3176 pExtents[i].pszBasename = NULL;
3177 pExtents[i].pszFullname = NULL;
3178 pExtents[i].pGD = NULL;
3179 pExtents[i].pRGD = NULL;
3180 pExtents[i].pDescData = NULL;
3181 pExtents[i].uVersion = 1;
3182 pExtents[i].uCompression = VMDK_COMPRESSION_NONE;
3183 pExtents[i].uExtent = i;
3184 pExtents[i].pImage = pImage;
3185 }
3186 pImage->pExtents = pExtents;
3187 pImage->cExtents = cExtents;
3188 }
3189 else
3190 rc = VERR_NO_MEMORY;
3191
3192 return rc;
3193}
3194
3195/**
3196 * Internal: Open an image, constructing all necessary data structures.
3197 */
3198static int vmdkOpenImage(PVMDKIMAGE pImage, unsigned uOpenFlags)
3199{
3200 int rc;
3201 uint32_t u32Magic;
3202 PVMDKFILE pFile;
3203 PVMDKEXTENT pExtent;
3204
3205 pImage->uOpenFlags = uOpenFlags;
3206
3207 /* Try to get error interface. */
3208 pImage->pInterfaceError = VDInterfaceGet(pImage->pVDIfsDisk, VDINTERFACETYPE_ERROR);
3209 if (pImage->pInterfaceError)
3210 pImage->pInterfaceErrorCallbacks = VDGetInterfaceError(pImage->pInterfaceError);
3211
3212 /* Get I/O interface. */
3213 pImage->pInterfaceIO = VDInterfaceGet(pImage->pVDIfsImage, VDINTERFACETYPE_IOINT);
3214 AssertPtrReturn(pImage->pInterfaceIO, VERR_INVALID_PARAMETER);
3215 pImage->pInterfaceIOCallbacks = VDGetInterfaceIOInt(pImage->pInterfaceIO);
3216 AssertPtrReturn(pImage->pInterfaceIOCallbacks, VERR_INVALID_PARAMETER);
3217
3218 /*
3219 * Open the image.
3220 * We don't have to check for asynchronous access because
3221 * we only support raw access and the opened file is a description
3222 * file were no data is stored.
3223 */
3224
3225 rc = vmdkFileOpen(pImage, &pFile, pImage->pszFilename,
3226 VDOpenFlagsToFileOpenFlags(uOpenFlags, false /* fCreate */),
3227 false /* fAsyncIO */);
3228 if (RT_FAILURE(rc))
3229 {
3230 /* Do NOT signal an appropriate error here, as the VD layer has the
3231 * choice of retrying the open if it failed. */
3232 goto out;
3233 }
3234 pImage->pFile = pFile;
3235
3236 /* Read magic (if present). */
3237 rc = vmdkFileReadSync(pImage, pFile, 0, &u32Magic, sizeof(u32Magic), NULL);
3238 if (RT_FAILURE(rc))
3239 {
3240 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error reading the magic number in '%s'"), pImage->pszFilename);
3241 goto out;
3242 }
3243
3244 /* Handle the file according to its magic number. */
3245 if (RT_LE2H_U32(u32Magic) == VMDK_SPARSE_MAGICNUMBER)
3246 {
3247 /* It's a hosted single-extent image. */
3248 rc = vmdkCreateExtents(pImage, 1);
3249 if (RT_FAILURE(rc))
3250 goto out;
3251 /* The opened file is passed to the extent. No separate descriptor
3252 * file, so no need to keep anything open for the image. */
3253 pExtent = &pImage->pExtents[0];
3254 pExtent->pFile = pFile;
3255 pImage->pFile = NULL;
3256 pExtent->pszFullname = RTPathAbsDup(pImage->pszFilename);
3257 if (!pExtent->pszFullname)
3258 {
3259 rc = VERR_NO_MEMORY;
3260 goto out;
3261 }
3262 rc = vmdkReadBinaryMetaExtent(pImage, pExtent, true /* fMagicAlreadyRead */);
3263 if (RT_FAILURE(rc))
3264 goto out;
3265
3266 /* As we're dealing with a monolithic image here, there must
3267 * be a descriptor embedded in the image file. */
3268 if (!pExtent->uDescriptorSector || !pExtent->cDescriptorSectors)
3269 {
3270 rc = vmdkError(pImage, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: monolithic image without descriptor in '%s'"), pImage->pszFilename);
3271 goto out;
3272 }
3273 /* HACK: extend the descriptor if it is unusually small and it fits in
3274 * the unused space after the image header. Allows opening VMDK files
3275 * with extremely small descriptor in read/write mode. */
3276 if ( !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
3277 && pExtent->cDescriptorSectors < 3
3278 && (int64_t)pExtent->uSectorGD - pExtent->uDescriptorSector >= 4
3279 && (!pExtent->uSectorRGD || (int64_t)pExtent->uSectorRGD - pExtent->uDescriptorSector >= 4))
3280 {
3281 pExtent->cDescriptorSectors = 4;
3282 pExtent->fMetaDirty = true;
3283 }
3284 /* Read the descriptor from the extent. */
3285 pExtent->pDescData = (char *)RTMemAllocZ(VMDK_SECTOR2BYTE(pExtent->cDescriptorSectors));
3286 if (!pExtent->pDescData)
3287 {
3288 rc = VERR_NO_MEMORY;
3289 goto out;
3290 }
3291 rc = vmdkFileReadSync(pImage, pExtent->pFile,
3292 VMDK_SECTOR2BYTE(pExtent->uDescriptorSector),
3293 pExtent->pDescData,
3294 VMDK_SECTOR2BYTE(pExtent->cDescriptorSectors), NULL);
3295 AssertRC(rc);
3296 if (RT_FAILURE(rc))
3297 {
3298 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: read error for descriptor in '%s'"), pExtent->pszFullname);
3299 goto out;
3300 }
3301
3302 rc = vmdkParseDescriptor(pImage, pExtent->pDescData,
3303 VMDK_SECTOR2BYTE(pExtent->cDescriptorSectors));
3304 if (RT_FAILURE(rc))
3305 goto out;
3306
3307 if ( pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED
3308 && uOpenFlags & VD_OPEN_FLAGS_ASYNC_IO)
3309 {
3310 rc = VERR_NOT_SUPPORTED;
3311 goto out;
3312 }
3313
3314 rc = vmdkReadMetaExtent(pImage, pExtent);
3315 if (RT_FAILURE(rc))
3316 goto out;
3317
3318 /* Mark the extent as unclean if opened in read-write mode. */
3319 if ( !(uOpenFlags & VD_OPEN_FLAGS_READONLY)
3320 && !(pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED))
3321 {
3322 pExtent->fUncleanShutdown = true;
3323 pExtent->fMetaDirty = true;
3324 }
3325 }
3326 else
3327 {
3328 /* Allocate at least 10K, and make sure that there is 5K free space
3329 * in case new entries need to be added to the descriptor. Never
3330 * allocate more than 128K, because that's no valid descriptor file
3331 * and will result in the correct "truncated read" error handling. */
3332 uint64_t cbFileSize;
3333 rc = vmdkFileGetSize(pImage, pFile, &cbFileSize);
3334 if (RT_FAILURE(rc))
3335 goto out;
3336
3337 /* If the descriptor file is shorter than 50 bytes it can't be valid. */
3338 if (cbFileSize < 50)
3339 {
3340 rc = vmdkError(pImage, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: descriptor in '%s' is too short"), pImage->pszFilename);
3341 goto out;
3342 }
3343
3344 uint64_t cbSize = cbFileSize;
3345 if (cbSize % VMDK_SECTOR2BYTE(10))
3346 cbSize += VMDK_SECTOR2BYTE(20) - cbSize % VMDK_SECTOR2BYTE(10);
3347 else
3348 cbSize += VMDK_SECTOR2BYTE(10);
3349 cbSize = RT_MIN(cbSize, _128K);
3350 pImage->cbDescAlloc = RT_MAX(VMDK_SECTOR2BYTE(20), cbSize);
3351 pImage->pDescData = (char *)RTMemAllocZ(pImage->cbDescAlloc);
3352 if (!pImage->pDescData)
3353 {
3354 rc = VERR_NO_MEMORY;
3355 goto out;
3356 }
3357
3358 /* Don't reread the place where the magic would live in a sparse
3359 * image if it's a descriptor based one. */
3360 memcpy(pImage->pDescData, &u32Magic, sizeof(u32Magic));
3361 size_t cbRead;
3362 rc = vmdkFileReadSync(pImage, pImage->pFile, sizeof(u32Magic),
3363 pImage->pDescData + sizeof(u32Magic),
3364 RT_MIN(pImage->cbDescAlloc - sizeof(u32Magic),
3365 cbFileSize - sizeof(u32Magic)),
3366 &cbRead);
3367 if (RT_FAILURE(rc))
3368 {
3369 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: read error for descriptor in '%s'"), pImage->pszFilename);
3370 goto out;
3371 }
3372 cbRead += sizeof(u32Magic);
3373 if (cbRead == pImage->cbDescAlloc)
3374 {
3375 /* Likely the read is truncated. Better fail a bit too early
3376 * (normally the descriptor is much smaller than our buffer). */
3377 rc = vmdkError(pImage, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: cannot read descriptor in '%s'"), pImage->pszFilename);
3378 goto out;
3379 }
3380
3381 rc = vmdkParseDescriptor(pImage, pImage->pDescData,
3382 pImage->cbDescAlloc);
3383 if (RT_FAILURE(rc))
3384 goto out;
3385
3386 /*
3387 * We have to check for the asynchronous open flag. The
3388 * extents are parsed and the type of all are known now.
3389 * Check if every extent is either FLAT or ZERO.
3390 */
3391 if (uOpenFlags & VD_OPEN_FLAGS_ASYNC_IO)
3392 {
3393 unsigned cFlatExtents = 0;
3394
3395 for (unsigned i = 0; i < pImage->cExtents; i++)
3396 {
3397 pExtent = &pImage->pExtents[i];
3398
3399 if (( pExtent->enmType != VMDKETYPE_FLAT
3400 && pExtent->enmType != VMDKETYPE_ZERO
3401 && pExtent->enmType != VMDKETYPE_VMFS)
3402 || ((pImage->pExtents[i].enmType == VMDKETYPE_FLAT) && (cFlatExtents > 0)))
3403 {
3404 /*
3405 * Opened image contains at least one none flat or zero extent.
3406 * Return error but don't set error message as the caller
3407 * has the chance to open in non async I/O mode.
3408 */
3409 rc = VERR_NOT_SUPPORTED;
3410 goto out;
3411 }
3412 if (pExtent->enmType == VMDKETYPE_FLAT)
3413 cFlatExtents++;
3414 }
3415 }
3416
3417 for (unsigned i = 0; i < pImage->cExtents; i++)
3418 {
3419 pExtent = &pImage->pExtents[i];
3420
3421 if (pExtent->pszBasename)
3422 {
3423 /* Hack to figure out whether the specified name in the
3424 * extent descriptor is absolute. Doesn't always work, but
3425 * should be good enough for now. */
3426 char *pszFullname;
3427 /** @todo implement proper path absolute check. */
3428 if (pExtent->pszBasename[0] == RTPATH_SLASH)
3429 {
3430 pszFullname = RTStrDup(pExtent->pszBasename);
3431 if (!pszFullname)
3432 {
3433 rc = VERR_NO_MEMORY;
3434 goto out;
3435 }
3436 }
3437 else
3438 {
3439 char *pszDirname = RTStrDup(pImage->pszFilename);
3440 if (!pszDirname)
3441 {
3442 rc = VERR_NO_MEMORY;
3443 goto out;
3444 }
3445 RTPathStripFilename(pszDirname);
3446 pszFullname = RTPathJoinA(pszDirname, pExtent->pszBasename);
3447 RTStrFree(pszDirname);
3448 if (!pszFullname)
3449 {
3450 rc = VERR_NO_STR_MEMORY;
3451 goto out;
3452 }
3453 }
3454 pExtent->pszFullname = pszFullname;
3455 }
3456 else
3457 pExtent->pszFullname = NULL;
3458
3459 switch (pExtent->enmType)
3460 {
3461 case VMDKETYPE_HOSTED_SPARSE:
3462 rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszFullname,
3463 VDOpenFlagsToFileOpenFlags(uOpenFlags,
3464 false /* fCreate */),
3465 false /* fAsyncIO */);
3466 if (RT_FAILURE(rc))
3467 {
3468 /* Do NOT signal an appropriate error here, as the VD
3469 * layer has the choice of retrying the open if it
3470 * failed. */
3471 goto out;
3472 }
3473 rc = vmdkReadBinaryMetaExtent(pImage, pExtent,
3474 false /* fMagicAlreadyRead */);
3475 if (RT_FAILURE(rc))
3476 goto out;
3477 rc = vmdkReadMetaExtent(pImage, pExtent);
3478 if (RT_FAILURE(rc))
3479 goto out;
3480
3481 /* Mark extent as unclean if opened in read-write mode. */
3482 if (!(uOpenFlags & VD_OPEN_FLAGS_READONLY))
3483 {
3484 pExtent->fUncleanShutdown = true;
3485 pExtent->fMetaDirty = true;
3486 }
3487 break;
3488 case VMDKETYPE_VMFS:
3489 case VMDKETYPE_FLAT:
3490 rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszFullname,
3491 VDOpenFlagsToFileOpenFlags(uOpenFlags,
3492 false /* fCreate */),
3493 true /* fAsyncIO */);
3494 if (RT_FAILURE(rc))
3495 {
3496 /* Do NOT signal an appropriate error here, as the VD
3497 * layer has the choice of retrying the open if it
3498 * failed. */
3499 goto out;
3500 }
3501 break;
3502 case VMDKETYPE_ZERO:
3503 /* Nothing to do. */
3504 break;
3505 default:
3506 AssertMsgFailed(("unknown vmdk extent type %d\n", pExtent->enmType));
3507 }
3508 }
3509 }
3510
3511 /* Make sure this is not reached accidentally with an error status. */
3512 AssertRC(rc);
3513
3514 /* Determine PCHS geometry if not set. */
3515 if (pImage->PCHSGeometry.cCylinders == 0)
3516 {
3517 uint64_t cCylinders = VMDK_BYTE2SECTOR(pImage->cbSize)
3518 / pImage->PCHSGeometry.cHeads
3519 / pImage->PCHSGeometry.cSectors;
3520 pImage->PCHSGeometry.cCylinders = (unsigned)RT_MIN(cCylinders, 16383);
3521 if ( !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
3522 && !(pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED))
3523 {
3524 rc = vmdkDescSetPCHSGeometry(pImage, &pImage->PCHSGeometry);
3525 AssertRC(rc);
3526 }
3527 }
3528
3529 /* Update the image metadata now in case has changed. */
3530 rc = vmdkFlushImage(pImage);
3531 if (RT_FAILURE(rc))
3532 goto out;
3533
3534 /* Figure out a few per-image constants from the extents. */
3535 pImage->cbSize = 0;
3536 for (unsigned i = 0; i < pImage->cExtents; i++)
3537 {
3538 pExtent = &pImage->pExtents[i];
3539 if ( pExtent->enmType == VMDKETYPE_HOSTED_SPARSE
3540#ifdef VBOX_WITH_VMDK_ESX
3541 || pExtent->enmType == VMDKETYPE_ESX_SPARSE
3542#endif /* VBOX_WITH_VMDK_ESX */
3543 )
3544 {
3545 /* Here used to be a check whether the nominal size of an extent
3546 * is a multiple of the grain size. The spec says that this is
3547 * always the case, but unfortunately some files out there in the
3548 * wild violate the spec (e.g. ReactOS 0.3.1). */
3549 }
3550 pImage->cbSize += VMDK_SECTOR2BYTE(pExtent->cNominalSectors);
3551 }
3552
3553 for (unsigned i = 0; i < pImage->cExtents; i++)
3554 {
3555 pExtent = &pImage->pExtents[i];
3556 if ( pImage->pExtents[i].enmType == VMDKETYPE_FLAT
3557 || pImage->pExtents[i].enmType == VMDKETYPE_ZERO)
3558 {
3559 pImage->uImageFlags |= VD_IMAGE_FLAGS_FIXED;
3560 break;
3561 }
3562 }
3563
3564 if ( !(pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
3565 || !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
3566 || !(pImage->uOpenFlags & VD_OPEN_FLAGS_SEQUENTIAL))
3567 rc = vmdkAllocateGrainTableCache(pImage);
3568
3569out:
3570 if (RT_FAILURE(rc))
3571 vmdkFreeImage(pImage, false);
3572 return rc;
3573}
3574
3575/**
3576 * Internal: create VMDK images for raw disk/partition access.
3577 */
3578static int vmdkCreateRawImage(PVMDKIMAGE pImage, const PVBOXHDDRAW pRaw,
3579 uint64_t cbSize)
3580{
3581 int rc = VINF_SUCCESS;
3582 PVMDKEXTENT pExtent;
3583
3584 if (pRaw->fRawDisk)
3585 {
3586 /* Full raw disk access. This requires setting up a descriptor
3587 * file and open the (flat) raw disk. */
3588 rc = vmdkCreateExtents(pImage, 1);
3589 if (RT_FAILURE(rc))
3590 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not create new extent list in '%s'"), pImage->pszFilename);
3591 pExtent = &pImage->pExtents[0];
3592 /* Create raw disk descriptor file. */
3593 rc = vmdkFileOpen(pImage, &pImage->pFile, pImage->pszFilename,
3594 VDOpenFlagsToFileOpenFlags(pImage->uOpenFlags,
3595 true /* fCreate */),
3596 false /* fAsyncIO */);
3597 if (RT_FAILURE(rc))
3598 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not create new file '%s'"), pImage->pszFilename);
3599
3600 /* Set up basename for extent description. Cannot use StrDup. */
3601 size_t cbBasename = strlen(pRaw->pszRawDisk) + 1;
3602 char *pszBasename = (char *)RTMemTmpAlloc(cbBasename);
3603 if (!pszBasename)
3604 return VERR_NO_MEMORY;
3605 memcpy(pszBasename, pRaw->pszRawDisk, cbBasename);
3606 pExtent->pszBasename = pszBasename;
3607 /* For raw disks the full name is identical to the base name. */
3608 pExtent->pszFullname = RTStrDup(pszBasename);
3609 if (!pExtent->pszFullname)
3610 return VERR_NO_MEMORY;
3611 pExtent->enmType = VMDKETYPE_FLAT;
3612 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(cbSize);
3613 pExtent->uSectorOffset = 0;
3614 pExtent->enmAccess = VMDKACCESS_READWRITE;
3615 pExtent->fMetaDirty = false;
3616
3617 /* Open flat image, the raw disk. */
3618 rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszFullname,
3619 VDOpenFlagsToFileOpenFlags(pImage->uOpenFlags & ~VD_OPEN_FLAGS_READONLY,
3620 false /* fCreate */),
3621 false /* fAsyncIO */);
3622 if (RT_FAILURE(rc))
3623 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not open raw disk file '%s'"), pExtent->pszFullname);
3624 }
3625 else
3626 {
3627 /* Raw partition access. This requires setting up a descriptor
3628 * file, write the partition information to a flat extent and
3629 * open all the (flat) raw disk partitions. */
3630
3631 /* First pass over the partition data areas to determine how many
3632 * extents we need. One data area can require up to 2 extents, as
3633 * it might be necessary to skip over unpartitioned space. */
3634 unsigned cExtents = 0;
3635 uint64_t uStart = 0;
3636 for (unsigned i = 0; i < pRaw->cPartDescs; i++)
3637 {
3638 PVBOXHDDRAWPARTDESC pPart = &pRaw->pPartDescs[i];
3639 if (uStart > pPart->uStart)
3640 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);
3641
3642 if (uStart < pPart->uStart)
3643 cExtents++;
3644 uStart = pPart->uStart + pPart->cbData;
3645 cExtents++;
3646 }
3647 /* Another extent for filling up the rest of the image. */
3648 if (uStart != cbSize)
3649 cExtents++;
3650
3651 rc = vmdkCreateExtents(pImage, cExtents);
3652 if (RT_FAILURE(rc))
3653 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not create new extent list in '%s'"), pImage->pszFilename);
3654
3655 /* Create raw partition descriptor file. */
3656 rc = vmdkFileOpen(pImage, &pImage->pFile, pImage->pszFilename,
3657 VDOpenFlagsToFileOpenFlags(pImage->uOpenFlags,
3658 true /* fCreate */),
3659 false /* fAsyncIO */);
3660 if (RT_FAILURE(rc))
3661 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not create new file '%s'"), pImage->pszFilename);
3662
3663 /* Create base filename for the partition table extent. */
3664 /** @todo remove fixed buffer without creating memory leaks. */
3665 char pszPartition[1024];
3666 const char *pszBase = RTPathFilename(pImage->pszFilename);
3667 const char *pszExt = RTPathExt(pszBase);
3668 if (pszExt == NULL)
3669 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: invalid filename '%s'"), pImage->pszFilename);
3670 char *pszBaseBase = RTStrDup(pszBase);
3671 if (!pszBaseBase)
3672 return VERR_NO_MEMORY;
3673 RTPathStripExt(pszBaseBase);
3674 RTStrPrintf(pszPartition, sizeof(pszPartition), "%s-pt%s",
3675 pszBaseBase, pszExt);
3676 RTStrFree(pszBaseBase);
3677
3678 /* Second pass over the partitions, now define all extents. */
3679 uint64_t uPartOffset = 0;
3680 cExtents = 0;
3681 uStart = 0;
3682 for (unsigned i = 0; i < pRaw->cPartDescs; i++)
3683 {
3684 PVBOXHDDRAWPARTDESC pPart = &pRaw->pPartDescs[i];
3685 pExtent = &pImage->pExtents[cExtents++];
3686
3687 if (uStart < pPart->uStart)
3688 {
3689 pExtent->pszBasename = NULL;
3690 pExtent->pszFullname = NULL;
3691 pExtent->enmType = VMDKETYPE_ZERO;
3692 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(pPart->uStart - uStart);
3693 pExtent->uSectorOffset = 0;
3694 pExtent->enmAccess = VMDKACCESS_READWRITE;
3695 pExtent->fMetaDirty = false;
3696 /* go to next extent */
3697 pExtent = &pImage->pExtents[cExtents++];
3698 }
3699 uStart = pPart->uStart + pPart->cbData;
3700
3701 if (pPart->pvPartitionData)
3702 {
3703 /* Set up basename for extent description. Can't use StrDup. */
3704 size_t cbBasename = strlen(pszPartition) + 1;
3705 char *pszBasename = (char *)RTMemTmpAlloc(cbBasename);
3706 if (!pszBasename)
3707 return VERR_NO_MEMORY;
3708 memcpy(pszBasename, pszPartition, cbBasename);
3709 pExtent->pszBasename = pszBasename;
3710
3711 /* Set up full name for partition extent. */
3712 char *pszDirname = RTStrDup(pImage->pszFilename);
3713 if (!pszDirname)
3714 return VERR_NO_STR_MEMORY;
3715 RTPathStripFilename(pszDirname);
3716 char *pszFullname = RTPathJoinA(pszDirname, pExtent->pszBasename);
3717 RTStrFree(pszDirname);
3718 if (!pszDirname)
3719 return VERR_NO_STR_MEMORY;
3720 pExtent->pszFullname = pszFullname;
3721 pExtent->enmType = VMDKETYPE_FLAT;
3722 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(pPart->cbData);
3723 pExtent->uSectorOffset = uPartOffset;
3724 pExtent->enmAccess = VMDKACCESS_READWRITE;
3725 pExtent->fMetaDirty = false;
3726
3727 /* Create partition table flat image. */
3728 rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszFullname,
3729 VDOpenFlagsToFileOpenFlags(pImage->uOpenFlags,
3730 true /* fCreate */),
3731 false /* fAsyncIO */);
3732 if (RT_FAILURE(rc))
3733 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not create new partition data file '%s'"), pExtent->pszFullname);
3734 rc = vmdkFileWriteSync(pImage, pExtent->pFile,
3735 VMDK_SECTOR2BYTE(uPartOffset),
3736 pPart->pvPartitionData,
3737 pPart->cbData, NULL);
3738 if (RT_FAILURE(rc))
3739 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not write partition data to '%s'"), pExtent->pszFullname);
3740 uPartOffset += VMDK_BYTE2SECTOR(pPart->cbData);
3741 }
3742 else
3743 {
3744 if (pPart->pszRawDevice)
3745 {
3746 /* Set up basename for extent descr. Can't use StrDup. */
3747 size_t cbBasename = strlen(pPart->pszRawDevice) + 1;
3748 char *pszBasename = (char *)RTMemTmpAlloc(cbBasename);
3749 if (!pszBasename)
3750 return VERR_NO_MEMORY;
3751 memcpy(pszBasename, pPart->pszRawDevice, cbBasename);
3752 pExtent->pszBasename = pszBasename;
3753 /* For raw disks full name is identical to base name. */
3754 pExtent->pszFullname = RTStrDup(pszBasename);
3755 if (!pExtent->pszFullname)
3756 return VERR_NO_MEMORY;
3757 pExtent->enmType = VMDKETYPE_FLAT;
3758 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(pPart->cbData);
3759 pExtent->uSectorOffset = VMDK_BYTE2SECTOR(pPart->uStartOffset);
3760 pExtent->enmAccess = VMDKACCESS_READWRITE;
3761 pExtent->fMetaDirty = false;
3762
3763 /* Open flat image, the raw partition. */
3764 rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszFullname,
3765 VDOpenFlagsToFileOpenFlags(pImage->uOpenFlags & ~VD_OPEN_FLAGS_READONLY,
3766 false /* fCreate */),
3767 false /* fAsyncIO */);
3768 if (RT_FAILURE(rc))
3769 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not open raw partition file '%s'"), pExtent->pszFullname);
3770 }
3771 else
3772 {
3773 pExtent->pszBasename = NULL;
3774 pExtent->pszFullname = NULL;
3775 pExtent->enmType = VMDKETYPE_ZERO;
3776 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(pPart->cbData);
3777 pExtent->uSectorOffset = 0;
3778 pExtent->enmAccess = VMDKACCESS_READWRITE;
3779 pExtent->fMetaDirty = false;
3780 }
3781 }
3782 }
3783 /* Another extent for filling up the rest of the image. */
3784 if (uStart != cbSize)
3785 {
3786 pExtent = &pImage->pExtents[cExtents++];
3787 pExtent->pszBasename = NULL;
3788 pExtent->pszFullname = NULL;
3789 pExtent->enmType = VMDKETYPE_ZERO;
3790 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(cbSize - uStart);
3791 pExtent->uSectorOffset = 0;
3792 pExtent->enmAccess = VMDKACCESS_READWRITE;
3793 pExtent->fMetaDirty = false;
3794 }
3795 }
3796
3797 rc = vmdkDescBaseSetStr(pImage, &pImage->Descriptor, "createType",
3798 pRaw->fRawDisk ?
3799 "fullDevice" : "partitionedDevice");
3800 if (RT_FAILURE(rc))
3801 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not set the image type in '%s'"), pImage->pszFilename);
3802 return rc;
3803}
3804
3805/**
3806 * Internal: create a regular (i.e. file-backed) VMDK image.
3807 */
3808static int vmdkCreateRegularImage(PVMDKIMAGE pImage, uint64_t cbSize,
3809 unsigned uImageFlags,
3810 PFNVDPROGRESS pfnProgress, void *pvUser,
3811 unsigned uPercentStart, unsigned uPercentSpan)
3812{
3813 int rc = VINF_SUCCESS;
3814 unsigned cExtents = 1;
3815 uint64_t cbOffset = 0;
3816 uint64_t cbRemaining = cbSize;
3817
3818 if (uImageFlags & VD_VMDK_IMAGE_FLAGS_SPLIT_2G)
3819 {
3820 cExtents = cbSize / VMDK_2G_SPLIT_SIZE;
3821 /* Do proper extent computation: need one smaller extent if the total
3822 * size isn't evenly divisible by the split size. */
3823 if (cbSize % VMDK_2G_SPLIT_SIZE)
3824 cExtents++;
3825 }
3826 rc = vmdkCreateExtents(pImage, cExtents);
3827 if (RT_FAILURE(rc))
3828 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not create new extent list in '%s'"), pImage->pszFilename);
3829
3830 /* Basename strings needed for constructing the extent names. */
3831 char *pszBasenameSubstr = RTPathFilename(pImage->pszFilename);
3832 AssertPtr(pszBasenameSubstr);
3833 size_t cbBasenameSubstr = strlen(pszBasenameSubstr) + 1;
3834
3835 /* Create separate descriptor file if necessary. */
3836 if (cExtents != 1 || (uImageFlags & VD_IMAGE_FLAGS_FIXED))
3837 {
3838 rc = vmdkFileOpen(pImage, &pImage->pFile, pImage->pszFilename,
3839 VDOpenFlagsToFileOpenFlags(pImage->uOpenFlags,
3840 true /* fCreate */),
3841 false /* fAsyncIO */);
3842 if (RT_FAILURE(rc))
3843 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not create new sparse descriptor file '%s'"), pImage->pszFilename);
3844 }
3845 else
3846 pImage->pFile = NULL;
3847
3848 /* Set up all extents. */
3849 for (unsigned i = 0; i < cExtents; i++)
3850 {
3851 PVMDKEXTENT pExtent = &pImage->pExtents[i];
3852 uint64_t cbExtent = cbRemaining;
3853
3854 /* Set up fullname/basename for extent description. Cannot use StrDup
3855 * for basename, as it is not guaranteed that the memory can be freed
3856 * with RTMemTmpFree, which must be used as in other code paths
3857 * StrDup is not usable. */
3858 if (cExtents == 1 && !(uImageFlags & VD_IMAGE_FLAGS_FIXED))
3859 {
3860 char *pszBasename = (char *)RTMemTmpAlloc(cbBasenameSubstr);
3861 if (!pszBasename)
3862 return VERR_NO_MEMORY;
3863 memcpy(pszBasename, pszBasenameSubstr, cbBasenameSubstr);
3864 pExtent->pszBasename = pszBasename;
3865 }
3866 else
3867 {
3868 char *pszBasenameExt = RTPathExt(pszBasenameSubstr);
3869 char *pszBasenameBase = RTStrDup(pszBasenameSubstr);
3870 RTPathStripExt(pszBasenameBase);
3871 char *pszTmp;
3872 size_t cbTmp;
3873 if (uImageFlags & VD_IMAGE_FLAGS_FIXED)
3874 {
3875 if (cExtents == 1)
3876 RTStrAPrintf(&pszTmp, "%s-flat%s", pszBasenameBase,
3877 pszBasenameExt);
3878 else
3879 RTStrAPrintf(&pszTmp, "%s-f%03d%s", pszBasenameBase,
3880 i+1, pszBasenameExt);
3881 }
3882 else
3883 RTStrAPrintf(&pszTmp, "%s-s%03d%s", pszBasenameBase, i+1,
3884 pszBasenameExt);
3885 RTStrFree(pszBasenameBase);
3886 if (!pszTmp)
3887 return VERR_NO_STR_MEMORY;
3888 cbTmp = strlen(pszTmp) + 1;
3889 char *pszBasename = (char *)RTMemTmpAlloc(cbTmp);
3890 if (!pszBasename)
3891 return VERR_NO_MEMORY;
3892 memcpy(pszBasename, pszTmp, cbTmp);
3893 RTStrFree(pszTmp);
3894 pExtent->pszBasename = pszBasename;
3895 if (uImageFlags & VD_VMDK_IMAGE_FLAGS_SPLIT_2G)
3896 cbExtent = RT_MIN(cbRemaining, VMDK_2G_SPLIT_SIZE);
3897 }
3898 char *pszBasedirectory = RTStrDup(pImage->pszFilename);
3899 if (!pszBasedirectory)
3900 return VERR_NO_STR_MEMORY;
3901 RTPathStripFilename(pszBasedirectory);
3902 char *pszFullname = RTPathJoinA(pszBasedirectory, pExtent->pszBasename);
3903 RTStrFree(pszBasedirectory);
3904 if (!pszFullname)
3905 return VERR_NO_STR_MEMORY;
3906 pExtent->pszFullname = pszFullname;
3907
3908 /* Create file for extent. */
3909 rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszFullname,
3910 VDOpenFlagsToFileOpenFlags(pImage->uOpenFlags,
3911 true /* fCreate */),
3912 false /* fAsyncIO */);
3913 if (RT_FAILURE(rc))
3914 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not create new file '%s'"), pExtent->pszFullname);
3915 if (uImageFlags & VD_IMAGE_FLAGS_FIXED)
3916 {
3917 rc = vmdkFileSetSize(pImage, pExtent->pFile, cbExtent);
3918 if (RT_FAILURE(rc))
3919 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not set size of new file '%s'"), pExtent->pszFullname);
3920
3921 /* Fill image with zeroes. We do this for every fixed-size image since on some systems
3922 * (for example Windows Vista), it takes ages to write a block near the end of a sparse
3923 * file and the guest could complain about an ATA timeout. */
3924
3925 /** @todo Starting with Linux 2.6.23, there is an fallocate() system call.
3926 * Currently supported file systems are ext4 and ocfs2. */
3927
3928 /* Allocate a temporary zero-filled buffer. Use a bigger block size to optimize writing */
3929 const size_t cbBuf = 128 * _1K;
3930 void *pvBuf = RTMemTmpAllocZ(cbBuf);
3931 if (!pvBuf)
3932 return VERR_NO_MEMORY;
3933
3934 uint64_t uOff = 0;
3935 /* Write data to all image blocks. */
3936 while (uOff < cbExtent)
3937 {
3938 unsigned cbChunk = (unsigned)RT_MIN(cbExtent, cbBuf);
3939
3940 rc = vmdkFileWriteSync(pImage, pExtent->pFile, uOff, pvBuf, cbChunk, NULL);
3941 if (RT_FAILURE(rc))
3942 {
3943 RTMemFree(pvBuf);
3944 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: writing block failed for '%s'"), pImage->pszFilename);
3945 }
3946
3947 uOff += cbChunk;
3948
3949 if (pfnProgress)
3950 {
3951 rc = pfnProgress(pvUser,
3952 uPercentStart + uOff * uPercentSpan / cbExtent);
3953 if (RT_FAILURE(rc))
3954 {
3955 RTMemFree(pvBuf);
3956 return rc;
3957 }
3958 }
3959 }
3960 RTMemTmpFree(pvBuf);
3961 }
3962
3963 /* Place descriptor file information (where integrated). */
3964 if (cExtents == 1 && !(uImageFlags & VD_IMAGE_FLAGS_FIXED))
3965 {
3966 pExtent->uDescriptorSector = 1;
3967 pExtent->cDescriptorSectors = VMDK_BYTE2SECTOR(pImage->cbDescAlloc);
3968 /* The descriptor is part of the (only) extent. */
3969 pExtent->pDescData = pImage->pDescData;
3970 pImage->pDescData = NULL;
3971 }
3972
3973 if (!(uImageFlags & VD_IMAGE_FLAGS_FIXED))
3974 {
3975 uint64_t cSectorsPerGDE, cSectorsPerGD;
3976 pExtent->enmType = VMDKETYPE_HOSTED_SPARSE;
3977 pExtent->cSectors = VMDK_BYTE2SECTOR(RT_ALIGN_64(cbExtent, _64K));
3978 pExtent->cSectorsPerGrain = VMDK_BYTE2SECTOR(_64K);
3979 pExtent->cGTEntries = 512;
3980 cSectorsPerGDE = pExtent->cGTEntries * pExtent->cSectorsPerGrain;
3981 pExtent->cSectorsPerGDE = cSectorsPerGDE;
3982 pExtent->cGDEntries = (pExtent->cSectors + cSectorsPerGDE - 1) / cSectorsPerGDE;
3983 cSectorsPerGD = (pExtent->cGDEntries + (512 / sizeof(uint32_t) - 1)) / (512 / sizeof(uint32_t));
3984 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
3985 {
3986 /* The spec says version is 1 for all VMDKs, but the vast
3987 * majority of streamOptimized VMDKs actually contain
3988 * version 3 - so go with the majority. Both are accepted. */
3989 pExtent->uVersion = 3;
3990 pExtent->uCompression = VMDK_COMPRESSION_DEFLATE;
3991 }
3992 }
3993 else
3994 {
3995 if (uImageFlags & VD_VMDK_IMAGE_FLAGS_ESX)
3996 pExtent->enmType = VMDKETYPE_VMFS;
3997 else
3998 pExtent->enmType = VMDKETYPE_FLAT;
3999 }
4000
4001 pExtent->enmAccess = VMDKACCESS_READWRITE;
4002 pExtent->fUncleanShutdown = true;
4003 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(cbExtent);
4004 pExtent->uSectorOffset = 0;
4005 pExtent->fMetaDirty = true;
4006
4007 if (!(uImageFlags & VD_IMAGE_FLAGS_FIXED))
4008 {
4009 /* fPreAlloc should never be false because VMware can't use such images. */
4010 rc = vmdkCreateGrainDirectory(pImage, pExtent,
4011 RT_MAX( pExtent->uDescriptorSector
4012 + pExtent->cDescriptorSectors,
4013 1),
4014 true /* fPreAlloc */);
4015 if (RT_FAILURE(rc))
4016 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not create new grain directory in '%s'"), pExtent->pszFullname);
4017 }
4018
4019 if (RT_SUCCESS(rc) && pfnProgress)
4020 pfnProgress(pvUser, uPercentStart + i * uPercentSpan / cExtents);
4021
4022 cbRemaining -= cbExtent;
4023 cbOffset += cbExtent;
4024 }
4025
4026 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_ESX)
4027 {
4028 /* VirtualBox doesn't care, but VMWare ESX freaks out if the wrong
4029 * controller type is set in an image. */
4030 rc = vmdkDescDDBSetStr(pImage, &pImage->Descriptor, "ddb.adapterType", "lsilogic");
4031 if (RT_FAILURE(rc))
4032 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not set controller type to lsilogic in '%s'"), pImage->pszFilename);
4033 }
4034
4035 const char *pszDescType = NULL;
4036 if (uImageFlags & VD_IMAGE_FLAGS_FIXED)
4037 {
4038 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_ESX)
4039 pszDescType = "vmfs";
4040 else
4041 pszDescType = (cExtents == 1)
4042 ? "monolithicFlat" : "twoGbMaxExtentFlat";
4043 }
4044 else
4045 {
4046 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
4047 pszDescType = "streamOptimized";
4048 else
4049 {
4050 pszDescType = (cExtents == 1)
4051 ? "monolithicSparse" : "twoGbMaxExtentSparse";
4052 }
4053 }
4054 rc = vmdkDescBaseSetStr(pImage, &pImage->Descriptor, "createType",
4055 pszDescType);
4056 if (RT_FAILURE(rc))
4057 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not set the image type in '%s'"), pImage->pszFilename);
4058 return rc;
4059}
4060
4061/**
4062 * Internal: Create a real stream optimized VMDK using only linear writes.
4063 */
4064static int vmdkCreateStreamImage(PVMDKIMAGE pImage, uint64_t cbSize,
4065 unsigned uImageFlags,
4066 PFNVDPROGRESS pfnProgress, void *pvUser,
4067 unsigned uPercentStart, unsigned uPercentSpan)
4068{
4069 int rc;
4070
4071 rc = vmdkCreateExtents(pImage, 1);
4072 if (RT_FAILURE(rc))
4073 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not create new extent list in '%s'"), pImage->pszFilename);
4074
4075 /* Basename strings needed for constructing the extent names. */
4076 const char *pszBasenameSubstr = RTPathFilename(pImage->pszFilename);
4077 AssertPtr(pszBasenameSubstr);
4078 size_t cbBasenameSubstr = strlen(pszBasenameSubstr) + 1;
4079
4080 /* No separate descriptor file. */
4081 pImage->pFile = NULL;
4082
4083 /* Set up all extents. */
4084 PVMDKEXTENT pExtent = &pImage->pExtents[0];
4085
4086 /* Set up fullname/basename for extent description. Cannot use StrDup
4087 * for basename, as it is not guaranteed that the memory can be freed
4088 * with RTMemTmpFree, which must be used as in other code paths
4089 * StrDup is not usable. */
4090 char *pszBasename = (char *)RTMemTmpAlloc(cbBasenameSubstr);
4091 if (!pszBasename)
4092 return VERR_NO_MEMORY;
4093 memcpy(pszBasename, pszBasenameSubstr, cbBasenameSubstr);
4094 pExtent->pszBasename = pszBasename;
4095
4096 char *pszBasedirectory = RTStrDup(pImage->pszFilename);
4097 RTPathStripFilename(pszBasedirectory);
4098 char *pszFullname = RTPathJoinA(pszBasedirectory, pExtent->pszBasename);
4099 RTStrFree(pszBasedirectory);
4100 if (!pszFullname)
4101 return VERR_NO_STR_MEMORY;
4102 pExtent->pszFullname = pszFullname;
4103
4104 /* Create file for extent. Make it write only, no reading allowed. */
4105 rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszFullname,
4106 VDOpenFlagsToFileOpenFlags(pImage->uOpenFlags,
4107 true /* fCreate */)
4108 & ~RTFILE_O_READ,
4109 false /* fAsyncIO */);
4110 if (RT_FAILURE(rc))
4111 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not create new file '%s'"), pExtent->pszFullname);
4112
4113 /* Place descriptor file information. */
4114 pExtent->uDescriptorSector = 1;
4115 pExtent->cDescriptorSectors = VMDK_BYTE2SECTOR(pImage->cbDescAlloc);
4116 /* The descriptor is part of the (only) extent. */
4117 pExtent->pDescData = pImage->pDescData;
4118 pImage->pDescData = NULL;
4119
4120 uint64_t cSectorsPerGDE, cSectorsPerGD;
4121 pExtent->enmType = VMDKETYPE_HOSTED_SPARSE;
4122 pExtent->cSectors = VMDK_BYTE2SECTOR(RT_ALIGN_64(cbSize, _64K));
4123 pExtent->cSectorsPerGrain = VMDK_BYTE2SECTOR(_64K);
4124 pExtent->cGTEntries = 512;
4125 cSectorsPerGDE = pExtent->cGTEntries * pExtent->cSectorsPerGrain;
4126 pExtent->cSectorsPerGDE = cSectorsPerGDE;
4127 pExtent->cGDEntries = (pExtent->cSectors + cSectorsPerGDE - 1) / cSectorsPerGDE;
4128 cSectorsPerGD = (pExtent->cGDEntries + (512 / sizeof(uint32_t) - 1)) / (512 / sizeof(uint32_t));
4129
4130 /* The spec says version is 1 for all VMDKs, but the vast
4131 * majority of streamOptimized VMDKs actually contain
4132 * version 3 - so go with the majority. Both are accepted. */
4133 pExtent->uVersion = 3;
4134 pExtent->uCompression = VMDK_COMPRESSION_DEFLATE;
4135 pExtent->fFooter = true;
4136
4137 pExtent->enmAccess = VMDKACCESS_READONLY;
4138 pExtent->fUncleanShutdown = false;
4139 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(cbSize);
4140 pExtent->uSectorOffset = 0;
4141 pExtent->fMetaDirty = true;
4142
4143 /* Create grain directory, without preallocating it straight away. It will
4144 * be constructed on the fly when writing out the data and written when
4145 * closing the image. The end effect is that the full grain directory is
4146 * allocated, which is a requirement of the VMDK specs. */
4147 rc = vmdkCreateGrainDirectory(pImage, pExtent, VMDK_GD_AT_END,
4148 false /* fPreAlloc */);
4149 if (RT_FAILURE(rc))
4150 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not create new grain directory in '%s'"), pExtent->pszFullname);
4151
4152 rc = vmdkDescBaseSetStr(pImage, &pImage->Descriptor, "createType",
4153 "streamOptimized");
4154 if (RT_FAILURE(rc))
4155 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not set the image type in '%s'"), pImage->pszFilename);
4156
4157 return rc;
4158}
4159
4160/**
4161 * Internal: The actual code for creating any VMDK variant currently in
4162 * existence on hosted environments.
4163 */
4164static int vmdkCreateImage(PVMDKIMAGE pImage, uint64_t cbSize,
4165 unsigned uImageFlags, const char *pszComment,
4166 PCVDGEOMETRY pPCHSGeometry,
4167 PCVDGEOMETRY pLCHSGeometry, PCRTUUID pUuid,
4168 PFNVDPROGRESS pfnProgress, void *pvUser,
4169 unsigned uPercentStart, unsigned uPercentSpan)
4170{
4171 int rc;
4172
4173 pImage->uImageFlags = uImageFlags;
4174
4175 /* Try to get error interface. */
4176 pImage->pInterfaceError = VDInterfaceGet(pImage->pVDIfsDisk, VDINTERFACETYPE_ERROR);
4177 if (pImage->pInterfaceError)
4178 pImage->pInterfaceErrorCallbacks = VDGetInterfaceError(pImage->pInterfaceError);
4179
4180 /* Get I/O interface. */
4181 pImage->pInterfaceIO = VDInterfaceGet(pImage->pVDIfsImage, VDINTERFACETYPE_IOINT);
4182 AssertPtrReturn(pImage->pInterfaceIO, VERR_INVALID_PARAMETER);
4183 pImage->pInterfaceIOCallbacks = VDGetInterfaceIOInt(pImage->pInterfaceIO);
4184 AssertPtrReturn(pImage->pInterfaceIOCallbacks, VERR_INVALID_PARAMETER);
4185
4186 rc = vmdkCreateDescriptor(pImage, pImage->pDescData, pImage->cbDescAlloc,
4187 &pImage->Descriptor);
4188 if (RT_FAILURE(rc))
4189 {
4190 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not create new descriptor in '%s'"), pImage->pszFilename);
4191 goto out;
4192 }
4193
4194 if ( (uImageFlags & VD_IMAGE_FLAGS_FIXED)
4195 && (uImageFlags & VD_VMDK_IMAGE_FLAGS_RAWDISK))
4196 {
4197 /* Raw disk image (includes raw partition). */
4198 const PVBOXHDDRAW pRaw = (const PVBOXHDDRAW)pszComment;
4199 /* As the comment is misused, zap it so that no garbage comment
4200 * is set below. */
4201 pszComment = NULL;
4202 rc = vmdkCreateRawImage(pImage, pRaw, cbSize);
4203 }
4204 else
4205 {
4206 if (uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
4207 {
4208 /* Stream optimized sparse image (monolithic). */
4209 rc = vmdkCreateStreamImage(pImage, cbSize, uImageFlags,
4210 pfnProgress, pvUser, uPercentStart,
4211 uPercentSpan * 95 / 100);
4212 }
4213 else
4214 {
4215 /* Regular fixed or sparse image (monolithic or split). */
4216 rc = vmdkCreateRegularImage(pImage, cbSize, uImageFlags,
4217 pfnProgress, pvUser, uPercentStart,
4218 uPercentSpan * 95 / 100);
4219 }
4220 }
4221
4222 if (RT_FAILURE(rc))
4223 goto out;
4224
4225 if (RT_SUCCESS(rc) && pfnProgress)
4226 pfnProgress(pvUser, uPercentStart + uPercentSpan * 98 / 100);
4227
4228 pImage->cbSize = cbSize;
4229
4230 for (unsigned i = 0; i < pImage->cExtents; i++)
4231 {
4232 PVMDKEXTENT pExtent = &pImage->pExtents[i];
4233
4234 rc = vmdkDescExtInsert(pImage, &pImage->Descriptor, pExtent->enmAccess,
4235 pExtent->cNominalSectors, pExtent->enmType,
4236 pExtent->pszBasename, pExtent->uSectorOffset);
4237 if (RT_FAILURE(rc))
4238 {
4239 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not insert the extent list into descriptor in '%s'"), pImage->pszFilename);
4240 goto out;
4241 }
4242 }
4243 vmdkDescExtRemoveDummy(pImage, &pImage->Descriptor);
4244
4245 if ( pPCHSGeometry->cCylinders != 0
4246 && pPCHSGeometry->cHeads != 0
4247 && pPCHSGeometry->cSectors != 0)
4248 {
4249 rc = vmdkDescSetPCHSGeometry(pImage, pPCHSGeometry);
4250 if (RT_FAILURE(rc))
4251 goto out;
4252 }
4253 if ( pLCHSGeometry->cCylinders != 0
4254 && pLCHSGeometry->cHeads != 0
4255 && pLCHSGeometry->cSectors != 0)
4256 {
4257 rc = vmdkDescSetLCHSGeometry(pImage, pLCHSGeometry);
4258 if (RT_FAILURE(rc))
4259 goto out;
4260 }
4261
4262 pImage->LCHSGeometry = *pLCHSGeometry;
4263 pImage->PCHSGeometry = *pPCHSGeometry;
4264
4265 pImage->ImageUuid = *pUuid;
4266 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
4267 VMDK_DDB_IMAGE_UUID, &pImage->ImageUuid);
4268 if (RT_FAILURE(rc))
4269 {
4270 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error storing image UUID in new descriptor in '%s'"), pImage->pszFilename);
4271 goto out;
4272 }
4273 RTUuidClear(&pImage->ParentUuid);
4274 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
4275 VMDK_DDB_PARENT_UUID, &pImage->ParentUuid);
4276 if (RT_FAILURE(rc))
4277 {
4278 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error storing parent image UUID in new descriptor in '%s'"), pImage->pszFilename);
4279 goto out;
4280 }
4281 RTUuidClear(&pImage->ModificationUuid);
4282 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
4283 VMDK_DDB_MODIFICATION_UUID,
4284 &pImage->ModificationUuid);
4285 if (RT_FAILURE(rc))
4286 {
4287 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error storing modification UUID in new descriptor in '%s'"), pImage->pszFilename);
4288 goto out;
4289 }
4290 RTUuidClear(&pImage->ParentModificationUuid);
4291 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
4292 VMDK_DDB_PARENT_MODIFICATION_UUID,
4293 &pImage->ParentModificationUuid);
4294 if (RT_FAILURE(rc))
4295 {
4296 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error storing parent modification UUID in new descriptor in '%s'"), pImage->pszFilename);
4297 goto out;
4298 }
4299
4300 rc = vmdkAllocateGrainTableCache(pImage);
4301 if (RT_FAILURE(rc))
4302 goto out;
4303
4304 rc = vmdkSetImageComment(pImage, pszComment);
4305 if (RT_FAILURE(rc))
4306 {
4307 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: cannot set image comment in '%s'"), pImage->pszFilename);
4308 goto out;
4309 }
4310
4311 if (RT_SUCCESS(rc) && pfnProgress)
4312 pfnProgress(pvUser, uPercentStart + uPercentSpan * 99 / 100);
4313
4314 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
4315 {
4316 /* streamOptimized is a bit special, we cannot trigger the flush
4317 * until all data has been written. So we write the necessary
4318 * information explicitly. */
4319 pImage->pExtents[0].cDescriptorSectors = VMDK_BYTE2SECTOR(RT_ALIGN_64( pImage->Descriptor.aLines[pImage->Descriptor.cLines]
4320 - pImage->Descriptor.aLines[0], 512));
4321 rc = vmdkWriteMetaSparseExtent(pImage, &pImage->pExtents[0], 0);
4322 if (RT_FAILURE(rc))
4323 {
4324 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: cannot write VMDK header in '%s'"), pImage->pszFilename);
4325 goto out;
4326 }
4327
4328 rc = vmdkWriteDescriptor(pImage);
4329 if (RT_FAILURE(rc))
4330 {
4331 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: cannot write VMDK descriptor in '%s'"), pImage->pszFilename);
4332 goto out;
4333 }
4334 }
4335 else
4336 rc = vmdkFlushImage(pImage);
4337
4338out:
4339 if (RT_SUCCESS(rc) && pfnProgress)
4340 pfnProgress(pvUser, uPercentStart + uPercentSpan);
4341
4342 if (RT_FAILURE(rc))
4343 vmdkFreeImage(pImage, rc != VERR_ALREADY_EXISTS);
4344 return rc;
4345}
4346
4347/**
4348 * Internal: Update image comment.
4349 */
4350static int vmdkSetImageComment(PVMDKIMAGE pImage, const char *pszComment)
4351{
4352 char *pszCommentEncoded;
4353 if (pszComment)
4354 {
4355 pszCommentEncoded = vmdkEncodeString(pszComment);
4356 if (!pszCommentEncoded)
4357 return VERR_NO_MEMORY;
4358 }
4359 else
4360 pszCommentEncoded = NULL;
4361 int rc = vmdkDescDDBSetStr(pImage, &pImage->Descriptor,
4362 "ddb.comment", pszCommentEncoded);
4363 if (pszComment)
4364 RTStrFree(pszCommentEncoded);
4365 if (RT_FAILURE(rc))
4366 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error storing image comment in descriptor in '%s'"), pImage->pszFilename);
4367 return VINF_SUCCESS;
4368}
4369
4370/**
4371 * Internal. Clear the grain table buffer for real stream optimized writing.
4372 */
4373static void vmdkStreamClearGT(PVMDKIMAGE pImage, PVMDKEXTENT pExtent)
4374{
4375 uint32_t cCacheLines = RT_ALIGN(pExtent->cGTEntries, VMDK_GT_CACHELINE_SIZE) / VMDK_GT_CACHELINE_SIZE;
4376 for (uint32_t i = 0; i < cCacheLines; i++)
4377 memset(&pImage->pGTCache->aGTCache[i].aGTData[0], '\0',
4378 VMDK_GT_CACHELINE_SIZE * sizeof(uint32_t));
4379}
4380
4381/**
4382 * Internal. Flush the grain table buffer for real stream optimized writing.
4383 */
4384static int vmdkStreamFlushGT(PVMDKIMAGE pImage, PVMDKEXTENT pExtent,
4385 uint32_t uGDEntry)
4386{
4387 int rc = VINF_SUCCESS;
4388 uint32_t cCacheLines = RT_ALIGN(pExtent->cGTEntries, VMDK_GT_CACHELINE_SIZE) / VMDK_GT_CACHELINE_SIZE;
4389
4390 /* VMware does not write out completely empty grain tables in the case
4391 * of streamOptimized images, which according to my interpretation of
4392 * the VMDK 1.1 spec is bending the rules. Since they do it and we can
4393 * handle it without problems do it the same way and save some bytes. */
4394 bool fAllZero = true;
4395 for (uint32_t i = 0; i < cCacheLines; i++)
4396 {
4397 /* Convert the grain table to little endian in place, as it will not
4398 * be used at all after this function has been called. */
4399 uint32_t *pGTTmp = &pImage->pGTCache->aGTCache[i].aGTData[0];
4400 for (uint32_t j = 0; j < VMDK_GT_CACHELINE_SIZE; j++, pGTTmp++)
4401 if (*pGTTmp)
4402 {
4403 fAllZero = false;
4404 break;
4405 }
4406 if (!fAllZero)
4407 break;
4408 }
4409 if (fAllZero)
4410 return VINF_SUCCESS;
4411
4412 uint64_t uFileOffset = pExtent->uAppendPosition;
4413 if (!uFileOffset)
4414 return VERR_INTERNAL_ERROR;
4415 /* Align to sector, as the previous write could have been any size. */
4416 uFileOffset = RT_ALIGN_64(uFileOffset, 512);
4417
4418 /* Grain table marker. */
4419 uint8_t aMarker[512];
4420 PVMDKMARKER pMarker = (PVMDKMARKER)&aMarker[0];
4421 memset(pMarker, '\0', sizeof(aMarker));
4422 pMarker->uSector = RT_H2LE_U64(VMDK_BYTE2SECTOR(pExtent->cGTEntries * sizeof(uint32_t)));
4423 pMarker->uType = RT_H2LE_U32(VMDK_MARKER_GT);
4424 rc = vmdkFileWriteSync(pImage, pExtent->pFile, uFileOffset,
4425 aMarker, sizeof(aMarker), NULL);
4426 AssertRC(rc);
4427 uFileOffset += 512;
4428
4429 if (!pExtent->pGD || pExtent->pGD[uGDEntry])
4430 return VERR_INTERNAL_ERROR;
4431
4432 pExtent->pGD[uGDEntry] = VMDK_BYTE2SECTOR(uFileOffset);
4433
4434 for (uint32_t i = 0; i < cCacheLines; i++)
4435 {
4436 /* Convert the grain table to little endian in place, as it will not
4437 * be used at all after this function has been called. */
4438 uint32_t *pGTTmp = &pImage->pGTCache->aGTCache[i].aGTData[0];
4439 for (uint32_t j = 0; j < VMDK_GT_CACHELINE_SIZE; j++, pGTTmp++)
4440 *pGTTmp = RT_H2LE_U32(*pGTTmp);
4441
4442 rc = vmdkFileWriteSync(pImage, pExtent->pFile, uFileOffset,
4443 &pImage->pGTCache->aGTCache[i].aGTData[0],
4444 VMDK_GT_CACHELINE_SIZE * sizeof(uint32_t),
4445 NULL);
4446 uFileOffset += VMDK_GT_CACHELINE_SIZE * sizeof(uint32_t);
4447 if (RT_FAILURE(rc))
4448 break;
4449 }
4450 Assert(!(uFileOffset % 512));
4451 pExtent->uAppendPosition = RT_ALIGN_64(uFileOffset, 512);
4452 return rc;
4453}
4454
4455/**
4456 * Internal. Free all allocated space for representing an image, and optionally
4457 * delete the image from disk.
4458 */
4459static int vmdkFreeImage(PVMDKIMAGE pImage, bool fDelete)
4460{
4461 int rc = VINF_SUCCESS;
4462
4463 /* Freeing a never allocated image (e.g. because the open failed) is
4464 * not signalled as an error. After all nothing bad happens. */
4465 if (pImage)
4466 {
4467 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
4468 {
4469 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
4470 {
4471 /* Check if all extents are clean. */
4472 for (unsigned i = 0; i < pImage->cExtents; i++)
4473 {
4474 Assert(!pImage->pExtents[i].fUncleanShutdown);
4475 }
4476 }
4477 else
4478 {
4479 /* Mark all extents as clean. */
4480 for (unsigned i = 0; i < pImage->cExtents; i++)
4481 {
4482 if ( ( pImage->pExtents[i].enmType == VMDKETYPE_HOSTED_SPARSE
4483#ifdef VBOX_WITH_VMDK_ESX
4484 || pImage->pExtents[i].enmType == VMDKETYPE_ESX_SPARSE
4485#endif /* VBOX_WITH_VMDK_ESX */
4486 )
4487 && pImage->pExtents[i].fUncleanShutdown)
4488 {
4489 pImage->pExtents[i].fUncleanShutdown = false;
4490 pImage->pExtents[i].fMetaDirty = true;
4491 }
4492
4493 /* From now on it's not safe to append any more data. */
4494 pImage->pExtents[i].uAppendPosition = 0;
4495 }
4496 }
4497 }
4498
4499 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
4500 {
4501 /* No need to write any pending data if the file will be deleted
4502 * or if the new file wasn't successfully created. */
4503 if ( !fDelete && pImage->pExtents
4504 && pImage->pExtents[0].cGTEntries
4505 && pImage->pExtents[0].uAppendPosition)
4506 {
4507 PVMDKEXTENT pExtent = &pImage->pExtents[0];
4508 uint32_t uLastGDEntry = pExtent->uLastGrainAccess / pExtent->cGTEntries;
4509 rc = vmdkStreamFlushGT(pImage, pExtent, uLastGDEntry);
4510 AssertRC(rc);
4511 vmdkStreamClearGT(pImage, pExtent);
4512 for (uint32_t i = uLastGDEntry + 1; i < pExtent->cGDEntries; i++)
4513 {
4514 rc = vmdkStreamFlushGT(pImage, pExtent, i);
4515 AssertRC(rc);
4516 }
4517
4518 uint64_t uFileOffset = pExtent->uAppendPosition;
4519 if (!uFileOffset)
4520 return VERR_INTERNAL_ERROR;
4521 uFileOffset = RT_ALIGN_64(uFileOffset, 512);
4522
4523 /* From now on it's not safe to append any more data. */
4524 pExtent->uAppendPosition = 0;
4525
4526 /* Grain directory marker. */
4527 uint8_t aMarker[512];
4528 PVMDKMARKER pMarker = (PVMDKMARKER)&aMarker[0];
4529 memset(pMarker, '\0', sizeof(aMarker));
4530 pMarker->uSector = VMDK_BYTE2SECTOR(RT_ALIGN_64(RT_H2LE_U64(pExtent->cGDEntries * sizeof(uint32_t)), 512));
4531 pMarker->uType = RT_H2LE_U32(VMDK_MARKER_GD);
4532 rc = vmdkFileWriteSync(pImage, pExtent->pFile, uFileOffset,
4533 aMarker, sizeof(aMarker), NULL);
4534 AssertRC(rc);
4535 uFileOffset += 512;
4536
4537 /* Write grain directory in little endian style. The array will
4538 * not be used after this, so convert in place. */
4539 uint32_t *pGDTmp = pExtent->pGD;
4540 for (uint32_t i = 0; i < pExtent->cGDEntries; i++, pGDTmp++)
4541 *pGDTmp = RT_H2LE_U32(*pGDTmp);
4542 rc = vmdkFileWriteSync(pImage, pExtent->pFile, uFileOffset,
4543 pExtent->pGD,
4544 pExtent->cGDEntries * sizeof(uint32_t),
4545 NULL);
4546 AssertRC(rc);
4547
4548 pExtent->uSectorGD = VMDK_BYTE2SECTOR(uFileOffset);
4549 pExtent->uSectorRGD = VMDK_BYTE2SECTOR(uFileOffset);
4550 uFileOffset = RT_ALIGN_64( uFileOffset
4551 + pExtent->cGDEntries * sizeof(uint32_t),
4552 512);
4553
4554 /* Footer marker. */
4555 memset(pMarker, '\0', sizeof(aMarker));
4556 pMarker->uSector = VMDK_BYTE2SECTOR(512);
4557 pMarker->uType = RT_H2LE_U32(VMDK_MARKER_FOOTER);
4558 rc = vmdkFileWriteSync(pImage, pExtent->pFile, uFileOffset,
4559 aMarker, sizeof(aMarker), NULL);
4560 AssertRC(rc);
4561
4562 uFileOffset += 512;
4563 rc = vmdkWriteMetaSparseExtent(pImage, pExtent, uFileOffset);
4564 AssertRC(rc);
4565
4566 uFileOffset += 512;
4567 /* End-of-stream marker. */
4568 memset(pMarker, '\0', sizeof(aMarker));
4569 rc = vmdkFileWriteSync(pImage, pExtent->pFile, uFileOffset,
4570 aMarker, sizeof(aMarker), NULL);
4571 AssertRC(rc);
4572 }
4573 }
4574 else
4575 vmdkFlushImage(pImage);
4576
4577 if (pImage->pExtents != NULL)
4578 {
4579 for (unsigned i = 0 ; i < pImage->cExtents; i++)
4580 vmdkFreeExtentData(pImage, &pImage->pExtents[i], fDelete);
4581 RTMemFree(pImage->pExtents);
4582 pImage->pExtents = NULL;
4583 }
4584 pImage->cExtents = 0;
4585 if (pImage->pFile != NULL)
4586 vmdkFileClose(pImage, &pImage->pFile, fDelete);
4587 vmdkFileCheckAllClose(pImage);
4588
4589 if (pImage->pGTCache)
4590 {
4591 RTMemFree(pImage->pGTCache);
4592 pImage->pGTCache = NULL;
4593 }
4594 if (pImage->pDescData)
4595 {
4596 RTMemFree(pImage->pDescData);
4597 pImage->pDescData = NULL;
4598 }
4599 }
4600
4601 LogFlowFunc(("returns %Rrc\n", rc));
4602 return rc;
4603}
4604
4605/**
4606 * Internal. Flush image data (and metadata) to disk.
4607 */
4608static int vmdkFlushImage(PVMDKIMAGE pImage)
4609{
4610 PVMDKEXTENT pExtent;
4611 int rc = VINF_SUCCESS;
4612
4613 /* Update descriptor if changed. */
4614 if (pImage->Descriptor.fDirty)
4615 {
4616 rc = vmdkWriteDescriptor(pImage);
4617 if (RT_FAILURE(rc))
4618 goto out;
4619 }
4620
4621 for (unsigned i = 0; i < pImage->cExtents; i++)
4622 {
4623 pExtent = &pImage->pExtents[i];
4624 if (pExtent->pFile != NULL && pExtent->fMetaDirty)
4625 {
4626 switch (pExtent->enmType)
4627 {
4628 case VMDKETYPE_HOSTED_SPARSE:
4629 if (!pExtent->fFooter)
4630 {
4631 rc = vmdkWriteMetaSparseExtent(pImage, pExtent, 0);
4632 if (RT_FAILURE(rc))
4633 goto out;
4634 }
4635 else
4636 {
4637 uint64_t uFileOffset = pExtent->uAppendPosition;
4638 /* Simply skip writing anything if the streamOptimized
4639 * image hasn't been just created. */
4640 if (!uFileOffset)
4641 break;
4642 uFileOffset = RT_ALIGN_64(uFileOffset, 512);
4643 rc = vmdkWriteMetaSparseExtent(pImage, pExtent,
4644 uFileOffset);
4645 if (RT_FAILURE(rc))
4646 goto out;
4647 }
4648 break;
4649#ifdef VBOX_WITH_VMDK_ESX
4650 case VMDKETYPE_ESX_SPARSE:
4651 /** @todo update the header. */
4652 break;
4653#endif /* VBOX_WITH_VMDK_ESX */
4654 case VMDKETYPE_VMFS:
4655 case VMDKETYPE_FLAT:
4656 /* Nothing to do. */
4657 break;
4658 case VMDKETYPE_ZERO:
4659 default:
4660 AssertMsgFailed(("extent with type %d marked as dirty\n",
4661 pExtent->enmType));
4662 break;
4663 }
4664 }
4665 switch (pExtent->enmType)
4666 {
4667 case VMDKETYPE_HOSTED_SPARSE:
4668#ifdef VBOX_WITH_VMDK_ESX
4669 case VMDKETYPE_ESX_SPARSE:
4670#endif /* VBOX_WITH_VMDK_ESX */
4671 case VMDKETYPE_VMFS:
4672 case VMDKETYPE_FLAT:
4673 /** @todo implement proper path absolute check. */
4674 if ( pExtent->pFile != NULL
4675 && !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
4676 && !(pExtent->pszBasename[0] == RTPATH_SLASH))
4677 rc = vmdkFileFlush(pImage, pExtent->pFile);
4678 break;
4679 case VMDKETYPE_ZERO:
4680 /* No need to do anything for this extent. */
4681 break;
4682 default:
4683 AssertMsgFailed(("unknown extent type %d\n", pExtent->enmType));
4684 break;
4685 }
4686 }
4687
4688out:
4689 return rc;
4690}
4691
4692/**
4693 * Internal. Find extent corresponding to the sector number in the disk.
4694 */
4695static int vmdkFindExtent(PVMDKIMAGE pImage, uint64_t offSector,
4696 PVMDKEXTENT *ppExtent, uint64_t *puSectorInExtent)
4697{
4698 PVMDKEXTENT pExtent = NULL;
4699 int rc = VINF_SUCCESS;
4700
4701 for (unsigned i = 0; i < pImage->cExtents; i++)
4702 {
4703 if (offSector < pImage->pExtents[i].cNominalSectors)
4704 {
4705 pExtent = &pImage->pExtents[i];
4706 *puSectorInExtent = offSector + pImage->pExtents[i].uSectorOffset;
4707 break;
4708 }
4709 offSector -= pImage->pExtents[i].cNominalSectors;
4710 }
4711
4712 if (pExtent)
4713 *ppExtent = pExtent;
4714 else
4715 rc = VERR_IO_SECTOR_NOT_FOUND;
4716
4717 return rc;
4718}
4719
4720/**
4721 * Internal. Hash function for placing the grain table hash entries.
4722 */
4723static uint32_t vmdkGTCacheHash(PVMDKGTCACHE pCache, uint64_t uSector,
4724 unsigned uExtent)
4725{
4726 /** @todo this hash function is quite simple, maybe use a better one which
4727 * scrambles the bits better. */
4728 return (uSector + uExtent) % pCache->cEntries;
4729}
4730
4731/**
4732 * Internal. Get sector number in the extent file from the relative sector
4733 * number in the extent.
4734 */
4735static int vmdkGetSector(PVMDKIMAGE pImage, PVMDKEXTENT pExtent,
4736 uint64_t uSector, uint64_t *puExtentSector)
4737{
4738 PVMDKGTCACHE pCache = pImage->pGTCache;
4739 uint64_t uGDIndex, uGTSector, uGTBlock;
4740 uint32_t uGTHash, uGTBlockIndex;
4741 PVMDKGTCACHEENTRY pGTCacheEntry;
4742 uint32_t aGTDataTmp[VMDK_GT_CACHELINE_SIZE];
4743 int rc;
4744
4745 /* For newly created and readonly/sequentially opened streamOptimized
4746 * images this must be a no-op, as the grain directory is not there. */
4747 if ( ( pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED
4748 && pExtent->uAppendPosition)
4749 || ( pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED
4750 && pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY
4751 && pImage->uOpenFlags & VD_OPEN_FLAGS_SEQUENTIAL))
4752 {
4753 *puExtentSector = 0;
4754 return VINF_SUCCESS;
4755 }
4756
4757 uGDIndex = uSector / pExtent->cSectorsPerGDE;
4758 if (uGDIndex >= pExtent->cGDEntries)
4759 return VERR_OUT_OF_RANGE;
4760 uGTSector = pExtent->pGD[uGDIndex];
4761 if (!uGTSector)
4762 {
4763 /* There is no grain table referenced by this grain directory
4764 * entry. So there is absolutely no data in this area. */
4765 *puExtentSector = 0;
4766 return VINF_SUCCESS;
4767 }
4768
4769 uGTBlock = uSector / (pExtent->cSectorsPerGrain * VMDK_GT_CACHELINE_SIZE);
4770 uGTHash = vmdkGTCacheHash(pCache, uGTBlock, pExtent->uExtent);
4771 pGTCacheEntry = &pCache->aGTCache[uGTHash];
4772 if ( pGTCacheEntry->uExtent != pExtent->uExtent
4773 || pGTCacheEntry->uGTBlock != uGTBlock)
4774 {
4775 /* Cache miss, fetch data from disk. */
4776 rc = vmdkFileReadSync(pImage, pExtent->pFile,
4777 VMDK_SECTOR2BYTE(uGTSector) + (uGTBlock % (pExtent->cGTEntries / VMDK_GT_CACHELINE_SIZE)) * sizeof(aGTDataTmp),
4778 aGTDataTmp, sizeof(aGTDataTmp), NULL);
4779 if (RT_FAILURE(rc))
4780 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: cannot read grain table entry in '%s'"), pExtent->pszFullname);
4781 pGTCacheEntry->uExtent = pExtent->uExtent;
4782 pGTCacheEntry->uGTBlock = uGTBlock;
4783 for (unsigned i = 0; i < VMDK_GT_CACHELINE_SIZE; i++)
4784 pGTCacheEntry->aGTData[i] = RT_LE2H_U32(aGTDataTmp[i]);
4785 }
4786 uGTBlockIndex = (uSector / pExtent->cSectorsPerGrain) % VMDK_GT_CACHELINE_SIZE;
4787 uint32_t uGrainSector = pGTCacheEntry->aGTData[uGTBlockIndex];
4788 if (uGrainSector)
4789 *puExtentSector = uGrainSector + uSector % pExtent->cSectorsPerGrain;
4790 else
4791 *puExtentSector = 0;
4792 return VINF_SUCCESS;
4793}
4794
4795/**
4796 * Internal. Get sector number in the extent file from the relative sector
4797 * number in the extent - version for async access.
4798 */
4799static int vmdkGetSectorAsync(PVMDKIMAGE pImage, PVDIOCTX pIoCtx,
4800 PVMDKEXTENT pExtent, uint64_t uSector,
4801 uint64_t *puExtentSector)
4802{
4803 PVMDKGTCACHE pCache = pImage->pGTCache;
4804 uint64_t uGDIndex, uGTSector, uGTBlock;
4805 uint32_t uGTHash, uGTBlockIndex;
4806 PVMDKGTCACHEENTRY pGTCacheEntry;
4807 uint32_t aGTDataTmp[VMDK_GT_CACHELINE_SIZE];
4808 int rc;
4809
4810 uGDIndex = uSector / pExtent->cSectorsPerGDE;
4811 if (uGDIndex >= pExtent->cGDEntries)
4812 return VERR_OUT_OF_RANGE;
4813 uGTSector = pExtent->pGD[uGDIndex];
4814 if (!uGTSector)
4815 {
4816 /* There is no grain table referenced by this grain directory
4817 * entry. So there is absolutely no data in this area. */
4818 *puExtentSector = 0;
4819 return VINF_SUCCESS;
4820 }
4821
4822 uGTBlock = uSector / (pExtent->cSectorsPerGrain * VMDK_GT_CACHELINE_SIZE);
4823 uGTHash = vmdkGTCacheHash(pCache, uGTBlock, pExtent->uExtent);
4824 pGTCacheEntry = &pCache->aGTCache[uGTHash];
4825 if ( pGTCacheEntry->uExtent != pExtent->uExtent
4826 || pGTCacheEntry->uGTBlock != uGTBlock)
4827 {
4828 /* Cache miss, fetch data from disk. */
4829 PVDMETAXFER pMetaXfer;
4830 rc = vmdkFileReadMetaAsync(pImage, pExtent->pFile,
4831 VMDK_SECTOR2BYTE(uGTSector) + (uGTBlock % (pExtent->cGTEntries / VMDK_GT_CACHELINE_SIZE)) * sizeof(aGTDataTmp),
4832 aGTDataTmp, sizeof(aGTDataTmp), pIoCtx, &pMetaXfer, NULL, NULL);
4833 if (RT_FAILURE(rc))
4834 return rc;
4835 /* We can release the metadata transfer immediately. */
4836 vmdkFileMetaXferRelease(pImage, pMetaXfer);
4837 pGTCacheEntry->uExtent = pExtent->uExtent;
4838 pGTCacheEntry->uGTBlock = uGTBlock;
4839 for (unsigned i = 0; i < VMDK_GT_CACHELINE_SIZE; i++)
4840 pGTCacheEntry->aGTData[i] = RT_LE2H_U32(aGTDataTmp[i]);
4841 }
4842 uGTBlockIndex = (uSector / pExtent->cSectorsPerGrain) % VMDK_GT_CACHELINE_SIZE;
4843 uint32_t uGrainSector = pGTCacheEntry->aGTData[uGTBlockIndex];
4844 if (uGrainSector)
4845 *puExtentSector = uGrainSector + uSector % pExtent->cSectorsPerGrain;
4846 else
4847 *puExtentSector = 0;
4848 return VINF_SUCCESS;
4849}
4850
4851/**
4852 * Internal. Allocates a new grain table (if necessary), writes the grain
4853 * and updates the grain table. The cache is also updated by this operation.
4854 * This is separate from vmdkGetSector, because that should be as fast as
4855 * possible. Most code from vmdkGetSector also appears here.
4856 */
4857static int vmdkAllocGrain(PVMDKIMAGE pImage, PVMDKEXTENT pExtent,
4858 uint64_t uSector, const void *pvBuf,
4859 uint64_t cbWrite)
4860{
4861 PVMDKGTCACHE pCache = pImage->pGTCache;
4862 uint64_t uGDIndex, uGTSector, uRGTSector, uGTBlock;
4863 uint64_t uFileOffset;
4864 uint32_t uGTHash, uGTBlockIndex;
4865 PVMDKGTCACHEENTRY pGTCacheEntry;
4866 uint32_t aGTDataTmp[VMDK_GT_CACHELINE_SIZE];
4867 int rc;
4868
4869 uGDIndex = uSector / pExtent->cSectorsPerGDE;
4870 if (uGDIndex >= pExtent->cGDEntries)
4871 return VERR_OUT_OF_RANGE;
4872 uGTSector = pExtent->pGD[uGDIndex];
4873 if (pExtent->pRGD)
4874 uRGTSector = pExtent->pRGD[uGDIndex];
4875 else
4876 uRGTSector = 0; /**< avoid compiler warning */
4877 if (!uGTSector)
4878 {
4879 /* There is no grain table referenced by this grain directory
4880 * entry. So there is absolutely no data in this area. Allocate
4881 * a new grain table and put the reference to it in the GDs. */
4882 uFileOffset = pExtent->uAppendPosition;
4883 if (!uFileOffset)
4884 return VERR_INTERNAL_ERROR;
4885 Assert(!(uFileOffset % 512));
4886 uFileOffset = RT_ALIGN_64(uFileOffset, 512);
4887 uGTSector = VMDK_BYTE2SECTOR(uFileOffset);
4888
4889 pExtent->uAppendPosition += pExtent->cGTEntries * sizeof(uint32_t);
4890
4891 /* Normally the grain table is preallocated for hosted sparse extents
4892 * that support more than 32 bit sector numbers. So this shouldn't
4893 * ever happen on a valid extent. */
4894 if (uGTSector > UINT32_MAX)
4895 return VERR_VD_VMDK_INVALID_HEADER;
4896
4897 /* Write grain table by writing the required number of grain table
4898 * cache chunks. Avoids dynamic memory allocation, but is a bit
4899 * slower. But as this is a pretty infrequently occurring case it
4900 * should be acceptable. */
4901 memset(aGTDataTmp, '\0', sizeof(aGTDataTmp));
4902 for (unsigned i = 0;
4903 i < pExtent->cGTEntries / VMDK_GT_CACHELINE_SIZE;
4904 i++)
4905 {
4906 rc = vmdkFileWriteSync(pImage, pExtent->pFile,
4907 VMDK_SECTOR2BYTE(uGTSector) + i * sizeof(aGTDataTmp),
4908 aGTDataTmp, sizeof(aGTDataTmp), NULL);
4909 if (RT_FAILURE(rc))
4910 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: cannot write grain table allocation in '%s'"), pExtent->pszFullname);
4911 }
4912 pExtent->uAppendPosition = RT_ALIGN_64( pExtent->uAppendPosition
4913 + pExtent->cGTEntries * sizeof(uint32_t),
4914 512);
4915
4916 if (pExtent->pRGD)
4917 {
4918 AssertReturn(!uRGTSector, VERR_VD_VMDK_INVALID_HEADER);
4919 uFileOffset = pExtent->uAppendPosition;
4920 if (!uFileOffset)
4921 return VERR_INTERNAL_ERROR;
4922 Assert(!(uFileOffset % 512));
4923 uRGTSector = VMDK_BYTE2SECTOR(uFileOffset);
4924
4925 pExtent->uAppendPosition += pExtent->cGTEntries * sizeof(uint32_t);
4926
4927 /* Normally the redundant grain table is preallocated for hosted
4928 * sparse extents that support more than 32 bit sector numbers. So
4929 * this shouldn't ever happen on a valid extent. */
4930 if (uRGTSector > UINT32_MAX)
4931 return VERR_VD_VMDK_INVALID_HEADER;
4932
4933 /* Write backup grain table by writing the required number of grain
4934 * table cache chunks. Avoids dynamic memory allocation, but is a
4935 * bit slower. But as this is a pretty infrequently occurring case
4936 * it should be acceptable. */
4937 for (unsigned i = 0;
4938 i < pExtent->cGTEntries / VMDK_GT_CACHELINE_SIZE;
4939 i++)
4940 {
4941 rc = vmdkFileWriteSync(pImage, pExtent->pFile,
4942 VMDK_SECTOR2BYTE(uRGTSector) + i * sizeof(aGTDataTmp),
4943 aGTDataTmp, sizeof(aGTDataTmp), NULL);
4944 if (RT_FAILURE(rc))
4945 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: cannot write backup grain table allocation in '%s'"), pExtent->pszFullname);
4946 }
4947
4948 pExtent->uAppendPosition = pExtent->uAppendPosition
4949 + pExtent->cGTEntries * sizeof(uint32_t);
4950 }
4951
4952 /* Update the grain directory on disk (doing it before writing the
4953 * grain table will result in a garbled extent if the operation is
4954 * aborted for some reason. Otherwise the worst that can happen is
4955 * some unused sectors in the extent. */
4956 uint32_t uGTSectorLE = RT_H2LE_U64(uGTSector);
4957 rc = vmdkFileWriteSync(pImage, pExtent->pFile,
4958 VMDK_SECTOR2BYTE(pExtent->uSectorGD) + uGDIndex * sizeof(uGTSectorLE),
4959 &uGTSectorLE, sizeof(uGTSectorLE), NULL);
4960 if (RT_FAILURE(rc))
4961 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: cannot write grain directory entry in '%s'"), pExtent->pszFullname);
4962 if (pExtent->pRGD)
4963 {
4964 uint32_t uRGTSectorLE = RT_H2LE_U64(uRGTSector);
4965 rc = vmdkFileWriteSync(pImage, pExtent->pFile,
4966 VMDK_SECTOR2BYTE(pExtent->uSectorRGD) + uGDIndex * sizeof(uRGTSectorLE),
4967 &uRGTSectorLE, sizeof(uRGTSectorLE), NULL);
4968 if (RT_FAILURE(rc))
4969 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: cannot write backup grain directory entry in '%s'"), pExtent->pszFullname);
4970 }
4971
4972 /* As the final step update the in-memory copy of the GDs. */
4973 pExtent->pGD[uGDIndex] = uGTSector;
4974 if (pExtent->pRGD)
4975 pExtent->pRGD[uGDIndex] = uRGTSector;
4976 }
4977
4978 uFileOffset = pExtent->uAppendPosition;
4979 if (!uFileOffset)
4980 return VERR_INTERNAL_ERROR;
4981 Assert(!(uFileOffset % 512));
4982
4983 /* Write the data. Always a full grain, or we're in big trouble. */
4984 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
4985 {
4986 if (cbWrite != VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain))
4987 return vmdkError(pImage, VERR_INTERNAL_ERROR, RT_SRC_POS, N_("VMDK: not enough data for a compressed data block in '%s'"), pExtent->pszFullname);
4988
4989 /* Invalidate cache, just in case some code incorrectly allows mixing
4990 * of reads and writes. Normally shouldn't be needed. */
4991 pExtent->uGrainSectorAbs = 0;
4992
4993 /* Write compressed data block and the markers. */
4994 uint32_t cbGrain = 0;
4995 rc = vmdkFileDeflateSync(pImage, pExtent, uFileOffset,
4996 pvBuf, cbWrite, uSector, &cbGrain);
4997 if (RT_FAILURE(rc))
4998 {
4999 AssertRC(rc);
5000 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: cannot write allocated compressed data block in '%s'"), pExtent->pszFullname);
5001 }
5002 pExtent->uLastGrainAccess = uSector / pExtent->cSectorsPerGrain;
5003 pExtent->uAppendPosition += cbGrain;
5004 }
5005 else
5006 {
5007 rc = vmdkFileWriteSync(pImage, pExtent->pFile, uFileOffset,
5008 pvBuf, cbWrite, NULL);
5009 if (RT_FAILURE(rc))
5010 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: cannot write allocated data block in '%s'"), pExtent->pszFullname);
5011 pExtent->uAppendPosition += cbWrite;
5012 }
5013
5014 /* Update the grain table (and the cache). */
5015 uGTBlock = uSector / (pExtent->cSectorsPerGrain * VMDK_GT_CACHELINE_SIZE);
5016 uGTHash = vmdkGTCacheHash(pCache, uGTBlock, pExtent->uExtent);
5017 pGTCacheEntry = &pCache->aGTCache[uGTHash];
5018 if ( pGTCacheEntry->uExtent != pExtent->uExtent
5019 || pGTCacheEntry->uGTBlock != uGTBlock)
5020 {
5021 /* Cache miss, fetch data from disk. */
5022 rc = vmdkFileReadSync(pImage, pExtent->pFile,
5023 VMDK_SECTOR2BYTE(uGTSector) + (uGTBlock % (pExtent->cGTEntries / VMDK_GT_CACHELINE_SIZE)) * sizeof(aGTDataTmp),
5024 aGTDataTmp, sizeof(aGTDataTmp), NULL);
5025 if (RT_FAILURE(rc))
5026 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: cannot read allocated grain table entry in '%s'"), pExtent->pszFullname);
5027 pGTCacheEntry->uExtent = pExtent->uExtent;
5028 pGTCacheEntry->uGTBlock = uGTBlock;
5029 for (unsigned i = 0; i < VMDK_GT_CACHELINE_SIZE; i++)
5030 pGTCacheEntry->aGTData[i] = RT_LE2H_U32(aGTDataTmp[i]);
5031 }
5032 else
5033 {
5034 /* Cache hit. Convert grain table block back to disk format, otherwise
5035 * the code below will write garbage for all but the updated entry. */
5036 for (unsigned i = 0; i < VMDK_GT_CACHELINE_SIZE; i++)
5037 aGTDataTmp[i] = RT_H2LE_U32(pGTCacheEntry->aGTData[i]);
5038 }
5039 uGTBlockIndex = (uSector / pExtent->cSectorsPerGrain) % VMDK_GT_CACHELINE_SIZE;
5040 aGTDataTmp[uGTBlockIndex] = RT_H2LE_U32(VMDK_BYTE2SECTOR(uFileOffset));
5041 pGTCacheEntry->aGTData[uGTBlockIndex] = VMDK_BYTE2SECTOR(uFileOffset);
5042 /* Update grain table on disk. */
5043 rc = vmdkFileWriteSync(pImage, pExtent->pFile,
5044 VMDK_SECTOR2BYTE(uGTSector) + (uGTBlock % (pExtent->cGTEntries / VMDK_GT_CACHELINE_SIZE)) * sizeof(aGTDataTmp),
5045 aGTDataTmp, sizeof(aGTDataTmp), NULL);
5046 if (RT_FAILURE(rc))
5047 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: cannot write updated grain table in '%s'"), pExtent->pszFullname);
5048 if (pExtent->pRGD)
5049 {
5050 /* Update backup grain table on disk. */
5051 rc = vmdkFileWriteSync(pImage, pExtent->pFile,
5052 VMDK_SECTOR2BYTE(uRGTSector) + (uGTBlock % (pExtent->cGTEntries / VMDK_GT_CACHELINE_SIZE)) * sizeof(aGTDataTmp),
5053 aGTDataTmp, sizeof(aGTDataTmp), NULL);
5054 if (RT_FAILURE(rc))
5055 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: cannot write updated backup grain table in '%s'"), pExtent->pszFullname);
5056 }
5057#ifdef VBOX_WITH_VMDK_ESX
5058 if (RT_SUCCESS(rc) && pExtent->enmType == VMDKETYPE_ESX_SPARSE)
5059 {
5060 pExtent->uFreeSector = uGTSector + VMDK_BYTE2SECTOR(cbWrite);
5061 pExtent->fMetaDirty = true;
5062 }
5063#endif /* VBOX_WITH_VMDK_ESX */
5064 return rc;
5065}
5066
5067/**
5068 * Internal. Writes the grain and also if necessary the grain tables.
5069 * Uses the grain table cache as a true grain table.
5070 */
5071static int vmdkStreamAllocGrain(PVMDKIMAGE pImage, PVMDKEXTENT pExtent,
5072 uint64_t uSector, const void *pvBuf,
5073 uint64_t cbWrite)
5074{
5075 uint32_t uGrain;
5076 uint32_t uGDEntry, uLastGDEntry;
5077 uint32_t cbGrain = 0;
5078 uint32_t uCacheLine, uCacheEntry;
5079 const void *pData = pvBuf;
5080 int rc;
5081
5082 /* Very strict requirements: always write at least one full grain, with
5083 * proper alignment. Everything else would require reading of already
5084 * written data, which we don't support for obvious reasons. The only
5085 * exception is the last grain, and only if the image size specifies
5086 * that only some portion holds data. In any case the write must be
5087 * within the image limits, no "overshoot" allowed. */
5088 if ( cbWrite == 0
5089 || ( cbWrite < VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain)
5090 && pExtent->cNominalSectors - uSector >= pExtent->cSectorsPerGrain)
5091 || uSector % pExtent->cSectorsPerGrain
5092 || uSector + VMDK_BYTE2SECTOR(cbWrite) > pExtent->cNominalSectors)
5093 return VERR_INVALID_PARAMETER;
5094
5095 /* Clip write range to at most the rest of the grain. */
5096 cbWrite = RT_MIN(cbWrite, VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain - uSector % pExtent->cSectorsPerGrain));
5097
5098 /* Do not allow to go back. */
5099 uGrain = uSector / pExtent->cSectorsPerGrain;
5100 uCacheLine = uGrain % pExtent->cGTEntries / VMDK_GT_CACHELINE_SIZE;
5101 uCacheEntry = uGrain % VMDK_GT_CACHELINE_SIZE;
5102 uGDEntry = uGrain / pExtent->cGTEntries;
5103 uLastGDEntry = pExtent->uLastGrainAccess / pExtent->cGTEntries;
5104 if (uGrain < pExtent->uLastGrainAccess)
5105 return VERR_VD_VMDK_INVALID_WRITE;
5106
5107 /* Zero byte write optimization. Since we don't tell VBoxHDD that we need
5108 * to allocate something, we also need to detect the situation ourself. */
5109 if ( !(pImage->uOpenFlags & VD_OPEN_FLAGS_HONOR_ZEROES)
5110 && ASMBitFirstSet((volatile void *)pvBuf, (uint32_t)cbWrite * 8) == -1)
5111 return VINF_SUCCESS;
5112
5113 if (uGDEntry != uLastGDEntry)
5114 {
5115 rc = vmdkStreamFlushGT(pImage, pExtent, uLastGDEntry);
5116 if (RT_FAILURE(rc))
5117 return rc;
5118 vmdkStreamClearGT(pImage, pExtent);
5119 for (uint32_t i = uLastGDEntry + 1; i < uGDEntry; i++)
5120 {
5121 rc = vmdkStreamFlushGT(pImage, pExtent, i);
5122 if (RT_FAILURE(rc))
5123 return rc;
5124 }
5125 }
5126
5127 uint64_t uFileOffset;
5128 uFileOffset = pExtent->uAppendPosition;
5129 if (!uFileOffset)
5130 return VERR_INTERNAL_ERROR;
5131 /* Align to sector, as the previous write could have been any size. */
5132 uFileOffset = RT_ALIGN_64(uFileOffset, 512);
5133
5134 /* Paranoia check: extent type, grain table buffer presence and
5135 * grain table buffer space. Also grain table entry must be clear. */
5136 if ( pExtent->enmType != VMDKETYPE_HOSTED_SPARSE
5137 || !pImage->pGTCache
5138 || pExtent->cGTEntries > VMDK_GT_CACHE_SIZE * VMDK_GT_CACHELINE_SIZE
5139 || pImage->pGTCache->aGTCache[uCacheLine].aGTData[uCacheEntry])
5140 return VERR_INTERNAL_ERROR;
5141
5142 /* Update grain table entry. */
5143 pImage->pGTCache->aGTCache[uCacheLine].aGTData[uCacheEntry] = VMDK_BYTE2SECTOR(uFileOffset);
5144
5145 if (cbWrite != VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain))
5146 {
5147 memcpy(pExtent->pvGrain, pvBuf, cbWrite);
5148 memset((char *)pExtent->pvGrain + cbWrite, '\0',
5149 VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain) - cbWrite);
5150 pData = pExtent->pvGrain;
5151 }
5152 rc = vmdkFileDeflateSync(pImage, pExtent, uFileOffset, pData,
5153 VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain),
5154 uSector, &cbGrain);
5155 if (RT_FAILURE(rc))
5156 {
5157 pExtent->uGrainSectorAbs = 0;
5158 AssertRC(rc);
5159 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: cannot write compressed data block in '%s'"), pExtent->pszFullname);
5160 }
5161 pExtent->uLastGrainAccess = uGrain;
5162 pExtent->uAppendPosition += cbGrain;
5163
5164 return rc;
5165}
5166
5167/**
5168 * Internal: Updates the grain table during a async grain allocation.
5169 */
5170static int vmdkAllocGrainAsyncGTUpdate(PVMDKIMAGE pImage, PVMDKEXTENT pExtent,
5171 PVDIOCTX pIoCtx,
5172 PVMDKGRAINALLOCASYNC pGrainAlloc)
5173{
5174 int rc = VINF_SUCCESS;
5175 PVMDKGTCACHE pCache = pImage->pGTCache;
5176 uint32_t aGTDataTmp[VMDK_GT_CACHELINE_SIZE];
5177 uint32_t uGTHash, uGTBlockIndex;
5178 uint64_t uGTSector, uRGTSector, uGTBlock;
5179 uint64_t uSector = pGrainAlloc->uSector;
5180 PVMDKGTCACHEENTRY pGTCacheEntry;
5181
5182 LogFlowFunc(("pImage=%#p pExtent=%#p pCache=%#p pIoCtx=%#p pGrainAlloc=%#p\n",
5183 pImage, pExtent, pCache, pIoCtx, pGrainAlloc));
5184
5185 uGTSector = pGrainAlloc->uGTSector;
5186 uRGTSector = pGrainAlloc->uRGTSector;
5187 LogFlow(("uGTSector=%llu uRGTSector=%llu\n", uGTSector, uRGTSector));
5188
5189 /* Update the grain table (and the cache). */
5190 uGTBlock = uSector / (pExtent->cSectorsPerGrain * VMDK_GT_CACHELINE_SIZE);
5191 uGTHash = vmdkGTCacheHash(pCache, uGTBlock, pExtent->uExtent);
5192 pGTCacheEntry = &pCache->aGTCache[uGTHash];
5193 if ( pGTCacheEntry->uExtent != pExtent->uExtent
5194 || pGTCacheEntry->uGTBlock != uGTBlock)
5195 {
5196 /* Cache miss, fetch data from disk. */
5197 LogFlow(("Cache miss, fetch data from disk\n"));
5198 PVDMETAXFER pMetaXfer = NULL;
5199 rc = vmdkFileReadMetaAsync(pImage, pExtent->pFile,
5200 VMDK_SECTOR2BYTE(uGTSector) + (uGTBlock % (pExtent->cGTEntries / VMDK_GT_CACHELINE_SIZE)) * sizeof(aGTDataTmp),
5201 aGTDataTmp, sizeof(aGTDataTmp), pIoCtx,
5202 &pMetaXfer, vmdkAllocGrainAsyncComplete, pGrainAlloc);
5203 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
5204 {
5205 pGrainAlloc->cIoXfersPending++;
5206 pGrainAlloc->fGTUpdateNeeded = true;
5207 /* Leave early, we will be called again after the read completed. */
5208 LogFlowFunc(("Metadata read in progress, leaving\n"));
5209 return rc;
5210 }
5211 else if (RT_FAILURE(rc))
5212 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: cannot read allocated grain table entry in '%s'"), pExtent->pszFullname);
5213 vmdkFileMetaXferRelease(pImage, pMetaXfer);
5214 pGTCacheEntry->uExtent = pExtent->uExtent;
5215 pGTCacheEntry->uGTBlock = uGTBlock;
5216 for (unsigned i = 0; i < VMDK_GT_CACHELINE_SIZE; i++)
5217 pGTCacheEntry->aGTData[i] = RT_LE2H_U32(aGTDataTmp[i]);
5218 }
5219 else
5220 {
5221 /* Cache hit. Convert grain table block back to disk format, otherwise
5222 * the code below will write garbage for all but the updated entry. */
5223 for (unsigned i = 0; i < VMDK_GT_CACHELINE_SIZE; i++)
5224 aGTDataTmp[i] = RT_H2LE_U32(pGTCacheEntry->aGTData[i]);
5225 }
5226 pGrainAlloc->fGTUpdateNeeded = false;
5227 uGTBlockIndex = (uSector / pExtent->cSectorsPerGrain) % VMDK_GT_CACHELINE_SIZE;
5228 aGTDataTmp[uGTBlockIndex] = RT_H2LE_U32(VMDK_BYTE2SECTOR(pGrainAlloc->uGrainOffset));
5229 pGTCacheEntry->aGTData[uGTBlockIndex] = VMDK_BYTE2SECTOR(pGrainAlloc->uGrainOffset);
5230 /* Update grain table on disk. */
5231 rc = vmdkFileWriteMetaAsync(pImage, pExtent->pFile,
5232 VMDK_SECTOR2BYTE(uGTSector) + (uGTBlock % (pExtent->cGTEntries / VMDK_GT_CACHELINE_SIZE)) * sizeof(aGTDataTmp),
5233 aGTDataTmp, sizeof(aGTDataTmp), pIoCtx,
5234 vmdkAllocGrainAsyncComplete, pGrainAlloc);
5235 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
5236 pGrainAlloc->cIoXfersPending++;
5237 else if (RT_FAILURE(rc))
5238 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: cannot write updated grain table in '%s'"), pExtent->pszFullname);
5239 if (pExtent->pRGD)
5240 {
5241 /* Update backup grain table on disk. */
5242 rc = vmdkFileWriteMetaAsync(pImage, pExtent->pFile,
5243 VMDK_SECTOR2BYTE(uRGTSector) + (uGTBlock % (pExtent->cGTEntries / VMDK_GT_CACHELINE_SIZE)) * sizeof(aGTDataTmp),
5244 aGTDataTmp, sizeof(aGTDataTmp), pIoCtx,
5245 vmdkAllocGrainAsyncComplete, pGrainAlloc);
5246 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
5247 pGrainAlloc->cIoXfersPending++;
5248 else if (RT_FAILURE(rc))
5249 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: cannot write updated backup grain table in '%s'"), pExtent->pszFullname);
5250 }
5251#ifdef VBOX_WITH_VMDK_ESX
5252 if (RT_SUCCESS(rc) && pExtent->enmType == VMDKETYPE_ESX_SPARSE)
5253 {
5254 pExtent->uFreeSector = uGTSector + VMDK_BYTE2SECTOR(cbWrite);
5255 pExtent->fMetaDirty = true;
5256 }
5257#endif /* VBOX_WITH_VMDK_ESX */
5258
5259 LogFlowFunc(("leaving rc=%Rrc\n", rc));
5260
5261 return rc;
5262}
5263
5264/**
5265 * Internal - complete the grain allocation by updating disk grain table if required.
5266 */
5267static int vmdkAllocGrainAsyncComplete(void *pBackendData, PVDIOCTX pIoCtx, void *pvUser, int rcReq)
5268{
5269 int rc = VINF_SUCCESS;
5270 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5271 PVMDKGRAINALLOCASYNC pGrainAlloc = (PVMDKGRAINALLOCASYNC)pvUser;
5272 PVMDKEXTENT pExtent = pGrainAlloc->pExtent;
5273
5274 LogFlowFunc(("pBackendData=%#p pIoCtx=%#p pvUser=%#p rcReq=%Rrc\n",
5275 pBackendData, pIoCtx, pvUser, rcReq));
5276
5277 pGrainAlloc->cIoXfersPending--;
5278 if (!pGrainAlloc->cIoXfersPending && pGrainAlloc->fGTUpdateNeeded)
5279 rc = vmdkAllocGrainAsyncGTUpdate(pImage, pGrainAlloc->pExtent,
5280 pIoCtx, pGrainAlloc);
5281
5282 if (!pGrainAlloc->cIoXfersPending)
5283 {
5284 /* Grain allocation completed. */
5285 RTMemFree(pGrainAlloc);
5286 }
5287
5288 LogFlowFunc(("Leaving rc=%Rrc\n", rc));
5289 return rc;
5290}
5291
5292/**
5293 * Internal. Allocates a new grain table (if necessary) - async version.
5294 */
5295static int vmdkAllocGrainAsync(PVMDKIMAGE pImage, PVMDKEXTENT pExtent,
5296 PVDIOCTX pIoCtx, uint64_t uSector,
5297 uint64_t cbWrite)
5298{
5299 PVMDKGTCACHE pCache = pImage->pGTCache;
5300 uint64_t uGDIndex, uGTSector, uRGTSector;
5301 uint64_t uFileOffset;
5302 PVMDKGRAINALLOCASYNC pGrainAlloc = NULL;
5303 int rc;
5304
5305 LogFlowFunc(("pCache=%#p pExtent=%#p pIoCtx=%#p uSector=%llu cbWrite=%llu\n",
5306 pCache, pExtent, pIoCtx, uSector, cbWrite));
5307
5308 AssertReturn(!(pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED), VERR_NOT_SUPPORTED);
5309
5310 pGrainAlloc = (PVMDKGRAINALLOCASYNC)RTMemAllocZ(sizeof(VMDKGRAINALLOCASYNC));
5311 if (!pGrainAlloc)
5312 return VERR_NO_MEMORY;
5313
5314 pGrainAlloc->pExtent = pExtent;
5315 pGrainAlloc->uSector = uSector;
5316
5317 uGDIndex = uSector / pExtent->cSectorsPerGDE;
5318 if (uGDIndex >= pExtent->cGDEntries)
5319 {
5320 RTMemFree(pGrainAlloc);
5321 return VERR_OUT_OF_RANGE;
5322 }
5323 uGTSector = pExtent->pGD[uGDIndex];
5324 if (pExtent->pRGD)
5325 uRGTSector = pExtent->pRGD[uGDIndex];
5326 else
5327 uRGTSector = 0; /**< avoid compiler warning */
5328 if (!uGTSector)
5329 {
5330 LogFlow(("Allocating new grain table\n"));
5331
5332 /* There is no grain table referenced by this grain directory
5333 * entry. So there is absolutely no data in this area. Allocate
5334 * a new grain table and put the reference to it in the GDs. */
5335 uFileOffset = pExtent->uAppendPosition;
5336 if (!uFileOffset)
5337 return VERR_INTERNAL_ERROR;
5338 Assert(!(uFileOffset % 512));
5339
5340 uFileOffset = RT_ALIGN_64(uFileOffset, 512);
5341 uGTSector = VMDK_BYTE2SECTOR(uFileOffset);
5342
5343 /* Normally the grain table is preallocated for hosted sparse extents
5344 * that support more than 32 bit sector numbers. So this shouldn't
5345 * ever happen on a valid extent. */
5346 if (uGTSector > UINT32_MAX)
5347 return VERR_VD_VMDK_INVALID_HEADER;
5348
5349 /* Write grain table by writing the required number of grain table
5350 * cache chunks. Allocate memory dynamically here or we flood the
5351 * metadata cache with very small entries. */
5352 size_t cbGTDataTmp = pExtent->cGTEntries * sizeof(uint32_t);
5353 uint32_t *paGTDataTmp = (uint32_t *)RTMemTmpAllocZ(cbGTDataTmp);
5354
5355 if (!paGTDataTmp)
5356 return VERR_NO_MEMORY;
5357
5358 memset(paGTDataTmp, '\0', cbGTDataTmp);
5359 rc = vmdkFileWriteMetaAsync(pImage, pExtent->pFile,
5360 VMDK_SECTOR2BYTE(uGTSector),
5361 paGTDataTmp, cbGTDataTmp, pIoCtx,
5362 vmdkAllocGrainAsyncComplete, pGrainAlloc);
5363 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
5364 pGrainAlloc->cIoXfersPending++;
5365 else if (RT_FAILURE(rc))
5366 {
5367 RTMemTmpFree(paGTDataTmp);
5368 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: cannot write grain table allocation in '%s'"), pExtent->pszFullname);
5369 }
5370 pExtent->uAppendPosition = RT_ALIGN_64( pExtent->uAppendPosition
5371 + cbGTDataTmp, 512);
5372
5373 if (pExtent->pRGD)
5374 {
5375 AssertReturn(!uRGTSector, VERR_VD_VMDK_INVALID_HEADER);
5376 uFileOffset = pExtent->uAppendPosition;
5377 if (!uFileOffset)
5378 return VERR_INTERNAL_ERROR;
5379 Assert(!(uFileOffset % 512));
5380 uRGTSector = VMDK_BYTE2SECTOR(uFileOffset);
5381
5382 /* Normally the redundant grain table is preallocated for hosted
5383 * sparse extents that support more than 32 bit sector numbers. So
5384 * this shouldn't ever happen on a valid extent. */
5385 if (uRGTSector > UINT32_MAX)
5386 {
5387 RTMemTmpFree(paGTDataTmp);
5388 return VERR_VD_VMDK_INVALID_HEADER;
5389 }
5390
5391 /* Write grain table by writing the required number of grain table
5392 * cache chunks. Allocate memory dynamically here or we flood the
5393 * metadata cache with very small entries. */
5394 rc = vmdkFileWriteMetaAsync(pImage, pExtent->pFile,
5395 VMDK_SECTOR2BYTE(uRGTSector),
5396 paGTDataTmp, cbGTDataTmp, pIoCtx,
5397 vmdkAllocGrainAsyncComplete, pGrainAlloc);
5398 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
5399 pGrainAlloc->cIoXfersPending++;
5400 else if (RT_FAILURE(rc))
5401 {
5402 RTMemTmpFree(paGTDataTmp);
5403 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: cannot write backup grain table allocation in '%s'"), pExtent->pszFullname);
5404 }
5405
5406 pExtent->uAppendPosition = pExtent->uAppendPosition + cbGTDataTmp;
5407 }
5408
5409 RTMemTmpFree(paGTDataTmp);
5410
5411 /* Update the grain directory on disk (doing it before writing the
5412 * grain table will result in a garbled extent if the operation is
5413 * aborted for some reason. Otherwise the worst that can happen is
5414 * some unused sectors in the extent. */
5415 uint32_t uGTSectorLE = RT_H2LE_U64(uGTSector);
5416 rc = vmdkFileWriteMetaAsync(pImage, pExtent->pFile,
5417 VMDK_SECTOR2BYTE(pExtent->uSectorGD) + uGDIndex * sizeof(uGTSectorLE),
5418 &uGTSectorLE, sizeof(uGTSectorLE), pIoCtx,
5419 vmdkAllocGrainAsyncComplete, pGrainAlloc);
5420 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
5421 pGrainAlloc->cIoXfersPending++;
5422 else if (RT_FAILURE(rc))
5423 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: cannot write grain directory entry in '%s'"), pExtent->pszFullname);
5424 if (pExtent->pRGD)
5425 {
5426 uint32_t uRGTSectorLE = RT_H2LE_U64(uRGTSector);
5427 rc = vmdkFileWriteMetaAsync(pImage, pExtent->pFile,
5428 VMDK_SECTOR2BYTE(pExtent->uSectorRGD) + uGDIndex * sizeof(uGTSectorLE),
5429 &uRGTSectorLE, sizeof(uRGTSectorLE), pIoCtx,
5430 vmdkAllocGrainAsyncComplete, pGrainAlloc);
5431 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
5432 pGrainAlloc->cIoXfersPending++;
5433 else if (RT_FAILURE(rc))
5434 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: cannot write backup grain directory entry in '%s'"), pExtent->pszFullname);
5435 }
5436
5437 /* As the final step update the in-memory copy of the GDs. */
5438 pExtent->pGD[uGDIndex] = uGTSector;
5439 if (pExtent->pRGD)
5440 pExtent->pRGD[uGDIndex] = uRGTSector;
5441 }
5442
5443 LogFlow(("uGTSector=%llu uRGTSector=%llu\n", uGTSector, uRGTSector));
5444 pGrainAlloc->uGTSector = uGTSector;
5445 pGrainAlloc->uRGTSector = uRGTSector;
5446
5447 uFileOffset = pExtent->uAppendPosition;
5448 if (!uFileOffset)
5449 return VERR_INTERNAL_ERROR;
5450 Assert(!(uFileOffset % 512));
5451
5452 pGrainAlloc->uGrainOffset = uFileOffset;
5453
5454 /* Write the data. Always a full grain, or we're in big trouble. */
5455 rc = vmdkFileWriteUserAsync(pImage, pExtent->pFile,
5456 uFileOffset, pIoCtx, cbWrite,
5457 vmdkAllocGrainAsyncComplete, pGrainAlloc);
5458 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
5459 pGrainAlloc->cIoXfersPending++;
5460 else if (RT_FAILURE(rc))
5461 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: cannot write allocated data block in '%s'"), pExtent->pszFullname);
5462
5463 pExtent->uAppendPosition += cbWrite;
5464
5465 rc = vmdkAllocGrainAsyncGTUpdate(pImage, pExtent, pIoCtx, pGrainAlloc);
5466
5467 if (!pGrainAlloc->cIoXfersPending)
5468 {
5469 /* Grain allocation completed. */
5470 RTMemFree(pGrainAlloc);
5471 }
5472
5473 LogFlowFunc(("leaving rc=%Rrc\n", rc));
5474
5475 return rc;
5476}
5477
5478/**
5479 * Internal. Reads the contents by sequentially going over the compressed
5480 * grains (hoping that they are in sequence).
5481 */
5482static int vmdkStreamReadSequential(PVMDKIMAGE pImage, PVMDKEXTENT pExtent,
5483 uint64_t uSector, void *pvBuf,
5484 uint64_t cbRead)
5485{
5486 int rc;
5487
5488 /* Do not allow to go back. */
5489 uint32_t uGrain = uSector / pExtent->cSectorsPerGrain;
5490 if (uGrain < pExtent->uLastGrainAccess)
5491 return VERR_VD_VMDK_INVALID_STATE;
5492 pExtent->uLastGrainAccess = uGrain;
5493
5494 /* After a previous error do not attempt to recover, as it would need
5495 * seeking (in the general case backwards which is forbidden). */
5496 if (!pExtent->uGrainSectorAbs)
5497 return VERR_VD_VMDK_INVALID_STATE;
5498
5499 /* Check if we need to read something from the image or if what we have
5500 * in the buffer is good to fulfill the request. */
5501 if (!pExtent->cbGrainStreamRead || uGrain > pExtent->uGrain)
5502 {
5503 uint32_t uGrainSectorAbs = pExtent->uGrainSectorAbs
5504 + VMDK_BYTE2SECTOR(pExtent->cbGrainStreamRead);
5505
5506 /* Get the marker from the next data block - and skip everything which
5507 * is not a compressed grain. If it's a compressed grain which is for
5508 * the requested sector (or after), read it. */
5509 VMDKMARKER Marker;
5510 do
5511 {
5512 RT_ZERO(Marker);
5513 rc = vmdkFileReadSync(pImage, pExtent->pFile,
5514 VMDK_SECTOR2BYTE(uGrainSectorAbs),
5515 &Marker, RT_OFFSETOF(VMDKMARKER, uType),
5516 NULL);
5517 if (RT_FAILURE(rc))
5518 return rc;
5519 Marker.uSector = RT_LE2H_U64(Marker.uSector);
5520 Marker.cbSize = RT_LE2H_U32(Marker.cbSize);
5521
5522 if (Marker.cbSize == 0)
5523 {
5524 /* A marker for something else than a compressed grain. */
5525 rc = vmdkFileReadSync(pImage, pExtent->pFile,
5526 VMDK_SECTOR2BYTE(uGrainSectorAbs)
5527 + RT_OFFSETOF(VMDKMARKER, uType),
5528 &Marker.uType, sizeof(Marker.uType),
5529 NULL);
5530 if (RT_FAILURE(rc))
5531 return rc;
5532 Marker.uType = RT_LE2H_U32(Marker.uType);
5533 switch (Marker.uType)
5534 {
5535 case VMDK_MARKER_EOS:
5536 uGrainSectorAbs++;
5537 /* Read (or mostly skip) to the end of file. Uses the
5538 * Marker (LBA sector) as it is unused anyway. This
5539 * makes sure that really everything is read in the
5540 * success case. If this read fails it means the image
5541 * is truncated, but this is harmless so ignore. */
5542 vmdkFileReadSync(pImage, pExtent->pFile,
5543 VMDK_SECTOR2BYTE(uGrainSectorAbs)
5544 + 511,
5545 &Marker.uSector, 1, NULL);
5546 break;
5547 case VMDK_MARKER_GT:
5548 uGrainSectorAbs += 1 + VMDK_BYTE2SECTOR(pExtent->cGTEntries * sizeof(uint32_t));
5549 break;
5550 case VMDK_MARKER_GD:
5551 uGrainSectorAbs += 1 + VMDK_BYTE2SECTOR(RT_ALIGN(pExtent->cGDEntries * sizeof(uint32_t), 512));
5552 break;
5553 case VMDK_MARKER_FOOTER:
5554 uGrainSectorAbs += 2;
5555 break;
5556 default:
5557 AssertMsgFailed(("VMDK: corrupted marker, type=%#x\n", Marker.uType));
5558 pExtent->uGrainSectorAbs = 0;
5559 return VERR_VD_VMDK_INVALID_STATE;
5560 }
5561 pExtent->cbGrainStreamRead = 0;
5562 }
5563 else
5564 {
5565 /* A compressed grain marker. If it is at/after what we're
5566 * interested in read and decompress data. */
5567 if (uSector > Marker.uSector + pExtent->cSectorsPerGrain)
5568 {
5569 uGrainSectorAbs += VMDK_BYTE2SECTOR(RT_ALIGN(Marker.cbSize + RT_OFFSETOF(VMDKMARKER, uType), 512));
5570 continue;
5571 }
5572 uint64_t uLBA = 0;
5573 uint32_t cbGrainStreamRead = 0;
5574 rc = vmdkFileInflateSync(pImage, pExtent,
5575 VMDK_SECTOR2BYTE(uGrainSectorAbs),
5576 pExtent->pvGrain,
5577 VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain),
5578 &Marker, &uLBA, &cbGrainStreamRead);
5579 if (RT_FAILURE(rc))
5580 {
5581 pExtent->uGrainSectorAbs = 0;
5582 return rc;
5583 }
5584 if ( pExtent->uGrain
5585 && uLBA / pExtent->cSectorsPerGrain <= pExtent->uGrain)
5586 {
5587 pExtent->uGrainSectorAbs = 0;
5588 return VERR_VD_VMDK_INVALID_STATE;
5589 }
5590 pExtent->uGrain = uLBA / pExtent->cSectorsPerGrain;
5591 pExtent->cbGrainStreamRead = cbGrainStreamRead;
5592 break;
5593 }
5594 } while (Marker.uType != VMDK_MARKER_EOS);
5595
5596 pExtent->uGrainSectorAbs = uGrainSectorAbs;
5597
5598 if (!pExtent->cbGrainStreamRead && Marker.uType == VMDK_MARKER_EOS)
5599 {
5600 pExtent->uGrain = UINT32_MAX;
5601 /* Must set a non-zero value for pExtent->cbGrainStreamRead or
5602 * the next read would try to get more data, and we're at EOF. */
5603 pExtent->cbGrainStreamRead = 1;
5604 }
5605 }
5606
5607 if (pExtent->uGrain > uSector / pExtent->cSectorsPerGrain)
5608 {
5609 /* The next data block we have is not for this area, so just return
5610 * that there is no data. */
5611 return VERR_VD_BLOCK_FREE;
5612 }
5613
5614 uint32_t uSectorInGrain = uSector % pExtent->cSectorsPerGrain;
5615 memcpy(pvBuf,
5616 (uint8_t *)pExtent->pvGrain + VMDK_SECTOR2BYTE(uSectorInGrain),
5617 cbRead);
5618 return VINF_SUCCESS;
5619}
5620
5621/**
5622 * Replaces a fragment of a string with the specified string.
5623 *
5624 * @returns Pointer to the allocated UTF-8 string.
5625 * @param pszWhere UTF-8 string to search in.
5626 * @param pszWhat UTF-8 string to search for.
5627 * @param pszByWhat UTF-8 string to replace the found string with.
5628 */
5629static char *vmdkStrReplace(const char *pszWhere, const char *pszWhat,
5630 const char *pszByWhat)
5631{
5632 AssertPtr(pszWhere);
5633 AssertPtr(pszWhat);
5634 AssertPtr(pszByWhat);
5635 const char *pszFoundStr = strstr(pszWhere, pszWhat);
5636 if (!pszFoundStr)
5637 return NULL;
5638 size_t cFinal = strlen(pszWhere) + 1 + strlen(pszByWhat) - strlen(pszWhat);
5639 char *pszNewStr = (char *)RTMemAlloc(cFinal);
5640 if (pszNewStr)
5641 {
5642 char *pszTmp = pszNewStr;
5643 memcpy(pszTmp, pszWhere, pszFoundStr - pszWhere);
5644 pszTmp += pszFoundStr - pszWhere;
5645 memcpy(pszTmp, pszByWhat, strlen(pszByWhat));
5646 pszTmp += strlen(pszByWhat);
5647 strcpy(pszTmp, pszFoundStr + strlen(pszWhat));
5648 }
5649 return pszNewStr;
5650}
5651
5652
5653/** @copydoc VBOXHDDBACKEND::pfnCheckIfValid */
5654static int vmdkCheckIfValid(const char *pszFilename, PVDINTERFACE pVDIfsDisk,
5655 PVDINTERFACE pVDIfsImage, VDTYPE *penmType)
5656{
5657 LogFlowFunc(("pszFilename=\"%s\" pVDIfsDisk=%#p pVDIfsImage=%#p penmType=%#p\n",
5658 pszFilename, pVDIfsDisk, pVDIfsImage, penmType));
5659 int rc = VINF_SUCCESS;
5660 PVMDKIMAGE pImage;
5661
5662 if ( !pszFilename
5663 || !*pszFilename
5664 || strchr(pszFilename, '"'))
5665 {
5666 rc = VERR_INVALID_PARAMETER;
5667 goto out;
5668 }
5669
5670 pImage = (PVMDKIMAGE)RTMemAllocZ(sizeof(VMDKIMAGE));
5671 if (!pImage)
5672 {
5673 rc = VERR_NO_MEMORY;
5674 goto out;
5675 }
5676 pImage->pszFilename = pszFilename;
5677 pImage->pFile = NULL;
5678 pImage->pExtents = NULL;
5679 pImage->pFiles = NULL;
5680 pImage->pGTCache = NULL;
5681 pImage->pDescData = NULL;
5682 pImage->pVDIfsDisk = pVDIfsDisk;
5683 pImage->pVDIfsImage = pVDIfsImage;
5684 /** @todo speed up this test open (VD_OPEN_FLAGS_INFO) by skipping as
5685 * much as possible in vmdkOpenImage. */
5686 rc = vmdkOpenImage(pImage, VD_OPEN_FLAGS_INFO | VD_OPEN_FLAGS_READONLY);
5687 vmdkFreeImage(pImage, false);
5688 RTMemFree(pImage);
5689
5690 if (RT_SUCCESS(rc))
5691 *penmType = VDTYPE_HDD;
5692
5693out:
5694 LogFlowFunc(("returns %Rrc\n", rc));
5695 return rc;
5696}
5697
5698/** @copydoc VBOXHDDBACKEND::pfnOpen */
5699static int vmdkOpen(const char *pszFilename, unsigned uOpenFlags,
5700 PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
5701 VDTYPE enmType, void **ppBackendData)
5702{
5703 LogFlowFunc(("pszFilename=\"%s\" uOpenFlags=%#x pVDIfsDisk=%#p pVDIfsImage=%#p ppBackendData=%#p\n", pszFilename, uOpenFlags, pVDIfsDisk, pVDIfsImage, ppBackendData));
5704 int rc;
5705 PVMDKIMAGE pImage;
5706
5707 /* Check open flags. All valid flags are supported. */
5708 if (uOpenFlags & ~VD_OPEN_FLAGS_MASK)
5709 {
5710 rc = VERR_INVALID_PARAMETER;
5711 goto out;
5712 }
5713
5714 /* Check remaining arguments. */
5715 if ( !VALID_PTR(pszFilename)
5716 || !*pszFilename
5717 || strchr(pszFilename, '"'))
5718 {
5719 rc = VERR_INVALID_PARAMETER;
5720 goto out;
5721 }
5722
5723 pImage = (PVMDKIMAGE)RTMemAllocZ(sizeof(VMDKIMAGE));
5724 if (!pImage)
5725 {
5726 rc = VERR_NO_MEMORY;
5727 goto out;
5728 }
5729 pImage->pszFilename = pszFilename;
5730 pImage->pFile = NULL;
5731 pImage->pExtents = NULL;
5732 pImage->pFiles = NULL;
5733 pImage->pGTCache = NULL;
5734 pImage->pDescData = NULL;
5735 pImage->pVDIfsDisk = pVDIfsDisk;
5736 pImage->pVDIfsImage = pVDIfsImage;
5737
5738 rc = vmdkOpenImage(pImage, uOpenFlags);
5739 if (RT_SUCCESS(rc))
5740 *ppBackendData = pImage;
5741
5742out:
5743 LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
5744 return rc;
5745}
5746
5747/** @copydoc VBOXHDDBACKEND::pfnCreate */
5748static int vmdkCreate(const char *pszFilename, uint64_t cbSize,
5749 unsigned uImageFlags, const char *pszComment,
5750 PCVDGEOMETRY pPCHSGeometry, PCVDGEOMETRY pLCHSGeometry,
5751 PCRTUUID pUuid, unsigned uOpenFlags,
5752 unsigned uPercentStart, unsigned uPercentSpan,
5753 PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
5754 PVDINTERFACE pVDIfsOperation, void **ppBackendData)
5755{
5756 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\n", pszFilename, cbSize, uImageFlags, pszComment, pPCHSGeometry, pLCHSGeometry, pUuid, uOpenFlags, uPercentStart, uPercentSpan, pVDIfsDisk, pVDIfsImage, pVDIfsOperation, ppBackendData));
5757 int rc;
5758 PVMDKIMAGE pImage;
5759
5760 PFNVDPROGRESS pfnProgress = NULL;
5761 void *pvUser = NULL;
5762 PVDINTERFACE pIfProgress = VDInterfaceGet(pVDIfsOperation,
5763 VDINTERFACETYPE_PROGRESS);
5764 PVDINTERFACEPROGRESS pCbProgress = NULL;
5765 if (pIfProgress)
5766 {
5767 pCbProgress = VDGetInterfaceProgress(pIfProgress);
5768 pfnProgress = pCbProgress->pfnProgress;
5769 pvUser = pIfProgress->pvUser;
5770 }
5771
5772 /* Check open flags. All valid flags are supported. */
5773 if (uOpenFlags & ~VD_OPEN_FLAGS_MASK)
5774 {
5775 rc = VERR_INVALID_PARAMETER;
5776 goto out;
5777 }
5778
5779 /* Check size. Maximum 2TB-64K for sparse images, otherwise unlimited. */
5780 if ( !cbSize
5781 || (!(uImageFlags & VD_IMAGE_FLAGS_FIXED) && cbSize >= _1T * 2 - _64K))
5782 {
5783 rc = VERR_VD_INVALID_SIZE;
5784 goto out;
5785 }
5786
5787 /* Check remaining arguments. */
5788 if ( !VALID_PTR(pszFilename)
5789 || !*pszFilename
5790 || strchr(pszFilename, '"')
5791 || !VALID_PTR(pPCHSGeometry)
5792 || !VALID_PTR(pLCHSGeometry)
5793#ifndef VBOX_WITH_VMDK_ESX
5794 || ( uImageFlags & VD_VMDK_IMAGE_FLAGS_ESX
5795 && !(uImageFlags & VD_IMAGE_FLAGS_FIXED))
5796#endif
5797 || ( (uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
5798 && (uImageFlags & ~(VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED | VD_IMAGE_FLAGS_DIFF))))
5799 {
5800 rc = VERR_INVALID_PARAMETER;
5801 goto out;
5802 }
5803
5804 pImage = (PVMDKIMAGE)RTMemAllocZ(sizeof(VMDKIMAGE));
5805 if (!pImage)
5806 {
5807 rc = VERR_NO_MEMORY;
5808 goto out;
5809 }
5810 pImage->pszFilename = pszFilename;
5811 pImage->pFile = NULL;
5812 pImage->pExtents = NULL;
5813 pImage->pFiles = NULL;
5814 pImage->pGTCache = NULL;
5815 pImage->pDescData = NULL;
5816 pImage->pVDIfsDisk = pVDIfsDisk;
5817 pImage->pVDIfsImage = pVDIfsImage;
5818 /* Descriptors for split images can be pretty large, especially if the
5819 * filename is long. So prepare for the worst, and allocate quite some
5820 * memory for the descriptor in this case. */
5821 if (uImageFlags & VD_VMDK_IMAGE_FLAGS_SPLIT_2G)
5822 pImage->cbDescAlloc = VMDK_SECTOR2BYTE(200);
5823 else
5824 pImage->cbDescAlloc = VMDK_SECTOR2BYTE(20);
5825 pImage->pDescData = (char *)RTMemAllocZ(pImage->cbDescAlloc);
5826 if (!pImage->pDescData)
5827 {
5828 RTMemFree(pImage);
5829 rc = VERR_NO_MEMORY;
5830 goto out;
5831 }
5832
5833 rc = vmdkCreateImage(pImage, cbSize, uImageFlags, pszComment,
5834 pPCHSGeometry, pLCHSGeometry, pUuid,
5835 pfnProgress, pvUser, uPercentStart, uPercentSpan);
5836 if (RT_SUCCESS(rc))
5837 {
5838 /* So far the image is opened in read/write mode. Make sure the
5839 * image is opened in read-only mode if the caller requested that. */
5840 if (uOpenFlags & VD_OPEN_FLAGS_READONLY)
5841 {
5842 vmdkFreeImage(pImage, false);
5843 rc = vmdkOpenImage(pImage, uOpenFlags);
5844 if (RT_FAILURE(rc))
5845 goto out;
5846 }
5847 *ppBackendData = pImage;
5848 }
5849 else
5850 {
5851 RTMemFree(pImage->pDescData);
5852 RTMemFree(pImage);
5853 }
5854
5855out:
5856 LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
5857 return rc;
5858}
5859
5860/** @copydoc VBOXHDDBACKEND::pfnRename */
5861static int vmdkRename(void *pBackendData, const char *pszFilename)
5862{
5863 LogFlowFunc(("pBackendData=%#p pszFilename=%#p\n", pBackendData, pszFilename));
5864
5865 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5866 int rc = VINF_SUCCESS;
5867 char **apszOldName = NULL;
5868 char **apszNewName = NULL;
5869 char **apszNewLines = NULL;
5870 char *pszOldDescName = NULL;
5871 bool fImageFreed = false;
5872 bool fEmbeddedDesc = false;
5873 unsigned cExtents = 0;
5874 char *pszNewBaseName = NULL;
5875 char *pszOldBaseName = NULL;
5876 char *pszNewFullName = NULL;
5877 char *pszOldFullName = NULL;
5878 const char *pszOldImageName;
5879 unsigned i, line;
5880 VMDKDESCRIPTOR DescriptorCopy;
5881 VMDKEXTENT ExtentCopy;
5882
5883 memset(&DescriptorCopy, 0, sizeof(DescriptorCopy));
5884
5885 /* Check arguments. */
5886 if ( !pImage
5887 || (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_RAWDISK)
5888 || !VALID_PTR(pszFilename)
5889 || !*pszFilename)
5890 {
5891 rc = VERR_INVALID_PARAMETER;
5892 goto out;
5893 }
5894
5895 cExtents = pImage->cExtents;
5896
5897 /*
5898 * Allocate an array to store both old and new names of renamed files
5899 * in case we have to roll back the changes. Arrays are initialized
5900 * with zeros. We actually save stuff when and if we change it.
5901 */
5902 apszOldName = (char **)RTMemTmpAllocZ((cExtents + 1) * sizeof(char*));
5903 apszNewName = (char **)RTMemTmpAllocZ((cExtents + 1) * sizeof(char*));
5904 apszNewLines = (char **)RTMemTmpAllocZ((cExtents) * sizeof(char*));
5905 if (!apszOldName || !apszNewName || !apszNewLines)
5906 {
5907 rc = VERR_NO_MEMORY;
5908 goto out;
5909 }
5910
5911 /* Save the descriptor size and position. */
5912 if (pImage->pDescData)
5913 {
5914 /* Separate descriptor file. */
5915 fEmbeddedDesc = false;
5916 }
5917 else
5918 {
5919 /* Embedded descriptor file. */
5920 ExtentCopy = pImage->pExtents[0];
5921 fEmbeddedDesc = true;
5922 }
5923 /* Save the descriptor content. */
5924 DescriptorCopy.cLines = pImage->Descriptor.cLines;
5925 for (i = 0; i < DescriptorCopy.cLines; i++)
5926 {
5927 DescriptorCopy.aLines[i] = RTStrDup(pImage->Descriptor.aLines[i]);
5928 if (!DescriptorCopy.aLines[i])
5929 {
5930 rc = VERR_NO_MEMORY;
5931 goto out;
5932 }
5933 }
5934
5935 /* Prepare both old and new base names used for string replacement. */
5936 pszNewBaseName = RTStrDup(RTPathFilename(pszFilename));
5937 RTPathStripExt(pszNewBaseName);
5938 pszOldBaseName = RTStrDup(RTPathFilename(pImage->pszFilename));
5939 RTPathStripExt(pszOldBaseName);
5940 /* Prepare both old and new full names used for string replacement. */
5941 pszNewFullName = RTStrDup(pszFilename);
5942 RTPathStripExt(pszNewFullName);
5943 pszOldFullName = RTStrDup(pImage->pszFilename);
5944 RTPathStripExt(pszOldFullName);
5945
5946 /* --- Up to this point we have not done any damage yet. --- */
5947
5948 /* Save the old name for easy access to the old descriptor file. */
5949 pszOldDescName = RTStrDup(pImage->pszFilename);
5950 /* Save old image name. */
5951 pszOldImageName = pImage->pszFilename;
5952
5953 /* Update the descriptor with modified extent names. */
5954 for (i = 0, line = pImage->Descriptor.uFirstExtent;
5955 i < cExtents;
5956 i++, line = pImage->Descriptor.aNextLines[line])
5957 {
5958 /* Assume that vmdkStrReplace will fail. */
5959 rc = VERR_NO_MEMORY;
5960 /* Update the descriptor. */
5961 apszNewLines[i] = vmdkStrReplace(pImage->Descriptor.aLines[line],
5962 pszOldBaseName, pszNewBaseName);
5963 if (!apszNewLines[i])
5964 goto rollback;
5965 pImage->Descriptor.aLines[line] = apszNewLines[i];
5966 }
5967 /* Make sure the descriptor gets written back. */
5968 pImage->Descriptor.fDirty = true;
5969 /* Flush the descriptor now, in case it is embedded. */
5970 vmdkFlushImage(pImage);
5971
5972 /* Close and rename/move extents. */
5973 for (i = 0; i < cExtents; i++)
5974 {
5975 PVMDKEXTENT pExtent = &pImage->pExtents[i];
5976 /* Compose new name for the extent. */
5977 apszNewName[i] = vmdkStrReplace(pExtent->pszFullname,
5978 pszOldFullName, pszNewFullName);
5979 if (!apszNewName[i])
5980 goto rollback;
5981 /* Close the extent file. */
5982 vmdkFileClose(pImage, &pExtent->pFile, false);
5983 /* Rename the extent file. */
5984 rc = vmdkFileMove(pImage, pExtent->pszFullname, apszNewName[i], 0);
5985 if (RT_FAILURE(rc))
5986 goto rollback;
5987 /* Remember the old name. */
5988 apszOldName[i] = RTStrDup(pExtent->pszFullname);
5989 }
5990 /* Release all old stuff. */
5991 vmdkFreeImage(pImage, false);
5992
5993 fImageFreed = true;
5994
5995 /* Last elements of new/old name arrays are intended for
5996 * storing descriptor's names.
5997 */
5998 apszNewName[cExtents] = RTStrDup(pszFilename);
5999 /* Rename the descriptor file if it's separate. */
6000 if (!fEmbeddedDesc)
6001 {
6002 rc = vmdkFileMove(pImage, pImage->pszFilename, apszNewName[cExtents], 0);
6003 if (RT_FAILURE(rc))
6004 goto rollback;
6005 /* Save old name only if we may need to change it back. */
6006 apszOldName[cExtents] = RTStrDup(pszFilename);
6007 }
6008
6009 /* Update pImage with the new information. */
6010 pImage->pszFilename = pszFilename;
6011
6012 /* Open the new image. */
6013 rc = vmdkOpenImage(pImage, pImage->uOpenFlags);
6014 if (RT_SUCCESS(rc))
6015 goto out;
6016
6017rollback:
6018 /* Roll back all changes in case of failure. */
6019 if (RT_FAILURE(rc))
6020 {
6021 int rrc;
6022 if (!fImageFreed)
6023 {
6024 /*
6025 * Some extents may have been closed, close the rest. We will
6026 * re-open the whole thing later.
6027 */
6028 vmdkFreeImage(pImage, false);
6029 }
6030 /* Rename files back. */
6031 for (i = 0; i <= cExtents; i++)
6032 {
6033 if (apszOldName[i])
6034 {
6035 rrc = vmdkFileMove(pImage, apszNewName[i], apszOldName[i], 0);
6036 AssertRC(rrc);
6037 }
6038 }
6039 /* Restore the old descriptor. */
6040 PVMDKFILE pFile;
6041 rrc = vmdkFileOpen(pImage, &pFile, pszOldDescName,
6042 VDOpenFlagsToFileOpenFlags(VD_OPEN_FLAGS_NORMAL,
6043 false /* fCreate */),
6044 false /* fAsyncIO */);
6045 AssertRC(rrc);
6046 if (fEmbeddedDesc)
6047 {
6048 ExtentCopy.pFile = pFile;
6049 pImage->pExtents = &ExtentCopy;
6050 }
6051 else
6052 {
6053 /* Shouldn't be null for separate descriptor.
6054 * There will be no access to the actual content.
6055 */
6056 pImage->pDescData = pszOldDescName;
6057 pImage->pFile = pFile;
6058 }
6059 pImage->Descriptor = DescriptorCopy;
6060 vmdkWriteDescriptor(pImage);
6061 vmdkFileClose(pImage, &pFile, false);
6062 /* Get rid of the stuff we implanted. */
6063 pImage->pExtents = NULL;
6064 pImage->pFile = NULL;
6065 pImage->pDescData = NULL;
6066 /* Re-open the image back. */
6067 pImage->pszFilename = pszOldImageName;
6068 rrc = vmdkOpenImage(pImage, pImage->uOpenFlags);
6069 AssertRC(rrc);
6070 }
6071
6072out:
6073 for (i = 0; i < DescriptorCopy.cLines; i++)
6074 if (DescriptorCopy.aLines[i])
6075 RTStrFree(DescriptorCopy.aLines[i]);
6076 if (apszOldName)
6077 {
6078 for (i = 0; i <= cExtents; i++)
6079 if (apszOldName[i])
6080 RTStrFree(apszOldName[i]);
6081 RTMemTmpFree(apszOldName);
6082 }
6083 if (apszNewName)
6084 {
6085 for (i = 0; i <= cExtents; i++)
6086 if (apszNewName[i])
6087 RTStrFree(apszNewName[i]);
6088 RTMemTmpFree(apszNewName);
6089 }
6090 if (apszNewLines)
6091 {
6092 for (i = 0; i < cExtents; i++)
6093 if (apszNewLines[i])
6094 RTStrFree(apszNewLines[i]);
6095 RTMemTmpFree(apszNewLines);
6096 }
6097 if (pszOldDescName)
6098 RTStrFree(pszOldDescName);
6099 if (pszOldBaseName)
6100 RTStrFree(pszOldBaseName);
6101 if (pszNewBaseName)
6102 RTStrFree(pszNewBaseName);
6103 if (pszOldFullName)
6104 RTStrFree(pszOldFullName);
6105 if (pszNewFullName)
6106 RTStrFree(pszNewFullName);
6107 LogFlowFunc(("returns %Rrc\n", rc));
6108 return rc;
6109}
6110
6111/** @copydoc VBOXHDDBACKEND::pfnClose */
6112static int vmdkClose(void *pBackendData, bool fDelete)
6113{
6114 LogFlowFunc(("pBackendData=%#p fDelete=%d\n", pBackendData, fDelete));
6115 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6116 int rc;
6117
6118 rc = vmdkFreeImage(pImage, fDelete);
6119 RTMemFree(pImage);
6120
6121 LogFlowFunc(("returns %Rrc\n", rc));
6122 return rc;
6123}
6124
6125/** @copydoc VBOXHDDBACKEND::pfnRead */
6126static int vmdkRead(void *pBackendData, uint64_t uOffset, void *pvBuf,
6127 size_t cbToRead, size_t *pcbActuallyRead)
6128{
6129 LogFlowFunc(("pBackendData=%#p uOffset=%llu pvBuf=%#p cbToRead=%zu pcbActuallyRead=%#p\n", pBackendData, uOffset, pvBuf, cbToRead, pcbActuallyRead));
6130 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6131 PVMDKEXTENT pExtent;
6132 uint64_t uSectorExtentRel;
6133 uint64_t uSectorExtentAbs;
6134 int rc;
6135
6136 AssertPtr(pImage);
6137 Assert(uOffset % 512 == 0);
6138 Assert(cbToRead % 512 == 0);
6139
6140 if ( uOffset + cbToRead > pImage->cbSize
6141 || cbToRead == 0)
6142 {
6143 rc = VERR_INVALID_PARAMETER;
6144 goto out;
6145 }
6146
6147 rc = vmdkFindExtent(pImage, VMDK_BYTE2SECTOR(uOffset),
6148 &pExtent, &uSectorExtentRel);
6149 if (RT_FAILURE(rc))
6150 goto out;
6151
6152 /* Check access permissions as defined in the extent descriptor. */
6153 if (pExtent->enmAccess == VMDKACCESS_NOACCESS)
6154 {
6155 rc = VERR_VD_VMDK_INVALID_STATE;
6156 goto out;
6157 }
6158
6159 /* Clip read range to remain in this extent. */
6160 cbToRead = RT_MIN(cbToRead, VMDK_SECTOR2BYTE(pExtent->uSectorOffset + pExtent->cNominalSectors - uSectorExtentRel));
6161
6162 /* Handle the read according to the current extent type. */
6163 switch (pExtent->enmType)
6164 {
6165 case VMDKETYPE_HOSTED_SPARSE:
6166#ifdef VBOX_WITH_VMDK_ESX
6167 case VMDKETYPE_ESX_SPARSE:
6168#endif /* VBOX_WITH_VMDK_ESX */
6169 rc = vmdkGetSector(pImage, pExtent, uSectorExtentRel,
6170 &uSectorExtentAbs);
6171 if (RT_FAILURE(rc))
6172 goto out;
6173 /* Clip read range to at most the rest of the grain. */
6174 cbToRead = RT_MIN(cbToRead, VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain - uSectorExtentRel % pExtent->cSectorsPerGrain));
6175 Assert(!(cbToRead % 512));
6176 if (uSectorExtentAbs == 0)
6177 {
6178 if ( !(pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
6179 || !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
6180 || !(pImage->uOpenFlags & VD_OPEN_FLAGS_SEQUENTIAL))
6181 rc = VERR_VD_BLOCK_FREE;
6182 else
6183 rc = vmdkStreamReadSequential(pImage, pExtent,
6184 uSectorExtentRel,
6185 pvBuf, cbToRead);
6186 }
6187 else
6188 {
6189 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
6190 {
6191 uint32_t uSectorInGrain = uSectorExtentRel % pExtent->cSectorsPerGrain;
6192 uSectorExtentAbs -= uSectorInGrain;
6193 uint64_t uLBA;
6194 if (pExtent->uGrainSectorAbs != uSectorExtentAbs)
6195 {
6196 rc = vmdkFileInflateSync(pImage, pExtent,
6197 VMDK_SECTOR2BYTE(uSectorExtentAbs),
6198 pExtent->pvGrain,
6199 VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain),
6200 NULL, &uLBA, NULL);
6201 if (RT_FAILURE(rc))
6202 {
6203 pExtent->uGrainSectorAbs = 0;
6204 AssertRC(rc);
6205 goto out;
6206 }
6207 pExtent->uGrainSectorAbs = uSectorExtentAbs;
6208 pExtent->uGrain = uSectorExtentRel / pExtent->cSectorsPerGrain;
6209 Assert(uLBA == uSectorExtentRel);
6210 }
6211 memcpy(pvBuf, (uint8_t *)pExtent->pvGrain + VMDK_SECTOR2BYTE(uSectorInGrain), cbToRead);
6212 }
6213 else
6214 {
6215 rc = vmdkFileReadSync(pImage, pExtent->pFile,
6216 VMDK_SECTOR2BYTE(uSectorExtentAbs),
6217 pvBuf, cbToRead, NULL);
6218 }
6219 }
6220 break;
6221 case VMDKETYPE_VMFS:
6222 case VMDKETYPE_FLAT:
6223 rc = vmdkFileReadSync(pImage, pExtent->pFile,
6224 VMDK_SECTOR2BYTE(uSectorExtentRel),
6225 pvBuf, cbToRead, NULL);
6226 break;
6227 case VMDKETYPE_ZERO:
6228 memset(pvBuf, '\0', cbToRead);
6229 break;
6230 }
6231 if (pcbActuallyRead)
6232 *pcbActuallyRead = cbToRead;
6233
6234out:
6235 LogFlowFunc(("returns %Rrc\n", rc));
6236 return rc;
6237}
6238
6239/** @copydoc VBOXHDDBACKEND::pfnWrite */
6240static int vmdkWrite(void *pBackendData, uint64_t uOffset, const void *pvBuf,
6241 size_t cbToWrite, size_t *pcbWriteProcess,
6242 size_t *pcbPreRead, size_t *pcbPostRead, unsigned fWrite)
6243{
6244 LogFlowFunc(("pBackendData=%#p uOffset=%llu pvBuf=%#p cbToWrite=%zu pcbWriteProcess=%#p pcbPreRead=%#p pcbPostRead=%#p\n", pBackendData, uOffset, pvBuf, cbToWrite, pcbWriteProcess, pcbPreRead, pcbPostRead));
6245 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6246 PVMDKEXTENT pExtent;
6247 uint64_t uSectorExtentRel;
6248 uint64_t uSectorExtentAbs;
6249 int rc;
6250
6251 AssertPtr(pImage);
6252 Assert(uOffset % 512 == 0);
6253 Assert(cbToWrite % 512 == 0);
6254
6255 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
6256 {
6257 rc = VERR_VD_IMAGE_READ_ONLY;
6258 goto out;
6259 }
6260
6261 if (cbToWrite == 0)
6262 {
6263 rc = VERR_INVALID_PARAMETER;
6264 goto out;
6265 }
6266
6267 /* No size check here, will do that later when the extent is located.
6268 * There are sparse images out there which according to the spec are
6269 * invalid, because the total size is not a multiple of the grain size.
6270 * Also for sparse images which are stitched together in odd ways (not at
6271 * grain boundaries, and with the nominal size not being a multiple of the
6272 * grain size), this would prevent writing to the last grain. */
6273
6274 rc = vmdkFindExtent(pImage, VMDK_BYTE2SECTOR(uOffset),
6275 &pExtent, &uSectorExtentRel);
6276 if (RT_FAILURE(rc))
6277 goto out;
6278
6279 /* Check access permissions as defined in the extent descriptor. */
6280 if ( pExtent->enmAccess != VMDKACCESS_READWRITE
6281 && ( !(pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
6282 && !pImage->pExtents[0].uAppendPosition
6283 && pExtent->enmAccess != VMDKACCESS_READONLY))
6284 {
6285 rc = VERR_VD_VMDK_INVALID_STATE;
6286 goto out;
6287 }
6288
6289 /* Handle the write according to the current extent type. */
6290 switch (pExtent->enmType)
6291 {
6292 case VMDKETYPE_HOSTED_SPARSE:
6293#ifdef VBOX_WITH_VMDK_ESX
6294 case VMDKETYPE_ESX_SPARSE:
6295#endif /* VBOX_WITH_VMDK_ESX */
6296 rc = vmdkGetSector(pImage, pExtent, uSectorExtentRel,
6297 &uSectorExtentAbs);
6298 if (RT_FAILURE(rc))
6299 goto out;
6300 /* Clip write range to at most the rest of the grain. */
6301 cbToWrite = RT_MIN(cbToWrite, VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain - uSectorExtentRel % pExtent->cSectorsPerGrain));
6302 if ( pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED
6303 && uSectorExtentRel < (uint64_t)pExtent->uLastGrainAccess * pExtent->cSectorsPerGrain)
6304 {
6305 rc = VERR_VD_VMDK_INVALID_WRITE;
6306 goto out;
6307 }
6308 if (uSectorExtentAbs == 0)
6309 {
6310 if (!(pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED))
6311 {
6312 if (cbToWrite == VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain))
6313 {
6314 /* Full block write to a previously unallocated block.
6315 * Check if the caller wants feedback. */
6316 if (!(fWrite & VD_WRITE_NO_ALLOC))
6317 {
6318 /* Allocate GT and store the grain. */
6319 rc = vmdkAllocGrain(pImage, pExtent,
6320 uSectorExtentRel,
6321 pvBuf, cbToWrite);
6322 }
6323 else
6324 rc = VERR_VD_BLOCK_FREE;
6325 *pcbPreRead = 0;
6326 *pcbPostRead = 0;
6327 }
6328 else
6329 {
6330 /* Clip write range to remain in this extent. */
6331 cbToWrite = RT_MIN(cbToWrite, VMDK_SECTOR2BYTE(pExtent->uSectorOffset + pExtent->cNominalSectors - uSectorExtentRel));
6332 *pcbPreRead = VMDK_SECTOR2BYTE(uSectorExtentRel % pExtent->cSectorsPerGrain);
6333 *pcbPostRead = VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain) - cbToWrite - *pcbPreRead;
6334 rc = VERR_VD_BLOCK_FREE;
6335 }
6336 }
6337 else
6338 {
6339 rc = vmdkStreamAllocGrain(pImage, pExtent,
6340 uSectorExtentRel,
6341 pvBuf, cbToWrite);
6342 }
6343 }
6344 else
6345 {
6346 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
6347 {
6348 /* A partial write to a streamOptimized image is simply
6349 * invalid. It requires rewriting already compressed data
6350 * which is somewhere between expensive and impossible. */
6351 rc = VERR_VD_VMDK_INVALID_STATE;
6352 pExtent->uGrainSectorAbs = 0;
6353 AssertRC(rc);
6354 }
6355 else
6356 {
6357 rc = vmdkFileWriteSync(pImage, pExtent->pFile,
6358 VMDK_SECTOR2BYTE(uSectorExtentAbs),
6359 pvBuf, cbToWrite, NULL);
6360 }
6361 }
6362 break;
6363 case VMDKETYPE_VMFS:
6364 case VMDKETYPE_FLAT:
6365 /* Clip write range to remain in this extent. */
6366 cbToWrite = RT_MIN(cbToWrite, VMDK_SECTOR2BYTE(pExtent->uSectorOffset + pExtent->cNominalSectors - uSectorExtentRel));
6367 rc = vmdkFileWriteSync(pImage, pExtent->pFile,
6368 VMDK_SECTOR2BYTE(uSectorExtentRel),
6369 pvBuf, cbToWrite, NULL);
6370 break;
6371 case VMDKETYPE_ZERO:
6372 /* Clip write range to remain in this extent. */
6373 cbToWrite = RT_MIN(cbToWrite, VMDK_SECTOR2BYTE(pExtent->uSectorOffset + pExtent->cNominalSectors - uSectorExtentRel));
6374 break;
6375 }
6376
6377 if (pcbWriteProcess)
6378 *pcbWriteProcess = cbToWrite;
6379
6380out:
6381 LogFlowFunc(("returns %Rrc\n", rc));
6382 return rc;
6383}
6384
6385/** @copydoc VBOXHDDBACKEND::pfnFlush */
6386static int vmdkFlush(void *pBackendData)
6387{
6388 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
6389 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6390 int rc = VINF_SUCCESS;
6391
6392 AssertPtr(pImage);
6393
6394 if (!(pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED))
6395 rc = vmdkFlushImage(pImage);
6396
6397 LogFlowFunc(("returns %Rrc\n", rc));
6398 return rc;
6399}
6400
6401/** @copydoc VBOXHDDBACKEND::pfnGetVersion */
6402static unsigned vmdkGetVersion(void *pBackendData)
6403{
6404 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
6405 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6406
6407 AssertPtr(pImage);
6408
6409 if (pImage)
6410 return VMDK_IMAGE_VERSION;
6411 else
6412 return 0;
6413}
6414
6415/** @copydoc VBOXHDDBACKEND::pfnGetSize */
6416static uint64_t vmdkGetSize(void *pBackendData)
6417{
6418 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
6419 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6420
6421 AssertPtr(pImage);
6422
6423 if (pImage)
6424 return pImage->cbSize;
6425 else
6426 return 0;
6427}
6428
6429/** @copydoc VBOXHDDBACKEND::pfnGetFileSize */
6430static uint64_t vmdkGetFileSize(void *pBackendData)
6431{
6432 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
6433 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6434 uint64_t cb = 0;
6435
6436 AssertPtr(pImage);
6437
6438 if (pImage)
6439 {
6440 uint64_t cbFile;
6441 if (pImage->pFile != NULL)
6442 {
6443 int rc = vmdkFileGetSize(pImage, pImage->pFile, &cbFile);
6444 if (RT_SUCCESS(rc))
6445 cb += cbFile;
6446 }
6447 for (unsigned i = 0; i < pImage->cExtents; i++)
6448 {
6449 if (pImage->pExtents[i].pFile != NULL)
6450 {
6451 int rc = vmdkFileGetSize(pImage, pImage->pExtents[i].pFile, &cbFile);
6452 if (RT_SUCCESS(rc))
6453 cb += cbFile;
6454 }
6455 }
6456 }
6457
6458 LogFlowFunc(("returns %lld\n", cb));
6459 return cb;
6460}
6461
6462/** @copydoc VBOXHDDBACKEND::pfnGetPCHSGeometry */
6463static int vmdkGetPCHSGeometry(void *pBackendData, PVDGEOMETRY pPCHSGeometry)
6464{
6465 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p\n", pBackendData, pPCHSGeometry));
6466 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6467 int rc;
6468
6469 AssertPtr(pImage);
6470
6471 if (pImage)
6472 {
6473 if (pImage->PCHSGeometry.cCylinders)
6474 {
6475 *pPCHSGeometry = pImage->PCHSGeometry;
6476 rc = VINF_SUCCESS;
6477 }
6478 else
6479 rc = VERR_VD_GEOMETRY_NOT_SET;
6480 }
6481 else
6482 rc = VERR_VD_NOT_OPENED;
6483
6484 LogFlowFunc(("returns %Rrc (PCHS=%u/%u/%u)\n", rc, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
6485 return rc;
6486}
6487
6488/** @copydoc VBOXHDDBACKEND::pfnSetPCHSGeometry */
6489static int vmdkSetPCHSGeometry(void *pBackendData, PCVDGEOMETRY pPCHSGeometry)
6490{
6491 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p PCHS=%u/%u/%u\n", pBackendData, pPCHSGeometry, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
6492 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6493 int rc;
6494
6495 AssertPtr(pImage);
6496
6497 if (pImage)
6498 {
6499 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
6500 {
6501 rc = VERR_VD_IMAGE_READ_ONLY;
6502 goto out;
6503 }
6504 if (pImage->uOpenFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
6505 {
6506 rc = VERR_NOT_SUPPORTED;
6507 goto out;
6508 }
6509 rc = vmdkDescSetPCHSGeometry(pImage, pPCHSGeometry);
6510 if (RT_FAILURE(rc))
6511 goto out;
6512
6513 pImage->PCHSGeometry = *pPCHSGeometry;
6514 rc = VINF_SUCCESS;
6515 }
6516 else
6517 rc = VERR_VD_NOT_OPENED;
6518
6519out:
6520 LogFlowFunc(("returns %Rrc\n", rc));
6521 return rc;
6522}
6523
6524/** @copydoc VBOXHDDBACKEND::pfnGetLCHSGeometry */
6525static int vmdkGetLCHSGeometry(void *pBackendData, PVDGEOMETRY pLCHSGeometry)
6526{
6527 LogFlowFunc(("pBackendData=%#p pLCHSGeometry=%#p\n", pBackendData, pLCHSGeometry));
6528 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6529 int rc;
6530
6531 AssertPtr(pImage);
6532
6533 if (pImage)
6534 {
6535 if (pImage->LCHSGeometry.cCylinders)
6536 {
6537 *pLCHSGeometry = pImage->LCHSGeometry;
6538 rc = VINF_SUCCESS;
6539 }
6540 else
6541 rc = VERR_VD_GEOMETRY_NOT_SET;
6542 }
6543 else
6544 rc = VERR_VD_NOT_OPENED;
6545
6546 LogFlowFunc(("returns %Rrc (LCHS=%u/%u/%u)\n", rc, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
6547 return rc;
6548}
6549
6550/** @copydoc VBOXHDDBACKEND::pfnSetLCHSGeometry */
6551static int vmdkSetLCHSGeometry(void *pBackendData, PCVDGEOMETRY pLCHSGeometry)
6552{
6553 LogFlowFunc(("pBackendData=%#p pLCHSGeometry=%#p LCHS=%u/%u/%u\n", pBackendData, pLCHSGeometry, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
6554 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6555 int rc;
6556
6557 AssertPtr(pImage);
6558
6559 if (pImage)
6560 {
6561 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
6562 {
6563 rc = VERR_VD_IMAGE_READ_ONLY;
6564 goto out;
6565 }
6566 if (pImage->uOpenFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
6567 {
6568 rc = VERR_NOT_SUPPORTED;
6569 goto out;
6570 }
6571 rc = vmdkDescSetLCHSGeometry(pImage, pLCHSGeometry);
6572 if (RT_FAILURE(rc))
6573 goto out;
6574
6575 pImage->LCHSGeometry = *pLCHSGeometry;
6576 rc = VINF_SUCCESS;
6577 }
6578 else
6579 rc = VERR_VD_NOT_OPENED;
6580
6581out:
6582 LogFlowFunc(("returns %Rrc\n", rc));
6583 return rc;
6584}
6585
6586/** @copydoc VBOXHDDBACKEND::pfnGetImageFlags */
6587static unsigned vmdkGetImageFlags(void *pBackendData)
6588{
6589 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
6590 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6591 unsigned uImageFlags;
6592
6593 AssertPtr(pImage);
6594
6595 if (pImage)
6596 uImageFlags = pImage->uImageFlags;
6597 else
6598 uImageFlags = 0;
6599
6600 LogFlowFunc(("returns %#x\n", uImageFlags));
6601 return uImageFlags;
6602}
6603
6604/** @copydoc VBOXHDDBACKEND::pfnGetOpenFlags */
6605static unsigned vmdkGetOpenFlags(void *pBackendData)
6606{
6607 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
6608 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6609 unsigned uOpenFlags;
6610
6611 AssertPtr(pImage);
6612
6613 if (pImage)
6614 uOpenFlags = pImage->uOpenFlags;
6615 else
6616 uOpenFlags = 0;
6617
6618 LogFlowFunc(("returns %#x\n", uOpenFlags));
6619 return uOpenFlags;
6620}
6621
6622/** @copydoc VBOXHDDBACKEND::pfnSetOpenFlags */
6623static int vmdkSetOpenFlags(void *pBackendData, unsigned uOpenFlags)
6624{
6625 LogFlowFunc(("pBackendData=%#p\n uOpenFlags=%#x", pBackendData, uOpenFlags));
6626 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6627 int rc;
6628
6629 /* Image must be opened and the new flags must be valid. */
6630 if (!pImage || (uOpenFlags & ~(VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO | VD_OPEN_FLAGS_ASYNC_IO | VD_OPEN_FLAGS_SHAREABLE | VD_OPEN_FLAGS_SEQUENTIAL)))
6631 {
6632 rc = VERR_INVALID_PARAMETER;
6633 goto out;
6634 }
6635
6636 /* StreamOptimized images need special treatment: reopen is prohibited. */
6637 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
6638 {
6639 if (pImage->uOpenFlags == uOpenFlags)
6640 rc = VINF_SUCCESS;
6641 else
6642 rc = VERR_INVALID_PARAMETER;
6643 goto out;
6644 }
6645
6646 /* Implement this operation via reopening the image. */
6647 vmdkFreeImage(pImage, false);
6648 rc = vmdkOpenImage(pImage, uOpenFlags);
6649
6650out:
6651 LogFlowFunc(("returns %Rrc\n", rc));
6652 return rc;
6653}
6654
6655/** @copydoc VBOXHDDBACKEND::pfnGetComment */
6656static int vmdkGetComment(void *pBackendData, char *pszComment,
6657 size_t cbComment)
6658{
6659 LogFlowFunc(("pBackendData=%#p pszComment=%#p cbComment=%zu\n", pBackendData, pszComment, cbComment));
6660 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6661 int rc;
6662
6663 AssertPtr(pImage);
6664
6665 if (pImage)
6666 {
6667 const char *pszCommentEncoded = NULL;
6668 rc = vmdkDescDDBGetStr(pImage, &pImage->Descriptor,
6669 "ddb.comment", &pszCommentEncoded);
6670 if (rc == VERR_VD_VMDK_VALUE_NOT_FOUND)
6671 pszCommentEncoded = NULL;
6672 else if (RT_FAILURE(rc))
6673 goto out;
6674
6675 if (pszComment && pszCommentEncoded)
6676 rc = vmdkDecodeString(pszCommentEncoded, pszComment, cbComment);
6677 else
6678 {
6679 if (pszComment)
6680 *pszComment = '\0';
6681 rc = VINF_SUCCESS;
6682 }
6683 if (pszCommentEncoded)
6684 RTStrFree((char *)(void *)pszCommentEncoded);
6685 }
6686 else
6687 rc = VERR_VD_NOT_OPENED;
6688
6689out:
6690 LogFlowFunc(("returns %Rrc comment='%s'\n", rc, pszComment));
6691 return rc;
6692}
6693
6694/** @copydoc VBOXHDDBACKEND::pfnSetComment */
6695static int vmdkSetComment(void *pBackendData, const char *pszComment)
6696{
6697 LogFlowFunc(("pBackendData=%#p pszComment=\"%s\"\n", pBackendData, pszComment));
6698 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6699 int rc;
6700
6701 AssertPtr(pImage);
6702
6703 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
6704 {
6705 rc = VERR_VD_IMAGE_READ_ONLY;
6706 goto out;
6707 }
6708 if (pImage->uOpenFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
6709 {
6710 rc = VERR_NOT_SUPPORTED;
6711 goto out;
6712 }
6713
6714 if (pImage)
6715 rc = vmdkSetImageComment(pImage, pszComment);
6716 else
6717 rc = VERR_VD_NOT_OPENED;
6718
6719out:
6720 LogFlowFunc(("returns %Rrc\n", rc));
6721 return rc;
6722}
6723
6724/** @copydoc VBOXHDDBACKEND::pfnGetUuid */
6725static int vmdkGetUuid(void *pBackendData, PRTUUID pUuid)
6726{
6727 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
6728 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6729 int rc;
6730
6731 AssertPtr(pImage);
6732
6733 if (pImage)
6734 {
6735 *pUuid = pImage->ImageUuid;
6736 rc = VINF_SUCCESS;
6737 }
6738 else
6739 rc = VERR_VD_NOT_OPENED;
6740
6741 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
6742 return rc;
6743}
6744
6745/** @copydoc VBOXHDDBACKEND::pfnSetUuid */
6746static int vmdkSetUuid(void *pBackendData, PCRTUUID pUuid)
6747{
6748 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
6749 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6750 int rc;
6751
6752 LogFlowFunc(("%RTuuid\n", pUuid));
6753 AssertPtr(pImage);
6754
6755 if (pImage)
6756 {
6757 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
6758 {
6759 if (!(pImage->uOpenFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED))
6760 {
6761 pImage->ImageUuid = *pUuid;
6762 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
6763 VMDK_DDB_IMAGE_UUID, pUuid);
6764 if (RT_FAILURE(rc))
6765 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error storing image UUID in descriptor in '%s'"), pImage->pszFilename);
6766 rc = VINF_SUCCESS;
6767 }
6768 else
6769 rc = VERR_NOT_SUPPORTED;
6770 }
6771 else
6772 rc = VERR_VD_IMAGE_READ_ONLY;
6773 }
6774 else
6775 rc = VERR_VD_NOT_OPENED;
6776
6777 LogFlowFunc(("returns %Rrc\n", rc));
6778 return rc;
6779}
6780
6781/** @copydoc VBOXHDDBACKEND::pfnGetModificationUuid */
6782static int vmdkGetModificationUuid(void *pBackendData, PRTUUID pUuid)
6783{
6784 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
6785 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6786 int rc;
6787
6788 AssertPtr(pImage);
6789
6790 if (pImage)
6791 {
6792 *pUuid = pImage->ModificationUuid;
6793 rc = VINF_SUCCESS;
6794 }
6795 else
6796 rc = VERR_VD_NOT_OPENED;
6797
6798 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
6799 return rc;
6800}
6801
6802/** @copydoc VBOXHDDBACKEND::pfnSetModificationUuid */
6803static int vmdkSetModificationUuid(void *pBackendData, PCRTUUID pUuid)
6804{
6805 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
6806 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6807 int rc;
6808
6809 AssertPtr(pImage);
6810
6811 if (pImage)
6812 {
6813 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
6814 {
6815 if (!(pImage->uOpenFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED))
6816 {
6817 /* Only touch the modification uuid if it changed. */
6818 if (RTUuidCompare(&pImage->ModificationUuid, pUuid))
6819 {
6820 pImage->ModificationUuid = *pUuid;
6821 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
6822 VMDK_DDB_MODIFICATION_UUID, pUuid);
6823 if (RT_FAILURE(rc))
6824 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error storing modification UUID in descriptor in '%s'"), pImage->pszFilename);
6825 }
6826 rc = VINF_SUCCESS;
6827 }
6828 else
6829 rc = VERR_NOT_SUPPORTED;
6830 }
6831 else
6832 rc = VERR_VD_IMAGE_READ_ONLY;
6833 }
6834 else
6835 rc = VERR_VD_NOT_OPENED;
6836
6837 LogFlowFunc(("returns %Rrc\n", rc));
6838 return rc;
6839}
6840
6841/** @copydoc VBOXHDDBACKEND::pfnGetParentUuid */
6842static int vmdkGetParentUuid(void *pBackendData, PRTUUID pUuid)
6843{
6844 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
6845 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6846 int rc;
6847
6848 AssertPtr(pImage);
6849
6850 if (pImage)
6851 {
6852 *pUuid = pImage->ParentUuid;
6853 rc = VINF_SUCCESS;
6854 }
6855 else
6856 rc = VERR_VD_NOT_OPENED;
6857
6858 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
6859 return rc;
6860}
6861
6862/** @copydoc VBOXHDDBACKEND::pfnSetParentUuid */
6863static int vmdkSetParentUuid(void *pBackendData, PCRTUUID pUuid)
6864{
6865 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
6866 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6867 int rc;
6868
6869 AssertPtr(pImage);
6870
6871 if (pImage)
6872 {
6873 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
6874 {
6875 if (!(pImage->uOpenFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED))
6876 {
6877 pImage->ParentUuid = *pUuid;
6878 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
6879 VMDK_DDB_PARENT_UUID, pUuid);
6880 if (RT_FAILURE(rc))
6881 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error storing parent image UUID in descriptor in '%s'"), pImage->pszFilename);
6882 rc = VINF_SUCCESS;
6883 }
6884 else
6885 rc = VERR_NOT_SUPPORTED;
6886 }
6887 else
6888 rc = VERR_VD_IMAGE_READ_ONLY;
6889 }
6890 else
6891 rc = VERR_VD_NOT_OPENED;
6892
6893 LogFlowFunc(("returns %Rrc\n", rc));
6894 return rc;
6895}
6896
6897/** @copydoc VBOXHDDBACKEND::pfnGetParentModificationUuid */
6898static int vmdkGetParentModificationUuid(void *pBackendData, PRTUUID pUuid)
6899{
6900 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
6901 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6902 int rc;
6903
6904 AssertPtr(pImage);
6905
6906 if (pImage)
6907 {
6908 *pUuid = pImage->ParentModificationUuid;
6909 rc = VINF_SUCCESS;
6910 }
6911 else
6912 rc = VERR_VD_NOT_OPENED;
6913
6914 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
6915 return rc;
6916}
6917
6918/** @copydoc VBOXHDDBACKEND::pfnSetParentModificationUuid */
6919static int vmdkSetParentModificationUuid(void *pBackendData, PCRTUUID pUuid)
6920{
6921 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
6922 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6923 int rc;
6924
6925 AssertPtr(pImage);
6926
6927 if (pImage)
6928 {
6929 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
6930 {
6931 if (!(pImage->uOpenFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED))
6932 {
6933 pImage->ParentModificationUuid = *pUuid;
6934 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
6935 VMDK_DDB_PARENT_MODIFICATION_UUID, pUuid);
6936 if (RT_FAILURE(rc))
6937 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error storing parent image UUID in descriptor in '%s'"), pImage->pszFilename);
6938 rc = VINF_SUCCESS;
6939 }
6940 else
6941 rc = VERR_NOT_SUPPORTED;
6942 }
6943 else
6944 rc = VERR_VD_IMAGE_READ_ONLY;
6945 }
6946 else
6947 rc = VERR_VD_NOT_OPENED;
6948
6949 LogFlowFunc(("returns %Rrc\n", rc));
6950 return rc;
6951}
6952
6953/** @copydoc VBOXHDDBACKEND::pfnDump */
6954static void vmdkDump(void *pBackendData)
6955{
6956 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6957
6958 AssertPtr(pImage);
6959 if (pImage)
6960 {
6961 vmdkMessage(pImage, "Header: Geometry PCHS=%u/%u/%u LCHS=%u/%u/%u cbSector=%llu\n",
6962 pImage->PCHSGeometry.cCylinders, pImage->PCHSGeometry.cHeads, pImage->PCHSGeometry.cSectors,
6963 pImage->LCHSGeometry.cCylinders, pImage->LCHSGeometry.cHeads, pImage->LCHSGeometry.cSectors,
6964 VMDK_BYTE2SECTOR(pImage->cbSize));
6965 vmdkMessage(pImage, "Header: uuidCreation={%RTuuid}\n", &pImage->ImageUuid);
6966 vmdkMessage(pImage, "Header: uuidModification={%RTuuid}\n", &pImage->ModificationUuid);
6967 vmdkMessage(pImage, "Header: uuidParent={%RTuuid}\n", &pImage->ParentUuid);
6968 vmdkMessage(pImage, "Header: uuidParentModification={%RTuuid}\n", &pImage->ParentModificationUuid);
6969 }
6970}
6971
6972/** @copydoc VBOXHDDBACKEND::pfnIsAsyncIOSupported */
6973static bool vmdkIsAsyncIOSupported(void *pBackendData)
6974{
6975 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6976
6977 /* We do not support async I/O for stream optimized VMDK images. */
6978 return (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED) == 0;
6979}
6980
6981/** @copydoc VBOXHDDBACKEND::pfnAsyncRead */
6982static int vmdkAsyncRead(void *pBackendData, uint64_t uOffset, size_t cbRead,
6983 PVDIOCTX pIoCtx, size_t *pcbActuallyRead)
6984{
6985 LogFlowFunc(("pBackendData=%#p uOffset=%llu pIoCtx=%#p cbToRead=%zu pcbActuallyRead=%#p\n",
6986 pBackendData, uOffset, pIoCtx, cbRead, pcbActuallyRead));
6987 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6988 PVMDKEXTENT pExtent;
6989 uint64_t uSectorExtentRel;
6990 uint64_t uSectorExtentAbs;
6991 int rc;
6992
6993 AssertPtr(pImage);
6994 Assert(uOffset % 512 == 0);
6995 Assert(cbRead % 512 == 0);
6996
6997 if ( uOffset + cbRead > pImage->cbSize
6998 || cbRead == 0)
6999 {
7000 rc = VERR_INVALID_PARAMETER;
7001 goto out;
7002 }
7003
7004 rc = vmdkFindExtent(pImage, VMDK_BYTE2SECTOR(uOffset),
7005 &pExtent, &uSectorExtentRel);
7006 if (RT_FAILURE(rc))
7007 goto out;
7008
7009 /* Check access permissions as defined in the extent descriptor. */
7010 if (pExtent->enmAccess == VMDKACCESS_NOACCESS)
7011 {
7012 rc = VERR_VD_VMDK_INVALID_STATE;
7013 goto out;
7014 }
7015
7016 /* Clip read range to remain in this extent. */
7017 cbRead = RT_MIN(cbRead, VMDK_SECTOR2BYTE(pExtent->uSectorOffset + pExtent->cNominalSectors - uSectorExtentRel));
7018
7019 /* Handle the read according to the current extent type. */
7020 switch (pExtent->enmType)
7021 {
7022 case VMDKETYPE_HOSTED_SPARSE:
7023#ifdef VBOX_WITH_VMDK_ESX
7024 case VMDKETYPE_ESX_SPARSE:
7025#endif /* VBOX_WITH_VMDK_ESX */
7026 rc = vmdkGetSectorAsync(pImage, pIoCtx, pExtent,
7027 uSectorExtentRel, &uSectorExtentAbs);
7028 if (RT_FAILURE(rc))
7029 goto out;
7030 /* Clip read range to at most the rest of the grain. */
7031 cbRead = RT_MIN(cbRead, VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain - uSectorExtentRel % pExtent->cSectorsPerGrain));
7032 Assert(!(cbRead % 512));
7033 if (uSectorExtentAbs == 0)
7034 rc = VERR_VD_BLOCK_FREE;
7035 else
7036 {
7037 AssertMsg(!(pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED), ("Async I/O is not supported for stream optimized VMDK's\n"));
7038 rc = vmdkFileReadUserAsync(pImage, pExtent->pFile,
7039 VMDK_SECTOR2BYTE(uSectorExtentAbs),
7040 pIoCtx, cbRead);
7041 }
7042 break;
7043 case VMDKETYPE_VMFS:
7044 case VMDKETYPE_FLAT:
7045 rc = vmdkFileReadUserAsync(pImage, pExtent->pFile,
7046 VMDK_SECTOR2BYTE(uSectorExtentRel),
7047 pIoCtx, cbRead);
7048 break;
7049 case VMDKETYPE_ZERO:
7050 size_t cbSet;
7051
7052 cbSet = vmdkFileIoCtxSet(pImage, pIoCtx, 0, cbRead);
7053 Assert(cbSet == cbRead);
7054
7055 rc = VINF_SUCCESS;
7056 break;
7057 }
7058 if (pcbActuallyRead)
7059 *pcbActuallyRead = cbRead;
7060
7061out:
7062 LogFlowFunc(("returns %Rrc\n", rc));
7063 return rc;
7064}
7065
7066/** @copydoc VBOXHDDBACKEND::pfnAsyncWrite */
7067static int vmdkAsyncWrite(void *pBackendData, uint64_t uOffset, size_t cbWrite,
7068 PVDIOCTX pIoCtx,
7069 size_t *pcbWriteProcess, size_t *pcbPreRead,
7070 size_t *pcbPostRead, unsigned fWrite)
7071{
7072 LogFlowFunc(("pBackendData=%#p uOffset=%llu pIoCtx=%#p cbToWrite=%zu pcbWriteProcess=%#p pcbPreRead=%#p pcbPostRead=%#p\n",
7073 pBackendData, uOffset, pIoCtx, cbWrite, pcbWriteProcess, pcbPreRead, pcbPostRead));
7074 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
7075 PVMDKEXTENT pExtent;
7076 uint64_t uSectorExtentRel;
7077 uint64_t uSectorExtentAbs;
7078 int rc;
7079
7080 AssertPtr(pImage);
7081 Assert(uOffset % 512 == 0);
7082 Assert(cbWrite % 512 == 0);
7083
7084 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
7085 {
7086 rc = VERR_VD_IMAGE_READ_ONLY;
7087 goto out;
7088 }
7089
7090 if (cbWrite == 0)
7091 {
7092 rc = VERR_INVALID_PARAMETER;
7093 goto out;
7094 }
7095
7096 /* No size check here, will do that later when the extent is located.
7097 * There are sparse images out there which according to the spec are
7098 * invalid, because the total size is not a multiple of the grain size.
7099 * Also for sparse images which are stitched together in odd ways (not at
7100 * grain boundaries, and with the nominal size not being a multiple of the
7101 * grain size), this would prevent writing to the last grain. */
7102
7103 rc = vmdkFindExtent(pImage, VMDK_BYTE2SECTOR(uOffset),
7104 &pExtent, &uSectorExtentRel);
7105 if (RT_FAILURE(rc))
7106 goto out;
7107
7108 /* Check access permissions as defined in the extent descriptor. */
7109 if (pExtent->enmAccess != VMDKACCESS_READWRITE)
7110 {
7111 rc = VERR_VD_VMDK_INVALID_STATE;
7112 goto out;
7113 }
7114
7115 /* Handle the write according to the current extent type. */
7116 switch (pExtent->enmType)
7117 {
7118 case VMDKETYPE_HOSTED_SPARSE:
7119#ifdef VBOX_WITH_VMDK_ESX
7120 case VMDKETYPE_ESX_SPARSE:
7121#endif /* VBOX_WITH_VMDK_ESX */
7122 rc = vmdkGetSectorAsync(pImage, pIoCtx, pExtent, uSectorExtentRel,
7123 &uSectorExtentAbs);
7124 if (RT_FAILURE(rc))
7125 goto out;
7126 /* Clip write range to at most the rest of the grain. */
7127 cbWrite = RT_MIN(cbWrite, VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain - uSectorExtentRel % pExtent->cSectorsPerGrain));
7128 if ( pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED
7129 && uSectorExtentRel < (uint64_t)pExtent->uLastGrainAccess * pExtent->cSectorsPerGrain)
7130 {
7131 rc = VERR_VD_VMDK_INVALID_WRITE;
7132 goto out;
7133 }
7134 if (uSectorExtentAbs == 0)
7135 {
7136 if (cbWrite == VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain))
7137 {
7138 /* Full block write to a previously unallocated block.
7139 * Check if the caller wants to avoid the automatic alloc. */
7140 if (!(fWrite & VD_WRITE_NO_ALLOC))
7141 {
7142 /* Allocate GT and find out where to store the grain. */
7143 rc = vmdkAllocGrainAsync(pImage, pExtent, pIoCtx,
7144 uSectorExtentRel, cbWrite);
7145 }
7146 else
7147 rc = VERR_VD_BLOCK_FREE;
7148 *pcbPreRead = 0;
7149 *pcbPostRead = 0;
7150 }
7151 else
7152 {
7153 /* Clip write range to remain in this extent. */
7154 cbWrite = RT_MIN(cbWrite, VMDK_SECTOR2BYTE(pExtent->uSectorOffset + pExtent->cNominalSectors - uSectorExtentRel));
7155 *pcbPreRead = VMDK_SECTOR2BYTE(uSectorExtentRel % pExtent->cSectorsPerGrain);
7156 *pcbPostRead = VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain) - cbWrite - *pcbPreRead;
7157 rc = VERR_VD_BLOCK_FREE;
7158 }
7159 }
7160 else
7161 {
7162 Assert(!(pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED));
7163 rc = vmdkFileWriteUserAsync(pImage, pExtent->pFile,
7164 VMDK_SECTOR2BYTE(uSectorExtentAbs),
7165 pIoCtx, cbWrite, NULL, NULL);
7166 }
7167 break;
7168 case VMDKETYPE_VMFS:
7169 case VMDKETYPE_FLAT:
7170 /* Clip write range to remain in this extent. */
7171 cbWrite = RT_MIN(cbWrite, VMDK_SECTOR2BYTE(pExtent->uSectorOffset + pExtent->cNominalSectors - uSectorExtentRel));
7172 rc = vmdkFileWriteUserAsync(pImage, pExtent->pFile,
7173 VMDK_SECTOR2BYTE(uSectorExtentRel),
7174 pIoCtx, cbWrite, NULL, NULL);
7175 break;
7176 case VMDKETYPE_ZERO:
7177 /* Clip write range to remain in this extent. */
7178 cbWrite = RT_MIN(cbWrite, VMDK_SECTOR2BYTE(pExtent->uSectorOffset + pExtent->cNominalSectors - uSectorExtentRel));
7179 break;
7180 }
7181
7182 if (pcbWriteProcess)
7183 *pcbWriteProcess = cbWrite;
7184
7185out:
7186 LogFlowFunc(("returns %Rrc\n", rc));
7187 return rc;
7188}
7189
7190/** @copydoc VBOXHDDBACKEND::pfnAsyncFlush */
7191static int vmdkAsyncFlush(void *pBackendData, PVDIOCTX pIoCtx)
7192{
7193 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
7194 PVMDKEXTENT pExtent;
7195 int rc = VINF_SUCCESS;
7196
7197 /* Update descriptor if changed. */
7198 /** @todo: The descriptor is never updated because
7199 * it remains unchanged during normal operation (only vmdkRename updates it).
7200 * So this part is actually not tested so far and requires testing as soon
7201 * as the descriptor might change during async I/O.
7202 */
7203 if (pImage->Descriptor.fDirty)
7204 {
7205 rc = vmdkWriteDescriptorAsync(pImage, pIoCtx);
7206 if ( RT_FAILURE(rc)
7207 && rc != VERR_VD_ASYNC_IO_IN_PROGRESS)
7208 goto out;
7209 }
7210
7211 for (unsigned i = 0; i < pImage->cExtents; i++)
7212 {
7213 pExtent = &pImage->pExtents[i];
7214 if (pExtent->pFile != NULL && pExtent->fMetaDirty)
7215 {
7216 switch (pExtent->enmType)
7217 {
7218 case VMDKETYPE_HOSTED_SPARSE:
7219#ifdef VBOX_WITH_VMDK_ESX
7220 case VMDKETYPE_ESX_SPARSE:
7221#endif /* VBOX_WITH_VMDK_ESX */
7222 rc = vmdkWriteMetaSparseExtentAsync(pImage, pExtent, 0, pIoCtx);
7223 if (RT_FAILURE(rc) && (rc != VERR_VD_ASYNC_IO_IN_PROGRESS))
7224 goto out;
7225 if (pExtent->fFooter)
7226 {
7227 uint64_t uFileOffset = pExtent->uAppendPosition;
7228 if (!uFileOffset)
7229 {
7230 rc = VERR_INTERNAL_ERROR;
7231 goto out;
7232 }
7233 uFileOffset = RT_ALIGN_64(uFileOffset, 512);
7234 rc = vmdkWriteMetaSparseExtent(pImage, pExtent, uFileOffset);
7235 if (RT_FAILURE(rc) && (rc != VERR_VD_ASYNC_IO_IN_PROGRESS))
7236 goto out;
7237 }
7238 break;
7239 case VMDKETYPE_VMFS:
7240 case VMDKETYPE_FLAT:
7241 /* Nothing to do. */
7242 break;
7243 case VMDKETYPE_ZERO:
7244 default:
7245 AssertMsgFailed(("extent with type %d marked as dirty\n",
7246 pExtent->enmType));
7247 break;
7248 }
7249 }
7250 switch (pExtent->enmType)
7251 {
7252 case VMDKETYPE_HOSTED_SPARSE:
7253#ifdef VBOX_WITH_VMDK_ESX
7254 case VMDKETYPE_ESX_SPARSE:
7255#endif /* VBOX_WITH_VMDK_ESX */
7256 case VMDKETYPE_VMFS:
7257 case VMDKETYPE_FLAT:
7258 /*
7259 * Don't ignore block devices like in the sync case
7260 * (they have an absolute path).
7261 * We might have unwritten data in the writeback cache and
7262 * the async I/O manager will handle these requests properly
7263 * even if the block device doesn't support these requests.
7264 */
7265 if ( pExtent->pFile != NULL
7266 && !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
7267 rc = vmdkFileFlushAsync(pImage, pExtent->pFile, pIoCtx);
7268 break;
7269 case VMDKETYPE_ZERO:
7270 /* No need to do anything for this extent. */
7271 break;
7272 default:
7273 AssertMsgFailed(("unknown extent type %d\n", pExtent->enmType));
7274 break;
7275 }
7276 }
7277
7278out:
7279 return rc;
7280}
7281
7282
7283VBOXHDDBACKEND g_VmdkBackend =
7284{
7285 /* pszBackendName */
7286 "VMDK",
7287 /* cbSize */
7288 sizeof(VBOXHDDBACKEND),
7289 /* uBackendCaps */
7290 VD_CAP_UUID | VD_CAP_CREATE_FIXED | VD_CAP_CREATE_DYNAMIC
7291 | VD_CAP_CREATE_SPLIT_2G | VD_CAP_DIFF | VD_CAP_FILE | VD_CAP_ASYNC
7292 | VD_CAP_VFS,
7293 /* paFileExtensions */
7294 s_aVmdkFileExtensions,
7295 /* paConfigInfo */
7296 NULL,
7297 /* hPlugin */
7298 NIL_RTLDRMOD,
7299 /* pfnCheckIfValid */
7300 vmdkCheckIfValid,
7301 /* pfnOpen */
7302 vmdkOpen,
7303 /* pfnCreate */
7304 vmdkCreate,
7305 /* pfnRename */
7306 vmdkRename,
7307 /* pfnClose */
7308 vmdkClose,
7309 /* pfnRead */
7310 vmdkRead,
7311 /* pfnWrite */
7312 vmdkWrite,
7313 /* pfnFlush */
7314 vmdkFlush,
7315 /* pfnGetVersion */
7316 vmdkGetVersion,
7317 /* pfnGetSize */
7318 vmdkGetSize,
7319 /* pfnGetFileSize */
7320 vmdkGetFileSize,
7321 /* pfnGetPCHSGeometry */
7322 vmdkGetPCHSGeometry,
7323 /* pfnSetPCHSGeometry */
7324 vmdkSetPCHSGeometry,
7325 /* pfnGetLCHSGeometry */
7326 vmdkGetLCHSGeometry,
7327 /* pfnSetLCHSGeometry */
7328 vmdkSetLCHSGeometry,
7329 /* pfnGetImageFlags */
7330 vmdkGetImageFlags,
7331 /* pfnGetOpenFlags */
7332 vmdkGetOpenFlags,
7333 /* pfnSetOpenFlags */
7334 vmdkSetOpenFlags,
7335 /* pfnGetComment */
7336 vmdkGetComment,
7337 /* pfnSetComment */
7338 vmdkSetComment,
7339 /* pfnGetUuid */
7340 vmdkGetUuid,
7341 /* pfnSetUuid */
7342 vmdkSetUuid,
7343 /* pfnGetModificationUuid */
7344 vmdkGetModificationUuid,
7345 /* pfnSetModificationUuid */
7346 vmdkSetModificationUuid,
7347 /* pfnGetParentUuid */
7348 vmdkGetParentUuid,
7349 /* pfnSetParentUuid */
7350 vmdkSetParentUuid,
7351 /* pfnGetParentModificationUuid */
7352 vmdkGetParentModificationUuid,
7353 /* pfnSetParentModificationUuid */
7354 vmdkSetParentModificationUuid,
7355 /* pfnDump */
7356 vmdkDump,
7357 /* pfnGetTimeStamp */
7358 NULL,
7359 /* pfnGetParentTimeStamp */
7360 NULL,
7361 /* pfnSetParentTimeStamp */
7362 NULL,
7363 /* pfnGetParentFilename */
7364 NULL,
7365 /* pfnSetParentFilename */
7366 NULL,
7367 /* pfnIsAsyncIOSupported */
7368 vmdkIsAsyncIOSupported,
7369 /* pfnAsyncRead */
7370 vmdkAsyncRead,
7371 /* pfnAsyncWrite */
7372 vmdkAsyncWrite,
7373 /* pfnAsyncFlush */
7374 vmdkAsyncFlush,
7375 /* pfnComposeLocation */
7376 genericFileComposeLocation,
7377 /* pfnComposeName */
7378 genericFileComposeName,
7379 /* pfnCompact */
7380 NULL,
7381 /* pfnResize */
7382 NULL
7383};
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