VirtualBox

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

Last change on this file since 54934 was 54430, checked in by vboxsync, 10 years ago

Storage/VD: make use of the image type (hdd/dvd/floppy) for sanity checking when creating disk images

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

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