VirtualBox

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

Last change on this file since 19223 was 18966, checked in by vboxsync, 16 years ago

Storage/Vmdk: compiler warning fix

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

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