VirtualBox

source: vbox/trunk/src/VBox/Devices/Storage/VmdkHDDCore.cpp@ 17847

Last change on this file since 17847 was 17847, checked in by vboxsync, 16 years ago

Storage/VMDK: put decompression buffer allocation in a place where the information is known, plug a few memory leaks in error situations.

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

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