VirtualBox

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

Last change on this file since 59455 was 59455, checked in by vboxsync, 9 years ago

Storage/VD: Remove the custom code in each backend which allocates all blocks in a fixed size image by writing zeros to it. Preparations to make use of more optimized methods to allocate large files on recent hosts (fallocate() and friends)

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette