VirtualBox

source: vbox/trunk/src/VBox/Devices/Storage/VmdkHDDCore.cpp@ 28684

最後變更 在這個檔案從28684是 28620,由 vboxsync 提交於 15 年 前

VBoxHDD: async I/O updates. Mostly complete except for bug fixes

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

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