VirtualBox

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

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

Storage: Error formatting fixes.

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