VirtualBox

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

Last change on this file since 28125 was 27977, checked in by vboxsync, 15 years ago

VBoxHDD: Async I/O for flat images are back

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

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