VirtualBox

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

Last change on this file since 27486 was 27477, checked in by vboxsync, 15 years ago

VMDK: No need to update the line if cb is 0

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

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