VirtualBox

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

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

Storage/VMDK: fix flush on close without breaking the cleanup when creation failed.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 217.4 KB
Line 
1/* $Id: VmdkHDDCore.cpp 18149 2009-03-23 16:28:11Z 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 /* As we're dealing with a monolithic image here, there must
2908 * be a descriptor embedded in the image file. */
2909 if (!pExtent->uDescriptorSector || !pExtent->cDescriptorSectors)
2910 {
2911 rc = vmdkError(pImage, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: monolithic image without descriptor in '%s'"), pImage->pszFilename);
2912 goto out;
2913 }
2914 /* Read the descriptor from the extent. */
2915 pExtent->pDescData = (char *)RTMemAllocZ(VMDK_SECTOR2BYTE(pExtent->cDescriptorSectors));
2916 if (!pExtent->pDescData)
2917 {
2918 rc = VERR_NO_MEMORY;
2919 goto out;
2920 }
2921 rc = vmdkFileReadAt(pExtent->pFile,
2922 VMDK_SECTOR2BYTE(pExtent->uDescriptorSector),
2923 pExtent->pDescData,
2924 VMDK_SECTOR2BYTE(pExtent->cDescriptorSectors), NULL);
2925 AssertRC(rc);
2926 if (RT_FAILURE(rc))
2927 {
2928 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: read error for descriptor in '%s'"), pExtent->pszFullname);
2929 goto out;
2930 }
2931
2932 rc = vmdkParseDescriptor(pImage, pExtent->pDescData,
2933 VMDK_SECTOR2BYTE(pExtent->cDescriptorSectors));
2934 if (RT_FAILURE(rc))
2935 goto out;
2936
2937 rc = vmdkReadMetaExtent(pImage, pExtent);
2938 if (RT_FAILURE(rc))
2939 goto out;
2940
2941 /* Mark the extent as unclean if opened in read-write mode. */
2942 if (!(uOpenFlags & VD_OPEN_FLAGS_READONLY))
2943 {
2944 pExtent->fUncleanShutdown = true;
2945 pExtent->fMetaDirty = true;
2946 }
2947 }
2948 else
2949 {
2950 pImage->cbDescAlloc = VMDK_SECTOR2BYTE(20);
2951 pImage->pDescData = (char *)RTMemAllocZ(pImage->cbDescAlloc);
2952 if (!pImage->pDescData)
2953 {
2954 rc = VERR_NO_MEMORY;
2955 goto out;
2956 }
2957
2958 size_t cbRead;
2959 rc = vmdkFileReadAt(pImage->pFile, 0, pImage->pDescData,
2960 pImage->cbDescAlloc, &cbRead);
2961 if (RT_FAILURE(rc))
2962 {
2963 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: read error for descriptor in '%s'"), pImage->pszFilename);
2964 goto out;
2965 }
2966 if (cbRead == pImage->cbDescAlloc)
2967 {
2968 /* Likely the read is truncated. Better fail a bit too early
2969 * (normally the descriptor is much smaller than our buffer). */
2970 rc = vmdkError(pImage, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: cannot read descriptor in '%s'"), pImage->pszFilename);
2971 goto out;
2972 }
2973
2974 rc = vmdkParseDescriptor(pImage, pImage->pDescData,
2975 pImage->cbDescAlloc);
2976 if (RT_FAILURE(rc))
2977 goto out;
2978
2979 /*
2980 * We have to check for the asynchronous open flag. The
2981 * extents are parsed and the type of all are known now.
2982 * Check if every extent is either FLAT or ZERO.
2983 */
2984 if (uOpenFlags & VD_OPEN_FLAGS_ASYNC_IO)
2985 {
2986 for (unsigned i = 0; i < pImage->cExtents; i++)
2987 {
2988 PVMDKEXTENT pExtent = &pImage->pExtents[i];
2989
2990 if ( (pExtent->enmType != VMDKETYPE_FLAT)
2991 && (pExtent->enmType != VMDKETYPE_ZERO))
2992 {
2993 /*
2994 * Opened image contains at least one none flat or zero extent.
2995 * Return error but don't set error message as the caller
2996 * has the chance to open in non async I/O mode.
2997 */
2998 rc = VERR_NOT_SUPPORTED;
2999 goto out;
3000 }
3001 }
3002 }
3003
3004 for (unsigned i = 0; i < pImage->cExtents; i++)
3005 {
3006 PVMDKEXTENT pExtent = &pImage->pExtents[i];
3007
3008 if (pExtent->pszBasename)
3009 {
3010 /* Hack to figure out whether the specified name in the
3011 * extent descriptor is absolute. Doesn't always work, but
3012 * should be good enough for now. */
3013 char *pszFullname;
3014 /** @todo implement proper path absolute check. */
3015 if (pExtent->pszBasename[0] == RTPATH_SLASH)
3016 {
3017 pszFullname = RTStrDup(pExtent->pszBasename);
3018 if (!pszFullname)
3019 {
3020 rc = VERR_NO_MEMORY;
3021 goto out;
3022 }
3023 }
3024 else
3025 {
3026 size_t cbDirname;
3027 char *pszDirname = RTStrDup(pImage->pszFilename);
3028 if (!pszDirname)
3029 {
3030 rc = VERR_NO_MEMORY;
3031 goto out;
3032 }
3033 RTPathStripFilename(pszDirname);
3034 cbDirname = strlen(pszDirname);
3035 rc = RTStrAPrintf(&pszFullname, "%s%c%s", pszDirname,
3036 RTPATH_SLASH, pExtent->pszBasename);
3037 RTStrFree(pszDirname);
3038 if (RT_FAILURE(rc))
3039 goto out;
3040 }
3041 pExtent->pszFullname = pszFullname;
3042 }
3043 else
3044 pExtent->pszFullname = NULL;
3045
3046 switch (pExtent->enmType)
3047 {
3048 case VMDKETYPE_HOSTED_SPARSE:
3049 rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszFullname,
3050 uOpenFlags & VD_OPEN_FLAGS_READONLY
3051 ? RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE
3052 : RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE, false);
3053 if (RT_FAILURE(rc))
3054 {
3055 /* Do NOT signal an appropriate error here, as the VD
3056 * layer has the choice of retrying the open if it
3057 * failed. */
3058 goto out;
3059 }
3060 rc = vmdkReadBinaryMetaExtent(pImage, pExtent);
3061 if (RT_FAILURE(rc))
3062 goto out;
3063 rc = vmdkReadMetaExtent(pImage, pExtent);
3064 if (RT_FAILURE(rc))
3065 goto out;
3066
3067 /* Mark extent as unclean if opened in read-write mode. */
3068 if (!(uOpenFlags & VD_OPEN_FLAGS_READONLY))
3069 {
3070 pExtent->fUncleanShutdown = true;
3071 pExtent->fMetaDirty = true;
3072 }
3073 break;
3074 case VMDKETYPE_FLAT:
3075 rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszFullname,
3076 uOpenFlags & VD_OPEN_FLAGS_READONLY
3077 ? RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE
3078 : RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE, true);
3079 if (RT_FAILURE(rc))
3080 {
3081 /* Do NOT signal an appropriate error here, as the VD
3082 * layer has the choice of retrying the open if it
3083 * failed. */
3084 goto out;
3085 }
3086 break;
3087 case VMDKETYPE_ZERO:
3088 /* Nothing to do. */
3089 break;
3090 default:
3091 AssertMsgFailed(("unknown vmdk extent type %d\n", pExtent->enmType));
3092 }
3093 }
3094 }
3095
3096 /* Make sure this is not reached accidentally with an error status. */
3097 AssertRC(rc);
3098
3099 /* Determine PCHS geometry if not set. */
3100 if (pImage->PCHSGeometry.cCylinders == 0)
3101 {
3102 uint64_t cCylinders = VMDK_BYTE2SECTOR(pImage->cbSize)
3103 / pImage->PCHSGeometry.cHeads
3104 / pImage->PCHSGeometry.cSectors;
3105 pImage->PCHSGeometry.cCylinders = (unsigned)RT_MIN(cCylinders, 16383);
3106 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
3107 {
3108 rc = vmdkDescSetPCHSGeometry(pImage, &pImage->PCHSGeometry);
3109 AssertRC(rc);
3110 }
3111 }
3112
3113 /* Update the image metadata now in case has changed. */
3114 rc = vmdkFlushImage(pImage);
3115 if (RT_FAILURE(rc))
3116 goto out;
3117
3118 /* Figure out a few per-image constants from the extents. */
3119 pImage->cbSize = 0;
3120 for (unsigned i = 0; i < pImage->cExtents; i++)
3121 {
3122 pExtent = &pImage->pExtents[i];
3123 if ( pExtent->enmType == VMDKETYPE_HOSTED_SPARSE
3124#ifdef VBOX_WITH_VMDK_ESX
3125 || pExtent->enmType == VMDKETYPE_ESX_SPARSE
3126#endif /* VBOX_WITH_VMDK_ESX */
3127 )
3128 {
3129 /* Here used to be a check whether the nominal size of an extent
3130 * is a multiple of the grain size. The spec says that this is
3131 * always the case, but unfortunately some files out there in the
3132 * wild violate the spec (e.g. ReactOS 0.3.1). */
3133 }
3134 pImage->cbSize += VMDK_SECTOR2BYTE(pExtent->cNominalSectors);
3135 }
3136
3137 for (unsigned i = 0; i < pImage->cExtents; i++)
3138 {
3139 pExtent = &pImage->pExtents[i];
3140 if ( pImage->pExtents[i].enmType == VMDKETYPE_FLAT
3141 || pImage->pExtents[i].enmType == VMDKETYPE_ZERO)
3142 {
3143 pImage->uImageFlags |= VD_IMAGE_FLAGS_FIXED;
3144 break;
3145 }
3146 }
3147
3148 rc = vmdkAllocateGrainTableCache(pImage);
3149 if (RT_FAILURE(rc))
3150 goto out;
3151
3152out:
3153 if (RT_FAILURE(rc))
3154 vmdkFreeImage(pImage, false);
3155 return rc;
3156}
3157
3158/**
3159 * Internal: create VMDK images for raw disk/partition access.
3160 */
3161static int vmdkCreateRawImage(PVMDKIMAGE pImage, const PVBOXHDDRAW pRaw,
3162 uint64_t cbSize)
3163{
3164 int rc = VINF_SUCCESS;
3165 PVMDKEXTENT pExtent;
3166
3167 if (pRaw->fRawDisk)
3168 {
3169 /* Full raw disk access. This requires setting up a descriptor
3170 * file and open the (flat) raw disk. */
3171 rc = vmdkCreateExtents(pImage, 1);
3172 if (RT_FAILURE(rc))
3173 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not create new extent list in '%s'"), pImage->pszFilename);
3174 pExtent = &pImage->pExtents[0];
3175 /* Create raw disk descriptor file. */
3176 rc = vmdkFileOpen(pImage, &pImage->pFile, pImage->pszFilename,
3177 RTFILE_O_READWRITE | RTFILE_O_CREATE | RTFILE_O_DENY_WRITE | RTFILE_O_NOT_CONTENT_INDEXED,
3178 false);
3179 if (RT_FAILURE(rc))
3180 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not create new file '%s'"), pImage->pszFilename);
3181
3182 /* Set up basename for extent description. Cannot use StrDup. */
3183 size_t cbBasename = strlen(pRaw->pszRawDisk) + 1;
3184 char *pszBasename = (char *)RTMemTmpAlloc(cbBasename);
3185 if (!pszBasename)
3186 return VERR_NO_MEMORY;
3187 memcpy(pszBasename, pRaw->pszRawDisk, cbBasename);
3188 pExtent->pszBasename = pszBasename;
3189 /* For raw disks the full name is identical to the base name. */
3190 pExtent->pszFullname = RTStrDup(pszBasename);
3191 if (!pExtent->pszFullname)
3192 return VERR_NO_MEMORY;
3193 pExtent->enmType = VMDKETYPE_FLAT;
3194 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(cbSize);
3195 pExtent->uSectorOffset = 0;
3196 pExtent->enmAccess = VMDKACCESS_READWRITE;
3197 pExtent->fMetaDirty = false;
3198
3199 /* Open flat image, the raw disk. */
3200 rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszFullname,
3201 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE, false);
3202 if (RT_FAILURE(rc))
3203 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not open raw disk file '%s'"), pExtent->pszFullname);
3204 }
3205 else
3206 {
3207 /* Raw partition access. This requires setting up a descriptor
3208 * file, write the partition information to a flat extent and
3209 * open all the (flat) raw disk partitions. */
3210
3211 /* First pass over the partitions to determine how many
3212 * extents we need. One partition can require up to 4 extents.
3213 * One to skip over unpartitioned space, one for the
3214 * partitioning data, one to skip over unpartitioned space
3215 * and one for the partition data. */
3216 unsigned cExtents = 0;
3217 uint64_t uStart = 0;
3218 for (unsigned i = 0; i < pRaw->cPartitions; i++)
3219 {
3220 PVBOXHDDRAWPART pPart = &pRaw->pPartitions[i];
3221 if (pPart->cbPartitionData)
3222 {
3223 if (uStart > pPart->uPartitionDataStart)
3224 return vmdkError(pImage, VERR_INVALID_PARAMETER, RT_SRC_POS, N_("VMDK: cannot go backwards for partitioning information in '%s'"), pImage->pszFilename);
3225 else if (uStart != pPart->uPartitionDataStart)
3226 cExtents++;
3227 uStart = pPart->uPartitionDataStart + pPart->cbPartitionData;
3228 cExtents++;
3229 }
3230 if (pPart->cbPartition)
3231 {
3232 if (uStart > pPart->uPartitionStart)
3233 return vmdkError(pImage, VERR_INVALID_PARAMETER, RT_SRC_POS, N_("VMDK: cannot go backwards for partition data in '%s'"), pImage->pszFilename);
3234 else if (uStart != pPart->uPartitionStart)
3235 cExtents++;
3236 uStart = pPart->uPartitionStart + pPart->cbPartition;
3237 cExtents++;
3238 }
3239 }
3240 /* Another extent for filling up the rest of the image. */
3241 if (uStart != cbSize)
3242 cExtents++;
3243
3244 rc = vmdkCreateExtents(pImage, cExtents);
3245 if (RT_FAILURE(rc))
3246 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not create new extent list in '%s'"), pImage->pszFilename);
3247
3248 /* Create raw partition descriptor file. */
3249 rc = vmdkFileOpen(pImage, &pImage->pFile, pImage->pszFilename,
3250 RTFILE_O_READWRITE | RTFILE_O_CREATE | RTFILE_O_DENY_WRITE | RTFILE_O_NOT_CONTENT_INDEXED,
3251 false);
3252 if (RT_FAILURE(rc))
3253 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not create new file '%s'"), pImage->pszFilename);
3254
3255 /* Create base filename for the partition table extent. */
3256 /** @todo remove fixed buffer without creating memory leaks. */
3257 char pszPartition[1024];
3258 const char *pszBase = RTPathFilename(pImage->pszFilename);
3259 const char *pszExt = RTPathExt(pszBase);
3260 if (pszExt == NULL)
3261 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: invalid filename '%s'"), pImage->pszFilename);
3262 char *pszBaseBase = RTStrDup(pszBase);
3263 if (!pszBaseBase)
3264 return VERR_NO_MEMORY;
3265 RTPathStripExt(pszBaseBase);
3266 RTStrPrintf(pszPartition, sizeof(pszPartition), "%s-pt%s",
3267 pszBaseBase, pszExt);
3268 RTStrFree(pszBaseBase);
3269
3270 /* Second pass over the partitions, now define all extents. */
3271 uint64_t uPartOffset = 0;
3272 cExtents = 0;
3273 uStart = 0;
3274 for (unsigned i = 0; i < pRaw->cPartitions; i++)
3275 {
3276 PVBOXHDDRAWPART pPart = &pRaw->pPartitions[i];
3277 if (pPart->cbPartitionData)
3278 {
3279 if (uStart != pPart->uPartitionDataStart)
3280 {
3281 pExtent = &pImage->pExtents[cExtents++];
3282 pExtent->pszBasename = NULL;
3283 pExtent->pszFullname = NULL;
3284 pExtent->enmType = VMDKETYPE_ZERO;
3285 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(pPart->uPartitionDataStart - uStart);
3286 pExtent->uSectorOffset = 0;
3287 pExtent->enmAccess = VMDKACCESS_READWRITE;
3288 pExtent->fMetaDirty = false;
3289 }
3290 uStart = pPart->uPartitionDataStart + pPart->cbPartitionData;
3291 pExtent = &pImage->pExtents[cExtents++];
3292 /* Set up basename for extent description. Can't use StrDup. */
3293 size_t cbBasename = strlen(pszPartition) + 1;
3294 char *pszBasename = (char *)RTMemTmpAlloc(cbBasename);
3295 if (!pszBasename)
3296 return VERR_NO_MEMORY;
3297 memcpy(pszBasename, pszPartition, cbBasename);
3298 pExtent->pszBasename = pszBasename;
3299
3300 /* Set up full name for partition extent. */
3301 size_t cbDirname;
3302 char *pszDirname = RTStrDup(pImage->pszFilename);
3303 if (!pszDirname)
3304 return VERR_NO_MEMORY;
3305 RTPathStripFilename(pszDirname);
3306 cbDirname = strlen(pszDirname);
3307 char *pszFullname;
3308 rc = RTStrAPrintf(&pszFullname, "%s%c%s", pszDirname,
3309 RTPATH_SLASH, pExtent->pszBasename);
3310 RTStrFree(pszDirname);
3311 if (RT_FAILURE(rc))
3312 return rc;
3313 pExtent->pszFullname = pszFullname;
3314 pExtent->enmType = VMDKETYPE_FLAT;
3315 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(pPart->cbPartitionData);
3316 pExtent->uSectorOffset = uPartOffset;
3317 pExtent->enmAccess = VMDKACCESS_READWRITE;
3318 pExtent->fMetaDirty = false;
3319
3320 /* Create partition table flat image. */
3321 rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszFullname,
3322 RTFILE_O_READWRITE | RTFILE_O_CREATE | RTFILE_O_DENY_WRITE | RTFILE_O_NOT_CONTENT_INDEXED,
3323 false);
3324 if (RT_FAILURE(rc))
3325 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not create new partition data file '%s'"), pExtent->pszFullname);
3326 rc = vmdkFileWriteAt(pExtent->pFile,
3327 VMDK_SECTOR2BYTE(uPartOffset),
3328 pPart->pvPartitionData,
3329 pPart->cbPartitionData, NULL);
3330 if (RT_FAILURE(rc))
3331 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not write partition data to '%s'"), pExtent->pszFullname);
3332 uPartOffset += VMDK_BYTE2SECTOR(pPart->cbPartitionData);
3333 }
3334 if (pPart->cbPartition)
3335 {
3336 if (uStart != pPart->uPartitionStart)
3337 {
3338 pExtent = &pImage->pExtents[cExtents++];
3339 pExtent->pszBasename = NULL;
3340 pExtent->pszFullname = NULL;
3341 pExtent->enmType = VMDKETYPE_ZERO;
3342 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(pPart->uPartitionStart - uStart);
3343 pExtent->uSectorOffset = 0;
3344 pExtent->enmAccess = VMDKACCESS_READWRITE;
3345 pExtent->fMetaDirty = false;
3346 }
3347 uStart = pPart->uPartitionStart + pPart->cbPartition;
3348 pExtent = &pImage->pExtents[cExtents++];
3349 if (pPart->pszRawDevice)
3350 {
3351 /* Set up basename for extent descr. Can't use StrDup. */
3352 size_t cbBasename = strlen(pPart->pszRawDevice) + 1;
3353 char *pszBasename = (char *)RTMemTmpAlloc(cbBasename);
3354 if (!pszBasename)
3355 return VERR_NO_MEMORY;
3356 memcpy(pszBasename, pPart->pszRawDevice, cbBasename);
3357 pExtent->pszBasename = pszBasename;
3358 /* For raw disks full name is identical to base name. */
3359 pExtent->pszFullname = RTStrDup(pszBasename);
3360 if (!pExtent->pszFullname)
3361 return VERR_NO_MEMORY;
3362 pExtent->enmType = VMDKETYPE_FLAT;
3363 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(pPart->cbPartition);
3364 pExtent->uSectorOffset = VMDK_BYTE2SECTOR(pPart->uPartitionStartOffset);
3365 pExtent->enmAccess = VMDKACCESS_READWRITE;
3366 pExtent->fMetaDirty = false;
3367
3368 /* Open flat image, the raw partition. */
3369 rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszFullname,
3370 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE,
3371 false);
3372 if (RT_FAILURE(rc))
3373 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not open raw partition file '%s'"), pExtent->pszFullname);
3374 }
3375 else
3376 {
3377 pExtent->pszBasename = NULL;
3378 pExtent->pszFullname = NULL;
3379 pExtent->enmType = VMDKETYPE_ZERO;
3380 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(pPart->cbPartition);
3381 pExtent->uSectorOffset = 0;
3382 pExtent->enmAccess = VMDKACCESS_READWRITE;
3383 pExtent->fMetaDirty = false;
3384 }
3385 }
3386 }
3387 /* Another extent for filling up the rest of the image. */
3388 if (uStart != cbSize)
3389 {
3390 pExtent = &pImage->pExtents[cExtents++];
3391 pExtent->pszBasename = NULL;
3392 pExtent->pszFullname = NULL;
3393 pExtent->enmType = VMDKETYPE_ZERO;
3394 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(cbSize - uStart);
3395 pExtent->uSectorOffset = 0;
3396 pExtent->enmAccess = VMDKACCESS_READWRITE;
3397 pExtent->fMetaDirty = false;
3398 }
3399 }
3400
3401 rc = vmdkDescBaseSetStr(pImage, &pImage->Descriptor, "createType",
3402 pRaw->fRawDisk ?
3403 "fullDevice" : "partitionedDevice");
3404 if (RT_FAILURE(rc))
3405 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not set the image type in '%s'"), pImage->pszFilename);
3406 return rc;
3407}
3408
3409/**
3410 * Internal: create a regular (i.e. file-backed) VMDK image.
3411 */
3412static int vmdkCreateRegularImage(PVMDKIMAGE pImage, uint64_t cbSize,
3413 unsigned uImageFlags,
3414 PFNVMPROGRESS pfnProgress, void *pvUser,
3415 unsigned uPercentStart, unsigned uPercentSpan)
3416{
3417 int rc = VINF_SUCCESS;
3418 unsigned cExtents = 1;
3419 uint64_t cbOffset = 0;
3420 uint64_t cbRemaining = cbSize;
3421
3422 if (uImageFlags & VD_VMDK_IMAGE_FLAGS_SPLIT_2G)
3423 {
3424 cExtents = cbSize / VMDK_2G_SPLIT_SIZE;
3425 /* Do proper extent computation: need one smaller extent if the total
3426 * size isn't evenly divisible by the split size. */
3427 if (cbSize % VMDK_2G_SPLIT_SIZE)
3428 cExtents++;
3429 }
3430 rc = vmdkCreateExtents(pImage, cExtents);
3431 if (RT_FAILURE(rc))
3432 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not create new extent list in '%s'"), pImage->pszFilename);
3433
3434 /* Basename strings needed for constructing the extent names. */
3435 char *pszBasenameSubstr = RTPathFilename(pImage->pszFilename);
3436 AssertPtr(pszBasenameSubstr);
3437 size_t cbBasenameSubstr = strlen(pszBasenameSubstr) + 1;
3438
3439 /* Create searate descriptor file if necessary. */
3440 if (cExtents != 1 || (uImageFlags & VD_IMAGE_FLAGS_FIXED))
3441 {
3442 rc = vmdkFileOpen(pImage, &pImage->pFile, pImage->pszFilename,
3443 RTFILE_O_READWRITE | RTFILE_O_CREATE | RTFILE_O_DENY_WRITE | RTFILE_O_NOT_CONTENT_INDEXED,
3444 false);
3445 if (RT_FAILURE(rc))
3446 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not create new sparse descriptor file '%s'"), pImage->pszFilename);
3447 }
3448 else
3449 pImage->pFile = NULL;
3450
3451 /* Set up all extents. */
3452 for (unsigned i = 0; i < cExtents; i++)
3453 {
3454 PVMDKEXTENT pExtent = &pImage->pExtents[i];
3455 uint64_t cbExtent = cbRemaining;
3456
3457 /* Set up fullname/basename for extent description. Cannot use StrDup
3458 * for basename, as it is not guaranteed that the memory can be freed
3459 * with RTMemTmpFree, which must be used as in other code paths
3460 * StrDup is not usable. */
3461 if (cExtents == 1 && !(uImageFlags & VD_IMAGE_FLAGS_FIXED))
3462 {
3463 char *pszBasename = (char *)RTMemTmpAlloc(cbBasenameSubstr);
3464 if (!pszBasename)
3465 return VERR_NO_MEMORY;
3466 memcpy(pszBasename, pszBasenameSubstr, cbBasenameSubstr);
3467 pExtent->pszBasename = pszBasename;
3468 }
3469 else
3470 {
3471 char *pszBasenameExt = RTPathExt(pszBasenameSubstr);
3472 char *pszBasenameBase = RTStrDup(pszBasenameSubstr);
3473 RTPathStripExt(pszBasenameBase);
3474 char *pszTmp;
3475 size_t cbTmp;
3476 if (uImageFlags & VD_IMAGE_FLAGS_FIXED)
3477 {
3478 if (cExtents == 1)
3479 rc = RTStrAPrintf(&pszTmp, "%s-flat%s", pszBasenameBase,
3480 pszBasenameExt);
3481 else
3482 rc = RTStrAPrintf(&pszTmp, "%s-f%03d%s", pszBasenameBase,
3483 i+1, pszBasenameExt);
3484 }
3485 else
3486 rc = RTStrAPrintf(&pszTmp, "%s-s%03d%s", pszBasenameBase, i+1,
3487 pszBasenameExt);
3488 RTStrFree(pszBasenameBase);
3489 if (RT_FAILURE(rc))
3490 return rc;
3491 cbTmp = strlen(pszTmp) + 1;
3492 char *pszBasename = (char *)RTMemTmpAlloc(cbTmp);
3493 if (!pszBasename)
3494 return VERR_NO_MEMORY;
3495 memcpy(pszBasename, pszTmp, cbTmp);
3496 RTStrFree(pszTmp);
3497 pExtent->pszBasename = pszBasename;
3498 if (uImageFlags & VD_VMDK_IMAGE_FLAGS_SPLIT_2G)
3499 cbExtent = RT_MIN(cbRemaining, VMDK_2G_SPLIT_SIZE);
3500 }
3501 char *pszBasedirectory = RTStrDup(pImage->pszFilename);
3502 RTPathStripFilename(pszBasedirectory);
3503 char *pszFullname;
3504 rc = RTStrAPrintf(&pszFullname, "%s%c%s", pszBasedirectory,
3505 RTPATH_SLASH, pExtent->pszBasename);
3506 RTStrFree(pszBasedirectory);
3507 if (RT_FAILURE(rc))
3508 return rc;
3509 pExtent->pszFullname = pszFullname;
3510
3511 /* Create file for extent. */
3512 rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszFullname,
3513 RTFILE_O_READWRITE | RTFILE_O_CREATE | RTFILE_O_DENY_WRITE | RTFILE_O_NOT_CONTENT_INDEXED,
3514 false);
3515 if (RT_FAILURE(rc))
3516 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not create new file '%s'"), pExtent->pszFullname);
3517 if (uImageFlags & VD_IMAGE_FLAGS_FIXED)
3518 {
3519 rc = vmdkFileSetSize(pExtent->pFile, cbExtent);
3520 if (RT_FAILURE(rc))
3521 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not set size of new file '%s'"), pExtent->pszFullname);
3522
3523 /* Fill image with zeroes. We do this for every fixed-size image since on some systems
3524 * (for example Windows Vista), it takes ages to write a block near the end of a sparse
3525 * file and the guest could complain about an ATA timeout. */
3526
3527 /** @todo Starting with Linux 2.6.23, there is an fallocate() system call.
3528 * Currently supported file systems are ext4 and ocfs2. */
3529
3530 /* Allocate a temporary zero-filled buffer. Use a bigger block size to optimize writing */
3531 const size_t cbBuf = 128 * _1K;
3532 void *pvBuf = RTMemTmpAllocZ(cbBuf);
3533 if (!pvBuf)
3534 return VERR_NO_MEMORY;
3535
3536 uint64_t uOff = 0;
3537 /* Write data to all image blocks. */
3538 while (uOff < cbExtent)
3539 {
3540 unsigned cbChunk = (unsigned)RT_MIN(cbExtent, cbBuf);
3541
3542 rc = vmdkFileWriteAt(pExtent->pFile, uOff, pvBuf, cbChunk, NULL);
3543 if (RT_FAILURE(rc))
3544 {
3545 RTMemFree(pvBuf);
3546 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: writing block failed for '%s'"), pImage->pszFilename);
3547 }
3548
3549 uOff += cbChunk;
3550
3551 if (pfnProgress)
3552 {
3553 rc = pfnProgress(NULL /* WARNING! pVM=NULL */,
3554 uPercentStart + uOff * uPercentSpan / cbExtent,
3555 pvUser);
3556 if (RT_FAILURE(rc))
3557 {
3558 RTMemFree(pvBuf);
3559 return rc;
3560 }
3561 }
3562 }
3563 RTMemTmpFree(pvBuf);
3564 }
3565
3566 /* Place descriptor file information (where integrated). */
3567 if (cExtents == 1 && !(uImageFlags & VD_IMAGE_FLAGS_FIXED))
3568 {
3569 pExtent->uDescriptorSector = 1;
3570 pExtent->cDescriptorSectors = VMDK_BYTE2SECTOR(pImage->cbDescAlloc);
3571 /* The descriptor is part of the (only) extent. */
3572 pExtent->pDescData = pImage->pDescData;
3573 pImage->pDescData = NULL;
3574 }
3575
3576 if (!(uImageFlags & VD_IMAGE_FLAGS_FIXED))
3577 {
3578 uint64_t cSectorsPerGDE, cSectorsPerGD;
3579 pExtent->enmType = VMDKETYPE_HOSTED_SPARSE;
3580 pExtent->cSectors = VMDK_BYTE2SECTOR(RT_ALIGN_64(cbExtent, 65536));
3581 pExtent->cSectorsPerGrain = VMDK_BYTE2SECTOR(65536);
3582 pExtent->cGTEntries = 512;
3583 cSectorsPerGDE = pExtent->cGTEntries * pExtent->cSectorsPerGrain;
3584 pExtent->cSectorsPerGDE = cSectorsPerGDE;
3585 pExtent->cGDEntries = (pExtent->cSectors + cSectorsPerGDE - 1) / cSectorsPerGDE;
3586 cSectorsPerGD = (pExtent->cGDEntries + (512 / sizeof(uint32_t) - 1)) / (512 / sizeof(uint32_t));
3587 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
3588 {
3589 /* The spec says version is 1 for all VMDKs, but the vast
3590 * majority of streamOptimized VMDKs actually contain
3591 * version 3 - so go with the majority. Both are acepted. */
3592 pExtent->uVersion = 3;
3593 pExtent->uCompression = VMDK_COMPRESSION_DEFLATE;
3594 }
3595 }
3596 else
3597 pExtent->enmType = VMDKETYPE_FLAT;
3598
3599 pExtent->enmAccess = VMDKACCESS_READWRITE;
3600 pExtent->fUncleanShutdown = true;
3601 pExtent->cNominalSectors = VMDK_BYTE2SECTOR(cbExtent);
3602 pExtent->uSectorOffset = VMDK_BYTE2SECTOR(cbOffset);
3603 pExtent->fMetaDirty = true;
3604
3605 if (!(uImageFlags & VD_IMAGE_FLAGS_FIXED))
3606 {
3607 rc = vmdkCreateGrainDirectory(pExtent,
3608 RT_MAX( pExtent->uDescriptorSector
3609 + pExtent->cDescriptorSectors,
3610 1),
3611 true);
3612 if (RT_FAILURE(rc))
3613 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not create new grain directory in '%s'"), pExtent->pszFullname);
3614 }
3615
3616 if (RT_SUCCESS(rc) && pfnProgress)
3617 pfnProgress(NULL /* WARNING! pVM=NULL */,
3618 uPercentStart + i * uPercentSpan / cExtents,
3619 pvUser);
3620
3621 cbRemaining -= cbExtent;
3622 cbOffset += cbExtent;
3623 }
3624
3625 const char *pszDescType = NULL;
3626 if (uImageFlags & VD_IMAGE_FLAGS_FIXED)
3627 {
3628 pszDescType = (cExtents == 1)
3629 ? "monolithicFlat" : "twoGbMaxExtentFlat";
3630 }
3631 else
3632 {
3633 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
3634 pszDescType = "streamOptimized";
3635 else
3636 {
3637 pszDescType = (cExtents == 1)
3638 ? "monolithicSparse" : "twoGbMaxExtentSparse";
3639 }
3640 }
3641 rc = vmdkDescBaseSetStr(pImage, &pImage->Descriptor, "createType",
3642 pszDescType);
3643 if (RT_FAILURE(rc))
3644 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not set the image type in '%s'"), pImage->pszFilename);
3645 return rc;
3646}
3647
3648/**
3649 * Internal: The actual code for creating any VMDK variant currently in
3650 * existence on hosted environments.
3651 */
3652static int vmdkCreateImage(PVMDKIMAGE pImage, uint64_t cbSize,
3653 unsigned uImageFlags, const char *pszComment,
3654 PCPDMMEDIAGEOMETRY pPCHSGeometry,
3655 PCPDMMEDIAGEOMETRY pLCHSGeometry, PCRTUUID pUuid,
3656 PFNVMPROGRESS pfnProgress, void *pvUser,
3657 unsigned uPercentStart, unsigned uPercentSpan)
3658{
3659 int rc;
3660
3661 pImage->uImageFlags = uImageFlags;
3662
3663 /* Try to get error interface. */
3664 pImage->pInterfaceError = VDInterfaceGet(pImage->pVDIfsDisk, VDINTERFACETYPE_ERROR);
3665 if (pImage->pInterfaceError)
3666 pImage->pInterfaceErrorCallbacks = VDGetInterfaceError(pImage->pInterfaceError);
3667
3668 /* Try to get async I/O interface. */
3669 pImage->pInterfaceAsyncIO = VDInterfaceGet(pImage->pVDIfsDisk, VDINTERFACETYPE_ASYNCIO);
3670 if (pImage->pInterfaceAsyncIO)
3671 pImage->pInterfaceAsyncIOCallbacks = VDGetInterfaceAsyncIO(pImage->pInterfaceAsyncIO);
3672
3673 rc = vmdkCreateDescriptor(pImage, pImage->pDescData, pImage->cbDescAlloc,
3674 &pImage->Descriptor);
3675 if (RT_FAILURE(rc))
3676 {
3677 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not create new descriptor in '%s'"), pImage->pszFilename);
3678 goto out;
3679 }
3680
3681 if ( (uImageFlags & VD_IMAGE_FLAGS_FIXED)
3682 && (uImageFlags & VD_VMDK_IMAGE_FLAGS_RAWDISK))
3683 {
3684 /* Raw disk image (includes raw partition). */
3685 const PVBOXHDDRAW pRaw = (const PVBOXHDDRAW)pszComment;
3686 /* As the comment is misused, zap it so that no garbage comment
3687 * is set below. */
3688 pszComment = NULL;
3689 rc = vmdkCreateRawImage(pImage, pRaw, cbSize);
3690 }
3691 else
3692 {
3693 /* Regular fixed or sparse image (monolithic or split). */
3694 rc = vmdkCreateRegularImage(pImage, cbSize, uImageFlags,
3695 pfnProgress, pvUser, uPercentStart,
3696 uPercentSpan * 95 / 100);
3697 }
3698
3699 if (RT_FAILURE(rc))
3700 goto out;
3701
3702 if (RT_SUCCESS(rc) && pfnProgress)
3703 pfnProgress(NULL /* WARNING! pVM=NULL */,
3704 uPercentStart + uPercentSpan * 98 / 100, pvUser);
3705
3706 pImage->cbSize = cbSize;
3707
3708 for (unsigned i = 0; i < pImage->cExtents; i++)
3709 {
3710 PVMDKEXTENT pExtent = &pImage->pExtents[i];
3711
3712 rc = vmdkDescExtInsert(pImage, &pImage->Descriptor, pExtent->enmAccess,
3713 pExtent->cNominalSectors, pExtent->enmType,
3714 pExtent->pszBasename, pExtent->uSectorOffset);
3715 if (RT_FAILURE(rc))
3716 {
3717 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: could not insert the extent list into descriptor in '%s'"), pImage->pszFilename);
3718 goto out;
3719 }
3720 }
3721 vmdkDescExtRemoveDummy(pImage, &pImage->Descriptor);
3722
3723 if ( pPCHSGeometry->cCylinders != 0
3724 && pPCHSGeometry->cHeads != 0
3725 && pPCHSGeometry->cSectors != 0)
3726 {
3727 rc = vmdkDescSetPCHSGeometry(pImage, pPCHSGeometry);
3728 if (RT_FAILURE(rc))
3729 goto out;
3730 }
3731 if ( pLCHSGeometry->cCylinders != 0
3732 && pLCHSGeometry->cHeads != 0
3733 && pLCHSGeometry->cSectors != 0)
3734 {
3735 rc = vmdkDescSetLCHSGeometry(pImage, pLCHSGeometry);
3736 if (RT_FAILURE(rc))
3737 goto out;
3738 }
3739
3740 pImage->LCHSGeometry = *pLCHSGeometry;
3741 pImage->PCHSGeometry = *pPCHSGeometry;
3742
3743 pImage->ImageUuid = *pUuid;
3744 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
3745 VMDK_DDB_IMAGE_UUID, &pImage->ImageUuid);
3746 if (RT_FAILURE(rc))
3747 {
3748 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error storing image UUID in new descriptor in '%s'"), pImage->pszFilename);
3749 goto out;
3750 }
3751 RTUuidClear(&pImage->ParentUuid);
3752 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
3753 VMDK_DDB_PARENT_UUID, &pImage->ParentUuid);
3754 if (RT_FAILURE(rc))
3755 {
3756 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error storing parent image UUID in new descriptor in '%s'"), pImage->pszFilename);
3757 goto out;
3758 }
3759 RTUuidClear(&pImage->ModificationUuid);
3760 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
3761 VMDK_DDB_MODIFICATION_UUID,
3762 &pImage->ModificationUuid);
3763 if (RT_FAILURE(rc))
3764 {
3765 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error storing modification UUID in new descriptor in '%s'"), pImage->pszFilename);
3766 goto out;
3767 }
3768 RTUuidClear(&pImage->ParentModificationUuid);
3769 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
3770 VMDK_DDB_PARENT_MODIFICATION_UUID,
3771 &pImage->ParentModificationUuid);
3772 if (RT_FAILURE(rc))
3773 {
3774 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error storing parent modification UUID in new descriptor in '%s'"), pImage->pszFilename);
3775 goto out;
3776 }
3777
3778 rc = vmdkAllocateGrainTableCache(pImage);
3779 if (RT_FAILURE(rc))
3780 goto out;
3781
3782 rc = vmdkSetImageComment(pImage, pszComment);
3783 if (RT_FAILURE(rc))
3784 {
3785 rc = vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: cannot set image comment in '%s'"), pImage->pszFilename);
3786 goto out;
3787 }
3788
3789 if (RT_SUCCESS(rc) && pfnProgress)
3790 pfnProgress(NULL /* WARNING! pVM=NULL */,
3791 uPercentStart + uPercentSpan * 99 / 100, pvUser);
3792
3793 rc = vmdkFlushImage(pImage);
3794
3795out:
3796 if (RT_SUCCESS(rc) && pfnProgress)
3797 pfnProgress(NULL /* WARNING! pVM=NULL */,
3798 uPercentStart + uPercentSpan, pvUser);
3799
3800 if (RT_FAILURE(rc))
3801 vmdkFreeImage(pImage, rc != VERR_ALREADY_EXISTS);
3802 return rc;
3803}
3804
3805/**
3806 * Internal: Update image comment.
3807 */
3808static int vmdkSetImageComment(PVMDKIMAGE pImage, const char *pszComment)
3809{
3810 char *pszCommentEncoded;
3811 if (pszComment)
3812 {
3813 pszCommentEncoded = vmdkEncodeString(pszComment);
3814 if (!pszCommentEncoded)
3815 return VERR_NO_MEMORY;
3816 }
3817 else
3818 pszCommentEncoded = NULL;
3819 int rc = vmdkDescDDBSetStr(pImage, &pImage->Descriptor,
3820 "ddb.comment", pszCommentEncoded);
3821 if (pszComment)
3822 RTStrFree(pszCommentEncoded);
3823 if (RT_FAILURE(rc))
3824 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error storing image comment in descriptor in '%s'"), pImage->pszFilename);
3825 return VINF_SUCCESS;
3826}
3827
3828/**
3829 * Internal. Free all allocated space for representing an image, and optionally
3830 * delete the image from disk.
3831 */
3832static void vmdkFreeImage(PVMDKIMAGE pImage, bool fDelete)
3833{
3834 AssertPtr(pImage);
3835
3836 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
3837 {
3838 /* Mark all extents as clean. */
3839 for (unsigned i = 0; i < pImage->cExtents; i++)
3840 {
3841 if (( pImage->pExtents[i].enmType == VMDKETYPE_HOSTED_SPARSE
3842#ifdef VBOX_WITH_VMDK_ESX
3843 || pImage->pExtents[i].enmType == VMDKETYPE_ESX_SPARSE
3844#endif /* VBOX_WITH_VMDK_ESX */
3845 )
3846 && pImage->pExtents[i].fUncleanShutdown)
3847 {
3848 pImage->pExtents[i].fUncleanShutdown = false;
3849 pImage->pExtents[i].fMetaDirty = true;
3850 }
3851 }
3852 }
3853 (void)vmdkFlushImage(pImage);
3854
3855 if (pImage->pExtents != NULL)
3856 {
3857 for (unsigned i = 0 ; i < pImage->cExtents; i++)
3858 vmdkFreeExtentData(pImage, &pImage->pExtents[i], fDelete);
3859 RTMemFree(pImage->pExtents);
3860 pImage->pExtents = NULL;
3861 }
3862 pImage->cExtents = 0;
3863 if (pImage->pFile != NULL)
3864 vmdkFileClose(pImage, &pImage->pFile, fDelete);
3865 vmdkFileCheckAllClose(pImage);
3866 if (pImage->pGTCache)
3867 {
3868 RTMemFree(pImage->pGTCache);
3869 pImage->pGTCache = NULL;
3870 }
3871 if (pImage->pDescData)
3872 {
3873 RTMemFree(pImage->pDescData);
3874 pImage->pDescData = NULL;
3875 }
3876}
3877
3878/**
3879 * Internal. Flush image data (and metadata) to disk.
3880 */
3881static int vmdkFlushImage(PVMDKIMAGE pImage)
3882{
3883 PVMDKEXTENT pExtent;
3884 int rc = VINF_SUCCESS;
3885
3886 /* Update descriptor if changed. */
3887 if (pImage->Descriptor.fDirty)
3888 {
3889 rc = vmdkWriteDescriptor(pImage);
3890 if (RT_FAILURE(rc))
3891 goto out;
3892 }
3893
3894 for (unsigned i = 0; i < pImage->cExtents; i++)
3895 {
3896 pExtent = &pImage->pExtents[i];
3897 if (pExtent->pFile != NULL && pExtent->fMetaDirty)
3898 {
3899 switch (pExtent->enmType)
3900 {
3901 case VMDKETYPE_HOSTED_SPARSE:
3902 rc = vmdkWriteMetaSparseExtent(pExtent, 0);
3903 if (RT_FAILURE(rc))
3904 goto out;
3905 if (pExtent->fFooter)
3906 {
3907 uint64_t cbSize;
3908 rc = vmdkFileGetSize(pExtent->pFile, &cbSize);
3909 if (RT_FAILURE(rc))
3910 goto out;
3911 cbSize = RT_ALIGN_64(cbSize, 512);
3912 rc = vmdkWriteMetaSparseExtent(pExtent, cbSize - 2*512);
3913 if (RT_FAILURE(rc))
3914 goto out;
3915 }
3916 break;
3917#ifdef VBOX_WITH_VMDK_ESX
3918 case VMDKETYPE_ESX_SPARSE:
3919 /** @todo update the header. */
3920 break;
3921#endif /* VBOX_WITH_VMDK_ESX */
3922 case VMDKETYPE_FLAT:
3923 /* Nothing to do. */
3924 break;
3925 case VMDKETYPE_ZERO:
3926 default:
3927 AssertMsgFailed(("extent with type %d marked as dirty\n",
3928 pExtent->enmType));
3929 break;
3930 }
3931 }
3932 switch (pExtent->enmType)
3933 {
3934 case VMDKETYPE_HOSTED_SPARSE:
3935#ifdef VBOX_WITH_VMDK_ESX
3936 case VMDKETYPE_ESX_SPARSE:
3937#endif /* VBOX_WITH_VMDK_ESX */
3938 case VMDKETYPE_FLAT:
3939 /** @todo implement proper path absolute check. */
3940 if ( pExtent->pFile != NULL
3941 && !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
3942 && !(pExtent->pszBasename[0] == RTPATH_SLASH))
3943 rc = vmdkFileFlush(pExtent->pFile);
3944 break;
3945 case VMDKETYPE_ZERO:
3946 /* No need to do anything for this extent. */
3947 break;
3948 default:
3949 AssertMsgFailed(("unknown extent type %d\n", pExtent->enmType));
3950 break;
3951 }
3952 }
3953
3954out:
3955 return rc;
3956}
3957
3958/**
3959 * Internal. Find extent corresponding to the sector number in the disk.
3960 */
3961static int vmdkFindExtent(PVMDKIMAGE pImage, uint64_t offSector,
3962 PVMDKEXTENT *ppExtent, uint64_t *puSectorInExtent)
3963{
3964 PVMDKEXTENT pExtent = NULL;
3965 int rc = VINF_SUCCESS;
3966
3967 for (unsigned i = 0; i < pImage->cExtents; i++)
3968 {
3969 if (offSector < pImage->pExtents[i].cNominalSectors)
3970 {
3971 pExtent = &pImage->pExtents[i];
3972 *puSectorInExtent = offSector + pImage->pExtents[i].uSectorOffset;
3973 break;
3974 }
3975 offSector -= pImage->pExtents[i].cNominalSectors;
3976 }
3977
3978 if (pExtent)
3979 *ppExtent = pExtent;
3980 else
3981 rc = VERR_IO_SECTOR_NOT_FOUND;
3982
3983 return rc;
3984}
3985
3986/**
3987 * Internal. Hash function for placing the grain table hash entries.
3988 */
3989static uint32_t vmdkGTCacheHash(PVMDKGTCACHE pCache, uint64_t uSector,
3990 unsigned uExtent)
3991{
3992 /** @todo this hash function is quite simple, maybe use a better one which
3993 * scrambles the bits better. */
3994 return (uSector + uExtent) % pCache->cEntries;
3995}
3996
3997/**
3998 * Internal. Get sector number in the extent file from the relative sector
3999 * number in the extent.
4000 */
4001static int vmdkGetSector(PVMDKGTCACHE pCache, PVMDKEXTENT pExtent,
4002 uint64_t uSector, uint64_t *puExtentSector)
4003{
4004 uint64_t uGDIndex, uGTSector, uGTBlock;
4005 uint32_t uGTHash, uGTBlockIndex;
4006 PVMDKGTCACHEENTRY pGTCacheEntry;
4007 uint32_t aGTDataTmp[VMDK_GT_CACHELINE_SIZE];
4008 int rc;
4009
4010 uGDIndex = uSector / pExtent->cSectorsPerGDE;
4011 if (uGDIndex >= pExtent->cGDEntries)
4012 return VERR_OUT_OF_RANGE;
4013 uGTSector = pExtent->pGD[uGDIndex];
4014 if (!uGTSector)
4015 {
4016 /* There is no grain table referenced by this grain directory
4017 * entry. So there is absolutely no data in this area. */
4018 *puExtentSector = 0;
4019 return VINF_SUCCESS;
4020 }
4021
4022 uGTBlock = uSector / (pExtent->cSectorsPerGrain * VMDK_GT_CACHELINE_SIZE);
4023 uGTHash = vmdkGTCacheHash(pCache, uGTBlock, pExtent->uExtent);
4024 pGTCacheEntry = &pCache->aGTCache[uGTHash];
4025 if ( pGTCacheEntry->uExtent != pExtent->uExtent
4026 || pGTCacheEntry->uGTBlock != uGTBlock)
4027 {
4028 /* Cache miss, fetch data from disk. */
4029 rc = vmdkFileReadAt(pExtent->pFile,
4030 VMDK_SECTOR2BYTE(uGTSector) + (uGTBlock % (pExtent->cGTEntries / VMDK_GT_CACHELINE_SIZE)) * sizeof(aGTDataTmp),
4031 aGTDataTmp, sizeof(aGTDataTmp), NULL);
4032 if (RT_FAILURE(rc))
4033 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: cannot read grain table entry in '%s'"), pExtent->pszFullname);
4034 pGTCacheEntry->uExtent = pExtent->uExtent;
4035 pGTCacheEntry->uGTBlock = uGTBlock;
4036 for (unsigned i = 0; i < VMDK_GT_CACHELINE_SIZE; i++)
4037 pGTCacheEntry->aGTData[i] = RT_LE2H_U32(aGTDataTmp[i]);
4038 }
4039 uGTBlockIndex = (uSector / pExtent->cSectorsPerGrain) % VMDK_GT_CACHELINE_SIZE;
4040 uint32_t uGrainSector = pGTCacheEntry->aGTData[uGTBlockIndex];
4041 if (uGrainSector)
4042 *puExtentSector = uGrainSector + uSector % pExtent->cSectorsPerGrain;
4043 else
4044 *puExtentSector = 0;
4045 return VINF_SUCCESS;
4046}
4047
4048/**
4049 * Internal. Allocates a new grain table (if necessary), writes the grain
4050 * and updates the grain table. The cache is also updated by this operation.
4051 * This is separate from vmdkGetSector, because that should be as fast as
4052 * possible. Most code from vmdkGetSector also appears here.
4053 */
4054static int vmdkAllocGrain(PVMDKGTCACHE pCache, PVMDKEXTENT pExtent,
4055 uint64_t uSector, const void *pvBuf,
4056 uint64_t cbWrite)
4057{
4058 uint64_t uGDIndex, uGTSector, uRGTSector, uGTBlock;
4059 uint64_t cbExtentSize;
4060 uint32_t uGTHash, uGTBlockIndex;
4061 PVMDKGTCACHEENTRY pGTCacheEntry;
4062 uint32_t aGTDataTmp[VMDK_GT_CACHELINE_SIZE];
4063 int rc;
4064
4065 uGDIndex = uSector / pExtent->cSectorsPerGDE;
4066 if (uGDIndex >= pExtent->cGDEntries)
4067 return VERR_OUT_OF_RANGE;
4068 uGTSector = pExtent->pGD[uGDIndex];
4069 if (pExtent->pRGD)
4070 uRGTSector = pExtent->pRGD[uGDIndex];
4071 else
4072 uRGTSector = 0; /**< avoid compiler warning */
4073 if (!uGTSector)
4074 {
4075 /* There is no grain table referenced by this grain directory
4076 * entry. So there is absolutely no data in this area. Allocate
4077 * a new grain table and put the reference to it in the GDs. */
4078 rc = vmdkFileGetSize(pExtent->pFile, &cbExtentSize);
4079 if (RT_FAILURE(rc))
4080 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: error getting size in '%s'"), pExtent->pszFullname);
4081 Assert(!(cbExtentSize % 512));
4082 cbExtentSize = RT_ALIGN_64(cbExtentSize, 512);
4083 uGTSector = VMDK_BYTE2SECTOR(cbExtentSize);
4084 /* For writable streamOptimized extents the final sector is the
4085 * end-of-stream marker. Will be re-added after the grain table.
4086 * If the file has a footer it also will be re-added before EOS. */
4087 if (pExtent->pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
4088 {
4089 uint64_t uEOSOff = 0;
4090 uGTSector--;
4091 if (pExtent->fFooter)
4092 {
4093 uGTSector--;
4094 uEOSOff = 512;
4095 rc = vmdkWriteMetaSparseExtent(pExtent, VMDK_SECTOR2BYTE(uGTSector) + pExtent->cGTEntries * sizeof(uint32_t));
4096 if (RT_FAILURE(rc))
4097 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: cannot write footer after grain table in '%s'"), pExtent->pszFullname);
4098 }
4099 pExtent->uLastGrainSector = 0;
4100 uint8_t aEOS[512];
4101 memset(aEOS, '\0', sizeof(aEOS));
4102 rc = vmdkFileWriteAt(pExtent->pFile,
4103 VMDK_SECTOR2BYTE(uGTSector) + pExtent->cGTEntries * sizeof(uint32_t) + uEOSOff,
4104 aEOS, sizeof(aEOS), NULL);
4105 if (RT_FAILURE(rc))
4106 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: cannot write end-of stream marker after grain table in '%s'"), pExtent->pszFullname);
4107 }
4108 /* Normally the grain table is preallocated for hosted sparse extents
4109 * that support more than 32 bit sector numbers. So this shouldn't
4110 * ever happen on a valid extent. */
4111 if (uGTSector > UINT32_MAX)
4112 return VERR_VD_VMDK_INVALID_HEADER;
4113 /* Write grain table by writing the required number of grain table
4114 * cache chunks. Avoids dynamic memory allocation, but is a bit
4115 * slower. But as this is a pretty infrequently occurring case it
4116 * should be acceptable. */
4117 memset(aGTDataTmp, '\0', sizeof(aGTDataTmp));
4118 for (unsigned i = 0;
4119 i < pExtent->cGTEntries / VMDK_GT_CACHELINE_SIZE;
4120 i++)
4121 {
4122 rc = vmdkFileWriteAt(pExtent->pFile,
4123 VMDK_SECTOR2BYTE(uGTSector) + i * sizeof(aGTDataTmp),
4124 aGTDataTmp, sizeof(aGTDataTmp), NULL);
4125 if (RT_FAILURE(rc))
4126 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: cannot write grain table allocation in '%s'"), pExtent->pszFullname);
4127 }
4128 if (pExtent->pRGD)
4129 {
4130 AssertReturn(!uRGTSector, VERR_VD_VMDK_INVALID_HEADER);
4131 rc = vmdkFileGetSize(pExtent->pFile, &cbExtentSize);
4132 if (RT_FAILURE(rc))
4133 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: error getting size in '%s'"), pExtent->pszFullname);
4134 Assert(!(cbExtentSize % 512));
4135 uRGTSector = VMDK_BYTE2SECTOR(cbExtentSize);
4136 /* For writable streamOptimized extents the final sector is the
4137 * end-of-stream marker. Will be re-added after the grain table.
4138 * If the file has a footer it also will be re-added before EOS. */
4139 if (pExtent->pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
4140 {
4141 uint64_t uEOSOff = 0;
4142 uRGTSector--;
4143 if (pExtent->fFooter)
4144 {
4145 uRGTSector--;
4146 uEOSOff = 512;
4147 rc = vmdkWriteMetaSparseExtent(pExtent, VMDK_SECTOR2BYTE(uRGTSector) + pExtent->cGTEntries * sizeof(uint32_t));
4148 if (RT_FAILURE(rc))
4149 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: cannot write footer after redundant grain table in '%s'"), pExtent->pszFullname);
4150 }
4151 pExtent->uLastGrainSector = 0;
4152 uint8_t aEOS[512];
4153 memset(aEOS, '\0', sizeof(aEOS));
4154 rc = vmdkFileWriteAt(pExtent->pFile,
4155 VMDK_SECTOR2BYTE(uRGTSector) + pExtent->cGTEntries * sizeof(uint32_t) + uEOSOff,
4156 aEOS, sizeof(aEOS), NULL);
4157 if (RT_FAILURE(rc))
4158 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: cannot write end-of stream marker after redundant grain table in '%s'"), pExtent->pszFullname);
4159 }
4160 /* Normally the redundant grain table is preallocated for hosted
4161 * sparse extents that support more than 32 bit sector numbers. So
4162 * this shouldn't ever happen on a valid extent. */
4163 if (uRGTSector > UINT32_MAX)
4164 return VERR_VD_VMDK_INVALID_HEADER;
4165 /* Write backup grain table by writing the required number of grain
4166 * table cache chunks. Avoids dynamic memory allocation, but is a
4167 * bit slower. But as this is a pretty infrequently occurring case
4168 * it should be acceptable. */
4169 for (unsigned i = 0;
4170 i < pExtent->cGTEntries / VMDK_GT_CACHELINE_SIZE;
4171 i++)
4172 {
4173 rc = vmdkFileWriteAt(pExtent->pFile,
4174 VMDK_SECTOR2BYTE(uRGTSector) + i * sizeof(aGTDataTmp),
4175 aGTDataTmp, sizeof(aGTDataTmp), NULL);
4176 if (RT_FAILURE(rc))
4177 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: cannot write backup grain table allocation in '%s'"), pExtent->pszFullname);
4178 }
4179 }
4180
4181 /* Update the grain directory on disk (doing it before writing the
4182 * grain table will result in a garbled extent if the operation is
4183 * aborted for some reason. Otherwise the worst that can happen is
4184 * some unused sectors in the extent. */
4185 uint32_t uGTSectorLE = RT_H2LE_U64(uGTSector);
4186 rc = vmdkFileWriteAt(pExtent->pFile,
4187 VMDK_SECTOR2BYTE(pExtent->uSectorGD) + uGDIndex * sizeof(uGTSectorLE),
4188 &uGTSectorLE, sizeof(uGTSectorLE), NULL);
4189 if (RT_FAILURE(rc))
4190 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: cannot write grain directory entry in '%s'"), pExtent->pszFullname);
4191 if (pExtent->pRGD)
4192 {
4193 uint32_t uRGTSectorLE = RT_H2LE_U64(uRGTSector);
4194 rc = vmdkFileWriteAt(pExtent->pFile,
4195 VMDK_SECTOR2BYTE(pExtent->uSectorRGD) + uGDIndex * sizeof(uRGTSectorLE),
4196 &uRGTSectorLE, sizeof(uRGTSectorLE), NULL);
4197 if (RT_FAILURE(rc))
4198 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: cannot write backup grain directory entry in '%s'"), pExtent->pszFullname);
4199 }
4200
4201 /* As the final step update the in-memory copy of the GDs. */
4202 pExtent->pGD[uGDIndex] = uGTSector;
4203 if (pExtent->pRGD)
4204 pExtent->pRGD[uGDIndex] = uRGTSector;
4205 }
4206
4207 rc = vmdkFileGetSize(pExtent->pFile, &cbExtentSize);
4208 if (RT_FAILURE(rc))
4209 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: error getting size in '%s'"), pExtent->pszFullname);
4210 Assert(!(cbExtentSize % 512));
4211
4212 /* Write the data. Always a full grain, or we're in big trouble. */
4213 if (pExtent->pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
4214 {
4215 /* For streamOptimized extents this is a little more difficult, as the
4216 * cached data also needs to be updated, to handle updating the last
4217 * written block properly. Also we're trying to avoid unnecessary gaps.
4218 * Additionally the end-of-stream marker needs to be written. */
4219 if (!pExtent->uLastGrainSector)
4220 {
4221 cbExtentSize -= 512;
4222 if (pExtent->fFooter)
4223 cbExtentSize -= 512;
4224 }
4225 else
4226 cbExtentSize = VMDK_SECTOR2BYTE(pExtent->uLastGrainSector) + pExtent->cbLastGrainWritten;
4227 Assert(cbWrite == VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain));
4228 uint32_t cbGrain = 0;
4229 rc = vmdkFileDeflateAt(pExtent->pFile, cbExtentSize,
4230 pvBuf, cbWrite, VMDK_MARKER_IGNORE, uSector, &cbGrain);
4231 if (RT_FAILURE(rc))
4232 {
4233 pExtent->uGrainSector = 0;
4234 pExtent->uLastGrainSector = 0;
4235 AssertRC(rc);
4236 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: cannot write allocated compressed data block in '%s'"), pExtent->pszFullname);
4237 }
4238 cbGrain = RT_ALIGN(cbGrain, 512);
4239 pExtent->uLastGrainSector = VMDK_BYTE2SECTOR(cbExtentSize);
4240 pExtent->uLastGrainWritten = uSector / pExtent->cSectorsPerGrain;
4241 pExtent->cbLastGrainWritten = cbGrain;
4242 memcpy(pExtent->pvGrain, pvBuf, cbWrite);
4243 pExtent->uGrainSector = uSector;
4244
4245 uint64_t uEOSOff = 0;
4246 if (pExtent->fFooter)
4247 {
4248 uEOSOff = 512;
4249 rc = vmdkWriteMetaSparseExtent(pExtent, cbExtentSize + RT_ALIGN(cbGrain, 512));
4250 if (RT_FAILURE(rc))
4251 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: cannot write footer after allocated data block in '%s'"), pExtent->pszFullname);
4252 }
4253 uint8_t aEOS[512];
4254 memset(aEOS, '\0', sizeof(aEOS));
4255 rc = vmdkFileWriteAt(pExtent->pFile, cbExtentSize + RT_ALIGN(cbGrain, 512) + uEOSOff,
4256 aEOS, sizeof(aEOS), NULL);
4257 if (RT_FAILURE(rc))
4258 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: cannot write end-of stream marker after allocated data block in '%s'"), pExtent->pszFullname);
4259 }
4260 else
4261 {
4262 rc = vmdkFileWriteAt(pExtent->pFile, cbExtentSize, pvBuf, cbWrite, NULL);
4263 if (RT_FAILURE(rc))
4264 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: cannot write allocated data block in '%s'"), pExtent->pszFullname);
4265 }
4266
4267 /* Update the grain table (and the cache). */
4268 uGTBlock = uSector / (pExtent->cSectorsPerGrain * VMDK_GT_CACHELINE_SIZE);
4269 uGTHash = vmdkGTCacheHash(pCache, uGTBlock, pExtent->uExtent);
4270 pGTCacheEntry = &pCache->aGTCache[uGTHash];
4271 if ( pGTCacheEntry->uExtent != pExtent->uExtent
4272 || pGTCacheEntry->uGTBlock != uGTBlock)
4273 {
4274 /* Cache miss, fetch data from disk. */
4275 rc = vmdkFileReadAt(pExtent->pFile,
4276 VMDK_SECTOR2BYTE(uGTSector) + (uGTBlock % (pExtent->cGTEntries / VMDK_GT_CACHELINE_SIZE)) * sizeof(aGTDataTmp),
4277 aGTDataTmp, sizeof(aGTDataTmp), NULL);
4278 if (RT_FAILURE(rc))
4279 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: cannot read allocated grain table entry in '%s'"), pExtent->pszFullname);
4280 pGTCacheEntry->uExtent = pExtent->uExtent;
4281 pGTCacheEntry->uGTBlock = uGTBlock;
4282 for (unsigned i = 0; i < VMDK_GT_CACHELINE_SIZE; i++)
4283 pGTCacheEntry->aGTData[i] = RT_LE2H_U32(aGTDataTmp[i]);
4284 }
4285 else
4286 {
4287 /* Cache hit. Convert grain table block back to disk format, otherwise
4288 * the code below will write garbage for all but the updated entry. */
4289 for (unsigned i = 0; i < VMDK_GT_CACHELINE_SIZE; i++)
4290 aGTDataTmp[i] = RT_H2LE_U32(pGTCacheEntry->aGTData[i]);
4291 }
4292 uGTBlockIndex = (uSector / pExtent->cSectorsPerGrain) % VMDK_GT_CACHELINE_SIZE;
4293 aGTDataTmp[uGTBlockIndex] = RT_H2LE_U32(VMDK_BYTE2SECTOR(cbExtentSize));
4294 pGTCacheEntry->aGTData[uGTBlockIndex] = VMDK_BYTE2SECTOR(cbExtentSize);
4295 /* Update grain table on disk. */
4296 rc = vmdkFileWriteAt(pExtent->pFile,
4297 VMDK_SECTOR2BYTE(uGTSector) + (uGTBlock % (pExtent->cGTEntries / VMDK_GT_CACHELINE_SIZE)) * sizeof(aGTDataTmp),
4298 aGTDataTmp, sizeof(aGTDataTmp), NULL);
4299 if (RT_FAILURE(rc))
4300 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: cannot write updated grain table in '%s'"), pExtent->pszFullname);
4301 if (pExtent->pRGD)
4302 {
4303 /* Update backup grain table on disk. */
4304 rc = vmdkFileWriteAt(pExtent->pFile,
4305 VMDK_SECTOR2BYTE(uRGTSector) + (uGTBlock % (pExtent->cGTEntries / VMDK_GT_CACHELINE_SIZE)) * sizeof(aGTDataTmp),
4306 aGTDataTmp, sizeof(aGTDataTmp), NULL);
4307 if (RT_FAILURE(rc))
4308 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: cannot write updated backup grain table in '%s'"), pExtent->pszFullname);
4309 }
4310#ifdef VBOX_WITH_VMDK_ESX
4311 if (RT_SUCCESS(rc) && pExtent->enmType == VMDKETYPE_ESX_SPARSE)
4312 {
4313 pExtent->uFreeSector = uGTSector + VMDK_BYTE2SECTOR(cbWrite);
4314 pExtent->fMetaDirty = true;
4315 }
4316#endif /* VBOX_WITH_VMDK_ESX */
4317 return rc;
4318}
4319
4320
4321/** @copydoc VBOXHDDBACKEND::pfnCheckIfValid */
4322static int vmdkCheckIfValid(const char *pszFilename)
4323{
4324 LogFlowFunc(("pszFilename=\"%s\"\n", pszFilename));
4325 int rc = VINF_SUCCESS;
4326 PVMDKIMAGE pImage;
4327
4328 if ( !pszFilename
4329 || !*pszFilename
4330 || strchr(pszFilename, '"'))
4331 {
4332 rc = VERR_INVALID_PARAMETER;
4333 goto out;
4334 }
4335
4336 pImage = (PVMDKIMAGE)RTMemAllocZ(sizeof(VMDKIMAGE));
4337 if (!pImage)
4338 {
4339 rc = VERR_NO_MEMORY;
4340 goto out;
4341 }
4342 pImage->pszFilename = pszFilename;
4343 pImage->pFile = NULL;
4344 pImage->pExtents = NULL;
4345 pImage->pFiles = NULL;
4346 pImage->pGTCache = NULL;
4347 pImage->pDescData = NULL;
4348 pImage->pVDIfsDisk = NULL;
4349 /** @todo speed up this test open (VD_OPEN_FLAGS_INFO) by skipping as
4350 * much as possible in vmdkOpenImage. */
4351 rc = vmdkOpenImage(pImage, VD_OPEN_FLAGS_INFO | VD_OPEN_FLAGS_READONLY);
4352 vmdkFreeImage(pImage, false);
4353 RTMemFree(pImage);
4354
4355out:
4356 LogFlowFunc(("returns %Rrc\n", rc));
4357 return rc;
4358}
4359
4360/** @copydoc VBOXHDDBACKEND::pfnOpen */
4361static int vmdkOpen(const char *pszFilename, unsigned uOpenFlags,
4362 PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
4363 void **ppBackendData)
4364{
4365 LogFlowFunc(("pszFilename=\"%s\" uOpenFlags=%#x pVDIfsDisk=%#p pVDIfsImage=%#p ppBackendData=%#p\n", pszFilename, uOpenFlags, pVDIfsDisk, pVDIfsImage, ppBackendData));
4366 int rc;
4367 PVMDKIMAGE pImage;
4368
4369 /* Check open flags. All valid flags are supported. */
4370 if (uOpenFlags & ~VD_OPEN_FLAGS_MASK)
4371 {
4372 rc = VERR_INVALID_PARAMETER;
4373 goto out;
4374 }
4375
4376 /* Check remaining arguments. */
4377 if ( !VALID_PTR(pszFilename)
4378 || !*pszFilename
4379 || strchr(pszFilename, '"'))
4380 {
4381 rc = VERR_INVALID_PARAMETER;
4382 goto out;
4383 }
4384
4385
4386 pImage = (PVMDKIMAGE)RTMemAllocZ(sizeof(VMDKIMAGE));
4387 if (!pImage)
4388 {
4389 rc = VERR_NO_MEMORY;
4390 goto out;
4391 }
4392 pImage->pszFilename = pszFilename;
4393 pImage->pFile = NULL;
4394 pImage->pExtents = NULL;
4395 pImage->pFiles = NULL;
4396 pImage->pGTCache = NULL;
4397 pImage->pDescData = NULL;
4398 pImage->pVDIfsDisk = pVDIfsDisk;
4399
4400 rc = vmdkOpenImage(pImage, uOpenFlags);
4401 if (RT_SUCCESS(rc))
4402 *ppBackendData = pImage;
4403
4404out:
4405 LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
4406 return rc;
4407}
4408
4409/** @copydoc VBOXHDDBACKEND::pfnCreate */
4410static int vmdkCreate(const char *pszFilename, uint64_t cbSize,
4411 unsigned uImageFlags, const char *pszComment,
4412 PCPDMMEDIAGEOMETRY pPCHSGeometry,
4413 PCPDMMEDIAGEOMETRY pLCHSGeometry, PCRTUUID pUuid,
4414 unsigned uOpenFlags, unsigned uPercentStart,
4415 unsigned uPercentSpan, PVDINTERFACE pVDIfsDisk,
4416 PVDINTERFACE pVDIfsImage, PVDINTERFACE pVDIfsOperation,
4417 void **ppBackendData)
4418{
4419 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));
4420 int rc;
4421 PVMDKIMAGE pImage;
4422
4423 PFNVMPROGRESS pfnProgress = NULL;
4424 void *pvUser = NULL;
4425 PVDINTERFACE pIfProgress = VDInterfaceGet(pVDIfsOperation,
4426 VDINTERFACETYPE_PROGRESS);
4427 PVDINTERFACEPROGRESS pCbProgress = NULL;
4428 if (pIfProgress)
4429 {
4430 pCbProgress = VDGetInterfaceProgress(pIfProgress);
4431 pfnProgress = pCbProgress->pfnProgress;
4432 pvUser = pIfProgress->pvUser;
4433 }
4434
4435 /* Check open flags. All valid flags are supported. */
4436 if (uOpenFlags & ~VD_OPEN_FLAGS_MASK)
4437 {
4438 rc = VERR_INVALID_PARAMETER;
4439 goto out;
4440 }
4441
4442 /* Check remaining arguments. */
4443 if ( !VALID_PTR(pszFilename)
4444 || !*pszFilename
4445 || strchr(pszFilename, '"')
4446 || !VALID_PTR(pPCHSGeometry)
4447 || !VALID_PTR(pLCHSGeometry)
4448 || ( (uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
4449 && (uImageFlags & ~(VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED | VD_IMAGE_FLAGS_DIFF))))
4450 {
4451 rc = VERR_INVALID_PARAMETER;
4452 goto out;
4453 }
4454
4455 pImage = (PVMDKIMAGE)RTMemAllocZ(sizeof(VMDKIMAGE));
4456 if (!pImage)
4457 {
4458 rc = VERR_NO_MEMORY;
4459 goto out;
4460 }
4461 pImage->pszFilename = pszFilename;
4462 pImage->pFile = NULL;
4463 pImage->pExtents = NULL;
4464 pImage->pFiles = NULL;
4465 pImage->pGTCache = NULL;
4466 pImage->pDescData = NULL;
4467 pImage->pVDIfsDisk = NULL;
4468 pImage->cbDescAlloc = VMDK_SECTOR2BYTE(20);
4469 pImage->pDescData = (char *)RTMemAllocZ(pImage->cbDescAlloc);
4470 if (!pImage->pDescData)
4471 {
4472 rc = VERR_NO_MEMORY;
4473 goto out;
4474 }
4475
4476 rc = vmdkCreateImage(pImage, cbSize, uImageFlags, pszComment,
4477 pPCHSGeometry, pLCHSGeometry, pUuid,
4478 pfnProgress, pvUser, uPercentStart, uPercentSpan);
4479 if (RT_SUCCESS(rc))
4480 {
4481 /* So far the image is opened in read/write mode. Make sure the
4482 * image is opened in read-only mode if the caller requested that. */
4483 if (uOpenFlags & VD_OPEN_FLAGS_READONLY)
4484 {
4485 vmdkFreeImage(pImage, false);
4486 rc = vmdkOpenImage(pImage, uOpenFlags);
4487 if (RT_FAILURE(rc))
4488 goto out;
4489 }
4490 *ppBackendData = pImage;
4491 }
4492 else
4493 {
4494 RTMemFree(pImage->pDescData);
4495 RTMemFree(pImage);
4496 }
4497
4498out:
4499 LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
4500 return rc;
4501}
4502
4503/**
4504 * Replaces a fragment of a string with the specified string.
4505 *
4506 * @returns Pointer to the allocated UTF-8 string.
4507 * @param pszWhere UTF-8 string to search in.
4508 * @param pszWhat UTF-8 string to search for.
4509 * @param pszByWhat UTF-8 string to replace the found string with.
4510 */
4511static char * vmdkStrReplace(const char *pszWhere, const char *pszWhat, const char *pszByWhat)
4512{
4513 AssertPtr(pszWhere);
4514 AssertPtr(pszWhat);
4515 AssertPtr(pszByWhat);
4516 const char *pszFoundStr = strstr(pszWhere, pszWhat);
4517 if (!pszFoundStr)
4518 return NULL;
4519 size_t cFinal = strlen(pszWhere) + 1 + strlen(pszByWhat) - strlen(pszWhat);
4520 char *pszNewStr = (char *)RTMemAlloc(cFinal);
4521 if (pszNewStr)
4522 {
4523 char *pszTmp = pszNewStr;
4524 memcpy(pszTmp, pszWhere, pszFoundStr - pszWhere);
4525 pszTmp += pszFoundStr - pszWhere;
4526 memcpy(pszTmp, pszByWhat, strlen(pszByWhat));
4527 pszTmp += strlen(pszByWhat);
4528 strcpy(pszTmp, pszFoundStr + strlen(pszWhat));
4529 }
4530 return pszNewStr;
4531}
4532
4533/** @copydoc VBOXHDDBACKEND::pfnRename */
4534static int vmdkRename(void *pBackendData, const char *pszFilename)
4535{
4536 LogFlowFunc(("pBackendData=%#p pszFilename=%#p\n", pBackendData, pszFilename));
4537
4538 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
4539 int rc = VINF_SUCCESS;
4540 char **apszOldName = NULL;
4541 char **apszNewName = NULL;
4542 char **apszNewLines = NULL;
4543 char *pszOldDescName = NULL;
4544 bool fImageFreed = false;
4545 bool fEmbeddedDesc = false;
4546 unsigned cExtents = pImage->cExtents;
4547 char *pszNewBaseName = NULL;
4548 char *pszOldBaseName = NULL;
4549 char *pszNewFullName = NULL;
4550 char *pszOldFullName = NULL;
4551 const char *pszOldImageName;
4552 unsigned i, line;
4553 VMDKDESCRIPTOR DescriptorCopy;
4554 VMDKEXTENT ExtentCopy;
4555
4556 memset(&DescriptorCopy, 0, sizeof(DescriptorCopy));
4557
4558 /* Check arguments. */
4559 if ( !pImage
4560 || (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_RAWDISK)
4561 || !VALID_PTR(pszFilename)
4562 || !*pszFilename)
4563 {
4564 rc = VERR_INVALID_PARAMETER;
4565 goto out;
4566 }
4567
4568 /*
4569 * Allocate an array to store both old and new names of renamed files
4570 * in case we have to roll back the changes. Arrays are initialized
4571 * with zeros. We actually save stuff when and if we change it.
4572 */
4573 apszOldName = (char **)RTMemTmpAllocZ((cExtents + 1) * sizeof(char*));
4574 apszNewName = (char **)RTMemTmpAllocZ((cExtents + 1) * sizeof(char*));
4575 apszNewLines = (char **)RTMemTmpAllocZ((cExtents) * sizeof(char*));
4576 if (!apszOldName || !apszNewName || !apszNewLines)
4577 {
4578 rc = VERR_NO_MEMORY;
4579 goto out;
4580 }
4581
4582 /* Save the descriptor size and position. */
4583 if (pImage->pDescData)
4584 {
4585 /* Separate descriptor file. */
4586 fEmbeddedDesc = false;
4587 }
4588 else
4589 {
4590 /* Embedded descriptor file. */
4591 ExtentCopy = pImage->pExtents[0];
4592 fEmbeddedDesc = true;
4593 }
4594 /* Save the descriptor content. */
4595 DescriptorCopy.cLines = pImage->Descriptor.cLines;
4596 for (i = 0; i < DescriptorCopy.cLines; i++)
4597 {
4598 DescriptorCopy.aLines[i] = RTStrDup(pImage->Descriptor.aLines[i]);
4599 if (!DescriptorCopy.aLines[i])
4600 {
4601 rc = VERR_NO_MEMORY;
4602 goto out;
4603 }
4604 }
4605
4606 /* Prepare both old and new base names used for string replacement. */
4607 pszNewBaseName = RTStrDup(RTPathFilename(pszFilename));
4608 RTPathStripExt(pszNewBaseName);
4609 pszOldBaseName = RTStrDup(RTPathFilename(pImage->pszFilename));
4610 RTPathStripExt(pszOldBaseName);
4611 /* Prepare both old and new full names used for string replacement. */
4612 pszNewFullName = RTStrDup(pszFilename);
4613 RTPathStripExt(pszNewFullName);
4614 pszOldFullName = RTStrDup(pImage->pszFilename);
4615 RTPathStripExt(pszOldFullName);
4616
4617 /* --- Up to this point we have not done any damage yet. --- */
4618
4619 /* Save the old name for easy access to the old descriptor file. */
4620 pszOldDescName = RTStrDup(pImage->pszFilename);
4621 /* Save old image name. */
4622 pszOldImageName = pImage->pszFilename;
4623
4624 /* Update the descriptor with modified extent names. */
4625 for (i = 0, line = pImage->Descriptor.uFirstExtent;
4626 i < cExtents;
4627 i++, line = pImage->Descriptor.aNextLines[line])
4628 {
4629 /* Assume that vmdkStrReplace will fail. */
4630 rc = VERR_NO_MEMORY;
4631 /* Update the descriptor. */
4632 apszNewLines[i] = vmdkStrReplace(pImage->Descriptor.aLines[line],
4633 pszOldBaseName, pszNewBaseName);
4634 if (!apszNewLines[i])
4635 goto rollback;
4636 pImage->Descriptor.aLines[line] = apszNewLines[i];
4637 }
4638 /* Make sure the descriptor gets written back. */
4639 pImage->Descriptor.fDirty = true;
4640 /* Flush the descriptor now, in case it is embedded. */
4641 (void)vmdkFlushImage(pImage);
4642
4643 /* Close and rename/move extents. */
4644 for (i = 0; i < cExtents; i++)
4645 {
4646 PVMDKEXTENT pExtent = &pImage->pExtents[i];
4647 /* Compose new name for the extent. */
4648 apszNewName[i] = vmdkStrReplace(pExtent->pszFullname,
4649 pszOldFullName, pszNewFullName);
4650 if (!apszNewName[i])
4651 goto rollback;
4652 /* Close the extent file. */
4653 vmdkFileClose(pImage, &pExtent->pFile, false);
4654 /* Rename the extent file. */
4655 rc = RTFileMove(pExtent->pszFullname, apszNewName[i], 0);
4656 if (RT_FAILURE(rc))
4657 goto rollback;
4658 /* Remember the old name. */
4659 apszOldName[i] = RTStrDup(pExtent->pszFullname);
4660 }
4661 /* Release all old stuff. */
4662 vmdkFreeImage(pImage, false);
4663
4664 fImageFreed = true;
4665
4666 /* Last elements of new/old name arrays are intended for
4667 * storing descriptor's names.
4668 */
4669 apszNewName[cExtents] = RTStrDup(pszFilename);
4670 /* Rename the descriptor file if it's separate. */
4671 if (!fEmbeddedDesc)
4672 {
4673 rc = RTFileMove(pImage->pszFilename, apszNewName[cExtents], 0);
4674 if (RT_FAILURE(rc))
4675 goto rollback;
4676 /* Save old name only if we may need to change it back. */
4677 apszOldName[cExtents] = RTStrDup(pszFilename);
4678 }
4679
4680 /* Update pImage with the new information. */
4681 pImage->pszFilename = pszFilename;
4682
4683 /* Open the new image. */
4684 rc = vmdkOpenImage(pImage, pImage->uOpenFlags);
4685 if (RT_SUCCESS(rc))
4686 goto out;
4687
4688rollback:
4689 /* Roll back all changes in case of failure. */
4690 if (RT_FAILURE(rc))
4691 {
4692 int rrc;
4693 if (!fImageFreed)
4694 {
4695 /*
4696 * Some extents may have been closed, close the rest. We will
4697 * re-open the whole thing later.
4698 */
4699 vmdkFreeImage(pImage, false);
4700 }
4701 /* Rename files back. */
4702 for (i = 0; i <= cExtents; i++)
4703 {
4704 if (apszOldName[i])
4705 {
4706 rrc = RTFileMove(apszNewName[i], apszOldName[i], 0);
4707 AssertRC(rrc);
4708 }
4709 }
4710 /* Restore the old descriptor. */
4711 PVMDKFILE pFile;
4712 rrc = vmdkFileOpen(pImage, &pFile, pszOldDescName,
4713 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE, false);
4714 AssertRC(rrc);
4715 if (fEmbeddedDesc)
4716 {
4717 ExtentCopy.pFile = pFile;
4718 pImage->pExtents = &ExtentCopy;
4719 }
4720 else
4721 {
4722 /* Shouldn't be null for separate descriptor.
4723 * There will be no access to the actual content.
4724 */
4725 pImage->pDescData = pszOldDescName;
4726 pImage->pFile = pFile;
4727 }
4728 pImage->Descriptor = DescriptorCopy;
4729 vmdkWriteDescriptor(pImage);
4730 vmdkFileClose(pImage, &pFile, false);
4731 /* Get rid of the stuff we implanted. */
4732 pImage->pExtents = NULL;
4733 pImage->pFile = NULL;
4734 pImage->pDescData = NULL;
4735 /* Re-open the image back. */
4736 pImage->pszFilename = pszOldImageName;
4737 rrc = vmdkOpenImage(pImage, pImage->uOpenFlags);
4738 AssertRC(rrc);
4739 }
4740
4741out:
4742 for (i = 0; i < DescriptorCopy.cLines; i++)
4743 if (DescriptorCopy.aLines[i])
4744 RTStrFree(DescriptorCopy.aLines[i]);
4745 if (apszOldName)
4746 {
4747 for (i = 0; i <= cExtents; i++)
4748 if (apszOldName[i])
4749 RTStrFree(apszOldName[i]);
4750 RTMemTmpFree(apszOldName);
4751 }
4752 if (apszNewName)
4753 {
4754 for (i = 0; i <= cExtents; i++)
4755 if (apszNewName[i])
4756 RTStrFree(apszNewName[i]);
4757 RTMemTmpFree(apszNewName);
4758 }
4759 if (apszNewLines)
4760 {
4761 for (i = 0; i < cExtents; i++)
4762 if (apszNewLines[i])
4763 RTStrFree(apszNewLines[i]);
4764 RTMemTmpFree(apszNewLines);
4765 }
4766 if (pszOldDescName)
4767 RTStrFree(pszOldDescName);
4768 if (pszOldBaseName)
4769 RTStrFree(pszOldBaseName);
4770 if (pszNewBaseName)
4771 RTStrFree(pszNewBaseName);
4772 if (pszOldFullName)
4773 RTStrFree(pszOldFullName);
4774 if (pszNewFullName)
4775 RTStrFree(pszNewFullName);
4776 LogFlowFunc(("returns %Rrc\n", rc));
4777 return rc;
4778}
4779
4780/** @copydoc VBOXHDDBACKEND::pfnClose */
4781static int vmdkClose(void *pBackendData, bool fDelete)
4782{
4783 LogFlowFunc(("pBackendData=%#p fDelete=%d\n", pBackendData, fDelete));
4784 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
4785 int rc = VINF_SUCCESS;
4786
4787 /* Freeing a never allocated image (e.g. because the open failed) is
4788 * not signalled as an error. After all nothing bad happens. */
4789 if (pImage)
4790 {
4791 vmdkFreeImage(pImage, fDelete);
4792 RTMemFree(pImage);
4793 }
4794
4795 LogFlowFunc(("returns %Rrc\n", rc));
4796 return rc;
4797}
4798
4799/** @copydoc VBOXHDDBACKEND::pfnRead */
4800static int vmdkRead(void *pBackendData, uint64_t uOffset, void *pvBuf,
4801 size_t cbToRead, size_t *pcbActuallyRead)
4802{
4803 LogFlowFunc(("pBackendData=%#p uOffset=%llu pvBuf=%#p cbToRead=%zu pcbActuallyRead=%#p\n", pBackendData, uOffset, pvBuf, cbToRead, pcbActuallyRead));
4804 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
4805 PVMDKEXTENT pExtent;
4806 uint64_t uSectorExtentRel;
4807 uint64_t uSectorExtentAbs;
4808 int rc;
4809
4810 AssertPtr(pImage);
4811 Assert(uOffset % 512 == 0);
4812 Assert(cbToRead % 512 == 0);
4813
4814 if ( uOffset + cbToRead > pImage->cbSize
4815 || cbToRead == 0)
4816 {
4817 rc = VERR_INVALID_PARAMETER;
4818 goto out;
4819 }
4820
4821 rc = vmdkFindExtent(pImage, VMDK_BYTE2SECTOR(uOffset),
4822 &pExtent, &uSectorExtentRel);
4823 if (RT_FAILURE(rc))
4824 goto out;
4825
4826 /* Check access permissions as defined in the extent descriptor. */
4827 if (pExtent->enmAccess == VMDKACCESS_NOACCESS)
4828 {
4829 rc = VERR_VD_VMDK_INVALID_STATE;
4830 goto out;
4831 }
4832
4833 /* Clip read range to remain in this extent. */
4834 cbToRead = RT_MIN(cbToRead, VMDK_SECTOR2BYTE(pExtent->uSectorOffset + pExtent->cNominalSectors - uSectorExtentRel));
4835
4836 /* Handle the read according to the current extent type. */
4837 switch (pExtent->enmType)
4838 {
4839 case VMDKETYPE_HOSTED_SPARSE:
4840#ifdef VBOX_WITH_VMDK_ESX
4841 case VMDKETYPE_ESX_SPARSE:
4842#endif /* VBOX_WITH_VMDK_ESX */
4843 rc = vmdkGetSector(pImage->pGTCache, pExtent, uSectorExtentRel,
4844 &uSectorExtentAbs);
4845 if (RT_FAILURE(rc))
4846 goto out;
4847 /* Clip read range to at most the rest of the grain. */
4848 cbToRead = RT_MIN(cbToRead, VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain - uSectorExtentRel % pExtent->cSectorsPerGrain));
4849 Assert(!(cbToRead % 512));
4850 if (uSectorExtentAbs == 0)
4851 rc = VERR_VD_BLOCK_FREE;
4852 else
4853 {
4854 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
4855 {
4856 uint32_t uSectorInGrain = uSectorExtentRel % pExtent->cSectorsPerGrain;
4857 uSectorExtentAbs -= uSectorInGrain;
4858 uint64_t uLBA;
4859 if (pExtent->uGrainSector != uSectorExtentAbs)
4860 {
4861 rc = vmdkFileInflateAt(pExtent->pFile, VMDK_SECTOR2BYTE(uSectorExtentAbs),
4862 pExtent->pvGrain, VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain), VMDK_MARKER_IGNORE, &uLBA, NULL);
4863 if (RT_FAILURE(rc))
4864 {
4865 pExtent->uGrainSector = 0;
4866 AssertRC(rc);
4867 goto out;
4868 }
4869 pExtent->uGrainSector = uSectorExtentAbs;
4870 Assert(uLBA == uSectorExtentRel);
4871 }
4872 memcpy(pvBuf, (uint8_t *)pExtent->pvGrain + VMDK_SECTOR2BYTE(uSectorInGrain), cbToRead);
4873 }
4874 else
4875 {
4876 rc = vmdkFileReadAt(pExtent->pFile,
4877 VMDK_SECTOR2BYTE(uSectorExtentAbs),
4878 pvBuf, cbToRead, NULL);
4879 }
4880 }
4881 break;
4882 case VMDKETYPE_FLAT:
4883 rc = vmdkFileReadAt(pExtent->pFile,
4884 VMDK_SECTOR2BYTE(uSectorExtentRel),
4885 pvBuf, cbToRead, NULL);
4886 break;
4887 case VMDKETYPE_ZERO:
4888 memset(pvBuf, '\0', cbToRead);
4889 break;
4890 }
4891 if (pcbActuallyRead)
4892 *pcbActuallyRead = cbToRead;
4893
4894out:
4895 LogFlowFunc(("returns %Rrc\n", rc));
4896 return rc;
4897}
4898
4899/** @copydoc VBOXHDDBACKEND::pfnWrite */
4900static int vmdkWrite(void *pBackendData, uint64_t uOffset, const void *pvBuf,
4901 size_t cbToWrite, size_t *pcbWriteProcess,
4902 size_t *pcbPreRead, size_t *pcbPostRead, unsigned fWrite)
4903{
4904 LogFlowFunc(("pBackendData=%#p uOffset=%llu pvBuf=%#p cbToWrite=%zu pcbWriteProcess=%#p pcbPreRead=%#p pcbPostRead=%#p\n", pBackendData, uOffset, pvBuf, cbToWrite, pcbWriteProcess, pcbPreRead, pcbPostRead));
4905 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
4906 PVMDKEXTENT pExtent;
4907 uint64_t uSectorExtentRel;
4908 uint64_t uSectorExtentAbs;
4909 int rc;
4910
4911 AssertPtr(pImage);
4912 Assert(uOffset % 512 == 0);
4913 Assert(cbToWrite % 512 == 0);
4914
4915 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
4916 {
4917 rc = VERR_VD_IMAGE_READ_ONLY;
4918 goto out;
4919 }
4920
4921 if (cbToWrite == 0)
4922 {
4923 rc = VERR_INVALID_PARAMETER;
4924 goto out;
4925 }
4926
4927 /* No size check here, will do that later when the extent is located.
4928 * There are sparse images out there which according to the spec are
4929 * invalid, because the total size is not a multiple of the grain size.
4930 * Also for sparse images which are stitched together in odd ways (not at
4931 * grain boundaries, and with the nominal size not being a multiple of the
4932 * grain size), this would prevent writing to the last grain. */
4933
4934 rc = vmdkFindExtent(pImage, VMDK_BYTE2SECTOR(uOffset),
4935 &pExtent, &uSectorExtentRel);
4936 if (RT_FAILURE(rc))
4937 goto out;
4938
4939 /* Check access permissions as defined in the extent descriptor. */
4940 if (pExtent->enmAccess != VMDKACCESS_READWRITE)
4941 {
4942 rc = VERR_VD_VMDK_INVALID_STATE;
4943 goto out;
4944 }
4945
4946 /* Handle the write according to the current extent type. */
4947 switch (pExtent->enmType)
4948 {
4949 case VMDKETYPE_HOSTED_SPARSE:
4950#ifdef VBOX_WITH_VMDK_ESX
4951 case VMDKETYPE_ESX_SPARSE:
4952#endif /* VBOX_WITH_VMDK_ESX */
4953 rc = vmdkGetSector(pImage->pGTCache, pExtent, uSectorExtentRel,
4954 &uSectorExtentAbs);
4955 if (RT_FAILURE(rc))
4956 goto out;
4957 /* Clip write range to at most the rest of the grain. */
4958 cbToWrite = RT_MIN(cbToWrite, VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain - uSectorExtentRel % pExtent->cSectorsPerGrain));
4959 if ( pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED
4960 && uSectorExtentRel < (uint64_t)pExtent->uLastGrainWritten * pExtent->cSectorsPerGrain)
4961 {
4962 rc = VERR_VD_VMDK_INVALID_WRITE;
4963 goto out;
4964 }
4965 if (uSectorExtentAbs == 0)
4966 {
4967 if (cbToWrite == VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain))
4968 {
4969 /* Full block write to a previously unallocated block.
4970 * Check if the caller wants to avoid the automatic alloc. */
4971 if (!(fWrite & VD_WRITE_NO_ALLOC))
4972 {
4973 /* Allocate GT and find out where to store the grain. */
4974 rc = vmdkAllocGrain(pImage->pGTCache, pExtent,
4975 uSectorExtentRel, pvBuf, cbToWrite);
4976 }
4977 else
4978 rc = VERR_VD_BLOCK_FREE;
4979 *pcbPreRead = 0;
4980 *pcbPostRead = 0;
4981 }
4982 else
4983 {
4984 /* Clip write range to remain in this extent. */
4985 cbToWrite = RT_MIN(cbToWrite, VMDK_SECTOR2BYTE(pExtent->uSectorOffset + pExtent->cNominalSectors - uSectorExtentRel));
4986 *pcbPreRead = VMDK_SECTOR2BYTE(uSectorExtentRel % pExtent->cSectorsPerGrain);
4987 *pcbPostRead = VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain) - cbToWrite - *pcbPreRead;
4988 rc = VERR_VD_BLOCK_FREE;
4989 }
4990 }
4991 else
4992 {
4993 if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
4994 {
4995 uint32_t uSectorInGrain = uSectorExtentRel % pExtent->cSectorsPerGrain;
4996 uSectorExtentAbs -= uSectorInGrain;
4997 uint64_t uLBA;
4998 if ( pExtent->uGrainSector != uSectorExtentAbs
4999 || pExtent->uGrainSector != pExtent->uLastGrainSector)
5000 {
5001 rc = vmdkFileInflateAt(pExtent->pFile, VMDK_SECTOR2BYTE(uSectorExtentAbs),
5002 pExtent->pvGrain, VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain), VMDK_MARKER_IGNORE, &uLBA, NULL);
5003 if (RT_FAILURE(rc))
5004 {
5005 pExtent->uGrainSector = 0;
5006 pExtent->uLastGrainSector = 0;
5007 AssertRC(rc);
5008 goto out;
5009 }
5010 pExtent->uGrainSector = uSectorExtentAbs;
5011 pExtent->uLastGrainSector = uSectorExtentAbs;
5012 Assert(uLBA == uSectorExtentRel);
5013 }
5014 memcpy((uint8_t *)pExtent->pvGrain + VMDK_SECTOR2BYTE(uSectorInGrain), pvBuf, cbToWrite);
5015 uint32_t cbGrain = 0;
5016 rc = vmdkFileDeflateAt(pExtent->pFile,
5017 VMDK_SECTOR2BYTE(uSectorExtentAbs),
5018 pExtent->pvGrain, VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain),
5019 VMDK_MARKER_IGNORE, uLBA, &cbGrain);
5020 if (RT_FAILURE(rc))
5021 {
5022 pExtent->uGrainSector = 0;
5023 pExtent->uLastGrainSector = 0;
5024 AssertRC(rc);
5025 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: cannot write compressed data block in '%s'"), pExtent->pszFullname);
5026 }
5027 cbGrain = RT_ALIGN(cbGrain, 512);
5028 pExtent->uLastGrainSector = uSectorExtentAbs;
5029 pExtent->uLastGrainWritten = uSectorExtentRel / pExtent->cSectorsPerGrain;
5030 pExtent->cbLastGrainWritten = cbGrain;
5031
5032 uint64_t uEOSOff = 0;
5033 if (pExtent->fFooter)
5034 {
5035 uEOSOff = 512;
5036 rc = vmdkWriteMetaSparseExtent(pExtent, VMDK_SECTOR2BYTE(uSectorExtentAbs) + RT_ALIGN(cbGrain, 512));
5037 if (RT_FAILURE(rc))
5038 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: cannot write footer after data block in '%s'"), pExtent->pszFullname);
5039 }
5040 uint8_t aEOS[512];
5041 memset(aEOS, '\0', sizeof(aEOS));
5042 rc = vmdkFileWriteAt(pExtent->pFile,
5043 VMDK_SECTOR2BYTE(uSectorExtentAbs) + RT_ALIGN(cbGrain, 512) + uEOSOff,
5044 aEOS, sizeof(aEOS), NULL);
5045 if (RT_FAILURE(rc))
5046 return vmdkError(pExtent->pImage, rc, RT_SRC_POS, N_("VMDK: cannot write end-of stream marker after data block in '%s'"), pExtent->pszFullname);
5047 }
5048 else
5049 {
5050 rc = vmdkFileWriteAt(pExtent->pFile,
5051 VMDK_SECTOR2BYTE(uSectorExtentAbs),
5052 pvBuf, cbToWrite, NULL);
5053 }
5054 }
5055 break;
5056 case VMDKETYPE_FLAT:
5057 /* Clip write range to remain in this extent. */
5058 cbToWrite = RT_MIN(cbToWrite, VMDK_SECTOR2BYTE(pExtent->uSectorOffset + pExtent->cNominalSectors - uSectorExtentRel));
5059 rc = vmdkFileWriteAt(pExtent->pFile,
5060 VMDK_SECTOR2BYTE(uSectorExtentRel),
5061 pvBuf, cbToWrite, NULL);
5062 break;
5063 case VMDKETYPE_ZERO:
5064 /* Clip write range to remain in this extent. */
5065 cbToWrite = RT_MIN(cbToWrite, VMDK_SECTOR2BYTE(pExtent->uSectorOffset + pExtent->cNominalSectors - uSectorExtentRel));
5066 break;
5067 }
5068 if (pcbWriteProcess)
5069 *pcbWriteProcess = cbToWrite;
5070
5071out:
5072 LogFlowFunc(("returns %Rrc\n", rc));
5073 return rc;
5074}
5075
5076/** @copydoc VBOXHDDBACKEND::pfnFlush */
5077static int vmdkFlush(void *pBackendData)
5078{
5079 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
5080 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5081 int rc;
5082
5083 AssertPtr(pImage);
5084
5085 rc = vmdkFlushImage(pImage);
5086 LogFlowFunc(("returns %Rrc\n", rc));
5087 return rc;
5088}
5089
5090/** @copydoc VBOXHDDBACKEND::pfnGetVersion */
5091static unsigned vmdkGetVersion(void *pBackendData)
5092{
5093 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
5094 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5095
5096 AssertPtr(pImage);
5097
5098 if (pImage)
5099 return VMDK_IMAGE_VERSION;
5100 else
5101 return 0;
5102}
5103
5104/** @copydoc VBOXHDDBACKEND::pfnGetSize */
5105static uint64_t vmdkGetSize(void *pBackendData)
5106{
5107 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
5108 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5109
5110 AssertPtr(pImage);
5111
5112 if (pImage)
5113 return pImage->cbSize;
5114 else
5115 return 0;
5116}
5117
5118/** @copydoc VBOXHDDBACKEND::pfnGetFileSize */
5119static uint64_t vmdkGetFileSize(void *pBackendData)
5120{
5121 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
5122 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5123 uint64_t cb = 0;
5124
5125 AssertPtr(pImage);
5126
5127 if (pImage)
5128 {
5129 uint64_t cbFile;
5130 if (pImage->pFile != NULL)
5131 {
5132 int rc = vmdkFileGetSize(pImage->pFile, &cbFile);
5133 if (RT_SUCCESS(rc))
5134 cb += cbFile;
5135 }
5136 for (unsigned i = 0; i < pImage->cExtents; i++)
5137 {
5138 if (pImage->pExtents[i].pFile != NULL)
5139 {
5140 int rc = vmdkFileGetSize(pImage->pExtents[i].pFile, &cbFile);
5141 if (RT_SUCCESS(rc))
5142 cb += cbFile;
5143 }
5144 }
5145 }
5146
5147 LogFlowFunc(("returns %lld\n", cb));
5148 return cb;
5149}
5150
5151/** @copydoc VBOXHDDBACKEND::pfnGetPCHSGeometry */
5152static int vmdkGetPCHSGeometry(void *pBackendData,
5153 PPDMMEDIAGEOMETRY pPCHSGeometry)
5154{
5155 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p\n", pBackendData, pPCHSGeometry));
5156 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5157 int rc;
5158
5159 AssertPtr(pImage);
5160
5161 if (pImage)
5162 {
5163 if (pImage->PCHSGeometry.cCylinders)
5164 {
5165 *pPCHSGeometry = pImage->PCHSGeometry;
5166 rc = VINF_SUCCESS;
5167 }
5168 else
5169 rc = VERR_VD_GEOMETRY_NOT_SET;
5170 }
5171 else
5172 rc = VERR_VD_NOT_OPENED;
5173
5174 LogFlowFunc(("returns %Rrc (PCHS=%u/%u/%u)\n", rc, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
5175 return rc;
5176}
5177
5178/** @copydoc VBOXHDDBACKEND::pfnSetPCHSGeometry */
5179static int vmdkSetPCHSGeometry(void *pBackendData,
5180 PCPDMMEDIAGEOMETRY pPCHSGeometry)
5181{
5182 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p PCHS=%u/%u/%u\n", pBackendData, pPCHSGeometry, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
5183 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5184 int rc;
5185
5186 AssertPtr(pImage);
5187
5188 if (pImage)
5189 {
5190 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
5191 {
5192 rc = VERR_VD_IMAGE_READ_ONLY;
5193 goto out;
5194 }
5195 rc = vmdkDescSetPCHSGeometry(pImage, pPCHSGeometry);
5196 if (RT_FAILURE(rc))
5197 goto out;
5198
5199 pImage->PCHSGeometry = *pPCHSGeometry;
5200 rc = VINF_SUCCESS;
5201 }
5202 else
5203 rc = VERR_VD_NOT_OPENED;
5204
5205out:
5206 LogFlowFunc(("returns %Rrc\n", rc));
5207 return rc;
5208}
5209
5210/** @copydoc VBOXHDDBACKEND::pfnGetLCHSGeometry */
5211static int vmdkGetLCHSGeometry(void *pBackendData,
5212 PPDMMEDIAGEOMETRY pLCHSGeometry)
5213{
5214 LogFlowFunc(("pBackendData=%#p pLCHSGeometry=%#p\n", pBackendData, pLCHSGeometry));
5215 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5216 int rc;
5217
5218 AssertPtr(pImage);
5219
5220 if (pImage)
5221 {
5222 if (pImage->LCHSGeometry.cCylinders)
5223 {
5224 *pLCHSGeometry = pImage->LCHSGeometry;
5225 rc = VINF_SUCCESS;
5226 }
5227 else
5228 rc = VERR_VD_GEOMETRY_NOT_SET;
5229 }
5230 else
5231 rc = VERR_VD_NOT_OPENED;
5232
5233 LogFlowFunc(("returns %Rrc (LCHS=%u/%u/%u)\n", rc, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
5234 return rc;
5235}
5236
5237/** @copydoc VBOXHDDBACKEND::pfnSetLCHSGeometry */
5238static int vmdkSetLCHSGeometry(void *pBackendData,
5239 PCPDMMEDIAGEOMETRY pLCHSGeometry)
5240{
5241 LogFlowFunc(("pBackendData=%#p pLCHSGeometry=%#p LCHS=%u/%u/%u\n", pBackendData, pLCHSGeometry, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
5242 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5243 int rc;
5244
5245 AssertPtr(pImage);
5246
5247 if (pImage)
5248 {
5249 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
5250 {
5251 rc = VERR_VD_IMAGE_READ_ONLY;
5252 goto out;
5253 }
5254 rc = vmdkDescSetLCHSGeometry(pImage, pLCHSGeometry);
5255 if (RT_FAILURE(rc))
5256 goto out;
5257
5258 pImage->LCHSGeometry = *pLCHSGeometry;
5259 rc = VINF_SUCCESS;
5260 }
5261 else
5262 rc = VERR_VD_NOT_OPENED;
5263
5264out:
5265 LogFlowFunc(("returns %Rrc\n", rc));
5266 return rc;
5267}
5268
5269/** @copydoc VBOXHDDBACKEND::pfnGetImageFlags */
5270static unsigned vmdkGetImageFlags(void *pBackendData)
5271{
5272 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
5273 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5274 unsigned uImageFlags;
5275
5276 AssertPtr(pImage);
5277
5278 if (pImage)
5279 uImageFlags = pImage->uImageFlags;
5280 else
5281 uImageFlags = 0;
5282
5283 LogFlowFunc(("returns %#x\n", uImageFlags));
5284 return uImageFlags;
5285}
5286
5287/** @copydoc VBOXHDDBACKEND::pfnGetOpenFlags */
5288static unsigned vmdkGetOpenFlags(void *pBackendData)
5289{
5290 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
5291 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5292 unsigned uOpenFlags;
5293
5294 AssertPtr(pImage);
5295
5296 if (pImage)
5297 uOpenFlags = pImage->uOpenFlags;
5298 else
5299 uOpenFlags = 0;
5300
5301 LogFlowFunc(("returns %#x\n", uOpenFlags));
5302 return uOpenFlags;
5303}
5304
5305/** @copydoc VBOXHDDBACKEND::pfnSetOpenFlags */
5306static int vmdkSetOpenFlags(void *pBackendData, unsigned uOpenFlags)
5307{
5308 LogFlowFunc(("pBackendData=%#p\n uOpenFlags=%#x", pBackendData, uOpenFlags));
5309 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5310 int rc;
5311
5312 /* Image must be opened and the new flags must be valid. Just readonly and
5313 * info flags are supported. */
5314 if (!pImage || (uOpenFlags & ~(VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO | VD_OPEN_FLAGS_ASYNC_IO)))
5315 {
5316 rc = VERR_INVALID_PARAMETER;
5317 goto out;
5318 }
5319
5320 /* Implement this operation via reopening the image. */
5321 vmdkFreeImage(pImage, false);
5322 rc = vmdkOpenImage(pImage, uOpenFlags);
5323
5324out:
5325 LogFlowFunc(("returns %Rrc\n", rc));
5326 return rc;
5327}
5328
5329/** @copydoc VBOXHDDBACKEND::pfnGetComment */
5330static int vmdkGetComment(void *pBackendData, char *pszComment,
5331 size_t cbComment)
5332{
5333 LogFlowFunc(("pBackendData=%#p pszComment=%#p cbComment=%zu\n", pBackendData, pszComment, cbComment));
5334 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5335 int rc;
5336
5337 AssertPtr(pImage);
5338
5339 if (pImage)
5340 {
5341 const char *pszCommentEncoded = NULL;
5342 rc = vmdkDescDDBGetStr(pImage, &pImage->Descriptor,
5343 "ddb.comment", &pszCommentEncoded);
5344 if (rc == VERR_VD_VMDK_VALUE_NOT_FOUND)
5345 pszCommentEncoded = NULL;
5346 else if (RT_FAILURE(rc))
5347 goto out;
5348
5349 if (pszComment && pszCommentEncoded)
5350 rc = vmdkDecodeString(pszCommentEncoded, pszComment, cbComment);
5351 else
5352 {
5353 if (pszComment)
5354 *pszComment = '\0';
5355 rc = VINF_SUCCESS;
5356 }
5357 if (pszCommentEncoded)
5358 RTStrFree((char *)(void *)pszCommentEncoded);
5359 }
5360 else
5361 rc = VERR_VD_NOT_OPENED;
5362
5363out:
5364 LogFlowFunc(("returns %Rrc comment='%s'\n", rc, pszComment));
5365 return rc;
5366}
5367
5368/** @copydoc VBOXHDDBACKEND::pfnSetComment */
5369static int vmdkSetComment(void *pBackendData, const char *pszComment)
5370{
5371 LogFlowFunc(("pBackendData=%#p pszComment=\"%s\"\n", pBackendData, pszComment));
5372 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5373 int rc;
5374
5375 AssertPtr(pImage);
5376
5377 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
5378 {
5379 rc = VERR_VD_IMAGE_READ_ONLY;
5380 goto out;
5381 }
5382
5383 if (pImage)
5384 rc = vmdkSetImageComment(pImage, pszComment);
5385 else
5386 rc = VERR_VD_NOT_OPENED;
5387
5388out:
5389 LogFlowFunc(("returns %Rrc\n", rc));
5390 return rc;
5391}
5392
5393/** @copydoc VBOXHDDBACKEND::pfnGetUuid */
5394static int vmdkGetUuid(void *pBackendData, PRTUUID pUuid)
5395{
5396 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
5397 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5398 int rc;
5399
5400 AssertPtr(pImage);
5401
5402 if (pImage)
5403 {
5404 *pUuid = pImage->ImageUuid;
5405 rc = VINF_SUCCESS;
5406 }
5407 else
5408 rc = VERR_VD_NOT_OPENED;
5409
5410 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
5411 return rc;
5412}
5413
5414/** @copydoc VBOXHDDBACKEND::pfnSetUuid */
5415static int vmdkSetUuid(void *pBackendData, PCRTUUID pUuid)
5416{
5417 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
5418 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5419 int rc;
5420
5421 LogFlowFunc(("%RTuuid\n", pUuid));
5422 AssertPtr(pImage);
5423
5424 if (pImage)
5425 {
5426 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
5427 {
5428 pImage->ImageUuid = *pUuid;
5429 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
5430 VMDK_DDB_IMAGE_UUID, pUuid);
5431 if (RT_FAILURE(rc))
5432 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error storing image UUID in descriptor in '%s'"), pImage->pszFilename);
5433 rc = VINF_SUCCESS;
5434 }
5435 else
5436 rc = VERR_VD_IMAGE_READ_ONLY;
5437 }
5438 else
5439 rc = VERR_VD_NOT_OPENED;
5440
5441 LogFlowFunc(("returns %Rrc\n", rc));
5442 return rc;
5443}
5444
5445/** @copydoc VBOXHDDBACKEND::pfnGetModificationUuid */
5446static int vmdkGetModificationUuid(void *pBackendData, PRTUUID pUuid)
5447{
5448 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
5449 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5450 int rc;
5451
5452 AssertPtr(pImage);
5453
5454 if (pImage)
5455 {
5456 *pUuid = pImage->ModificationUuid;
5457 rc = VINF_SUCCESS;
5458 }
5459 else
5460 rc = VERR_VD_NOT_OPENED;
5461
5462 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
5463 return rc;
5464}
5465
5466/** @copydoc VBOXHDDBACKEND::pfnSetModificationUuid */
5467static int vmdkSetModificationUuid(void *pBackendData, PCRTUUID pUuid)
5468{
5469 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
5470 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5471 int rc;
5472
5473 AssertPtr(pImage);
5474
5475 if (pImage)
5476 {
5477 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
5478 {
5479 pImage->ModificationUuid = *pUuid;
5480 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
5481 VMDK_DDB_MODIFICATION_UUID, pUuid);
5482 if (RT_FAILURE(rc))
5483 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error storing modification UUID in descriptor in '%s'"), pImage->pszFilename);
5484 rc = VINF_SUCCESS;
5485 }
5486 else
5487 rc = VERR_VD_IMAGE_READ_ONLY;
5488 }
5489 else
5490 rc = VERR_VD_NOT_OPENED;
5491
5492 LogFlowFunc(("returns %Rrc\n", rc));
5493 return rc;
5494}
5495
5496/** @copydoc VBOXHDDBACKEND::pfnGetParentUuid */
5497static int vmdkGetParentUuid(void *pBackendData, PRTUUID pUuid)
5498{
5499 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
5500 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5501 int rc;
5502
5503 AssertPtr(pImage);
5504
5505 if (pImage)
5506 {
5507 *pUuid = pImage->ParentUuid;
5508 rc = VINF_SUCCESS;
5509 }
5510 else
5511 rc = VERR_VD_NOT_OPENED;
5512
5513 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
5514 return rc;
5515}
5516
5517/** @copydoc VBOXHDDBACKEND::pfnSetParentUuid */
5518static int vmdkSetParentUuid(void *pBackendData, PCRTUUID pUuid)
5519{
5520 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
5521 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5522 int rc;
5523
5524 AssertPtr(pImage);
5525
5526 if (pImage)
5527 {
5528 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
5529 {
5530 pImage->ParentUuid = *pUuid;
5531 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
5532 VMDK_DDB_PARENT_UUID, pUuid);
5533 if (RT_FAILURE(rc))
5534 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error storing parent image UUID in descriptor in '%s'"), pImage->pszFilename);
5535 rc = VINF_SUCCESS;
5536 }
5537 else
5538 rc = VERR_VD_IMAGE_READ_ONLY;
5539 }
5540 else
5541 rc = VERR_VD_NOT_OPENED;
5542
5543 LogFlowFunc(("returns %Rrc\n", rc));
5544 return rc;
5545}
5546
5547/** @copydoc VBOXHDDBACKEND::pfnGetParentModificationUuid */
5548static int vmdkGetParentModificationUuid(void *pBackendData, PRTUUID pUuid)
5549{
5550 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
5551 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5552 int rc;
5553
5554 AssertPtr(pImage);
5555
5556 if (pImage)
5557 {
5558 *pUuid = pImage->ParentModificationUuid;
5559 rc = VINF_SUCCESS;
5560 }
5561 else
5562 rc = VERR_VD_NOT_OPENED;
5563
5564 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
5565 return rc;
5566}
5567
5568/** @copydoc VBOXHDDBACKEND::pfnSetParentModificationUuid */
5569static int vmdkSetParentModificationUuid(void *pBackendData, PCRTUUID pUuid)
5570{
5571 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
5572 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5573 int rc;
5574
5575 AssertPtr(pImage);
5576
5577 if (pImage)
5578 {
5579 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
5580 {
5581 pImage->ParentModificationUuid = *pUuid;
5582 rc = vmdkDescDDBSetUuid(pImage, &pImage->Descriptor,
5583 VMDK_DDB_PARENT_MODIFICATION_UUID, pUuid);
5584 if (RT_FAILURE(rc))
5585 return vmdkError(pImage, rc, RT_SRC_POS, N_("VMDK: error storing parent image UUID in descriptor in '%s'"), pImage->pszFilename);
5586 rc = VINF_SUCCESS;
5587 }
5588 else
5589 rc = VERR_VD_IMAGE_READ_ONLY;
5590 }
5591 else
5592 rc = VERR_VD_NOT_OPENED;
5593
5594 LogFlowFunc(("returns %Rrc\n", rc));
5595 return rc;
5596}
5597
5598/** @copydoc VBOXHDDBACKEND::pfnDump */
5599static void vmdkDump(void *pBackendData)
5600{
5601 PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
5602
5603 AssertPtr(pImage);
5604 if (pImage)
5605 {
5606 RTLogPrintf("Header: Geometry PCHS=%u/%u/%u LCHS=%u/%u/%u cbSector=%llu\n",
5607 pImage->PCHSGeometry.cCylinders, pImage->PCHSGeometry.cHeads, pImage->PCHSGeometry.cSectors,
5608 pImage->LCHSGeometry.cCylinders, pImage->LCHSGeometry.cHeads, pImage->LCHSGeometry.cSectors,
5609 VMDK_BYTE2SECTOR(pImage->cbSize));
5610 RTLogPrintf("Header: uuidCreation={%RTuuid}\n", &pImage->ImageUuid);
5611 RTLogPrintf("Header: uuidModification={%RTuuid}\n", &pImage->ModificationUuid);
5612 RTLogPrintf("Header: uuidParent={%RTuuid}\n", &pImage->ParentUuid);
5613 RTLogPrintf("Header: uuidParentModification={%RTuuid}\n", &pImage->ParentModificationUuid);
5614 }
5615}
5616
5617
5618static int vmdkGetTimeStamp(void *pvBackendData, PRTTIMESPEC pTimeStamp)
5619{
5620 int rc = VERR_NOT_IMPLEMENTED;
5621 LogFlow(("%s: returned %Rrc\n", __FUNCTION__, rc));
5622 return rc;
5623}
5624
5625static int vmdkGetParentTimeStamp(void *pvBackendData, PRTTIMESPEC pTimeStamp)
5626{
5627 int rc = VERR_NOT_IMPLEMENTED;
5628 LogFlow(("%s: returned %Rrc\n", __FUNCTION__, rc));
5629 return rc;
5630}
5631
5632static int vmdkSetParentTimeStamp(void *pvBackendData, PCRTTIMESPEC pTimeStamp)
5633{
5634 int rc = VERR_NOT_IMPLEMENTED;
5635 LogFlow(("%s: returned %Rrc\n", __FUNCTION__, rc));
5636 return rc;
5637}
5638
5639static int vmdkGetParentFilename(void *pvBackendData, char **ppszParentFilename)
5640{
5641 int rc = VERR_NOT_IMPLEMENTED;
5642 LogFlow(("%s: returned %Rrc\n", __FUNCTION__, rc));
5643 return rc;
5644}
5645
5646static int vmdkSetParentFilename(void *pvBackendData, const char *pszParentFilename)
5647{
5648 int rc = VERR_NOT_IMPLEMENTED;
5649 LogFlow(("%s: returned %Rrc\n", __FUNCTION__, rc));
5650 return rc;
5651}
5652
5653static bool vmdkIsAsyncIOSupported(void *pvBackendData)
5654{
5655 PVMDKIMAGE pImage = (PVMDKIMAGE)pvBackendData;
5656 bool fAsyncIOSupported = false;
5657
5658 if (pImage)
5659 {
5660 /* We only support async I/O support if the image only consists of FLAT or ZERO extents. */
5661 fAsyncIOSupported = true;
5662 for (unsigned i = 0; i < pImage->cExtents; i++)
5663 {
5664 if ( (pImage->pExtents[i].enmType != VMDKETYPE_FLAT)
5665 && (pImage->pExtents[i].enmType != VMDKETYPE_ZERO))
5666 {
5667 fAsyncIOSupported = false;
5668 break; /* Stop search */
5669 }
5670 }
5671 }
5672
5673 return fAsyncIOSupported;
5674}
5675
5676static int vmdkAsyncRead(void *pvBackendData, uint64_t uOffset, size_t cbRead,
5677 PPDMDATASEG paSeg, unsigned cSeg, void *pvUser)
5678{
5679 PVMDKIMAGE pImage = (PVMDKIMAGE)pvBackendData;
5680 PVMDKEXTENT pExtent;
5681 int rc = VINF_SUCCESS;
5682 unsigned cTasksToSubmit = 0;
5683 PPDMDATASEG paSegCurrent = paSeg;
5684 unsigned cbLeftInCurrentSegment = paSegCurrent->cbSeg;
5685 unsigned uOffsetInCurrentSegment = 0;
5686
5687 AssertPtr(pImage);
5688 Assert(uOffset % 512 == 0);
5689 Assert(cbRead % 512 == 0);
5690
5691 if ( uOffset + cbRead > pImage->cbSize
5692 || cbRead == 0)
5693 {
5694 rc = VERR_INVALID_PARAMETER;
5695 goto out;
5696 }
5697
5698 while (cbRead && cSeg)
5699 {
5700 unsigned cbToRead;
5701 uint64_t uSectorExtentRel;
5702
5703 rc = vmdkFindExtent(pImage, VMDK_BYTE2SECTOR(uOffset),
5704 &pExtent, &uSectorExtentRel);
5705 if (RT_FAILURE(rc))
5706 goto out;
5707
5708 /* Check access permissions as defined in the extent descriptor. */
5709 if (pExtent->enmAccess == VMDKACCESS_NOACCESS)
5710 {
5711 rc = VERR_VD_VMDK_INVALID_STATE;
5712 goto out;
5713 }
5714
5715 /* Clip read range to remain in this extent. */
5716 cbToRead = RT_MIN(cbRead, VMDK_SECTOR2BYTE(pExtent->uSectorOffset + pExtent->cNominalSectors - uSectorExtentRel));
5717 /* Clip read range to remain into current data segment. */
5718 cbToRead = RT_MIN(cbToRead, cbLeftInCurrentSegment);
5719
5720 switch (pExtent->enmType)
5721 {
5722 case VMDKETYPE_FLAT:
5723 {
5724 /* Setup new task. */
5725 void *pTask;
5726 rc = pImage->pInterfaceAsyncIOCallbacks->pfnPrepareRead(pImage->pInterfaceAsyncIO->pvUser, pExtent->pFile->pStorage,
5727 VMDK_SECTOR2BYTE(uSectorExtentRel),
5728 (uint8_t *)paSegCurrent->pvSeg + uOffsetInCurrentSegment,
5729 cbToRead, &pTask);
5730 if (RT_FAILURE(rc))
5731 {
5732 AssertMsgFailed(("Preparing read failed rc=%Rrc\n", rc));
5733 goto out;
5734 }
5735
5736 /* Check for enough room first. */
5737 if (cTasksToSubmit >= pImage->cTask)
5738 {
5739 /* We reached maximum, resize array. Try to realloc memory first. */
5740 void **apTaskNew = (void **)RTMemRealloc(pImage->apTask, (cTasksToSubmit + 10)*sizeof(void *));
5741
5742 if (!apTaskNew)
5743 {
5744 /* We failed. Allocate completely new. */
5745 apTaskNew = (void **)RTMemAllocZ((cTasksToSubmit + 10)* sizeof(void *));
5746 if (!apTaskNew)
5747 {
5748 /* Damn, we are out of memory. */
5749 rc = VERR_NO_MEMORY;
5750 goto out;
5751 }
5752
5753 /* Copy task handles over. */
5754 for (unsigned i = 0; i < cTasksToSubmit; i++)
5755 apTaskNew[i] = pImage->apTask[i];
5756
5757 /* Free old memory. */
5758 RTMemFree(pImage->apTask);
5759 }
5760
5761 pImage->cTask = cTasksToSubmit + 10;
5762 pImage->apTask = apTaskNew;
5763 }
5764
5765 pImage->apTask[cTasksToSubmit] = pTask;
5766 cTasksToSubmit++;
5767 break;
5768 }
5769 case VMDKETYPE_ZERO:
5770 memset((uint8_t *)paSegCurrent->pvSeg + uOffsetInCurrentSegment, 0, cbToRead);
5771 break;
5772 default:
5773 AssertMsgFailed(("Unsupported extent type %u\n", pExtent->enmType));
5774 }
5775
5776 cbRead -= cbToRead;
5777 uOffset += cbToRead;
5778 cbLeftInCurrentSegment -= cbToRead;
5779 uOffsetInCurrentSegment += cbToRead;
5780 /* Go to next extent if there is no space left in current one. */
5781 if (!cbLeftInCurrentSegment)
5782 {
5783 uOffsetInCurrentSegment = 0;
5784 paSegCurrent++;
5785 cSeg--;
5786 cbLeftInCurrentSegment = paSegCurrent->cbSeg;
5787 }
5788 }
5789
5790 AssertMsg(cbRead == 0, ("No segment left but there is still data to read\n"));
5791
5792 if (cTasksToSubmit == 0)
5793 {
5794 /* The request was completely in a ZERO extent nothing to do. */
5795 rc = VINF_VD_ASYNC_IO_FINISHED;
5796 }
5797 else
5798 {
5799 /* Submit tasks. */
5800 rc = pImage->pInterfaceAsyncIOCallbacks->pfnTasksSubmit(pImage->pInterfaceAsyncIO->pvUser,
5801 pImage->apTask, cTasksToSubmit,
5802 NULL, pvUser,
5803 NULL /* Nothing required after read. */);
5804 AssertMsgRC(rc, ("Failed to enqueue tasks rc=%Rrc\n", rc));
5805 }
5806
5807out:
5808 LogFlowFunc(("returns %Rrc\n", rc));
5809 return rc;
5810}
5811
5812static int vmdkAsyncWrite(void *pvBackendData, uint64_t uOffset, size_t cbWrite,
5813 PPDMDATASEG paSeg, unsigned cSeg, void *pvUser)
5814{
5815 PVMDKIMAGE pImage = (PVMDKIMAGE)pvBackendData;
5816 PVMDKEXTENT pExtent;
5817 int rc = VINF_SUCCESS;
5818 unsigned cTasksToSubmit = 0;
5819 PPDMDATASEG paSegCurrent = paSeg;
5820 unsigned cbLeftInCurrentSegment = paSegCurrent->cbSeg;
5821 unsigned uOffsetInCurrentSegment = 0;
5822
5823 AssertPtr(pImage);
5824 Assert(uOffset % 512 == 0);
5825 Assert(cbWrite % 512 == 0);
5826
5827 if ( uOffset + cbWrite > pImage->cbSize
5828 || cbWrite == 0)
5829 {
5830 rc = VERR_INVALID_PARAMETER;
5831 goto out;
5832 }
5833
5834 while (cbWrite && cSeg)
5835 {
5836 unsigned cbToWrite;
5837 uint64_t uSectorExtentRel;
5838
5839 rc = vmdkFindExtent(pImage, VMDK_BYTE2SECTOR(uOffset),
5840 &pExtent, &uSectorExtentRel);
5841 if (RT_FAILURE(rc))
5842 goto out;
5843
5844 /* Check access permissions as defined in the extent descriptor. */
5845 if (pExtent->enmAccess == VMDKACCESS_NOACCESS)
5846 {
5847 rc = VERR_VD_VMDK_INVALID_STATE;
5848 goto out;
5849 }
5850
5851 /* Clip write range to remain in this extent. */
5852 cbToWrite = RT_MIN(cbWrite, VMDK_SECTOR2BYTE(pExtent->uSectorOffset + pExtent->cNominalSectors - uSectorExtentRel));
5853 /* Clip write range to remain into current data segment. */
5854 cbToWrite = RT_MIN(cbToWrite, cbLeftInCurrentSegment);
5855
5856 switch (pExtent->enmType)
5857 {
5858 case VMDKETYPE_FLAT:
5859 {
5860 /* Setup new task. */
5861 void *pTask;
5862 rc = pImage->pInterfaceAsyncIOCallbacks->pfnPrepareWrite(pImage->pInterfaceAsyncIO->pvUser, pExtent->pFile->pStorage,
5863 VMDK_SECTOR2BYTE(uSectorExtentRel),
5864 (uint8_t *)paSegCurrent->pvSeg + uOffsetInCurrentSegment,
5865 cbToWrite, &pTask);
5866 if (RT_FAILURE(rc))
5867 {
5868 AssertMsgFailed(("Preparing read failed rc=%Rrc\n", rc));
5869 goto out;
5870 }
5871
5872 /* Check for enough room first. */
5873 if (cTasksToSubmit >= pImage->cTask)
5874 {
5875 /* We reached maximum, resize array. Try to realloc memory first. */
5876 void **apTaskNew = (void **)RTMemRealloc(pImage->apTask, (cTasksToSubmit + 10)*sizeof(void *));
5877
5878 if (!apTaskNew)
5879 {
5880 /* We failed. Allocate completely new. */
5881 apTaskNew = (void **)RTMemAllocZ((cTasksToSubmit + 10)* sizeof(void *));
5882 if (!apTaskNew)
5883 {
5884 /* Damn, we are out of memory. */
5885 rc = VERR_NO_MEMORY;
5886 goto out;
5887 }
5888
5889 /* Copy task handles over. */
5890 for (unsigned i = 0; i < cTasksToSubmit; i++)
5891 apTaskNew[i] = pImage->apTask[i];
5892
5893 /* Free old memory. */
5894 RTMemFree(pImage->apTask);
5895 }
5896
5897 pImage->cTask = cTasksToSubmit + 10;
5898 pImage->apTask = apTaskNew;
5899 }
5900
5901 pImage->apTask[cTasksToSubmit] = pTask;
5902 cTasksToSubmit++;
5903 break;
5904 }
5905 case VMDKETYPE_ZERO:
5906 /* Nothing left to do. */
5907 break;
5908 default:
5909 AssertMsgFailed(("Unsupported extent type %u\n", pExtent->enmType));
5910 }
5911
5912 cbWrite -= cbToWrite;
5913 uOffset += cbToWrite;
5914 cbLeftInCurrentSegment -= cbToWrite;
5915 uOffsetInCurrentSegment += cbToWrite;
5916 /* Go to next extent if there is no space left in current one. */
5917 if (!cbLeftInCurrentSegment)
5918 {
5919 uOffsetInCurrentSegment = 0;
5920 paSegCurrent++;
5921 cSeg--;
5922 cbLeftInCurrentSegment = paSegCurrent->cbSeg;
5923 }
5924 }
5925
5926 AssertMsg(cbWrite == 0, ("No segment left but there is still data to read\n"));
5927
5928 if (cTasksToSubmit == 0)
5929 {
5930 /* The request was completely in a ZERO extent nothing to do. */
5931 rc = VINF_VD_ASYNC_IO_FINISHED;
5932 }
5933 else
5934 {
5935 /* Submit tasks. */
5936 rc = pImage->pInterfaceAsyncIOCallbacks->pfnTasksSubmit(pImage->pInterfaceAsyncIO->pvUser,
5937 pImage->apTask, cTasksToSubmit,
5938 NULL, pvUser,
5939 NULL /* Nothing required after read. */);
5940 AssertMsgRC(rc, ("Failed to enqueue tasks rc=%Rrc\n", rc));
5941 }
5942
5943out:
5944 LogFlowFunc(("returns %Rrc\n", rc));
5945 return rc;
5946
5947}
5948
5949
5950VBOXHDDBACKEND g_VmdkBackend =
5951{
5952 /* pszBackendName */
5953 "VMDK",
5954 /* cbSize */
5955 sizeof(VBOXHDDBACKEND),
5956 /* uBackendCaps */
5957 VD_CAP_UUID | VD_CAP_CREATE_FIXED | VD_CAP_CREATE_DYNAMIC
5958 | VD_CAP_CREATE_SPLIT_2G | VD_CAP_DIFF | VD_CAP_FILE |VD_CAP_ASYNC,
5959 /* papszFileExtensions */
5960 s_apszVmdkFileExtensions,
5961 /* paConfigInfo */
5962 NULL,
5963 /* hPlugin */
5964 NIL_RTLDRMOD,
5965 /* pfnCheckIfValid */
5966 vmdkCheckIfValid,
5967 /* pfnOpen */
5968 vmdkOpen,
5969 /* pfnCreate */
5970 vmdkCreate,
5971 /* pfnRename */
5972 vmdkRename,
5973 /* pfnClose */
5974 vmdkClose,
5975 /* pfnRead */
5976 vmdkRead,
5977 /* pfnWrite */
5978 vmdkWrite,
5979 /* pfnFlush */
5980 vmdkFlush,
5981 /* pfnGetVersion */
5982 vmdkGetVersion,
5983 /* pfnGetSize */
5984 vmdkGetSize,
5985 /* pfnGetFileSize */
5986 vmdkGetFileSize,
5987 /* pfnGetPCHSGeometry */
5988 vmdkGetPCHSGeometry,
5989 /* pfnSetPCHSGeometry */
5990 vmdkSetPCHSGeometry,
5991 /* pfnGetLCHSGeometry */
5992 vmdkGetLCHSGeometry,
5993 /* pfnSetLCHSGeometry */
5994 vmdkSetLCHSGeometry,
5995 /* pfnGetImageFlags */
5996 vmdkGetImageFlags,
5997 /* pfnGetOpenFlags */
5998 vmdkGetOpenFlags,
5999 /* pfnSetOpenFlags */
6000 vmdkSetOpenFlags,
6001 /* pfnGetComment */
6002 vmdkGetComment,
6003 /* pfnSetComment */
6004 vmdkSetComment,
6005 /* pfnGetUuid */
6006 vmdkGetUuid,
6007 /* pfnSetUuid */
6008 vmdkSetUuid,
6009 /* pfnGetModificationUuid */
6010 vmdkGetModificationUuid,
6011 /* pfnSetModificationUuid */
6012 vmdkSetModificationUuid,
6013 /* pfnGetParentUuid */
6014 vmdkGetParentUuid,
6015 /* pfnSetParentUuid */
6016 vmdkSetParentUuid,
6017 /* pfnGetParentModificationUuid */
6018 vmdkGetParentModificationUuid,
6019 /* pfnSetParentModificationUuid */
6020 vmdkSetParentModificationUuid,
6021 /* pfnDump */
6022 vmdkDump,
6023 /* pfnGetTimeStamp */
6024 vmdkGetTimeStamp,
6025 /* pfnGetParentTimeStamp */
6026 vmdkGetParentTimeStamp,
6027 /* pfnSetParentTimeStamp */
6028 vmdkSetParentTimeStamp,
6029 /* pfnGetParentFilename */
6030 vmdkGetParentFilename,
6031 /* pfnSetParentFilename */
6032 vmdkSetParentFilename,
6033 /* pfnIsAsyncIOSupported */
6034 vmdkIsAsyncIOSupported,
6035 /* pfnAsyncRead */
6036 vmdkAsyncRead,
6037 /* pfnAsyncWrite */
6038 vmdkAsyncWrite,
6039 /* pfnComposeLocation */
6040 genericFileComposeLocation,
6041 /* pfnComposeName */
6042 genericFileComposeName
6043};
Note: See TracBrowser for help on using the repository browser.

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