VirtualBox

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

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

First part of the PDMAsyncCompletion rewrite:

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

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