VirtualBox

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

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

Storage/VMDK: Make the descriptor bigger if it is unreasonably small and we might want to add more data to it.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 218.0 KB
Line 
1/* $Id: VmdkHDDCore.cpp 18179 2009-03-24 13:25:13Z 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.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * 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 /** Flag whether there is a footer in this extent. */
307 bool fFooter;
308 /** Compression type for this extent. */
309 uint16_t uCompression;
310 /** Last grain which has been written to. Only for streamOptimized extents. */
311 uint32_t uLastGrainWritten;
312 /** Sector number of last grain which has been written to. Only for
313 * streamOptimized extents. */
314 uint32_t uLastGrainSector;
315 /** Data size of last grain which has been written to. Only for
316 * streamOptimized extents. */
317 uint32_t cbLastGrainWritten;
318 /** Starting sector of the decompressed grain buffer. */
319 uint32_t uGrainSector;
320 /** Decompressed grain buffer for streamOptimized extents. */
321 void *pvGrain;
322 /** Reference to the image in which this extent is used. Do not use this
323 * on a regular basis to avoid passing pImage references to functions
324 * explicitly. */
325 struct VMDKIMAGE *pImage;
326} VMDKEXTENT, *PVMDKEXTENT;
327
328/**
329 * Grain table cache size. Allocated per image.
330 */
331#define VMDK_GT_CACHE_SIZE 256
332
333/**
334 * Grain table block size. Smaller than an actual grain table block to allow
335 * more grain table blocks to be cached without having to allocate excessive
336 * amounts of memory for the cache.
337 */
338#define VMDK_GT_CACHELINE_SIZE 128
339
340
341/**
342 * Maximum number of lines in a descriptor file. Not worth the effort of
343 * making it variable. Descriptor files are generally very short (~20 lines).
344 */
345#define VMDK_DESCRIPTOR_LINES_MAX 100U
346
347/**
348 * Parsed descriptor information. Allows easy access and update of the
349 * descriptor (whether separate file or not). Free form text files suck.
350 */
351typedef struct VMDKDESCRIPTOR
352{
353 /** Line number of first entry of the disk descriptor. */
354 unsigned uFirstDesc;
355 /** Line number of first entry in the extent description. */
356 unsigned uFirstExtent;
357 /** Line number of first disk database entry. */
358 unsigned uFirstDDB;
359 /** Total number of lines. */
360 unsigned cLines;
361 /** Total amount of memory available for the descriptor. */
362 size_t cbDescAlloc;
363 /** Set if descriptor has been changed and not yet written to disk. */
364 bool fDirty;
365 /** Array of pointers to the data in the descriptor. */
366 char *aLines[VMDK_DESCRIPTOR_LINES_MAX];
367 /** Array of line indices pointing to the next non-comment line. */
368 unsigned aNextLines[VMDK_DESCRIPTOR_LINES_MAX];
369} VMDKDESCRIPTOR, *PVMDKDESCRIPTOR;
370
371
372/**
373 * Cache entry for translating extent/sector to a sector number in that
374 * extent.
375 */
376typedef struct VMDKGTCACHEENTRY
377{
378 /** Extent number for which this entry is valid. */
379 uint32_t uExtent;
380 /** GT data block number. */
381 uint64_t uGTBlock;
382 /** Data part of the cache entry. */
383 uint32_t aGTData[VMDK_GT_CACHELINE_SIZE];
384} VMDKGTCACHEENTRY, *PVMDKGTCACHEENTRY;
385
386/**
387 * Cache data structure for blocks of grain table entries. For now this is a
388 * fixed size direct mapping cache, but this should be adapted to the size of
389 * the sparse image and maybe converted to a set-associative cache. The
390 * implementation below implements a write-through cache with write allocate.
391 */
392typedef struct VMDKGTCACHE
393{
394 /** Cache entries. */
395 VMDKGTCACHEENTRY aGTCache[VMDK_GT_CACHE_SIZE];
396 /** Number of cache entries (currently unused). */
397 unsigned cEntries;
398} VMDKGTCACHE, *PVMDKGTCACHE;
399
400/**
401 * Complete VMDK image data structure. Mainly a collection of extents and a few
402 * extra global data fields.
403 */
404typedef struct VMDKIMAGE
405{
406 /** Pointer to the image extents. */
407 PVMDKEXTENT pExtents;
408 /** Number of image extents. */
409 unsigned cExtents;
410 /** Pointer to the files list, for opening a file referenced multiple
411 * times only once (happens mainly with raw partition access). */
412 PVMDKFILE pFiles;
413
414 /** Base image name. */
415 const char *pszFilename;
416 /** Descriptor file if applicable. */
417 PVMDKFILE pFile;
418
419 /** Pointer to the per-disk VD interface list. */
420 PVDINTERFACE pVDIfsDisk;
421
422 /** Error interface. */
423 PVDINTERFACE pInterfaceError;
424 /** Error interface callbacks. */
425 PVDINTERFACEERROR pInterfaceErrorCallbacks;
426
427 /** Async I/O interface. */
428 PVDINTERFACE pInterfaceAsyncIO;
429 /** Async I/O interface callbacks. */
430 PVDINTERFACEASYNCIO pInterfaceAsyncIOCallbacks;
431 /**
432 * Pointer to an array of task handles for task submission.
433 * This is an optimization because the task number to submit is not known
434 * and allocating/freeing an array in the read/write functions every time
435 * is too expensive.
436 */
437 void **apTask;
438 /** Entries available in the task handle array. */
439 unsigned cTask;
440
441 /** Open flags passed by VBoxHD layer. */
442 unsigned uOpenFlags;
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 RTStrFree((char *)(void *)pszCreateType);
2066
2067 /* Count the number of extent config entries. */
2068 for (uLine = pImage->Descriptor.uFirstExtent, cExtents = 0;
2069 uLine != 0;
2070 uLine = pImage->Descriptor.aNextLines[uLine], cExtents++)
2071 /* nothing */;
2072
2073 if (!pImage->pDescData && cExtents != 1)
2074 {
2075 /* Monolithic image, must have only one extent (already opened). */
2076 return vmdkError(pImage, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: monolithic image may only have one extent in '%s'"), pImage->pszFilename);
2077 }
2078
2079 if (pImage->pDescData)
2080 {
2081 /* Non-monolithic image, extents need to be allocated. */
2082 rc = vmdkCreateExtents(pImage, cExtents);
2083 if (RT_FAILURE(rc))
2084 return rc;
2085 }
2086
2087 for (unsigned i = 0, uLine = pImage->Descriptor.uFirstExtent;
2088 i < cExtents; i++, uLine = pImage->Descriptor.aNextLines[uLine])
2089 {
2090 char *pszLine = pImage->Descriptor.aLines[uLine];
2091
2092 /* Access type of the extent. */
2093 if (!strncmp(pszLine, "RW", 2))
2094 {
2095 pImage->pExtents[i].enmAccess = VMDKACCESS_READWRITE;
2096 pszLine += 2;
2097 }
2098 else if (!strncmp(pszLine, "RDONLY", 6))
2099 {
2100 pImage->pExtents[i].enmAccess = VMDKACCESS_READONLY;
2101 pszLine += 6;
2102 }
2103 else if (!strncmp(pszLine, "NOACCESS", 8))
2104 {
2105 pImage->pExtents[i].enmAccess = VMDKACCESS_NOACCESS;
2106 pszLine += 8;
2107 }
2108 else
2109 return vmdkError(pImage, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: parse error in extent description in '%s'"), pImage->pszFilename);
2110 if (*pszLine++ != ' ')
2111 return vmdkError(pImage, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: parse error in extent description in '%s'"), pImage->pszFilename);
2112
2113 /* Nominal size of the extent. */
2114 rc = RTStrToUInt64Ex(pszLine, &pszLine, 10,
2115 &pImage->pExtents[i].cNominalSectors);
2116 if (RT_FAILURE(rc))
2117 return vmdkError(pImage, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: parse error in extent description in '%s'"), pImage->pszFilename);
2118 if (*pszLine++ != ' ')
2119 return vmdkError(pImage, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: parse error in extent description in '%s'"), pImage->pszFilename);
2120
2121 /* Type of the extent. */
2122#ifdef VBOX_WITH_VMDK_ESX
2123 /** @todo Add the ESX extent types. Not necessary for now because
2124 * the ESX extent types are only used inside an ESX server. They are
2125 * automatically converted if the VMDK is exported. */
2126#endif /* VBOX_WITH_VMDK_ESX */
2127 if (!strncmp(pszLine, "SPARSE", 6))
2128 {
2129 pImage->pExtents[i].enmType = VMDKETYPE_HOSTED_SPARSE;
2130 pszLine += 6;
2131 }
2132 else if (!strncmp(pszLine, "FLAT", 4))
2133 {
2134 pImage->pExtents[i].enmType = VMDKETYPE_FLAT;
2135 pszLine += 4;
2136 }
2137 else if (!strncmp(pszLine, "ZERO", 4))
2138 {
2139 pImage->pExtents[i].enmType = VMDKETYPE_ZERO;
2140 pszLine += 4;
2141 }
2142 else
2143 return vmdkError(pImage, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: parse error in extent description in '%s'"), pImage->pszFilename);
2144 if (pImage->pExtents[i].enmType == VMDKETYPE_ZERO)
2145 {
2146 /* This one has no basename or offset. */
2147 if (*pszLine == ' ')
2148 pszLine++;
2149 if (*pszLine != '\0')
2150 return vmdkError(pImage, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: parse error in extent description in '%s'"), pImage->pszFilename);
2151 pImage->pExtents[i].pszBasename = NULL;
2152 }
2153 else
2154 {
2155 /* All other extent types have basename and optional offset. */
2156 if (*pszLine++ != ' ')
2157 return vmdkError(pImage, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: parse error in extent description in '%s'"), pImage->pszFilename);
2158
2159 /* Basename of the image. Surrounded by quotes. */
2160 char *pszBasename;
2161 rc = vmdkStringUnquote(pImage, pszLine, &pszBasename, &pszLine);
2162 if (RT_FAILURE(rc))
2163 return rc;
2164 pImage->pExtents[i].pszBasename = pszBasename;
2165 if (*pszLine == ' ')
2166 {
2167 pszLine++;
2168 if (*pszLine != '\0')
2169 {
2170 /* Optional offset in extent specified. */
2171 rc = RTStrToUInt64Ex(pszLine, &pszLine, 10,
2172 &pImage->pExtents[i].uSectorOffset);
2173 if (RT_FAILURE(rc))
2174 return vmdkError(pImage, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: parse error in extent description in '%s'"), pImage->pszFilename);
2175 }
2176 }
2177
2178 if (*pszLine != '\0')
2179 return vmdkError(pImage, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: parse error in extent description in '%s'"), pImage->pszFilename);
2180 }
2181 }
2182
2183 /* Determine PCHS geometry (autogenerate if necessary). */
2184 rc = vmdkDescDDBGetU32(pImage, &pImage->Descriptor,
2185 VMDK_DDB_GEO_PCHS_CYLINDERS,
2186 &pImage->PCHSGeometry.cCylinders);
2187 if (rc == VERR_VD_VMDK_VALUE_NOT_FOUND)
2188 pImage->PCHSGeometry.cCylinders = 0;
2189 else if (RT_FAILURE(rc))
2190 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error getting PCHS geometry from extent description in '%s'"), pImage->pszFilename);
2191 rc = vmdkDescDDBGetU32(pImage, &pImage->Descriptor,
2192 VMDK_DDB_GEO_PCHS_HEADS,
2193 &pImage->PCHSGeometry.cHeads);
2194 if (rc == VERR_VD_VMDK_VALUE_NOT_FOUND)
2195 pImage->PCHSGeometry.cHeads = 0;
2196 else if (RT_FAILURE(rc))
2197 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error getting PCHS geometry from extent description in '%s'"), pImage->pszFilename);
2198 rc = vmdkDescDDBGetU32(pImage, &pImage->Descriptor,
2199 VMDK_DDB_GEO_PCHS_SECTORS,
2200 &pImage->PCHSGeometry.cSectors);
2201 if (rc == VERR_VD_VMDK_VALUE_NOT_FOUND)
2202 pImage->PCHSGeometry.cSectors = 0;
2203 else if (RT_FAILURE(rc))
2204 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error getting PCHS geometry from extent description in '%s'"), pImage->pszFilename);
2205 if ( pImage->PCHSGeometry.cCylinders == 0
2206 || pImage->PCHSGeometry.cHeads == 0
2207 || pImage->PCHSGeometry.cHeads > 16
2208 || pImage->PCHSGeometry.cSectors == 0
2209 || pImage->PCHSGeometry.cSectors > 63)
2210 {
2211 /* Mark PCHS geometry as not yet valid (can't do the calculation here
2212 * as the total image size isn't known yet). */
2213 pImage->PCHSGeometry.cCylinders = 0;
2214 pImage->PCHSGeometry.cHeads = 16;
2215 pImage->PCHSGeometry.cSectors = 63;
2216 }
2217
2218 /* Determine LCHS geometry (set to 0 if not specified). */
2219 rc = vmdkDescDDBGetU32(pImage, &pImage->Descriptor,
2220 VMDK_DDB_GEO_LCHS_CYLINDERS,
2221 &pImage->LCHSGeometry.cCylinders);
2222 if (rc == VERR_VD_VMDK_VALUE_NOT_FOUND)
2223 pImage->LCHSGeometry.cCylinders = 0;
2224 else if (RT_FAILURE(rc))
2225 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error getting LCHS geometry from extent description in '%s'"), pImage->pszFilename);
2226 rc = vmdkDescDDBGetU32(pImage, &pImage->Descriptor,
2227 VMDK_DDB_GEO_LCHS_HEADS,
2228 &pImage->LCHSGeometry.cHeads);
2229 if (rc == VERR_VD_VMDK_VALUE_NOT_FOUND)
2230 pImage->LCHSGeometry.cHeads = 0;
2231 else if (RT_FAILURE(rc))
2232 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error getting LCHS geometry from extent description in '%s'"), pImage->pszFilename);
2233 rc = vmdkDescDDBGetU32(pImage, &pImage->Descriptor,
2234 VMDK_DDB_GEO_LCHS_SECTORS,
2235 &pImage->LCHSGeometry.cSectors);
2236 if (rc == VERR_VD_VMDK_VALUE_NOT_FOUND)
2237 pImage->LCHSGeometry.cSectors = 0;
2238 else if (RT_FAILURE(rc))
2239 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error getting LCHS geometry from extent description in '%s'"), pImage->pszFilename);
2240 if ( pImage->LCHSGeometry.cCylinders == 0
2241 || pImage->LCHSGeometry.cHeads == 0
2242 || pImage->LCHSGeometry.cSectors == 0)
2243 {
2244 pImage->LCHSGeometry.cCylinders = 0;
2245 pImage->LCHSGeometry.cHeads = 0;
2246 pImage->LCHSGeometry.cSectors = 0;
2247 }
2248
2249 /* Get image UUID. */
2250 rc = vmdkDescDDBGetUuid(pImage, &pImage->Descriptor, VMDK_DDB_IMAGE_UUID,
2251 &pImage->ImageUuid);
2252 if (rc == VERR_VD_VMDK_VALUE_NOT_FOUND)
2253 {
2254 /* Image without UUID. Probably created by VMware and not yet used
2255 * by VirtualBox. Can only be added for images opened in read/write
2256 * mode, so don't bother producing a sensible UUID otherwise. */
2257 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2258 RTUuidClear(&pImage->ImageUuid);
2259 else
2260 {
2261 rc = RTUuidCreate(&pImage->ImageUuid);
2262 if (RT_FAILURE(rc))
2263 return rc;
2264 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
2265 VMDK_DDB_IMAGE_UUID, &pImage->ImageUuid);
2266 if (RT_FAILURE(rc))
2267 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error storing image UUID in descriptor in '%s'"), pImage->pszFilename);
2268 }
2269 }
2270 else if (RT_FAILURE(rc))
2271 return rc;
2272
2273 /* Get image modification UUID. */
2274 rc = vmdkDescDDBGetUuid(pImage, &pImage->Descriptor,
2275 VMDK_DDB_MODIFICATION_UUID,
2276 &pImage->ModificationUuid);
2277 if (rc == VERR_VD_VMDK_VALUE_NOT_FOUND)
2278 {
2279 /* Image without UUID. Probably created by VMware and not yet used
2280 * by VirtualBox. Can only be added for images opened in read/write
2281 * mode, so don't bother producing a sensible UUID otherwise. */
2282 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2283 RTUuidClear(&pImage->ModificationUuid);
2284 else
2285 {
2286 rc = RTUuidCreate(&pImage->ModificationUuid);
2287 if (RT_FAILURE(rc))
2288 return rc;
2289 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
2290 VMDK_DDB_MODIFICATION_UUID,
2291 &pImage->ModificationUuid);
2292 if (RT_FAILURE(rc))
2293 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error storing image modification UUID in descriptor in '%s'"), pImage->pszFilename);
2294 }
2295 }
2296 else if (RT_FAILURE(rc))
2297 return rc;
2298
2299 /* Get UUID of parent image. */
2300 rc = vmdkDescDDBGetUuid(pImage, &pImage->Descriptor, VMDK_DDB_PARENT_UUID,
2301 &pImage->ParentUuid);
2302 if (rc == VERR_VD_VMDK_VALUE_NOT_FOUND)
2303 {
2304 /* Image without UUID. Probably created by VMware and not yet used
2305 * by VirtualBox. Can only be added for images opened in read/write
2306 * mode, so don't bother producing a sensible UUID otherwise. */
2307 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2308 RTUuidClear(&pImage->ParentUuid);
2309 else
2310 {
2311 rc = RTUuidClear(&pImage->ParentUuid);
2312 if (RT_FAILURE(rc))
2313 return rc;
2314 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
2315 VMDK_DDB_PARENT_UUID, &pImage->ParentUuid);
2316 if (RT_FAILURE(rc))
2317 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error storing parent UUID in descriptor in '%s'"), pImage->pszFilename);
2318 }
2319 }
2320 else if (RT_FAILURE(rc))
2321 return rc;
2322
2323 /* Get parent image modification UUID. */
2324 rc = vmdkDescDDBGetUuid(pImage, &pImage->Descriptor,
2325 VMDK_DDB_PARENT_MODIFICATION_UUID,
2326 &pImage->ParentModificationUuid);
2327 if (rc == VERR_VD_VMDK_VALUE_NOT_FOUND)
2328 {
2329 /* Image without UUID. Probably created by VMware and not yet used
2330 * by VirtualBox. Can only be added for images opened in read/write
2331 * mode, so don't bother producing a sensible UUID otherwise. */
2332 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2333 RTUuidClear(&pImage->ParentModificationUuid);
2334 else
2335 {
2336 rc = RTUuidCreate(&pImage->ParentModificationUuid);
2337 if (RT_FAILURE(rc))
2338 return rc;
2339 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
2340 VMDK_DDB_PARENT_MODIFICATION_UUID,
2341 &pImage->ParentModificationUuid);
2342 if (RT_FAILURE(rc))
2343 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error storing parent modification UUID in descriptor in '%s'"), pImage->pszFilename);
2344 }
2345 }
2346 else if (RT_FAILURE(rc))
2347 return rc;
2348
2349 return VINF_SUCCESS;
2350}
2351
2352/**
2353 * Internal: write/update the descriptor part of the image.
2354 */
2355static int vmdkWriteDescriptor(PVMDKIMAGE pImage)
2356{
2357 int rc = VINF_SUCCESS;
2358 uint64_t cbLimit;
2359 uint64_t uOffset;
2360 PVMDKFILE pDescFile;
2361
2362 if (pImage->pDescData)
2363 {
2364 /* Separate descriptor file. */
2365 uOffset = 0;
2366 cbLimit = 0;
2367 pDescFile = pImage->pFile;
2368 }
2369 else
2370 {
2371 /* Embedded descriptor file. */
2372 uOffset = VMDK_SECTOR2BYTE(pImage->pExtents[0].uDescriptorSector);
2373 cbLimit = VMDK_SECTOR2BYTE(pImage->pExtents[0].cDescriptorSectors);
2374 cbLimit += uOffset;
2375 pDescFile = pImage->pExtents[0].pFile;
2376 }
2377 /* Bail out if there is no file to write to. */
2378 if (pDescFile == NULL)
2379 return VERR_INVALID_PARAMETER;
2380 for (unsigned i = 0; i < pImage->Descriptor.cLines; i++)
2381 {
2382 const char *psz = pImage->Descriptor.aLines[i];
2383 size_t cb = strlen(psz);
2384
2385 if (cbLimit && uOffset + cb + 1 > cbLimit)
2386 return vmdkError(pImage, VERR_BUFFER_OVERFLOW, RT_SRC_POS, N_("VMDK: descriptor too long in '%s'"), pImage->pszFilename);
2387 rc = vmdkFileWriteAt(pDescFile, uOffset, psz, cb, NULL);
2388 if (RT_FAILURE(rc))
2389 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error writing descriptor in '%s'"), pImage->pszFilename);
2390 uOffset += cb;
2391 rc = vmdkFileWriteAt(pDescFile, uOffset, "\n", 1, NULL);
2392 if (RT_FAILURE(rc))
2393 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error writing descriptor in '%s'"), pImage->pszFilename);
2394 uOffset++;
2395 }
2396 if (cbLimit)
2397 {
2398 /* Inefficient, but simple. */
2399 while (uOffset < cbLimit)
2400 {
2401 rc = vmdkFileWriteAt(pDescFile, uOffset, "", 1, NULL);
2402 if (RT_FAILURE(rc))
2403 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error writing descriptor in '%s'"), pImage->pszFilename);
2404 uOffset++;
2405 }
2406 }
2407 else
2408 {
2409 rc = vmdkFileSetSize(pDescFile, uOffset);
2410 if (RT_FAILURE(rc))
2411 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error truncating descriptor in '%s'"), pImage->pszFilename);
2412 }
2413 pImage->Descriptor.fDirty = false;
2414 return rc;
2415}
2416
2417/**
2418 * Internal: validate the consistency check values in a binary header.
2419 */
2420static int vmdkValidateHeader(PVMDKIMAGE pImage, PVMDKEXTENT pExtent, const SparseExtentHeader *pHeader)
2421{
2422 int rc = VINF_SUCCESS;
2423 if (RT_LE2H_U32(pHeader->magicNumber) != VMDK_SPARSE_MAGICNUMBER)
2424 {
2425 rc = vmdkError(pImage, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: incorrect magic in sparse extent header in '%s'"), pExtent->pszFullname);
2426 return rc;
2427 }
2428 if (RT_LE2H_U32(pHeader->version) != 1 && RT_LE2H_U32(pHeader->version) != 3)
2429 {
2430 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);
2431 return rc;
2432 }
2433 if ( (RT_LE2H_U32(pHeader->flags) & 1)
2434 && ( pHeader->singleEndLineChar != '\n'
2435 || pHeader->nonEndLineChar != ' '
2436 || pHeader->doubleEndLineChar1 != '\r'
2437 || pHeader->doubleEndLineChar2 != '\n') )
2438 {
2439 rc = vmdkError(pImage, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: corrupted by CR/LF translation in '%s'"), pExtent->pszFullname);
2440 return rc;
2441 }
2442 return rc;
2443}
2444
2445/**
2446 * Internal: read metadata belonging to an extent with binary header, i.e.
2447 * as found in monolithic files.
2448 */
2449static int vmdkReadBinaryMetaExtent(PVMDKIMAGE pImage, PVMDKEXTENT pExtent)
2450{
2451 SparseExtentHeader Header;
2452 uint64_t cSectorsPerGDE;
2453
2454 int rc = vmdkFileReadAt(pExtent->pFile, 0, &Header, sizeof(Header), NULL);
2455 AssertRC(rc);
2456 if (RT_FAILURE(rc))
2457 {
2458 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error reading extent header in '%s'"), pExtent->pszFullname);
2459 goto out;
2460 }
2461 rc = vmdkValidateHeader(pImage, pExtent, &Header);
2462 if (RT_FAILURE(rc))
2463 goto out;
2464 if ( RT_LE2H_U32(Header.flags & RT_BIT(17))
2465 && RT_LE2H_U64(Header.gdOffset) == VMDK_GD_AT_END)
2466 {
2467 /* Read the footer, which isn't compressed and comes before the
2468 * end-of-stream marker. This is bending the VMDK 1.1 spec, but that's
2469 * VMware reality. Theory and practice have very little in common. */
2470 uint64_t cbSize;
2471 rc = vmdkFileGetSize(pExtent->pFile, &cbSize);
2472 AssertRC(rc);
2473 if (RT_FAILURE(rc))
2474 {
2475 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: cannot get size of '%s'"), pExtent->pszFullname);
2476 goto out;
2477 }
2478 cbSize = RT_ALIGN_64(cbSize, 512);
2479 rc = vmdkFileReadAt(pExtent->pFile, cbSize - 2*512, &Header, sizeof(Header), NULL);
2480 AssertRC(rc);
2481 if (RT_FAILURE(rc))
2482 {
2483 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error reading extent footer in '%s'"), pExtent->pszFullname);
2484 goto out;
2485 }
2486 rc = vmdkValidateHeader(pImage, pExtent, &Header);
2487 if (RT_FAILURE(rc))
2488 goto out;
2489 pExtent->fFooter = true;
2490 }
2491 pExtent->uVersion = RT_LE2H_U32(Header.version);
2492 pExtent->enmType = VMDKETYPE_HOSTED_SPARSE; /* Just dummy value, changed later. */
2493 pExtent->cSectors = RT_LE2H_U64(Header.capacity);
2494 pExtent->cSectorsPerGrain = RT_LE2H_U64(Header.grainSize);
2495 pExtent->uDescriptorSector = RT_LE2H_U64(Header.descriptorOffset);
2496 pExtent->cDescriptorSectors = RT_LE2H_U64(Header.descriptorSize);
2497 if (pExtent->uDescriptorSector && !pExtent->cDescriptorSectors)
2498 {
2499 rc = vmdkError(pImage, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: inconsistent embedded descriptor config in '%s'"), pExtent->pszFullname);
2500 goto out;
2501 }
2502 pExtent->cGTEntries = RT_LE2H_U32(Header.numGTEsPerGT);
2503 if (RT_LE2H_U32(Header.flags) & RT_BIT(1))
2504 {
2505 pExtent->uSectorRGD = RT_LE2H_U64(Header.rgdOffset);
2506 pExtent->uSectorGD = RT_LE2H_U64(Header.gdOffset);
2507 }
2508 else
2509 {
2510 pExtent->uSectorGD = RT_LE2H_U64(Header.gdOffset);
2511 pExtent->uSectorRGD = 0;
2512 }
2513 if (pExtent->uSectorGD == VMDK_GD_AT_END || pExtent->uSectorRGD == VMDK_GD_AT_END)
2514 {
2515 rc = vmdkError(pImage, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: cannot resolve grain directory offset in '%s'"), pExtent->pszFullname);
2516 goto out;
2517 }
2518 pExtent->cOverheadSectors = RT_LE2H_U64(Header.overHead);
2519 pExtent->fUncleanShutdown = !!Header.uncleanShutdown;
2520 pExtent->uCompression = RT_LE2H_U16(Header.compressAlgorithm);
2521 cSectorsPerGDE = pExtent->cGTEntries * pExtent->cSectorsPerGrain;
2522 if (!cSectorsPerGDE || cSectorsPerGDE > UINT32_MAX)
2523 {
2524 rc = vmdkError(pImage, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: incorrect grain directory size in '%s'"), pExtent->pszFullname);
2525 goto out;
2526 }
2527 pExtent->cSectorsPerGDE = cSectorsPerGDE;
2528 pExtent->cGDEntries = (pExtent->cSectors + cSectorsPerGDE - 1) / cSectorsPerGDE;
2529
2530 /* Fix up the number of descriptor sectors, as some flat images have
2531 * really just one, and this causes failures when inserting the UUID
2532 * values and other extra information. */
2533 if (pExtent->cDescriptorSectors != 0 && pExtent->cDescriptorSectors < 4)
2534 {
2535 /* Do it the easy way - just fix it for flat images which have no
2536 * other complicated metadata which needs space too. */
2537 if ( pExtent->uDescriptorSector + 4 < pExtent->cOverheadSectors
2538 && pExtent->cGTEntries * pExtent->cGDEntries == 0)
2539 pExtent->cDescriptorSectors = 4;
2540 }
2541
2542out:
2543 if (RT_FAILURE(rc))
2544 vmdkFreeExtentData(pImage, pExtent, false);
2545
2546 return rc;
2547}
2548
2549/**
2550 * Internal: read additional metadata belonging to an extent. For those
2551 * extents which have no additional metadata just verify the information.
2552 */
2553static int vmdkReadMetaExtent(PVMDKIMAGE pImage, PVMDKEXTENT pExtent)
2554{
2555 int rc = VINF_SUCCESS;
2556 uint64_t cbExtentSize;
2557
2558 /* The image must be a multiple of a sector in size and contain the data
2559 * area (flat images only). If not, it means the image is at least
2560 * truncated, or even seriously garbled. */
2561 rc = vmdkFileGetSize(pExtent->pFile, &cbExtentSize);
2562 if (RT_FAILURE(rc))
2563 {
2564 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error getting size in '%s'"), pExtent->pszFullname);
2565 goto out;
2566 }
2567/* disabled the size check again as there are too many too short vmdks out there */
2568#ifdef VBOX_WITH_VMDK_STRICT_SIZE_CHECK
2569 if ( cbExtentSize != RT_ALIGN_64(cbExtentSize, 512)
2570 && (pExtent->enmType != VMDKETYPE_FLAT || pExtent->cNominalSectors + pExtent->uSectorOffset > VMDK_BYTE2SECTOR(cbExtentSize)))
2571 {
2572 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);
2573 goto out;
2574 }
2575#endif /* VBOX_WITH_VMDK_STRICT_SIZE_CHECK */
2576 if (pExtent->enmType != VMDKETYPE_HOSTED_SPARSE)
2577 goto out;
2578
2579 /* The spec says that this must be a power of two and greater than 8,
2580 * but probably they meant not less than 8. */
2581 if ( (pExtent->cSectorsPerGrain & (pExtent->cSectorsPerGrain - 1))
2582 || pExtent->cSectorsPerGrain < 8)
2583 {
2584 rc = vmdkError(pImage, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: invalid extent grain size %u in '%s'"), pExtent->cSectorsPerGrain, pExtent->pszFullname);
2585 goto out;
2586 }
2587
2588 /* This code requires that a grain table must hold a power of two multiple
2589 * of the number of entries per GT cache entry. */
2590 if ( (pExtent->cGTEntries & (pExtent->cGTEntries - 1))
2591 || pExtent->cGTEntries < VMDK_GT_CACHELINE_SIZE)
2592 {
2593 rc = vmdkError(pImage, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: grain table cache size problem in '%s'"), pExtent->pszFullname);
2594 goto out;
2595 }
2596
2597 rc = vmdkReadGrainDirectory(pExtent);
2598
2599out:
2600 if (RT_FAILURE(rc))
2601 vmdkFreeExtentData(pImage, pExtent, false);
2602
2603 return rc;
2604}
2605
2606/**
2607 * Internal: write/update the metadata for a sparse extent.
2608 */
2609static int vmdkWriteMetaSparseExtent(PVMDKEXTENT pExtent, uint64_t uOffset)
2610{
2611 SparseExtentHeader Header;
2612
2613 memset(&Header, '\0', sizeof(Header));
2614 Header.magicNumber = RT_H2LE_U32(VMDK_SPARSE_MAGICNUMBER);
2615 Header.version = RT_H2LE_U32(pExtent->uVersion);
2616 Header.flags = RT_H2LE_U32(RT_BIT(0));
2617 if (pExtent->pRGD)
2618 Header.flags |= RT_H2LE_U32(RT_BIT(1));
2619 if (pExtent->pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
2620 Header.flags |= RT_H2LE_U32(RT_BIT(16) | RT_BIT(17));
2621 Header.capacity = RT_H2LE_U64(pExtent->cSectors);
2622 Header.grainSize = RT_H2LE_U64(pExtent->cSectorsPerGrain);
2623 Header.descriptorOffset = RT_H2LE_U64(pExtent->uDescriptorSector);
2624 Header.descriptorSize = RT_H2LE_U64(pExtent->cDescriptorSectors);
2625 Header.numGTEsPerGT = RT_H2LE_U32(pExtent->cGTEntries);
2626 if (pExtent->fFooter && uOffset == 0)
2627 {
2628 if (pExtent->pRGD)
2629 {
2630 Assert(pExtent->uSectorRGD);
2631 Header.rgdOffset = RT_H2LE_U64(VMDK_GD_AT_END);
2632 Header.gdOffset = RT_H2LE_U64(VMDK_GD_AT_END);
2633 }
2634 else
2635 {
2636 Header.gdOffset = RT_H2LE_U64(VMDK_GD_AT_END);
2637 }
2638 }
2639 else
2640 {
2641 if (pExtent->pRGD)
2642 {
2643 Assert(pExtent->uSectorRGD);
2644 Header.rgdOffset = RT_H2LE_U64(pExtent->uSectorRGD);
2645 Header.gdOffset = RT_H2LE_U64(pExtent->uSectorGD);
2646 }
2647 else
2648 {
2649 Header.gdOffset = RT_H2LE_U64(pExtent->uSectorGD);
2650 }
2651 }
2652 Header.overHead = RT_H2LE_U64(pExtent->cOverheadSectors);
2653 Header.uncleanShutdown = pExtent->fUncleanShutdown;
2654 Header.singleEndLineChar = '\n';
2655 Header.nonEndLineChar = ' ';
2656 Header.doubleEndLineChar1 = '\r';
2657 Header.doubleEndLineChar2 = '\n';
2658 Header.compressAlgorithm = RT_H2LE_U16(pExtent->uCompression);
2659
2660 int rc = vmdkFileWriteAt(pExtent->pFile, uOffset, &Header, sizeof(Header), NULL);
2661 AssertRC(rc);
2662 if (RT_FAILURE(rc))
2663 rc = vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: error writing extent header in '%s'"), pExtent->pszFullname);
2664 return rc;
2665}
2666
2667#ifdef VBOX_WITH_VMDK_ESX
2668/**
2669 * Internal: unused code to read the metadata of a sparse ESX extent.
2670 *
2671 * Such extents never leave ESX server, so this isn't ever used.
2672 */
2673static int vmdkReadMetaESXSparseExtent(PVMDKEXTENT pExtent)
2674{
2675 COWDisk_Header Header;
2676 uint64_t cSectorsPerGDE;
2677
2678 int rc = vmdkFileReadAt(pExtent->pFile, 0, &Header, sizeof(Header), NULL);
2679 AssertRC(rc);
2680 if (RT_FAILURE(rc))
2681 goto out;
2682 if ( RT_LE2H_U32(Header.magicNumber) != VMDK_ESX_SPARSE_MAGICNUMBER
2683 || RT_LE2H_U32(Header.version) != 1
2684 || RT_LE2H_U32(Header.flags) != 3)
2685 {
2686 rc = VERR_VD_VMDK_INVALID_HEADER;
2687 goto out;
2688 }
2689 pExtent->enmType = VMDKETYPE_ESX_SPARSE;
2690 pExtent->cSectors = RT_LE2H_U32(Header.numSectors);
2691 pExtent->cSectorsPerGrain = RT_LE2H_U32(Header.grainSize);
2692 /* The spec says that this must be between 1 sector and 1MB. This code
2693 * assumes it's a power of two, so check that requirement, too. */
2694 if ( (pExtent->cSectorsPerGrain & (pExtent->cSectorsPerGrain - 1))
2695 || pExtent->cSectorsPerGrain == 0
2696 || pExtent->cSectorsPerGrain > 2048)
2697 {
2698 rc = VERR_VD_VMDK_INVALID_HEADER;
2699 goto out;
2700 }
2701 pExtent->uDescriptorSector = 0;
2702 pExtent->cDescriptorSectors = 0;
2703 pExtent->uSectorGD = RT_LE2H_U32(Header.gdOffset);
2704 pExtent->uSectorRGD = 0;
2705 pExtent->cOverheadSectors = 0;
2706 pExtent->cGTEntries = 4096;
2707 cSectorsPerGDE = pExtent->cGTEntries * pExtent->cSectorsPerGrain;
2708 if (!cSectorsPerGDE || cSectorsPerGDE > UINT32_MAX)
2709 {
2710 rc = VERR_VD_VMDK_INVALID_HEADER;
2711 goto out;
2712 }
2713 pExtent->cSectorsPerGDE = cSectorsPerGDE;
2714 pExtent->cGDEntries = (pExtent->cSectors + cSectorsPerGDE - 1) / cSectorsPerGDE;
2715 if (pExtent->cGDEntries != RT_LE2H_U32(Header.numGDEntries))
2716 {
2717 /* Inconsistency detected. Computed number of GD entries doesn't match
2718 * stored value. Better be safe than sorry. */
2719 rc = VERR_VD_VMDK_INVALID_HEADER;
2720 goto out;
2721 }
2722 pExtent->uFreeSector = RT_LE2H_U32(Header.freeSector);
2723 pExtent->fUncleanShutdown = !!Header.uncleanShutdown;
2724
2725 rc = vmdkReadGrainDirectory(pExtent);
2726
2727out:
2728 if (RT_FAILURE(rc))
2729 vmdkFreeExtentData(pImage, pExtent, false);
2730
2731 return rc;
2732}
2733#endif /* VBOX_WITH_VMDK_ESX */
2734
2735/**
2736 * Internal: free the memory used by the extent data structure, optionally
2737 * deleting the referenced files.
2738 */
2739static void vmdkFreeExtentData(PVMDKIMAGE pImage, PVMDKEXTENT pExtent,
2740 bool fDelete)
2741{
2742 vmdkFreeGrainDirectory(pExtent);
2743 if (pExtent->pDescData)
2744 {
2745 RTMemFree(pExtent->pDescData);
2746 pExtent->pDescData = NULL;
2747 }
2748 if (pExtent->pFile != NULL)
2749 {
2750 /* Do not delete raw extents, these have full and base names equal. */
2751 vmdkFileClose(pImage, &pExtent->pFile,
2752 fDelete
2753 && pExtent->pszFullname
2754 && strcmp(pExtent->pszFullname, pExtent->pszBasename));
2755 }
2756 if (pExtent->pszBasename)
2757 {
2758 RTMemTmpFree((void *)pExtent->pszBasename);
2759 pExtent->pszBasename = NULL;
2760 }
2761 if (pExtent->pszFullname)
2762 {
2763 RTStrFree((char *)(void *)pExtent->pszFullname);
2764 pExtent->pszFullname = NULL;
2765 }
2766 if (pExtent->pvGrain)
2767 {
2768 RTMemFree(pExtent->pvGrain);
2769 pExtent->pvGrain = NULL;
2770 }
2771}
2772
2773/**
2774 * Internal: allocate grain table cache if necessary for this image.
2775 */
2776static int vmdkAllocateGrainTableCache(PVMDKIMAGE pImage)
2777{
2778 PVMDKEXTENT pExtent;
2779
2780 /* Allocate grain table cache if any sparse extent is present. */
2781 for (unsigned i = 0; i < pImage->cExtents; i++)
2782 {
2783 pExtent = &pImage->pExtents[i];
2784 if ( pExtent->enmType == VMDKETYPE_HOSTED_SPARSE
2785#ifdef VBOX_WITH_VMDK_ESX
2786 || pExtent->enmType == VMDKETYPE_ESX_SPARSE
2787#endif /* VBOX_WITH_VMDK_ESX */
2788 )
2789 {
2790 /* Allocate grain table cache. */
2791 pImage->pGTCache = (PVMDKGTCACHE)RTMemAllocZ(sizeof(VMDKGTCACHE));
2792 if (!pImage->pGTCache)
2793 return VERR_NO_MEMORY;
2794 for (unsigned i = 0; i < VMDK_GT_CACHE_SIZE; i++)
2795 {
2796 PVMDKGTCACHEENTRY pGCE = &pImage->pGTCache->aGTCache[i];
2797 pGCE->uExtent = UINT32_MAX;
2798 }
2799 pImage->pGTCache->cEntries = VMDK_GT_CACHE_SIZE;
2800 break;
2801 }
2802 }
2803
2804 return VINF_SUCCESS;
2805}
2806
2807/**
2808 * Internal: allocate the given number of extents.
2809 */
2810static int vmdkCreateExtents(PVMDKIMAGE pImage, unsigned cExtents)
2811{
2812 int rc = VINF_SUCCESS;
2813 PVMDKEXTENT pExtents = (PVMDKEXTENT)RTMemAllocZ(cExtents * sizeof(VMDKEXTENT));
2814 if (pImage)
2815 {
2816 for (unsigned i = 0; i < cExtents; i++)
2817 {
2818 pExtents[i].pFile = NULL;
2819 pExtents[i].pszBasename = NULL;
2820 pExtents[i].pszFullname = NULL;
2821 pExtents[i].pGD = NULL;
2822 pExtents[i].pRGD = NULL;
2823 pExtents[i].pDescData = NULL;
2824 pExtents[i].uVersion = 1;
2825 pExtents[i].uCompression = VMDK_COMPRESSION_NONE;
2826 pExtents[i].uExtent = i;
2827 pExtents[i].pImage = pImage;
2828 }
2829 pImage->pExtents = pExtents;
2830 pImage->cExtents = cExtents;
2831 }
2832 else
2833 rc = VERR_NO_MEMORY;
2834
2835 return rc;
2836}
2837
2838/**
2839 * Internal: Open an image, constructing all necessary data structures.
2840 */
2841static int vmdkOpenImage(PVMDKIMAGE pImage, unsigned uOpenFlags)
2842{
2843 int rc;
2844 uint32_t u32Magic;
2845 PVMDKFILE pFile;
2846 PVMDKEXTENT pExtent;
2847
2848 pImage->uOpenFlags = uOpenFlags;
2849
2850 /* Try to get error interface. */
2851 pImage->pInterfaceError = VDInterfaceGet(pImage->pVDIfsDisk, VDINTERFACETYPE_ERROR);
2852 if (pImage->pInterfaceError)
2853 pImage->pInterfaceErrorCallbacks = VDGetInterfaceError(pImage->pInterfaceError);
2854
2855 /* Try to get async I/O interface. */
2856 pImage->pInterfaceAsyncIO = VDInterfaceGet(pImage->pVDIfsDisk, VDINTERFACETYPE_ASYNCIO);
2857 if (pImage->pInterfaceAsyncIO)
2858 pImage->pInterfaceAsyncIOCallbacks = VDGetInterfaceAsyncIO(pImage->pInterfaceAsyncIO);
2859
2860 /*
2861 * Open the image.
2862 * We don't have to check for asynchronous access because
2863 * we only support raw access and the opened file is a description
2864 * file were no data is stored.
2865 */
2866 rc = vmdkFileOpen(pImage, &pFile, pImage->pszFilename,
2867 uOpenFlags & VD_OPEN_FLAGS_READONLY
2868 ? RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE
2869 : RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE, false);
2870 if (RT_FAILURE(rc))
2871 {
2872 /* Do NOT signal an appropriate error here, as the VD layer has the
2873 * choice of retrying the open if it failed. */
2874 goto out;
2875 }
2876 pImage->pFile = pFile;
2877
2878 /* Read magic (if present). */
2879 rc = vmdkFileReadAt(pFile, 0, &u32Magic, sizeof(u32Magic), NULL);
2880 if (RT_FAILURE(rc))
2881 {
2882 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error reading the magic number in '%s'"), pImage->pszFilename);
2883 goto out;
2884 }
2885
2886 /* Handle the file according to its magic number. */
2887 if (RT_LE2H_U32(u32Magic) == VMDK_SPARSE_MAGICNUMBER)
2888 {
2889 /* It's a hosted single-extent image. */
2890 rc = vmdkCreateExtents(pImage, 1);
2891 if (RT_FAILURE(rc))
2892 goto out;
2893 /* The opened file is passed to the extent. No separate descriptor
2894 * file, so no need to keep anything open for the image. */
2895 pExtent = &pImage->pExtents[0];
2896 pExtent->pFile = pFile;
2897 pImage->pFile = NULL;
2898 pExtent->pszFullname = RTPathAbsDup(pImage->pszFilename);
2899 if (!pExtent->pszFullname)
2900 {
2901 rc = VERR_NO_MEMORY;
2902 goto out;
2903 }
2904 rc = vmdkReadBinaryMetaExtent(pImage, pExtent);
2905 if (RT_FAILURE(rc))
2906 goto out;
2907
2908 /* As we're dealing with a monolithic image here, there must
2909 * be a descriptor embedded in the image file. */
2910 if (!pExtent->uDescriptorSector || !pExtent->cDescriptorSectors)
2911 {
2912 rc = vmdkError(pImage, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: monolithic image without descriptor in '%s'"), pImage->pszFilename);
2913 goto out;
2914 }
2915 /* HACK: extend the descriptor if it is unusually small and it fits in
2916 * the unused space after the image header. Allows opening VMDK files
2917 * with extremely small descriptor in read/write mode. */
2918 if ( !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2919 && pExtent->cDescriptorSectors < 3
2920 && (int64_t)pExtent->uSectorGD - pExtent->uDescriptorSector >= 4
2921 && (!pExtent->uSectorRGD || (int64_t)pExtent->uSectorRGD - pExtent->uDescriptorSector >= 4))
2922 {
2923 pExtent->cDescriptorSectors = 4;
2924 pExtent->fMetaDirty = true;
2925 }
2926 /* Read the descriptor from the extent. */
2927 pExtent->pDescData = (char *)RTMemAllocZ(VMDK_SECTOR2BYTE(pExtent->cDescriptorSectors));
2928 if (!pExtent->pDescData)
2929 {
2930 rc = VERR_NO_MEMORY;
2931 goto out;
2932 }
2933 rc = vmdkFileReadAt(pExtent->pFile,
2934 VMDK_SECTOR2BYTE(pExtent->uDescriptorSector),
2935 pExtent->pDescData,
2936 VMDK_SECTOR2BYTE(pExtent->cDescriptorSectors), NULL);
2937 AssertRC(rc);
2938 if (RT_FAILURE(rc))
2939 {
2940 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: read error for descriptor in '%s'"), pExtent->pszFullname);
2941 goto out;
2942 }
2943
2944 rc = vmdkParseDescriptor(pImage, pExtent->pDescData,
2945 VMDK_SECTOR2BYTE(pExtent->cDescriptorSectors));
2946 if (RT_FAILURE(rc))
2947 goto out;
2948
2949 rc = vmdkReadMetaExtent(pImage, pExtent);
2950 if (RT_FAILURE(rc))
2951 goto out;
2952
2953 /* Mark the extent as unclean if opened in read-write mode. */
2954 if (!(uOpenFlags & VD_OPEN_FLAGS_READONLY))
2955 {
2956 pExtent->fUncleanShutdown = true;
2957 pExtent->fMetaDirty = true;
2958 }
2959 }
2960 else
2961 {
2962 pImage->cbDescAlloc = VMDK_SECTOR2BYTE(20);
2963 pImage->pDescData = (char *)RTMemAllocZ(pImage->cbDescAlloc);
2964 if (!pImage->pDescData)
2965 {
2966 rc = VERR_NO_MEMORY;
2967 goto out;
2968 }
2969
2970 size_t cbRead;
2971 rc = vmdkFileReadAt(pImage->pFile, 0, pImage->pDescData,
2972 pImage->cbDescAlloc, &cbRead);
2973 if (RT_FAILURE(rc))
2974 {
2975 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: read error for descriptor in '%s'"), pImage->pszFilename);
2976 goto out;
2977 }
2978 if (cbRead == pImage->cbDescAlloc)
2979 {
2980 /* Likely the read is truncated. Better fail a bit too early
2981 * (normally the descriptor is much smaller than our buffer). */
2982 rc = vmdkError(pImage, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: cannot read descriptor in '%s'"), pImage->pszFilename);
2983 goto out;
2984 }
2985
2986 rc = vmdkParseDescriptor(pImage, pImage->pDescData,
2987 pImage->cbDescAlloc);
2988 if (RT_FAILURE(rc))
2989 goto out;
2990
2991 /*
2992 * We have to check for the asynchronous open flag. The
2993 * extents are parsed and the type of all are known now.
2994 * Check if every extent is either FLAT or ZERO.
2995 */
2996 if (uOpenFlags & VD_OPEN_FLAGS_ASYNC_IO)
2997 {
2998 for (unsigned i = 0; i < pImage->cExtents; i++)
2999 {
3000 PVMDKEXTENT pExtent = &pImage->pExtents[i];
3001
3002 if ( (pExtent->enmType != VMDKETYPE_FLAT)
3003 && (pExtent->enmType != VMDKETYPE_ZERO))
3004 {
3005 /*
3006 * Opened image contains at least one none flat or zero extent.
3007 * Return error but don't set error message as the caller
3008 * has the chance to open in non async I/O mode.
3009 */
3010 rc = VERR_NOT_SUPPORTED;
3011 goto out;
3012 }
3013 }
3014 }
3015
3016 for (unsigned i = 0; i < pImage->cExtents; i++)
3017 {
3018 PVMDKEXTENT pExtent = &pImage->pExtents[i];
3019
3020 if (pExtent->pszBasename)
3021 {
3022 /* Hack to figure out whether the specified name in the
3023 * extent descriptor is absolute. Doesn't always work, but
3024 * should be good enough for now. */
3025 char *pszFullname;
3026 /** @todo implement proper path absolute check. */
3027 if (pExtent->pszBasename[0] == RTPATH_SLASH)
3028 {
3029 pszFullname = RTStrDup(pExtent->pszBasename);
3030 if (!pszFullname)
3031 {
3032 rc = VERR_NO_MEMORY;
3033 goto out;
3034 }
3035 }
3036 else
3037 {
3038 size_t cbDirname;
3039 char *pszDirname = RTStrDup(pImage->pszFilename);
3040 if (!pszDirname)
3041 {
3042 rc = VERR_NO_MEMORY;
3043 goto out;
3044 }
3045 RTPathStripFilename(pszDirname);
3046 cbDirname = strlen(pszDirname);
3047 rc = RTStrAPrintf(&pszFullname, "%s%c%s", pszDirname,
3048 RTPATH_SLASH, pExtent->pszBasename);
3049 RTStrFree(pszDirname);
3050 if (RT_FAILURE(rc))
3051 goto out;
3052 }
3053 pExtent->pszFullname = pszFullname;
3054 }
3055 else
3056 pExtent->pszFullname = NULL;
3057
3058 switch (pExtent->enmType)
3059 {
3060 case VMDKETYPE_HOSTED_SPARSE:
3061 rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszFullname,
3062 uOpenFlags & VD_OPEN_FLAGS_READONLY
3063 ? RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE
3064 : RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE, false);
3065 if (RT_FAILURE(rc))
3066 {
3067 /* Do NOT signal an appropriate error here, as the VD
3068 * layer has the choice of retrying the open if it
3069 * failed. */
3070 goto out;
3071 }
3072 rc = vmdkReadBinaryMetaExtent(pImage, pExtent);
3073 if (RT_FAILURE(rc))
3074 goto out;
3075 rc = vmdkReadMetaExtent(pImage, pExtent);
3076 if (RT_FAILURE(rc))
3077 goto out;
3078
3079 /* Mark extent as unclean if opened in read-write mode. */
3080 if (!(uOpenFlags & VD_OPEN_FLAGS_READONLY))
3081 {
3082 pExtent->fUncleanShutdown = true;
3083 pExtent->fMetaDirty = true;
3084 }
3085 break;
3086 case VMDKETYPE_FLAT:
3087 rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszFullname,
3088 uOpenFlags & VD_OPEN_FLAGS_READONLY
3089 ? RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE
3090 : RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE, true);
3091 if (RT_FAILURE(rc))
3092 {
3093 /* Do NOT signal an appropriate error here, as the VD
3094 * layer has the choice of retrying the open if it
3095 * failed. */
3096 goto out;
3097 }
3098 break;
3099 case VMDKETYPE_ZERO:
3100 /* Nothing to do. */
3101 break;
3102 default:
3103 AssertMsgFailed(("unknown vmdk extent type %d\n", pExtent->enmType));
3104 }
3105 }
3106 }
3107
3108 /* Make sure this is not reached accidentally with an error status. */
3109 AssertRC(rc);
3110
3111 /* Determine PCHS geometry if not set. */
3112 if (pImage->PCHSGeometry.cCylinders == 0)
3113 {
3114 uint64_t cCylinders = VMDK_BYTE2SECTOR(pImage->cbSize)
3115 / pImage->PCHSGeometry.cHeads
3116 / pImage->PCHSGeometry.cSectors;
3117 pImage->PCHSGeometry.cCylinders = (unsigned)RT_MIN(cCylinders, 16383);
3118 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
3119 {
3120 rc = vmdkDescSetPCHSGeometry(pImage, &pImage->PCHSGeometry);
3121 AssertRC(rc);
3122 }
3123 }
3124
3125 /* Update the image metadata now in case has changed. */
3126 rc = vmdkFlushImage(pImage);
3127 if (RT_FAILURE(rc))
3128 goto out;
3129
3130 /* Figure out a few per-image constants from the extents. */
3131 pImage->cbSize = 0;
3132 for (unsigned i = 0; i < pImage->cExtents; i++)
3133 {
3134 pExtent = &pImage->pExtents[i];
3135 if ( pExtent->enmType == VMDKETYPE_HOSTED_SPARSE
3136#ifdef VBOX_WITH_VMDK_ESX
3137 || pExtent->enmType == VMDKETYPE_ESX_SPARSE
3138#endif /* VBOX_WITH_VMDK_ESX */
3139 )
3140 {
3141 /* Here used to be a check whether the nominal size of an extent
3142 * is a multiple of the grain size. The spec says that this is
3143 * always the case, but unfortunately some files out there in the
3144 * wild violate the spec (e.g. ReactOS 0.3.1). */
3145 }
3146 pImage->cbSize += VMDK_SECTOR2BYTE(pExtent->cNominalSectors);
3147 }
3148
3149 for (unsigned i = 0; i < pImage->cExtents; i++)
3150 {
3151 pExtent = &pImage->pExtents[i];
3152 if ( pImage->pExtents[i].enmType == VMDKETYPE_FLAT
3153 || pImage->pExtents[i].enmType == VMDKETYPE_ZERO)
3154 {
3155 pImage->uImageFlags |= VD_IMAGE_FLAGS_FIXED;
3156 break;
3157 }
3158 }
3159
3160 rc = vmdkAllocateGrainTableCache(pImage);
3161 if (RT_FAILURE(rc))
3162 goto out;
3163
3164out:
3165 if (RT_FAILURE(rc))
3166 vmdkFreeImage(pImage, false);
3167 return rc;
3168}
3169
3170/**
3171 * Internal: create VMDK images for raw disk/partition access.
3172 */
3173static int vmdkCreateRawImage(PVMDKIMAGE pImage, const PVBOXHDDRAW pRaw,
3174 uint64_t cbSize)
3175{
3176 int rc = VINF_SUCCESS;
3177 PVMDKEXTENT pExtent;
3178
3179 if (pRaw->fRawDisk)
3180 {
3181 /* Full raw disk access. This requires setting up a descriptor
3182 * file and open the (flat) raw disk. */
3183 rc = vmdkCreateExtents(pImage, 1);
3184 if (RT_FAILURE(rc))
3185 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not create new extent list in '%s'"), pImage->pszFilename);
3186 pExtent = &pImage->pExtents[0];
3187 /* Create raw disk descriptor file. */
3188 rc = vmdkFileOpen(pImage, &pImage->pFile, pImage->pszFilename,
3189 RTFILE_O_READWRITE | RTFILE_O_CREATE | RTFILE_O_DENY_WRITE | RTFILE_O_NOT_CONTENT_INDEXED,
3190 false);
3191 if (RT_FAILURE(rc))
3192 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not create new file '%s'"), pImage->pszFilename);
3193
3194 /* Set up basename for extent description. Cannot use StrDup. */
3195 size_t cbBasename = strlen(pRaw->pszRawDisk) + 1;
3196 char *pszBasename = (char *)RTMemTmpAlloc(cbBasename);
3197 if (!pszBasename)
3198 return VERR_NO_MEMORY;
3199 memcpy(pszBasename, pRaw->pszRawDisk, cbBasename);
3200 pExtent->pszBasename = pszBasename;
3201 /* For raw disks the full name is identical to the base name. */
3202 pExtent->pszFullname = RTStrDup(pszBasename);
3203 if (!pExtent->pszFullname)
3204 return VERR_NO_MEMORY;
3205 pExtent->enmType = VMDKETYPE_FLAT;
3206 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(cbSize);
3207 pExtent->uSectorOffset = 0;
3208 pExtent->enmAccess = VMDKACCESS_READWRITE;
3209 pExtent->fMetaDirty = false;
3210
3211 /* Open flat image, the raw disk. */
3212 rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszFullname,
3213 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE, false);
3214 if (RT_FAILURE(rc))
3215 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not open raw disk file '%s'"), pExtent->pszFullname);
3216 }
3217 else
3218 {
3219 /* Raw partition access. This requires setting up a descriptor
3220 * file, write the partition information to a flat extent and
3221 * open all the (flat) raw disk partitions. */
3222
3223 /* First pass over the partitions to determine how many
3224 * extents we need. One partition can require up to 4 extents.
3225 * One to skip over unpartitioned space, one for the
3226 * partitioning data, one to skip over unpartitioned space
3227 * and one for the partition data. */
3228 unsigned cExtents = 0;
3229 uint64_t uStart = 0;
3230 for (unsigned i = 0; i < pRaw->cPartitions; i++)
3231 {
3232 PVBOXHDDRAWPART pPart = &pRaw->pPartitions[i];
3233 if (pPart->cbPartitionData)
3234 {
3235 if (uStart > pPart->uPartitionDataStart)
3236 return vmdkError(pImage, VERR_INVALID_PARAMETER, RT_SRC_POS, N_("VMDK: cannot go backwards for partitioning information in '%s'"), pImage->pszFilename);
3237 else if (uStart != pPart->uPartitionDataStart)
3238 cExtents++;
3239 uStart = pPart->uPartitionDataStart + pPart->cbPartitionData;
3240 cExtents++;
3241 }
3242 if (pPart->cbPartition)
3243 {
3244 if (uStart > pPart->uPartitionStart)
3245 return vmdkError(pImage, VERR_INVALID_PARAMETER, RT_SRC_POS, N_("VMDK: cannot go backwards for partition data in '%s'"), pImage->pszFilename);
3246 else if (uStart != pPart->uPartitionStart)
3247 cExtents++;
3248 uStart = pPart->uPartitionStart + pPart->cbPartition;
3249 cExtents++;
3250 }
3251 }
3252 /* Another extent for filling up the rest of the image. */
3253 if (uStart != cbSize)
3254 cExtents++;
3255
3256 rc = vmdkCreateExtents(pImage, cExtents);
3257 if (RT_FAILURE(rc))
3258 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not create new extent list in '%s'"), pImage->pszFilename);
3259
3260 /* Create raw partition descriptor file. */
3261 rc = vmdkFileOpen(pImage, &pImage->pFile, pImage->pszFilename,
3262 RTFILE_O_READWRITE | RTFILE_O_CREATE | RTFILE_O_DENY_WRITE | RTFILE_O_NOT_CONTENT_INDEXED,
3263 false);
3264 if (RT_FAILURE(rc))
3265 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not create new file '%s'"), pImage->pszFilename);
3266
3267 /* Create base filename for the partition table extent. */
3268 /** @todo remove fixed buffer without creating memory leaks. */
3269 char pszPartition[1024];
3270 const char *pszBase = RTPathFilename(pImage->pszFilename);
3271 const char *pszExt = RTPathExt(pszBase);
3272 if (pszExt == NULL)
3273 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: invalid filename '%s'"), pImage->pszFilename);
3274 char *pszBaseBase = RTStrDup(pszBase);
3275 if (!pszBaseBase)
3276 return VERR_NO_MEMORY;
3277 RTPathStripExt(pszBaseBase);
3278 RTStrPrintf(pszPartition, sizeof(pszPartition), "%s-pt%s",
3279 pszBaseBase, pszExt);
3280 RTStrFree(pszBaseBase);
3281
3282 /* Second pass over the partitions, now define all extents. */
3283 uint64_t uPartOffset = 0;
3284 cExtents = 0;
3285 uStart = 0;
3286 for (unsigned i = 0; i < pRaw->cPartitions; i++)
3287 {
3288 PVBOXHDDRAWPART pPart = &pRaw->pPartitions[i];
3289 if (pPart->cbPartitionData)
3290 {
3291 if (uStart != pPart->uPartitionDataStart)
3292 {
3293 pExtent = &pImage->pExtents[cExtents++];
3294 pExtent->pszBasename = NULL;
3295 pExtent->pszFullname = NULL;
3296 pExtent->enmType = VMDKETYPE_ZERO;
3297 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(pPart->uPartitionDataStart - uStart);
3298 pExtent->uSectorOffset = 0;
3299 pExtent->enmAccess = VMDKACCESS_READWRITE;
3300 pExtent->fMetaDirty = false;
3301 }
3302 uStart = pPart->uPartitionDataStart + pPart->cbPartitionData;
3303 pExtent = &pImage->pExtents[cExtents++];
3304 /* Set up basename for extent description. Can't use StrDup. */
3305 size_t cbBasename = strlen(pszPartition) + 1;
3306 char *pszBasename = (char *)RTMemTmpAlloc(cbBasename);
3307 if (!pszBasename)
3308 return VERR_NO_MEMORY;
3309 memcpy(pszBasename, pszPartition, cbBasename);
3310 pExtent->pszBasename = pszBasename;
3311
3312 /* Set up full name for partition extent. */
3313 size_t cbDirname;
3314 char *pszDirname = RTStrDup(pImage->pszFilename);
3315 if (!pszDirname)
3316 return VERR_NO_MEMORY;
3317 RTPathStripFilename(pszDirname);
3318 cbDirname = strlen(pszDirname);
3319 char *pszFullname;
3320 rc = RTStrAPrintf(&pszFullname, "%s%c%s", pszDirname,
3321 RTPATH_SLASH, pExtent->pszBasename);
3322 RTStrFree(pszDirname);
3323 if (RT_FAILURE(rc))
3324 return rc;
3325 pExtent->pszFullname = pszFullname;
3326 pExtent->enmType = VMDKETYPE_FLAT;
3327 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(pPart->cbPartitionData);
3328 pExtent->uSectorOffset = uPartOffset;
3329 pExtent->enmAccess = VMDKACCESS_READWRITE;
3330 pExtent->fMetaDirty = false;
3331
3332 /* Create partition table flat image. */
3333 rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszFullname,
3334 RTFILE_O_READWRITE | RTFILE_O_CREATE | RTFILE_O_DENY_WRITE | RTFILE_O_NOT_CONTENT_INDEXED,
3335 false);
3336 if (RT_FAILURE(rc))
3337 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not create new partition data file '%s'"), pExtent->pszFullname);
3338 rc = vmdkFileWriteAt(pExtent->pFile,
3339 VMDK_SECTOR2BYTE(uPartOffset),
3340 pPart->pvPartitionData,
3341 pPart->cbPartitionData, NULL);
3342 if (RT_FAILURE(rc))
3343 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not write partition data to '%s'"), pExtent->pszFullname);
3344 uPartOffset += VMDK_BYTE2SECTOR(pPart->cbPartitionData);
3345 }
3346 if (pPart->cbPartition)
3347 {
3348 if (uStart != pPart->uPartitionStart)
3349 {
3350 pExtent = &pImage->pExtents[cExtents++];
3351 pExtent->pszBasename = NULL;
3352 pExtent->pszFullname = NULL;
3353 pExtent->enmType = VMDKETYPE_ZERO;
3354 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(pPart->uPartitionStart - uStart);
3355 pExtent->uSectorOffset = 0;
3356 pExtent->enmAccess = VMDKACCESS_READWRITE;
3357 pExtent->fMetaDirty = false;
3358 }
3359 uStart = pPart->uPartitionStart + pPart->cbPartition;
3360 pExtent = &pImage->pExtents[cExtents++];
3361 if (pPart->pszRawDevice)
3362 {
3363 /* Set up basename for extent descr. Can't use StrDup. */
3364 size_t cbBasename = strlen(pPart->pszRawDevice) + 1;
3365 char *pszBasename = (char *)RTMemTmpAlloc(cbBasename);
3366 if (!pszBasename)
3367 return VERR_NO_MEMORY;
3368 memcpy(pszBasename, pPart->pszRawDevice, cbBasename);
3369 pExtent->pszBasename = pszBasename;
3370 /* For raw disks full name is identical to base name. */
3371 pExtent->pszFullname = RTStrDup(pszBasename);
3372 if (!pExtent->pszFullname)
3373 return VERR_NO_MEMORY;
3374 pExtent->enmType = VMDKETYPE_FLAT;
3375 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(pPart->cbPartition);
3376 pExtent->uSectorOffset = VMDK_BYTE2SECTOR(pPart->uPartitionStartOffset);
3377 pExtent->enmAccess = VMDKACCESS_READWRITE;
3378 pExtent->fMetaDirty = false;
3379
3380 /* Open flat image, the raw partition. */
3381 rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszFullname,
3382 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE,
3383 false);
3384 if (RT_FAILURE(rc))
3385 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not open raw partition file '%s'"), pExtent->pszFullname);
3386 }
3387 else
3388 {
3389 pExtent->pszBasename = NULL;
3390 pExtent->pszFullname = NULL;
3391 pExtent->enmType = VMDKETYPE_ZERO;
3392 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(pPart->cbPartition);
3393 pExtent->uSectorOffset = 0;
3394 pExtent->enmAccess = VMDKACCESS_READWRITE;
3395 pExtent->fMetaDirty = false;
3396 }
3397 }
3398 }
3399 /* Another extent for filling up the rest of the image. */
3400 if (uStart != cbSize)
3401 {
3402 pExtent = &pImage->pExtents[cExtents++];
3403 pExtent->pszBasename = NULL;
3404 pExtent->pszFullname = NULL;
3405 pExtent->enmType = VMDKETYPE_ZERO;
3406 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(cbSize - uStart);
3407 pExtent->uSectorOffset = 0;
3408 pExtent->enmAccess = VMDKACCESS_READWRITE;
3409 pExtent->fMetaDirty = false;
3410 }
3411 }
3412
3413 rc = vmdkDescBaseSetStr(pImage, &pImage->Descriptor, "createType",
3414 pRaw->fRawDisk ?
3415 "fullDevice" : "partitionedDevice");
3416 if (RT_FAILURE(rc))
3417 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not set the image type in '%s'"), pImage->pszFilename);
3418 return rc;
3419}
3420
3421/**
3422 * Internal: create a regular (i.e. file-backed) VMDK image.
3423 */
3424static int vmdkCreateRegularImage(PVMDKIMAGE pImage, uint64_t cbSize,
3425 unsigned uImageFlags,
3426 PFNVMPROGRESS pfnProgress, void *pvUser,
3427 unsigned uPercentStart, unsigned uPercentSpan)
3428{
3429 int rc = VINF_SUCCESS;
3430 unsigned cExtents = 1;
3431 uint64_t cbOffset = 0;
3432 uint64_t cbRemaining = cbSize;
3433
3434 if (uImageFlags & VD_VMDK_IMAGE_FLAGS_SPLIT_2G)
3435 {
3436 cExtents = cbSize / VMDK_2G_SPLIT_SIZE;
3437 /* Do proper extent computation: need one smaller extent if the total
3438 * size isn't evenly divisible by the split size. */
3439 if (cbSize % VMDK_2G_SPLIT_SIZE)
3440 cExtents++;
3441 }
3442 rc = vmdkCreateExtents(pImage, cExtents);
3443 if (RT_FAILURE(rc))
3444 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not create new extent list in '%s'"), pImage->pszFilename);
3445
3446 /* Basename strings needed for constructing the extent names. */
3447 char *pszBasenameSubstr = RTPathFilename(pImage->pszFilename);
3448 AssertPtr(pszBasenameSubstr);
3449 size_t cbBasenameSubstr = strlen(pszBasenameSubstr) + 1;
3450
3451 /* Create searate descriptor file if necessary. */
3452 if (cExtents != 1 || (uImageFlags & VD_IMAGE_FLAGS_FIXED))
3453 {
3454 rc = vmdkFileOpen(pImage, &pImage->pFile, pImage->pszFilename,
3455 RTFILE_O_READWRITE | RTFILE_O_CREATE | RTFILE_O_DENY_WRITE | RTFILE_O_NOT_CONTENT_INDEXED,
3456 false);
3457 if (RT_FAILURE(rc))
3458 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not create new sparse descriptor file '%s'"), pImage->pszFilename);
3459 }
3460 else
3461 pImage->pFile = NULL;
3462
3463 /* Set up all extents. */
3464 for (unsigned i = 0; i < cExtents; i++)
3465 {
3466 PVMDKEXTENT pExtent = &pImage->pExtents[i];
3467 uint64_t cbExtent = cbRemaining;
3468
3469 /* Set up fullname/basename for extent description. Cannot use StrDup
3470 * for basename, as it is not guaranteed that the memory can be freed
3471 * with RTMemTmpFree, which must be used as in other code paths
3472 * StrDup is not usable. */
3473 if (cExtents == 1 && !(uImageFlags & VD_IMAGE_FLAGS_FIXED))
3474 {
3475 char *pszBasename = (char *)RTMemTmpAlloc(cbBasenameSubstr);
3476 if (!pszBasename)
3477 return VERR_NO_MEMORY;
3478 memcpy(pszBasename, pszBasenameSubstr, cbBasenameSubstr);
3479 pExtent->pszBasename = pszBasename;
3480 }
3481 else
3482 {
3483 char *pszBasenameExt = RTPathExt(pszBasenameSubstr);
3484 char *pszBasenameBase = RTStrDup(pszBasenameSubstr);
3485 RTPathStripExt(pszBasenameBase);
3486 char *pszTmp;
3487 size_t cbTmp;
3488 if (uImageFlags & VD_IMAGE_FLAGS_FIXED)
3489 {
3490 if (cExtents == 1)
3491 rc = RTStrAPrintf(&pszTmp, "%s-flat%s", pszBasenameBase,
3492 pszBasenameExt);
3493 else
3494 rc = RTStrAPrintf(&pszTmp, "%s-f%03d%s", pszBasenameBase,
3495 i+1, pszBasenameExt);
3496 }
3497 else
3498 rc = RTStrAPrintf(&pszTmp, "%s-s%03d%s", pszBasenameBase, i+1,
3499 pszBasenameExt);
3500 RTStrFree(pszBasenameBase);
3501 if (RT_FAILURE(rc))
3502 return rc;
3503 cbTmp = strlen(pszTmp) + 1;
3504 char *pszBasename = (char *)RTMemTmpAlloc(cbTmp);
3505 if (!pszBasename)
3506 return VERR_NO_MEMORY;
3507 memcpy(pszBasename, pszTmp, cbTmp);
3508 RTStrFree(pszTmp);
3509 pExtent->pszBasename = pszBasename;
3510 if (uImageFlags & VD_VMDK_IMAGE_FLAGS_SPLIT_2G)
3511 cbExtent = RT_MIN(cbRemaining, VMDK_2G_SPLIT_SIZE);
3512 }
3513 char *pszBasedirectory = RTStrDup(pImage->pszFilename);
3514 RTPathStripFilename(pszBasedirectory);
3515 char *pszFullname;
3516 rc = RTStrAPrintf(&pszFullname, "%s%c%s", pszBasedirectory,
3517 RTPATH_SLASH, pExtent->pszBasename);
3518 RTStrFree(pszBasedirectory);
3519 if (RT_FAILURE(rc))
3520 return rc;
3521 pExtent->pszFullname = pszFullname;
3522
3523 /* Create file for extent. */
3524 rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszFullname,
3525 RTFILE_O_READWRITE | RTFILE_O_CREATE | RTFILE_O_DENY_WRITE | RTFILE_O_NOT_CONTENT_INDEXED,
3526 false);
3527 if (RT_FAILURE(rc))
3528 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not create new file '%s'"), pExtent->pszFullname);
3529 if (uImageFlags & VD_IMAGE_FLAGS_FIXED)
3530 {
3531 rc = vmdkFileSetSize(pExtent->pFile, cbExtent);
3532 if (RT_FAILURE(rc))
3533 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not set size of new file '%s'"), pExtent->pszFullname);
3534
3535 /* Fill image with zeroes. We do this for every fixed-size image since on some systems
3536 * (for example Windows Vista), it takes ages to write a block near the end of a sparse
3537 * file and the guest could complain about an ATA timeout. */
3538
3539 /** @todo Starting with Linux 2.6.23, there is an fallocate() system call.
3540 * Currently supported file systems are ext4 and ocfs2. */
3541
3542 /* Allocate a temporary zero-filled buffer. Use a bigger block size to optimize writing */
3543 const size_t cbBuf = 128 * _1K;
3544 void *pvBuf = RTMemTmpAllocZ(cbBuf);
3545 if (!pvBuf)
3546 return VERR_NO_MEMORY;
3547
3548 uint64_t uOff = 0;
3549 /* Write data to all image blocks. */
3550 while (uOff < cbExtent)
3551 {
3552 unsigned cbChunk = (unsigned)RT_MIN(cbExtent, cbBuf);
3553
3554 rc = vmdkFileWriteAt(pExtent->pFile, uOff, pvBuf, cbChunk, NULL);
3555 if (RT_FAILURE(rc))
3556 {
3557 RTMemFree(pvBuf);
3558 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: writing block failed for '%s'"), pImage->pszFilename);
3559 }
3560
3561 uOff += cbChunk;
3562
3563 if (pfnProgress)
3564 {
3565 rc = pfnProgress(NULL /* WARNING! pVM=NULL */,
3566 uPercentStart + uOff * uPercentSpan / cbExtent,
3567 pvUser);
3568 if (RT_FAILURE(rc))
3569 {
3570 RTMemFree(pvBuf);
3571 return rc;
3572 }
3573 }
3574 }
3575 RTMemTmpFree(pvBuf);
3576 }
3577
3578 /* Place descriptor file information (where integrated). */
3579 if (cExtents == 1 && !(uImageFlags & VD_IMAGE_FLAGS_FIXED))
3580 {
3581 pExtent->uDescriptorSector = 1;
3582 pExtent->cDescriptorSectors = VMDK_BYTE2SECTOR(pImage->cbDescAlloc);
3583 /* The descriptor is part of the (only) extent. */
3584 pExtent->pDescData = pImage->pDescData;
3585 pImage->pDescData = NULL;
3586 }
3587
3588 if (!(uImageFlags & VD_IMAGE_FLAGS_FIXED))
3589 {
3590 uint64_t cSectorsPerGDE, cSectorsPerGD;
3591 pExtent->enmType = VMDKETYPE_HOSTED_SPARSE;
3592 pExtent->cSectors = VMDK_BYTE2SECTOR(RT_ALIGN_64(cbExtent, 65536));
3593 pExtent->cSectorsPerGrain = VMDK_BYTE2SECTOR(65536);
3594 pExtent->cGTEntries = 512;
3595 cSectorsPerGDE = pExtent->cGTEntries * pExtent->cSectorsPerGrain;
3596 pExtent->cSectorsPerGDE = cSectorsPerGDE;
3597 pExtent->cGDEntries = (pExtent->cSectors + cSectorsPerGDE - 1) / cSectorsPerGDE;
3598 cSectorsPerGD = (pExtent->cGDEntries + (512 / sizeof(uint32_t) - 1)) / (512 / sizeof(uint32_t));
3599 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
3600 {
3601 /* The spec says version is 1 for all VMDKs, but the vast
3602 * majority of streamOptimized VMDKs actually contain
3603 * version 3 - so go with the majority. Both are acepted. */
3604 pExtent->uVersion = 3;
3605 pExtent->uCompression = VMDK_COMPRESSION_DEFLATE;
3606 }
3607 }
3608 else
3609 pExtent->enmType = VMDKETYPE_FLAT;
3610
3611 pExtent->enmAccess = VMDKACCESS_READWRITE;
3612 pExtent->fUncleanShutdown = true;
3613 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(cbExtent);
3614 pExtent->uSectorOffset = VMDK_BYTE2SECTOR(cbOffset);
3615 pExtent->fMetaDirty = true;
3616
3617 if (!(uImageFlags & VD_IMAGE_FLAGS_FIXED))
3618 {
3619 rc = vmdkCreateGrainDirectory(pExtent,
3620 RT_MAX( pExtent->uDescriptorSector
3621 + pExtent->cDescriptorSectors,
3622 1),
3623 true);
3624 if (RT_FAILURE(rc))
3625 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not create new grain directory in '%s'"), pExtent->pszFullname);
3626 }
3627
3628 if (RT_SUCCESS(rc) && pfnProgress)
3629 pfnProgress(NULL /* WARNING! pVM=NULL */,
3630 uPercentStart + i * uPercentSpan / cExtents,
3631 pvUser);
3632
3633 cbRemaining -= cbExtent;
3634 cbOffset += cbExtent;
3635 }
3636
3637 const char *pszDescType = NULL;
3638 if (uImageFlags & VD_IMAGE_FLAGS_FIXED)
3639 {
3640 pszDescType = (cExtents == 1)
3641 ? "monolithicFlat" : "twoGbMaxExtentFlat";
3642 }
3643 else
3644 {
3645 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
3646 pszDescType = "streamOptimized";
3647 else
3648 {
3649 pszDescType = (cExtents == 1)
3650 ? "monolithicSparse" : "twoGbMaxExtentSparse";
3651 }
3652 }
3653 rc = vmdkDescBaseSetStr(pImage, &pImage->Descriptor, "createType",
3654 pszDescType);
3655 if (RT_FAILURE(rc))
3656 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not set the image type in '%s'"), pImage->pszFilename);
3657 return rc;
3658}
3659
3660/**
3661 * Internal: The actual code for creating any VMDK variant currently in
3662 * existence on hosted environments.
3663 */
3664static int vmdkCreateImage(PVMDKIMAGE pImage, uint64_t cbSize,
3665 unsigned uImageFlags, const char *pszComment,
3666 PCPDMMEDIAGEOMETRY pPCHSGeometry,
3667 PCPDMMEDIAGEOMETRY pLCHSGeometry, PCRTUUID pUuid,
3668 PFNVMPROGRESS pfnProgress, void *pvUser,
3669 unsigned uPercentStart, unsigned uPercentSpan)
3670{
3671 int rc;
3672
3673 pImage->uImageFlags = uImageFlags;
3674
3675 /* Try to get error interface. */
3676 pImage->pInterfaceError = VDInterfaceGet(pImage->pVDIfsDisk, VDINTERFACETYPE_ERROR);
3677 if (pImage->pInterfaceError)
3678 pImage->pInterfaceErrorCallbacks = VDGetInterfaceError(pImage->pInterfaceError);
3679
3680 /* Try to get async I/O interface. */
3681 pImage->pInterfaceAsyncIO = VDInterfaceGet(pImage->pVDIfsDisk, VDINTERFACETYPE_ASYNCIO);
3682 if (pImage->pInterfaceAsyncIO)
3683 pImage->pInterfaceAsyncIOCallbacks = VDGetInterfaceAsyncIO(pImage->pInterfaceAsyncIO);
3684
3685 rc = vmdkCreateDescriptor(pImage, pImage->pDescData, pImage->cbDescAlloc,
3686 &pImage->Descriptor);
3687 if (RT_FAILURE(rc))
3688 {
3689 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not create new descriptor in '%s'"), pImage->pszFilename);
3690 goto out;
3691 }
3692
3693 if ( (uImageFlags & VD_IMAGE_FLAGS_FIXED)
3694 && (uImageFlags & VD_VMDK_IMAGE_FLAGS_RAWDISK))
3695 {
3696 /* Raw disk image (includes raw partition). */
3697 const PVBOXHDDRAW pRaw = (const PVBOXHDDRAW)pszComment;
3698 /* As the comment is misused, zap it so that no garbage comment
3699 * is set below. */
3700 pszComment = NULL;
3701 rc = vmdkCreateRawImage(pImage, pRaw, cbSize);
3702 }
3703 else
3704 {
3705 /* Regular fixed or sparse image (monolithic or split). */
3706 rc = vmdkCreateRegularImage(pImage, cbSize, uImageFlags,
3707 pfnProgress, pvUser, uPercentStart,
3708 uPercentSpan * 95 / 100);
3709 }
3710
3711 if (RT_FAILURE(rc))
3712 goto out;
3713
3714 if (RT_SUCCESS(rc) && pfnProgress)
3715 pfnProgress(NULL /* WARNING! pVM=NULL */,
3716 uPercentStart + uPercentSpan * 98 / 100, pvUser);
3717
3718 pImage->cbSize = cbSize;
3719
3720 for (unsigned i = 0; i < pImage->cExtents; i++)
3721 {
3722 PVMDKEXTENT pExtent = &pImage->pExtents[i];
3723
3724 rc = vmdkDescExtInsert(pImage, &pImage->Descriptor, pExtent->enmAccess,
3725 pExtent->cNominalSectors, pExtent->enmType,
3726 pExtent->pszBasename, pExtent->uSectorOffset);
3727 if (RT_FAILURE(rc))
3728 {
3729 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not insert the extent list into descriptor in '%s'"), pImage->pszFilename);
3730 goto out;
3731 }
3732 }
3733 vmdkDescExtRemoveDummy(pImage, &pImage->Descriptor);
3734
3735 if ( pPCHSGeometry->cCylinders != 0
3736 && pPCHSGeometry->cHeads != 0
3737 && pPCHSGeometry->cSectors != 0)
3738 {
3739 rc = vmdkDescSetPCHSGeometry(pImage, pPCHSGeometry);
3740 if (RT_FAILURE(rc))
3741 goto out;
3742 }
3743 if ( pLCHSGeometry->cCylinders != 0
3744 && pLCHSGeometry->cHeads != 0
3745 && pLCHSGeometry->cSectors != 0)
3746 {
3747 rc = vmdkDescSetLCHSGeometry(pImage, pLCHSGeometry);
3748 if (RT_FAILURE(rc))
3749 goto out;
3750 }
3751
3752 pImage->LCHSGeometry = *pLCHSGeometry;
3753 pImage->PCHSGeometry = *pPCHSGeometry;
3754
3755 pImage->ImageUuid = *pUuid;
3756 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
3757 VMDK_DDB_IMAGE_UUID, &pImage->ImageUuid);
3758 if (RT_FAILURE(rc))
3759 {
3760 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error storing image UUID in new descriptor in '%s'"), pImage->pszFilename);
3761 goto out;
3762 }
3763 RTUuidClear(&pImage->ParentUuid);
3764 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
3765 VMDK_DDB_PARENT_UUID, &pImage->ParentUuid);
3766 if (RT_FAILURE(rc))
3767 {
3768 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error storing parent image UUID in new descriptor in '%s'"), pImage->pszFilename);
3769 goto out;
3770 }
3771 RTUuidClear(&pImage->ModificationUuid);
3772 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
3773 VMDK_DDB_MODIFICATION_UUID,
3774 &pImage->ModificationUuid);
3775 if (RT_FAILURE(rc))
3776 {
3777 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error storing modification UUID in new descriptor in '%s'"), pImage->pszFilename);
3778 goto out;
3779 }
3780 RTUuidClear(&pImage->ParentModificationUuid);
3781 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
3782 VMDK_DDB_PARENT_MODIFICATION_UUID,
3783 &pImage->ParentModificationUuid);
3784 if (RT_FAILURE(rc))
3785 {
3786 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error storing parent modification UUID in new descriptor in '%s'"), pImage->pszFilename);
3787 goto out;
3788 }
3789
3790 rc = vmdkAllocateGrainTableCache(pImage);
3791 if (RT_FAILURE(rc))
3792 goto out;
3793
3794 rc = vmdkSetImageComment(pImage, pszComment);
3795 if (RT_FAILURE(rc))
3796 {
3797 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: cannot set image comment in '%s'"), pImage->pszFilename);
3798 goto out;
3799 }
3800
3801 if (RT_SUCCESS(rc) && pfnProgress)
3802 pfnProgress(NULL /* WARNING! pVM=NULL */,
3803 uPercentStart + uPercentSpan * 99 / 100, pvUser);
3804
3805 rc = vmdkFlushImage(pImage);
3806
3807out:
3808 if (RT_SUCCESS(rc) && pfnProgress)
3809 pfnProgress(NULL /* WARNING! pVM=NULL */,
3810 uPercentStart + uPercentSpan, pvUser);
3811
3812 if (RT_FAILURE(rc))
3813 vmdkFreeImage(pImage, rc != VERR_ALREADY_EXISTS);
3814 return rc;
3815}
3816
3817/**
3818 * Internal: Update image comment.
3819 */
3820static int vmdkSetImageComment(PVMDKIMAGE pImage, const char *pszComment)
3821{
3822 char *pszCommentEncoded;
3823 if (pszComment)
3824 {
3825 pszCommentEncoded = vmdkEncodeString(pszComment);
3826 if (!pszCommentEncoded)
3827 return VERR_NO_MEMORY;
3828 }
3829 else
3830 pszCommentEncoded = NULL;
3831 int rc = vmdkDescDDBSetStr(pImage, &pImage->Descriptor,
3832 "ddb.comment", pszCommentEncoded);
3833 if (pszComment)
3834 RTStrFree(pszCommentEncoded);
3835 if (RT_FAILURE(rc))
3836 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error storing image comment in descriptor in '%s'"), pImage->pszFilename);
3837 return VINF_SUCCESS;
3838}
3839
3840/**
3841 * Internal. Free all allocated space for representing an image, and optionally
3842 * delete the image from disk.
3843 */
3844static void vmdkFreeImage(PVMDKIMAGE pImage, bool fDelete)
3845{
3846 AssertPtr(pImage);
3847
3848 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
3849 {
3850 /* Mark all extents as clean. */
3851 for (unsigned i = 0; i < pImage->cExtents; i++)
3852 {
3853 if (( pImage->pExtents[i].enmType == VMDKETYPE_HOSTED_SPARSE
3854#ifdef VBOX_WITH_VMDK_ESX
3855 || pImage->pExtents[i].enmType == VMDKETYPE_ESX_SPARSE
3856#endif /* VBOX_WITH_VMDK_ESX */
3857 )
3858 && pImage->pExtents[i].fUncleanShutdown)
3859 {
3860 pImage->pExtents[i].fUncleanShutdown = false;
3861 pImage->pExtents[i].fMetaDirty = true;
3862 }
3863 }
3864 }
3865 (void)vmdkFlushImage(pImage);
3866
3867 if (pImage->pExtents != NULL)
3868 {
3869 for (unsigned i = 0 ; i < pImage->cExtents; i++)
3870 vmdkFreeExtentData(pImage, &pImage->pExtents[i], fDelete);
3871 RTMemFree(pImage->pExtents);
3872 pImage->pExtents = NULL;
3873 }
3874 pImage->cExtents = 0;
3875 if (pImage->pFile != NULL)
3876 vmdkFileClose(pImage, &pImage->pFile, fDelete);
3877 vmdkFileCheckAllClose(pImage);
3878 if (pImage->pGTCache)
3879 {
3880 RTMemFree(pImage->pGTCache);
3881 pImage->pGTCache = NULL;
3882 }
3883 if (pImage->pDescData)
3884 {
3885 RTMemFree(pImage->pDescData);
3886 pImage->pDescData = NULL;
3887 }
3888}
3889
3890/**
3891 * Internal. Flush image data (and metadata) to disk.
3892 */
3893static int vmdkFlushImage(PVMDKIMAGE pImage)
3894{
3895 PVMDKEXTENT pExtent;
3896 int rc = VINF_SUCCESS;
3897
3898 /* Update descriptor if changed. */
3899 if (pImage->Descriptor.fDirty)
3900 {
3901 rc = vmdkWriteDescriptor(pImage);
3902 if (RT_FAILURE(rc))
3903 goto out;
3904 }
3905
3906 for (unsigned i = 0; i < pImage->cExtents; i++)
3907 {
3908 pExtent = &pImage->pExtents[i];
3909 if (pExtent->pFile != NULL && pExtent->fMetaDirty)
3910 {
3911 switch (pExtent->enmType)
3912 {
3913 case VMDKETYPE_HOSTED_SPARSE:
3914 rc = vmdkWriteMetaSparseExtent(pExtent, 0);
3915 if (RT_FAILURE(rc))
3916 goto out;
3917 if (pExtent->fFooter)
3918 {
3919 uint64_t cbSize;
3920 rc = vmdkFileGetSize(pExtent->pFile, &cbSize);
3921 if (RT_FAILURE(rc))
3922 goto out;
3923 cbSize = RT_ALIGN_64(cbSize, 512);
3924 rc = vmdkWriteMetaSparseExtent(pExtent, cbSize - 2*512);
3925 if (RT_FAILURE(rc))
3926 goto out;
3927 }
3928 break;
3929#ifdef VBOX_WITH_VMDK_ESX
3930 case VMDKETYPE_ESX_SPARSE:
3931 /** @todo update the header. */
3932 break;
3933#endif /* VBOX_WITH_VMDK_ESX */
3934 case VMDKETYPE_FLAT:
3935 /* Nothing to do. */
3936 break;
3937 case VMDKETYPE_ZERO:
3938 default:
3939 AssertMsgFailed(("extent with type %d marked as dirty\n",
3940 pExtent->enmType));
3941 break;
3942 }
3943 }
3944 switch (pExtent->enmType)
3945 {
3946 case VMDKETYPE_HOSTED_SPARSE:
3947#ifdef VBOX_WITH_VMDK_ESX
3948 case VMDKETYPE_ESX_SPARSE:
3949#endif /* VBOX_WITH_VMDK_ESX */
3950 case VMDKETYPE_FLAT:
3951 /** @todo implement proper path absolute check. */
3952 if ( pExtent->pFile != NULL
3953 && !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
3954 && !(pExtent->pszBasename[0] == RTPATH_SLASH))
3955 rc = vmdkFileFlush(pExtent->pFile);
3956 break;
3957 case VMDKETYPE_ZERO:
3958 /* No need to do anything for this extent. */
3959 break;
3960 default:
3961 AssertMsgFailed(("unknown extent type %d\n", pExtent->enmType));
3962 break;
3963 }
3964 }
3965
3966out:
3967 return rc;
3968}
3969
3970/**
3971 * Internal. Find extent corresponding to the sector number in the disk.
3972 */
3973static int vmdkFindExtent(PVMDKIMAGE pImage, uint64_t offSector,
3974 PVMDKEXTENT *ppExtent, uint64_t *puSectorInExtent)
3975{
3976 PVMDKEXTENT pExtent = NULL;
3977 int rc = VINF_SUCCESS;
3978
3979 for (unsigned i = 0; i < pImage->cExtents; i++)
3980 {
3981 if (offSector < pImage->pExtents[i].cNominalSectors)
3982 {
3983 pExtent = &pImage->pExtents[i];
3984 *puSectorInExtent = offSector + pImage->pExtents[i].uSectorOffset;
3985 break;
3986 }
3987 offSector -= pImage->pExtents[i].cNominalSectors;
3988 }
3989
3990 if (pExtent)
3991 *ppExtent = pExtent;
3992 else
3993 rc = VERR_IO_SECTOR_NOT_FOUND;
3994
3995 return rc;
3996}
3997
3998/**
3999 * Internal. Hash function for placing the grain table hash entries.
4000 */
4001static uint32_t vmdkGTCacheHash(PVMDKGTCACHE pCache, uint64_t uSector,
4002 unsigned uExtent)
4003{
4004 /** @todo this hash function is quite simple, maybe use a better one which
4005 * scrambles the bits better. */
4006 return (uSector + uExtent) % pCache->cEntries;
4007}
4008
4009/**
4010 * Internal. Get sector number in the extent file from the relative sector
4011 * number in the extent.
4012 */
4013static int vmdkGetSector(PVMDKGTCACHE pCache, PVMDKEXTENT pExtent,
4014 uint64_t uSector, uint64_t *puExtentSector)
4015{
4016 uint64_t uGDIndex, uGTSector, uGTBlock;
4017 uint32_t uGTHash, uGTBlockIndex;
4018 PVMDKGTCACHEENTRY pGTCacheEntry;
4019 uint32_t aGTDataTmp[VMDK_GT_CACHELINE_SIZE];
4020 int rc;
4021
4022 uGDIndex = uSector / pExtent->cSectorsPerGDE;
4023 if (uGDIndex >= pExtent->cGDEntries)
4024 return VERR_OUT_OF_RANGE;
4025 uGTSector = pExtent->pGD[uGDIndex];
4026 if (!uGTSector)
4027 {
4028 /* There is no grain table referenced by this grain directory
4029 * entry. So there is absolutely no data in this area. */
4030 *puExtentSector = 0;
4031 return VINF_SUCCESS;
4032 }
4033
4034 uGTBlock = uSector / (pExtent->cSectorsPerGrain * VMDK_GT_CACHELINE_SIZE);
4035 uGTHash = vmdkGTCacheHash(pCache, uGTBlock, pExtent->uExtent);
4036 pGTCacheEntry = &pCache->aGTCache[uGTHash];
4037 if ( pGTCacheEntry->uExtent != pExtent->uExtent
4038 || pGTCacheEntry->uGTBlock != uGTBlock)
4039 {
4040 /* Cache miss, fetch data from disk. */
4041 rc = vmdkFileReadAt(pExtent->pFile,
4042 VMDK_SECTOR2BYTE(uGTSector) + (uGTBlock % (pExtent->cGTEntries / VMDK_GT_CACHELINE_SIZE)) * sizeof(aGTDataTmp),
4043 aGTDataTmp, sizeof(aGTDataTmp), NULL);
4044 if (RT_FAILURE(rc))
4045 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: cannot read grain table entry in '%s'"), pExtent->pszFullname);
4046 pGTCacheEntry->uExtent = pExtent->uExtent;
4047 pGTCacheEntry->uGTBlock = uGTBlock;
4048 for (unsigned i = 0; i < VMDK_GT_CACHELINE_SIZE; i++)
4049 pGTCacheEntry->aGTData[i] = RT_LE2H_U32(aGTDataTmp[i]);
4050 }
4051 uGTBlockIndex = (uSector / pExtent->cSectorsPerGrain) % VMDK_GT_CACHELINE_SIZE;
4052 uint32_t uGrainSector = pGTCacheEntry->aGTData[uGTBlockIndex];
4053 if (uGrainSector)
4054 *puExtentSector = uGrainSector + uSector % pExtent->cSectorsPerGrain;
4055 else
4056 *puExtentSector = 0;
4057 return VINF_SUCCESS;
4058}
4059
4060/**
4061 * Internal. Allocates a new grain table (if necessary), writes the grain
4062 * and updates the grain table. The cache is also updated by this operation.
4063 * This is separate from vmdkGetSector, because that should be as fast as
4064 * possible. Most code from vmdkGetSector also appears here.
4065 */
4066static int vmdkAllocGrain(PVMDKGTCACHE pCache, PVMDKEXTENT pExtent,
4067 uint64_t uSector, const void *pvBuf,
4068 uint64_t cbWrite)
4069{
4070 uint64_t uGDIndex, uGTSector, uRGTSector, uGTBlock;
4071 uint64_t cbExtentSize;
4072 uint32_t uGTHash, uGTBlockIndex;
4073 PVMDKGTCACHEENTRY pGTCacheEntry;
4074 uint32_t aGTDataTmp[VMDK_GT_CACHELINE_SIZE];
4075 int rc;
4076
4077 uGDIndex = uSector / pExtent->cSectorsPerGDE;
4078 if (uGDIndex >= pExtent->cGDEntries)
4079 return VERR_OUT_OF_RANGE;
4080 uGTSector = pExtent->pGD[uGDIndex];
4081 if (pExtent->pRGD)
4082 uRGTSector = pExtent->pRGD[uGDIndex];
4083 else
4084 uRGTSector = 0; /**< avoid compiler warning */
4085 if (!uGTSector)
4086 {
4087 /* There is no grain table referenced by this grain directory
4088 * entry. So there is absolutely no data in this area. Allocate
4089 * a new grain table and put the reference to it in the GDs. */
4090 rc = vmdkFileGetSize(pExtent->pFile, &cbExtentSize);
4091 if (RT_FAILURE(rc))
4092 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: error getting size in '%s'"), pExtent->pszFullname);
4093 Assert(!(cbExtentSize % 512));
4094 cbExtentSize = RT_ALIGN_64(cbExtentSize, 512);
4095 uGTSector = VMDK_BYTE2SECTOR(cbExtentSize);
4096 /* For writable streamOptimized extents the final sector is the
4097 * end-of-stream marker. Will be re-added after the grain table.
4098 * If the file has a footer it also will be re-added before EOS. */
4099 if (pExtent->pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
4100 {
4101 uint64_t uEOSOff = 0;
4102 uGTSector--;
4103 if (pExtent->fFooter)
4104 {
4105 uGTSector--;
4106 uEOSOff = 512;
4107 rc = vmdkWriteMetaSparseExtent(pExtent, VMDK_SECTOR2BYTE(uGTSector) + pExtent->cGTEntries * sizeof(uint32_t));
4108 if (RT_FAILURE(rc))
4109 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: cannot write footer after grain table in '%s'"), pExtent->pszFullname);
4110 }
4111 pExtent->uLastGrainSector = 0;
4112 uint8_t aEOS[512];
4113 memset(aEOS, '\0', sizeof(aEOS));
4114 rc = vmdkFileWriteAt(pExtent->pFile,
4115 VMDK_SECTOR2BYTE(uGTSector) + pExtent->cGTEntries * sizeof(uint32_t) + uEOSOff,
4116 aEOS, sizeof(aEOS), NULL);
4117 if (RT_FAILURE(rc))
4118 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: cannot write end-of stream marker after grain table in '%s'"), pExtent->pszFullname);
4119 }
4120 /* Normally the grain table is preallocated for hosted sparse extents
4121 * that support more than 32 bit sector numbers. So this shouldn't
4122 * ever happen on a valid extent. */
4123 if (uGTSector > UINT32_MAX)
4124 return VERR_VD_VMDK_INVALID_HEADER;
4125 /* Write grain table by writing the required number of grain table
4126 * cache chunks. Avoids dynamic memory allocation, but is a bit
4127 * slower. But as this is a pretty infrequently occurring case it
4128 * should be acceptable. */
4129 memset(aGTDataTmp, '\0', sizeof(aGTDataTmp));
4130 for (unsigned i = 0;
4131 i < pExtent->cGTEntries / VMDK_GT_CACHELINE_SIZE;
4132 i++)
4133 {
4134 rc = vmdkFileWriteAt(pExtent->pFile,
4135 VMDK_SECTOR2BYTE(uGTSector) + i * sizeof(aGTDataTmp),
4136 aGTDataTmp, sizeof(aGTDataTmp), NULL);
4137 if (RT_FAILURE(rc))
4138 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: cannot write grain table allocation in '%s'"), pExtent->pszFullname);
4139 }
4140 if (pExtent->pRGD)
4141 {
4142 AssertReturn(!uRGTSector, VERR_VD_VMDK_INVALID_HEADER);
4143 rc = vmdkFileGetSize(pExtent->pFile, &cbExtentSize);
4144 if (RT_FAILURE(rc))
4145 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: error getting size in '%s'"), pExtent->pszFullname);
4146 Assert(!(cbExtentSize % 512));
4147 uRGTSector = VMDK_BYTE2SECTOR(cbExtentSize);
4148 /* For writable streamOptimized extents the final sector is the
4149 * end-of-stream marker. Will be re-added after the grain table.
4150 * If the file has a footer it also will be re-added before EOS. */
4151 if (pExtent->pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
4152 {
4153 uint64_t uEOSOff = 0;
4154 uRGTSector--;
4155 if (pExtent->fFooter)
4156 {
4157 uRGTSector--;
4158 uEOSOff = 512;
4159 rc = vmdkWriteMetaSparseExtent(pExtent, VMDK_SECTOR2BYTE(uRGTSector) + pExtent->cGTEntries * sizeof(uint32_t));
4160 if (RT_FAILURE(rc))
4161 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: cannot write footer after redundant grain table in '%s'"), pExtent->pszFullname);
4162 }
4163 pExtent->uLastGrainSector = 0;
4164 uint8_t aEOS[512];
4165 memset(aEOS, '\0', sizeof(aEOS));
4166 rc = vmdkFileWriteAt(pExtent->pFile,
4167 VMDK_SECTOR2BYTE(uRGTSector) + pExtent->cGTEntries * sizeof(uint32_t) + uEOSOff,
4168 aEOS, sizeof(aEOS), NULL);
4169 if (RT_FAILURE(rc))
4170 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: cannot write end-of stream marker after redundant grain table in '%s'"), pExtent->pszFullname);
4171 }
4172 /* Normally the redundant grain table is preallocated for hosted
4173 * sparse extents that support more than 32 bit sector numbers. So
4174 * this shouldn't ever happen on a valid extent. */
4175 if (uRGTSector > UINT32_MAX)
4176 return VERR_VD_VMDK_INVALID_HEADER;
4177 /* Write backup grain table by writing the required number of grain
4178 * table cache chunks. Avoids dynamic memory allocation, but is a
4179 * bit slower. But as this is a pretty infrequently occurring case
4180 * it should be acceptable. */
4181 for (unsigned i = 0;
4182 i < pExtent->cGTEntries / VMDK_GT_CACHELINE_SIZE;
4183 i++)
4184 {
4185 rc = vmdkFileWriteAt(pExtent->pFile,
4186 VMDK_SECTOR2BYTE(uRGTSector) + i * sizeof(aGTDataTmp),
4187 aGTDataTmp, sizeof(aGTDataTmp), NULL);
4188 if (RT_FAILURE(rc))
4189 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: cannot write backup grain table allocation in '%s'"), pExtent->pszFullname);
4190 }
4191 }
4192
4193 /* Update the grain directory on disk (doing it before writing the
4194 * grain table will result in a garbled extent if the operation is
4195 * aborted for some reason. Otherwise the worst that can happen is
4196 * some unused sectors in the extent. */
4197 uint32_t uGTSectorLE = RT_H2LE_U64(uGTSector);
4198 rc = vmdkFileWriteAt(pExtent->pFile,
4199 VMDK_SECTOR2BYTE(pExtent->uSectorGD) + uGDIndex * sizeof(uGTSectorLE),
4200 &uGTSectorLE, sizeof(uGTSectorLE), NULL);
4201 if (RT_FAILURE(rc))
4202 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: cannot write grain directory entry in '%s'"), pExtent->pszFullname);
4203 if (pExtent->pRGD)
4204 {
4205 uint32_t uRGTSectorLE = RT_H2LE_U64(uRGTSector);
4206 rc = vmdkFileWriteAt(pExtent->pFile,
4207 VMDK_SECTOR2BYTE(pExtent->uSectorRGD) + uGDIndex * sizeof(uRGTSectorLE),
4208 &uRGTSectorLE, sizeof(uRGTSectorLE), NULL);
4209 if (RT_FAILURE(rc))
4210 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: cannot write backup grain directory entry in '%s'"), pExtent->pszFullname);
4211 }
4212
4213 /* As the final step update the in-memory copy of the GDs. */
4214 pExtent->pGD[uGDIndex] = uGTSector;
4215 if (pExtent->pRGD)
4216 pExtent->pRGD[uGDIndex] = uRGTSector;
4217 }
4218
4219 rc = vmdkFileGetSize(pExtent->pFile, &cbExtentSize);
4220 if (RT_FAILURE(rc))
4221 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: error getting size in '%s'"), pExtent->pszFullname);
4222 Assert(!(cbExtentSize % 512));
4223
4224 /* Write the data. Always a full grain, or we're in big trouble. */
4225 if (pExtent->pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
4226 {
4227 /* For streamOptimized extents this is a little more difficult, as the
4228 * cached data also needs to be updated, to handle updating the last
4229 * written block properly. Also we're trying to avoid unnecessary gaps.
4230 * Additionally the end-of-stream marker needs to be written. */
4231 if (!pExtent->uLastGrainSector)
4232 {
4233 cbExtentSize -= 512;
4234 if (pExtent->fFooter)
4235 cbExtentSize -= 512;
4236 }
4237 else
4238 cbExtentSize = VMDK_SECTOR2BYTE(pExtent->uLastGrainSector) + pExtent->cbLastGrainWritten;
4239 Assert(cbWrite == VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain));
4240 uint32_t cbGrain = 0;
4241 rc = vmdkFileDeflateAt(pExtent->pFile, cbExtentSize,
4242 pvBuf, cbWrite, VMDK_MARKER_IGNORE, uSector, &cbGrain);
4243 if (RT_FAILURE(rc))
4244 {
4245 pExtent->uGrainSector = 0;
4246 pExtent->uLastGrainSector = 0;
4247 AssertRC(rc);
4248 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: cannot write allocated compressed data block in '%s'"), pExtent->pszFullname);
4249 }
4250 cbGrain = RT_ALIGN(cbGrain, 512);
4251 pExtent->uLastGrainSector = VMDK_BYTE2SECTOR(cbExtentSize);
4252 pExtent->uLastGrainWritten = uSector / pExtent->cSectorsPerGrain;
4253 pExtent->cbLastGrainWritten = cbGrain;
4254 memcpy(pExtent->pvGrain, pvBuf, cbWrite);
4255 pExtent->uGrainSector = uSector;
4256
4257 uint64_t uEOSOff = 0;
4258 if (pExtent->fFooter)
4259 {
4260 uEOSOff = 512;
4261 rc = vmdkWriteMetaSparseExtent(pExtent, cbExtentSize + RT_ALIGN(cbGrain, 512));
4262 if (RT_FAILURE(rc))
4263 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: cannot write footer after allocated data block in '%s'"), pExtent->pszFullname);
4264 }
4265 uint8_t aEOS[512];
4266 memset(aEOS, '\0', sizeof(aEOS));
4267 rc = vmdkFileWriteAt(pExtent->pFile, cbExtentSize + RT_ALIGN(cbGrain, 512) + uEOSOff,
4268 aEOS, sizeof(aEOS), NULL);
4269 if (RT_FAILURE(rc))
4270 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: cannot write end-of stream marker after allocated data block in '%s'"), pExtent->pszFullname);
4271 }
4272 else
4273 {
4274 rc = vmdkFileWriteAt(pExtent->pFile, cbExtentSize, pvBuf, cbWrite, NULL);
4275 if (RT_FAILURE(rc))
4276 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: cannot write allocated data block in '%s'"), pExtent->pszFullname);
4277 }
4278
4279 /* Update the grain table (and the cache). */
4280 uGTBlock = uSector / (pExtent->cSectorsPerGrain * VMDK_GT_CACHELINE_SIZE);
4281 uGTHash = vmdkGTCacheHash(pCache, uGTBlock, pExtent->uExtent);
4282 pGTCacheEntry = &pCache->aGTCache[uGTHash];
4283 if ( pGTCacheEntry->uExtent != pExtent->uExtent
4284 || pGTCacheEntry->uGTBlock != uGTBlock)
4285 {
4286 /* Cache miss, fetch data from disk. */
4287 rc = vmdkFileReadAt(pExtent->pFile,
4288 VMDK_SECTOR2BYTE(uGTSector) + (uGTBlock % (pExtent->cGTEntries / VMDK_GT_CACHELINE_SIZE)) * sizeof(aGTDataTmp),
4289 aGTDataTmp, sizeof(aGTDataTmp), NULL);
4290 if (RT_FAILURE(rc))
4291 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: cannot read allocated grain table entry in '%s'"), pExtent->pszFullname);
4292 pGTCacheEntry->uExtent = pExtent->uExtent;
4293 pGTCacheEntry->uGTBlock = uGTBlock;
4294 for (unsigned i = 0; i < VMDK_GT_CACHELINE_SIZE; i++)
4295 pGTCacheEntry->aGTData[i] = RT_LE2H_U32(aGTDataTmp[i]);
4296 }
4297 else
4298 {
4299 /* Cache hit. Convert grain table block back to disk format, otherwise
4300 * the code below will write garbage for all but the updated entry. */
4301 for (unsigned i = 0; i < VMDK_GT_CACHELINE_SIZE; i++)
4302 aGTDataTmp[i] = RT_H2LE_U32(pGTCacheEntry->aGTData[i]);
4303 }
4304 uGTBlockIndex = (uSector / pExtent->cSectorsPerGrain) % VMDK_GT_CACHELINE_SIZE;
4305 aGTDataTmp[uGTBlockIndex] = RT_H2LE_U32(VMDK_BYTE2SECTOR(cbExtentSize));
4306 pGTCacheEntry->aGTData[uGTBlockIndex] = VMDK_BYTE2SECTOR(cbExtentSize);
4307 /* Update grain table on disk. */
4308 rc = vmdkFileWriteAt(pExtent->pFile,
4309 VMDK_SECTOR2BYTE(uGTSector) + (uGTBlock % (pExtent->cGTEntries / VMDK_GT_CACHELINE_SIZE)) * sizeof(aGTDataTmp),
4310 aGTDataTmp, sizeof(aGTDataTmp), NULL);
4311 if (RT_FAILURE(rc))
4312 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: cannot write updated grain table in '%s'"), pExtent->pszFullname);
4313 if (pExtent->pRGD)
4314 {
4315 /* Update backup grain table on disk. */
4316 rc = vmdkFileWriteAt(pExtent->pFile,
4317 VMDK_SECTOR2BYTE(uRGTSector) + (uGTBlock % (pExtent->cGTEntries / VMDK_GT_CACHELINE_SIZE)) * sizeof(aGTDataTmp),
4318 aGTDataTmp, sizeof(aGTDataTmp), NULL);
4319 if (RT_FAILURE(rc))
4320 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: cannot write updated backup grain table in '%s'"), pExtent->pszFullname);
4321 }
4322#ifdef VBOX_WITH_VMDK_ESX
4323 if (RT_SUCCESS(rc) && pExtent->enmType == VMDKETYPE_ESX_SPARSE)
4324 {
4325 pExtent->uFreeSector = uGTSector + VMDK_BYTE2SECTOR(cbWrite);
4326 pExtent->fMetaDirty = true;
4327 }
4328#endif /* VBOX_WITH_VMDK_ESX */
4329 return rc;
4330}
4331
4332
4333/** @copydoc VBOXHDDBACKEND::pfnCheckIfValid */
4334static int vmdkCheckIfValid(const char *pszFilename)
4335{
4336 LogFlowFunc(("pszFilename=\"%s\"\n", pszFilename));
4337 int rc = VINF_SUCCESS;
4338 PVMDKIMAGE pImage;
4339
4340 if ( !pszFilename
4341 || !*pszFilename
4342 || strchr(pszFilename, '"'))
4343 {
4344 rc = VERR_INVALID_PARAMETER;
4345 goto out;
4346 }
4347
4348 pImage = (PVMDKIMAGE)RTMemAllocZ(sizeof(VMDKIMAGE));
4349 if (!pImage)
4350 {
4351 rc = VERR_NO_MEMORY;
4352 goto out;
4353 }
4354 pImage->pszFilename = pszFilename;
4355 pImage->pFile = NULL;
4356 pImage->pExtents = NULL;
4357 pImage->pFiles = NULL;
4358 pImage->pGTCache = NULL;
4359 pImage->pDescData = NULL;
4360 pImage->pVDIfsDisk = NULL;
4361 /** @todo speed up this test open (VD_OPEN_FLAGS_INFO) by skipping as
4362 * much as possible in vmdkOpenImage. */
4363 rc = vmdkOpenImage(pImage, VD_OPEN_FLAGS_INFO | VD_OPEN_FLAGS_READONLY);
4364 vmdkFreeImage(pImage, false);
4365 RTMemFree(pImage);
4366
4367out:
4368 LogFlowFunc(("returns %Rrc\n", rc));
4369 return rc;
4370}
4371
4372/** @copydoc VBOXHDDBACKEND::pfnOpen */
4373static int vmdkOpen(const char *pszFilename, unsigned uOpenFlags,
4374 PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
4375 void **ppBackendData)
4376{
4377 LogFlowFunc(("pszFilename=\"%s\" uOpenFlags=%#x pVDIfsDisk=%#p pVDIfsImage=%#p ppBackendData=%#p\n", pszFilename, uOpenFlags, pVDIfsDisk, pVDIfsImage, ppBackendData));
4378 int rc;
4379 PVMDKIMAGE pImage;
4380
4381 /* Check open flags. All valid flags are supported. */
4382 if (uOpenFlags & ~VD_OPEN_FLAGS_MASK)
4383 {
4384 rc = VERR_INVALID_PARAMETER;
4385 goto out;
4386 }
4387
4388 /* Check remaining arguments. */
4389 if ( !VALID_PTR(pszFilename)
4390 || !*pszFilename
4391 || strchr(pszFilename, '"'))
4392 {
4393 rc = VERR_INVALID_PARAMETER;
4394 goto out;
4395 }
4396
4397
4398 pImage = (PVMDKIMAGE)RTMemAllocZ(sizeof(VMDKIMAGE));
4399 if (!pImage)
4400 {
4401 rc = VERR_NO_MEMORY;
4402 goto out;
4403 }
4404 pImage->pszFilename = pszFilename;
4405 pImage->pFile = NULL;
4406 pImage->pExtents = NULL;
4407 pImage->pFiles = NULL;
4408 pImage->pGTCache = NULL;
4409 pImage->pDescData = NULL;
4410 pImage->pVDIfsDisk = pVDIfsDisk;
4411
4412 rc = vmdkOpenImage(pImage, uOpenFlags);
4413 if (RT_SUCCESS(rc))
4414 *ppBackendData = pImage;
4415
4416out:
4417 LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
4418 return rc;
4419}
4420
4421/** @copydoc VBOXHDDBACKEND::pfnCreate */
4422static int vmdkCreate(const char *pszFilename, uint64_t cbSize,
4423 unsigned uImageFlags, const char *pszComment,
4424 PCPDMMEDIAGEOMETRY pPCHSGeometry,
4425 PCPDMMEDIAGEOMETRY pLCHSGeometry, PCRTUUID pUuid,
4426 unsigned uOpenFlags, unsigned uPercentStart,
4427 unsigned uPercentSpan, PVDINTERFACE pVDIfsDisk,
4428 PVDINTERFACE pVDIfsImage, PVDINTERFACE pVDIfsOperation,
4429 void **ppBackendData)
4430{
4431 LogFlowFunc(("pszFilename=\"%s\" cbSize=%llu uImageFlags=%#x pszComment=\"%s\" pPCHSGeometry=%#p pLCHSGeometry=%#p Uuid=%RTuuid uOpenFlags=%#x uPercentStart=%u uPercentSpan=%u pVDIfsDisk=%#p pVDIfsImage=%#p pVDIfsOperation=%#p ppBackendData=%#p", pszFilename, cbSize, uImageFlags, pszComment, pPCHSGeometry, pLCHSGeometry, pUuid, uOpenFlags, uPercentStart, uPercentSpan, pVDIfsDisk, pVDIfsImage, pVDIfsOperation, ppBackendData));
4432 int rc;
4433 PVMDKIMAGE pImage;
4434
4435 PFNVMPROGRESS pfnProgress = NULL;
4436 void *pvUser = NULL;
4437 PVDINTERFACE pIfProgress = VDInterfaceGet(pVDIfsOperation,
4438 VDINTERFACETYPE_PROGRESS);
4439 PVDINTERFACEPROGRESS pCbProgress = NULL;
4440 if (pIfProgress)
4441 {
4442 pCbProgress = VDGetInterfaceProgress(pIfProgress);
4443 pfnProgress = pCbProgress->pfnProgress;
4444 pvUser = pIfProgress->pvUser;
4445 }
4446
4447 /* Check open flags. All valid flags are supported. */
4448 if (uOpenFlags & ~VD_OPEN_FLAGS_MASK)
4449 {
4450 rc = VERR_INVALID_PARAMETER;
4451 goto out;
4452 }
4453
4454 /* Check remaining arguments. */
4455 if ( !VALID_PTR(pszFilename)
4456 || !*pszFilename
4457 || strchr(pszFilename, '"')
4458 || !VALID_PTR(pPCHSGeometry)
4459 || !VALID_PTR(pLCHSGeometry)
4460 || ( (uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
4461 && (uImageFlags & ~(VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED | VD_IMAGE_FLAGS_DIFF))))
4462 {
4463 rc = VERR_INVALID_PARAMETER;
4464 goto out;
4465 }
4466
4467 pImage = (PVMDKIMAGE)RTMemAllocZ(sizeof(VMDKIMAGE));
4468 if (!pImage)
4469 {
4470 rc = VERR_NO_MEMORY;
4471 goto out;
4472 }
4473 pImage->pszFilename = pszFilename;
4474 pImage->pFile = NULL;
4475 pImage->pExtents = NULL;
4476 pImage->pFiles = NULL;
4477 pImage->pGTCache = NULL;
4478 pImage->pDescData = NULL;
4479 pImage->pVDIfsDisk = NULL;
4480 pImage->cbDescAlloc = VMDK_SECTOR2BYTE(20);
4481 pImage->pDescData = (char *)RTMemAllocZ(pImage->cbDescAlloc);
4482 if (!pImage->pDescData)
4483 {
4484 rc = VERR_NO_MEMORY;
4485 goto out;
4486 }
4487
4488 rc = vmdkCreateImage(pImage, cbSize, uImageFlags, pszComment,
4489 pPCHSGeometry, pLCHSGeometry, pUuid,
4490 pfnProgress, pvUser, uPercentStart, uPercentSpan);
4491 if (RT_SUCCESS(rc))
4492 {
4493 /* So far the image is opened in read/write mode. Make sure the
4494 * image is opened in read-only mode if the caller requested that. */
4495 if (uOpenFlags & VD_OPEN_FLAGS_READONLY)
4496 {
4497 vmdkFreeImage(pImage, false);
4498 rc = vmdkOpenImage(pImage, uOpenFlags);
4499 if (RT_FAILURE(rc))
4500 goto out;
4501 }
4502 *ppBackendData = pImage;
4503 }
4504 else
4505 {
4506 RTMemFree(pImage->pDescData);
4507 RTMemFree(pImage);
4508 }
4509
4510out:
4511 LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
4512 return rc;
4513}
4514
4515/**
4516 * Replaces a fragment of a string with the specified string.
4517 *
4518 * @returns Pointer to the allocated UTF-8 string.
4519 * @param pszWhere UTF-8 string to search in.
4520 * @param pszWhat UTF-8 string to search for.
4521 * @param pszByWhat UTF-8 string to replace the found string with.
4522 */
4523static char * vmdkStrReplace(const char *pszWhere, const char *pszWhat, const char *pszByWhat)
4524{
4525 AssertPtr(pszWhere);
4526 AssertPtr(pszWhat);
4527 AssertPtr(pszByWhat);
4528 const char *pszFoundStr = strstr(pszWhere, pszWhat);
4529 if (!pszFoundStr)
4530 return NULL;
4531 size_t cFinal = strlen(pszWhere) + 1 + strlen(pszByWhat) - strlen(pszWhat);
4532 char *pszNewStr = (char *)RTMemAlloc(cFinal);
4533 if (pszNewStr)
4534 {
4535 char *pszTmp = pszNewStr;
4536 memcpy(pszTmp, pszWhere, pszFoundStr - pszWhere);
4537 pszTmp += pszFoundStr - pszWhere;
4538 memcpy(pszTmp, pszByWhat, strlen(pszByWhat));
4539 pszTmp += strlen(pszByWhat);
4540 strcpy(pszTmp, pszFoundStr + strlen(pszWhat));
4541 }
4542 return pszNewStr;
4543}
4544
4545/** @copydoc VBOXHDDBACKEND::pfnRename */
4546static int vmdkRename(void *pBackendData, const char *pszFilename)
4547{
4548 LogFlowFunc(("pBackendData=%#p pszFilename=%#p\n", pBackendData, pszFilename));
4549
4550 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
4551 int rc = VINF_SUCCESS;
4552 char **apszOldName = NULL;
4553 char **apszNewName = NULL;
4554 char **apszNewLines = NULL;
4555 char *pszOldDescName = NULL;
4556 bool fImageFreed = false;
4557 bool fEmbeddedDesc = false;
4558 unsigned cExtents = pImage->cExtents;
4559 char *pszNewBaseName = NULL;
4560 char *pszOldBaseName = NULL;
4561 char *pszNewFullName = NULL;
4562 char *pszOldFullName = NULL;
4563 const char *pszOldImageName;
4564 unsigned i, line;
4565 VMDKDESCRIPTOR DescriptorCopy;
4566 VMDKEXTENT ExtentCopy;
4567
4568 memset(&DescriptorCopy, 0, sizeof(DescriptorCopy));
4569
4570 /* Check arguments. */
4571 if ( !pImage
4572 || (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_RAWDISK)
4573 || !VALID_PTR(pszFilename)
4574 || !*pszFilename)
4575 {
4576 rc = VERR_INVALID_PARAMETER;
4577 goto out;
4578 }
4579
4580 /*
4581 * Allocate an array to store both old and new names of renamed files
4582 * in case we have to roll back the changes. Arrays are initialized
4583 * with zeros. We actually save stuff when and if we change it.
4584 */
4585 apszOldName = (char **)RTMemTmpAllocZ((cExtents + 1) * sizeof(char*));
4586 apszNewName = (char **)RTMemTmpAllocZ((cExtents + 1) * sizeof(char*));
4587 apszNewLines = (char **)RTMemTmpAllocZ((cExtents) * sizeof(char*));
4588 if (!apszOldName || !apszNewName || !apszNewLines)
4589 {
4590 rc = VERR_NO_MEMORY;
4591 goto out;
4592 }
4593
4594 /* Save the descriptor size and position. */
4595 if (pImage->pDescData)
4596 {
4597 /* Separate descriptor file. */
4598 fEmbeddedDesc = false;
4599 }
4600 else
4601 {
4602 /* Embedded descriptor file. */
4603 ExtentCopy = pImage->pExtents[0];
4604 fEmbeddedDesc = true;
4605 }
4606 /* Save the descriptor content. */
4607 DescriptorCopy.cLines = pImage->Descriptor.cLines;
4608 for (i = 0; i < DescriptorCopy.cLines; i++)
4609 {
4610 DescriptorCopy.aLines[i] = RTStrDup(pImage->Descriptor.aLines[i]);
4611 if (!DescriptorCopy.aLines[i])
4612 {
4613 rc = VERR_NO_MEMORY;
4614 goto out;
4615 }
4616 }
4617
4618 /* Prepare both old and new base names used for string replacement. */
4619 pszNewBaseName = RTStrDup(RTPathFilename(pszFilename));
4620 RTPathStripExt(pszNewBaseName);
4621 pszOldBaseName = RTStrDup(RTPathFilename(pImage->pszFilename));
4622 RTPathStripExt(pszOldBaseName);
4623 /* Prepare both old and new full names used for string replacement. */
4624 pszNewFullName = RTStrDup(pszFilename);
4625 RTPathStripExt(pszNewFullName);
4626 pszOldFullName = RTStrDup(pImage->pszFilename);
4627 RTPathStripExt(pszOldFullName);
4628
4629 /* --- Up to this point we have not done any damage yet. --- */
4630
4631 /* Save the old name for easy access to the old descriptor file. */
4632 pszOldDescName = RTStrDup(pImage->pszFilename);
4633 /* Save old image name. */
4634 pszOldImageName = pImage->pszFilename;
4635
4636 /* Update the descriptor with modified extent names. */
4637 for (i = 0, line = pImage->Descriptor.uFirstExtent;
4638 i < cExtents;
4639 i++, line = pImage->Descriptor.aNextLines[line])
4640 {
4641 /* Assume that vmdkStrReplace will fail. */
4642 rc = VERR_NO_MEMORY;
4643 /* Update the descriptor. */
4644 apszNewLines[i] = vmdkStrReplace(pImage->Descriptor.aLines[line],
4645 pszOldBaseName, pszNewBaseName);
4646 if (!apszNewLines[i])
4647 goto rollback;
4648 pImage->Descriptor.aLines[line] = apszNewLines[i];
4649 }
4650 /* Make sure the descriptor gets written back. */
4651 pImage->Descriptor.fDirty = true;
4652 /* Flush the descriptor now, in case it is embedded. */
4653 (void)vmdkFlushImage(pImage);
4654
4655 /* Close and rename/move extents. */
4656 for (i = 0; i < cExtents; i++)
4657 {
4658 PVMDKEXTENT pExtent = &pImage->pExtents[i];
4659 /* Compose new name for the extent. */
4660 apszNewName[i] = vmdkStrReplace(pExtent->pszFullname,
4661 pszOldFullName, pszNewFullName);
4662 if (!apszNewName[i])
4663 goto rollback;
4664 /* Close the extent file. */
4665 vmdkFileClose(pImage, &pExtent->pFile, false);
4666 /* Rename the extent file. */
4667 rc = RTFileMove(pExtent->pszFullname, apszNewName[i], 0);
4668 if (RT_FAILURE(rc))
4669 goto rollback;
4670 /* Remember the old name. */
4671 apszOldName[i] = RTStrDup(pExtent->pszFullname);
4672 }
4673 /* Release all old stuff. */
4674 vmdkFreeImage(pImage, false);
4675
4676 fImageFreed = true;
4677
4678 /* Last elements of new/old name arrays are intended for
4679 * storing descriptor's names.
4680 */
4681 apszNewName[cExtents] = RTStrDup(pszFilename);
4682 /* Rename the descriptor file if it's separate. */
4683 if (!fEmbeddedDesc)
4684 {
4685 rc = RTFileMove(pImage->pszFilename, apszNewName[cExtents], 0);
4686 if (RT_FAILURE(rc))
4687 goto rollback;
4688 /* Save old name only if we may need to change it back. */
4689 apszOldName[cExtents] = RTStrDup(pszFilename);
4690 }
4691
4692 /* Update pImage with the new information. */
4693 pImage->pszFilename = pszFilename;
4694
4695 /* Open the new image. */
4696 rc = vmdkOpenImage(pImage, pImage->uOpenFlags);
4697 if (RT_SUCCESS(rc))
4698 goto out;
4699
4700rollback:
4701 /* Roll back all changes in case of failure. */
4702 if (RT_FAILURE(rc))
4703 {
4704 int rrc;
4705 if (!fImageFreed)
4706 {
4707 /*
4708 * Some extents may have been closed, close the rest. We will
4709 * re-open the whole thing later.
4710 */
4711 vmdkFreeImage(pImage, false);
4712 }
4713 /* Rename files back. */
4714 for (i = 0; i <= cExtents; i++)
4715 {
4716 if (apszOldName[i])
4717 {
4718 rrc = RTFileMove(apszNewName[i], apszOldName[i], 0);
4719 AssertRC(rrc);
4720 }
4721 }
4722 /* Restore the old descriptor. */
4723 PVMDKFILE pFile;
4724 rrc = vmdkFileOpen(pImage, &pFile, pszOldDescName,
4725 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE, false);
4726 AssertRC(rrc);
4727 if (fEmbeddedDesc)
4728 {
4729 ExtentCopy.pFile = pFile;
4730 pImage->pExtents = &ExtentCopy;
4731 }
4732 else
4733 {
4734 /* Shouldn't be null for separate descriptor.
4735 * There will be no access to the actual content.
4736 */
4737 pImage->pDescData = pszOldDescName;
4738 pImage->pFile = pFile;
4739 }
4740 pImage->Descriptor = DescriptorCopy;
4741 vmdkWriteDescriptor(pImage);
4742 vmdkFileClose(pImage, &pFile, false);
4743 /* Get rid of the stuff we implanted. */
4744 pImage->pExtents = NULL;
4745 pImage->pFile = NULL;
4746 pImage->pDescData = NULL;
4747 /* Re-open the image back. */
4748 pImage->pszFilename = pszOldImageName;
4749 rrc = vmdkOpenImage(pImage, pImage->uOpenFlags);
4750 AssertRC(rrc);
4751 }
4752
4753out:
4754 for (i = 0; i < DescriptorCopy.cLines; i++)
4755 if (DescriptorCopy.aLines[i])
4756 RTStrFree(DescriptorCopy.aLines[i]);
4757 if (apszOldName)
4758 {
4759 for (i = 0; i <= cExtents; i++)
4760 if (apszOldName[i])
4761 RTStrFree(apszOldName[i]);
4762 RTMemTmpFree(apszOldName);
4763 }
4764 if (apszNewName)
4765 {
4766 for (i = 0; i <= cExtents; i++)
4767 if (apszNewName[i])
4768 RTStrFree(apszNewName[i]);
4769 RTMemTmpFree(apszNewName);
4770 }
4771 if (apszNewLines)
4772 {
4773 for (i = 0; i < cExtents; i++)
4774 if (apszNewLines[i])
4775 RTStrFree(apszNewLines[i]);
4776 RTMemTmpFree(apszNewLines);
4777 }
4778 if (pszOldDescName)
4779 RTStrFree(pszOldDescName);
4780 if (pszOldBaseName)
4781 RTStrFree(pszOldBaseName);
4782 if (pszNewBaseName)
4783 RTStrFree(pszNewBaseName);
4784 if (pszOldFullName)
4785 RTStrFree(pszOldFullName);
4786 if (pszNewFullName)
4787 RTStrFree(pszNewFullName);
4788 LogFlowFunc(("returns %Rrc\n", rc));
4789 return rc;
4790}
4791
4792/** @copydoc VBOXHDDBACKEND::pfnClose */
4793static int vmdkClose(void *pBackendData, bool fDelete)
4794{
4795 LogFlowFunc(("pBackendData=%#p fDelete=%d\n", pBackendData, fDelete));
4796 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
4797 int rc = VINF_SUCCESS;
4798
4799 /* Freeing a never allocated image (e.g. because the open failed) is
4800 * not signalled as an error. After all nothing bad happens. */
4801 if (pImage)
4802 {
4803 vmdkFreeImage(pImage, fDelete);
4804 RTMemFree(pImage);
4805 }
4806
4807 LogFlowFunc(("returns %Rrc\n", rc));
4808 return rc;
4809}
4810
4811/** @copydoc VBOXHDDBACKEND::pfnRead */
4812static int vmdkRead(void *pBackendData, uint64_t uOffset, void *pvBuf,
4813 size_t cbToRead, size_t *pcbActuallyRead)
4814{
4815 LogFlowFunc(("pBackendData=%#p uOffset=%llu pvBuf=%#p cbToRead=%zu pcbActuallyRead=%#p\n", pBackendData, uOffset, pvBuf, cbToRead, pcbActuallyRead));
4816 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
4817 PVMDKEXTENT pExtent;
4818 uint64_t uSectorExtentRel;
4819 uint64_t uSectorExtentAbs;
4820 int rc;
4821
4822 AssertPtr(pImage);
4823 Assert(uOffset % 512 == 0);
4824 Assert(cbToRead % 512 == 0);
4825
4826 if ( uOffset + cbToRead > pImage->cbSize
4827 || cbToRead == 0)
4828 {
4829 rc = VERR_INVALID_PARAMETER;
4830 goto out;
4831 }
4832
4833 rc = vmdkFindExtent(pImage, VMDK_BYTE2SECTOR(uOffset),
4834 &pExtent, &uSectorExtentRel);
4835 if (RT_FAILURE(rc))
4836 goto out;
4837
4838 /* Check access permissions as defined in the extent descriptor. */
4839 if (pExtent->enmAccess == VMDKACCESS_NOACCESS)
4840 {
4841 rc = VERR_VD_VMDK_INVALID_STATE;
4842 goto out;
4843 }
4844
4845 /* Clip read range to remain in this extent. */
4846 cbToRead = RT_MIN(cbToRead, VMDK_SECTOR2BYTE(pExtent->uSectorOffset + pExtent->cNominalSectors - uSectorExtentRel));
4847
4848 /* Handle the read according to the current extent type. */
4849 switch (pExtent->enmType)
4850 {
4851 case VMDKETYPE_HOSTED_SPARSE:
4852#ifdef VBOX_WITH_VMDK_ESX
4853 case VMDKETYPE_ESX_SPARSE:
4854#endif /* VBOX_WITH_VMDK_ESX */
4855 rc = vmdkGetSector(pImage->pGTCache, pExtent, uSectorExtentRel,
4856 &uSectorExtentAbs);
4857 if (RT_FAILURE(rc))
4858 goto out;
4859 /* Clip read range to at most the rest of the grain. */
4860 cbToRead = RT_MIN(cbToRead, VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain - uSectorExtentRel % pExtent->cSectorsPerGrain));
4861 Assert(!(cbToRead % 512));
4862 if (uSectorExtentAbs == 0)
4863 rc = VERR_VD_BLOCK_FREE;
4864 else
4865 {
4866 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
4867 {
4868 uint32_t uSectorInGrain = uSectorExtentRel % pExtent->cSectorsPerGrain;
4869 uSectorExtentAbs -= uSectorInGrain;
4870 uint64_t uLBA;
4871 if (pExtent->uGrainSector != uSectorExtentAbs)
4872 {
4873 rc = vmdkFileInflateAt(pExtent->pFile, VMDK_SECTOR2BYTE(uSectorExtentAbs),
4874 pExtent->pvGrain, VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain), VMDK_MARKER_IGNORE, &uLBA, NULL);
4875 if (RT_FAILURE(rc))
4876 {
4877 pExtent->uGrainSector = 0;
4878 AssertRC(rc);
4879 goto out;
4880 }
4881 pExtent->uGrainSector = uSectorExtentAbs;
4882 Assert(uLBA == uSectorExtentRel);
4883 }
4884 memcpy(pvBuf, (uint8_t *)pExtent->pvGrain + VMDK_SECTOR2BYTE(uSectorInGrain), cbToRead);
4885 }
4886 else
4887 {
4888 rc = vmdkFileReadAt(pExtent->pFile,
4889 VMDK_SECTOR2BYTE(uSectorExtentAbs),
4890 pvBuf, cbToRead, NULL);
4891 }
4892 }
4893 break;
4894 case VMDKETYPE_FLAT:
4895 rc = vmdkFileReadAt(pExtent->pFile,
4896 VMDK_SECTOR2BYTE(uSectorExtentRel),
4897 pvBuf, cbToRead, NULL);
4898 break;
4899 case VMDKETYPE_ZERO:
4900 memset(pvBuf, '\0', cbToRead);
4901 break;
4902 }
4903 if (pcbActuallyRead)
4904 *pcbActuallyRead = cbToRead;
4905
4906out:
4907 LogFlowFunc(("returns %Rrc\n", rc));
4908 return rc;
4909}
4910
4911/** @copydoc VBOXHDDBACKEND::pfnWrite */
4912static int vmdkWrite(void *pBackendData, uint64_t uOffset, const void *pvBuf,
4913 size_t cbToWrite, size_t *pcbWriteProcess,
4914 size_t *pcbPreRead, size_t *pcbPostRead, unsigned fWrite)
4915{
4916 LogFlowFunc(("pBackendData=%#p uOffset=%llu pvBuf=%#p cbToWrite=%zu pcbWriteProcess=%#p pcbPreRead=%#p pcbPostRead=%#p\n", pBackendData, uOffset, pvBuf, cbToWrite, pcbWriteProcess, pcbPreRead, pcbPostRead));
4917 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
4918 PVMDKEXTENT pExtent;
4919 uint64_t uSectorExtentRel;
4920 uint64_t uSectorExtentAbs;
4921 int rc;
4922
4923 AssertPtr(pImage);
4924 Assert(uOffset % 512 == 0);
4925 Assert(cbToWrite % 512 == 0);
4926
4927 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
4928 {
4929 rc = VERR_VD_IMAGE_READ_ONLY;
4930 goto out;
4931 }
4932
4933 if (cbToWrite == 0)
4934 {
4935 rc = VERR_INVALID_PARAMETER;
4936 goto out;
4937 }
4938
4939 /* No size check here, will do that later when the extent is located.
4940 * There are sparse images out there which according to the spec are
4941 * invalid, because the total size is not a multiple of the grain size.
4942 * Also for sparse images which are stitched together in odd ways (not at
4943 * grain boundaries, and with the nominal size not being a multiple of the
4944 * grain size), this would prevent writing to the last grain. */
4945
4946 rc = vmdkFindExtent(pImage, VMDK_BYTE2SECTOR(uOffset),
4947 &pExtent, &uSectorExtentRel);
4948 if (RT_FAILURE(rc))
4949 goto out;
4950
4951 /* Check access permissions as defined in the extent descriptor. */
4952 if (pExtent->enmAccess != VMDKACCESS_READWRITE)
4953 {
4954 rc = VERR_VD_VMDK_INVALID_STATE;
4955 goto out;
4956 }
4957
4958 /* Handle the write according to the current extent type. */
4959 switch (pExtent->enmType)
4960 {
4961 case VMDKETYPE_HOSTED_SPARSE:
4962#ifdef VBOX_WITH_VMDK_ESX
4963 case VMDKETYPE_ESX_SPARSE:
4964#endif /* VBOX_WITH_VMDK_ESX */
4965 rc = vmdkGetSector(pImage->pGTCache, pExtent, uSectorExtentRel,
4966 &uSectorExtentAbs);
4967 if (RT_FAILURE(rc))
4968 goto out;
4969 /* Clip write range to at most the rest of the grain. */
4970 cbToWrite = RT_MIN(cbToWrite, VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain - uSectorExtentRel % pExtent->cSectorsPerGrain));
4971 if ( pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED
4972 && uSectorExtentRel < (uint64_t)pExtent->uLastGrainWritten * pExtent->cSectorsPerGrain)
4973 {
4974 rc = VERR_VD_VMDK_INVALID_WRITE;
4975 goto out;
4976 }
4977 if (uSectorExtentAbs == 0)
4978 {
4979 if (cbToWrite == VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain))
4980 {
4981 /* Full block write to a previously unallocated block.
4982 * Check if the caller wants to avoid the automatic alloc. */
4983 if (!(fWrite & VD_WRITE_NO_ALLOC))
4984 {
4985 /* Allocate GT and find out where to store the grain. */
4986 rc = vmdkAllocGrain(pImage->pGTCache, pExtent,
4987 uSectorExtentRel, pvBuf, cbToWrite);
4988 }
4989 else
4990 rc = VERR_VD_BLOCK_FREE;
4991 *pcbPreRead = 0;
4992 *pcbPostRead = 0;
4993 }
4994 else
4995 {
4996 /* Clip write range to remain in this extent. */
4997 cbToWrite = RT_MIN(cbToWrite, VMDK_SECTOR2BYTE(pExtent->uSectorOffset + pExtent->cNominalSectors - uSectorExtentRel));
4998 *pcbPreRead = VMDK_SECTOR2BYTE(uSectorExtentRel % pExtent->cSectorsPerGrain);
4999 *pcbPostRead = VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain) - cbToWrite - *pcbPreRead;
5000 rc = VERR_VD_BLOCK_FREE;
5001 }
5002 }
5003 else
5004 {
5005 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
5006 {
5007 uint32_t uSectorInGrain = uSectorExtentRel % pExtent->cSectorsPerGrain;
5008 uSectorExtentAbs -= uSectorInGrain;
5009 uint64_t uLBA;
5010 if ( pExtent->uGrainSector != uSectorExtentAbs
5011 || pExtent->uGrainSector != pExtent->uLastGrainSector)
5012 {
5013 rc = vmdkFileInflateAt(pExtent->pFile, VMDK_SECTOR2BYTE(uSectorExtentAbs),
5014 pExtent->pvGrain, VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain), VMDK_MARKER_IGNORE, &uLBA, NULL);
5015 if (RT_FAILURE(rc))
5016 {
5017 pExtent->uGrainSector = 0;
5018 pExtent->uLastGrainSector = 0;
5019 AssertRC(rc);
5020 goto out;
5021 }
5022 pExtent->uGrainSector = uSectorExtentAbs;
5023 pExtent->uLastGrainSector = uSectorExtentAbs;
5024 Assert(uLBA == uSectorExtentRel);
5025 }
5026 memcpy((uint8_t *)pExtent->pvGrain + VMDK_SECTOR2BYTE(uSectorInGrain), pvBuf, cbToWrite);
5027 uint32_t cbGrain = 0;
5028 rc = vmdkFileDeflateAt(pExtent->pFile,
5029 VMDK_SECTOR2BYTE(uSectorExtentAbs),
5030 pExtent->pvGrain, VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain),
5031 VMDK_MARKER_IGNORE, uLBA, &cbGrain);
5032 if (RT_FAILURE(rc))
5033 {
5034 pExtent->uGrainSector = 0;
5035 pExtent->uLastGrainSector = 0;
5036 AssertRC(rc);
5037 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: cannot write compressed data block in '%s'"), pExtent->pszFullname);
5038 }
5039 cbGrain = RT_ALIGN(cbGrain, 512);
5040 pExtent->uLastGrainSector = uSectorExtentAbs;
5041 pExtent->uLastGrainWritten = uSectorExtentRel / pExtent->cSectorsPerGrain;
5042 pExtent->cbLastGrainWritten = cbGrain;
5043
5044 uint64_t uEOSOff = 0;
5045 if (pExtent->fFooter)
5046 {
5047 uEOSOff = 512;
5048 rc = vmdkWriteMetaSparseExtent(pExtent, VMDK_SECTOR2BYTE(uSectorExtentAbs) + RT_ALIGN(cbGrain, 512));
5049 if (RT_FAILURE(rc))
5050 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: cannot write footer after data block in '%s'"), pExtent->pszFullname);
5051 }
5052 uint8_t aEOS[512];
5053 memset(aEOS, '\0', sizeof(aEOS));
5054 rc = vmdkFileWriteAt(pExtent->pFile,
5055 VMDK_SECTOR2BYTE(uSectorExtentAbs) + RT_ALIGN(cbGrain, 512) + uEOSOff,
5056 aEOS, sizeof(aEOS), NULL);
5057 if (RT_FAILURE(rc))
5058 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: cannot write end-of stream marker after data block in '%s'"), pExtent->pszFullname);
5059 }
5060 else
5061 {
5062 rc = vmdkFileWriteAt(pExtent->pFile,
5063 VMDK_SECTOR2BYTE(uSectorExtentAbs),
5064 pvBuf, cbToWrite, NULL);
5065 }
5066 }
5067 break;
5068 case VMDKETYPE_FLAT:
5069 /* Clip write range to remain in this extent. */
5070 cbToWrite = RT_MIN(cbToWrite, VMDK_SECTOR2BYTE(pExtent->uSectorOffset + pExtent->cNominalSectors - uSectorExtentRel));
5071 rc = vmdkFileWriteAt(pExtent->pFile,
5072 VMDK_SECTOR2BYTE(uSectorExtentRel),
5073 pvBuf, cbToWrite, NULL);
5074 break;
5075 case VMDKETYPE_ZERO:
5076 /* Clip write range to remain in this extent. */
5077 cbToWrite = RT_MIN(cbToWrite, VMDK_SECTOR2BYTE(pExtent->uSectorOffset + pExtent->cNominalSectors - uSectorExtentRel));
5078 break;
5079 }
5080 if (pcbWriteProcess)
5081 *pcbWriteProcess = cbToWrite;
5082
5083out:
5084 LogFlowFunc(("returns %Rrc\n", rc));
5085 return rc;
5086}
5087
5088/** @copydoc VBOXHDDBACKEND::pfnFlush */
5089static int vmdkFlush(void *pBackendData)
5090{
5091 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
5092 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5093 int rc;
5094
5095 AssertPtr(pImage);
5096
5097 rc = vmdkFlushImage(pImage);
5098 LogFlowFunc(("returns %Rrc\n", rc));
5099 return rc;
5100}
5101
5102/** @copydoc VBOXHDDBACKEND::pfnGetVersion */
5103static unsigned vmdkGetVersion(void *pBackendData)
5104{
5105 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
5106 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5107
5108 AssertPtr(pImage);
5109
5110 if (pImage)
5111 return VMDK_IMAGE_VERSION;
5112 else
5113 return 0;
5114}
5115
5116/** @copydoc VBOXHDDBACKEND::pfnGetSize */
5117static uint64_t vmdkGetSize(void *pBackendData)
5118{
5119 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
5120 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5121
5122 AssertPtr(pImage);
5123
5124 if (pImage)
5125 return pImage->cbSize;
5126 else
5127 return 0;
5128}
5129
5130/** @copydoc VBOXHDDBACKEND::pfnGetFileSize */
5131static uint64_t vmdkGetFileSize(void *pBackendData)
5132{
5133 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
5134 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5135 uint64_t cb = 0;
5136
5137 AssertPtr(pImage);
5138
5139 if (pImage)
5140 {
5141 uint64_t cbFile;
5142 if (pImage->pFile != NULL)
5143 {
5144 int rc = vmdkFileGetSize(pImage->pFile, &cbFile);
5145 if (RT_SUCCESS(rc))
5146 cb += cbFile;
5147 }
5148 for (unsigned i = 0; i < pImage->cExtents; i++)
5149 {
5150 if (pImage->pExtents[i].pFile != NULL)
5151 {
5152 int rc = vmdkFileGetSize(pImage->pExtents[i].pFile, &cbFile);
5153 if (RT_SUCCESS(rc))
5154 cb += cbFile;
5155 }
5156 }
5157 }
5158
5159 LogFlowFunc(("returns %lld\n", cb));
5160 return cb;
5161}
5162
5163/** @copydoc VBOXHDDBACKEND::pfnGetPCHSGeometry */
5164static int vmdkGetPCHSGeometry(void *pBackendData,
5165 PPDMMEDIAGEOMETRY pPCHSGeometry)
5166{
5167 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p\n", pBackendData, pPCHSGeometry));
5168 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5169 int rc;
5170
5171 AssertPtr(pImage);
5172
5173 if (pImage)
5174 {
5175 if (pImage->PCHSGeometry.cCylinders)
5176 {
5177 *pPCHSGeometry = pImage->PCHSGeometry;
5178 rc = VINF_SUCCESS;
5179 }
5180 else
5181 rc = VERR_VD_GEOMETRY_NOT_SET;
5182 }
5183 else
5184 rc = VERR_VD_NOT_OPENED;
5185
5186 LogFlowFunc(("returns %Rrc (PCHS=%u/%u/%u)\n", rc, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
5187 return rc;
5188}
5189
5190/** @copydoc VBOXHDDBACKEND::pfnSetPCHSGeometry */
5191static int vmdkSetPCHSGeometry(void *pBackendData,
5192 PCPDMMEDIAGEOMETRY pPCHSGeometry)
5193{
5194 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p PCHS=%u/%u/%u\n", pBackendData, pPCHSGeometry, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
5195 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5196 int rc;
5197
5198 AssertPtr(pImage);
5199
5200 if (pImage)
5201 {
5202 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
5203 {
5204 rc = VERR_VD_IMAGE_READ_ONLY;
5205 goto out;
5206 }
5207 rc = vmdkDescSetPCHSGeometry(pImage, pPCHSGeometry);
5208 if (RT_FAILURE(rc))
5209 goto out;
5210
5211 pImage->PCHSGeometry = *pPCHSGeometry;
5212 rc = VINF_SUCCESS;
5213 }
5214 else
5215 rc = VERR_VD_NOT_OPENED;
5216
5217out:
5218 LogFlowFunc(("returns %Rrc\n", rc));
5219 return rc;
5220}
5221
5222/** @copydoc VBOXHDDBACKEND::pfnGetLCHSGeometry */
5223static int vmdkGetLCHSGeometry(void *pBackendData,
5224 PPDMMEDIAGEOMETRY pLCHSGeometry)
5225{
5226 LogFlowFunc(("pBackendData=%#p pLCHSGeometry=%#p\n", pBackendData, pLCHSGeometry));
5227 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5228 int rc;
5229
5230 AssertPtr(pImage);
5231
5232 if (pImage)
5233 {
5234 if (pImage->LCHSGeometry.cCylinders)
5235 {
5236 *pLCHSGeometry = pImage->LCHSGeometry;
5237 rc = VINF_SUCCESS;
5238 }
5239 else
5240 rc = VERR_VD_GEOMETRY_NOT_SET;
5241 }
5242 else
5243 rc = VERR_VD_NOT_OPENED;
5244
5245 LogFlowFunc(("returns %Rrc (LCHS=%u/%u/%u)\n", rc, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
5246 return rc;
5247}
5248
5249/** @copydoc VBOXHDDBACKEND::pfnSetLCHSGeometry */
5250static int vmdkSetLCHSGeometry(void *pBackendData,
5251 PCPDMMEDIAGEOMETRY pLCHSGeometry)
5252{
5253 LogFlowFunc(("pBackendData=%#p pLCHSGeometry=%#p LCHS=%u/%u/%u\n", pBackendData, pLCHSGeometry, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
5254 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5255 int rc;
5256
5257 AssertPtr(pImage);
5258
5259 if (pImage)
5260 {
5261 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
5262 {
5263 rc = VERR_VD_IMAGE_READ_ONLY;
5264 goto out;
5265 }
5266 rc = vmdkDescSetLCHSGeometry(pImage, pLCHSGeometry);
5267 if (RT_FAILURE(rc))
5268 goto out;
5269
5270 pImage->LCHSGeometry = *pLCHSGeometry;
5271 rc = VINF_SUCCESS;
5272 }
5273 else
5274 rc = VERR_VD_NOT_OPENED;
5275
5276out:
5277 LogFlowFunc(("returns %Rrc\n", rc));
5278 return rc;
5279}
5280
5281/** @copydoc VBOXHDDBACKEND::pfnGetImageFlags */
5282static unsigned vmdkGetImageFlags(void *pBackendData)
5283{
5284 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
5285 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5286 unsigned uImageFlags;
5287
5288 AssertPtr(pImage);
5289
5290 if (pImage)
5291 uImageFlags = pImage->uImageFlags;
5292 else
5293 uImageFlags = 0;
5294
5295 LogFlowFunc(("returns %#x\n", uImageFlags));
5296 return uImageFlags;
5297}
5298
5299/** @copydoc VBOXHDDBACKEND::pfnGetOpenFlags */
5300static unsigned vmdkGetOpenFlags(void *pBackendData)
5301{
5302 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
5303 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5304 unsigned uOpenFlags;
5305
5306 AssertPtr(pImage);
5307
5308 if (pImage)
5309 uOpenFlags = pImage->uOpenFlags;
5310 else
5311 uOpenFlags = 0;
5312
5313 LogFlowFunc(("returns %#x\n", uOpenFlags));
5314 return uOpenFlags;
5315}
5316
5317/** @copydoc VBOXHDDBACKEND::pfnSetOpenFlags */
5318static int vmdkSetOpenFlags(void *pBackendData, unsigned uOpenFlags)
5319{
5320 LogFlowFunc(("pBackendData=%#p\n uOpenFlags=%#x", pBackendData, uOpenFlags));
5321 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5322 int rc;
5323
5324 /* Image must be opened and the new flags must be valid. Just readonly and
5325 * info flags are supported. */
5326 if (!pImage || (uOpenFlags & ~(VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO | VD_OPEN_FLAGS_ASYNC_IO)))
5327 {
5328 rc = VERR_INVALID_PARAMETER;
5329 goto out;
5330 }
5331
5332 /* Implement this operation via reopening the image. */
5333 vmdkFreeImage(pImage, false);
5334 rc = vmdkOpenImage(pImage, uOpenFlags);
5335
5336out:
5337 LogFlowFunc(("returns %Rrc\n", rc));
5338 return rc;
5339}
5340
5341/** @copydoc VBOXHDDBACKEND::pfnGetComment */
5342static int vmdkGetComment(void *pBackendData, char *pszComment,
5343 size_t cbComment)
5344{
5345 LogFlowFunc(("pBackendData=%#p pszComment=%#p cbComment=%zu\n", pBackendData, pszComment, cbComment));
5346 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5347 int rc;
5348
5349 AssertPtr(pImage);
5350
5351 if (pImage)
5352 {
5353 const char *pszCommentEncoded = NULL;
5354 rc = vmdkDescDDBGetStr(pImage, &pImage->Descriptor,
5355 "ddb.comment", &pszCommentEncoded);
5356 if (rc == VERR_VD_VMDK_VALUE_NOT_FOUND)
5357 pszCommentEncoded = NULL;
5358 else if (RT_FAILURE(rc))
5359 goto out;
5360
5361 if (pszComment && pszCommentEncoded)
5362 rc = vmdkDecodeString(pszCommentEncoded, pszComment, cbComment);
5363 else
5364 {
5365 if (pszComment)
5366 *pszComment = '\0';
5367 rc = VINF_SUCCESS;
5368 }
5369 if (pszCommentEncoded)
5370 RTStrFree((char *)(void *)pszCommentEncoded);
5371 }
5372 else
5373 rc = VERR_VD_NOT_OPENED;
5374
5375out:
5376 LogFlowFunc(("returns %Rrc comment='%s'\n", rc, pszComment));
5377 return rc;
5378}
5379
5380/** @copydoc VBOXHDDBACKEND::pfnSetComment */
5381static int vmdkSetComment(void *pBackendData, const char *pszComment)
5382{
5383 LogFlowFunc(("pBackendData=%#p pszComment=\"%s\"\n", pBackendData, pszComment));
5384 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5385 int rc;
5386
5387 AssertPtr(pImage);
5388
5389 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
5390 {
5391 rc = VERR_VD_IMAGE_READ_ONLY;
5392 goto out;
5393 }
5394
5395 if (pImage)
5396 rc = vmdkSetImageComment(pImage, pszComment);
5397 else
5398 rc = VERR_VD_NOT_OPENED;
5399
5400out:
5401 LogFlowFunc(("returns %Rrc\n", rc));
5402 return rc;
5403}
5404
5405/** @copydoc VBOXHDDBACKEND::pfnGetUuid */
5406static int vmdkGetUuid(void *pBackendData, PRTUUID pUuid)
5407{
5408 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
5409 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5410 int rc;
5411
5412 AssertPtr(pImage);
5413
5414 if (pImage)
5415 {
5416 *pUuid = pImage->ImageUuid;
5417 rc = VINF_SUCCESS;
5418 }
5419 else
5420 rc = VERR_VD_NOT_OPENED;
5421
5422 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
5423 return rc;
5424}
5425
5426/** @copydoc VBOXHDDBACKEND::pfnSetUuid */
5427static int vmdkSetUuid(void *pBackendData, PCRTUUID pUuid)
5428{
5429 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
5430 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5431 int rc;
5432
5433 LogFlowFunc(("%RTuuid\n", pUuid));
5434 AssertPtr(pImage);
5435
5436 if (pImage)
5437 {
5438 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
5439 {
5440 pImage->ImageUuid = *pUuid;
5441 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
5442 VMDK_DDB_IMAGE_UUID, pUuid);
5443 if (RT_FAILURE(rc))
5444 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error storing image UUID in descriptor in '%s'"), pImage->pszFilename);
5445 rc = VINF_SUCCESS;
5446 }
5447 else
5448 rc = VERR_VD_IMAGE_READ_ONLY;
5449 }
5450 else
5451 rc = VERR_VD_NOT_OPENED;
5452
5453 LogFlowFunc(("returns %Rrc\n", rc));
5454 return rc;
5455}
5456
5457/** @copydoc VBOXHDDBACKEND::pfnGetModificationUuid */
5458static int vmdkGetModificationUuid(void *pBackendData, PRTUUID pUuid)
5459{
5460 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
5461 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5462 int rc;
5463
5464 AssertPtr(pImage);
5465
5466 if (pImage)
5467 {
5468 *pUuid = pImage->ModificationUuid;
5469 rc = VINF_SUCCESS;
5470 }
5471 else
5472 rc = VERR_VD_NOT_OPENED;
5473
5474 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
5475 return rc;
5476}
5477
5478/** @copydoc VBOXHDDBACKEND::pfnSetModificationUuid */
5479static int vmdkSetModificationUuid(void *pBackendData, PCRTUUID pUuid)
5480{
5481 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
5482 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5483 int rc;
5484
5485 AssertPtr(pImage);
5486
5487 if (pImage)
5488 {
5489 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
5490 {
5491 pImage->ModificationUuid = *pUuid;
5492 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
5493 VMDK_DDB_MODIFICATION_UUID, pUuid);
5494 if (RT_FAILURE(rc))
5495 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error storing modification UUID in descriptor in '%s'"), pImage->pszFilename);
5496 rc = VINF_SUCCESS;
5497 }
5498 else
5499 rc = VERR_VD_IMAGE_READ_ONLY;
5500 }
5501 else
5502 rc = VERR_VD_NOT_OPENED;
5503
5504 LogFlowFunc(("returns %Rrc\n", rc));
5505 return rc;
5506}
5507
5508/** @copydoc VBOXHDDBACKEND::pfnGetParentUuid */
5509static int vmdkGetParentUuid(void *pBackendData, PRTUUID pUuid)
5510{
5511 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
5512 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5513 int rc;
5514
5515 AssertPtr(pImage);
5516
5517 if (pImage)
5518 {
5519 *pUuid = pImage->ParentUuid;
5520 rc = VINF_SUCCESS;
5521 }
5522 else
5523 rc = VERR_VD_NOT_OPENED;
5524
5525 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
5526 return rc;
5527}
5528
5529/** @copydoc VBOXHDDBACKEND::pfnSetParentUuid */
5530static int vmdkSetParentUuid(void *pBackendData, PCRTUUID pUuid)
5531{
5532 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
5533 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5534 int rc;
5535
5536 AssertPtr(pImage);
5537
5538 if (pImage)
5539 {
5540 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
5541 {
5542 pImage->ParentUuid = *pUuid;
5543 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
5544 VMDK_DDB_PARENT_UUID, pUuid);
5545 if (RT_FAILURE(rc))
5546 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error storing parent image UUID in descriptor in '%s'"), pImage->pszFilename);
5547 rc = VINF_SUCCESS;
5548 }
5549 else
5550 rc = VERR_VD_IMAGE_READ_ONLY;
5551 }
5552 else
5553 rc = VERR_VD_NOT_OPENED;
5554
5555 LogFlowFunc(("returns %Rrc\n", rc));
5556 return rc;
5557}
5558
5559/** @copydoc VBOXHDDBACKEND::pfnGetParentModificationUuid */
5560static int vmdkGetParentModificationUuid(void *pBackendData, PRTUUID pUuid)
5561{
5562 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
5563 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5564 int rc;
5565
5566 AssertPtr(pImage);
5567
5568 if (pImage)
5569 {
5570 *pUuid = pImage->ParentModificationUuid;
5571 rc = VINF_SUCCESS;
5572 }
5573 else
5574 rc = VERR_VD_NOT_OPENED;
5575
5576 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
5577 return rc;
5578}
5579
5580/** @copydoc VBOXHDDBACKEND::pfnSetParentModificationUuid */
5581static int vmdkSetParentModificationUuid(void *pBackendData, PCRTUUID pUuid)
5582{
5583 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
5584 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5585 int rc;
5586
5587 AssertPtr(pImage);
5588
5589 if (pImage)
5590 {
5591 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
5592 {
5593 pImage->ParentModificationUuid = *pUuid;
5594 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
5595 VMDK_DDB_PARENT_MODIFICATION_UUID, pUuid);
5596 if (RT_FAILURE(rc))
5597 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error storing parent image UUID in descriptor in '%s'"), pImage->pszFilename);
5598 rc = VINF_SUCCESS;
5599 }
5600 else
5601 rc = VERR_VD_IMAGE_READ_ONLY;
5602 }
5603 else
5604 rc = VERR_VD_NOT_OPENED;
5605
5606 LogFlowFunc(("returns %Rrc\n", rc));
5607 return rc;
5608}
5609
5610/** @copydoc VBOXHDDBACKEND::pfnDump */
5611static void vmdkDump(void *pBackendData)
5612{
5613 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5614
5615 AssertPtr(pImage);
5616 if (pImage)
5617 {
5618 RTLogPrintf("Header: Geometry PCHS=%u/%u/%u LCHS=%u/%u/%u cbSector=%llu\n",
5619 pImage->PCHSGeometry.cCylinders, pImage->PCHSGeometry.cHeads, pImage->PCHSGeometry.cSectors,
5620 pImage->LCHSGeometry.cCylinders, pImage->LCHSGeometry.cHeads, pImage->LCHSGeometry.cSectors,
5621 VMDK_BYTE2SECTOR(pImage->cbSize));
5622 RTLogPrintf("Header: uuidCreation={%RTuuid}\n", &pImage->ImageUuid);
5623 RTLogPrintf("Header: uuidModification={%RTuuid}\n", &pImage->ModificationUuid);
5624 RTLogPrintf("Header: uuidParent={%RTuuid}\n", &pImage->ParentUuid);
5625 RTLogPrintf("Header: uuidParentModification={%RTuuid}\n", &pImage->ParentModificationUuid);
5626 }
5627}
5628
5629
5630static int vmdkGetTimeStamp(void *pvBackendData, PRTTIMESPEC pTimeStamp)
5631{
5632 int rc = VERR_NOT_IMPLEMENTED;
5633 LogFlow(("%s: returned %Rrc\n", __FUNCTION__, rc));
5634 return rc;
5635}
5636
5637static int vmdkGetParentTimeStamp(void *pvBackendData, PRTTIMESPEC pTimeStamp)
5638{
5639 int rc = VERR_NOT_IMPLEMENTED;
5640 LogFlow(("%s: returned %Rrc\n", __FUNCTION__, rc));
5641 return rc;
5642}
5643
5644static int vmdkSetParentTimeStamp(void *pvBackendData, PCRTTIMESPEC pTimeStamp)
5645{
5646 int rc = VERR_NOT_IMPLEMENTED;
5647 LogFlow(("%s: returned %Rrc\n", __FUNCTION__, rc));
5648 return rc;
5649}
5650
5651static int vmdkGetParentFilename(void *pvBackendData, char **ppszParentFilename)
5652{
5653 int rc = VERR_NOT_IMPLEMENTED;
5654 LogFlow(("%s: returned %Rrc\n", __FUNCTION__, rc));
5655 return rc;
5656}
5657
5658static int vmdkSetParentFilename(void *pvBackendData, const char *pszParentFilename)
5659{
5660 int rc = VERR_NOT_IMPLEMENTED;
5661 LogFlow(("%s: returned %Rrc\n", __FUNCTION__, rc));
5662 return rc;
5663}
5664
5665static bool vmdkIsAsyncIOSupported(void *pvBackendData)
5666{
5667 PVMDKIMAGE pImage = (PVMDKIMAGE)pvBackendData;
5668 bool fAsyncIOSupported = false;
5669
5670 if (pImage)
5671 {
5672 /* We only support async I/O support if the image only consists of FLAT or ZERO extents. */
5673 fAsyncIOSupported = true;
5674 for (unsigned i = 0; i < pImage->cExtents; i++)
5675 {
5676 if ( (pImage->pExtents[i].enmType != VMDKETYPE_FLAT)
5677 && (pImage->pExtents[i].enmType != VMDKETYPE_ZERO))
5678 {
5679 fAsyncIOSupported = false;
5680 break; /* Stop search */
5681 }
5682 }
5683 }
5684
5685 return fAsyncIOSupported;
5686}
5687
5688static int vmdkAsyncRead(void *pvBackendData, uint64_t uOffset, size_t cbRead,
5689 PPDMDATASEG paSeg, unsigned cSeg, void *pvUser)
5690{
5691 PVMDKIMAGE pImage = (PVMDKIMAGE)pvBackendData;
5692 PVMDKEXTENT pExtent;
5693 int rc = VINF_SUCCESS;
5694 unsigned cTasksToSubmit = 0;
5695 PPDMDATASEG paSegCurrent = paSeg;
5696 unsigned cbLeftInCurrentSegment = paSegCurrent->cbSeg;
5697 unsigned uOffsetInCurrentSegment = 0;
5698
5699 AssertPtr(pImage);
5700 Assert(uOffset % 512 == 0);
5701 Assert(cbRead % 512 == 0);
5702
5703 if ( uOffset + cbRead > pImage->cbSize
5704 || cbRead == 0)
5705 {
5706 rc = VERR_INVALID_PARAMETER;
5707 goto out;
5708 }
5709
5710 while (cbRead && cSeg)
5711 {
5712 unsigned cbToRead;
5713 uint64_t uSectorExtentRel;
5714
5715 rc = vmdkFindExtent(pImage, VMDK_BYTE2SECTOR(uOffset),
5716 &pExtent, &uSectorExtentRel);
5717 if (RT_FAILURE(rc))
5718 goto out;
5719
5720 /* Check access permissions as defined in the extent descriptor. */
5721 if (pExtent->enmAccess == VMDKACCESS_NOACCESS)
5722 {
5723 rc = VERR_VD_VMDK_INVALID_STATE;
5724 goto out;
5725 }
5726
5727 /* Clip read range to remain in this extent. */
5728 cbToRead = RT_MIN(cbRead, VMDK_SECTOR2BYTE(pExtent->uSectorOffset + pExtent->cNominalSectors - uSectorExtentRel));
5729 /* Clip read range to remain into current data segment. */
5730 cbToRead = RT_MIN(cbToRead, cbLeftInCurrentSegment);
5731
5732 switch (pExtent->enmType)
5733 {
5734 case VMDKETYPE_FLAT:
5735 {
5736 /* Setup new task. */
5737 void *pTask;
5738 rc = pImage->pInterfaceAsyncIOCallbacks->pfnPrepareRead(pImage->pInterfaceAsyncIO->pvUser, pExtent->pFile->pStorage,
5739 VMDK_SECTOR2BYTE(uSectorExtentRel),
5740 (uint8_t *)paSegCurrent->pvSeg + uOffsetInCurrentSegment,
5741 cbToRead, &pTask);
5742 if (RT_FAILURE(rc))
5743 {
5744 AssertMsgFailed(("Preparing read failed rc=%Rrc\n", rc));
5745 goto out;
5746 }
5747
5748 /* Check for enough room first. */
5749 if (cTasksToSubmit >= pImage->cTask)
5750 {
5751 /* We reached maximum, resize array. Try to realloc memory first. */
5752 void **apTaskNew = (void **)RTMemRealloc(pImage->apTask, (cTasksToSubmit + 10)*sizeof(void *));
5753
5754 if (!apTaskNew)
5755 {
5756 /* We failed. Allocate completely new. */
5757 apTaskNew = (void **)RTMemAllocZ((cTasksToSubmit + 10)* sizeof(void *));
5758 if (!apTaskNew)
5759 {
5760 /* Damn, we are out of memory. */
5761 rc = VERR_NO_MEMORY;
5762 goto out;
5763 }
5764
5765 /* Copy task handles over. */
5766 for (unsigned i = 0; i < cTasksToSubmit; i++)
5767 apTaskNew[i] = pImage->apTask[i];
5768
5769 /* Free old memory. */
5770 RTMemFree(pImage->apTask);
5771 }
5772
5773 pImage->cTask = cTasksToSubmit + 10;
5774 pImage->apTask = apTaskNew;
5775 }
5776
5777 pImage->apTask[cTasksToSubmit] = pTask;
5778 cTasksToSubmit++;
5779 break;
5780 }
5781 case VMDKETYPE_ZERO:
5782 memset((uint8_t *)paSegCurrent->pvSeg + uOffsetInCurrentSegment, 0, cbToRead);
5783 break;
5784 default:
5785 AssertMsgFailed(("Unsupported extent type %u\n", pExtent->enmType));
5786 }
5787
5788 cbRead -= cbToRead;
5789 uOffset += cbToRead;
5790 cbLeftInCurrentSegment -= cbToRead;
5791 uOffsetInCurrentSegment += cbToRead;
5792 /* Go to next extent if there is no space left in current one. */
5793 if (!cbLeftInCurrentSegment)
5794 {
5795 uOffsetInCurrentSegment = 0;
5796 paSegCurrent++;
5797 cSeg--;
5798 cbLeftInCurrentSegment = paSegCurrent->cbSeg;
5799 }
5800 }
5801
5802 AssertMsg(cbRead == 0, ("No segment left but there is still data to read\n"));
5803
5804 if (cTasksToSubmit == 0)
5805 {
5806 /* The request was completely in a ZERO extent nothing to do. */
5807 rc = VINF_VD_ASYNC_IO_FINISHED;
5808 }
5809 else
5810 {
5811 /* Submit tasks. */
5812 rc = pImage->pInterfaceAsyncIOCallbacks->pfnTasksSubmit(pImage->pInterfaceAsyncIO->pvUser,
5813 pImage->apTask, cTasksToSubmit,
5814 NULL, pvUser,
5815 NULL /* Nothing required after read. */);
5816 AssertMsgRC(rc, ("Failed to enqueue tasks rc=%Rrc\n", rc));
5817 }
5818
5819out:
5820 LogFlowFunc(("returns %Rrc\n", rc));
5821 return rc;
5822}
5823
5824static int vmdkAsyncWrite(void *pvBackendData, uint64_t uOffset, size_t cbWrite,
5825 PPDMDATASEG paSeg, unsigned cSeg, void *pvUser)
5826{
5827 PVMDKIMAGE pImage = (PVMDKIMAGE)pvBackendData;
5828 PVMDKEXTENT pExtent;
5829 int rc = VINF_SUCCESS;
5830 unsigned cTasksToSubmit = 0;
5831 PPDMDATASEG paSegCurrent = paSeg;
5832 unsigned cbLeftInCurrentSegment = paSegCurrent->cbSeg;
5833 unsigned uOffsetInCurrentSegment = 0;
5834
5835 AssertPtr(pImage);
5836 Assert(uOffset % 512 == 0);
5837 Assert(cbWrite % 512 == 0);
5838
5839 if ( uOffset + cbWrite > pImage->cbSize
5840 || cbWrite == 0)
5841 {
5842 rc = VERR_INVALID_PARAMETER;
5843 goto out;
5844 }
5845
5846 while (cbWrite && cSeg)
5847 {
5848 unsigned cbToWrite;
5849 uint64_t uSectorExtentRel;
5850
5851 rc = vmdkFindExtent(pImage, VMDK_BYTE2SECTOR(uOffset),
5852 &pExtent, &uSectorExtentRel);
5853 if (RT_FAILURE(rc))
5854 goto out;
5855
5856 /* Check access permissions as defined in the extent descriptor. */
5857 if (pExtent->enmAccess == VMDKACCESS_NOACCESS)
5858 {
5859 rc = VERR_VD_VMDK_INVALID_STATE;
5860 goto out;
5861 }
5862
5863 /* Clip write range to remain in this extent. */
5864 cbToWrite = RT_MIN(cbWrite, VMDK_SECTOR2BYTE(pExtent->uSectorOffset + pExtent->cNominalSectors - uSectorExtentRel));
5865 /* Clip write range to remain into current data segment. */
5866 cbToWrite = RT_MIN(cbToWrite, cbLeftInCurrentSegment);
5867
5868 switch (pExtent->enmType)
5869 {
5870 case VMDKETYPE_FLAT:
5871 {
5872 /* Setup new task. */
5873 void *pTask;
5874 rc = pImage->pInterfaceAsyncIOCallbacks->pfnPrepareWrite(pImage->pInterfaceAsyncIO->pvUser, pExtent->pFile->pStorage,
5875 VMDK_SECTOR2BYTE(uSectorExtentRel),
5876 (uint8_t *)paSegCurrent->pvSeg + uOffsetInCurrentSegment,
5877 cbToWrite, &pTask);
5878 if (RT_FAILURE(rc))
5879 {
5880 AssertMsgFailed(("Preparing read failed rc=%Rrc\n", rc));
5881 goto out;
5882 }
5883
5884 /* Check for enough room first. */
5885 if (cTasksToSubmit >= pImage->cTask)
5886 {
5887 /* We reached maximum, resize array. Try to realloc memory first. */
5888 void **apTaskNew = (void **)RTMemRealloc(pImage->apTask, (cTasksToSubmit + 10)*sizeof(void *));
5889
5890 if (!apTaskNew)
5891 {
5892 /* We failed. Allocate completely new. */
5893 apTaskNew = (void **)RTMemAllocZ((cTasksToSubmit + 10)* sizeof(void *));
5894 if (!apTaskNew)
5895 {
5896 /* Damn, we are out of memory. */
5897 rc = VERR_NO_MEMORY;
5898 goto out;
5899 }
5900
5901 /* Copy task handles over. */
5902 for (unsigned i = 0; i < cTasksToSubmit; i++)
5903 apTaskNew[i] = pImage->apTask[i];
5904
5905 /* Free old memory. */
5906 RTMemFree(pImage->apTask);
5907 }
5908
5909 pImage->cTask = cTasksToSubmit + 10;
5910 pImage->apTask = apTaskNew;
5911 }
5912
5913 pImage->apTask[cTasksToSubmit] = pTask;
5914 cTasksToSubmit++;
5915 break;
5916 }
5917 case VMDKETYPE_ZERO:
5918 /* Nothing left to do. */
5919 break;
5920 default:
5921 AssertMsgFailed(("Unsupported extent type %u\n", pExtent->enmType));
5922 }
5923
5924 cbWrite -= cbToWrite;
5925 uOffset += cbToWrite;
5926 cbLeftInCurrentSegment -= cbToWrite;
5927 uOffsetInCurrentSegment += cbToWrite;
5928 /* Go to next extent if there is no space left in current one. */
5929 if (!cbLeftInCurrentSegment)
5930 {
5931 uOffsetInCurrentSegment = 0;
5932 paSegCurrent++;
5933 cSeg--;
5934 cbLeftInCurrentSegment = paSegCurrent->cbSeg;
5935 }
5936 }
5937
5938 AssertMsg(cbWrite == 0, ("No segment left but there is still data to read\n"));
5939
5940 if (cTasksToSubmit == 0)
5941 {
5942 /* The request was completely in a ZERO extent nothing to do. */
5943 rc = VINF_VD_ASYNC_IO_FINISHED;
5944 }
5945 else
5946 {
5947 /* Submit tasks. */
5948 rc = pImage->pInterfaceAsyncIOCallbacks->pfnTasksSubmit(pImage->pInterfaceAsyncIO->pvUser,
5949 pImage->apTask, cTasksToSubmit,
5950 NULL, pvUser,
5951 NULL /* Nothing required after read. */);
5952 AssertMsgRC(rc, ("Failed to enqueue tasks rc=%Rrc\n", rc));
5953 }
5954
5955out:
5956 LogFlowFunc(("returns %Rrc\n", rc));
5957 return rc;
5958
5959}
5960
5961
5962VBOXHDDBACKEND g_VmdkBackend =
5963{
5964 /* pszBackendName */
5965 "VMDK",
5966 /* cbSize */
5967 sizeof(VBOXHDDBACKEND),
5968 /* uBackendCaps */
5969 VD_CAP_UUID | VD_CAP_CREATE_FIXED | VD_CAP_CREATE_DYNAMIC
5970 | VD_CAP_CREATE_SPLIT_2G | VD_CAP_DIFF | VD_CAP_FILE |VD_CAP_ASYNC,
5971 /* papszFileExtensions */
5972 s_apszVmdkFileExtensions,
5973 /* paConfigInfo */
5974 NULL,
5975 /* hPlugin */
5976 NIL_RTLDRMOD,
5977 /* pfnCheckIfValid */
5978 vmdkCheckIfValid,
5979 /* pfnOpen */
5980 vmdkOpen,
5981 /* pfnCreate */
5982 vmdkCreate,
5983 /* pfnRename */
5984 vmdkRename,
5985 /* pfnClose */
5986 vmdkClose,
5987 /* pfnRead */
5988 vmdkRead,
5989 /* pfnWrite */
5990 vmdkWrite,
5991 /* pfnFlush */
5992 vmdkFlush,
5993 /* pfnGetVersion */
5994 vmdkGetVersion,
5995 /* pfnGetSize */
5996 vmdkGetSize,
5997 /* pfnGetFileSize */
5998 vmdkGetFileSize,
5999 /* pfnGetPCHSGeometry */
6000 vmdkGetPCHSGeometry,
6001 /* pfnSetPCHSGeometry */
6002 vmdkSetPCHSGeometry,
6003 /* pfnGetLCHSGeometry */
6004 vmdkGetLCHSGeometry,
6005 /* pfnSetLCHSGeometry */
6006 vmdkSetLCHSGeometry,
6007 /* pfnGetImageFlags */
6008 vmdkGetImageFlags,
6009 /* pfnGetOpenFlags */
6010 vmdkGetOpenFlags,
6011 /* pfnSetOpenFlags */
6012 vmdkSetOpenFlags,
6013 /* pfnGetComment */
6014 vmdkGetComment,
6015 /* pfnSetComment */
6016 vmdkSetComment,
6017 /* pfnGetUuid */
6018 vmdkGetUuid,
6019 /* pfnSetUuid */
6020 vmdkSetUuid,
6021 /* pfnGetModificationUuid */
6022 vmdkGetModificationUuid,
6023 /* pfnSetModificationUuid */
6024 vmdkSetModificationUuid,
6025 /* pfnGetParentUuid */
6026 vmdkGetParentUuid,
6027 /* pfnSetParentUuid */
6028 vmdkSetParentUuid,
6029 /* pfnGetParentModificationUuid */
6030 vmdkGetParentModificationUuid,
6031 /* pfnSetParentModificationUuid */
6032 vmdkSetParentModificationUuid,
6033 /* pfnDump */
6034 vmdkDump,
6035 /* pfnGetTimeStamp */
6036 vmdkGetTimeStamp,
6037 /* pfnGetParentTimeStamp */
6038 vmdkGetParentTimeStamp,
6039 /* pfnSetParentTimeStamp */
6040 vmdkSetParentTimeStamp,
6041 /* pfnGetParentFilename */
6042 vmdkGetParentFilename,
6043 /* pfnSetParentFilename */
6044 vmdkSetParentFilename,
6045 /* pfnIsAsyncIOSupported */
6046 vmdkIsAsyncIOSupported,
6047 /* pfnAsyncRead */
6048 vmdkAsyncRead,
6049 /* pfnAsyncWrite */
6050 vmdkAsyncWrite,
6051 /* pfnComposeLocation */
6052 genericFileComposeLocation,
6053 /* pfnComposeName */
6054 genericFileComposeName
6055};
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