VirtualBox

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

Last change on this file since 63001 was 62757, checked in by vboxsync, 8 years ago

vmdkDescSetStr: why bother skipping blanks after '='?

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