VirtualBox

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

Last change on this file since 69036 was 69036, checked in by vboxsync, 7 years ago

bugref:9014. Fixed the error from changeset r110635.

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