VirtualBox

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

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

Storage/VMDK: write the compressed block size to the marker.

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