VirtualBox

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

Last change on this file since 27340 was 27232, checked in by vboxsync, 15 years ago

Storage/VBoxHDD+DrvVD: implement framework for providing thread synchronization. Additionally some cleanup to resolve a few minor long-standing todos.

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