VirtualBox

source: vbox/trunk/src/VBox/Storage/VMDK.cpp@ 45221

Last change on this file since 45221 was 44528, checked in by vboxsync, 12 years ago

header (C) fixes

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