VirtualBox

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

Last change on this file since 46876 was 46613, checked in by vboxsync, 12 years ago

Storage: Propagate errors when closing a file but free everything nevertheless (see @bugref{6791})

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 241.2 KB
Line 
1/* $Id: VMDK.cpp 46613 2013-06-18 10:27:13Z 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 int 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 *
2865 * @returns VBox status code.
2866 * @param pImage Pointer to the image instance data.
2867 * @param pExtent The extent to free.
2868 * @param fDelete Flag whether to delete the backing storage.
2869 */
2870static int vmdkFreeExtentData(PVMDKIMAGE pImage, PVMDKEXTENT pExtent,
2871 bool fDelete)
2872{
2873 int rc = VINF_SUCCESS;
2874
2875 vmdkFreeGrainDirectory(pExtent);
2876 if (pExtent->pDescData)
2877 {
2878 RTMemFree(pExtent->pDescData);
2879 pExtent->pDescData = NULL;
2880 }
2881 if (pExtent->pFile != NULL)
2882 {
2883 /* Do not delete raw extents, these have full and base names equal. */
2884 rc =vmdkFileClose(pImage, &pExtent->pFile,
2885 fDelete
2886 && pExtent->pszFullname
2887 && strcmp(pExtent->pszFullname, pExtent->pszBasename));
2888 }
2889 if (pExtent->pszBasename)
2890 {
2891 RTMemTmpFree((void *)pExtent->pszBasename);
2892 pExtent->pszBasename = NULL;
2893 }
2894 if (pExtent->pszFullname)
2895 {
2896 RTStrFree((char *)(void *)pExtent->pszFullname);
2897 pExtent->pszFullname = NULL;
2898 }
2899 vmdkFreeStreamBuffers(pExtent);
2900
2901 return rc;
2902}
2903
2904/**
2905 * Internal: allocate grain table cache if necessary for this image.
2906 */
2907static int vmdkAllocateGrainTableCache(PVMDKIMAGE pImage)
2908{
2909 PVMDKEXTENT pExtent;
2910
2911 /* Allocate grain table cache if any sparse extent is present. */
2912 for (unsigned i = 0; i < pImage->cExtents; i++)
2913 {
2914 pExtent = &pImage->pExtents[i];
2915 if ( pExtent->enmType == VMDKETYPE_HOSTED_SPARSE
2916#ifdef VBOX_WITH_VMDK_ESX
2917 || pExtent->enmType == VMDKETYPE_ESX_SPARSE
2918#endif /* VBOX_WITH_VMDK_ESX */
2919 )
2920 {
2921 /* Allocate grain table cache. */
2922 pImage->pGTCache = (PVMDKGTCACHE)RTMemAllocZ(sizeof(VMDKGTCACHE));
2923 if (!pImage->pGTCache)
2924 return VERR_NO_MEMORY;
2925 for (unsigned j = 0; j < VMDK_GT_CACHE_SIZE; j++)
2926 {
2927 PVMDKGTCACHEENTRY pGCE = &pImage->pGTCache->aGTCache[j];
2928 pGCE->uExtent = UINT32_MAX;
2929 }
2930 pImage->pGTCache->cEntries = VMDK_GT_CACHE_SIZE;
2931 break;
2932 }
2933 }
2934
2935 return VINF_SUCCESS;
2936}
2937
2938/**
2939 * Internal: allocate the given number of extents.
2940 */
2941static int vmdkCreateExtents(PVMDKIMAGE pImage, unsigned cExtents)
2942{
2943 int rc = VINF_SUCCESS;
2944 PVMDKEXTENT pExtents = (PVMDKEXTENT)RTMemAllocZ(cExtents * sizeof(VMDKEXTENT));
2945 if (pExtents)
2946 {
2947 for (unsigned i = 0; i < cExtents; i++)
2948 {
2949 pExtents[i].pFile = NULL;
2950 pExtents[i].pszBasename = NULL;
2951 pExtents[i].pszFullname = NULL;
2952 pExtents[i].pGD = NULL;
2953 pExtents[i].pRGD = NULL;
2954 pExtents[i].pDescData = NULL;
2955 pExtents[i].uVersion = 1;
2956 pExtents[i].uCompression = VMDK_COMPRESSION_NONE;
2957 pExtents[i].uExtent = i;
2958 pExtents[i].pImage = pImage;
2959 }
2960 pImage->pExtents = pExtents;
2961 pImage->cExtents = cExtents;
2962 }
2963 else
2964 rc = VERR_NO_MEMORY;
2965
2966 return rc;
2967}
2968
2969/**
2970 * Internal: Open an image, constructing all necessary data structures.
2971 */
2972static int vmdkOpenImage(PVMDKIMAGE pImage, unsigned uOpenFlags)
2973{
2974 int rc;
2975 uint32_t u32Magic;
2976 PVMDKFILE pFile;
2977 PVMDKEXTENT pExtent;
2978
2979 pImage->uOpenFlags = uOpenFlags;
2980
2981 pImage->pIfError = VDIfErrorGet(pImage->pVDIfsDisk);
2982 pImage->pIfIo = VDIfIoIntGet(pImage->pVDIfsImage);
2983 AssertPtrReturn(pImage->pIfIo, VERR_INVALID_PARAMETER);
2984
2985 /*
2986 * Open the image.
2987 * We don't have to check for asynchronous access because
2988 * we only support raw access and the opened file is a description
2989 * file were no data is stored.
2990 */
2991
2992 rc = vmdkFileOpen(pImage, &pFile, pImage->pszFilename,
2993 VDOpenFlagsToFileOpenFlags(uOpenFlags, false /* fCreate */));
2994 if (RT_FAILURE(rc))
2995 {
2996 /* Do NOT signal an appropriate error here, as the VD layer has the
2997 * choice of retrying the open if it failed. */
2998 goto out;
2999 }
3000 pImage->pFile = pFile;
3001
3002 /* Read magic (if present). */
3003 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pFile->pStorage, 0,
3004 &u32Magic, sizeof(u32Magic));
3005 if (RT_FAILURE(rc))
3006 {
3007 vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error reading the magic number in '%s'"), pImage->pszFilename);
3008 rc = VERR_VD_VMDK_INVALID_HEADER;
3009 goto out;
3010 }
3011
3012 /* Handle the file according to its magic number. */
3013 if (RT_LE2H_U32(u32Magic) == VMDK_SPARSE_MAGICNUMBER)
3014 {
3015 /* It's a hosted single-extent image. */
3016 rc = vmdkCreateExtents(pImage, 1);
3017 if (RT_FAILURE(rc))
3018 goto out;
3019 /* The opened file is passed to the extent. No separate descriptor
3020 * file, so no need to keep anything open for the image. */
3021 pExtent = &pImage->pExtents[0];
3022 pExtent->pFile = pFile;
3023 pImage->pFile = NULL;
3024 pExtent->pszFullname = RTPathAbsDup(pImage->pszFilename);
3025 if (!pExtent->pszFullname)
3026 {
3027 rc = VERR_NO_MEMORY;
3028 goto out;
3029 }
3030 rc = vmdkReadBinaryMetaExtent(pImage, pExtent, true /* fMagicAlreadyRead */);
3031 if (RT_FAILURE(rc))
3032 goto out;
3033
3034 /* As we're dealing with a monolithic image here, there must
3035 * be a descriptor embedded in the image file. */
3036 if (!pExtent->uDescriptorSector || !pExtent->cDescriptorSectors)
3037 {
3038 rc = vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: monolithic image without descriptor in '%s'"), pImage->pszFilename);
3039 goto out;
3040 }
3041 /* HACK: extend the descriptor if it is unusually small and it fits in
3042 * the unused space after the image header. Allows opening VMDK files
3043 * with extremely small descriptor in read/write mode. */
3044 if ( !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
3045 && pExtent->cDescriptorSectors < 3
3046 && (int64_t)pExtent->uSectorGD - pExtent->uDescriptorSector >= 4
3047 && (!pExtent->uSectorRGD || (int64_t)pExtent->uSectorRGD - pExtent->uDescriptorSector >= 4))
3048 {
3049 pExtent->cDescriptorSectors = 4;
3050 pExtent->fMetaDirty = true;
3051 }
3052 /* Read the descriptor from the extent. */
3053 pExtent->pDescData = (char *)RTMemAllocZ(VMDK_SECTOR2BYTE(pExtent->cDescriptorSectors));
3054 if (!pExtent->pDescData)
3055 {
3056 rc = VERR_NO_MEMORY;
3057 goto out;
3058 }
3059 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pExtent->pFile->pStorage,
3060 VMDK_SECTOR2BYTE(pExtent->uDescriptorSector),
3061 pExtent->pDescData,
3062 VMDK_SECTOR2BYTE(pExtent->cDescriptorSectors));
3063 AssertRC(rc);
3064 if (RT_FAILURE(rc))
3065 {
3066 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: read error for descriptor in '%s'"), pExtent->pszFullname);
3067 goto out;
3068 }
3069
3070 rc = vmdkParseDescriptor(pImage, pExtent->pDescData,
3071 VMDK_SECTOR2BYTE(pExtent->cDescriptorSectors));
3072 if (RT_FAILURE(rc))
3073 goto out;
3074
3075 if ( pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED
3076 && uOpenFlags & VD_OPEN_FLAGS_ASYNC_IO)
3077 {
3078 rc = VERR_NOT_SUPPORTED;
3079 goto out;
3080 }
3081
3082 rc = vmdkReadMetaExtent(pImage, pExtent);
3083 if (RT_FAILURE(rc))
3084 goto out;
3085
3086 /* Mark the extent as unclean if opened in read-write mode. */
3087 if ( !(uOpenFlags & VD_OPEN_FLAGS_READONLY)
3088 && !(pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED))
3089 {
3090 pExtent->fUncleanShutdown = true;
3091 pExtent->fMetaDirty = true;
3092 }
3093 }
3094 else
3095 {
3096 /* Allocate at least 10K, and make sure that there is 5K free space
3097 * in case new entries need to be added to the descriptor. Never
3098 * allocate more than 128K, because that's no valid descriptor file
3099 * and will result in the correct "truncated read" error handling. */
3100 uint64_t cbFileSize;
3101 rc = vdIfIoIntFileGetSize(pImage->pIfIo, pFile->pStorage, &cbFileSize);
3102 if (RT_FAILURE(rc))
3103 goto out;
3104
3105 /* If the descriptor file is shorter than 50 bytes it can't be valid. */
3106 if (cbFileSize < 50)
3107 {
3108 rc = vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: descriptor in '%s' is too short"), pImage->pszFilename);
3109 goto out;
3110 }
3111
3112 uint64_t cbSize = cbFileSize;
3113 if (cbSize % VMDK_SECTOR2BYTE(10))
3114 cbSize += VMDK_SECTOR2BYTE(20) - cbSize % VMDK_SECTOR2BYTE(10);
3115 else
3116 cbSize += VMDK_SECTOR2BYTE(10);
3117 cbSize = RT_MIN(cbSize, _128K);
3118 pImage->cbDescAlloc = RT_MAX(VMDK_SECTOR2BYTE(20), cbSize);
3119 pImage->pDescData = (char *)RTMemAllocZ(pImage->cbDescAlloc);
3120 if (!pImage->pDescData)
3121 {
3122 rc = VERR_NO_MEMORY;
3123 goto out;
3124 }
3125
3126 /* Don't reread the place where the magic would live in a sparse
3127 * image if it's a descriptor based one. */
3128 memcpy(pImage->pDescData, &u32Magic, sizeof(u32Magic));
3129 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pFile->pStorage, sizeof(u32Magic),
3130 pImage->pDescData + sizeof(u32Magic),
3131 RT_MIN(pImage->cbDescAlloc - sizeof(u32Magic),
3132 cbFileSize - sizeof(u32Magic)));
3133 if (RT_FAILURE(rc))
3134 {
3135 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: read error for descriptor in '%s'"), pImage->pszFilename);
3136 goto out;
3137 }
3138
3139#if 0 /** @todo: Revisit */
3140 cbRead += sizeof(u32Magic);
3141 if (cbRead == pImage->cbDescAlloc)
3142 {
3143 /* Likely the read is truncated. Better fail a bit too early
3144 * (normally the descriptor is much smaller than our buffer). */
3145 rc = vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: cannot read descriptor in '%s'"), pImage->pszFilename);
3146 goto out;
3147 }
3148#endif
3149
3150 rc = vmdkParseDescriptor(pImage, pImage->pDescData,
3151 pImage->cbDescAlloc);
3152 if (RT_FAILURE(rc))
3153 goto out;
3154
3155 /*
3156 * We have to check for the asynchronous open flag. The
3157 * extents are parsed and the type of all are known now.
3158 * Check if every extent is either FLAT or ZERO.
3159 */
3160 if (uOpenFlags & VD_OPEN_FLAGS_ASYNC_IO)
3161 {
3162 unsigned cFlatExtents = 0;
3163
3164 for (unsigned i = 0; i < pImage->cExtents; i++)
3165 {
3166 pExtent = &pImage->pExtents[i];
3167
3168 if (( pExtent->enmType != VMDKETYPE_FLAT
3169 && pExtent->enmType != VMDKETYPE_ZERO
3170 && pExtent->enmType != VMDKETYPE_VMFS)
3171 || ((pImage->pExtents[i].enmType == VMDKETYPE_FLAT) && (cFlatExtents > 0)))
3172 {
3173 /*
3174 * Opened image contains at least one none flat or zero extent.
3175 * Return error but don't set error message as the caller
3176 * has the chance to open in non async I/O mode.
3177 */
3178 rc = VERR_NOT_SUPPORTED;
3179 goto out;
3180 }
3181 if (pExtent->enmType == VMDKETYPE_FLAT)
3182 cFlatExtents++;
3183 }
3184 }
3185
3186 for (unsigned i = 0; i < pImage->cExtents; i++)
3187 {
3188 pExtent = &pImage->pExtents[i];
3189
3190 if (pExtent->pszBasename)
3191 {
3192 /* Hack to figure out whether the specified name in the
3193 * extent descriptor is absolute. Doesn't always work, but
3194 * should be good enough for now. */
3195 char *pszFullname;
3196 /** @todo implement proper path absolute check. */
3197 if (pExtent->pszBasename[0] == RTPATH_SLASH)
3198 {
3199 pszFullname = RTStrDup(pExtent->pszBasename);
3200 if (!pszFullname)
3201 {
3202 rc = VERR_NO_MEMORY;
3203 goto out;
3204 }
3205 }
3206 else
3207 {
3208 char *pszDirname = RTStrDup(pImage->pszFilename);
3209 if (!pszDirname)
3210 {
3211 rc = VERR_NO_MEMORY;
3212 goto out;
3213 }
3214 RTPathStripFilename(pszDirname);
3215 pszFullname = RTPathJoinA(pszDirname, pExtent->pszBasename);
3216 RTStrFree(pszDirname);
3217 if (!pszFullname)
3218 {
3219 rc = VERR_NO_STR_MEMORY;
3220 goto out;
3221 }
3222 }
3223 pExtent->pszFullname = pszFullname;
3224 }
3225 else
3226 pExtent->pszFullname = NULL;
3227
3228 switch (pExtent->enmType)
3229 {
3230 case VMDKETYPE_HOSTED_SPARSE:
3231 rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszFullname,
3232 VDOpenFlagsToFileOpenFlags(uOpenFlags,
3233 false /* fCreate */));
3234 if (RT_FAILURE(rc))
3235 {
3236 /* Do NOT signal an appropriate error here, as the VD
3237 * layer has the choice of retrying the open if it
3238 * failed. */
3239 goto out;
3240 }
3241 rc = vmdkReadBinaryMetaExtent(pImage, pExtent,
3242 false /* fMagicAlreadyRead */);
3243 if (RT_FAILURE(rc))
3244 goto out;
3245 rc = vmdkReadMetaExtent(pImage, pExtent);
3246 if (RT_FAILURE(rc))
3247 goto out;
3248
3249 /* Mark extent as unclean if opened in read-write mode. */
3250 if (!(uOpenFlags & VD_OPEN_FLAGS_READONLY))
3251 {
3252 pExtent->fUncleanShutdown = true;
3253 pExtent->fMetaDirty = true;
3254 }
3255 break;
3256 case VMDKETYPE_VMFS:
3257 case VMDKETYPE_FLAT:
3258 rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszFullname,
3259 VDOpenFlagsToFileOpenFlags(uOpenFlags,
3260 false /* fCreate */));
3261 if (RT_FAILURE(rc))
3262 {
3263 /* Do NOT signal an appropriate error here, as the VD
3264 * layer has the choice of retrying the open if it
3265 * failed. */
3266 goto out;
3267 }
3268 break;
3269 case VMDKETYPE_ZERO:
3270 /* Nothing to do. */
3271 break;
3272 default:
3273 AssertMsgFailed(("unknown vmdk extent type %d\n", pExtent->enmType));
3274 }
3275 }
3276 }
3277
3278 /* Make sure this is not reached accidentally with an error status. */
3279 AssertRC(rc);
3280
3281 /* Determine PCHS geometry if not set. */
3282 if (pImage->PCHSGeometry.cCylinders == 0)
3283 {
3284 uint64_t cCylinders = VMDK_BYTE2SECTOR(pImage->cbSize)
3285 / pImage->PCHSGeometry.cHeads
3286 / pImage->PCHSGeometry.cSectors;
3287 pImage->PCHSGeometry.cCylinders = (unsigned)RT_MIN(cCylinders, 16383);
3288 if ( !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
3289 && !(pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED))
3290 {
3291 rc = vmdkDescSetPCHSGeometry(pImage, &pImage->PCHSGeometry);
3292 AssertRC(rc);
3293 }
3294 }
3295
3296 /* Update the image metadata now in case has changed. */
3297 rc = vmdkFlushImage(pImage, NULL);
3298 if (RT_FAILURE(rc))
3299 goto out;
3300
3301 /* Figure out a few per-image constants from the extents. */
3302 pImage->cbSize = 0;
3303 for (unsigned i = 0; i < pImage->cExtents; i++)
3304 {
3305 pExtent = &pImage->pExtents[i];
3306 if ( pExtent->enmType == VMDKETYPE_HOSTED_SPARSE
3307#ifdef VBOX_WITH_VMDK_ESX
3308 || pExtent->enmType == VMDKETYPE_ESX_SPARSE
3309#endif /* VBOX_WITH_VMDK_ESX */
3310 )
3311 {
3312 /* Here used to be a check whether the nominal size of an extent
3313 * is a multiple of the grain size. The spec says that this is
3314 * always the case, but unfortunately some files out there in the
3315 * wild violate the spec (e.g. ReactOS 0.3.1). */
3316 }
3317 pImage->cbSize += VMDK_SECTOR2BYTE(pExtent->cNominalSectors);
3318 }
3319
3320 for (unsigned i = 0; i < pImage->cExtents; i++)
3321 {
3322 pExtent = &pImage->pExtents[i];
3323 if ( pImage->pExtents[i].enmType == VMDKETYPE_FLAT
3324 || pImage->pExtents[i].enmType == VMDKETYPE_ZERO)
3325 {
3326 pImage->uImageFlags |= VD_IMAGE_FLAGS_FIXED;
3327 break;
3328 }
3329 }
3330
3331 if ( !(pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
3332 || !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
3333 || !(pImage->uOpenFlags & VD_OPEN_FLAGS_SEQUENTIAL))
3334 rc = vmdkAllocateGrainTableCache(pImage);
3335
3336out:
3337 if (RT_FAILURE(rc))
3338 vmdkFreeImage(pImage, false);
3339 return rc;
3340}
3341
3342/**
3343 * Internal: create VMDK images for raw disk/partition access.
3344 */
3345static int vmdkCreateRawImage(PVMDKIMAGE pImage, const PVBOXHDDRAW pRaw,
3346 uint64_t cbSize)
3347{
3348 int rc = VINF_SUCCESS;
3349 PVMDKEXTENT pExtent;
3350
3351 if (pRaw->fRawDisk)
3352 {
3353 /* Full raw disk access. This requires setting up a descriptor
3354 * file and open the (flat) raw disk. */
3355 rc = vmdkCreateExtents(pImage, 1);
3356 if (RT_FAILURE(rc))
3357 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not create new extent list in '%s'"), pImage->pszFilename);
3358 pExtent = &pImage->pExtents[0];
3359 /* Create raw disk descriptor file. */
3360 rc = vmdkFileOpen(pImage, &pImage->pFile, pImage->pszFilename,
3361 VDOpenFlagsToFileOpenFlags(pImage->uOpenFlags,
3362 true /* fCreate */));
3363 if (RT_FAILURE(rc))
3364 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not create new file '%s'"), pImage->pszFilename);
3365
3366 /* Set up basename for extent description. Cannot use StrDup. */
3367 size_t cbBasename = strlen(pRaw->pszRawDisk) + 1;
3368 char *pszBasename = (char *)RTMemTmpAlloc(cbBasename);
3369 if (!pszBasename)
3370 return VERR_NO_MEMORY;
3371 memcpy(pszBasename, pRaw->pszRawDisk, cbBasename);
3372 pExtent->pszBasename = pszBasename;
3373 /* For raw disks the full name is identical to the base name. */
3374 pExtent->pszFullname = RTStrDup(pszBasename);
3375 if (!pExtent->pszFullname)
3376 return VERR_NO_MEMORY;
3377 pExtent->enmType = VMDKETYPE_FLAT;
3378 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(cbSize);
3379 pExtent->uSectorOffset = 0;
3380 pExtent->enmAccess = VMDKACCESS_READWRITE;
3381 pExtent->fMetaDirty = false;
3382
3383 /* Open flat image, the raw disk. */
3384 rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszFullname,
3385 VDOpenFlagsToFileOpenFlags(pImage->uOpenFlags & ~VD_OPEN_FLAGS_READONLY,
3386 false /* fCreate */));
3387 if (RT_FAILURE(rc))
3388 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not open raw disk file '%s'"), pExtent->pszFullname);
3389 }
3390 else
3391 {
3392 /* Raw partition access. This requires setting up a descriptor
3393 * file, write the partition information to a flat extent and
3394 * open all the (flat) raw disk partitions. */
3395
3396 /* First pass over the partition data areas to determine how many
3397 * extents we need. One data area can require up to 2 extents, as
3398 * it might be necessary to skip over unpartitioned space. */
3399 unsigned cExtents = 0;
3400 uint64_t uStart = 0;
3401 for (unsigned i = 0; i < pRaw->cPartDescs; i++)
3402 {
3403 PVBOXHDDRAWPARTDESC pPart = &pRaw->pPartDescs[i];
3404 if (uStart > pPart->uStart)
3405 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);
3406
3407 if (uStart < pPart->uStart)
3408 cExtents++;
3409 uStart = pPart->uStart + pPart->cbData;
3410 cExtents++;
3411 }
3412 /* Another extent for filling up the rest of the image. */
3413 if (uStart != cbSize)
3414 cExtents++;
3415
3416 rc = vmdkCreateExtents(pImage, cExtents);
3417 if (RT_FAILURE(rc))
3418 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not create new extent list in '%s'"), pImage->pszFilename);
3419
3420 /* Create raw partition descriptor file. */
3421 rc = vmdkFileOpen(pImage, &pImage->pFile, pImage->pszFilename,
3422 VDOpenFlagsToFileOpenFlags(pImage->uOpenFlags,
3423 true /* fCreate */));
3424 if (RT_FAILURE(rc))
3425 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not create new file '%s'"), pImage->pszFilename);
3426
3427 /* Create base filename for the partition table extent. */
3428 /** @todo remove fixed buffer without creating memory leaks. */
3429 char pszPartition[1024];
3430 const char *pszBase = RTPathFilename(pImage->pszFilename);
3431 const char *pszExt = RTPathExt(pszBase);
3432 if (pszExt == NULL)
3433 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: invalid filename '%s'"), pImage->pszFilename);
3434 char *pszBaseBase = RTStrDup(pszBase);
3435 if (!pszBaseBase)
3436 return VERR_NO_MEMORY;
3437 RTPathStripExt(pszBaseBase);
3438 RTStrPrintf(pszPartition, sizeof(pszPartition), "%s-pt%s",
3439 pszBaseBase, pszExt);
3440 RTStrFree(pszBaseBase);
3441
3442 /* Second pass over the partitions, now define all extents. */
3443 uint64_t uPartOffset = 0;
3444 cExtents = 0;
3445 uStart = 0;
3446 for (unsigned i = 0; i < pRaw->cPartDescs; i++)
3447 {
3448 PVBOXHDDRAWPARTDESC pPart = &pRaw->pPartDescs[i];
3449 pExtent = &pImage->pExtents[cExtents++];
3450
3451 if (uStart < pPart->uStart)
3452 {
3453 pExtent->pszBasename = NULL;
3454 pExtent->pszFullname = NULL;
3455 pExtent->enmType = VMDKETYPE_ZERO;
3456 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(pPart->uStart - uStart);
3457 pExtent->uSectorOffset = 0;
3458 pExtent->enmAccess = VMDKACCESS_READWRITE;
3459 pExtent->fMetaDirty = false;
3460 /* go to next extent */
3461 pExtent = &pImage->pExtents[cExtents++];
3462 }
3463 uStart = pPart->uStart + pPart->cbData;
3464
3465 if (pPart->pvPartitionData)
3466 {
3467 /* Set up basename for extent description. Can't use StrDup. */
3468 size_t cbBasename = strlen(pszPartition) + 1;
3469 char *pszBasename = (char *)RTMemTmpAlloc(cbBasename);
3470 if (!pszBasename)
3471 return VERR_NO_MEMORY;
3472 memcpy(pszBasename, pszPartition, cbBasename);
3473 pExtent->pszBasename = pszBasename;
3474
3475 /* Set up full name for partition extent. */
3476 char *pszDirname = RTStrDup(pImage->pszFilename);
3477 if (!pszDirname)
3478 return VERR_NO_STR_MEMORY;
3479 RTPathStripFilename(pszDirname);
3480 char *pszFullname = RTPathJoinA(pszDirname, pExtent->pszBasename);
3481 RTStrFree(pszDirname);
3482 if (!pszDirname)
3483 return VERR_NO_STR_MEMORY;
3484 pExtent->pszFullname = pszFullname;
3485 pExtent->enmType = VMDKETYPE_FLAT;
3486 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(pPart->cbData);
3487 pExtent->uSectorOffset = uPartOffset;
3488 pExtent->enmAccess = VMDKACCESS_READWRITE;
3489 pExtent->fMetaDirty = false;
3490
3491 /* Create partition table flat image. */
3492 rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszFullname,
3493 VDOpenFlagsToFileOpenFlags(pImage->uOpenFlags,
3494 true /* fCreate */));
3495 if (RT_FAILURE(rc))
3496 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not create new partition data file '%s'"), pExtent->pszFullname);
3497 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pExtent->pFile->pStorage,
3498 VMDK_SECTOR2BYTE(uPartOffset),
3499 pPart->pvPartitionData,
3500 pPart->cbData);
3501 if (RT_FAILURE(rc))
3502 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not write partition data to '%s'"), pExtent->pszFullname);
3503 uPartOffset += VMDK_BYTE2SECTOR(pPart->cbData);
3504 }
3505 else
3506 {
3507 if (pPart->pszRawDevice)
3508 {
3509 /* Set up basename for extent descr. Can't use StrDup. */
3510 size_t cbBasename = strlen(pPart->pszRawDevice) + 1;
3511 char *pszBasename = (char *)RTMemTmpAlloc(cbBasename);
3512 if (!pszBasename)
3513 return VERR_NO_MEMORY;
3514 memcpy(pszBasename, pPart->pszRawDevice, cbBasename);
3515 pExtent->pszBasename = pszBasename;
3516 /* For raw disks full name is identical to base name. */
3517 pExtent->pszFullname = RTStrDup(pszBasename);
3518 if (!pExtent->pszFullname)
3519 return VERR_NO_MEMORY;
3520 pExtent->enmType = VMDKETYPE_FLAT;
3521 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(pPart->cbData);
3522 pExtent->uSectorOffset = VMDK_BYTE2SECTOR(pPart->uStartOffset);
3523 pExtent->enmAccess = VMDKACCESS_READWRITE;
3524 pExtent->fMetaDirty = false;
3525
3526 /* Open flat image, the raw partition. */
3527 rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszFullname,
3528 VDOpenFlagsToFileOpenFlags(pImage->uOpenFlags & ~VD_OPEN_FLAGS_READONLY,
3529 false /* fCreate */));
3530 if (RT_FAILURE(rc))
3531 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not open raw partition file '%s'"), pExtent->pszFullname);
3532 }
3533 else
3534 {
3535 pExtent->pszBasename = NULL;
3536 pExtent->pszFullname = NULL;
3537 pExtent->enmType = VMDKETYPE_ZERO;
3538 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(pPart->cbData);
3539 pExtent->uSectorOffset = 0;
3540 pExtent->enmAccess = VMDKACCESS_READWRITE;
3541 pExtent->fMetaDirty = false;
3542 }
3543 }
3544 }
3545 /* Another extent for filling up the rest of the image. */
3546 if (uStart != cbSize)
3547 {
3548 pExtent = &pImage->pExtents[cExtents++];
3549 pExtent->pszBasename = NULL;
3550 pExtent->pszFullname = NULL;
3551 pExtent->enmType = VMDKETYPE_ZERO;
3552 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(cbSize - uStart);
3553 pExtent->uSectorOffset = 0;
3554 pExtent->enmAccess = VMDKACCESS_READWRITE;
3555 pExtent->fMetaDirty = false;
3556 }
3557 }
3558
3559 rc = vmdkDescBaseSetStr(pImage, &pImage->Descriptor, "createType",
3560 pRaw->fRawDisk ?
3561 "fullDevice" : "partitionedDevice");
3562 if (RT_FAILURE(rc))
3563 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not set the image type in '%s'"), pImage->pszFilename);
3564 return rc;
3565}
3566
3567/**
3568 * Internal: create a regular (i.e. file-backed) VMDK image.
3569 */
3570static int vmdkCreateRegularImage(PVMDKIMAGE pImage, uint64_t cbSize,
3571 unsigned uImageFlags,
3572 PFNVDPROGRESS pfnProgress, void *pvUser,
3573 unsigned uPercentStart, unsigned uPercentSpan)
3574{
3575 int rc = VINF_SUCCESS;
3576 unsigned cExtents = 1;
3577 uint64_t cbOffset = 0;
3578 uint64_t cbRemaining = cbSize;
3579
3580 if (uImageFlags & VD_VMDK_IMAGE_FLAGS_SPLIT_2G)
3581 {
3582 cExtents = cbSize / VMDK_2G_SPLIT_SIZE;
3583 /* Do proper extent computation: need one smaller extent if the total
3584 * size isn't evenly divisible by the split size. */
3585 if (cbSize % VMDK_2G_SPLIT_SIZE)
3586 cExtents++;
3587 }
3588 rc = vmdkCreateExtents(pImage, cExtents);
3589 if (RT_FAILURE(rc))
3590 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not create new extent list in '%s'"), pImage->pszFilename);
3591
3592 /* Basename strings needed for constructing the extent names. */
3593 char *pszBasenameSubstr = RTPathFilename(pImage->pszFilename);
3594 AssertPtr(pszBasenameSubstr);
3595 size_t cbBasenameSubstr = strlen(pszBasenameSubstr) + 1;
3596
3597 /* Create separate descriptor file if necessary. */
3598 if (cExtents != 1 || (uImageFlags & VD_IMAGE_FLAGS_FIXED))
3599 {
3600 rc = vmdkFileOpen(pImage, &pImage->pFile, pImage->pszFilename,
3601 VDOpenFlagsToFileOpenFlags(pImage->uOpenFlags,
3602 true /* fCreate */));
3603 if (RT_FAILURE(rc))
3604 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not create new sparse descriptor file '%s'"), pImage->pszFilename);
3605 }
3606 else
3607 pImage->pFile = NULL;
3608
3609 /* Set up all extents. */
3610 for (unsigned i = 0; i < cExtents; i++)
3611 {
3612 PVMDKEXTENT pExtent = &pImage->pExtents[i];
3613 uint64_t cbExtent = cbRemaining;
3614
3615 /* Set up fullname/basename for extent description. Cannot use StrDup
3616 * for basename, as it is not guaranteed that the memory can be freed
3617 * with RTMemTmpFree, which must be used as in other code paths
3618 * StrDup is not usable. */
3619 if (cExtents == 1 && !(uImageFlags & VD_IMAGE_FLAGS_FIXED))
3620 {
3621 char *pszBasename = (char *)RTMemTmpAlloc(cbBasenameSubstr);
3622 if (!pszBasename)
3623 return VERR_NO_MEMORY;
3624 memcpy(pszBasename, pszBasenameSubstr, cbBasenameSubstr);
3625 pExtent->pszBasename = pszBasename;
3626 }
3627 else
3628 {
3629 char *pszBasenameExt = RTPathExt(pszBasenameSubstr);
3630 char *pszBasenameBase = RTStrDup(pszBasenameSubstr);
3631 RTPathStripExt(pszBasenameBase);
3632 char *pszTmp;
3633 size_t cbTmp;
3634 if (uImageFlags & VD_IMAGE_FLAGS_FIXED)
3635 {
3636 if (cExtents == 1)
3637 RTStrAPrintf(&pszTmp, "%s-flat%s", pszBasenameBase,
3638 pszBasenameExt);
3639 else
3640 RTStrAPrintf(&pszTmp, "%s-f%03d%s", pszBasenameBase,
3641 i+1, pszBasenameExt);
3642 }
3643 else
3644 RTStrAPrintf(&pszTmp, "%s-s%03d%s", pszBasenameBase, i+1,
3645 pszBasenameExt);
3646 RTStrFree(pszBasenameBase);
3647 if (!pszTmp)
3648 return VERR_NO_STR_MEMORY;
3649 cbTmp = strlen(pszTmp) + 1;
3650 char *pszBasename = (char *)RTMemTmpAlloc(cbTmp);
3651 if (!pszBasename)
3652 return VERR_NO_MEMORY;
3653 memcpy(pszBasename, pszTmp, cbTmp);
3654 RTStrFree(pszTmp);
3655 pExtent->pszBasename = pszBasename;
3656 if (uImageFlags & VD_VMDK_IMAGE_FLAGS_SPLIT_2G)
3657 cbExtent = RT_MIN(cbRemaining, VMDK_2G_SPLIT_SIZE);
3658 }
3659 char *pszBasedirectory = RTStrDup(pImage->pszFilename);
3660 if (!pszBasedirectory)
3661 return VERR_NO_STR_MEMORY;
3662 RTPathStripFilename(pszBasedirectory);
3663 char *pszFullname = RTPathJoinA(pszBasedirectory, pExtent->pszBasename);
3664 RTStrFree(pszBasedirectory);
3665 if (!pszFullname)
3666 return VERR_NO_STR_MEMORY;
3667 pExtent->pszFullname = pszFullname;
3668
3669 /* Create file for extent. */
3670 rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszFullname,
3671 VDOpenFlagsToFileOpenFlags(pImage->uOpenFlags,
3672 true /* fCreate */));
3673 if (RT_FAILURE(rc))
3674 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not create new file '%s'"), pExtent->pszFullname);
3675 if (uImageFlags & VD_IMAGE_FLAGS_FIXED)
3676 {
3677 rc = vdIfIoIntFileSetSize(pImage->pIfIo, pExtent->pFile->pStorage, cbExtent);
3678 if (RT_FAILURE(rc))
3679 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not set size of new file '%s'"), pExtent->pszFullname);
3680
3681 /* Fill image with zeroes. We do this for every fixed-size image since on some systems
3682 * (for example Windows Vista), it takes ages to write a block near the end of a sparse
3683 * file and the guest could complain about an ATA timeout. */
3684
3685 /** @todo Starting with Linux 2.6.23, there is an fallocate() system call.
3686 * Currently supported file systems are ext4 and ocfs2. */
3687
3688 /* Allocate a temporary zero-filled buffer. Use a bigger block size to optimize writing */
3689 const size_t cbBuf = 128 * _1K;
3690 void *pvBuf = RTMemTmpAllocZ(cbBuf);
3691 if (!pvBuf)
3692 return VERR_NO_MEMORY;
3693
3694 uint64_t uOff = 0;
3695 /* Write data to all image blocks. */
3696 while (uOff < cbExtent)
3697 {
3698 unsigned cbChunk = (unsigned)RT_MIN(cbExtent, cbBuf);
3699
3700 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pExtent->pFile->pStorage,
3701 uOff, pvBuf, cbChunk);
3702 if (RT_FAILURE(rc))
3703 {
3704 RTMemFree(pvBuf);
3705 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: writing block failed for '%s'"), pImage->pszFilename);
3706 }
3707
3708 uOff += cbChunk;
3709
3710 if (pfnProgress)
3711 {
3712 rc = pfnProgress(pvUser,
3713 uPercentStart + (cbOffset + uOff) * uPercentSpan / cbSize);
3714 if (RT_FAILURE(rc))
3715 {
3716 RTMemFree(pvBuf);
3717 return rc;
3718 }
3719 }
3720 }
3721 RTMemTmpFree(pvBuf);
3722 }
3723
3724 /* Place descriptor file information (where integrated). */
3725 if (cExtents == 1 && !(uImageFlags & VD_IMAGE_FLAGS_FIXED))
3726 {
3727 pExtent->uDescriptorSector = 1;
3728 pExtent->cDescriptorSectors = VMDK_BYTE2SECTOR(pImage->cbDescAlloc);
3729 /* The descriptor is part of the (only) extent. */
3730 pExtent->pDescData = pImage->pDescData;
3731 pImage->pDescData = NULL;
3732 }
3733
3734 if (!(uImageFlags & VD_IMAGE_FLAGS_FIXED))
3735 {
3736 uint64_t cSectorsPerGDE, cSectorsPerGD;
3737 pExtent->enmType = VMDKETYPE_HOSTED_SPARSE;
3738 pExtent->cSectors = VMDK_BYTE2SECTOR(RT_ALIGN_64(cbExtent, _64K));
3739 pExtent->cSectorsPerGrain = VMDK_BYTE2SECTOR(_64K);
3740 pExtent->cGTEntries = 512;
3741 cSectorsPerGDE = pExtent->cGTEntries * pExtent->cSectorsPerGrain;
3742 pExtent->cSectorsPerGDE = cSectorsPerGDE;
3743 pExtent->cGDEntries = (pExtent->cSectors + cSectorsPerGDE - 1) / cSectorsPerGDE;
3744 cSectorsPerGD = (pExtent->cGDEntries + (512 / sizeof(uint32_t) - 1)) / (512 / sizeof(uint32_t));
3745 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
3746 {
3747 /* The spec says version is 1 for all VMDKs, but the vast
3748 * majority of streamOptimized VMDKs actually contain
3749 * version 3 - so go with the majority. Both are accepted. */
3750 pExtent->uVersion = 3;
3751 pExtent->uCompression = VMDK_COMPRESSION_DEFLATE;
3752 }
3753 }
3754 else
3755 {
3756 if (uImageFlags & VD_VMDK_IMAGE_FLAGS_ESX)
3757 pExtent->enmType = VMDKETYPE_VMFS;
3758 else
3759 pExtent->enmType = VMDKETYPE_FLAT;
3760 }
3761
3762 pExtent->enmAccess = VMDKACCESS_READWRITE;
3763 pExtent->fUncleanShutdown = true;
3764 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(cbExtent);
3765 pExtent->uSectorOffset = 0;
3766 pExtent->fMetaDirty = true;
3767
3768 if (!(uImageFlags & VD_IMAGE_FLAGS_FIXED))
3769 {
3770 /* fPreAlloc should never be false because VMware can't use such images. */
3771 rc = vmdkCreateGrainDirectory(pImage, pExtent,
3772 RT_MAX( pExtent->uDescriptorSector
3773 + pExtent->cDescriptorSectors,
3774 1),
3775 true /* fPreAlloc */);
3776 if (RT_FAILURE(rc))
3777 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not create new grain directory in '%s'"), pExtent->pszFullname);
3778 }
3779
3780 cbOffset += cbExtent;
3781
3782 if (RT_SUCCESS(rc) && pfnProgress)
3783 pfnProgress(pvUser, uPercentStart + cbOffset * uPercentSpan / cbSize);
3784
3785 cbRemaining -= cbExtent;
3786 }
3787
3788 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_ESX)
3789 {
3790 /* VirtualBox doesn't care, but VMWare ESX freaks out if the wrong
3791 * controller type is set in an image. */
3792 rc = vmdkDescDDBSetStr(pImage, &pImage->Descriptor, "ddb.adapterType", "lsilogic");
3793 if (RT_FAILURE(rc))
3794 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not set controller type to lsilogic in '%s'"), pImage->pszFilename);
3795 }
3796
3797 const char *pszDescType = NULL;
3798 if (uImageFlags & VD_IMAGE_FLAGS_FIXED)
3799 {
3800 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_ESX)
3801 pszDescType = "vmfs";
3802 else
3803 pszDescType = (cExtents == 1)
3804 ? "monolithicFlat" : "twoGbMaxExtentFlat";
3805 }
3806 else
3807 {
3808 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
3809 pszDescType = "streamOptimized";
3810 else
3811 {
3812 pszDescType = (cExtents == 1)
3813 ? "monolithicSparse" : "twoGbMaxExtentSparse";
3814 }
3815 }
3816 rc = vmdkDescBaseSetStr(pImage, &pImage->Descriptor, "createType",
3817 pszDescType);
3818 if (RT_FAILURE(rc))
3819 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not set the image type in '%s'"), pImage->pszFilename);
3820 return rc;
3821}
3822
3823/**
3824 * Internal: Create a real stream optimized VMDK using only linear writes.
3825 */
3826static int vmdkCreateStreamImage(PVMDKIMAGE pImage, uint64_t cbSize,
3827 unsigned uImageFlags,
3828 PFNVDPROGRESS pfnProgress, void *pvUser,
3829 unsigned uPercentStart, unsigned uPercentSpan)
3830{
3831 int rc;
3832
3833 rc = vmdkCreateExtents(pImage, 1);
3834 if (RT_FAILURE(rc))
3835 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not create new extent list in '%s'"), pImage->pszFilename);
3836
3837 /* Basename strings needed for constructing the extent names. */
3838 const char *pszBasenameSubstr = RTPathFilename(pImage->pszFilename);
3839 AssertPtr(pszBasenameSubstr);
3840 size_t cbBasenameSubstr = strlen(pszBasenameSubstr) + 1;
3841
3842 /* No separate descriptor file. */
3843 pImage->pFile = NULL;
3844
3845 /* Set up all extents. */
3846 PVMDKEXTENT pExtent = &pImage->pExtents[0];
3847
3848 /* Set up fullname/basename for extent description. Cannot use StrDup
3849 * for basename, as it is not guaranteed that the memory can be freed
3850 * with RTMemTmpFree, which must be used as in other code paths
3851 * StrDup is not usable. */
3852 char *pszBasename = (char *)RTMemTmpAlloc(cbBasenameSubstr);
3853 if (!pszBasename)
3854 return VERR_NO_MEMORY;
3855 memcpy(pszBasename, pszBasenameSubstr, cbBasenameSubstr);
3856 pExtent->pszBasename = pszBasename;
3857
3858 char *pszBasedirectory = RTStrDup(pImage->pszFilename);
3859 RTPathStripFilename(pszBasedirectory);
3860 char *pszFullname = RTPathJoinA(pszBasedirectory, pExtent->pszBasename);
3861 RTStrFree(pszBasedirectory);
3862 if (!pszFullname)
3863 return VERR_NO_STR_MEMORY;
3864 pExtent->pszFullname = pszFullname;
3865
3866 /* Create file for extent. Make it write only, no reading allowed. */
3867 rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszFullname,
3868 VDOpenFlagsToFileOpenFlags(pImage->uOpenFlags,
3869 true /* fCreate */)
3870 & ~RTFILE_O_READ);
3871 if (RT_FAILURE(rc))
3872 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not create new file '%s'"), pExtent->pszFullname);
3873
3874 /* Place descriptor file information. */
3875 pExtent->uDescriptorSector = 1;
3876 pExtent->cDescriptorSectors = VMDK_BYTE2SECTOR(pImage->cbDescAlloc);
3877 /* The descriptor is part of the (only) extent. */
3878 pExtent->pDescData = pImage->pDescData;
3879 pImage->pDescData = NULL;
3880
3881 uint64_t cSectorsPerGDE, cSectorsPerGD;
3882 pExtent->enmType = VMDKETYPE_HOSTED_SPARSE;
3883 pExtent->cSectors = VMDK_BYTE2SECTOR(RT_ALIGN_64(cbSize, _64K));
3884 pExtent->cSectorsPerGrain = VMDK_BYTE2SECTOR(_64K);
3885 pExtent->cGTEntries = 512;
3886 cSectorsPerGDE = pExtent->cGTEntries * pExtent->cSectorsPerGrain;
3887 pExtent->cSectorsPerGDE = cSectorsPerGDE;
3888 pExtent->cGDEntries = (pExtent->cSectors + cSectorsPerGDE - 1) / cSectorsPerGDE;
3889 cSectorsPerGD = (pExtent->cGDEntries + (512 / sizeof(uint32_t) - 1)) / (512 / sizeof(uint32_t));
3890
3891 /* The spec says version is 1 for all VMDKs, but the vast
3892 * majority of streamOptimized VMDKs actually contain
3893 * version 3 - so go with the majority. Both are accepted. */
3894 pExtent->uVersion = 3;
3895 pExtent->uCompression = VMDK_COMPRESSION_DEFLATE;
3896 pExtent->fFooter = true;
3897
3898 pExtent->enmAccess = VMDKACCESS_READONLY;
3899 pExtent->fUncleanShutdown = false;
3900 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(cbSize);
3901 pExtent->uSectorOffset = 0;
3902 pExtent->fMetaDirty = true;
3903
3904 /* Create grain directory, without preallocating it straight away. It will
3905 * be constructed on the fly when writing out the data and written when
3906 * closing the image. The end effect is that the full grain directory is
3907 * allocated, which is a requirement of the VMDK specs. */
3908 rc = vmdkCreateGrainDirectory(pImage, pExtent, VMDK_GD_AT_END,
3909 false /* fPreAlloc */);
3910 if (RT_FAILURE(rc))
3911 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not create new grain directory in '%s'"), pExtent->pszFullname);
3912
3913 rc = vmdkDescBaseSetStr(pImage, &pImage->Descriptor, "createType",
3914 "streamOptimized");
3915 if (RT_FAILURE(rc))
3916 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not set the image type in '%s'"), pImage->pszFilename);
3917
3918 return rc;
3919}
3920
3921/**
3922 * Internal: The actual code for creating any VMDK variant currently in
3923 * existence on hosted environments.
3924 */
3925static int vmdkCreateImage(PVMDKIMAGE pImage, uint64_t cbSize,
3926 unsigned uImageFlags, const char *pszComment,
3927 PCVDGEOMETRY pPCHSGeometry,
3928 PCVDGEOMETRY pLCHSGeometry, PCRTUUID pUuid,
3929 PFNVDPROGRESS pfnProgress, void *pvUser,
3930 unsigned uPercentStart, unsigned uPercentSpan)
3931{
3932 int rc;
3933
3934 pImage->uImageFlags = uImageFlags;
3935
3936 pImage->pIfError = VDIfErrorGet(pImage->pVDIfsDisk);
3937 pImage->pIfIo = VDIfIoIntGet(pImage->pVDIfsImage);
3938 AssertPtrReturn(pImage->pIfIo, VERR_INVALID_PARAMETER);
3939
3940 rc = vmdkCreateDescriptor(pImage, pImage->pDescData, pImage->cbDescAlloc,
3941 &pImage->Descriptor);
3942 if (RT_FAILURE(rc))
3943 {
3944 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not create new descriptor in '%s'"), pImage->pszFilename);
3945 goto out;
3946 }
3947
3948 if ( (uImageFlags & VD_IMAGE_FLAGS_FIXED)
3949 && (uImageFlags & VD_VMDK_IMAGE_FLAGS_RAWDISK))
3950 {
3951 /* Raw disk image (includes raw partition). */
3952 const PVBOXHDDRAW pRaw = (const PVBOXHDDRAW)pszComment;
3953 /* As the comment is misused, zap it so that no garbage comment
3954 * is set below. */
3955 pszComment = NULL;
3956 rc = vmdkCreateRawImage(pImage, pRaw, cbSize);
3957 }
3958 else
3959 {
3960 if (uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
3961 {
3962 /* Stream optimized sparse image (monolithic). */
3963 rc = vmdkCreateStreamImage(pImage, cbSize, uImageFlags,
3964 pfnProgress, pvUser, uPercentStart,
3965 uPercentSpan * 95 / 100);
3966 }
3967 else
3968 {
3969 /* Regular fixed or sparse image (monolithic or split). */
3970 rc = vmdkCreateRegularImage(pImage, cbSize, uImageFlags,
3971 pfnProgress, pvUser, uPercentStart,
3972 uPercentSpan * 95 / 100);
3973 }
3974 }
3975
3976 if (RT_FAILURE(rc))
3977 goto out;
3978
3979 if (RT_SUCCESS(rc) && pfnProgress)
3980 pfnProgress(pvUser, uPercentStart + uPercentSpan * 98 / 100);
3981
3982 pImage->cbSize = cbSize;
3983
3984 for (unsigned i = 0; i < pImage->cExtents; i++)
3985 {
3986 PVMDKEXTENT pExtent = &pImage->pExtents[i];
3987
3988 rc = vmdkDescExtInsert(pImage, &pImage->Descriptor, pExtent->enmAccess,
3989 pExtent->cNominalSectors, pExtent->enmType,
3990 pExtent->pszBasename, pExtent->uSectorOffset);
3991 if (RT_FAILURE(rc))
3992 {
3993 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not insert the extent list into descriptor in '%s'"), pImage->pszFilename);
3994 goto out;
3995 }
3996 }
3997 vmdkDescExtRemoveDummy(pImage, &pImage->Descriptor);
3998
3999 if ( pPCHSGeometry->cCylinders != 0
4000 && pPCHSGeometry->cHeads != 0
4001 && pPCHSGeometry->cSectors != 0)
4002 {
4003 rc = vmdkDescSetPCHSGeometry(pImage, pPCHSGeometry);
4004 if (RT_FAILURE(rc))
4005 goto out;
4006 }
4007 if ( pLCHSGeometry->cCylinders != 0
4008 && pLCHSGeometry->cHeads != 0
4009 && pLCHSGeometry->cSectors != 0)
4010 {
4011 rc = vmdkDescSetLCHSGeometry(pImage, pLCHSGeometry);
4012 if (RT_FAILURE(rc))
4013 goto out;
4014 }
4015
4016 pImage->LCHSGeometry = *pLCHSGeometry;
4017 pImage->PCHSGeometry = *pPCHSGeometry;
4018
4019 pImage->ImageUuid = *pUuid;
4020 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
4021 VMDK_DDB_IMAGE_UUID, &pImage->ImageUuid);
4022 if (RT_FAILURE(rc))
4023 {
4024 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error storing image UUID in new descriptor in '%s'"), pImage->pszFilename);
4025 goto out;
4026 }
4027 RTUuidClear(&pImage->ParentUuid);
4028 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
4029 VMDK_DDB_PARENT_UUID, &pImage->ParentUuid);
4030 if (RT_FAILURE(rc))
4031 {
4032 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error storing parent image UUID in new descriptor in '%s'"), pImage->pszFilename);
4033 goto out;
4034 }
4035 RTUuidClear(&pImage->ModificationUuid);
4036 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
4037 VMDK_DDB_MODIFICATION_UUID,
4038 &pImage->ModificationUuid);
4039 if (RT_FAILURE(rc))
4040 {
4041 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error storing modification UUID in new descriptor in '%s'"), pImage->pszFilename);
4042 goto out;
4043 }
4044 RTUuidClear(&pImage->ParentModificationUuid);
4045 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
4046 VMDK_DDB_PARENT_MODIFICATION_UUID,
4047 &pImage->ParentModificationUuid);
4048 if (RT_FAILURE(rc))
4049 {
4050 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error storing parent modification UUID in new descriptor in '%s'"), pImage->pszFilename);
4051 goto out;
4052 }
4053
4054 rc = vmdkAllocateGrainTableCache(pImage);
4055 if (RT_FAILURE(rc))
4056 goto out;
4057
4058 rc = vmdkSetImageComment(pImage, pszComment);
4059 if (RT_FAILURE(rc))
4060 {
4061 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: cannot set image comment in '%s'"), pImage->pszFilename);
4062 goto out;
4063 }
4064
4065 if (RT_SUCCESS(rc) && pfnProgress)
4066 pfnProgress(pvUser, uPercentStart + uPercentSpan * 99 / 100);
4067
4068 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
4069 {
4070 /* streamOptimized is a bit special, we cannot trigger the flush
4071 * until all data has been written. So we write the necessary
4072 * information explicitly. */
4073 pImage->pExtents[0].cDescriptorSectors = VMDK_BYTE2SECTOR(RT_ALIGN_64( pImage->Descriptor.aLines[pImage->Descriptor.cLines]
4074 - pImage->Descriptor.aLines[0], 512));
4075 rc = vmdkWriteMetaSparseExtent(pImage, &pImage->pExtents[0], 0, NULL);
4076 if (RT_FAILURE(rc))
4077 {
4078 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: cannot write VMDK header in '%s'"), pImage->pszFilename);
4079 goto out;
4080 }
4081
4082 rc = vmdkWriteDescriptor(pImage, NULL);
4083 if (RT_FAILURE(rc))
4084 {
4085 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: cannot write VMDK descriptor in '%s'"), pImage->pszFilename);
4086 goto out;
4087 }
4088 }
4089 else
4090 rc = vmdkFlushImage(pImage, NULL);
4091
4092out:
4093 if (RT_SUCCESS(rc) && pfnProgress)
4094 pfnProgress(pvUser, uPercentStart + uPercentSpan);
4095
4096 if (RT_FAILURE(rc))
4097 vmdkFreeImage(pImage, rc != VERR_ALREADY_EXISTS);
4098 return rc;
4099}
4100
4101/**
4102 * Internal: Update image comment.
4103 */
4104static int vmdkSetImageComment(PVMDKIMAGE pImage, const char *pszComment)
4105{
4106 char *pszCommentEncoded;
4107 if (pszComment)
4108 {
4109 pszCommentEncoded = vmdkEncodeString(pszComment);
4110 if (!pszCommentEncoded)
4111 return VERR_NO_MEMORY;
4112 }
4113 else
4114 pszCommentEncoded = NULL;
4115 int rc = vmdkDescDDBSetStr(pImage, &pImage->Descriptor,
4116 "ddb.comment", pszCommentEncoded);
4117 if (pszComment)
4118 RTStrFree(pszCommentEncoded);
4119 if (RT_FAILURE(rc))
4120 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error storing image comment in descriptor in '%s'"), pImage->pszFilename);
4121 return VINF_SUCCESS;
4122}
4123
4124/**
4125 * Internal. Clear the grain table buffer for real stream optimized writing.
4126 */
4127static void vmdkStreamClearGT(PVMDKIMAGE pImage, PVMDKEXTENT pExtent)
4128{
4129 uint32_t cCacheLines = RT_ALIGN(pExtent->cGTEntries, VMDK_GT_CACHELINE_SIZE) / VMDK_GT_CACHELINE_SIZE;
4130 for (uint32_t i = 0; i < cCacheLines; i++)
4131 memset(&pImage->pGTCache->aGTCache[i].aGTData[0], '\0',
4132 VMDK_GT_CACHELINE_SIZE * sizeof(uint32_t));
4133}
4134
4135/**
4136 * Internal. Flush the grain table buffer for real stream optimized writing.
4137 */
4138static int vmdkStreamFlushGT(PVMDKIMAGE pImage, PVMDKEXTENT pExtent,
4139 uint32_t uGDEntry)
4140{
4141 int rc = VINF_SUCCESS;
4142 uint32_t cCacheLines = RT_ALIGN(pExtent->cGTEntries, VMDK_GT_CACHELINE_SIZE) / VMDK_GT_CACHELINE_SIZE;
4143
4144 /* VMware does not write out completely empty grain tables in the case
4145 * of streamOptimized images, which according to my interpretation of
4146 * the VMDK 1.1 spec is bending the rules. Since they do it and we can
4147 * handle it without problems do it the same way and save some bytes. */
4148 bool fAllZero = true;
4149 for (uint32_t i = 0; i < cCacheLines; i++)
4150 {
4151 /* Convert the grain table to little endian in place, as it will not
4152 * be used at all after this function has been called. */
4153 uint32_t *pGTTmp = &pImage->pGTCache->aGTCache[i].aGTData[0];
4154 for (uint32_t j = 0; j < VMDK_GT_CACHELINE_SIZE; j++, pGTTmp++)
4155 if (*pGTTmp)
4156 {
4157 fAllZero = false;
4158 break;
4159 }
4160 if (!fAllZero)
4161 break;
4162 }
4163 if (fAllZero)
4164 return VINF_SUCCESS;
4165
4166 uint64_t uFileOffset = pExtent->uAppendPosition;
4167 if (!uFileOffset)
4168 return VERR_INTERNAL_ERROR;
4169 /* Align to sector, as the previous write could have been any size. */
4170 uFileOffset = RT_ALIGN_64(uFileOffset, 512);
4171
4172 /* Grain table marker. */
4173 uint8_t aMarker[512];
4174 PVMDKMARKER pMarker = (PVMDKMARKER)&aMarker[0];
4175 memset(pMarker, '\0', sizeof(aMarker));
4176 pMarker->uSector = RT_H2LE_U64(VMDK_BYTE2SECTOR((uint64_t)pExtent->cGTEntries * sizeof(uint32_t)));
4177 pMarker->uType = RT_H2LE_U32(VMDK_MARKER_GT);
4178 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pExtent->pFile->pStorage, uFileOffset,
4179 aMarker, sizeof(aMarker));
4180 AssertRC(rc);
4181 uFileOffset += 512;
4182
4183 if (!pExtent->pGD || pExtent->pGD[uGDEntry])
4184 return VERR_INTERNAL_ERROR;
4185
4186 pExtent->pGD[uGDEntry] = VMDK_BYTE2SECTOR(uFileOffset);
4187
4188 for (uint32_t i = 0; i < cCacheLines; i++)
4189 {
4190 /* Convert the grain table to little endian in place, as it will not
4191 * be used at all after this function has been called. */
4192 uint32_t *pGTTmp = &pImage->pGTCache->aGTCache[i].aGTData[0];
4193 for (uint32_t j = 0; j < VMDK_GT_CACHELINE_SIZE; j++, pGTTmp++)
4194 *pGTTmp = RT_H2LE_U32(*pGTTmp);
4195
4196 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pExtent->pFile->pStorage, uFileOffset,
4197 &pImage->pGTCache->aGTCache[i].aGTData[0],
4198 VMDK_GT_CACHELINE_SIZE * sizeof(uint32_t));
4199 uFileOffset += VMDK_GT_CACHELINE_SIZE * sizeof(uint32_t);
4200 if (RT_FAILURE(rc))
4201 break;
4202 }
4203 Assert(!(uFileOffset % 512));
4204 pExtent->uAppendPosition = RT_ALIGN_64(uFileOffset, 512);
4205 return rc;
4206}
4207
4208/**
4209 * Internal. Free all allocated space for representing an image, and optionally
4210 * delete the image from disk.
4211 */
4212static int vmdkFreeImage(PVMDKIMAGE pImage, bool fDelete)
4213{
4214 int rc = VINF_SUCCESS;
4215
4216 /* Freeing a never allocated image (e.g. because the open failed) is
4217 * not signalled as an error. After all nothing bad happens. */
4218 if (pImage)
4219 {
4220 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
4221 {
4222 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
4223 {
4224 /* Check if all extents are clean. */
4225 for (unsigned i = 0; i < pImage->cExtents; i++)
4226 {
4227 Assert(!pImage->pExtents[i].fUncleanShutdown);
4228 }
4229 }
4230 else
4231 {
4232 /* Mark all extents as clean. */
4233 for (unsigned i = 0; i < pImage->cExtents; i++)
4234 {
4235 if ( ( pImage->pExtents[i].enmType == VMDKETYPE_HOSTED_SPARSE
4236#ifdef VBOX_WITH_VMDK_ESX
4237 || pImage->pExtents[i].enmType == VMDKETYPE_ESX_SPARSE
4238#endif /* VBOX_WITH_VMDK_ESX */
4239 )
4240 && pImage->pExtents[i].fUncleanShutdown)
4241 {
4242 pImage->pExtents[i].fUncleanShutdown = false;
4243 pImage->pExtents[i].fMetaDirty = true;
4244 }
4245
4246 /* From now on it's not safe to append any more data. */
4247 pImage->pExtents[i].uAppendPosition = 0;
4248 }
4249 }
4250 }
4251
4252 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
4253 {
4254 /* No need to write any pending data if the file will be deleted
4255 * or if the new file wasn't successfully created. */
4256 if ( !fDelete && pImage->pExtents
4257 && pImage->pExtents[0].cGTEntries
4258 && pImage->pExtents[0].uAppendPosition)
4259 {
4260 PVMDKEXTENT pExtent = &pImage->pExtents[0];
4261 uint32_t uLastGDEntry = pExtent->uLastGrainAccess / pExtent->cGTEntries;
4262 rc = vmdkStreamFlushGT(pImage, pExtent, uLastGDEntry);
4263 AssertRC(rc);
4264 vmdkStreamClearGT(pImage, pExtent);
4265 for (uint32_t i = uLastGDEntry + 1; i < pExtent->cGDEntries; i++)
4266 {
4267 rc = vmdkStreamFlushGT(pImage, pExtent, i);
4268 AssertRC(rc);
4269 }
4270
4271 uint64_t uFileOffset = pExtent->uAppendPosition;
4272 if (!uFileOffset)
4273 return VERR_INTERNAL_ERROR;
4274 uFileOffset = RT_ALIGN_64(uFileOffset, 512);
4275
4276 /* From now on it's not safe to append any more data. */
4277 pExtent->uAppendPosition = 0;
4278
4279 /* Grain directory marker. */
4280 uint8_t aMarker[512];
4281 PVMDKMARKER pMarker = (PVMDKMARKER)&aMarker[0];
4282 memset(pMarker, '\0', sizeof(aMarker));
4283 pMarker->uSector = VMDK_BYTE2SECTOR(RT_ALIGN_64(RT_H2LE_U64((uint64_t)pExtent->cGDEntries * sizeof(uint32_t)), 512));
4284 pMarker->uType = RT_H2LE_U32(VMDK_MARKER_GD);
4285 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pExtent->pFile->pStorage, uFileOffset,
4286 aMarker, sizeof(aMarker));
4287 AssertRC(rc);
4288 uFileOffset += 512;
4289
4290 /* Write grain directory in little endian style. The array will
4291 * not be used after this, so convert in place. */
4292 uint32_t *pGDTmp = pExtent->pGD;
4293 for (uint32_t i = 0; i < pExtent->cGDEntries; i++, pGDTmp++)
4294 *pGDTmp = RT_H2LE_U32(*pGDTmp);
4295 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pExtent->pFile->pStorage,
4296 uFileOffset, pExtent->pGD,
4297 pExtent->cGDEntries * sizeof(uint32_t));
4298 AssertRC(rc);
4299
4300 pExtent->uSectorGD = VMDK_BYTE2SECTOR(uFileOffset);
4301 pExtent->uSectorRGD = VMDK_BYTE2SECTOR(uFileOffset);
4302 uFileOffset = RT_ALIGN_64( uFileOffset
4303 + pExtent->cGDEntries * sizeof(uint32_t),
4304 512);
4305
4306 /* Footer marker. */
4307 memset(pMarker, '\0', sizeof(aMarker));
4308 pMarker->uSector = VMDK_BYTE2SECTOR(512);
4309 pMarker->uType = RT_H2LE_U32(VMDK_MARKER_FOOTER);
4310 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pExtent->pFile->pStorage,
4311 uFileOffset, aMarker, sizeof(aMarker));
4312 AssertRC(rc);
4313
4314 uFileOffset += 512;
4315 rc = vmdkWriteMetaSparseExtent(pImage, pExtent, uFileOffset, NULL);
4316 AssertRC(rc);
4317
4318 uFileOffset += 512;
4319 /* End-of-stream marker. */
4320 memset(pMarker, '\0', sizeof(aMarker));
4321 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pExtent->pFile->pStorage,
4322 uFileOffset, aMarker, sizeof(aMarker));
4323 AssertRC(rc);
4324 }
4325 }
4326 else
4327 vmdkFlushImage(pImage, NULL);
4328
4329 if (pImage->pExtents != NULL)
4330 {
4331 for (unsigned i = 0 ; i < pImage->cExtents; i++)
4332 {
4333 int rc2 = vmdkFreeExtentData(pImage, &pImage->pExtents[i], fDelete);
4334 if (RT_SUCCESS(rc))
4335 rc = rc2; /* Propogate any error when closing the file. */
4336 }
4337 RTMemFree(pImage->pExtents);
4338 pImage->pExtents = NULL;
4339 }
4340 pImage->cExtents = 0;
4341 if (pImage->pFile != NULL)
4342 {
4343 int rc2 = vmdkFileClose(pImage, &pImage->pFile, fDelete);
4344 if (RT_SUCCESS(rc))
4345 rc = rc2; /* Propogate any error when closing the file. */
4346 }
4347 int rc2 = vmdkFileCheckAllClose(pImage);
4348 if (RT_SUCCESS(rc))
4349 rc = rc2; /* Propogate any error when closing the file. */
4350
4351 if (pImage->pGTCache)
4352 {
4353 RTMemFree(pImage->pGTCache);
4354 pImage->pGTCache = NULL;
4355 }
4356 if (pImage->pDescData)
4357 {
4358 RTMemFree(pImage->pDescData);
4359 pImage->pDescData = NULL;
4360 }
4361 }
4362
4363 LogFlowFunc(("returns %Rrc\n", rc));
4364 return rc;
4365}
4366
4367/**
4368 * Internal. Flush image data (and metadata) to disk.
4369 */
4370static int vmdkFlushImage(PVMDKIMAGE pImage, PVDIOCTX pIoCtx)
4371{
4372 PVMDKEXTENT pExtent;
4373 int rc = VINF_SUCCESS;
4374
4375 /* Update descriptor if changed. */
4376 if (pImage->Descriptor.fDirty)
4377 {
4378 rc = vmdkWriteDescriptor(pImage, pIoCtx);
4379 if (RT_FAILURE(rc))
4380 goto out;
4381 }
4382
4383 for (unsigned i = 0; i < pImage->cExtents; i++)
4384 {
4385 pExtent = &pImage->pExtents[i];
4386 if (pExtent->pFile != NULL && pExtent->fMetaDirty)
4387 {
4388 switch (pExtent->enmType)
4389 {
4390 case VMDKETYPE_HOSTED_SPARSE:
4391 if (!pExtent->fFooter)
4392 {
4393 rc = vmdkWriteMetaSparseExtent(pImage, pExtent, 0, pIoCtx);
4394 if (RT_FAILURE(rc))
4395 goto out;
4396 }
4397 else
4398 {
4399 uint64_t uFileOffset = pExtent->uAppendPosition;
4400 /* Simply skip writing anything if the streamOptimized
4401 * image hasn't been just created. */
4402 if (!uFileOffset)
4403 break;
4404 uFileOffset = RT_ALIGN_64(uFileOffset, 512);
4405 rc = vmdkWriteMetaSparseExtent(pImage, pExtent,
4406 uFileOffset, pIoCtx);
4407 if (RT_FAILURE(rc))
4408 goto out;
4409 }
4410 break;
4411#ifdef VBOX_WITH_VMDK_ESX
4412 case VMDKETYPE_ESX_SPARSE:
4413 /** @todo update the header. */
4414 break;
4415#endif /* VBOX_WITH_VMDK_ESX */
4416 case VMDKETYPE_VMFS:
4417 case VMDKETYPE_FLAT:
4418 /* Nothing to do. */
4419 break;
4420 case VMDKETYPE_ZERO:
4421 default:
4422 AssertMsgFailed(("extent with type %d marked as dirty\n",
4423 pExtent->enmType));
4424 break;
4425 }
4426 }
4427 switch (pExtent->enmType)
4428 {
4429 case VMDKETYPE_HOSTED_SPARSE:
4430#ifdef VBOX_WITH_VMDK_ESX
4431 case VMDKETYPE_ESX_SPARSE:
4432#endif /* VBOX_WITH_VMDK_ESX */
4433 case VMDKETYPE_VMFS:
4434 case VMDKETYPE_FLAT:
4435 /** @todo implement proper path absolute check. */
4436 if ( pExtent->pFile != NULL
4437 && !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
4438 && !(pExtent->pszBasename[0] == RTPATH_SLASH))
4439 rc = vdIfIoIntFileFlush(pImage->pIfIo, pExtent->pFile->pStorage, pIoCtx,
4440 NULL, NULL);
4441 break;
4442 case VMDKETYPE_ZERO:
4443 /* No need to do anything for this extent. */
4444 break;
4445 default:
4446 AssertMsgFailed(("unknown extent type %d\n", pExtent->enmType));
4447 break;
4448 }
4449 }
4450
4451out:
4452 return rc;
4453}
4454
4455/**
4456 * Internal. Find extent corresponding to the sector number in the disk.
4457 */
4458static int vmdkFindExtent(PVMDKIMAGE pImage, uint64_t offSector,
4459 PVMDKEXTENT *ppExtent, uint64_t *puSectorInExtent)
4460{
4461 PVMDKEXTENT pExtent = NULL;
4462 int rc = VINF_SUCCESS;
4463
4464 for (unsigned i = 0; i < pImage->cExtents; i++)
4465 {
4466 if (offSector < pImage->pExtents[i].cNominalSectors)
4467 {
4468 pExtent = &pImage->pExtents[i];
4469 *puSectorInExtent = offSector + pImage->pExtents[i].uSectorOffset;
4470 break;
4471 }
4472 offSector -= pImage->pExtents[i].cNominalSectors;
4473 }
4474
4475 if (pExtent)
4476 *ppExtent = pExtent;
4477 else
4478 rc = VERR_IO_SECTOR_NOT_FOUND;
4479
4480 return rc;
4481}
4482
4483/**
4484 * Internal. Hash function for placing the grain table hash entries.
4485 */
4486static uint32_t vmdkGTCacheHash(PVMDKGTCACHE pCache, uint64_t uSector,
4487 unsigned uExtent)
4488{
4489 /** @todo this hash function is quite simple, maybe use a better one which
4490 * scrambles the bits better. */
4491 return (uSector + uExtent) % pCache->cEntries;
4492}
4493
4494/**
4495 * Internal. Get sector number in the extent file from the relative sector
4496 * number in the extent.
4497 */
4498static int vmdkGetSector(PVMDKIMAGE pImage, PVDIOCTX pIoCtx,
4499 PVMDKEXTENT pExtent, uint64_t uSector,
4500 uint64_t *puExtentSector)
4501{
4502 PVMDKGTCACHE pCache = pImage->pGTCache;
4503 uint64_t uGDIndex, uGTSector, uGTBlock;
4504 uint32_t uGTHash, uGTBlockIndex;
4505 PVMDKGTCACHEENTRY pGTCacheEntry;
4506 uint32_t aGTDataTmp[VMDK_GT_CACHELINE_SIZE];
4507 int rc;
4508
4509 /* For newly created and readonly/sequentially opened streamOptimized
4510 * images this must be a no-op, as the grain directory is not there. */
4511 if ( ( pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED
4512 && pExtent->uAppendPosition)
4513 || ( pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED
4514 && pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY
4515 && pImage->uOpenFlags & VD_OPEN_FLAGS_SEQUENTIAL))
4516 {
4517 *puExtentSector = 0;
4518 return VINF_SUCCESS;
4519 }
4520
4521 uGDIndex = uSector / pExtent->cSectorsPerGDE;
4522 if (uGDIndex >= pExtent->cGDEntries)
4523 return VERR_OUT_OF_RANGE;
4524 uGTSector = pExtent->pGD[uGDIndex];
4525 if (!uGTSector)
4526 {
4527 /* There is no grain table referenced by this grain directory
4528 * entry. So there is absolutely no data in this area. */
4529 *puExtentSector = 0;
4530 return VINF_SUCCESS;
4531 }
4532
4533 uGTBlock = uSector / (pExtent->cSectorsPerGrain * VMDK_GT_CACHELINE_SIZE);
4534 uGTHash = vmdkGTCacheHash(pCache, uGTBlock, pExtent->uExtent);
4535 pGTCacheEntry = &pCache->aGTCache[uGTHash];
4536 if ( pGTCacheEntry->uExtent != pExtent->uExtent
4537 || pGTCacheEntry->uGTBlock != uGTBlock)
4538 {
4539 /* Cache miss, fetch data from disk. */
4540 PVDMETAXFER pMetaXfer;
4541 rc = vdIfIoIntFileReadMeta(pImage->pIfIo, pExtent->pFile->pStorage,
4542 VMDK_SECTOR2BYTE(uGTSector) + (uGTBlock % (pExtent->cGTEntries / VMDK_GT_CACHELINE_SIZE)) * sizeof(aGTDataTmp),
4543 aGTDataTmp, sizeof(aGTDataTmp), pIoCtx, &pMetaXfer, NULL, NULL);
4544 if (RT_FAILURE(rc))
4545 return rc;
4546 /* We can release the metadata transfer immediately. */
4547 vdIfIoIntMetaXferRelease(pImage->pIfIo, pMetaXfer);
4548 pGTCacheEntry->uExtent = pExtent->uExtent;
4549 pGTCacheEntry->uGTBlock = uGTBlock;
4550 for (unsigned i = 0; i < VMDK_GT_CACHELINE_SIZE; i++)
4551 pGTCacheEntry->aGTData[i] = RT_LE2H_U32(aGTDataTmp[i]);
4552 }
4553 uGTBlockIndex = (uSector / pExtent->cSectorsPerGrain) % VMDK_GT_CACHELINE_SIZE;
4554 uint32_t uGrainSector = pGTCacheEntry->aGTData[uGTBlockIndex];
4555 if (uGrainSector)
4556 *puExtentSector = uGrainSector + uSector % pExtent->cSectorsPerGrain;
4557 else
4558 *puExtentSector = 0;
4559 return VINF_SUCCESS;
4560}
4561
4562/**
4563 * Internal. Writes the grain and also if necessary the grain tables.
4564 * Uses the grain table cache as a true grain table.
4565 */
4566static int vmdkStreamAllocGrain(PVMDKIMAGE pImage, PVMDKEXTENT pExtent,
4567 uint64_t uSector, PVDIOCTX pIoCtx,
4568 uint64_t cbWrite)
4569{
4570 uint32_t uGrain;
4571 uint32_t uGDEntry, uLastGDEntry;
4572 uint32_t cbGrain = 0;
4573 uint32_t uCacheLine, uCacheEntry;
4574 const void *pData;
4575 int rc;
4576
4577 /* Very strict requirements: always write at least one full grain, with
4578 * proper alignment. Everything else would require reading of already
4579 * written data, which we don't support for obvious reasons. The only
4580 * exception is the last grain, and only if the image size specifies
4581 * that only some portion holds data. In any case the write must be
4582 * within the image limits, no "overshoot" allowed. */
4583 if ( cbWrite == 0
4584 || ( cbWrite < VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain)
4585 && pExtent->cNominalSectors - uSector >= pExtent->cSectorsPerGrain)
4586 || uSector % pExtent->cSectorsPerGrain
4587 || uSector + VMDK_BYTE2SECTOR(cbWrite) > pExtent->cNominalSectors)
4588 return VERR_INVALID_PARAMETER;
4589
4590 /* Clip write range to at most the rest of the grain. */
4591 cbWrite = RT_MIN(cbWrite, VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain - uSector % pExtent->cSectorsPerGrain));
4592
4593 /* Do not allow to go back. */
4594 uGrain = uSector / pExtent->cSectorsPerGrain;
4595 uCacheLine = uGrain % pExtent->cGTEntries / VMDK_GT_CACHELINE_SIZE;
4596 uCacheEntry = uGrain % VMDK_GT_CACHELINE_SIZE;
4597 uGDEntry = uGrain / pExtent->cGTEntries;
4598 uLastGDEntry = pExtent->uLastGrainAccess / pExtent->cGTEntries;
4599 if (uGrain < pExtent->uLastGrainAccess)
4600 return VERR_VD_VMDK_INVALID_WRITE;
4601
4602 /* Zero byte write optimization. Since we don't tell VBoxHDD that we need
4603 * to allocate something, we also need to detect the situation ourself. */
4604 if ( !(pImage->uOpenFlags & VD_OPEN_FLAGS_HONOR_ZEROES)
4605 && vdIfIoIntIoCtxIsZero(pImage->pIfIo, pIoCtx, cbWrite, true /* fAdvance */))
4606 return VINF_SUCCESS;
4607
4608 if (uGDEntry != uLastGDEntry)
4609 {
4610 rc = vmdkStreamFlushGT(pImage, pExtent, uLastGDEntry);
4611 if (RT_FAILURE(rc))
4612 return rc;
4613 vmdkStreamClearGT(pImage, pExtent);
4614 for (uint32_t i = uLastGDEntry + 1; i < uGDEntry; i++)
4615 {
4616 rc = vmdkStreamFlushGT(pImage, pExtent, i);
4617 if (RT_FAILURE(rc))
4618 return rc;
4619 }
4620 }
4621
4622 uint64_t uFileOffset;
4623 uFileOffset = pExtent->uAppendPosition;
4624 if (!uFileOffset)
4625 return VERR_INTERNAL_ERROR;
4626 /* Align to sector, as the previous write could have been any size. */
4627 uFileOffset = RT_ALIGN_64(uFileOffset, 512);
4628
4629 /* Paranoia check: extent type, grain table buffer presence and
4630 * grain table buffer space. Also grain table entry must be clear. */
4631 if ( pExtent->enmType != VMDKETYPE_HOSTED_SPARSE
4632 || !pImage->pGTCache
4633 || pExtent->cGTEntries > VMDK_GT_CACHE_SIZE * VMDK_GT_CACHELINE_SIZE
4634 || pImage->pGTCache->aGTCache[uCacheLine].aGTData[uCacheEntry])
4635 return VERR_INTERNAL_ERROR;
4636
4637 /* Update grain table entry. */
4638 pImage->pGTCache->aGTCache[uCacheLine].aGTData[uCacheEntry] = VMDK_BYTE2SECTOR(uFileOffset);
4639
4640 if (cbWrite != VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain))
4641 {
4642 vdIfIoIntIoCtxCopyFrom(pImage->pIfIo, pIoCtx, pExtent->pvGrain, cbWrite);
4643 memset((char *)pExtent->pvGrain + cbWrite, '\0',
4644 VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain) - cbWrite);
4645 pData = pExtent->pvGrain;
4646 }
4647 else
4648 {
4649 RTSGSEG Segment;
4650 unsigned cSegments = 1;
4651 size_t cbSeg = 0;
4652
4653 cbSeg = vdIfIoIntIoCtxSegArrayCreate(pImage->pIfIo, pIoCtx, &Segment,
4654 &cSegments, VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain));
4655 Assert(cbSeg == VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain));
4656 pData = Segment.pvSeg;
4657 }
4658 rc = vmdkFileDeflateSync(pImage, pExtent, uFileOffset, pData,
4659 VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain),
4660 uSector, &cbGrain);
4661 if (RT_FAILURE(rc))
4662 {
4663 pExtent->uGrainSectorAbs = 0;
4664 AssertRC(rc);
4665 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: cannot write compressed data block in '%s'"), pExtent->pszFullname);
4666 }
4667 pExtent->uLastGrainAccess = uGrain;
4668 pExtent->uAppendPosition += cbGrain;
4669
4670 return rc;
4671}
4672
4673/**
4674 * Internal: Updates the grain table during grain allocation.
4675 */
4676static int vmdkAllocGrainGTUpdate(PVMDKIMAGE pImage, PVMDKEXTENT pExtent, PVDIOCTX pIoCtx,
4677 PVMDKGRAINALLOCASYNC pGrainAlloc)
4678{
4679 int rc = VINF_SUCCESS;
4680 PVMDKGTCACHE pCache = pImage->pGTCache;
4681 uint32_t aGTDataTmp[VMDK_GT_CACHELINE_SIZE];
4682 uint32_t uGTHash, uGTBlockIndex;
4683 uint64_t uGTSector, uRGTSector, uGTBlock;
4684 uint64_t uSector = pGrainAlloc->uSector;
4685 PVMDKGTCACHEENTRY pGTCacheEntry;
4686
4687 LogFlowFunc(("pImage=%#p pExtent=%#p pCache=%#p pIoCtx=%#p pGrainAlloc=%#p\n",
4688 pImage, pExtent, pCache, pIoCtx, pGrainAlloc));
4689
4690 uGTSector = pGrainAlloc->uGTSector;
4691 uRGTSector = pGrainAlloc->uRGTSector;
4692 LogFlow(("uGTSector=%llu uRGTSector=%llu\n", uGTSector, uRGTSector));
4693
4694 /* Update the grain table (and the cache). */
4695 uGTBlock = uSector / (pExtent->cSectorsPerGrain * VMDK_GT_CACHELINE_SIZE);
4696 uGTHash = vmdkGTCacheHash(pCache, uGTBlock, pExtent->uExtent);
4697 pGTCacheEntry = &pCache->aGTCache[uGTHash];
4698 if ( pGTCacheEntry->uExtent != pExtent->uExtent
4699 || pGTCacheEntry->uGTBlock != uGTBlock)
4700 {
4701 /* Cache miss, fetch data from disk. */
4702 LogFlow(("Cache miss, fetch data from disk\n"));
4703 PVDMETAXFER pMetaXfer = NULL;
4704 rc = vdIfIoIntFileReadMeta(pImage->pIfIo, pExtent->pFile->pStorage,
4705 VMDK_SECTOR2BYTE(uGTSector) + (uGTBlock % (pExtent->cGTEntries / VMDK_GT_CACHELINE_SIZE)) * sizeof(aGTDataTmp),
4706 aGTDataTmp, sizeof(aGTDataTmp), pIoCtx,
4707 &pMetaXfer, vmdkAllocGrainComplete, pGrainAlloc);
4708 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
4709 {
4710 pGrainAlloc->cIoXfersPending++;
4711 pGrainAlloc->fGTUpdateNeeded = true;
4712 /* Leave early, we will be called again after the read completed. */
4713 LogFlowFunc(("Metadata read in progress, leaving\n"));
4714 return rc;
4715 }
4716 else if (RT_FAILURE(rc))
4717 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: cannot read allocated grain table entry in '%s'"), pExtent->pszFullname);
4718 vdIfIoIntMetaXferRelease(pImage->pIfIo, pMetaXfer);
4719 pGTCacheEntry->uExtent = pExtent->uExtent;
4720 pGTCacheEntry->uGTBlock = uGTBlock;
4721 for (unsigned i = 0; i < VMDK_GT_CACHELINE_SIZE; i++)
4722 pGTCacheEntry->aGTData[i] = RT_LE2H_U32(aGTDataTmp[i]);
4723 }
4724 else
4725 {
4726 /* Cache hit. Convert grain table block back to disk format, otherwise
4727 * the code below will write garbage for all but the updated entry. */
4728 for (unsigned i = 0; i < VMDK_GT_CACHELINE_SIZE; i++)
4729 aGTDataTmp[i] = RT_H2LE_U32(pGTCacheEntry->aGTData[i]);
4730 }
4731 pGrainAlloc->fGTUpdateNeeded = false;
4732 uGTBlockIndex = (uSector / pExtent->cSectorsPerGrain) % VMDK_GT_CACHELINE_SIZE;
4733 aGTDataTmp[uGTBlockIndex] = RT_H2LE_U32(VMDK_BYTE2SECTOR(pGrainAlloc->uGrainOffset));
4734 pGTCacheEntry->aGTData[uGTBlockIndex] = VMDK_BYTE2SECTOR(pGrainAlloc->uGrainOffset);
4735 /* Update grain table on disk. */
4736 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pExtent->pFile->pStorage,
4737 VMDK_SECTOR2BYTE(uGTSector) + (uGTBlock % (pExtent->cGTEntries / VMDK_GT_CACHELINE_SIZE)) * sizeof(aGTDataTmp),
4738 aGTDataTmp, sizeof(aGTDataTmp), pIoCtx,
4739 vmdkAllocGrainComplete, pGrainAlloc);
4740 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
4741 pGrainAlloc->cIoXfersPending++;
4742 else if (RT_FAILURE(rc))
4743 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: cannot write updated grain table in '%s'"), pExtent->pszFullname);
4744 if (pExtent->pRGD)
4745 {
4746 /* Update backup grain table on disk. */
4747 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pExtent->pFile->pStorage,
4748 VMDK_SECTOR2BYTE(uRGTSector) + (uGTBlock % (pExtent->cGTEntries / VMDK_GT_CACHELINE_SIZE)) * sizeof(aGTDataTmp),
4749 aGTDataTmp, sizeof(aGTDataTmp), pIoCtx,
4750 vmdkAllocGrainComplete, pGrainAlloc);
4751 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
4752 pGrainAlloc->cIoXfersPending++;
4753 else if (RT_FAILURE(rc))
4754 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: cannot write updated backup grain table in '%s'"), pExtent->pszFullname);
4755 }
4756#ifdef VBOX_WITH_VMDK_ESX
4757 if (RT_SUCCESS(rc) && pExtent->enmType == VMDKETYPE_ESX_SPARSE)
4758 {
4759 pExtent->uFreeSector = uGTSector + VMDK_BYTE2SECTOR(cbWrite);
4760 pExtent->fMetaDirty = true;
4761 }
4762#endif /* VBOX_WITH_VMDK_ESX */
4763
4764 LogFlowFunc(("leaving rc=%Rrc\n", rc));
4765
4766 return rc;
4767}
4768
4769/**
4770 * Internal - complete the grain allocation by updating disk grain table if required.
4771 */
4772static int vmdkAllocGrainComplete(void *pBackendData, PVDIOCTX pIoCtx, void *pvUser, int rcReq)
4773{
4774 int rc = VINF_SUCCESS;
4775 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
4776 PVMDKGRAINALLOCASYNC pGrainAlloc = (PVMDKGRAINALLOCASYNC)pvUser;
4777 PVMDKEXTENT pExtent = pGrainAlloc->pExtent;
4778
4779 LogFlowFunc(("pBackendData=%#p pIoCtx=%#p pvUser=%#p rcReq=%Rrc\n",
4780 pBackendData, pIoCtx, pvUser, rcReq));
4781
4782 pGrainAlloc->cIoXfersPending--;
4783 if (!pGrainAlloc->cIoXfersPending && pGrainAlloc->fGTUpdateNeeded)
4784 rc = vmdkAllocGrainGTUpdate(pImage, pGrainAlloc->pExtent, pIoCtx, pGrainAlloc);
4785
4786 if (!pGrainAlloc->cIoXfersPending)
4787 {
4788 /* Grain allocation completed. */
4789 RTMemFree(pGrainAlloc);
4790 }
4791
4792 LogFlowFunc(("Leaving rc=%Rrc\n", rc));
4793 return rc;
4794}
4795
4796/**
4797 * Internal. Allocates a new grain table (if necessary).
4798 */
4799static int vmdkAllocGrain(PVMDKIMAGE pImage, PVMDKEXTENT pExtent, PVDIOCTX pIoCtx,
4800 uint64_t uSector, uint64_t cbWrite)
4801{
4802 PVMDKGTCACHE pCache = pImage->pGTCache;
4803 uint64_t uGDIndex, uGTSector, uRGTSector;
4804 uint64_t uFileOffset;
4805 PVMDKGRAINALLOCASYNC pGrainAlloc = NULL;
4806 int rc;
4807
4808 LogFlowFunc(("pCache=%#p pExtent=%#p pIoCtx=%#p uSector=%llu cbWrite=%llu\n",
4809 pCache, pExtent, pIoCtx, uSector, cbWrite));
4810
4811 pGrainAlloc = (PVMDKGRAINALLOCASYNC)RTMemAllocZ(sizeof(VMDKGRAINALLOCASYNC));
4812 if (!pGrainAlloc)
4813 return VERR_NO_MEMORY;
4814
4815 pGrainAlloc->pExtent = pExtent;
4816 pGrainAlloc->uSector = uSector;
4817
4818 uGDIndex = uSector / pExtent->cSectorsPerGDE;
4819 if (uGDIndex >= pExtent->cGDEntries)
4820 {
4821 RTMemFree(pGrainAlloc);
4822 return VERR_OUT_OF_RANGE;
4823 }
4824 uGTSector = pExtent->pGD[uGDIndex];
4825 if (pExtent->pRGD)
4826 uRGTSector = pExtent->pRGD[uGDIndex];
4827 else
4828 uRGTSector = 0; /**< avoid compiler warning */
4829 if (!uGTSector)
4830 {
4831 LogFlow(("Allocating new grain table\n"));
4832
4833 /* There is no grain table referenced by this grain directory
4834 * entry. So there is absolutely no data in this area. Allocate
4835 * a new grain table and put the reference to it in the GDs. */
4836 uFileOffset = pExtent->uAppendPosition;
4837 if (!uFileOffset)
4838 return VERR_INTERNAL_ERROR;
4839 Assert(!(uFileOffset % 512));
4840
4841 uFileOffset = RT_ALIGN_64(uFileOffset, 512);
4842 uGTSector = VMDK_BYTE2SECTOR(uFileOffset);
4843
4844 /* Normally the grain table is preallocated for hosted sparse extents
4845 * that support more than 32 bit sector numbers. So this shouldn't
4846 * ever happen on a valid extent. */
4847 if (uGTSector > UINT32_MAX)
4848 return VERR_VD_VMDK_INVALID_HEADER;
4849
4850 /* Write grain table by writing the required number of grain table
4851 * cache chunks. Allocate memory dynamically here or we flood the
4852 * metadata cache with very small entries. */
4853 size_t cbGTDataTmp = pExtent->cGTEntries * sizeof(uint32_t);
4854 uint32_t *paGTDataTmp = (uint32_t *)RTMemTmpAllocZ(cbGTDataTmp);
4855
4856 if (!paGTDataTmp)
4857 return VERR_NO_MEMORY;
4858
4859 memset(paGTDataTmp, '\0', cbGTDataTmp);
4860 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pExtent->pFile->pStorage,
4861 VMDK_SECTOR2BYTE(uGTSector),
4862 paGTDataTmp, cbGTDataTmp, pIoCtx,
4863 vmdkAllocGrainComplete, pGrainAlloc);
4864 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
4865 pGrainAlloc->cIoXfersPending++;
4866 else if (RT_FAILURE(rc))
4867 {
4868 RTMemTmpFree(paGTDataTmp);
4869 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: cannot write grain table allocation in '%s'"), pExtent->pszFullname);
4870 }
4871 pExtent->uAppendPosition = RT_ALIGN_64( pExtent->uAppendPosition
4872 + cbGTDataTmp, 512);
4873
4874 if (pExtent->pRGD)
4875 {
4876 AssertReturn(!uRGTSector, VERR_VD_VMDK_INVALID_HEADER);
4877 uFileOffset = pExtent->uAppendPosition;
4878 if (!uFileOffset)
4879 return VERR_INTERNAL_ERROR;
4880 Assert(!(uFileOffset % 512));
4881 uRGTSector = VMDK_BYTE2SECTOR(uFileOffset);
4882
4883 /* Normally the redundant grain table is preallocated for hosted
4884 * sparse extents that support more than 32 bit sector numbers. So
4885 * this shouldn't ever happen on a valid extent. */
4886 if (uRGTSector > UINT32_MAX)
4887 {
4888 RTMemTmpFree(paGTDataTmp);
4889 return VERR_VD_VMDK_INVALID_HEADER;
4890 }
4891
4892 /* Write grain table by writing the required number of grain table
4893 * cache chunks. Allocate memory dynamically here or we flood the
4894 * metadata cache with very small entries. */
4895 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pExtent->pFile->pStorage,
4896 VMDK_SECTOR2BYTE(uRGTSector),
4897 paGTDataTmp, cbGTDataTmp, pIoCtx,
4898 vmdkAllocGrainComplete, pGrainAlloc);
4899 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
4900 pGrainAlloc->cIoXfersPending++;
4901 else if (RT_FAILURE(rc))
4902 {
4903 RTMemTmpFree(paGTDataTmp);
4904 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: cannot write backup grain table allocation in '%s'"), pExtent->pszFullname);
4905 }
4906
4907 pExtent->uAppendPosition = pExtent->uAppendPosition + cbGTDataTmp;
4908 }
4909
4910 RTMemTmpFree(paGTDataTmp);
4911
4912 /* Update the grain directory on disk (doing it before writing the
4913 * grain table will result in a garbled extent if the operation is
4914 * aborted for some reason. Otherwise the worst that can happen is
4915 * some unused sectors in the extent. */
4916 uint32_t uGTSectorLE = RT_H2LE_U64(uGTSector);
4917 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pExtent->pFile->pStorage,
4918 VMDK_SECTOR2BYTE(pExtent->uSectorGD) + uGDIndex * sizeof(uGTSectorLE),
4919 &uGTSectorLE, sizeof(uGTSectorLE), pIoCtx,
4920 vmdkAllocGrainComplete, pGrainAlloc);
4921 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
4922 pGrainAlloc->cIoXfersPending++;
4923 else if (RT_FAILURE(rc))
4924 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: cannot write grain directory entry in '%s'"), pExtent->pszFullname);
4925 if (pExtent->pRGD)
4926 {
4927 uint32_t uRGTSectorLE = RT_H2LE_U64(uRGTSector);
4928 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pExtent->pFile->pStorage,
4929 VMDK_SECTOR2BYTE(pExtent->uSectorRGD) + uGDIndex * sizeof(uGTSectorLE),
4930 &uRGTSectorLE, sizeof(uRGTSectorLE), pIoCtx,
4931 vmdkAllocGrainComplete, pGrainAlloc);
4932 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
4933 pGrainAlloc->cIoXfersPending++;
4934 else if (RT_FAILURE(rc))
4935 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: cannot write backup grain directory entry in '%s'"), pExtent->pszFullname);
4936 }
4937
4938 /* As the final step update the in-memory copy of the GDs. */
4939 pExtent->pGD[uGDIndex] = uGTSector;
4940 if (pExtent->pRGD)
4941 pExtent->pRGD[uGDIndex] = uRGTSector;
4942 }
4943
4944 LogFlow(("uGTSector=%llu uRGTSector=%llu\n", uGTSector, uRGTSector));
4945 pGrainAlloc->uGTSector = uGTSector;
4946 pGrainAlloc->uRGTSector = uRGTSector;
4947
4948 uFileOffset = pExtent->uAppendPosition;
4949 if (!uFileOffset)
4950 return VERR_INTERNAL_ERROR;
4951 Assert(!(uFileOffset % 512));
4952
4953 pGrainAlloc->uGrainOffset = uFileOffset;
4954
4955 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
4956 {
4957 AssertMsgReturn(vdIfIoIntIoCtxIsSynchronous(pImage->pIfIo, pIoCtx),
4958 ("Accesses to stream optimized images must be synchronous\n"),
4959 VERR_INVALID_STATE);
4960
4961 if (cbWrite != VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain))
4962 return vdIfError(pImage->pIfError, VERR_INTERNAL_ERROR, RT_SRC_POS, N_("VMDK: not enough data for a compressed data block in '%s'"), pExtent->pszFullname);
4963
4964 /* Invalidate cache, just in case some code incorrectly allows mixing
4965 * of reads and writes. Normally shouldn't be needed. */
4966 pExtent->uGrainSectorAbs = 0;
4967
4968 /* Write compressed data block and the markers. */
4969 uint32_t cbGrain = 0;
4970 size_t cbSeg = 0;
4971 RTSGSEG Segment;
4972 unsigned cSegments = 1;
4973
4974 cbSeg = vdIfIoIntIoCtxSegArrayCreate(pImage->pIfIo, pIoCtx, &Segment,
4975 &cSegments, cbWrite);
4976 Assert(cbSeg == cbWrite);
4977
4978 rc = vmdkFileDeflateSync(pImage, pExtent, uFileOffset,
4979 Segment.pvSeg, cbWrite, uSector, &cbGrain);
4980 if (RT_FAILURE(rc))
4981 {
4982 AssertRC(rc);
4983 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: cannot write allocated compressed data block in '%s'"), pExtent->pszFullname);
4984 }
4985 pExtent->uLastGrainAccess = uSector / pExtent->cSectorsPerGrain;
4986 pExtent->uAppendPosition += cbGrain;
4987 }
4988 else
4989 {
4990 /* Write the data. Always a full grain, or we're in big trouble. */
4991 rc = vdIfIoIntFileWriteUser(pImage->pIfIo, pExtent->pFile->pStorage,
4992 uFileOffset, pIoCtx, cbWrite,
4993 vmdkAllocGrainComplete, pGrainAlloc);
4994 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
4995 pGrainAlloc->cIoXfersPending++;
4996 else if (RT_FAILURE(rc))
4997 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: cannot write allocated data block in '%s'"), pExtent->pszFullname);
4998
4999 pExtent->uAppendPosition += cbWrite;
5000 }
5001
5002 rc = vmdkAllocGrainGTUpdate(pImage, pExtent, pIoCtx, pGrainAlloc);
5003
5004 if (!pGrainAlloc->cIoXfersPending)
5005 {
5006 /* Grain allocation completed. */
5007 RTMemFree(pGrainAlloc);
5008 }
5009
5010 LogFlowFunc(("leaving rc=%Rrc\n", rc));
5011
5012 return rc;
5013}
5014
5015/**
5016 * Internal. Reads the contents by sequentially going over the compressed
5017 * grains (hoping that they are in sequence).
5018 */
5019static int vmdkStreamReadSequential(PVMDKIMAGE pImage, PVMDKEXTENT pExtent,
5020 uint64_t uSector, PVDIOCTX pIoCtx,
5021 uint64_t cbRead)
5022{
5023 int rc;
5024
5025 LogFlowFunc(("pImage=%#p pExtent=%#p uSector=%llu pIoCtx=%#p cbRead=%llu\n",
5026 pImage, pExtent, uSector, pIoCtx, cbRead));
5027
5028 AssertMsgReturn(vdIfIoIntIoCtxIsSynchronous(pImage->pIfIo, pIoCtx),
5029 ("Async I/O not supported for sequential stream optimized images\n"),
5030 VERR_INVALID_STATE);
5031
5032 /* Do not allow to go back. */
5033 uint32_t uGrain = uSector / pExtent->cSectorsPerGrain;
5034 if (uGrain < pExtent->uLastGrainAccess)
5035 return VERR_VD_VMDK_INVALID_STATE;
5036 pExtent->uLastGrainAccess = uGrain;
5037
5038 /* After a previous error do not attempt to recover, as it would need
5039 * seeking (in the general case backwards which is forbidden). */
5040 if (!pExtent->uGrainSectorAbs)
5041 return VERR_VD_VMDK_INVALID_STATE;
5042
5043 /* Check if we need to read something from the image or if what we have
5044 * in the buffer is good to fulfill the request. */
5045 if (!pExtent->cbGrainStreamRead || uGrain > pExtent->uGrain)
5046 {
5047 uint32_t uGrainSectorAbs = pExtent->uGrainSectorAbs
5048 + VMDK_BYTE2SECTOR(pExtent->cbGrainStreamRead);
5049
5050 /* Get the marker from the next data block - and skip everything which
5051 * is not a compressed grain. If it's a compressed grain which is for
5052 * the requested sector (or after), read it. */
5053 VMDKMARKER Marker;
5054 do
5055 {
5056 RT_ZERO(Marker);
5057 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pExtent->pFile->pStorage,
5058 VMDK_SECTOR2BYTE(uGrainSectorAbs),
5059 &Marker, RT_OFFSETOF(VMDKMARKER, uType));
5060 if (RT_FAILURE(rc))
5061 return rc;
5062 Marker.uSector = RT_LE2H_U64(Marker.uSector);
5063 Marker.cbSize = RT_LE2H_U32(Marker.cbSize);
5064
5065 if (Marker.cbSize == 0)
5066 {
5067 /* A marker for something else than a compressed grain. */
5068 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pExtent->pFile->pStorage,
5069 VMDK_SECTOR2BYTE(uGrainSectorAbs)
5070 + RT_OFFSETOF(VMDKMARKER, uType),
5071 &Marker.uType, sizeof(Marker.uType));
5072 if (RT_FAILURE(rc))
5073 return rc;
5074 Marker.uType = RT_LE2H_U32(Marker.uType);
5075 switch (Marker.uType)
5076 {
5077 case VMDK_MARKER_EOS:
5078 uGrainSectorAbs++;
5079 /* Read (or mostly skip) to the end of file. Uses the
5080 * Marker (LBA sector) as it is unused anyway. This
5081 * makes sure that really everything is read in the
5082 * success case. If this read fails it means the image
5083 * is truncated, but this is harmless so ignore. */
5084 vdIfIoIntFileReadSync(pImage->pIfIo, pExtent->pFile->pStorage,
5085 VMDK_SECTOR2BYTE(uGrainSectorAbs)
5086 + 511,
5087 &Marker.uSector, 1);
5088 break;
5089 case VMDK_MARKER_GT:
5090 uGrainSectorAbs += 1 + VMDK_BYTE2SECTOR(pExtent->cGTEntries * sizeof(uint32_t));
5091 break;
5092 case VMDK_MARKER_GD:
5093 uGrainSectorAbs += 1 + VMDK_BYTE2SECTOR(RT_ALIGN(pExtent->cGDEntries * sizeof(uint32_t), 512));
5094 break;
5095 case VMDK_MARKER_FOOTER:
5096 uGrainSectorAbs += 2;
5097 break;
5098 case VMDK_MARKER_UNSPECIFIED:
5099 /* Skip over the contents of the unspecified marker
5100 * type 4 which exists in some vSphere created files. */
5101 /** @todo figure out what the payload means. */
5102 uGrainSectorAbs += 1;
5103 break;
5104 default:
5105 AssertMsgFailed(("VMDK: corrupted marker, type=%#x\n", Marker.uType));
5106 pExtent->uGrainSectorAbs = 0;
5107 return VERR_VD_VMDK_INVALID_STATE;
5108 }
5109 pExtent->cbGrainStreamRead = 0;
5110 }
5111 else
5112 {
5113 /* A compressed grain marker. If it is at/after what we're
5114 * interested in read and decompress data. */
5115 if (uSector > Marker.uSector + pExtent->cSectorsPerGrain)
5116 {
5117 uGrainSectorAbs += VMDK_BYTE2SECTOR(RT_ALIGN(Marker.cbSize + RT_OFFSETOF(VMDKMARKER, uType), 512));
5118 continue;
5119 }
5120 uint64_t uLBA = 0;
5121 uint32_t cbGrainStreamRead = 0;
5122 rc = vmdkFileInflateSync(pImage, pExtent,
5123 VMDK_SECTOR2BYTE(uGrainSectorAbs),
5124 pExtent->pvGrain,
5125 VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain),
5126 &Marker, &uLBA, &cbGrainStreamRead);
5127 if (RT_FAILURE(rc))
5128 {
5129 pExtent->uGrainSectorAbs = 0;
5130 return rc;
5131 }
5132 if ( pExtent->uGrain
5133 && uLBA / pExtent->cSectorsPerGrain <= pExtent->uGrain)
5134 {
5135 pExtent->uGrainSectorAbs = 0;
5136 return VERR_VD_VMDK_INVALID_STATE;
5137 }
5138 pExtent->uGrain = uLBA / pExtent->cSectorsPerGrain;
5139 pExtent->cbGrainStreamRead = cbGrainStreamRead;
5140 break;
5141 }
5142 } while (Marker.uType != VMDK_MARKER_EOS);
5143
5144 pExtent->uGrainSectorAbs = uGrainSectorAbs;
5145
5146 if (!pExtent->cbGrainStreamRead && Marker.uType == VMDK_MARKER_EOS)
5147 {
5148 pExtent->uGrain = UINT32_MAX;
5149 /* Must set a non-zero value for pExtent->cbGrainStreamRead or
5150 * the next read would try to get more data, and we're at EOF. */
5151 pExtent->cbGrainStreamRead = 1;
5152 }
5153 }
5154
5155 if (pExtent->uGrain > uSector / pExtent->cSectorsPerGrain)
5156 {
5157 /* The next data block we have is not for this area, so just return
5158 * that there is no data. */
5159 LogFlowFunc(("returns VERR_VD_BLOCK_FREE\n"));
5160 return VERR_VD_BLOCK_FREE;
5161 }
5162
5163 uint32_t uSectorInGrain = uSector % pExtent->cSectorsPerGrain;
5164 vdIfIoIntIoCtxCopyTo(pImage->pIfIo, pIoCtx,
5165 (uint8_t *)pExtent->pvGrain + VMDK_SECTOR2BYTE(uSectorInGrain),
5166 cbRead);
5167 LogFlowFunc(("returns VINF_SUCCESS\n"));
5168 return VINF_SUCCESS;
5169}
5170
5171/**
5172 * Replaces a fragment of a string with the specified string.
5173 *
5174 * @returns Pointer to the allocated UTF-8 string.
5175 * @param pszWhere UTF-8 string to search in.
5176 * @param pszWhat UTF-8 string to search for.
5177 * @param pszByWhat UTF-8 string to replace the found string with.
5178 */
5179static char *vmdkStrReplace(const char *pszWhere, const char *pszWhat,
5180 const char *pszByWhat)
5181{
5182 AssertPtr(pszWhere);
5183 AssertPtr(pszWhat);
5184 AssertPtr(pszByWhat);
5185 const char *pszFoundStr = strstr(pszWhere, pszWhat);
5186 if (!pszFoundStr)
5187 return NULL;
5188 size_t cFinal = strlen(pszWhere) + 1 + strlen(pszByWhat) - strlen(pszWhat);
5189 char *pszNewStr = (char *)RTMemAlloc(cFinal);
5190 if (pszNewStr)
5191 {
5192 char *pszTmp = pszNewStr;
5193 memcpy(pszTmp, pszWhere, pszFoundStr - pszWhere);
5194 pszTmp += pszFoundStr - pszWhere;
5195 memcpy(pszTmp, pszByWhat, strlen(pszByWhat));
5196 pszTmp += strlen(pszByWhat);
5197 strcpy(pszTmp, pszFoundStr + strlen(pszWhat));
5198 }
5199 return pszNewStr;
5200}
5201
5202
5203/** @copydoc VBOXHDDBACKEND::pfnCheckIfValid */
5204static int vmdkCheckIfValid(const char *pszFilename, PVDINTERFACE pVDIfsDisk,
5205 PVDINTERFACE pVDIfsImage, VDTYPE *penmType)
5206{
5207 LogFlowFunc(("pszFilename=\"%s\" pVDIfsDisk=%#p pVDIfsImage=%#p penmType=%#p\n",
5208 pszFilename, pVDIfsDisk, pVDIfsImage, penmType));
5209 int rc = VINF_SUCCESS;
5210 PVMDKIMAGE pImage;
5211
5212 if ( !pszFilename
5213 || !*pszFilename
5214 || strchr(pszFilename, '"'))
5215 {
5216 rc = VERR_INVALID_PARAMETER;
5217 goto out;
5218 }
5219
5220 pImage = (PVMDKIMAGE)RTMemAllocZ(sizeof(VMDKIMAGE));
5221 if (!pImage)
5222 {
5223 rc = VERR_NO_MEMORY;
5224 goto out;
5225 }
5226 pImage->pszFilename = pszFilename;
5227 pImage->pFile = NULL;
5228 pImage->pExtents = NULL;
5229 pImage->pFiles = NULL;
5230 pImage->pGTCache = NULL;
5231 pImage->pDescData = NULL;
5232 pImage->pVDIfsDisk = pVDIfsDisk;
5233 pImage->pVDIfsImage = pVDIfsImage;
5234 /** @todo speed up this test open (VD_OPEN_FLAGS_INFO) by skipping as
5235 * much as possible in vmdkOpenImage. */
5236 rc = vmdkOpenImage(pImage, VD_OPEN_FLAGS_INFO | VD_OPEN_FLAGS_READONLY);
5237 vmdkFreeImage(pImage, false);
5238 RTMemFree(pImage);
5239
5240 if (RT_SUCCESS(rc))
5241 *penmType = VDTYPE_HDD;
5242
5243out:
5244 LogFlowFunc(("returns %Rrc\n", rc));
5245 return rc;
5246}
5247
5248/** @copydoc VBOXHDDBACKEND::pfnOpen */
5249static int vmdkOpen(const char *pszFilename, unsigned uOpenFlags,
5250 PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
5251 VDTYPE enmType, void **ppBackendData)
5252{
5253 LogFlowFunc(("pszFilename=\"%s\" uOpenFlags=%#x pVDIfsDisk=%#p pVDIfsImage=%#p ppBackendData=%#p\n", pszFilename, uOpenFlags, pVDIfsDisk, pVDIfsImage, ppBackendData));
5254 int rc;
5255 PVMDKIMAGE pImage;
5256
5257 /* Check open flags. All valid flags are supported. */
5258 if (uOpenFlags & ~VD_OPEN_FLAGS_MASK)
5259 {
5260 rc = VERR_INVALID_PARAMETER;
5261 goto out;
5262 }
5263
5264 /* Check remaining arguments. */
5265 if ( !VALID_PTR(pszFilename)
5266 || !*pszFilename
5267 || strchr(pszFilename, '"'))
5268 {
5269 rc = VERR_INVALID_PARAMETER;
5270 goto out;
5271 }
5272
5273 pImage = (PVMDKIMAGE)RTMemAllocZ(sizeof(VMDKIMAGE));
5274 if (!pImage)
5275 {
5276 rc = VERR_NO_MEMORY;
5277 goto out;
5278 }
5279 pImage->pszFilename = pszFilename;
5280 pImage->pFile = NULL;
5281 pImage->pExtents = NULL;
5282 pImage->pFiles = NULL;
5283 pImage->pGTCache = NULL;
5284 pImage->pDescData = NULL;
5285 pImage->pVDIfsDisk = pVDIfsDisk;
5286 pImage->pVDIfsImage = pVDIfsImage;
5287
5288 rc = vmdkOpenImage(pImage, uOpenFlags);
5289 if (RT_SUCCESS(rc))
5290 *ppBackendData = pImage;
5291 else
5292 RTMemFree(pImage);
5293
5294out:
5295 LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
5296 return rc;
5297}
5298
5299/** @copydoc VBOXHDDBACKEND::pfnCreate */
5300static int vmdkCreate(const char *pszFilename, uint64_t cbSize,
5301 unsigned uImageFlags, const char *pszComment,
5302 PCVDGEOMETRY pPCHSGeometry, PCVDGEOMETRY pLCHSGeometry,
5303 PCRTUUID pUuid, unsigned uOpenFlags,
5304 unsigned uPercentStart, unsigned uPercentSpan,
5305 PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
5306 PVDINTERFACE pVDIfsOperation, void **ppBackendData)
5307{
5308 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));
5309 int rc;
5310 PVMDKIMAGE pImage;
5311
5312 PFNVDPROGRESS pfnProgress = NULL;
5313 void *pvUser = NULL;
5314 PVDINTERFACEPROGRESS pIfProgress = VDIfProgressGet(pVDIfsOperation);
5315 if (pIfProgress)
5316 {
5317 pfnProgress = pIfProgress->pfnProgress;
5318 pvUser = pIfProgress->Core.pvUser;
5319 }
5320
5321 /* Check the image flags. */
5322 if ((uImageFlags & ~VD_VMDK_IMAGE_FLAGS_MASK) != 0)
5323 {
5324 rc = VERR_VD_INVALID_TYPE;
5325 goto out;
5326 }
5327
5328 /* Check open flags. All valid flags are supported. */
5329 if (uOpenFlags & ~VD_OPEN_FLAGS_MASK)
5330 {
5331 rc = VERR_INVALID_PARAMETER;
5332 goto out;
5333 }
5334
5335 /* Check size. Maximum 2TB-64K for sparse images, otherwise unlimited. */
5336 if ( !cbSize
5337 || (!(uImageFlags & VD_IMAGE_FLAGS_FIXED) && cbSize >= _1T * 2 - _64K))
5338 {
5339 rc = VERR_VD_INVALID_SIZE;
5340 goto out;
5341 }
5342
5343 /* Check remaining arguments. */
5344 if ( !VALID_PTR(pszFilename)
5345 || !*pszFilename
5346 || strchr(pszFilename, '"')
5347 || !VALID_PTR(pPCHSGeometry)
5348 || !VALID_PTR(pLCHSGeometry)
5349#ifndef VBOX_WITH_VMDK_ESX
5350 || ( uImageFlags & VD_VMDK_IMAGE_FLAGS_ESX
5351 && !(uImageFlags & VD_IMAGE_FLAGS_FIXED))
5352#endif
5353 || ( (uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
5354 && (uImageFlags & ~(VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED | VD_IMAGE_FLAGS_DIFF))))
5355 {
5356 rc = VERR_INVALID_PARAMETER;
5357 goto out;
5358 }
5359
5360 pImage = (PVMDKIMAGE)RTMemAllocZ(sizeof(VMDKIMAGE));
5361 if (!pImage)
5362 {
5363 rc = VERR_NO_MEMORY;
5364 goto out;
5365 }
5366 pImage->pszFilename = pszFilename;
5367 pImage->pFile = NULL;
5368 pImage->pExtents = NULL;
5369 pImage->pFiles = NULL;
5370 pImage->pGTCache = NULL;
5371 pImage->pDescData = NULL;
5372 pImage->pVDIfsDisk = pVDIfsDisk;
5373 pImage->pVDIfsImage = pVDIfsImage;
5374 /* Descriptors for split images can be pretty large, especially if the
5375 * filename is long. So prepare for the worst, and allocate quite some
5376 * memory for the descriptor in this case. */
5377 if (uImageFlags & VD_VMDK_IMAGE_FLAGS_SPLIT_2G)
5378 pImage->cbDescAlloc = VMDK_SECTOR2BYTE(200);
5379 else
5380 pImage->cbDescAlloc = VMDK_SECTOR2BYTE(20);
5381 pImage->pDescData = (char *)RTMemAllocZ(pImage->cbDescAlloc);
5382 if (!pImage->pDescData)
5383 {
5384 RTMemFree(pImage);
5385 rc = VERR_NO_MEMORY;
5386 goto out;
5387 }
5388
5389 rc = vmdkCreateImage(pImage, cbSize, uImageFlags, pszComment,
5390 pPCHSGeometry, pLCHSGeometry, pUuid,
5391 pfnProgress, pvUser, uPercentStart, uPercentSpan);
5392 if (RT_SUCCESS(rc))
5393 {
5394 /* So far the image is opened in read/write mode. Make sure the
5395 * image is opened in read-only mode if the caller requested that. */
5396 if (uOpenFlags & VD_OPEN_FLAGS_READONLY)
5397 {
5398 vmdkFreeImage(pImage, false);
5399 rc = vmdkOpenImage(pImage, uOpenFlags);
5400 if (RT_FAILURE(rc))
5401 goto out;
5402 }
5403 *ppBackendData = pImage;
5404 }
5405 else
5406 {
5407 RTMemFree(pImage->pDescData);
5408 RTMemFree(pImage);
5409 }
5410
5411out:
5412 LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
5413 return rc;
5414}
5415
5416/** @copydoc VBOXHDDBACKEND::pfnRename */
5417static int vmdkRename(void *pBackendData, const char *pszFilename)
5418{
5419 LogFlowFunc(("pBackendData=%#p pszFilename=%#p\n", pBackendData, pszFilename));
5420
5421 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5422 int rc = VINF_SUCCESS;
5423 char **apszOldName = NULL;
5424 char **apszNewName = NULL;
5425 char **apszNewLines = NULL;
5426 char *pszOldDescName = NULL;
5427 bool fImageFreed = false;
5428 bool fEmbeddedDesc = false;
5429 unsigned cExtents = 0;
5430 char *pszNewBaseName = NULL;
5431 char *pszOldBaseName = NULL;
5432 char *pszNewFullName = NULL;
5433 char *pszOldFullName = NULL;
5434 const char *pszOldImageName;
5435 unsigned i, line;
5436 VMDKDESCRIPTOR DescriptorCopy;
5437 VMDKEXTENT ExtentCopy;
5438
5439 memset(&DescriptorCopy, 0, sizeof(DescriptorCopy));
5440
5441 /* Check arguments. */
5442 if ( !pImage
5443 || (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_RAWDISK)
5444 || !VALID_PTR(pszFilename)
5445 || !*pszFilename)
5446 {
5447 rc = VERR_INVALID_PARAMETER;
5448 goto out;
5449 }
5450
5451 cExtents = pImage->cExtents;
5452
5453 /*
5454 * Allocate an array to store both old and new names of renamed files
5455 * in case we have to roll back the changes. Arrays are initialized
5456 * with zeros. We actually save stuff when and if we change it.
5457 */
5458 apszOldName = (char **)RTMemTmpAllocZ((cExtents + 1) * sizeof(char*));
5459 apszNewName = (char **)RTMemTmpAllocZ((cExtents + 1) * sizeof(char*));
5460 apszNewLines = (char **)RTMemTmpAllocZ((cExtents) * sizeof(char*));
5461 if (!apszOldName || !apszNewName || !apszNewLines)
5462 {
5463 rc = VERR_NO_MEMORY;
5464 goto out;
5465 }
5466
5467 /* Save the descriptor size and position. */
5468 if (pImage->pDescData)
5469 {
5470 /* Separate descriptor file. */
5471 fEmbeddedDesc = false;
5472 }
5473 else
5474 {
5475 /* Embedded descriptor file. */
5476 ExtentCopy = pImage->pExtents[0];
5477 fEmbeddedDesc = true;
5478 }
5479 /* Save the descriptor content. */
5480 DescriptorCopy.cLines = pImage->Descriptor.cLines;
5481 for (i = 0; i < DescriptorCopy.cLines; i++)
5482 {
5483 DescriptorCopy.aLines[i] = RTStrDup(pImage->Descriptor.aLines[i]);
5484 if (!DescriptorCopy.aLines[i])
5485 {
5486 rc = VERR_NO_MEMORY;
5487 goto out;
5488 }
5489 }
5490
5491 /* Prepare both old and new base names used for string replacement. */
5492 pszNewBaseName = RTStrDup(RTPathFilename(pszFilename));
5493 RTPathStripExt(pszNewBaseName);
5494 pszOldBaseName = RTStrDup(RTPathFilename(pImage->pszFilename));
5495 RTPathStripExt(pszOldBaseName);
5496 /* Prepare both old and new full names used for string replacement. */
5497 pszNewFullName = RTStrDup(pszFilename);
5498 RTPathStripExt(pszNewFullName);
5499 pszOldFullName = RTStrDup(pImage->pszFilename);
5500 RTPathStripExt(pszOldFullName);
5501
5502 /* --- Up to this point we have not done any damage yet. --- */
5503
5504 /* Save the old name for easy access to the old descriptor file. */
5505 pszOldDescName = RTStrDup(pImage->pszFilename);
5506 /* Save old image name. */
5507 pszOldImageName = pImage->pszFilename;
5508
5509 /* Update the descriptor with modified extent names. */
5510 for (i = 0, line = pImage->Descriptor.uFirstExtent;
5511 i < cExtents;
5512 i++, line = pImage->Descriptor.aNextLines[line])
5513 {
5514 /* Assume that vmdkStrReplace will fail. */
5515 rc = VERR_NO_MEMORY;
5516 /* Update the descriptor. */
5517 apszNewLines[i] = vmdkStrReplace(pImage->Descriptor.aLines[line],
5518 pszOldBaseName, pszNewBaseName);
5519 if (!apszNewLines[i])
5520 goto rollback;
5521 pImage->Descriptor.aLines[line] = apszNewLines[i];
5522 }
5523 /* Make sure the descriptor gets written back. */
5524 pImage->Descriptor.fDirty = true;
5525 /* Flush the descriptor now, in case it is embedded. */
5526 vmdkFlushImage(pImage, NULL);
5527
5528 /* Close and rename/move extents. */
5529 for (i = 0; i < cExtents; i++)
5530 {
5531 PVMDKEXTENT pExtent = &pImage->pExtents[i];
5532 /* Compose new name for the extent. */
5533 apszNewName[i] = vmdkStrReplace(pExtent->pszFullname,
5534 pszOldFullName, pszNewFullName);
5535 if (!apszNewName[i])
5536 goto rollback;
5537 /* Close the extent file. */
5538 rc = vmdkFileClose(pImage, &pExtent->pFile, false);
5539 if (RT_FAILURE(rc))
5540 goto rollback;
5541
5542 /* Rename the extent file. */
5543 rc = vdIfIoIntFileMove(pImage->pIfIo, pExtent->pszFullname, apszNewName[i], 0);
5544 if (RT_FAILURE(rc))
5545 goto rollback;
5546 /* Remember the old name. */
5547 apszOldName[i] = RTStrDup(pExtent->pszFullname);
5548 }
5549 /* Release all old stuff. */
5550 rc = vmdkFreeImage(pImage, false);
5551 if (RT_FAILURE(rc))
5552 goto rollback;
5553
5554 fImageFreed = true;
5555
5556 /* Last elements of new/old name arrays are intended for
5557 * storing descriptor's names.
5558 */
5559 apszNewName[cExtents] = RTStrDup(pszFilename);
5560 /* Rename the descriptor file if it's separate. */
5561 if (!fEmbeddedDesc)
5562 {
5563 rc = vdIfIoIntFileMove(pImage->pIfIo, pImage->pszFilename, apszNewName[cExtents], 0);
5564 if (RT_FAILURE(rc))
5565 goto rollback;
5566 /* Save old name only if we may need to change it back. */
5567 apszOldName[cExtents] = RTStrDup(pszFilename);
5568 }
5569
5570 /* Update pImage with the new information. */
5571 pImage->pszFilename = pszFilename;
5572
5573 /* Open the new image. */
5574 rc = vmdkOpenImage(pImage, pImage->uOpenFlags);
5575 if (RT_SUCCESS(rc))
5576 goto out;
5577
5578rollback:
5579 /* Roll back all changes in case of failure. */
5580 if (RT_FAILURE(rc))
5581 {
5582 int rrc;
5583 if (!fImageFreed)
5584 {
5585 /*
5586 * Some extents may have been closed, close the rest. We will
5587 * re-open the whole thing later.
5588 */
5589 vmdkFreeImage(pImage, false);
5590 }
5591 /* Rename files back. */
5592 for (i = 0; i <= cExtents; i++)
5593 {
5594 if (apszOldName[i])
5595 {
5596 rrc = vdIfIoIntFileMove(pImage->pIfIo, apszNewName[i], apszOldName[i], 0);
5597 AssertRC(rrc);
5598 }
5599 }
5600 /* Restore the old descriptor. */
5601 PVMDKFILE pFile;
5602 rrc = vmdkFileOpen(pImage, &pFile, pszOldDescName,
5603 VDOpenFlagsToFileOpenFlags(VD_OPEN_FLAGS_NORMAL,
5604 false /* fCreate */));
5605 AssertRC(rrc);
5606 if (fEmbeddedDesc)
5607 {
5608 ExtentCopy.pFile = pFile;
5609 pImage->pExtents = &ExtentCopy;
5610 }
5611 else
5612 {
5613 /* Shouldn't be null for separate descriptor.
5614 * There will be no access to the actual content.
5615 */
5616 pImage->pDescData = pszOldDescName;
5617 pImage->pFile = pFile;
5618 }
5619 pImage->Descriptor = DescriptorCopy;
5620 vmdkWriteDescriptor(pImage, NULL);
5621 vmdkFileClose(pImage, &pFile, false);
5622 /* Get rid of the stuff we implanted. */
5623 pImage->pExtents = NULL;
5624 pImage->pFile = NULL;
5625 pImage->pDescData = NULL;
5626 /* Re-open the image back. */
5627 pImage->pszFilename = pszOldImageName;
5628 rrc = vmdkOpenImage(pImage, pImage->uOpenFlags);
5629 AssertRC(rrc);
5630 }
5631
5632out:
5633 for (i = 0; i < DescriptorCopy.cLines; i++)
5634 if (DescriptorCopy.aLines[i])
5635 RTStrFree(DescriptorCopy.aLines[i]);
5636 if (apszOldName)
5637 {
5638 for (i = 0; i <= cExtents; i++)
5639 if (apszOldName[i])
5640 RTStrFree(apszOldName[i]);
5641 RTMemTmpFree(apszOldName);
5642 }
5643 if (apszNewName)
5644 {
5645 for (i = 0; i <= cExtents; i++)
5646 if (apszNewName[i])
5647 RTStrFree(apszNewName[i]);
5648 RTMemTmpFree(apszNewName);
5649 }
5650 if (apszNewLines)
5651 {
5652 for (i = 0; i < cExtents; i++)
5653 if (apszNewLines[i])
5654 RTStrFree(apszNewLines[i]);
5655 RTMemTmpFree(apszNewLines);
5656 }
5657 if (pszOldDescName)
5658 RTStrFree(pszOldDescName);
5659 if (pszOldBaseName)
5660 RTStrFree(pszOldBaseName);
5661 if (pszNewBaseName)
5662 RTStrFree(pszNewBaseName);
5663 if (pszOldFullName)
5664 RTStrFree(pszOldFullName);
5665 if (pszNewFullName)
5666 RTStrFree(pszNewFullName);
5667 LogFlowFunc(("returns %Rrc\n", rc));
5668 return rc;
5669}
5670
5671/** @copydoc VBOXHDDBACKEND::pfnClose */
5672static int vmdkClose(void *pBackendData, bool fDelete)
5673{
5674 LogFlowFunc(("pBackendData=%#p fDelete=%d\n", pBackendData, fDelete));
5675 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5676 int rc;
5677
5678 rc = vmdkFreeImage(pImage, fDelete);
5679 RTMemFree(pImage);
5680
5681 LogFlowFunc(("returns %Rrc\n", rc));
5682 return rc;
5683}
5684
5685/** @copydoc VBOXHDDBACKEND::pfnRead */
5686static int vmdkRead(void *pBackendData, uint64_t uOffset, size_t cbToRead,
5687 PVDIOCTX pIoCtx, size_t *pcbActuallyRead)
5688{
5689 LogFlowFunc(("pBackendData=%#p uOffset=%llu pIoCtx=%#p cbToRead=%zu pcbActuallyRead=%#p\n",
5690 pBackendData, uOffset, pIoCtx, cbToRead, pcbActuallyRead));
5691 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5692 PVMDKEXTENT pExtent;
5693 uint64_t uSectorExtentRel;
5694 uint64_t uSectorExtentAbs;
5695 int rc;
5696
5697 AssertPtr(pImage);
5698 Assert(uOffset % 512 == 0);
5699 Assert(cbToRead % 512 == 0);
5700
5701 if ( uOffset + cbToRead > pImage->cbSize
5702 || cbToRead == 0)
5703 {
5704 rc = VERR_INVALID_PARAMETER;
5705 goto out;
5706 }
5707
5708 rc = vmdkFindExtent(pImage, VMDK_BYTE2SECTOR(uOffset),
5709 &pExtent, &uSectorExtentRel);
5710 if (RT_FAILURE(rc))
5711 goto out;
5712
5713 /* Check access permissions as defined in the extent descriptor. */
5714 if (pExtent->enmAccess == VMDKACCESS_NOACCESS)
5715 {
5716 rc = VERR_VD_VMDK_INVALID_STATE;
5717 goto out;
5718 }
5719
5720 /* Clip read range to remain in this extent. */
5721 cbToRead = RT_MIN(cbToRead, VMDK_SECTOR2BYTE(pExtent->uSectorOffset + pExtent->cNominalSectors - uSectorExtentRel));
5722
5723 /* Handle the read according to the current extent type. */
5724 switch (pExtent->enmType)
5725 {
5726 case VMDKETYPE_HOSTED_SPARSE:
5727#ifdef VBOX_WITH_VMDK_ESX
5728 case VMDKETYPE_ESX_SPARSE:
5729#endif /* VBOX_WITH_VMDK_ESX */
5730 rc = vmdkGetSector(pImage, pIoCtx, pExtent, uSectorExtentRel, &uSectorExtentAbs);
5731 if (RT_FAILURE(rc))
5732 goto out;
5733 /* Clip read range to at most the rest of the grain. */
5734 cbToRead = RT_MIN(cbToRead, VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain - uSectorExtentRel % pExtent->cSectorsPerGrain));
5735 Assert(!(cbToRead % 512));
5736 if (uSectorExtentAbs == 0)
5737 {
5738 if ( !(pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
5739 || !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
5740 || !(pImage->uOpenFlags & VD_OPEN_FLAGS_SEQUENTIAL))
5741 rc = VERR_VD_BLOCK_FREE;
5742 else
5743 rc = vmdkStreamReadSequential(pImage, pExtent,
5744 uSectorExtentRel,
5745 pIoCtx, cbToRead);
5746 }
5747 else
5748 {
5749 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
5750 {
5751 AssertMsg(vdIfIoIntIoCtxIsSynchronous(pImage->pIfIo, pIoCtx),
5752 ("Async I/O is not supported for stream optimized VMDK's\n"));
5753
5754 uint32_t uSectorInGrain = uSectorExtentRel % pExtent->cSectorsPerGrain;
5755 uSectorExtentAbs -= uSectorInGrain;
5756 uint64_t uLBA;
5757 if (pExtent->uGrainSectorAbs != uSectorExtentAbs)
5758 {
5759 rc = vmdkFileInflateSync(pImage, pExtent,
5760 VMDK_SECTOR2BYTE(uSectorExtentAbs),
5761 pExtent->pvGrain,
5762 VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain),
5763 NULL, &uLBA, NULL);
5764 if (RT_FAILURE(rc))
5765 {
5766 pExtent->uGrainSectorAbs = 0;
5767 AssertRC(rc);
5768 goto out;
5769 }
5770 pExtent->uGrainSectorAbs = uSectorExtentAbs;
5771 pExtent->uGrain = uSectorExtentRel / pExtent->cSectorsPerGrain;
5772 Assert(uLBA == uSectorExtentRel);
5773 }
5774 vdIfIoIntIoCtxCopyTo(pImage->pIfIo, pIoCtx,
5775 (uint8_t *)pExtent->pvGrain
5776 + VMDK_SECTOR2BYTE(uSectorInGrain),
5777 cbToRead);
5778 }
5779 else
5780 rc = vdIfIoIntFileReadUser(pImage->pIfIo, pExtent->pFile->pStorage,
5781 VMDK_SECTOR2BYTE(uSectorExtentAbs),
5782 pIoCtx, cbToRead);
5783 }
5784 break;
5785 case VMDKETYPE_VMFS:
5786 case VMDKETYPE_FLAT:
5787 rc = vdIfIoIntFileReadUser(pImage->pIfIo, pExtent->pFile->pStorage,
5788 VMDK_SECTOR2BYTE(uSectorExtentRel),
5789 pIoCtx, cbToRead);
5790 break;
5791 case VMDKETYPE_ZERO:
5792 size_t cbSet;
5793
5794 cbSet = vdIfIoIntIoCtxSet(pImage->pIfIo, pIoCtx, 0, cbToRead);
5795 Assert(cbSet == cbToRead);
5796
5797 rc = VINF_SUCCESS;
5798 break;
5799 }
5800 if (pcbActuallyRead)
5801 *pcbActuallyRead = cbToRead;
5802
5803out:
5804 LogFlowFunc(("returns %Rrc\n", rc));
5805 return rc;
5806}
5807
5808/** @copydoc VBOXHDDBACKEND::pfnWrite */
5809static int vmdkWrite(void *pBackendData, uint64_t uOffset, size_t cbToWrite,
5810 PVDIOCTX pIoCtx, size_t *pcbWriteProcess, size_t *pcbPreRead,
5811 size_t *pcbPostRead, unsigned fWrite)
5812{
5813 LogFlowFunc(("pBackendData=%#p uOffset=%llu pIoCtx=%#p cbToWrite=%zu pcbWriteProcess=%#p pcbPreRead=%#p pcbPostRead=%#p\n",
5814 pBackendData, uOffset, pIoCtx, cbToWrite, pcbWriteProcess, pcbPreRead, pcbPostRead));
5815 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5816 PVMDKEXTENT pExtent;
5817 uint64_t uSectorExtentRel;
5818 uint64_t uSectorExtentAbs;
5819 int rc;
5820
5821 AssertPtr(pImage);
5822 Assert(uOffset % 512 == 0);
5823 Assert(cbToWrite % 512 == 0);
5824
5825 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
5826 {
5827 rc = VERR_VD_IMAGE_READ_ONLY;
5828 goto out;
5829 }
5830
5831 if (cbToWrite == 0)
5832 {
5833 rc = VERR_INVALID_PARAMETER;
5834 goto out;
5835 }
5836
5837 /* No size check here, will do that later when the extent is located.
5838 * There are sparse images out there which according to the spec are
5839 * invalid, because the total size is not a multiple of the grain size.
5840 * Also for sparse images which are stitched together in odd ways (not at
5841 * grain boundaries, and with the nominal size not being a multiple of the
5842 * grain size), this would prevent writing to the last grain. */
5843
5844 rc = vmdkFindExtent(pImage, VMDK_BYTE2SECTOR(uOffset),
5845 &pExtent, &uSectorExtentRel);
5846 if (RT_FAILURE(rc))
5847 goto out;
5848
5849 /* Check access permissions as defined in the extent descriptor. */
5850 if ( pExtent->enmAccess != VMDKACCESS_READWRITE
5851 && ( !(pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
5852 && !pImage->pExtents[0].uAppendPosition
5853 && pExtent->enmAccess != VMDKACCESS_READONLY))
5854 {
5855 rc = VERR_VD_VMDK_INVALID_STATE;
5856 goto out;
5857 }
5858
5859 /* Handle the write according to the current extent type. */
5860 switch (pExtent->enmType)
5861 {
5862 case VMDKETYPE_HOSTED_SPARSE:
5863#ifdef VBOX_WITH_VMDK_ESX
5864 case VMDKETYPE_ESX_SPARSE:
5865#endif /* VBOX_WITH_VMDK_ESX */
5866 rc = vmdkGetSector(pImage, pIoCtx, pExtent, uSectorExtentRel, &uSectorExtentAbs);
5867 if (RT_FAILURE(rc))
5868 goto out;
5869 /* Clip write range to at most the rest of the grain. */
5870 cbToWrite = RT_MIN(cbToWrite, VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain - uSectorExtentRel % pExtent->cSectorsPerGrain));
5871 if ( pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED
5872 && uSectorExtentRel < (uint64_t)pExtent->uLastGrainAccess * pExtent->cSectorsPerGrain)
5873 {
5874 rc = VERR_VD_VMDK_INVALID_WRITE;
5875 goto out;
5876 }
5877 if (uSectorExtentAbs == 0)
5878 {
5879 if (!(pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED))
5880 {
5881 if (cbToWrite == VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain))
5882 {
5883 /* Full block write to a previously unallocated block.
5884 * Check if the caller wants to avoid the automatic alloc. */
5885 if (!(fWrite & VD_WRITE_NO_ALLOC))
5886 {
5887 /* Allocate GT and find out where to store the grain. */
5888 rc = vmdkAllocGrain(pImage, pExtent, pIoCtx,
5889 uSectorExtentRel, cbToWrite);
5890 }
5891 else
5892 rc = VERR_VD_BLOCK_FREE;
5893 *pcbPreRead = 0;
5894 *pcbPostRead = 0;
5895 }
5896 else
5897 {
5898 /* Clip write range to remain in this extent. */
5899 cbToWrite = RT_MIN(cbToWrite, VMDK_SECTOR2BYTE(pExtent->uSectorOffset + pExtent->cNominalSectors - uSectorExtentRel));
5900 *pcbPreRead = VMDK_SECTOR2BYTE(uSectorExtentRel % pExtent->cSectorsPerGrain);
5901 *pcbPostRead = VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain) - cbToWrite - *pcbPreRead;
5902 rc = VERR_VD_BLOCK_FREE;
5903 }
5904 }
5905 else
5906 {
5907 rc = vmdkStreamAllocGrain(pImage, pExtent,
5908 uSectorExtentRel,
5909 pIoCtx, cbToWrite);
5910 }
5911 }
5912 else
5913 {
5914 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
5915 {
5916 /* A partial write to a streamOptimized image is simply
5917 * invalid. It requires rewriting already compressed data
5918 * which is somewhere between expensive and impossible. */
5919 rc = VERR_VD_VMDK_INVALID_STATE;
5920 pExtent->uGrainSectorAbs = 0;
5921 AssertRC(rc);
5922 }
5923 else
5924 {
5925 Assert(!(pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED));
5926 rc = vdIfIoIntFileWriteUser(pImage->pIfIo, pExtent->pFile->pStorage,
5927 VMDK_SECTOR2BYTE(uSectorExtentAbs),
5928 pIoCtx, cbToWrite, NULL, NULL);
5929 }
5930 }
5931 break;
5932 case VMDKETYPE_VMFS:
5933 case VMDKETYPE_FLAT:
5934 /* Clip write range to remain in this extent. */
5935 cbToWrite = RT_MIN(cbToWrite, VMDK_SECTOR2BYTE(pExtent->uSectorOffset + pExtent->cNominalSectors - uSectorExtentRel));
5936 rc = vdIfIoIntFileWriteUser(pImage->pIfIo, pExtent->pFile->pStorage,
5937 VMDK_SECTOR2BYTE(uSectorExtentRel),
5938 pIoCtx, cbToWrite, NULL, NULL);
5939 break;
5940 case VMDKETYPE_ZERO:
5941 /* Clip write range to remain in this extent. */
5942 cbToWrite = RT_MIN(cbToWrite, VMDK_SECTOR2BYTE(pExtent->uSectorOffset + pExtent->cNominalSectors - uSectorExtentRel));
5943 break;
5944 }
5945
5946 if (pcbWriteProcess)
5947 *pcbWriteProcess = cbToWrite;
5948
5949out:
5950 LogFlowFunc(("returns %Rrc\n", rc));
5951 return rc;
5952}
5953
5954/** @copydoc VBOXHDDBACKEND::pfnFlush */
5955static int vmdkFlush(void *pBackendData, PVDIOCTX pIoCtx)
5956{
5957 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5958
5959 return vmdkFlushImage(pImage, pIoCtx);
5960}
5961
5962/** @copydoc VBOXHDDBACKEND::pfnGetVersion */
5963static unsigned vmdkGetVersion(void *pBackendData)
5964{
5965 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
5966 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5967
5968 AssertPtr(pImage);
5969
5970 if (pImage)
5971 return VMDK_IMAGE_VERSION;
5972 else
5973 return 0;
5974}
5975
5976/** @copydoc VBOXHDDBACKEND::pfnGetSize */
5977static uint64_t vmdkGetSize(void *pBackendData)
5978{
5979 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
5980 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5981
5982 AssertPtr(pImage);
5983
5984 if (pImage)
5985 return pImage->cbSize;
5986 else
5987 return 0;
5988}
5989
5990/** @copydoc VBOXHDDBACKEND::pfnGetFileSize */
5991static uint64_t vmdkGetFileSize(void *pBackendData)
5992{
5993 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
5994 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5995 uint64_t cb = 0;
5996
5997 AssertPtr(pImage);
5998
5999 if (pImage)
6000 {
6001 uint64_t cbFile;
6002 if (pImage->pFile != NULL)
6003 {
6004 int rc = vdIfIoIntFileGetSize(pImage->pIfIo, pImage->pFile->pStorage, &cbFile);
6005 if (RT_SUCCESS(rc))
6006 cb += cbFile;
6007 }
6008 for (unsigned i = 0; i < pImage->cExtents; i++)
6009 {
6010 if (pImage->pExtents[i].pFile != NULL)
6011 {
6012 int rc = vdIfIoIntFileGetSize(pImage->pIfIo, pImage->pExtents[i].pFile->pStorage, &cbFile);
6013 if (RT_SUCCESS(rc))
6014 cb += cbFile;
6015 }
6016 }
6017 }
6018
6019 LogFlowFunc(("returns %lld\n", cb));
6020 return cb;
6021}
6022
6023/** @copydoc VBOXHDDBACKEND::pfnGetPCHSGeometry */
6024static int vmdkGetPCHSGeometry(void *pBackendData, PVDGEOMETRY pPCHSGeometry)
6025{
6026 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p\n", pBackendData, pPCHSGeometry));
6027 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6028 int rc;
6029
6030 AssertPtr(pImage);
6031
6032 if (pImage)
6033 {
6034 if (pImage->PCHSGeometry.cCylinders)
6035 {
6036 *pPCHSGeometry = pImage->PCHSGeometry;
6037 rc = VINF_SUCCESS;
6038 }
6039 else
6040 rc = VERR_VD_GEOMETRY_NOT_SET;
6041 }
6042 else
6043 rc = VERR_VD_NOT_OPENED;
6044
6045 LogFlowFunc(("returns %Rrc (PCHS=%u/%u/%u)\n", rc, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
6046 return rc;
6047}
6048
6049/** @copydoc VBOXHDDBACKEND::pfnSetPCHSGeometry */
6050static int vmdkSetPCHSGeometry(void *pBackendData, PCVDGEOMETRY pPCHSGeometry)
6051{
6052 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p PCHS=%u/%u/%u\n", pBackendData, pPCHSGeometry, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
6053 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6054 int rc;
6055
6056 AssertPtr(pImage);
6057
6058 if (pImage)
6059 {
6060 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
6061 {
6062 rc = VERR_VD_IMAGE_READ_ONLY;
6063 goto out;
6064 }
6065 if (pImage->uOpenFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
6066 {
6067 rc = VERR_NOT_SUPPORTED;
6068 goto out;
6069 }
6070 rc = vmdkDescSetPCHSGeometry(pImage, pPCHSGeometry);
6071 if (RT_FAILURE(rc))
6072 goto out;
6073
6074 pImage->PCHSGeometry = *pPCHSGeometry;
6075 rc = VINF_SUCCESS;
6076 }
6077 else
6078 rc = VERR_VD_NOT_OPENED;
6079
6080out:
6081 LogFlowFunc(("returns %Rrc\n", rc));
6082 return rc;
6083}
6084
6085/** @copydoc VBOXHDDBACKEND::pfnGetLCHSGeometry */
6086static int vmdkGetLCHSGeometry(void *pBackendData, PVDGEOMETRY pLCHSGeometry)
6087{
6088 LogFlowFunc(("pBackendData=%#p pLCHSGeometry=%#p\n", pBackendData, pLCHSGeometry));
6089 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6090 int rc;
6091
6092 AssertPtr(pImage);
6093
6094 if (pImage)
6095 {
6096 if (pImage->LCHSGeometry.cCylinders)
6097 {
6098 *pLCHSGeometry = pImage->LCHSGeometry;
6099 rc = VINF_SUCCESS;
6100 }
6101 else
6102 rc = VERR_VD_GEOMETRY_NOT_SET;
6103 }
6104 else
6105 rc = VERR_VD_NOT_OPENED;
6106
6107 LogFlowFunc(("returns %Rrc (LCHS=%u/%u/%u)\n", rc, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
6108 return rc;
6109}
6110
6111/** @copydoc VBOXHDDBACKEND::pfnSetLCHSGeometry */
6112static int vmdkSetLCHSGeometry(void *pBackendData, PCVDGEOMETRY pLCHSGeometry)
6113{
6114 LogFlowFunc(("pBackendData=%#p pLCHSGeometry=%#p LCHS=%u/%u/%u\n", pBackendData, pLCHSGeometry, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
6115 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6116 int rc;
6117
6118 AssertPtr(pImage);
6119
6120 if (pImage)
6121 {
6122 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
6123 {
6124 rc = VERR_VD_IMAGE_READ_ONLY;
6125 goto out;
6126 }
6127 if (pImage->uOpenFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
6128 {
6129 rc = VERR_NOT_SUPPORTED;
6130 goto out;
6131 }
6132 rc = vmdkDescSetLCHSGeometry(pImage, pLCHSGeometry);
6133 if (RT_FAILURE(rc))
6134 goto out;
6135
6136 pImage->LCHSGeometry = *pLCHSGeometry;
6137 rc = VINF_SUCCESS;
6138 }
6139 else
6140 rc = VERR_VD_NOT_OPENED;
6141
6142out:
6143 LogFlowFunc(("returns %Rrc\n", rc));
6144 return rc;
6145}
6146
6147/** @copydoc VBOXHDDBACKEND::pfnGetImageFlags */
6148static unsigned vmdkGetImageFlags(void *pBackendData)
6149{
6150 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
6151 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6152 unsigned uImageFlags;
6153
6154 AssertPtr(pImage);
6155
6156 if (pImage)
6157 uImageFlags = pImage->uImageFlags;
6158 else
6159 uImageFlags = 0;
6160
6161 LogFlowFunc(("returns %#x\n", uImageFlags));
6162 return uImageFlags;
6163}
6164
6165/** @copydoc VBOXHDDBACKEND::pfnGetOpenFlags */
6166static unsigned vmdkGetOpenFlags(void *pBackendData)
6167{
6168 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
6169 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6170 unsigned uOpenFlags;
6171
6172 AssertPtr(pImage);
6173
6174 if (pImage)
6175 uOpenFlags = pImage->uOpenFlags;
6176 else
6177 uOpenFlags = 0;
6178
6179 LogFlowFunc(("returns %#x\n", uOpenFlags));
6180 return uOpenFlags;
6181}
6182
6183/** @copydoc VBOXHDDBACKEND::pfnSetOpenFlags */
6184static int vmdkSetOpenFlags(void *pBackendData, unsigned uOpenFlags)
6185{
6186 LogFlowFunc(("pBackendData=%#p uOpenFlags=%#x\n", pBackendData, uOpenFlags));
6187 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6188 int rc;
6189
6190 /* Image must be opened and the new flags must be valid. */
6191 if (!pImage || (uOpenFlags & ~( VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO
6192 | VD_OPEN_FLAGS_ASYNC_IO | VD_OPEN_FLAGS_SHAREABLE
6193 | VD_OPEN_FLAGS_SEQUENTIAL | VD_OPEN_FLAGS_SKIP_CONSISTENCY_CHECKS)))
6194 {
6195 rc = VERR_INVALID_PARAMETER;
6196 goto out;
6197 }
6198
6199 /* StreamOptimized images need special treatment: reopen is prohibited. */
6200 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
6201 {
6202 if (pImage->uOpenFlags == uOpenFlags)
6203 rc = VINF_SUCCESS;
6204 else
6205 rc = VERR_INVALID_PARAMETER;
6206 }
6207 else
6208 {
6209 /* Implement this operation via reopening the image. */
6210 vmdkFreeImage(pImage, false);
6211 rc = vmdkOpenImage(pImage, uOpenFlags);
6212 }
6213
6214out:
6215 LogFlowFunc(("returns %Rrc\n", rc));
6216 return rc;
6217}
6218
6219/** @copydoc VBOXHDDBACKEND::pfnGetComment */
6220static int vmdkGetComment(void *pBackendData, char *pszComment,
6221 size_t cbComment)
6222{
6223 LogFlowFunc(("pBackendData=%#p pszComment=%#p cbComment=%zu\n", pBackendData, pszComment, cbComment));
6224 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6225 int rc;
6226
6227 AssertPtr(pImage);
6228
6229 if (pImage)
6230 {
6231 const char *pszCommentEncoded = NULL;
6232 rc = vmdkDescDDBGetStr(pImage, &pImage->Descriptor,
6233 "ddb.comment", &pszCommentEncoded);
6234 if (rc == VERR_VD_VMDK_VALUE_NOT_FOUND)
6235 pszCommentEncoded = NULL;
6236 else if (RT_FAILURE(rc))
6237 goto out;
6238
6239 if (pszComment && pszCommentEncoded)
6240 rc = vmdkDecodeString(pszCommentEncoded, pszComment, cbComment);
6241 else
6242 {
6243 if (pszComment)
6244 *pszComment = '\0';
6245 rc = VINF_SUCCESS;
6246 }
6247 if (pszCommentEncoded)
6248 RTStrFree((char *)(void *)pszCommentEncoded);
6249 }
6250 else
6251 rc = VERR_VD_NOT_OPENED;
6252
6253out:
6254 LogFlowFunc(("returns %Rrc comment='%s'\n", rc, pszComment));
6255 return rc;
6256}
6257
6258/** @copydoc VBOXHDDBACKEND::pfnSetComment */
6259static int vmdkSetComment(void *pBackendData, const char *pszComment)
6260{
6261 LogFlowFunc(("pBackendData=%#p pszComment=\"%s\"\n", pBackendData, pszComment));
6262 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6263 int rc;
6264
6265 AssertPtr(pImage);
6266
6267 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
6268 {
6269 rc = VERR_VD_IMAGE_READ_ONLY;
6270 goto out;
6271 }
6272 if (pImage->uOpenFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
6273 {
6274 rc = VERR_NOT_SUPPORTED;
6275 goto out;
6276 }
6277
6278 if (pImage)
6279 rc = vmdkSetImageComment(pImage, pszComment);
6280 else
6281 rc = VERR_VD_NOT_OPENED;
6282
6283out:
6284 LogFlowFunc(("returns %Rrc\n", rc));
6285 return rc;
6286}
6287
6288/** @copydoc VBOXHDDBACKEND::pfnGetUuid */
6289static int vmdkGetUuid(void *pBackendData, PRTUUID pUuid)
6290{
6291 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
6292 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6293 int rc;
6294
6295 AssertPtr(pImage);
6296
6297 if (pImage)
6298 {
6299 *pUuid = pImage->ImageUuid;
6300 rc = VINF_SUCCESS;
6301 }
6302 else
6303 rc = VERR_VD_NOT_OPENED;
6304
6305 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
6306 return rc;
6307}
6308
6309/** @copydoc VBOXHDDBACKEND::pfnSetUuid */
6310static int vmdkSetUuid(void *pBackendData, PCRTUUID pUuid)
6311{
6312 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
6313 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6314 int rc;
6315
6316 LogFlowFunc(("%RTuuid\n", pUuid));
6317 AssertPtr(pImage);
6318
6319 if (pImage)
6320 {
6321 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
6322 {
6323 if (!(pImage->uOpenFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED))
6324 {
6325 pImage->ImageUuid = *pUuid;
6326 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
6327 VMDK_DDB_IMAGE_UUID, pUuid);
6328 if (RT_FAILURE(rc))
6329 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error storing image UUID in descriptor in '%s'"), pImage->pszFilename);
6330 rc = VINF_SUCCESS;
6331 }
6332 else
6333 rc = VERR_NOT_SUPPORTED;
6334 }
6335 else
6336 rc = VERR_VD_IMAGE_READ_ONLY;
6337 }
6338 else
6339 rc = VERR_VD_NOT_OPENED;
6340
6341 LogFlowFunc(("returns %Rrc\n", rc));
6342 return rc;
6343}
6344
6345/** @copydoc VBOXHDDBACKEND::pfnGetModificationUuid */
6346static int vmdkGetModificationUuid(void *pBackendData, PRTUUID pUuid)
6347{
6348 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
6349 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6350 int rc;
6351
6352 AssertPtr(pImage);
6353
6354 if (pImage)
6355 {
6356 *pUuid = pImage->ModificationUuid;
6357 rc = VINF_SUCCESS;
6358 }
6359 else
6360 rc = VERR_VD_NOT_OPENED;
6361
6362 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
6363 return rc;
6364}
6365
6366/** @copydoc VBOXHDDBACKEND::pfnSetModificationUuid */
6367static int vmdkSetModificationUuid(void *pBackendData, PCRTUUID pUuid)
6368{
6369 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
6370 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6371 int rc;
6372
6373 AssertPtr(pImage);
6374
6375 if (pImage)
6376 {
6377 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
6378 {
6379 if (!(pImage->uOpenFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED))
6380 {
6381 /* Only touch the modification uuid if it changed. */
6382 if (RTUuidCompare(&pImage->ModificationUuid, pUuid))
6383 {
6384 pImage->ModificationUuid = *pUuid;
6385 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
6386 VMDK_DDB_MODIFICATION_UUID, pUuid);
6387 if (RT_FAILURE(rc))
6388 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error storing modification UUID in descriptor in '%s'"), pImage->pszFilename);
6389 }
6390 rc = VINF_SUCCESS;
6391 }
6392 else
6393 rc = VERR_NOT_SUPPORTED;
6394 }
6395 else
6396 rc = VERR_VD_IMAGE_READ_ONLY;
6397 }
6398 else
6399 rc = VERR_VD_NOT_OPENED;
6400
6401 LogFlowFunc(("returns %Rrc\n", rc));
6402 return rc;
6403}
6404
6405/** @copydoc VBOXHDDBACKEND::pfnGetParentUuid */
6406static int vmdkGetParentUuid(void *pBackendData, PRTUUID pUuid)
6407{
6408 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
6409 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6410 int rc;
6411
6412 AssertPtr(pImage);
6413
6414 if (pImage)
6415 {
6416 *pUuid = pImage->ParentUuid;
6417 rc = VINF_SUCCESS;
6418 }
6419 else
6420 rc = VERR_VD_NOT_OPENED;
6421
6422 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
6423 return rc;
6424}
6425
6426/** @copydoc VBOXHDDBACKEND::pfnSetParentUuid */
6427static int vmdkSetParentUuid(void *pBackendData, PCRTUUID pUuid)
6428{
6429 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
6430 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6431 int rc;
6432
6433 AssertPtr(pImage);
6434
6435 if (pImage)
6436 {
6437 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
6438 {
6439 if (!(pImage->uOpenFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED))
6440 {
6441 pImage->ParentUuid = *pUuid;
6442 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
6443 VMDK_DDB_PARENT_UUID, pUuid);
6444 if (RT_FAILURE(rc))
6445 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error storing parent image UUID in descriptor in '%s'"), pImage->pszFilename);
6446 rc = VINF_SUCCESS;
6447 }
6448 else
6449 rc = VERR_NOT_SUPPORTED;
6450 }
6451 else
6452 rc = VERR_VD_IMAGE_READ_ONLY;
6453 }
6454 else
6455 rc = VERR_VD_NOT_OPENED;
6456
6457 LogFlowFunc(("returns %Rrc\n", rc));
6458 return rc;
6459}
6460
6461/** @copydoc VBOXHDDBACKEND::pfnGetParentModificationUuid */
6462static int vmdkGetParentModificationUuid(void *pBackendData, PRTUUID pUuid)
6463{
6464 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
6465 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6466 int rc;
6467
6468 AssertPtr(pImage);
6469
6470 if (pImage)
6471 {
6472 *pUuid = pImage->ParentModificationUuid;
6473 rc = VINF_SUCCESS;
6474 }
6475 else
6476 rc = VERR_VD_NOT_OPENED;
6477
6478 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
6479 return rc;
6480}
6481
6482/** @copydoc VBOXHDDBACKEND::pfnSetParentModificationUuid */
6483static int vmdkSetParentModificationUuid(void *pBackendData, PCRTUUID pUuid)
6484{
6485 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
6486 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6487 int rc;
6488
6489 AssertPtr(pImage);
6490
6491 if (pImage)
6492 {
6493 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
6494 {
6495 if (!(pImage->uOpenFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED))
6496 {
6497 pImage->ParentModificationUuid = *pUuid;
6498 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
6499 VMDK_DDB_PARENT_MODIFICATION_UUID, pUuid);
6500 if (RT_FAILURE(rc))
6501 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error storing parent image UUID in descriptor in '%s'"), pImage->pszFilename);
6502 rc = VINF_SUCCESS;
6503 }
6504 else
6505 rc = VERR_NOT_SUPPORTED;
6506 }
6507 else
6508 rc = VERR_VD_IMAGE_READ_ONLY;
6509 }
6510 else
6511 rc = VERR_VD_NOT_OPENED;
6512
6513 LogFlowFunc(("returns %Rrc\n", rc));
6514 return rc;
6515}
6516
6517/** @copydoc VBOXHDDBACKEND::pfnDump */
6518static void vmdkDump(void *pBackendData)
6519{
6520 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
6521
6522 AssertPtr(pImage);
6523 if (pImage)
6524 {
6525 vdIfErrorMessage(pImage->pIfError, "Header: Geometry PCHS=%u/%u/%u LCHS=%u/%u/%u cbSector=%llu\n",
6526 pImage->PCHSGeometry.cCylinders, pImage->PCHSGeometry.cHeads, pImage->PCHSGeometry.cSectors,
6527 pImage->LCHSGeometry.cCylinders, pImage->LCHSGeometry.cHeads, pImage->LCHSGeometry.cSectors,
6528 VMDK_BYTE2SECTOR(pImage->cbSize));
6529 vdIfErrorMessage(pImage->pIfError, "Header: uuidCreation={%RTuuid}\n", &pImage->ImageUuid);
6530 vdIfErrorMessage(pImage->pIfError, "Header: uuidModification={%RTuuid}\n", &pImage->ModificationUuid);
6531 vdIfErrorMessage(pImage->pIfError, "Header: uuidParent={%RTuuid}\n", &pImage->ParentUuid);
6532 vdIfErrorMessage(pImage->pIfError, "Header: uuidParentModification={%RTuuid}\n", &pImage->ParentModificationUuid);
6533 }
6534}
6535
6536
6537
6538VBOXHDDBACKEND g_VmdkBackend =
6539{
6540 /* pszBackendName */
6541 "VMDK",
6542 /* cbSize */
6543 sizeof(VBOXHDDBACKEND),
6544 /* uBackendCaps */
6545 VD_CAP_UUID | VD_CAP_CREATE_FIXED | VD_CAP_CREATE_DYNAMIC
6546 | VD_CAP_CREATE_SPLIT_2G | VD_CAP_DIFF | VD_CAP_FILE | VD_CAP_ASYNC
6547 | VD_CAP_VFS,
6548 /* paFileExtensions */
6549 s_aVmdkFileExtensions,
6550 /* paConfigInfo */
6551 NULL,
6552 /* hPlugin */
6553 NIL_RTLDRMOD,
6554 /* pfnCheckIfValid */
6555 vmdkCheckIfValid,
6556 /* pfnOpen */
6557 vmdkOpen,
6558 /* pfnCreate */
6559 vmdkCreate,
6560 /* pfnRename */
6561 vmdkRename,
6562 /* pfnClose */
6563 vmdkClose,
6564 /* pfnRead */
6565 vmdkRead,
6566 /* pfnWrite */
6567 vmdkWrite,
6568 /* pfnFlush */
6569 vmdkFlush,
6570 /* pfnDiscard */
6571 NULL,
6572 /* pfnGetVersion */
6573 vmdkGetVersion,
6574 /* pfnGetSize */
6575 vmdkGetSize,
6576 /* pfnGetFileSize */
6577 vmdkGetFileSize,
6578 /* pfnGetPCHSGeometry */
6579 vmdkGetPCHSGeometry,
6580 /* pfnSetPCHSGeometry */
6581 vmdkSetPCHSGeometry,
6582 /* pfnGetLCHSGeometry */
6583 vmdkGetLCHSGeometry,
6584 /* pfnSetLCHSGeometry */
6585 vmdkSetLCHSGeometry,
6586 /* pfnGetImageFlags */
6587 vmdkGetImageFlags,
6588 /* pfnGetOpenFlags */
6589 vmdkGetOpenFlags,
6590 /* pfnSetOpenFlags */
6591 vmdkSetOpenFlags,
6592 /* pfnGetComment */
6593 vmdkGetComment,
6594 /* pfnSetComment */
6595 vmdkSetComment,
6596 /* pfnGetUuid */
6597 vmdkGetUuid,
6598 /* pfnSetUuid */
6599 vmdkSetUuid,
6600 /* pfnGetModificationUuid */
6601 vmdkGetModificationUuid,
6602 /* pfnSetModificationUuid */
6603 vmdkSetModificationUuid,
6604 /* pfnGetParentUuid */
6605 vmdkGetParentUuid,
6606 /* pfnSetParentUuid */
6607 vmdkSetParentUuid,
6608 /* pfnGetParentModificationUuid */
6609 vmdkGetParentModificationUuid,
6610 /* pfnSetParentModificationUuid */
6611 vmdkSetParentModificationUuid,
6612 /* pfnDump */
6613 vmdkDump,
6614 /* pfnGetTimeStamp */
6615 NULL,
6616 /* pfnGetParentTimeStamp */
6617 NULL,
6618 /* pfnSetParentTimeStamp */
6619 NULL,
6620 /* pfnGetParentFilename */
6621 NULL,
6622 /* pfnSetParentFilename */
6623 NULL,
6624 /* pfnComposeLocation */
6625 genericFileComposeLocation,
6626 /* pfnComposeName */
6627 genericFileComposeName,
6628 /* pfnCompact */
6629 NULL,
6630 /* pfnResize */
6631 NULL,
6632 /* pfnRepair */
6633 NULL
6634};
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