VirtualBox

source: vbox/trunk/src/VBox/Storage/VHD.cpp@ 77699

Last change on this file since 77699 was 77699, checked in by vboxsync, 6 years ago

Storage/VHD,Parallels: Plug two small memory leaks when opening an image fails at a particular stage

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 119.1 KB
Line 
1/* $Id: VHD.cpp 77699 2019-03-13 23:22:08Z vboxsync $ */
2/** @file
3 * VHD Disk image, Core Code.
4 */
5
6/*
7 * Copyright (C) 2006-2019 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.215389.xyz. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#define LOG_GROUP LOG_GROUP_VD_VHD
23#include <VBox/vd-plugin.h>
24#include <VBox/err.h>
25
26#include <VBox/log.h>
27#include <VBox/version.h>
28#include <iprt/asm.h>
29#include <iprt/assert.h>
30#include <iprt/mem.h>
31#include <iprt/uuid.h>
32#include <iprt/path.h>
33#include <iprt/string.h>
34#include <iprt/utf16.h>
35
36#include "VDBackends.h"
37
38#define VHD_RELATIVE_MAX_PATH 512
39#define VHD_ABSOLUTE_MAX_PATH 512
40
41#define VHD_SECTOR_SIZE 512
42#define VHD_BLOCK_SIZE (2 * _1M)
43
44/** The maximum VHD size is 2TB due to the 32bit sector numbers in the BAT.
45 * Note that this is the maximum file size including all footers and headers
46 * and not the maximum virtual disk size presented to the guest.
47 */
48#define VHD_MAX_SIZE (2 * _1T)
49/** Maximum number of 512 byte sectors for a VHD image. */
50#define VHD_MAX_SECTORS (VHD_MAX_SIZE / VHD_SECTOR_SIZE)
51
52/* This is common to all VHD disk types and is located at the end of the image */
53#pragma pack(1)
54typedef struct VHDFooter
55{
56 char Cookie[8];
57 uint32_t Features;
58 uint32_t Version;
59 uint64_t DataOffset;
60 uint32_t Timestamp;
61 uint8_t CreatorApp[4];
62 uint32_t CreatorVer;
63 uint32_t CreatorOS;
64 uint64_t OrigSize;
65 uint64_t CurSize;
66 uint16_t DiskGeometryCylinder;
67 uint8_t DiskGeometryHeads;
68 uint8_t DiskGeometrySectors;
69 uint32_t DiskType;
70 uint32_t Checksum;
71 char UniqueID[16];
72 uint8_t SavedState;
73 uint8_t Reserved[427];
74} VHDFooter;
75#pragma pack()
76
77/* this really is spelled with only one n */
78#define VHD_FOOTER_COOKIE "conectix"
79#define VHD_FOOTER_COOKIE_SIZE 8
80
81#define VHD_FOOTER_FEATURES_NOT_ENABLED 0
82#define VHD_FOOTER_FEATURES_TEMPORARY 1
83#define VHD_FOOTER_FEATURES_RESERVED 2
84
85#define VHD_FOOTER_FILE_FORMAT_VERSION 0x00010000
86#define VHD_FOOTER_DATA_OFFSET_FIXED UINT64_C(0xffffffffffffffff)
87#define VHD_FOOTER_DISK_TYPE_FIXED 2
88#define VHD_FOOTER_DISK_TYPE_DYNAMIC 3
89#define VHD_FOOTER_DISK_TYPE_DIFFERENCING 4
90
91#define VHD_MAX_LOCATOR_ENTRIES 8
92#define VHD_PLATFORM_CODE_NONE 0
93#define VHD_PLATFORM_CODE_WI2R 0x57693272
94#define VHD_PLATFORM_CODE_WI2K 0x5769326B
95#define VHD_PLATFORM_CODE_W2RU 0x57327275
96#define VHD_PLATFORM_CODE_W2KU 0x57326B75
97#define VHD_PLATFORM_CODE_MAC 0x4D163220
98#define VHD_PLATFORM_CODE_MACX 0x4D163258
99
100/* Header for expanding disk images. */
101#pragma pack(1)
102typedef struct VHDParentLocatorEntry
103{
104 uint32_t u32Code;
105 uint32_t u32DataSpace;
106 uint32_t u32DataLength;
107 uint32_t u32Reserved;
108 uint64_t u64DataOffset;
109} VHDPLE, *PVHDPLE;
110
111typedef struct VHDDynamicDiskHeader
112{
113 char Cookie[8];
114 uint64_t DataOffset;
115 uint64_t TableOffset;
116 uint32_t HeaderVersion;
117 uint32_t MaxTableEntries;
118 uint32_t BlockSize;
119 uint32_t Checksum;
120 uint8_t ParentUuid[16];
121 uint32_t ParentTimestamp;
122 uint32_t Reserved0;
123 uint16_t ParentUnicodeName[256];
124 VHDPLE ParentLocatorEntry[VHD_MAX_LOCATOR_ENTRIES];
125 uint8_t Reserved1[256];
126} VHDDynamicDiskHeader;
127#pragma pack()
128
129#define VHD_DYNAMIC_DISK_HEADER_COOKIE "cxsparse"
130#define VHD_DYNAMIC_DISK_HEADER_COOKIE_SIZE 8
131#define VHD_DYNAMIC_DISK_HEADER_VERSION 0x00010000
132
133/**
134 * Complete VHD image data structure.
135 */
136typedef struct VHDIMAGE
137{
138 /** Image file name. */
139 const char *pszFilename;
140 /** Opaque storage handle. */
141 PVDIOSTORAGE pStorage;
142
143 /** Pointer to the per-disk VD interface list. */
144 PVDINTERFACE pVDIfsDisk;
145 /** Pointer to the per-image VD interface list. */
146 PVDINTERFACE pVDIfsImage;
147 /** Error interface. */
148 PVDINTERFACEERROR pIfError;
149 /** I/O interface. */
150 PVDINTERFACEIOINT pIfIo;
151
152 /** Open flags passed by VBoxHDD layer. */
153 unsigned uOpenFlags;
154 /** Image flags defined during creation or determined during open. */
155 unsigned uImageFlags;
156 /** Total size of the image. */
157 uint64_t cbSize;
158
159 /** Physical geometry of this image. */
160 VDGEOMETRY PCHSGeometry;
161 /** Logical geometry of this image. */
162 VDGEOMETRY LCHSGeometry;
163
164 /** Image UUID. */
165 RTUUID ImageUuid;
166 /** Parent image UUID. */
167 RTUUID ParentUuid;
168
169 /** Parent's time stamp at the time of image creation. */
170 uint32_t u32ParentTimestamp;
171 /** Relative path to the parent image. */
172 char *pszParentFilename;
173
174 /** The Block Allocation Table. */
175 uint32_t *pBlockAllocationTable;
176 /** Number of entries in the table. */
177 uint32_t cBlockAllocationTableEntries;
178
179 /** Size of one data block. */
180 uint32_t cbDataBlock;
181 /** Sectors per data block. */
182 uint32_t cSectorsPerDataBlock;
183 /** Length of the sector bitmap in bytes. */
184 uint32_t cbDataBlockBitmap;
185 /** A copy of the disk footer. */
186 VHDFooter vhdFooterCopy;
187 /** Current end offset of the file (without the disk footer). */
188 uint64_t uCurrentEndOfFile;
189 /** Size of the data block bitmap in sectors. */
190 uint32_t cDataBlockBitmapSectors;
191 /** Start of the block allocation table. */
192 uint64_t uBlockAllocationTableOffset;
193 /** Buffer to hold block's bitmap for bit search operations. */
194 uint8_t *pu8Bitmap;
195 /** Offset to the next data structure (dynamic disk header). */
196 uint64_t u64DataOffset;
197 /** Flag to force dynamic disk header update. */
198 bool fDynHdrNeedsUpdate;
199 /** The static region list. */
200 VDREGIONLIST RegionList;
201} VHDIMAGE, *PVHDIMAGE;
202
203/**
204 * Structure tracking the expansion process of the image
205 * for async access.
206 */
207typedef struct VHDIMAGEEXPAND
208{
209 /** Flag indicating the status of each step. */
210 volatile uint32_t fFlags;
211 /** The index in the block allocation table which is written. */
212 uint32_t idxBatAllocated;
213 /** Big endian representation of the block index
214 * which is written in the BAT. */
215 uint32_t idxBlockBe;
216 /** Old end of the file - used for rollback in case of an error. */
217 uint64_t cbEofOld;
218 /** Sector bitmap written to the new block - variable in size. */
219 uint8_t au8Bitmap[1];
220} VHDIMAGEEXPAND, *PVHDIMAGEEXPAND;
221
222/**
223 * Flag defines
224 */
225#define VHDIMAGEEXPAND_STEP_IN_PROGRESS (0x0)
226#define VHDIMAGEEXPAND_STEP_FAILED (0x2)
227#define VHDIMAGEEXPAND_STEP_SUCCESS (0x3)
228/** All steps completed successfully. */
229#define VHDIMAGEEXPAND_ALL_SUCCESS (0xff)
230/** All steps completed (no success indicator) */
231#define VHDIMAGEEXPAND_ALL_COMPLETE (0xaa)
232
233/** Every status field has 2 bits so we can encode 4 steps in one byte. */
234#define VHDIMAGEEXPAND_STATUS_MASK 0x03
235#define VHDIMAGEEXPAND_BLOCKBITMAP_STATUS_SHIFT 0x00
236#define VHDIMAGEEXPAND_USERBLOCK_STATUS_SHIFT 0x02
237#define VHDIMAGEEXPAND_FOOTER_STATUS_SHIFT 0x04
238#define VHDIMAGEEXPAND_BAT_STATUS_SHIFT 0x06
239
240/**
241 * Helper macros to get and set the status field.
242 */
243#define VHDIMAGEEXPAND_STATUS_GET(fFlags, cShift) \
244 (((fFlags) >> (cShift)) & VHDIMAGEEXPAND_STATUS_MASK)
245#define VHDIMAGEEXPAND_STATUS_SET(fFlags, cShift, uVal) \
246 ASMAtomicOrU32(&(fFlags), ((uVal) & VHDIMAGEEXPAND_STATUS_MASK) << (cShift))
247
248
249/*********************************************************************************************************************************
250* Static Variables *
251*********************************************************************************************************************************/
252
253/** NULL-terminated array of supported file extensions. */
254static const VDFILEEXTENSION s_aVhdFileExtensions[] =
255{
256 {"vhd", VDTYPE_HDD},
257 {NULL, VDTYPE_INVALID}
258};
259
260
261/*********************************************************************************************************************************
262* Internal Functions *
263*********************************************************************************************************************************/
264
265
266/**
267 * Internal: Compute and update header checksum.
268 */
269static uint32_t vhdChecksum(void *pHeader, uint32_t cbSize)
270{
271 uint32_t u32ChkSum = 0;
272 for (uint32_t i = 0; i < cbSize; i++)
273 u32ChkSum += ((unsigned char *)pHeader)[i];
274 return ~u32ChkSum;
275}
276
277/**
278 * Internal: Convert filename to UTF16 with appropriate endianness.
279 */
280static int vhdFilenameToUtf16(const char *pszFilename, uint16_t *pu16Buf,
281 uint32_t cbBufSize, uint32_t *pcbActualSize,
282 bool fBigEndian)
283{
284 int rc;
285 PRTUTF16 pTmp16 = NULL;
286 size_t cTmp16Len;
287
288 rc = RTStrToUtf16(pszFilename, &pTmp16);
289 if (RT_SUCCESS(rc))
290 {
291 cTmp16Len = RTUtf16Len(pTmp16);
292 if (cTmp16Len * sizeof(*pTmp16) <= cbBufSize)
293 {
294 if (fBigEndian)
295 for (unsigned i = 0; i < cTmp16Len; i++)
296 pu16Buf[i] = RT_H2BE_U16(pTmp16[i]);
297 else
298 memcpy(pu16Buf, pTmp16, cTmp16Len * sizeof(*pTmp16));
299 if (pcbActualSize)
300 *pcbActualSize = (uint32_t)(cTmp16Len * sizeof(*pTmp16));
301 }
302 else
303 rc = VERR_FILENAME_TOO_LONG;
304 }
305
306 if (pTmp16)
307 RTUtf16Free(pTmp16);
308 return rc;
309}
310
311/**
312 * Internal: Update one locator entry.
313 */
314static int vhdLocatorUpdate(PVHDIMAGE pImage, PVHDPLE pLocator, const char *pszFilename)
315{
316 int rc = VINF_SUCCESS;
317 uint32_t cb = 0;
318 uint32_t cbMaxLen = RT_BE2H_U32(pLocator->u32DataSpace);
319 void *pvBuf = RTMemTmpAllocZ(cbMaxLen);
320 char *pszTmp;
321
322 if (!pvBuf)
323 return VERR_NO_MEMORY;
324
325 switch (RT_BE2H_U32(pLocator->u32Code))
326 {
327 case VHD_PLATFORM_CODE_WI2R:
328 {
329 if (RTPathStartsWithRoot(pszFilename))
330 {
331 /* Convert to relative path. */
332 char szPath[RTPATH_MAX];
333 rc = RTPathCalcRelative(szPath, sizeof(szPath), pImage->pszFilename, true /*fFromFile*/, pszFilename);
334 if (RT_SUCCESS(rc))
335 {
336 /* Update plain relative name. */
337 cb = (uint32_t)strlen(szPath);
338 if (cb > cbMaxLen)
339 {
340 rc = VERR_FILENAME_TOO_LONG;
341 break;
342 }
343 memcpy(pvBuf, szPath, cb);
344 }
345 }
346 else
347 {
348 /* Update plain relative name. */
349 cb = (uint32_t)strlen(pszFilename);
350 if (cb > cbMaxLen)
351 {
352 rc = VERR_FILENAME_TOO_LONG;
353 break;
354 }
355 memcpy(pvBuf, pszFilename, cb);
356 }
357 if (RT_SUCCESS(rc))
358 pLocator->u32DataLength = RT_H2BE_U32(cb);
359 break;
360 }
361 case VHD_PLATFORM_CODE_WI2K:
362 /* Update plain absolute name. */
363 rc = RTPathAbs(pszFilename, (char *)pvBuf, cbMaxLen);
364 if (RT_SUCCESS(rc))
365 {
366 cb = (uint32_t)strlen((const char *)pvBuf);
367 pLocator->u32DataLength = RT_H2BE_U32(cb);
368 }
369 break;
370 case VHD_PLATFORM_CODE_W2RU:
371 if (RTPathStartsWithRoot(pszFilename))
372 {
373 /* Convert to relative path. */
374 char szPath[RTPATH_MAX];
375 rc = RTPathCalcRelative(szPath, sizeof(szPath), pImage->pszFilename, true /*fFromFile*/, pszFilename);
376 if (RT_SUCCESS(rc))
377 rc = vhdFilenameToUtf16(szPath, (uint16_t *)pvBuf, cbMaxLen, &cb, false);
378 }
379 else
380 {
381 /* Update unicode relative name. */
382 rc = vhdFilenameToUtf16(pszFilename, (uint16_t *)pvBuf, cbMaxLen, &cb, false);
383 }
384
385 if (RT_SUCCESS(rc))
386 pLocator->u32DataLength = RT_H2BE_U32(cb);
387 break;
388 case VHD_PLATFORM_CODE_W2KU:
389 /* Update unicode absolute name. */
390 pszTmp = (char*)RTMemTmpAllocZ(cbMaxLen);
391 if (!pszTmp)
392 {
393 rc = VERR_NO_MEMORY;
394 break;
395 }
396 rc = RTPathAbs(pszFilename, pszTmp, cbMaxLen);
397 if (RT_FAILURE(rc))
398 {
399 RTMemTmpFree(pszTmp);
400 break;
401 }
402 rc = vhdFilenameToUtf16(pszTmp, (uint16_t *)pvBuf, cbMaxLen, &cb, false);
403 RTMemTmpFree(pszTmp);
404 if (RT_SUCCESS(rc))
405 pLocator->u32DataLength = RT_H2BE_U32(cb);
406 break;
407 default:
408 rc = VERR_NOT_IMPLEMENTED;
409 break;
410 }
411
412 if (RT_SUCCESS(rc))
413 {
414 Assert(cb > 0);
415 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage,
416 RT_BE2H_U64(pLocator->u64DataOffset),
417 pvBuf, cb);
418 }
419
420 if (pvBuf)
421 RTMemTmpFree(pvBuf);
422 return rc;
423}
424
425/**
426 * Internal: Update dynamic disk header from VHDIMAGE.
427 */
428static int vhdDynamicHeaderUpdate(PVHDIMAGE pImage)
429{
430 VHDDynamicDiskHeader ddh;
431 int rc, i;
432
433 if (!pImage)
434 return VERR_VD_NOT_OPENED;
435
436 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage,
437 pImage->u64DataOffset, &ddh, sizeof(ddh));
438 if (RT_FAILURE(rc))
439 return rc;
440 if (memcmp(ddh.Cookie, VHD_DYNAMIC_DISK_HEADER_COOKIE, VHD_DYNAMIC_DISK_HEADER_COOKIE_SIZE) != 0)
441 return VERR_VD_VHD_INVALID_HEADER;
442
443 uint32_t u32Checksum = RT_BE2H_U32(ddh.Checksum);
444 ddh.Checksum = 0;
445 if (u32Checksum != vhdChecksum(&ddh, sizeof(ddh)))
446 return VERR_VD_VHD_INVALID_HEADER;
447
448 /* Update parent's timestamp. */
449 ddh.ParentTimestamp = RT_H2BE_U32(pImage->u32ParentTimestamp);
450 /* Update parent's filename. */
451 if (pImage->pszParentFilename)
452 {
453 rc = vhdFilenameToUtf16(RTPathFilename(pImage->pszParentFilename),
454 ddh.ParentUnicodeName, sizeof(ddh.ParentUnicodeName) - 1, NULL, true);
455 if (RT_FAILURE(rc))
456 return rc;
457 }
458
459 /* Update parent's locators. */
460 for (i = 0; i < VHD_MAX_LOCATOR_ENTRIES; i++)
461 {
462 /* Skip empty locators */
463 if ( ddh.ParentLocatorEntry[i].u32Code != RT_H2BE_U32(VHD_PLATFORM_CODE_NONE)
464 && pImage->pszParentFilename)
465 {
466 rc = vhdLocatorUpdate(pImage, &ddh.ParentLocatorEntry[i], pImage->pszParentFilename);
467 if (RT_FAILURE(rc))
468 return rc;
469 }
470 }
471 /* Update parent's UUID */
472 memcpy(ddh.ParentUuid, pImage->ParentUuid.au8, sizeof(ddh.ParentUuid));
473
474 /* Update data offset and number of table entries. */
475 ddh.MaxTableEntries = RT_H2BE_U32(pImage->cBlockAllocationTableEntries);
476
477 ddh.Checksum = 0;
478 ddh.Checksum = RT_H2BE_U32(vhdChecksum(&ddh, sizeof(ddh)));
479 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage,
480 pImage->u64DataOffset, &ddh, sizeof(ddh));
481 return rc;
482}
483
484/**
485 * Internal: Update the VHD footer.
486 */
487static int vhdUpdateFooter(PVHDIMAGE pImage)
488{
489 int rc = VINF_SUCCESS;
490
491 /* Update fields which can change. */
492 pImage->vhdFooterCopy.CurSize = RT_H2BE_U64(pImage->cbSize);
493 pImage->vhdFooterCopy.DiskGeometryCylinder = RT_H2BE_U16(pImage->PCHSGeometry.cCylinders);
494 pImage->vhdFooterCopy.DiskGeometryHeads = pImage->PCHSGeometry.cHeads;
495 pImage->vhdFooterCopy.DiskGeometrySectors = pImage->PCHSGeometry.cSectors;
496
497 pImage->vhdFooterCopy.Checksum = 0;
498 pImage->vhdFooterCopy.Checksum = RT_H2BE_U32(vhdChecksum(&pImage->vhdFooterCopy, sizeof(VHDFooter)));
499
500 if (pImage->pBlockAllocationTable)
501 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage, 0,
502 &pImage->vhdFooterCopy, sizeof(VHDFooter));
503
504 if (RT_SUCCESS(rc))
505 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage,
506 pImage->uCurrentEndOfFile, &pImage->vhdFooterCopy,
507 sizeof(VHDFooter));
508
509 return rc;
510}
511
512/**
513 * Internal. Flush image data to disk.
514 */
515static int vhdFlushImage(PVHDIMAGE pImage)
516{
517 int rc = VINF_SUCCESS;
518
519 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
520 return VINF_SUCCESS;
521
522 if (pImage->pBlockAllocationTable)
523 {
524 /*
525 * This is an expanding image. Write the BAT and copy of the disk footer.
526 */
527 size_t cbBlockAllocationTableToWrite = pImage->cBlockAllocationTableEntries * sizeof(uint32_t);
528 uint32_t *pBlockAllocationTableToWrite = (uint32_t *)RTMemAllocZ(cbBlockAllocationTableToWrite);
529
530 if (!pBlockAllocationTableToWrite)
531 return VERR_NO_MEMORY;
532
533 /*
534 * The BAT entries have to be stored in big endian format.
535 */
536 for (unsigned i = 0; i < pImage->cBlockAllocationTableEntries; i++)
537 pBlockAllocationTableToWrite[i] = RT_H2BE_U32(pImage->pBlockAllocationTable[i]);
538
539 /*
540 * Write the block allocation table after the copy of the disk footer and the dynamic disk header.
541 */
542 vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage, pImage->uBlockAllocationTableOffset,
543 pBlockAllocationTableToWrite, cbBlockAllocationTableToWrite);
544 if (pImage->fDynHdrNeedsUpdate)
545 rc = vhdDynamicHeaderUpdate(pImage);
546 RTMemFree(pBlockAllocationTableToWrite);
547 }
548
549 if (RT_SUCCESS(rc))
550 rc = vhdUpdateFooter(pImage);
551
552 if (RT_SUCCESS(rc))
553 rc = vdIfIoIntFileFlushSync(pImage->pIfIo, pImage->pStorage);
554
555 return rc;
556}
557
558/**
559 * Internal. Free all allocated space for representing an image except pImage,
560 * and optionally delete the image from disk.
561 */
562static int vhdFreeImage(PVHDIMAGE pImage, bool fDelete)
563{
564 int rc = VINF_SUCCESS;
565
566 /* Freeing a never allocated image (e.g. because the open failed) is
567 * not signalled as an error. After all nothing bad happens. */
568 if (pImage)
569 {
570 if (pImage->pStorage)
571 {
572 /* No point updating the file that is deleted anyway. */
573 if (!fDelete)
574 vhdFlushImage(pImage);
575
576 rc = vdIfIoIntFileClose(pImage->pIfIo, pImage->pStorage);
577 pImage->pStorage = NULL;
578 }
579
580 if (pImage->pszParentFilename)
581 {
582 RTStrFree(pImage->pszParentFilename);
583 pImage->pszParentFilename = NULL;
584 }
585 if (pImage->pBlockAllocationTable)
586 {
587 RTMemFree(pImage->pBlockAllocationTable);
588 pImage->pBlockAllocationTable = NULL;
589 }
590 if (pImage->pu8Bitmap)
591 {
592 RTMemFree(pImage->pu8Bitmap);
593 pImage->pu8Bitmap = NULL;
594 }
595
596 if (fDelete && pImage->pszFilename)
597 {
598 int rc2 = vdIfIoIntFileDelete(pImage->pIfIo, pImage->pszFilename);
599 if (RT_SUCCESS(rc))
600 rc = rc2;
601 }
602 }
603
604 LogFlowFunc(("returns %Rrc\n", rc));
605 return rc;
606}
607
608/* 946684800 is the number of seconds between 1/1/1970 and 1/1/2000 */
609#define VHD_TO_UNIX_EPOCH_SECONDS UINT64_C(946684800)
610
611static uint32_t vhdRtTime2VhdTime(PCRTTIMESPEC pRtTimestamp)
612{
613 uint64_t u64Seconds = RTTimeSpecGetSeconds(pRtTimestamp);
614 return (uint32_t)(u64Seconds - VHD_TO_UNIX_EPOCH_SECONDS);
615}
616
617static void vhdTime2RtTime(PRTTIMESPEC pRtTimestamp, uint32_t u32VhdTimestamp)
618{
619 RTTimeSpecSetSeconds(pRtTimestamp, VHD_TO_UNIX_EPOCH_SECONDS + u32VhdTimestamp);
620}
621
622/**
623 * Internal: Allocates the block bitmap rounding up to the next 32bit or 64bit boundary.
624 * Can be freed with RTMemFree. The memory is zeroed.
625 */
626DECLINLINE(uint8_t *)vhdBlockBitmapAllocate(PVHDIMAGE pImage)
627{
628#ifdef RT_ARCH_AMD64
629 return (uint8_t *)RTMemAllocZ(pImage->cbDataBlockBitmap + 8);
630#else
631 return (uint8_t *)RTMemAllocZ(pImage->cbDataBlockBitmap + 4);
632#endif
633}
634
635/**
636 * Internal: called when the async expansion process completed (failure or success).
637 * Will do the necessary rollback if an error occurred.
638 */
639static int vhdAsyncExpansionComplete(PVHDIMAGE pImage, PVDIOCTX pIoCtx, PVHDIMAGEEXPAND pExpand)
640{
641 int rc = VINF_SUCCESS;
642 uint32_t fFlags = ASMAtomicReadU32(&pExpand->fFlags);
643 bool fIoInProgress = false;
644
645 /* Quick path, check if everything succeeded. */
646 if (fFlags == VHDIMAGEEXPAND_ALL_SUCCESS)
647 {
648 pImage->pBlockAllocationTable[pExpand->idxBatAllocated] = RT_BE2H_U32(pExpand->idxBlockBe);
649 RTMemFree(pExpand);
650 }
651 else
652 {
653 uint32_t uStatus;
654
655 uStatus = VHDIMAGEEXPAND_STATUS_GET(pExpand->fFlags, VHDIMAGEEXPAND_BAT_STATUS_SHIFT);
656 if ( uStatus == VHDIMAGEEXPAND_STEP_FAILED
657 || uStatus == VHDIMAGEEXPAND_STEP_SUCCESS)
658 {
659 /* Undo and restore the old value. */
660 pImage->pBlockAllocationTable[pExpand->idxBatAllocated] = ~0U;
661
662 /* Restore the old value on the disk.
663 * No need for a completion callback because we can't
664 * do anything if this fails. */
665 if (uStatus == VHDIMAGEEXPAND_STEP_SUCCESS)
666 {
667 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
668 pImage->uBlockAllocationTableOffset
669 + pExpand->idxBatAllocated * sizeof(uint32_t),
670 &pImage->pBlockAllocationTable[pExpand->idxBatAllocated],
671 sizeof(uint32_t), pIoCtx, NULL, NULL);
672 fIoInProgress |= rc == VERR_VD_ASYNC_IO_IN_PROGRESS;
673 }
674 }
675
676 /* Restore old size (including the footer because another application might
677 * fill up the free space making it impossible to add the footer)
678 * and add the footer at the right place again. */
679 rc = vdIfIoIntFileSetSize(pImage->pIfIo, pImage->pStorage,
680 pExpand->cbEofOld + sizeof(VHDFooter));
681 AssertRC(rc);
682
683 pImage->uCurrentEndOfFile = pExpand->cbEofOld;
684 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
685 pImage->uCurrentEndOfFile,
686 &pImage->vhdFooterCopy, sizeof(VHDFooter),
687 pIoCtx, NULL, NULL);
688 fIoInProgress |= rc == VERR_VD_ASYNC_IO_IN_PROGRESS;
689 }
690
691 return fIoInProgress ? VERR_VD_ASYNC_IO_IN_PROGRESS : rc;
692}
693
694static int vhdAsyncExpansionStepCompleted(void *pBackendData, PVDIOCTX pIoCtx, void *pvUser, int rcReq, unsigned iStep)
695{
696 PVHDIMAGE pImage = (PVHDIMAGE)pBackendData;
697 PVHDIMAGEEXPAND pExpand = (PVHDIMAGEEXPAND)pvUser;
698
699 LogFlowFunc(("pBackendData=%#p pIoCtx=%#p pvUser=%#p rcReq=%Rrc iStep=%u\n",
700 pBackendData, pIoCtx, pvUser, rcReq, iStep));
701
702 if (RT_SUCCESS(rcReq))
703 VHDIMAGEEXPAND_STATUS_SET(pExpand->fFlags, iStep, VHDIMAGEEXPAND_STEP_SUCCESS);
704 else
705 VHDIMAGEEXPAND_STATUS_SET(pExpand->fFlags, iStep, VHDIMAGEEXPAND_STEP_FAILED);
706
707 if ((pExpand->fFlags & VHDIMAGEEXPAND_ALL_COMPLETE) == VHDIMAGEEXPAND_ALL_COMPLETE)
708 return vhdAsyncExpansionComplete(pImage, pIoCtx, pExpand);
709
710 return VERR_VD_ASYNC_IO_IN_PROGRESS;
711}
712
713static DECLCALLBACK(int) vhdAsyncExpansionDataBlockBitmapComplete(void *pBackendData, PVDIOCTX pIoCtx, void *pvUser, int rcReq)
714{
715 return vhdAsyncExpansionStepCompleted(pBackendData, pIoCtx, pvUser, rcReq, VHDIMAGEEXPAND_BLOCKBITMAP_STATUS_SHIFT);
716}
717
718static DECLCALLBACK(int) vhdAsyncExpansionDataComplete(void *pBackendData, PVDIOCTX pIoCtx, void *pvUser, int rcReq)
719{
720 return vhdAsyncExpansionStepCompleted(pBackendData, pIoCtx, pvUser, rcReq, VHDIMAGEEXPAND_USERBLOCK_STATUS_SHIFT);
721}
722
723static DECLCALLBACK(int) vhdAsyncExpansionBatUpdateComplete(void *pBackendData, PVDIOCTX pIoCtx, void *pvUser, int rcReq)
724{
725 return vhdAsyncExpansionStepCompleted(pBackendData, pIoCtx, pvUser, rcReq, VHDIMAGEEXPAND_BAT_STATUS_SHIFT);
726}
727
728static DECLCALLBACK(int) vhdAsyncExpansionFooterUpdateComplete(void *pBackendData, PVDIOCTX pIoCtx, void *pvUser, int rcReq)
729{
730 return vhdAsyncExpansionStepCompleted(pBackendData, pIoCtx, pvUser, rcReq, VHDIMAGEEXPAND_FOOTER_STATUS_SHIFT);
731}
732
733static int vhdLoadDynamicDisk(PVHDIMAGE pImage, uint64_t uDynamicDiskHeaderOffset)
734{
735 VHDDynamicDiskHeader vhdDynamicDiskHeader;
736 int rc = VINF_SUCCESS;
737 uint32_t *pBlockAllocationTable;
738 uint64_t uBlockAllocationTableOffset;
739 unsigned i = 0;
740
741 Log(("Open a dynamic disk.\n"));
742
743 /*
744 * Read the dynamic disk header.
745 */
746 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage, uDynamicDiskHeaderOffset,
747 &vhdDynamicDiskHeader, sizeof(VHDDynamicDiskHeader));
748 if (memcmp(vhdDynamicDiskHeader.Cookie, VHD_DYNAMIC_DISK_HEADER_COOKIE, VHD_DYNAMIC_DISK_HEADER_COOKIE_SIZE))
749 return VERR_INVALID_PARAMETER;
750
751 pImage->cbDataBlock = RT_BE2H_U32(vhdDynamicDiskHeader.BlockSize);
752 LogFlowFunc(("BlockSize=%u\n", pImage->cbDataBlock));
753 pImage->cBlockAllocationTableEntries = RT_BE2H_U32(vhdDynamicDiskHeader.MaxTableEntries);
754 LogFlowFunc(("MaxTableEntries=%lu\n", pImage->cBlockAllocationTableEntries));
755 AssertMsg(!(pImage->cbDataBlock % VHD_SECTOR_SIZE), ("%s: Data block size is not a multiple of %!\n", __FUNCTION__, VHD_SECTOR_SIZE));
756
757 /*
758 * Bail out if the number of BAT entries exceeds the number of sectors for a maximum image.
759 * Lower the number of sectors in the BAT as a few sectors are already occupied by the footers
760 * and headers.
761 */
762 if (pImage->cBlockAllocationTableEntries > (VHD_MAX_SECTORS - 2))
763 return VERR_VD_VHD_INVALID_HEADER;
764
765 pImage->cSectorsPerDataBlock = pImage->cbDataBlock / VHD_SECTOR_SIZE;
766 LogFlowFunc(("SectorsPerDataBlock=%u\n", pImage->cSectorsPerDataBlock));
767
768 /*
769 * Every block starts with a bitmap indicating which sectors are valid and which are not.
770 * We store the size of it to be able to calculate the real offset.
771 */
772 pImage->cbDataBlockBitmap = pImage->cSectorsPerDataBlock / 8;
773 pImage->cDataBlockBitmapSectors = pImage->cbDataBlockBitmap / VHD_SECTOR_SIZE;
774 /* Round up to full sector size */
775 if (pImage->cbDataBlockBitmap % VHD_SECTOR_SIZE > 0)
776 pImage->cDataBlockBitmapSectors++;
777 LogFlowFunc(("cbDataBlockBitmap=%u\n", pImage->cbDataBlockBitmap));
778 LogFlowFunc(("cDataBlockBitmapSectors=%u\n", pImage->cDataBlockBitmapSectors));
779
780 pImage->pu8Bitmap = vhdBlockBitmapAllocate(pImage);
781 if (!pImage->pu8Bitmap)
782 return VERR_NO_MEMORY;
783
784 pBlockAllocationTable = (uint32_t *)RTMemAllocZ(pImage->cBlockAllocationTableEntries * sizeof(uint32_t));
785 if (!pBlockAllocationTable)
786 return VERR_NO_MEMORY;
787
788 /*
789 * Read the table.
790 */
791 uBlockAllocationTableOffset = RT_BE2H_U64(vhdDynamicDiskHeader.TableOffset);
792 LogFlowFunc(("uBlockAllocationTableOffset=%llu\n", uBlockAllocationTableOffset));
793 pImage->uBlockAllocationTableOffset = uBlockAllocationTableOffset;
794 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage,
795 uBlockAllocationTableOffset, pBlockAllocationTable,
796 pImage->cBlockAllocationTableEntries * sizeof(uint32_t));
797 if (RT_FAILURE(rc))
798 {
799 RTMemFree(pBlockAllocationTable);
800 return rc;
801 }
802
803 /*
804 * Because the offset entries inside the allocation table are stored big endian
805 * we need to convert them into host endian.
806 */
807 pImage->pBlockAllocationTable = (uint32_t *)RTMemAllocZ(pImage->cBlockAllocationTableEntries * sizeof(uint32_t));
808 if (!pImage->pBlockAllocationTable)
809 {
810 RTMemFree(pBlockAllocationTable);
811 return VERR_NO_MEMORY;
812 }
813
814 for (i = 0; i < pImage->cBlockAllocationTableEntries; i++)
815 pImage->pBlockAllocationTable[i] = RT_BE2H_U32(pBlockAllocationTable[i]);
816
817 RTMemFree(pBlockAllocationTable);
818
819 if (pImage->uImageFlags & VD_IMAGE_FLAGS_DIFF)
820 memcpy(pImage->ParentUuid.au8, vhdDynamicDiskHeader.ParentUuid, sizeof(pImage->ParentUuid));
821
822 return rc;
823}
824
825static int vhdOpenImage(PVHDIMAGE pImage, unsigned uOpenFlags)
826{
827 uint64_t FileSize;
828 VHDFooter vhdFooter;
829
830 pImage->uOpenFlags = uOpenFlags;
831
832 pImage->pIfError = VDIfErrorGet(pImage->pVDIfsDisk);
833 pImage->pIfIo = VDIfIoIntGet(pImage->pVDIfsImage);
834 AssertPtrReturn(pImage->pIfIo, VERR_INVALID_PARAMETER);
835
836 /*
837 * Open the image.
838 */
839 int rc = vdIfIoIntFileOpen(pImage->pIfIo, pImage->pszFilename,
840 VDOpenFlagsToFileOpenFlags(uOpenFlags,
841 false /* fCreate */),
842 &pImage->pStorage);
843 if (RT_FAILURE(rc))
844 {
845 /* Do NOT signal an appropriate error here, as the VD layer has the
846 * choice of retrying the open if it failed. */
847 return rc;
848 }
849
850 rc = vdIfIoIntFileGetSize(pImage->pIfIo, pImage->pStorage, &FileSize);
851 pImage->uCurrentEndOfFile = FileSize - sizeof(VHDFooter);
852
853 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage, pImage->uCurrentEndOfFile,
854 &vhdFooter, sizeof(VHDFooter));
855 if (RT_SUCCESS(rc))
856 {
857 if (memcmp(vhdFooter.Cookie, VHD_FOOTER_COOKIE, VHD_FOOTER_COOKIE_SIZE) != 0)
858 {
859 /*
860 * There is also a backup header at the beginning in case the image got corrupted.
861 * Such corrupted images are detected here to let the open handler repair it later.
862 */
863 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage, 0,
864 &vhdFooter, sizeof(VHDFooter));
865 if (RT_SUCCESS(rc))
866 {
867 if (memcmp(vhdFooter.Cookie, VHD_FOOTER_COOKIE, VHD_FOOTER_COOKIE_SIZE) != 0)
868 rc = VERR_VD_VHD_INVALID_HEADER;
869 else
870 rc = VERR_VD_IMAGE_CORRUPTED;
871 }
872 }
873 }
874
875 if (RT_FAILURE(rc))
876 {
877 vhdFreeImage(pImage, false);
878 return rc;
879 }
880
881 switch (RT_BE2H_U32(vhdFooter.DiskType))
882 {
883 case VHD_FOOTER_DISK_TYPE_FIXED:
884 pImage->uImageFlags |= VD_IMAGE_FLAGS_FIXED;
885 break;
886 case VHD_FOOTER_DISK_TYPE_DYNAMIC:
887 pImage->uImageFlags &= ~VD_IMAGE_FLAGS_FIXED;
888 break;
889 case VHD_FOOTER_DISK_TYPE_DIFFERENCING:
890 pImage->uImageFlags |= VD_IMAGE_FLAGS_DIFF;
891 pImage->uImageFlags &= ~VD_IMAGE_FLAGS_FIXED;
892 break;
893 default:
894 return VERR_NOT_IMPLEMENTED;
895 }
896
897 pImage->cbSize = RT_BE2H_U64(vhdFooter.CurSize);
898 pImage->LCHSGeometry.cCylinders = 0;
899 pImage->LCHSGeometry.cHeads = 0;
900 pImage->LCHSGeometry.cSectors = 0;
901 pImage->PCHSGeometry.cCylinders = RT_BE2H_U16(vhdFooter.DiskGeometryCylinder);
902 pImage->PCHSGeometry.cHeads = vhdFooter.DiskGeometryHeads;
903 pImage->PCHSGeometry.cSectors = vhdFooter.DiskGeometrySectors;
904
905 /*
906 * Copy of the disk footer.
907 * If we allocate new blocks in differencing disks on write access
908 * the footer is overwritten. We need to write it at the end of the file.
909 */
910 memcpy(&pImage->vhdFooterCopy, &vhdFooter, sizeof(VHDFooter));
911
912 /*
913 * Is there a better way?
914 */
915 memcpy(&pImage->ImageUuid, &vhdFooter.UniqueID, 16);
916
917 pImage->u64DataOffset = RT_BE2H_U64(vhdFooter.DataOffset);
918 LogFlowFunc(("DataOffset=%llu\n", pImage->u64DataOffset));
919
920 if (!(pImage->uImageFlags & VD_IMAGE_FLAGS_FIXED))
921 rc = vhdLoadDynamicDisk(pImage, pImage->u64DataOffset);
922
923 if (RT_SUCCESS(rc))
924 {
925 PVDREGIONDESC pRegion = &pImage->RegionList.aRegions[0];
926 pImage->RegionList.fFlags = 0;
927 pImage->RegionList.cRegions = 1;
928
929 pRegion->offRegion = 0; /* Disk start. */
930 pRegion->cbBlock = 512;
931 pRegion->enmDataForm = VDREGIONDATAFORM_RAW;
932 pRegion->enmMetadataForm = VDREGIONMETADATAFORM_NONE;
933 pRegion->cbData = 512;
934 pRegion->cbMetadata = 0;
935 pRegion->cRegionBlocksOrBytes = pImage->cbSize;
936 }
937 else
938 vhdFreeImage(pImage, false);
939 return rc;
940}
941
942/**
943 * Internal: Checks if a sector in the block bitmap is set
944 */
945DECLINLINE(bool) vhdBlockBitmapSectorContainsData(PVHDIMAGE pImage, uint32_t cBlockBitmapEntry)
946{
947 uint32_t iBitmap = (cBlockBitmapEntry / 8); /* Byte in the block bitmap. */
948
949 /*
950 * The index of the bit in the byte of the data block bitmap.
951 * The most significant bit stands for a lower sector number.
952 */
953 uint8_t iBitInByte = (8-1) - (cBlockBitmapEntry % 8);
954 uint8_t *puBitmap = pImage->pu8Bitmap + iBitmap;
955
956 AssertMsg(puBitmap < (pImage->pu8Bitmap + pImage->cbDataBlockBitmap),
957 ("VHD: Current bitmap position exceeds maximum size of the bitmap\n"));
958
959 return ((*puBitmap) & RT_BIT(iBitInByte)) != 0;
960}
961
962/**
963 * Internal: Sets the given sector in the sector bitmap.
964 */
965DECLINLINE(bool) vhdBlockBitmapSectorSet(PVHDIMAGE pImage, uint8_t *pu8Bitmap, uint32_t cBlockBitmapEntry)
966{
967 RT_NOREF1(pImage);
968 uint32_t iBitmap = (cBlockBitmapEntry / 8); /* Byte in the block bitmap. */
969
970 /*
971 * The index of the bit in the byte of the data block bitmap.
972 * The most significant bit stands for a lower sector number.
973 */
974 uint8_t iBitInByte = (8-1) - (cBlockBitmapEntry % 8);
975 uint8_t *puBitmap = pu8Bitmap + iBitmap;
976
977 AssertMsg(puBitmap < (pu8Bitmap + pImage->cbDataBlockBitmap),
978 ("VHD: Current bitmap position exceeds maximum size of the bitmap\n"));
979
980 bool fClear = ((*puBitmap) & RT_BIT(iBitInByte)) == 0;
981 *puBitmap |= RT_BIT(iBitInByte);
982 return fClear;
983}
984
985/**
986 * Internal: Derive drive geometry from its size.
987 */
988static void vhdSetDiskGeometry(PVHDIMAGE pImage, uint64_t cbSize)
989{
990 uint64_t u64TotalSectors = cbSize / VHD_SECTOR_SIZE;
991 uint32_t u32CylinderTimesHeads, u32Heads, u32SectorsPerTrack;
992
993 if (u64TotalSectors > 65535 * 16 * 255)
994 {
995 /* ATA disks limited to 127 GB. */
996 u64TotalSectors = 65535 * 16 * 255;
997 }
998
999 if (u64TotalSectors >= 65535 * 16 * 63)
1000 {
1001 u32SectorsPerTrack = 255;
1002 u32Heads = 16;
1003 u32CylinderTimesHeads = u64TotalSectors / u32SectorsPerTrack;
1004 }
1005 else
1006 {
1007 u32SectorsPerTrack = 17;
1008 u32CylinderTimesHeads = u64TotalSectors / u32SectorsPerTrack;
1009
1010 u32Heads = (u32CylinderTimesHeads + 1023) / 1024;
1011
1012 if (u32Heads < 4)
1013 {
1014 u32Heads = 4;
1015 }
1016 if (u32CylinderTimesHeads >= (u32Heads * 1024) || u32Heads > 16)
1017 {
1018 u32SectorsPerTrack = 31;
1019 u32Heads = 16;
1020 u32CylinderTimesHeads = u64TotalSectors / u32SectorsPerTrack;
1021 }
1022 if (u32CylinderTimesHeads >= (u32Heads * 1024))
1023 {
1024 u32SectorsPerTrack = 63;
1025 u32Heads = 16;
1026 u32CylinderTimesHeads = u64TotalSectors / u32SectorsPerTrack;
1027 }
1028 }
1029 pImage->PCHSGeometry.cCylinders = u32CylinderTimesHeads / u32Heads;
1030 pImage->PCHSGeometry.cHeads = u32Heads;
1031 pImage->PCHSGeometry.cSectors = u32SectorsPerTrack;
1032 pImage->LCHSGeometry.cCylinders = 0;
1033 pImage->LCHSGeometry.cHeads = 0;
1034 pImage->LCHSGeometry.cSectors = 0;
1035}
1036
1037
1038static uint32_t vhdAllocateParentLocators(PVHDIMAGE pImage, VHDDynamicDiskHeader *pDDH, uint64_t u64Offset)
1039{
1040 RT_NOREF1(pImage);
1041 PVHDPLE pLocator = pDDH->ParentLocatorEntry;
1042
1043 /*
1044 * The VHD spec states that the DataSpace field holds the number of sectors
1045 * required to store the parent locator path.
1046 * As it turned out VPC and Hyper-V store the amount of bytes reserved for the
1047 * path and not the number of sectors.
1048 */
1049
1050 /* Unicode absolute Windows path. */
1051 pLocator->u32Code = RT_H2BE_U32(VHD_PLATFORM_CODE_W2KU);
1052 pLocator->u32DataSpace = RT_H2BE_U32(VHD_ABSOLUTE_MAX_PATH * sizeof(RTUTF16));
1053 pLocator->u64DataOffset = RT_H2BE_U64(u64Offset);
1054 pLocator++;
1055 u64Offset += VHD_ABSOLUTE_MAX_PATH * sizeof(RTUTF16);
1056 /* Unicode relative Windows path. */
1057 pLocator->u32Code = RT_H2BE_U32(VHD_PLATFORM_CODE_W2RU);
1058 pLocator->u32DataSpace = RT_H2BE_U32(VHD_RELATIVE_MAX_PATH * sizeof(RTUTF16));
1059 pLocator->u64DataOffset = RT_H2BE_U64(u64Offset);
1060 u64Offset += VHD_RELATIVE_MAX_PATH * sizeof(RTUTF16);
1061 return u64Offset;
1062}
1063
1064/**
1065 * Internal: Additional code for dynamic VHD image creation.
1066 */
1067static int vhdCreateDynamicImage(PVHDIMAGE pImage, uint64_t cbSize)
1068{
1069 int rc;
1070 VHDDynamicDiskHeader DynamicDiskHeader;
1071 uint32_t u32BlockAllocationTableSectors;
1072 void *pvTmp = NULL;
1073
1074 memset(&DynamicDiskHeader, 0, sizeof(DynamicDiskHeader));
1075
1076 pImage->u64DataOffset = sizeof(VHDFooter);
1077 pImage->cbDataBlock = VHD_BLOCK_SIZE; /* 2 MB */
1078 pImage->cSectorsPerDataBlock = pImage->cbDataBlock / VHD_SECTOR_SIZE;
1079 pImage->cbDataBlockBitmap = pImage->cSectorsPerDataBlock / 8;
1080 pImage->cDataBlockBitmapSectors = pImage->cbDataBlockBitmap / VHD_SECTOR_SIZE;
1081 /* Align to sector boundary */
1082 if (pImage->cbDataBlockBitmap % VHD_SECTOR_SIZE > 0)
1083 pImage->cDataBlockBitmapSectors++;
1084 pImage->pu8Bitmap = vhdBlockBitmapAllocate(pImage);
1085 if (!pImage->pu8Bitmap)
1086 return vdIfError(pImage->pIfError, VERR_NO_MEMORY, RT_SRC_POS, N_("VHD: cannot allocate memory for bitmap storage"));
1087
1088 /* Initialize BAT. */
1089 pImage->uBlockAllocationTableOffset = (uint64_t)sizeof(VHDFooter) + sizeof(VHDDynamicDiskHeader);
1090 pImage->cBlockAllocationTableEntries = (uint32_t)((cbSize + pImage->cbDataBlock - 1) / pImage->cbDataBlock); /* Align table to the block size. */
1091 u32BlockAllocationTableSectors = (pImage->cBlockAllocationTableEntries * sizeof(uint32_t) + VHD_SECTOR_SIZE - 1) / VHD_SECTOR_SIZE;
1092 pImage->pBlockAllocationTable = (uint32_t *)RTMemAllocZ(pImage->cBlockAllocationTableEntries * sizeof(uint32_t));
1093 if (!pImage->pBlockAllocationTable)
1094 return vdIfError(pImage->pIfError, VERR_NO_MEMORY, RT_SRC_POS, N_("VHD: cannot allocate memory for BAT"));
1095
1096 for (unsigned i = 0; i < pImage->cBlockAllocationTableEntries; i++)
1097 {
1098 pImage->pBlockAllocationTable[i] = 0xFFFFFFFF; /* It is actually big endian. */
1099 }
1100
1101 /* Round up to the sector size. */
1102 if (pImage->uImageFlags & VD_IMAGE_FLAGS_DIFF) /* fix hyper-v unreadable error */
1103 pImage->uCurrentEndOfFile = vhdAllocateParentLocators(pImage, &DynamicDiskHeader,
1104 pImage->uBlockAllocationTableOffset + u32BlockAllocationTableSectors * VHD_SECTOR_SIZE);
1105 else
1106 pImage->uCurrentEndOfFile = pImage->uBlockAllocationTableOffset + u32BlockAllocationTableSectors * VHD_SECTOR_SIZE;
1107
1108 /* Set dynamic image size. */
1109 pvTmp = RTMemTmpAllocZ(pImage->uCurrentEndOfFile + sizeof(VHDFooter));
1110 if (!pvTmp)
1111 return vdIfError(pImage->pIfError, VERR_NO_MEMORY, RT_SRC_POS, N_("VHD: cannot set the file size for '%s'"), pImage->pszFilename);
1112
1113 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage, 0, pvTmp,
1114 pImage->uCurrentEndOfFile + sizeof(VHDFooter));
1115 if (RT_FAILURE(rc))
1116 {
1117 RTMemTmpFree(pvTmp);
1118 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VHD: cannot set the file size for '%s'"), pImage->pszFilename);
1119 }
1120
1121 RTMemTmpFree(pvTmp);
1122
1123 /* Initialize and write the dynamic disk header. */
1124 memcpy(DynamicDiskHeader.Cookie, VHD_DYNAMIC_DISK_HEADER_COOKIE, sizeof(DynamicDiskHeader.Cookie));
1125 DynamicDiskHeader.DataOffset = UINT64_C(0xFFFFFFFFFFFFFFFF); /* Initially the disk has no data. */
1126 DynamicDiskHeader.TableOffset = RT_H2BE_U64(pImage->uBlockAllocationTableOffset);
1127 DynamicDiskHeader.HeaderVersion = RT_H2BE_U32(VHD_DYNAMIC_DISK_HEADER_VERSION);
1128 DynamicDiskHeader.BlockSize = RT_H2BE_U32(pImage->cbDataBlock);
1129 DynamicDiskHeader.MaxTableEntries = RT_H2BE_U32(pImage->cBlockAllocationTableEntries);
1130 /* Compute and update checksum. */
1131 DynamicDiskHeader.Checksum = 0;
1132 DynamicDiskHeader.Checksum = RT_H2BE_U32(vhdChecksum(&DynamicDiskHeader, sizeof(DynamicDiskHeader)));
1133
1134 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage, sizeof(VHDFooter),
1135 &DynamicDiskHeader, sizeof(DynamicDiskHeader));
1136 if (RT_FAILURE(rc))
1137 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VHD: cannot write dynamic disk header to image '%s'"), pImage->pszFilename);
1138
1139 /* Write BAT. */
1140 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage, pImage->uBlockAllocationTableOffset,
1141 pImage->pBlockAllocationTable,
1142 pImage->cBlockAllocationTableEntries * sizeof(uint32_t));
1143 if (RT_FAILURE(rc))
1144 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VHD: cannot write BAT to image '%s'"), pImage->pszFilename);
1145
1146 return rc;
1147}
1148
1149/**
1150 * Internal: The actual code for VHD image creation, both fixed and dynamic.
1151 */
1152static int vhdCreateImage(PVHDIMAGE pImage, uint64_t cbSize,
1153 unsigned uImageFlags, const char *pszComment,
1154 PCVDGEOMETRY pPCHSGeometry,
1155 PCVDGEOMETRY pLCHSGeometry, PCRTUUID pUuid,
1156 unsigned uOpenFlags,
1157 PVDINTERFACEPROGRESS pIfProgress,
1158 unsigned uPercentStart, unsigned uPercentSpan)
1159{
1160 RT_NOREF3(pszComment, pPCHSGeometry, pLCHSGeometry);
1161 VHDFooter Footer;
1162 RTTIMESPEC now;
1163
1164 pImage->uOpenFlags = uOpenFlags;
1165 pImage->uImageFlags = uImageFlags;
1166 pImage->pIfError = VDIfErrorGet(pImage->pVDIfsDisk);
1167
1168 int rc = vdIfIoIntFileOpen(pImage->pIfIo, pImage->pszFilename,
1169 VDOpenFlagsToFileOpenFlags(uOpenFlags & ~VD_OPEN_FLAGS_READONLY,
1170 true /* fCreate */),
1171 &pImage->pStorage);
1172 if (RT_SUCCESS(rc))
1173 {
1174 pImage->cbSize = cbSize;
1175 pImage->ImageUuid = *pUuid;
1176 RTUuidClear(&pImage->ParentUuid);
1177 vhdSetDiskGeometry(pImage, cbSize);
1178
1179 /* Initialize the footer. */
1180 memset(&Footer, 0, sizeof(Footer));
1181 memcpy(Footer.Cookie, VHD_FOOTER_COOKIE, sizeof(Footer.Cookie));
1182 Footer.Features = RT_H2BE_U32(0x2);
1183 Footer.Version = RT_H2BE_U32(VHD_FOOTER_FILE_FORMAT_VERSION);
1184 Footer.Timestamp = RT_H2BE_U32(vhdRtTime2VhdTime(RTTimeNow(&now)));
1185 memcpy(Footer.CreatorApp, "vbox", sizeof(Footer.CreatorApp));
1186 Footer.CreatorVer = RT_H2BE_U32(VBOX_VERSION);
1187#ifdef RT_OS_DARWIN
1188 Footer.CreatorOS = RT_H2BE_U32(0x4D616320); /* "Mac " */
1189#else /* Virtual PC supports only two platforms atm, so everything else will be Wi2k. */
1190 Footer.CreatorOS = RT_H2BE_U32(0x5769326B); /* "Wi2k" */
1191#endif
1192 Footer.OrigSize = RT_H2BE_U64(cbSize);
1193 Footer.CurSize = Footer.OrigSize;
1194 Footer.DiskGeometryCylinder = RT_H2BE_U16(pImage->PCHSGeometry.cCylinders);
1195 Footer.DiskGeometryHeads = pImage->PCHSGeometry.cHeads;
1196 Footer.DiskGeometrySectors = pImage->PCHSGeometry.cSectors;
1197 memcpy(Footer.UniqueID, pImage->ImageUuid.au8, sizeof(Footer.UniqueID));
1198 Footer.SavedState = 0;
1199
1200 if (uImageFlags & VD_IMAGE_FLAGS_FIXED)
1201 {
1202 Footer.DiskType = RT_H2BE_U32(VHD_FOOTER_DISK_TYPE_FIXED);
1203 /*
1204 * Initialize fixed image.
1205 * "The size of the entire file is the size of the hard disk in
1206 * the guest operating system plus the size of the footer."
1207 */
1208 pImage->u64DataOffset = VHD_FOOTER_DATA_OFFSET_FIXED;
1209 pImage->uCurrentEndOfFile = cbSize;
1210 rc = vdIfIoIntFileSetAllocationSize(pImage->pIfIo, pImage->pStorage, pImage->uCurrentEndOfFile + sizeof(VHDFooter),
1211 0 /* fFlags */, pIfProgress,
1212 uPercentStart, uPercentSpan);
1213 if (RT_FAILURE(rc))
1214 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VHD: cannot set the file size for '%s'"), pImage->pszFilename);
1215 }
1216 else
1217 {
1218 /*
1219 * Initialize dynamic image.
1220 *
1221 * The overall structure of dynamic disk is:
1222 *
1223 * [Copy of hard disk footer (512 bytes)]
1224 * [Dynamic disk header (1024 bytes)]
1225 * [BAT (Block Allocation Table)]
1226 * [Parent Locators]
1227 * [Data block 1]
1228 * [Data block 2]
1229 * ...
1230 * [Data block N]
1231 * [Hard disk footer (512 bytes)]
1232 */
1233 Footer.DiskType = (uImageFlags & VD_IMAGE_FLAGS_DIFF)
1234 ? RT_H2BE_U32(VHD_FOOTER_DISK_TYPE_DIFFERENCING)
1235 : RT_H2BE_U32(VHD_FOOTER_DISK_TYPE_DYNAMIC);
1236 /* We are half way thorough with creation of image, let the caller know. */
1237 vdIfProgress(pIfProgress, (uPercentStart + uPercentSpan) / 2);
1238
1239 rc = vhdCreateDynamicImage(pImage, cbSize);
1240 }
1241
1242 if (RT_SUCCESS(rc))
1243 {
1244 /* Compute and update the footer checksum. */
1245 Footer.DataOffset = RT_H2BE_U64(pImage->u64DataOffset);
1246 Footer.Checksum = 0;
1247 Footer.Checksum = RT_H2BE_U32(vhdChecksum(&Footer, sizeof(Footer)));
1248
1249 pImage->vhdFooterCopy = Footer;
1250
1251 /* Store the footer */
1252 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage, pImage->uCurrentEndOfFile,
1253 &Footer, sizeof(Footer));
1254 if (RT_SUCCESS(rc))
1255 {
1256 /* Dynamic images contain a copy of the footer at the very beginning of the file. */
1257 if (!(uImageFlags & VD_IMAGE_FLAGS_FIXED))
1258 {
1259 /* Write the copy of the footer. */
1260 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage, 0, &Footer, sizeof(Footer));
1261 if (RT_FAILURE(rc))
1262 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VHD: cannot write a copy of footer to image '%s'"), pImage->pszFilename);
1263 }
1264 }
1265 else
1266 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VHD: cannot write footer to image '%s'"), pImage->pszFilename);
1267 }
1268 }
1269 else
1270 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VHD: cannot create image '%s'"), pImage->pszFilename);
1271
1272 if (RT_SUCCESS(rc))
1273 vdIfProgress(pIfProgress, uPercentStart + uPercentSpan);
1274
1275 if (RT_SUCCESS(rc))
1276 {
1277 PVDREGIONDESC pRegion = &pImage->RegionList.aRegions[0];
1278 pImage->RegionList.fFlags = 0;
1279 pImage->RegionList.cRegions = 1;
1280
1281 pRegion->offRegion = 0; /* Disk start. */
1282 pRegion->cbBlock = 512;
1283 pRegion->enmDataForm = VDREGIONDATAFORM_RAW;
1284 pRegion->enmMetadataForm = VDREGIONMETADATAFORM_NONE;
1285 pRegion->cbData = 512;
1286 pRegion->cbMetadata = 0;
1287 pRegion->cRegionBlocksOrBytes = pImage->cbSize;
1288 }
1289 else
1290 vhdFreeImage(pImage, rc != VERR_ALREADY_EXISTS);
1291 return rc;
1292}
1293
1294
1295/** @interface_method_impl{VDIMAGEBACKEND,pfnProbe} */
1296static DECLCALLBACK(int) vhdProbe(const char *pszFilename, PVDINTERFACE pVDIfsDisk,
1297 PVDINTERFACE pVDIfsImage, VDTYPE *penmType)
1298{
1299 RT_NOREF1(pVDIfsDisk);
1300 LogFlowFunc(("pszFilename=\"%s\" pVDIfsDisk=%#p pVDIfsImage=%#p\n", pszFilename, pVDIfsDisk, pVDIfsImage));
1301 PVDIOSTORAGE pStorage;
1302 PVDINTERFACEIOINT pIfIo = VDIfIoIntGet(pVDIfsImage);
1303 AssertPtrReturn(pIfIo, VERR_INVALID_PARAMETER);
1304
1305 int rc = vdIfIoIntFileOpen(pIfIo, pszFilename,
1306 VDOpenFlagsToFileOpenFlags(VD_OPEN_FLAGS_READONLY,
1307 false /* fCreate */),
1308 &pStorage);
1309 if (RT_SUCCESS(rc))
1310 {
1311 uint64_t cbFile;
1312
1313 rc = vdIfIoIntFileGetSize(pIfIo, pStorage, &cbFile);
1314 if ( RT_SUCCESS(rc)
1315 && cbFile >= sizeof(VHDFooter))
1316 {
1317 VHDFooter vhdFooter;
1318
1319 rc = vdIfIoIntFileReadSync(pIfIo, pStorage, cbFile - sizeof(VHDFooter),
1320 &vhdFooter, sizeof(VHDFooter));
1321 if (RT_SUCCESS(rc))
1322 {
1323 if (memcmp(vhdFooter.Cookie, VHD_FOOTER_COOKIE, VHD_FOOTER_COOKIE_SIZE) != 0)
1324 {
1325 /*
1326 * There is also a backup header at the beginning in case the image got corrupted.
1327 * Such corrupted images are detected here to let the open handler repair it later.
1328 */
1329 rc = vdIfIoIntFileReadSync(pIfIo, pStorage, 0, &vhdFooter, sizeof(VHDFooter));
1330 if ( RT_FAILURE(rc)
1331 || (memcmp(vhdFooter.Cookie, VHD_FOOTER_COOKIE, VHD_FOOTER_COOKIE_SIZE) != 0))
1332 rc = VERR_VD_VHD_INVALID_HEADER;
1333 }
1334
1335 if (RT_SUCCESS(rc))
1336 *penmType = VDTYPE_HDD;
1337 }
1338 else
1339 rc = VERR_VD_VHD_INVALID_HEADER;
1340 }
1341 else if (RT_SUCCESS(rc))
1342 rc = VERR_VD_VHD_INVALID_HEADER;
1343
1344 vdIfIoIntFileClose(pIfIo, pStorage);
1345 }
1346
1347 LogFlowFunc(("returns %Rrc\n", rc));
1348 return rc;
1349}
1350
1351/** @interface_method_impl{VDIMAGEBACKEND,pfnOpen} */
1352static DECLCALLBACK(int) vhdOpen(const char *pszFilename, unsigned uOpenFlags,
1353 PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
1354 VDTYPE enmType, void **ppBackendData)
1355{
1356 RT_NOREF1(enmType); /**< @todo r=klaus make use of the type info. */
1357
1358 LogFlowFunc(("pszFilename=\"%s\" uOpenFlags=%#x pVDIfsDisk=%#p pVDIfsImage=%#p enmType=%u ppBackendData=%#p\n",
1359 pszFilename, uOpenFlags, pVDIfsDisk, pVDIfsImage, enmType, ppBackendData));
1360 int rc = VINF_SUCCESS;
1361
1362 /* Check open flags. All valid flags are supported. */
1363 AssertReturn(!(uOpenFlags & ~VD_OPEN_FLAGS_MASK), VERR_INVALID_PARAMETER);
1364 AssertReturn((VALID_PTR(pszFilename) && *pszFilename), VERR_INVALID_PARAMETER);
1365
1366 PVHDIMAGE pImage = (PVHDIMAGE)RTMemAllocZ(RT_UOFFSETOF(VHDIMAGE, RegionList.aRegions[1]));
1367 if (RT_LIKELY(pImage))
1368 {
1369 pImage->pszFilename = pszFilename;
1370 pImage->pStorage = NULL;
1371 pImage->pVDIfsDisk = pVDIfsDisk;
1372 pImage->pVDIfsImage = pVDIfsImage;
1373
1374 rc = vhdOpenImage(pImage, uOpenFlags);
1375 if (RT_SUCCESS(rc))
1376 *ppBackendData = pImage;
1377 else
1378 RTMemFree(pImage);
1379 }
1380 else
1381 rc = VERR_NO_MEMORY;
1382
1383 LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
1384 return rc;
1385}
1386
1387/** @interface_method_impl{VDIMAGEBACKEND,pfnCreate} */
1388static DECLCALLBACK(int) vhdCreate(const char *pszFilename, uint64_t cbSize,
1389 unsigned uImageFlags, const char *pszComment,
1390 PCVDGEOMETRY pPCHSGeometry, PCVDGEOMETRY pLCHSGeometry,
1391 PCRTUUID pUuid, unsigned uOpenFlags,
1392 unsigned uPercentStart, unsigned uPercentSpan,
1393 PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
1394 PVDINTERFACE pVDIfsOperation, VDTYPE enmType,
1395 void **ppBackendData)
1396{
1397 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 enmType=%u ppBackendData=%#p",
1398 pszFilename, cbSize, uImageFlags, pszComment, pPCHSGeometry, pLCHSGeometry, pUuid, uOpenFlags, uPercentStart, uPercentSpan, pVDIfsDisk, pVDIfsImage, pVDIfsOperation, enmType, ppBackendData));
1399 int rc;
1400 PVDINTERFACEPROGRESS pIfProgress = VDIfProgressGet(pVDIfsOperation);
1401
1402 /* Check the VD container type. */
1403 if (enmType != VDTYPE_HDD)
1404 return VERR_VD_INVALID_TYPE;
1405
1406 /* Check open flags. All valid flags are supported. */
1407 AssertReturn(!(uOpenFlags & ~VD_OPEN_FLAGS_MASK), VERR_INVALID_PARAMETER);
1408 AssertReturn( VALID_PTR(pszFilename)
1409 && *pszFilename
1410 && VALID_PTR(pPCHSGeometry)
1411 && VALID_PTR(pLCHSGeometry), VERR_INVALID_PARAMETER);
1412 /** @todo Check the values of other params */
1413
1414 PVHDIMAGE pImage = (PVHDIMAGE)RTMemAllocZ(RT_UOFFSETOF(VHDIMAGE, RegionList.aRegions[1]));
1415 if (RT_LIKELY(pImage))
1416 {
1417 pImage->pszFilename = pszFilename;
1418 pImage->pStorage = NULL;
1419 pImage->pVDIfsDisk = pVDIfsDisk;
1420 pImage->pVDIfsImage = pVDIfsImage;
1421
1422 /* Get I/O interface. */
1423 pImage->pIfIo = VDIfIoIntGet(pImage->pVDIfsImage);
1424 if (RT_LIKELY(VALID_PTR(pImage->pIfIo)))
1425 {
1426 rc = vhdCreateImage(pImage, cbSize, uImageFlags, pszComment,
1427 pPCHSGeometry, pLCHSGeometry, pUuid, uOpenFlags,
1428 pIfProgress, uPercentStart, uPercentSpan);
1429 if (RT_SUCCESS(rc))
1430 {
1431 /* So far the image is opened in read/write mode. Make sure the
1432 * image is opened in read-only mode if the caller requested that. */
1433 if (uOpenFlags & VD_OPEN_FLAGS_READONLY)
1434 {
1435 vhdFreeImage(pImage, false);
1436 rc = vhdOpenImage(pImage, uOpenFlags);
1437 }
1438
1439 if (RT_SUCCESS(rc))
1440 *ppBackendData = pImage;
1441 }
1442 }
1443 else
1444 rc = VERR_INVALID_PARAMETER;
1445
1446 if (RT_FAILURE(rc))
1447 RTMemFree(pImage);
1448 }
1449 else
1450 rc = VERR_NO_MEMORY;
1451
1452 LogFlowFunc(("returns %Rrc\n", rc));
1453 return rc;
1454}
1455
1456/** @interface_method_impl{VDIMAGEBACKEND,pfnRename} */
1457static DECLCALLBACK(int) vhdRename(void *pBackendData, const char *pszFilename)
1458{
1459 LogFlowFunc(("pBackendData=%#p pszFilename=%#p\n", pBackendData, pszFilename));
1460 int rc = VINF_SUCCESS;
1461 PVHDIMAGE pImage = (PVHDIMAGE)pBackendData;
1462
1463 /* Check arguments. */
1464 AssertReturn((pImage && pszFilename && *pszFilename), VERR_INVALID_PARAMETER);
1465
1466 /* Close the image. */
1467 rc = vhdFreeImage(pImage, false);
1468 if (RT_SUCCESS(rc))
1469 {
1470 /* Rename the file. */
1471 rc = vdIfIoIntFileMove(pImage->pIfIo, pImage->pszFilename, pszFilename, 0);
1472 if (RT_SUCCESS(rc))
1473 {
1474 /* Update pImage with the new information. */
1475 pImage->pszFilename = pszFilename;
1476
1477 /* Open the old file with new name. */
1478 rc = vhdOpenImage(pImage, pImage->uOpenFlags);
1479 }
1480 else
1481 {
1482 /* The move failed, try to reopen the original image. */
1483 int rc2 = vhdOpenImage(pImage, pImage->uOpenFlags);
1484 if (RT_FAILURE(rc2))
1485 rc = rc2;
1486 }
1487 }
1488
1489 LogFlowFunc(("returns %Rrc\n", rc));
1490 return rc;
1491}
1492
1493/** @interface_method_impl{VDIMAGEBACKEND,pfnClose} */
1494static DECLCALLBACK(int) vhdClose(void *pBackendData, bool fDelete)
1495{
1496 LogFlowFunc(("pBackendData=%#p fDelete=%d\n", pBackendData, fDelete));
1497 PVHDIMAGE pImage = (PVHDIMAGE)pBackendData;
1498
1499 int rc = vhdFreeImage(pImage, fDelete);
1500 RTMemFree(pImage);
1501
1502 LogFlowFunc(("returns %Rrc\n", rc));
1503 return rc;
1504}
1505
1506/** @interface_method_impl{VDIMAGEBACKEND,pfnRead} */
1507static DECLCALLBACK(int) vhdRead(void *pBackendData, uint64_t uOffset, size_t cbToRead,
1508 PVDIOCTX pIoCtx, size_t *pcbActuallyRead)
1509{
1510 PVHDIMAGE pImage = (PVHDIMAGE)pBackendData;
1511 int rc = VINF_SUCCESS;
1512
1513 LogFlowFunc(("pBackendData=%p uOffset=%#llx pIoCtx=%#p cbToRead=%u pcbActuallyRead=%p\n",
1514 pBackendData, uOffset, pIoCtx, cbToRead, pcbActuallyRead));
1515
1516 AssertPtr(pImage);
1517 Assert(uOffset % 512 == 0);
1518 Assert(cbToRead % 512 == 0);
1519 AssertReturn((VALID_PTR(pIoCtx) && cbToRead), VERR_INVALID_PARAMETER);
1520 AssertReturn(uOffset + cbToRead <= pImage->cbSize, VERR_INVALID_PARAMETER);
1521
1522 /*
1523 * If we have a dynamic disk image, we need to find the data block and sector to read.
1524 */
1525 if (pImage->pBlockAllocationTable)
1526 {
1527 /*
1528 * Get the data block first.
1529 */
1530 uint32_t cBlockAllocationTableEntry = (uOffset / VHD_SECTOR_SIZE) / pImage->cSectorsPerDataBlock;
1531 uint32_t cBATEntryIndex = (uOffset / VHD_SECTOR_SIZE) % pImage->cSectorsPerDataBlock;
1532 uint64_t uVhdOffset;
1533
1534 LogFlowFunc(("cBlockAllocationTableEntry=%u cBatEntryIndex=%u\n", cBlockAllocationTableEntry, cBATEntryIndex));
1535 LogFlowFunc(("BlockAllocationEntry=%u\n", pImage->pBlockAllocationTable[cBlockAllocationTableEntry]));
1536
1537 /*
1538 * Clip read range to remain in this data block.
1539 */
1540 cbToRead = RT_MIN(cbToRead, (pImage->cbDataBlock - (cBATEntryIndex * VHD_SECTOR_SIZE)));
1541
1542 /*
1543 * If the block is not allocated the content of the entry is ~0
1544 */
1545 if (pImage->pBlockAllocationTable[cBlockAllocationTableEntry] == ~0U)
1546 rc = VERR_VD_BLOCK_FREE;
1547 else
1548 {
1549 uVhdOffset = ((uint64_t)pImage->pBlockAllocationTable[cBlockAllocationTableEntry] + pImage->cDataBlockBitmapSectors + cBATEntryIndex) * VHD_SECTOR_SIZE;
1550 LogFlowFunc(("uVhdOffset=%llu cbToRead=%u\n", uVhdOffset, cbToRead));
1551
1552 /* Read in the block's bitmap. */
1553 PVDMETAXFER pMetaXfer;
1554 rc = vdIfIoIntFileReadMeta(pImage->pIfIo, pImage->pStorage,
1555 ((uint64_t)pImage->pBlockAllocationTable[cBlockAllocationTableEntry]) * VHD_SECTOR_SIZE,
1556 pImage->pu8Bitmap, pImage->cbDataBlockBitmap,
1557 pIoCtx, &pMetaXfer, NULL, NULL);
1558
1559 if (RT_SUCCESS(rc))
1560 {
1561 uint32_t cSectors = 0;
1562
1563 vdIfIoIntMetaXferRelease(pImage->pIfIo, pMetaXfer);
1564 if (vhdBlockBitmapSectorContainsData(pImage, cBATEntryIndex))
1565 {
1566 cBATEntryIndex++;
1567 cSectors = 1;
1568
1569 /*
1570 * The first sector being read is marked dirty, read as much as we
1571 * can from child. Note that only sectors that are marked dirty
1572 * must be read from child.
1573 */
1574 while ( (cSectors < (cbToRead / VHD_SECTOR_SIZE))
1575 && vhdBlockBitmapSectorContainsData(pImage, cBATEntryIndex))
1576 {
1577 cBATEntryIndex++;
1578 cSectors++;
1579 }
1580
1581 cbToRead = cSectors * VHD_SECTOR_SIZE;
1582
1583 LogFlowFunc(("uVhdOffset=%llu cbToRead=%u\n", uVhdOffset, cbToRead));
1584 rc = vdIfIoIntFileReadUser(pImage->pIfIo, pImage->pStorage,
1585 uVhdOffset, pIoCtx, cbToRead);
1586 }
1587 else
1588 {
1589 /*
1590 * The first sector being read is marked clean, so we should read from
1591 * our parent instead, but only as much as there are the following
1592 * clean sectors, because the block may still contain dirty sectors
1593 * further on. We just need to compute the number of clean sectors
1594 * and pass it to our caller along with the notification that they
1595 * should be read from the parent.
1596 */
1597 cBATEntryIndex++;
1598 cSectors = 1;
1599
1600 while ( (cSectors < (cbToRead / VHD_SECTOR_SIZE))
1601 && !vhdBlockBitmapSectorContainsData(pImage, cBATEntryIndex))
1602 {
1603 cBATEntryIndex++;
1604 cSectors++;
1605 }
1606
1607 cbToRead = cSectors * VHD_SECTOR_SIZE;
1608 LogFunc(("Sectors free: uVhdOffset=%llu cbToRead=%u\n", uVhdOffset, cbToRead));
1609 rc = VERR_VD_BLOCK_FREE;
1610 }
1611 }
1612 else
1613 AssertMsg(rc == VERR_VD_NOT_ENOUGH_METADATA, ("Reading block bitmap failed rc=%Rrc\n", rc));
1614 }
1615 }
1616 else
1617 rc = vdIfIoIntFileReadUser(pImage->pIfIo, pImage->pStorage, uOffset, pIoCtx, cbToRead);
1618
1619 if (pcbActuallyRead)
1620 *pcbActuallyRead = cbToRead;
1621
1622 LogFlowFunc(("returns rc=%Rrc\n", rc));
1623 return rc;
1624}
1625
1626/** @interface_method_impl{VDIMAGEBACKEND,pfnWrite} */
1627static DECLCALLBACK(int) vhdWrite(void *pBackendData, uint64_t uOffset, size_t cbToWrite,
1628 PVDIOCTX pIoCtx, size_t *pcbWriteProcess, size_t *pcbPreRead,
1629 size_t *pcbPostRead, unsigned fWrite)
1630{
1631 PVHDIMAGE pImage = (PVHDIMAGE)pBackendData;
1632 int rc = VINF_SUCCESS;
1633
1634 LogFlowFunc(("pBackendData=%p uOffset=%llu pIoCtx=%#p cbToWrite=%u pcbWriteProcess=%p pcbPreRead=%p pcbPostRead=%p fWrite=%u\n",
1635 pBackendData, uOffset, pIoCtx, cbToWrite, pcbWriteProcess, pcbPreRead, pcbPostRead, fWrite));
1636
1637 AssertPtr(pImage);
1638 Assert(!(uOffset % VHD_SECTOR_SIZE));
1639 Assert(!(cbToWrite % VHD_SECTOR_SIZE));
1640 AssertReturn((VALID_PTR(pIoCtx) && cbToWrite), VERR_INVALID_PARAMETER);
1641 AssertReturn(uOffset + cbToWrite <= pImage->cbSize, VERR_INVALID_PARAMETER);
1642
1643 if (pImage->pBlockAllocationTable)
1644 {
1645 /*
1646 * Get the data block first.
1647 */
1648 uint32_t cSector = uOffset / VHD_SECTOR_SIZE;
1649 uint32_t cBlockAllocationTableEntry = cSector / pImage->cSectorsPerDataBlock;
1650 uint32_t cBATEntryIndex = cSector % pImage->cSectorsPerDataBlock;
1651 uint64_t uVhdOffset;
1652
1653 /*
1654 * Clip write range.
1655 */
1656 cbToWrite = RT_MIN(cbToWrite, (pImage->cbDataBlock - (cBATEntryIndex * VHD_SECTOR_SIZE)));
1657
1658 /*
1659 * If the block is not allocated the content of the entry is ~0
1660 * and we need to allocate a new block. Note that while blocks are
1661 * allocated with a relatively big granularity, each sector has its
1662 * own bitmap entry, indicating whether it has been written or not.
1663 * So that means for the purposes of the higher level that the
1664 * granularity is invisible. This means there's no need to return
1665 * VERR_VD_BLOCK_FREE unless the block hasn't been allocated yet.
1666 */
1667 if (pImage->pBlockAllocationTable[cBlockAllocationTableEntry] == ~0U)
1668 {
1669 /* Check if the block allocation should be suppressed. */
1670 if ( (fWrite & VD_WRITE_NO_ALLOC)
1671 || (cbToWrite != pImage->cbDataBlock))
1672 {
1673 *pcbPreRead = cBATEntryIndex * VHD_SECTOR_SIZE;
1674 *pcbPostRead = pImage->cSectorsPerDataBlock * VHD_SECTOR_SIZE - cbToWrite - *pcbPreRead;
1675
1676 if (pcbWriteProcess)
1677 *pcbWriteProcess = cbToWrite;
1678 return VERR_VD_BLOCK_FREE;
1679 }
1680
1681 PVHDIMAGEEXPAND pExpand;
1682 pExpand = (PVHDIMAGEEXPAND)RTMemAllocZ(RT_UOFFSETOF_DYN(VHDIMAGEEXPAND,
1683 au8Bitmap[pImage->cDataBlockBitmapSectors * VHD_SECTOR_SIZE]));
1684 bool fIoInProgress = false;
1685
1686 if (!pExpand)
1687 return VERR_NO_MEMORY;
1688
1689 pExpand->cbEofOld = pImage->uCurrentEndOfFile;
1690 pExpand->idxBatAllocated = cBlockAllocationTableEntry;
1691 pExpand->idxBlockBe = RT_H2BE_U32(pImage->uCurrentEndOfFile / VHD_SECTOR_SIZE);
1692
1693 /* Set the bits for all sectors having been written. */
1694 for (uint32_t iSector = 0; iSector < (cbToWrite / VHD_SECTOR_SIZE); iSector++)
1695 {
1696 /* No need to check for a changed value because this is an initial write. */
1697 vhdBlockBitmapSectorSet(pImage, pExpand->au8Bitmap, cBATEntryIndex);
1698 cBATEntryIndex++;
1699 }
1700
1701 do
1702 {
1703 /*
1704 * Start with the sector bitmap.
1705 */
1706 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
1707 pImage->uCurrentEndOfFile,
1708 pExpand->au8Bitmap,
1709 pImage->cDataBlockBitmapSectors * VHD_SECTOR_SIZE, pIoCtx,
1710 vhdAsyncExpansionDataBlockBitmapComplete,
1711 pExpand);
1712 if (RT_SUCCESS(rc))
1713 VHDIMAGEEXPAND_STATUS_SET(pExpand->fFlags, VHDIMAGEEXPAND_BLOCKBITMAP_STATUS_SHIFT, VHDIMAGEEXPAND_STEP_SUCCESS);
1714 else if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1715 fIoInProgress = true;
1716 else
1717 {
1718 VHDIMAGEEXPAND_STATUS_SET(pExpand->fFlags, VHDIMAGEEXPAND_BLOCKBITMAP_STATUS_SHIFT, VHDIMAGEEXPAND_STEP_FAILED);
1719 VHDIMAGEEXPAND_STATUS_SET(pExpand->fFlags, VHDIMAGEEXPAND_USERBLOCK_STATUS_SHIFT, VHDIMAGEEXPAND_STEP_FAILED);
1720 VHDIMAGEEXPAND_STATUS_SET(pExpand->fFlags, VHDIMAGEEXPAND_BAT_STATUS_SHIFT, VHDIMAGEEXPAND_STEP_FAILED);
1721 VHDIMAGEEXPAND_STATUS_SET(pExpand->fFlags, VHDIMAGEEXPAND_FOOTER_STATUS_SHIFT, VHDIMAGEEXPAND_STEP_FAILED);
1722 break;
1723 }
1724
1725
1726 /*
1727 * Write the new block at the current end of the file.
1728 */
1729 rc = vdIfIoIntFileWriteUser(pImage->pIfIo, pImage->pStorage,
1730 pImage->uCurrentEndOfFile + (pImage->cDataBlockBitmapSectors + (cSector % pImage->cSectorsPerDataBlock)) * VHD_SECTOR_SIZE,
1731 pIoCtx, cbToWrite,
1732 vhdAsyncExpansionDataComplete,
1733 pExpand);
1734 if (RT_SUCCESS(rc))
1735 VHDIMAGEEXPAND_STATUS_SET(pExpand->fFlags, VHDIMAGEEXPAND_USERBLOCK_STATUS_SHIFT, VHDIMAGEEXPAND_STEP_SUCCESS);
1736 else if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1737 fIoInProgress = true;
1738 else
1739 {
1740 VHDIMAGEEXPAND_STATUS_SET(pExpand->fFlags, VHDIMAGEEXPAND_USERBLOCK_STATUS_SHIFT, VHDIMAGEEXPAND_STEP_FAILED);
1741 VHDIMAGEEXPAND_STATUS_SET(pExpand->fFlags, VHDIMAGEEXPAND_BAT_STATUS_SHIFT, VHDIMAGEEXPAND_STEP_FAILED);
1742 VHDIMAGEEXPAND_STATUS_SET(pExpand->fFlags, VHDIMAGEEXPAND_FOOTER_STATUS_SHIFT, VHDIMAGEEXPAND_STEP_FAILED);
1743 break;
1744 }
1745
1746 /*
1747 * Write entry in the BAT.
1748 */
1749 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
1750 pImage->uBlockAllocationTableOffset + cBlockAllocationTableEntry * sizeof(uint32_t),
1751 &pExpand->idxBlockBe, sizeof(uint32_t), pIoCtx,
1752 vhdAsyncExpansionBatUpdateComplete,
1753 pExpand);
1754 if (RT_SUCCESS(rc))
1755 VHDIMAGEEXPAND_STATUS_SET(pExpand->fFlags, VHDIMAGEEXPAND_BAT_STATUS_SHIFT, VHDIMAGEEXPAND_STEP_SUCCESS);
1756 else if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1757 fIoInProgress = true;
1758 else
1759 {
1760 VHDIMAGEEXPAND_STATUS_SET(pExpand->fFlags, VHDIMAGEEXPAND_BAT_STATUS_SHIFT, VHDIMAGEEXPAND_STEP_FAILED);
1761 VHDIMAGEEXPAND_STATUS_SET(pExpand->fFlags, VHDIMAGEEXPAND_FOOTER_STATUS_SHIFT, VHDIMAGEEXPAND_STEP_FAILED);
1762 break;
1763 }
1764
1765 /*
1766 * Set the new end of the file and link the new block into the BAT.
1767 */
1768 pImage->uCurrentEndOfFile += pImage->cDataBlockBitmapSectors * VHD_SECTOR_SIZE + pImage->cbDataBlock;
1769
1770 /* Update the footer. */
1771 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
1772 pImage->uCurrentEndOfFile,
1773 &pImage->vhdFooterCopy,
1774 sizeof(VHDFooter), pIoCtx,
1775 vhdAsyncExpansionFooterUpdateComplete,
1776 pExpand);
1777 if (RT_SUCCESS(rc))
1778 VHDIMAGEEXPAND_STATUS_SET(pExpand->fFlags, VHDIMAGEEXPAND_FOOTER_STATUS_SHIFT, VHDIMAGEEXPAND_STEP_SUCCESS);
1779 else if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1780 fIoInProgress = true;
1781 else
1782 {
1783 VHDIMAGEEXPAND_STATUS_SET(pExpand->fFlags, VHDIMAGEEXPAND_FOOTER_STATUS_SHIFT, VHDIMAGEEXPAND_STEP_FAILED);
1784 break;
1785 }
1786
1787 } while (0);
1788
1789 if (!fIoInProgress)
1790 vhdAsyncExpansionComplete(pImage, pIoCtx, pExpand);
1791 else
1792 rc = VERR_VD_ASYNC_IO_IN_PROGRESS;
1793 }
1794 else
1795 {
1796 /*
1797 * Calculate the real offset in the file.
1798 */
1799 uVhdOffset = ((uint64_t)pImage->pBlockAllocationTable[cBlockAllocationTableEntry] + pImage->cDataBlockBitmapSectors + cBATEntryIndex) * VHD_SECTOR_SIZE;
1800
1801 /* Read in the block's bitmap. */
1802 PVDMETAXFER pMetaXfer;
1803 rc = vdIfIoIntFileReadMeta(pImage->pIfIo, pImage->pStorage,
1804 ((uint64_t)pImage->pBlockAllocationTable[cBlockAllocationTableEntry]) * VHD_SECTOR_SIZE,
1805 pImage->pu8Bitmap,
1806 pImage->cbDataBlockBitmap, pIoCtx,
1807 &pMetaXfer, NULL, NULL);
1808 if (RT_SUCCESS(rc))
1809 {
1810 vdIfIoIntMetaXferRelease(pImage->pIfIo, pMetaXfer);
1811
1812 /* Write data. */
1813 rc = vdIfIoIntFileWriteUser(pImage->pIfIo, pImage->pStorage,
1814 uVhdOffset, pIoCtx, cbToWrite,
1815 NULL, NULL);
1816 if (RT_SUCCESS(rc) || rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1817 {
1818 bool fChanged = false;
1819
1820 /* Set the bits for all sectors having been written. */
1821 for (uint32_t iSector = 0; iSector < (cbToWrite / VHD_SECTOR_SIZE); iSector++)
1822 {
1823 fChanged |= vhdBlockBitmapSectorSet(pImage, pImage->pu8Bitmap, cBATEntryIndex);
1824 cBATEntryIndex++;
1825 }
1826
1827 /* Only write the bitmap if it was changed. */
1828 if (fChanged)
1829 {
1830 /*
1831 * Write the bitmap back.
1832 *
1833 * @note We don't have a completion callback here because we
1834 * can't do anything if the write fails for some reason.
1835 * The error will propagated to the device/guest
1836 * by the generic VD layer already and we don't need
1837 * to rollback anything here.
1838 */
1839 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
1840 ((uint64_t)pImage->pBlockAllocationTable[cBlockAllocationTableEntry]) * VHD_SECTOR_SIZE,
1841 pImage->pu8Bitmap,
1842 pImage->cbDataBlockBitmap,
1843 pIoCtx, NULL, NULL);
1844 }
1845 }
1846 }
1847 }
1848 }
1849 else
1850 rc = vdIfIoIntFileWriteUser(pImage->pIfIo, pImage->pStorage,
1851 uOffset, pIoCtx, cbToWrite, NULL, NULL);
1852
1853 if (pcbWriteProcess)
1854 *pcbWriteProcess = cbToWrite;
1855
1856 /* Stay on the safe side. Do not run the risk of confusing the higher
1857 * level, as that can be pretty lethal to image consistency. */
1858 *pcbPreRead = 0;
1859 *pcbPostRead = 0;
1860
1861 return rc;
1862}
1863
1864/** @interface_method_impl{VDIMAGEBACKEND,pfnFlush} */
1865static DECLCALLBACK(int) vhdFlush(void *pBackendData, PVDIOCTX pIoCtx)
1866{
1867 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1868 PVHDIMAGE pImage = (PVHDIMAGE)pBackendData;
1869
1870 /* No need to write anything here. Data is always updated on a write. */
1871 int rc = vdIfIoIntFileFlush(pImage->pIfIo, pImage->pStorage, pIoCtx, NULL, NULL);
1872 LogFlowFunc(("returns %Rrc\n", rc));
1873 return rc;
1874}
1875
1876/** @interface_method_impl{VDIMAGEBACKEND,pfnGetVersion} */
1877static DECLCALLBACK(unsigned) vhdGetVersion(void *pBackendData)
1878{
1879 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1880 PVHDIMAGE pImage = (PVHDIMAGE)pBackendData;
1881
1882 AssertPtrReturn(pImage, 0);
1883
1884 unsigned uVersion = 1; /**< @todo use correct version */
1885
1886 LogFlowFunc(("returns %u\n", uVersion));
1887 return uVersion;
1888}
1889
1890/** @interface_method_impl{VDIMAGEBACKEND,pfnGetFileSize} */
1891static DECLCALLBACK(uint64_t) vhdGetFileSize(void *pBackendData)
1892{
1893 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1894 PVHDIMAGE pImage = (PVHDIMAGE)pBackendData;
1895 uint64_t cb = 0;
1896
1897 AssertPtrReturn(pImage, 0);
1898
1899 if (pImage->pStorage)
1900 cb = pImage->uCurrentEndOfFile + sizeof(VHDFooter);
1901
1902 LogFlowFunc(("returns %lld\n", cb));
1903 return cb;
1904}
1905
1906/** @interface_method_impl{VDIMAGEBACKEND,pfnGetPCHSGeometry} */
1907static DECLCALLBACK(int) vhdGetPCHSGeometry(void *pBackendData, PVDGEOMETRY pPCHSGeometry)
1908{
1909 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p\n", pBackendData, pPCHSGeometry));
1910 PVHDIMAGE pImage = (PVHDIMAGE)pBackendData;
1911 int rc = VINF_SUCCESS;
1912
1913 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
1914
1915 if (pImage->PCHSGeometry.cCylinders)
1916 *pPCHSGeometry = pImage->PCHSGeometry;
1917 else
1918 rc = VERR_VD_GEOMETRY_NOT_SET;
1919
1920 LogFlowFunc(("returns %Rrc (CHS=%u/%u/%u)\n", rc, pImage->PCHSGeometry.cCylinders,
1921 pImage->PCHSGeometry.cHeads, pImage->PCHSGeometry.cSectors));
1922 return rc;
1923}
1924
1925/** @interface_method_impl{VDIMAGEBACKEND,pfnSetPCHSGeometry} */
1926static DECLCALLBACK(int) vhdSetPCHSGeometry(void *pBackendData, PCVDGEOMETRY pPCHSGeometry)
1927{
1928 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p PCHS=%u/%u/%u\n",
1929 pBackendData, pPCHSGeometry, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
1930 PVHDIMAGE pImage = (PVHDIMAGE)pBackendData;
1931 int rc = VINF_SUCCESS;
1932
1933 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
1934
1935 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
1936 rc = VERR_VD_IMAGE_READ_ONLY;
1937 else
1938 pImage->PCHSGeometry = *pPCHSGeometry;
1939
1940 LogFlowFunc(("returns %Rrc\n", rc));
1941 return rc;
1942}
1943
1944/** @interface_method_impl{VDIMAGEBACKEND,pfnGetLCHSGeometry} */
1945static DECLCALLBACK(int) vhdGetLCHSGeometry(void *pBackendData, PVDGEOMETRY pLCHSGeometry)
1946{
1947 LogFlowFunc(("pBackendData=%#p pLCHSGeometry=%#p\n", pBackendData, pLCHSGeometry));
1948 PVHDIMAGE pImage = (PVHDIMAGE)pBackendData;
1949 int rc = VINF_SUCCESS;
1950
1951 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
1952
1953 if (pImage->LCHSGeometry.cCylinders)
1954 *pLCHSGeometry = pImage->LCHSGeometry;
1955 else
1956 rc = VERR_VD_GEOMETRY_NOT_SET;
1957
1958 LogFlowFunc(("returns %Rrc (CHS=%u/%u/%u)\n", rc, pImage->LCHSGeometry.cCylinders,
1959 pImage->LCHSGeometry.cHeads, pImage->LCHSGeometry.cSectors));
1960 return rc;
1961}
1962
1963/** @interface_method_impl{VDIMAGEBACKEND,pfnSetLCHSGeometry} */
1964static DECLCALLBACK(int) vhdSetLCHSGeometry(void *pBackendData, PCVDGEOMETRY pLCHSGeometry)
1965{
1966 PVHDIMAGE pImage = (PVHDIMAGE)pBackendData;
1967 int rc = VINF_SUCCESS;
1968
1969 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
1970
1971 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
1972 rc = VERR_VD_IMAGE_READ_ONLY;
1973 else
1974 pImage->LCHSGeometry = *pLCHSGeometry;
1975
1976 LogFlowFunc(("returns %Rrc\n", rc));
1977 return rc;
1978}
1979
1980/** @copydoc VDIMAGEBACKEND::pfnQueryRegions */
1981static DECLCALLBACK(int) vhdQueryRegions(void *pBackendData, PCVDREGIONLIST *ppRegionList)
1982{
1983 LogFlowFunc(("pBackendData=%#p ppRegionList=%#p\n", pBackendData, ppRegionList));
1984 PVHDIMAGE pThis = (PVHDIMAGE)pBackendData;
1985
1986 AssertPtrReturn(pThis, VERR_VD_NOT_OPENED);
1987
1988 *ppRegionList = &pThis->RegionList;
1989 LogFlowFunc(("returns %Rrc\n", VINF_SUCCESS));
1990 return VINF_SUCCESS;
1991}
1992
1993/** @copydoc VDIMAGEBACKEND::pfnRegionListRelease */
1994static DECLCALLBACK(void) vhdRegionListRelease(void *pBackendData, PCVDREGIONLIST pRegionList)
1995{
1996 RT_NOREF1(pRegionList);
1997 LogFlowFunc(("pBackendData=%#p pRegionList=%#p\n", pBackendData, pRegionList));
1998 PVHDIMAGE pThis = (PVHDIMAGE)pBackendData;
1999 AssertPtr(pThis); RT_NOREF(pThis);
2000
2001 /* Nothing to do here. */
2002}
2003
2004/** @interface_method_impl{VDIMAGEBACKEND,pfnGetImageFlags} */
2005static DECLCALLBACK(unsigned) vhdGetImageFlags(void *pBackendData)
2006{
2007 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
2008 PVHDIMAGE pImage = (PVHDIMAGE)pBackendData;
2009
2010 AssertPtrReturn(pImage, 0);
2011
2012 LogFlowFunc(("returns %#x\n", pImage->uImageFlags));
2013 return pImage->uImageFlags;
2014}
2015
2016/** @interface_method_impl{VDIMAGEBACKEND,pfnGetOpenFlags} */
2017static DECLCALLBACK(unsigned) vhdGetOpenFlags(void *pBackendData)
2018{
2019 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
2020 PVHDIMAGE pImage = (PVHDIMAGE)pBackendData;
2021
2022 AssertPtrReturn(pImage, 0);
2023
2024 LogFlowFunc(("returns %#x\n", pImage->uOpenFlags));
2025 return pImage->uOpenFlags;
2026}
2027
2028/** @interface_method_impl{VDIMAGEBACKEND,pfnSetOpenFlags} */
2029static DECLCALLBACK(int) vhdSetOpenFlags(void *pBackendData, unsigned uOpenFlags)
2030{
2031 LogFlowFunc(("pBackendData=%#p\n uOpenFlags=%#x", pBackendData, uOpenFlags));
2032 PVHDIMAGE pImage = (PVHDIMAGE)pBackendData;
2033 int rc = VINF_SUCCESS;
2034
2035 /* Image must be opened and the new flags must be valid. */
2036 if (!pImage || (uOpenFlags & ~( VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO
2037 | VD_OPEN_FLAGS_ASYNC_IO | VD_OPEN_FLAGS_SHAREABLE
2038 | VD_OPEN_FLAGS_SEQUENTIAL | VD_OPEN_FLAGS_SKIP_CONSISTENCY_CHECKS)))
2039 rc = VERR_INVALID_PARAMETER;
2040 else
2041 {
2042 /* Implement this operation via reopening the image. */
2043 rc = vhdFreeImage(pImage, false);
2044 if (RT_SUCCESS(rc))
2045 rc = vhdOpenImage(pImage, uOpenFlags);
2046 }
2047
2048 LogFlowFunc(("returns %Rrc\n", rc));
2049 return rc;
2050}
2051
2052/** @interface_method_impl{VDIMAGEBACKEND,pfnGetComment} */
2053static DECLCALLBACK(int) vhdGetComment(void *pBackendData, char *pszComment,
2054 size_t cbComment)
2055{
2056 RT_NOREF2(pszComment, cbComment);
2057 LogFlowFunc(("pBackendData=%#p pszComment=%#p cbComment=%zu\n", pBackendData, pszComment, cbComment));
2058 PVHDIMAGE pImage = (PVHDIMAGE)pBackendData;
2059
2060 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2061
2062 LogFlowFunc(("returns %Rrc comment='%s'\n", VERR_NOT_SUPPORTED, pszComment));
2063 return VERR_NOT_SUPPORTED;
2064}
2065
2066/** @interface_method_impl{VDIMAGEBACKEND,pfnSetComment} */
2067static DECLCALLBACK(int) vhdSetComment(void *pBackendData, const char *pszComment)
2068{
2069 RT_NOREF1(pszComment);
2070 LogFlowFunc(("pBackendData=%#p pszComment=\"%s\"\n", pBackendData, pszComment));
2071 PVHDIMAGE pImage = (PVHDIMAGE)pBackendData;
2072
2073 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2074
2075 int rc;
2076 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2077 rc = VERR_VD_IMAGE_READ_ONLY;
2078 else
2079 rc = VERR_NOT_SUPPORTED;
2080
2081 LogFlowFunc(("returns %Rrc\n", rc));
2082 return rc;
2083}
2084
2085/** @interface_method_impl{VDIMAGEBACKEND,pfnGetUuid} */
2086static DECLCALLBACK(int) vhdGetUuid(void *pBackendData, PRTUUID pUuid)
2087{
2088 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
2089 PVHDIMAGE pImage = (PVHDIMAGE)pBackendData;
2090
2091 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2092
2093 *pUuid = pImage->ImageUuid;
2094
2095 LogFlowFunc(("returns %Rrc (%RTuuid)\n", VINF_SUCCESS, pUuid));
2096 return VINF_SUCCESS;
2097}
2098
2099/** @interface_method_impl{VDIMAGEBACKEND,pfnSetUuid} */
2100static DECLCALLBACK(int) vhdSetUuid(void *pBackendData, PCRTUUID pUuid)
2101{
2102 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
2103 PVHDIMAGE pImage = (PVHDIMAGE)pBackendData;
2104 int rc = VINF_SUCCESS;
2105
2106 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2107
2108 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
2109 {
2110 pImage->ImageUuid = *pUuid;
2111 /* Update the footer copy. It will get written to disk when the image is closed. */
2112 memcpy(&pImage->vhdFooterCopy.UniqueID, pUuid, 16);
2113 /* Update checksum. */
2114 pImage->vhdFooterCopy.Checksum = 0;
2115 pImage->vhdFooterCopy.Checksum = RT_H2BE_U32(vhdChecksum(&pImage->vhdFooterCopy, sizeof(VHDFooter)));
2116
2117 /* Need to update the dynamic disk header to update the disk footer copy at the beginning. */
2118 if (!(pImage->uImageFlags & VD_IMAGE_FLAGS_FIXED))
2119 pImage->fDynHdrNeedsUpdate = true;
2120 }
2121 else
2122 rc = VERR_VD_IMAGE_READ_ONLY;
2123
2124 LogFlowFunc(("returns %Rrc\n", rc));
2125 return rc;
2126}
2127
2128/** @interface_method_impl{VDIMAGEBACKEND,pfnGetModificationUuid} */
2129static DECLCALLBACK(int) vhdGetModificationUuid(void *pBackendData, PRTUUID pUuid)
2130{
2131 RT_NOREF1(pUuid);
2132 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
2133 PVHDIMAGE pImage = (PVHDIMAGE)pBackendData;
2134
2135 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2136
2137 LogFlowFunc(("returns %Rrc (%RTuuid)\n", VERR_NOT_SUPPORTED, pUuid));
2138 return VERR_NOT_SUPPORTED;
2139}
2140
2141/** @interface_method_impl{VDIMAGEBACKEND,pfnSetModificationUuid} */
2142static DECLCALLBACK(int) vhdSetModificationUuid(void *pBackendData, PCRTUUID pUuid)
2143{
2144 RT_NOREF1(pUuid);
2145 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
2146 PVHDIMAGE pImage = (PVHDIMAGE)pBackendData;
2147
2148 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2149
2150 int rc;
2151 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2152 rc = VERR_VD_IMAGE_READ_ONLY;
2153 else
2154 rc = VERR_NOT_SUPPORTED;
2155
2156 LogFlowFunc(("returns %Rrc\n", rc));
2157 return rc;
2158}
2159
2160/** @interface_method_impl{VDIMAGEBACKEND,pfnGetParentUuid} */
2161static DECLCALLBACK(int) vhdGetParentUuid(void *pBackendData, PRTUUID pUuid)
2162{
2163 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
2164 PVHDIMAGE pImage = (PVHDIMAGE)pBackendData;
2165
2166 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2167
2168 *pUuid = pImage->ParentUuid;
2169
2170 LogFlowFunc(("returns %Rrc (%RTuuid)\n", VINF_SUCCESS, pUuid));
2171 return VINF_SUCCESS;
2172}
2173
2174/** @interface_method_impl{VDIMAGEBACKEND,pfnSetParentUuid} */
2175static DECLCALLBACK(int) vhdSetParentUuid(void *pBackendData, PCRTUUID pUuid)
2176{
2177 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
2178 PVHDIMAGE pImage = (PVHDIMAGE)pBackendData;
2179 int rc = VINF_SUCCESS;
2180
2181 if (pImage && pImage->pStorage)
2182 {
2183 if (!(pImage->uImageFlags & VD_IMAGE_FLAGS_FIXED))
2184 {
2185 pImage->ParentUuid = *pUuid;
2186 pImage->fDynHdrNeedsUpdate = true;
2187 }
2188 else
2189 rc = VERR_VD_IMAGE_READ_ONLY;
2190 }
2191 else
2192 rc = VERR_VD_NOT_OPENED;
2193
2194 LogFlowFunc(("returns %Rrc\n", rc));
2195 return rc;
2196}
2197
2198/** @interface_method_impl{VDIMAGEBACKEND,pfnGetParentModificationUuid} */
2199static DECLCALLBACK(int) vhdGetParentModificationUuid(void *pBackendData, PRTUUID pUuid)
2200{
2201 RT_NOREF1(pUuid);
2202 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
2203 PVHDIMAGE pImage = (PVHDIMAGE)pBackendData;
2204
2205 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2206
2207 LogFlowFunc(("returns %Rrc (%RTuuid)\n", VERR_NOT_SUPPORTED, pUuid));
2208 return VERR_NOT_SUPPORTED;
2209}
2210
2211/** @interface_method_impl{VDIMAGEBACKEND,pfnSetParentModificationUuid} */
2212static DECLCALLBACK(int) vhdSetParentModificationUuid(void *pBackendData, PCRTUUID pUuid)
2213{
2214 RT_NOREF1(pUuid);
2215 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
2216 PVHDIMAGE pImage = (PVHDIMAGE)pBackendData;
2217
2218 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2219
2220 int rc;
2221 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2222 rc = VERR_VD_IMAGE_READ_ONLY;
2223 else
2224 rc = VERR_NOT_SUPPORTED;
2225
2226 LogFlowFunc(("returns %Rrc\n", rc));
2227 return rc;
2228}
2229
2230/** @interface_method_impl{VDIMAGEBACKEND,pfnDump} */
2231static DECLCALLBACK(void) vhdDump(void *pBackendData)
2232{
2233 PVHDIMAGE pImage = (PVHDIMAGE)pBackendData;
2234
2235 AssertPtrReturnVoid(pImage);
2236 vdIfErrorMessage(pImage->pIfError, "Header: Geometry PCHS=%u/%u/%u LCHS=%u/%u/%u cbSector=%u\n",
2237 pImage->PCHSGeometry.cCylinders, pImage->PCHSGeometry.cHeads, pImage->PCHSGeometry.cSectors,
2238 pImage->LCHSGeometry.cCylinders, pImage->LCHSGeometry.cHeads, pImage->LCHSGeometry.cSectors,
2239 VHD_SECTOR_SIZE);
2240 vdIfErrorMessage(pImage->pIfError, "Header: uuidCreation={%RTuuid}\n", &pImage->ImageUuid);
2241 vdIfErrorMessage(pImage->pIfError, "Header: uuidParent={%RTuuid}\n", &pImage->ParentUuid);
2242}
2243
2244/** @interface_method_impl{VDIMAGEBACKEND,pfnGetTimestamp} */
2245static DECLCALLBACK(int) vhdGetTimestamp(void *pBackendData, PRTTIMESPEC pTimestamp)
2246{
2247 PVHDIMAGE pImage = (PVHDIMAGE)pBackendData;
2248
2249 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2250
2251 int rc = vdIfIoIntFileGetModificationTime(pImage->pIfIo, pImage->pszFilename, pTimestamp);
2252
2253 LogFlowFunc(("returns %Rrc\n", rc));
2254 return rc;
2255}
2256
2257/** @interface_method_impl{VDIMAGEBACKEND,pfnGetParentTimestamp} */
2258static DECLCALLBACK(int) vhdGetParentTimestamp(void *pBackendData, PRTTIMESPEC pTimestamp)
2259{
2260 PVHDIMAGE pImage = (PVHDIMAGE)pBackendData;
2261
2262 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2263
2264 vhdTime2RtTime(pTimestamp, pImage->u32ParentTimestamp);
2265 LogFlowFunc(("returns %Rrc\n", VINF_SUCCESS));
2266 return VINF_SUCCESS;
2267}
2268
2269/** @interface_method_impl{VDIMAGEBACKEND,pfnSetParentTimestamp} */
2270static DECLCALLBACK(int) vhdSetParentTimestamp(void *pBackendData, PCRTTIMESPEC pTimestamp)
2271{
2272 int rc = VINF_SUCCESS;
2273 PVHDIMAGE pImage = (PVHDIMAGE)pBackendData;
2274
2275 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2276 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2277 rc = VERR_VD_IMAGE_READ_ONLY;
2278 else
2279 {
2280 pImage->u32ParentTimestamp = vhdRtTime2VhdTime(pTimestamp);
2281 pImage->fDynHdrNeedsUpdate = true;
2282 }
2283
2284 LogFlowFunc(("returns %Rrc\n", rc));
2285 return rc;
2286}
2287
2288/** @interface_method_impl{VDIMAGEBACKEND,pfnGetParentFilename} */
2289static DECLCALLBACK(int) vhdGetParentFilename(void *pBackendData, char **ppszParentFilename)
2290{
2291 PVHDIMAGE pImage = (PVHDIMAGE)pBackendData;
2292
2293 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2294 *ppszParentFilename = RTStrDup(pImage->pszParentFilename);
2295
2296 LogFlowFunc(("returns %Rrc\n", VINF_SUCCESS));
2297 return VINF_SUCCESS;
2298}
2299
2300/** @interface_method_impl{VDIMAGEBACKEND,pfnSetParentFilename} */
2301static DECLCALLBACK(int) vhdSetParentFilename(void *pBackendData, const char *pszParentFilename)
2302{
2303 int rc = VINF_SUCCESS;
2304 PVHDIMAGE pImage = (PVHDIMAGE)pBackendData;
2305
2306 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2307
2308 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2309 rc = VERR_VD_IMAGE_READ_ONLY;
2310 else
2311 {
2312 if (pImage->pszParentFilename)
2313 RTStrFree(pImage->pszParentFilename);
2314 pImage->pszParentFilename = RTStrDup(pszParentFilename);
2315 if (!pImage->pszParentFilename)
2316 rc = VERR_NO_MEMORY;
2317 else
2318 pImage->fDynHdrNeedsUpdate = true;
2319 }
2320
2321 LogFlowFunc(("returns %Rrc\n", rc));
2322 return rc;
2323}
2324
2325/** @interface_method_impl{VDIMAGEBACKEND,pfnCompact} */
2326static DECLCALLBACK(int) vhdCompact(void *pBackendData, unsigned uPercentStart,
2327 unsigned uPercentSpan, PVDINTERFACE pVDIfsDisk,
2328 PVDINTERFACE pVDIfsImage, PVDINTERFACE pVDIfsOperation)
2329{
2330 RT_NOREF2(pVDIfsDisk, pVDIfsImage);
2331 PVHDIMAGE pImage = (PVHDIMAGE)pBackendData;
2332 int rc = VINF_SUCCESS;
2333 void *pvBuf = NULL;
2334 uint32_t *paBlocks = NULL;
2335 PVDINTERFACEPROGRESS pIfProgress = VDIfProgressGet(pVDIfsOperation);
2336
2337 DECLCALLBACKMEMBER(int, pfnParentRead)(void *, uint64_t, void *, size_t) = NULL;
2338 void *pvParent = NULL;
2339 PVDINTERFACEPARENTSTATE pIfParentState = VDIfParentStateGet(pVDIfsOperation);
2340 if (pIfParentState)
2341 {
2342 pfnParentRead = pIfParentState->pfnParentRead;
2343 pvParent = pIfParentState->Core.pvUser;
2344 }
2345
2346 do
2347 {
2348 AssertBreakStmt(pImage, rc = VERR_INVALID_PARAMETER);
2349
2350 AssertBreakStmt(!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY),
2351 rc = VERR_VD_IMAGE_READ_ONLY);
2352
2353 /* Reject fixed images as they don't have a BAT. */
2354 if (pImage->uImageFlags & VD_IMAGE_FLAGS_FIXED)
2355 {
2356 rc = VERR_NOT_SUPPORTED;
2357 break;
2358 }
2359
2360 if (pfnParentRead)
2361 {
2362 pvParent = RTMemTmpAlloc(pImage->cbDataBlock);
2363 AssertBreakStmt(pvParent, rc = VERR_NO_MEMORY);
2364 }
2365 pvBuf = RTMemTmpAlloc(pImage->cbDataBlock);
2366 AssertBreakStmt(pvBuf, rc = VERR_NO_MEMORY);
2367
2368 unsigned cBlocksAllocated = 0;
2369 unsigned cBlocksToMove = 0;
2370 unsigned cBlocks = pImage->cBlockAllocationTableEntries;
2371 uint32_t offBlocksStart = ~0U; /* Start offset of data blocks in sectors. */
2372 uint32_t *paBat = pImage->pBlockAllocationTable;
2373
2374 /* Count the number of allocated blocks and find the start offset for the data blocks. */
2375 for (unsigned i = 0; i < cBlocks; i++)
2376 if (paBat[i] != ~0U)
2377 {
2378 cBlocksAllocated++;
2379 if (paBat[i] < offBlocksStart)
2380 offBlocksStart = paBat[i];
2381 }
2382
2383 if (!cBlocksAllocated)
2384 {
2385 /* Nothing to do. */
2386 rc = VINF_SUCCESS;
2387 break;
2388 }
2389
2390 paBlocks = (uint32_t *)RTMemTmpAllocZ(cBlocksAllocated * sizeof(uint32_t));
2391 AssertBreakStmt(paBlocks, rc = VERR_NO_MEMORY);
2392
2393 /* Invalidate the back resolving array. */
2394 for (unsigned i = 0; i < cBlocksAllocated; i++)
2395 paBlocks[i] = ~0U;
2396
2397 /* Fill the back resolving table. */
2398 for (unsigned i = 0; i < cBlocks; i++)
2399 if (paBat[i] != ~0U)
2400 {
2401 unsigned idxBlock = (paBat[i] - offBlocksStart) / pImage->cSectorsPerDataBlock;
2402 if ( idxBlock < cBlocksAllocated
2403 && paBlocks[idxBlock] == ~0U)
2404 paBlocks[idxBlock] = i;
2405 else
2406 {
2407 /* The image is in an inconsistent state. Don't go further. */
2408 rc = VERR_INVALID_STATE;
2409 break;
2410 }
2411 }
2412
2413 if (RT_FAILURE(rc))
2414 break;
2415
2416 /* Find redundant information and update the block pointers
2417 * accordingly, creating bubbles. Keep disk up to date, as this
2418 * enables cancelling. */
2419 for (unsigned i = 0; i < cBlocks; i++)
2420 {
2421 if (paBat[i] != ~0U)
2422 {
2423 unsigned idxBlock = (paBat[i] - offBlocksStart) / pImage->cSectorsPerDataBlock;
2424
2425 /* Block present in image file, read relevant data. */
2426 uint64_t u64Offset = ((uint64_t)paBat[i] + pImage->cDataBlockBitmapSectors) * VHD_SECTOR_SIZE;
2427 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage,
2428 u64Offset, pvBuf, pImage->cbDataBlock);
2429 if (RT_FAILURE(rc))
2430 break;
2431
2432 if (ASMBitFirstSet((volatile void *)pvBuf, (uint32_t)pImage->cbDataBlock * 8) == -1)
2433 {
2434 paBat[i] = UINT32_MAX;
2435 paBlocks[idxBlock] = ~0U;
2436 /* Adjust progress info, one block to be relocated. */
2437 cBlocksToMove++;
2438 }
2439 else if (pfnParentRead)
2440 {
2441 rc = pfnParentRead(pvParent, (uint64_t)i * pImage->cbDataBlock, pvParent, pImage->cbDataBlock);
2442 if (RT_FAILURE(rc))
2443 break;
2444 if (!memcmp(pvParent, pvBuf, pImage->cbDataBlock))
2445 {
2446 paBat[i] = ~0U;
2447 paBlocks[idxBlock] = ~0U;
2448 /* Adjust progress info, one block to be relocated. */
2449 cBlocksToMove++;
2450 }
2451 }
2452 }
2453
2454 vdIfProgress(pIfProgress, (uint64_t)i * uPercentSpan / (cBlocks + cBlocksToMove) + uPercentStart);
2455 }
2456
2457 if (RT_SUCCESS(rc))
2458 {
2459 /* Fill bubbles with other data (if available). */
2460 unsigned cBlocksMoved = 0;
2461 unsigned uBlockUsedPos = cBlocksAllocated;
2462 size_t cbBlock = pImage->cbDataBlock + pImage->cbDataBlockBitmap; /** < Size of whole block containing the bitmap and the user data. */
2463
2464 /* Allocate data buffer to hold the data block and allocation bitmap in front of the actual data. */
2465 RTMemTmpFree(pvBuf);
2466 pvBuf = RTMemTmpAllocZ(cbBlock);
2467 AssertBreakStmt(pvBuf, rc = VERR_NO_MEMORY);
2468
2469 for (unsigned i = 0; i < cBlocksAllocated; i++)
2470 {
2471 unsigned uBlock = paBlocks[i];
2472 if (uBlock == ~0U)
2473 {
2474 unsigned uBlockData = ~0U;
2475 while (uBlockUsedPos > i && uBlockData == ~0U)
2476 {
2477 uBlockUsedPos--;
2478 uBlockData = paBlocks[uBlockUsedPos];
2479 }
2480 /* Terminate early if there is no block which needs copying. */
2481 if (uBlockUsedPos == i)
2482 break;
2483 uint64_t u64Offset = (uint64_t)uBlockUsedPos * cbBlock
2484 + (offBlocksStart * VHD_SECTOR_SIZE);
2485 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage,
2486 u64Offset, pvBuf, cbBlock);
2487 if (RT_FAILURE(rc))
2488 break;
2489
2490 u64Offset = (uint64_t)i * cbBlock
2491 + (offBlocksStart * VHD_SECTOR_SIZE);
2492 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage,
2493 u64Offset, pvBuf, cbBlock);
2494 if (RT_FAILURE(rc))
2495 break;
2496
2497 paBat[uBlockData] = i*(pImage->cSectorsPerDataBlock + pImage->cDataBlockBitmapSectors) + offBlocksStart;
2498
2499 /* Truncate the file but leave enough room for the footer to avoid
2500 * races if other processes fill the whole harddisk. */
2501 rc = vdIfIoIntFileSetSize(pImage->pIfIo, pImage->pStorage,
2502 pImage->uCurrentEndOfFile - cbBlock + VHD_SECTOR_SIZE);
2503 if (RT_FAILURE(rc))
2504 break;
2505
2506 /* Update pointers and write footer. */
2507 pImage->uCurrentEndOfFile -= cbBlock;
2508
2509 /* We're kinda screwed if this failes. */
2510 rc = vhdUpdateFooter(pImage);
2511 if (RT_FAILURE(rc))
2512 break;
2513
2514 paBlocks[i] = uBlockData;
2515 paBlocks[uBlockUsedPos] = ~0U;
2516 cBlocksMoved++;
2517 }
2518
2519 rc = vdIfProgress(pIfProgress, (uint64_t)(cBlocks + cBlocksMoved) * uPercentSpan / (cBlocks + cBlocksToMove) + uPercentStart);
2520 }
2521 }
2522
2523 /* Write the new BAT in any case. */
2524 rc = vhdFlushImage(pImage);
2525 } while (0);
2526
2527 if (paBlocks)
2528 RTMemTmpFree(paBlocks);
2529 if (pvParent)
2530 RTMemTmpFree(pvParent);
2531 if (pvBuf)
2532 RTMemTmpFree(pvBuf);
2533
2534 if (RT_SUCCESS(rc))
2535 vdIfProgress(pIfProgress, uPercentStart + uPercentSpan);
2536
2537 LogFlowFunc(("returns %Rrc\n", rc));
2538 return rc;
2539}
2540
2541/** @interface_method_impl{VDIMAGEBACKEND,pfnResize} */
2542static DECLCALLBACK(int) vhdResize(void *pBackendData, uint64_t cbSize,
2543 PCVDGEOMETRY pPCHSGeometry, PCVDGEOMETRY pLCHSGeometry,
2544 unsigned uPercentStart, unsigned uPercentSpan,
2545 PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
2546 PVDINTERFACE pVDIfsOperation)
2547{
2548 RT_NOREF5(uPercentSpan, uPercentStart, pVDIfsDisk, pVDIfsImage, pVDIfsOperation);
2549 PVHDIMAGE pImage = (PVHDIMAGE)pBackendData;
2550 int rc = VINF_SUCCESS;
2551
2552 /* Making the image smaller is not supported at the moment. */
2553 if (cbSize < pImage->cbSize)
2554 rc = VERR_VD_SHRINK_NOT_SUPPORTED;
2555 else if (pImage->uImageFlags & VD_IMAGE_FLAGS_FIXED)
2556 rc = VERR_NOT_SUPPORTED;
2557 else if (cbSize > pImage->cbSize)
2558 {
2559 unsigned cBlocksAllocated = 0;
2560 size_t cbBlock = pImage->cbDataBlock + pImage->cbDataBlockBitmap; /** < Size of a block including the sector bitmap. */
2561 uint32_t cBlocksNew = cbSize / pImage->cbDataBlock; /** < New number of blocks in the image after the resize */
2562 if (cbSize % pImage->cbDataBlock)
2563 cBlocksNew++;
2564
2565 uint32_t cBlocksOld = pImage->cBlockAllocationTableEntries; /** < Number of blocks before the resize. */
2566 uint64_t cbBlockspaceNew = RT_ALIGN_32(cBlocksNew * sizeof(uint32_t), VHD_SECTOR_SIZE); /** < Required space for the block array after the resize. */
2567 uint64_t offStartDataNew = RT_ALIGN_32(pImage->uBlockAllocationTableOffset + cbBlockspaceNew, VHD_SECTOR_SIZE); /** < New start offset for block data after the resize */
2568 uint64_t offStartDataOld = ~0ULL;
2569
2570 /* Go through the BAT and find the data start offset. */
2571 for (unsigned idxBlock = 0; idxBlock < pImage->cBlockAllocationTableEntries; idxBlock++)
2572 {
2573 if (pImage->pBlockAllocationTable[idxBlock] != ~0U)
2574 {
2575 uint64_t offStartBlock = (uint64_t)pImage->pBlockAllocationTable[idxBlock] * VHD_SECTOR_SIZE;
2576 if (offStartBlock < offStartDataOld)
2577 offStartDataOld = offStartBlock;
2578 cBlocksAllocated++;
2579 }
2580 }
2581
2582 if ( offStartDataOld != offStartDataNew
2583 && cBlocksAllocated > 0)
2584 {
2585 /* Calculate how many sectors nee to be relocated. */
2586 uint64_t cbOverlapping = offStartDataNew - offStartDataOld;
2587 unsigned cBlocksReloc = (unsigned)(cbOverlapping / cbBlock);
2588 if (cbOverlapping % cbBlock)
2589 cBlocksReloc++;
2590
2591 cBlocksReloc = RT_MIN(cBlocksReloc, cBlocksAllocated);
2592 offStartDataNew = offStartDataOld;
2593
2594 /* Do the relocation. */
2595 LogFlow(("Relocating %u blocks\n", cBlocksReloc));
2596
2597 /*
2598 * Get the blocks we need to relocate first, they are appended to the end
2599 * of the image.
2600 */
2601 void *pvBuf = NULL, *pvZero = NULL;
2602 do
2603 {
2604 /* Allocate data buffer. */
2605 pvBuf = RTMemAllocZ(cbBlock);
2606 if (!pvBuf)
2607 {
2608 rc = VERR_NO_MEMORY;
2609 break;
2610 }
2611
2612 /* Allocate buffer for overwriting with zeroes. */
2613 pvZero = RTMemAllocZ(cbBlock);
2614 if (!pvZero)
2615 {
2616 rc = VERR_NO_MEMORY;
2617 break;
2618 }
2619
2620 for (unsigned i = 0; i < cBlocksReloc; i++)
2621 {
2622 uint32_t uBlock = offStartDataNew / VHD_SECTOR_SIZE;
2623
2624 /* Search the index in the block table. */
2625 for (unsigned idxBlock = 0; idxBlock < cBlocksOld; idxBlock++)
2626 {
2627 if (pImage->pBlockAllocationTable[idxBlock] == uBlock)
2628 {
2629 /* Read data and append to the end of the image. */
2630 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage,
2631 offStartDataNew, pvBuf, cbBlock);
2632 if (RT_FAILURE(rc))
2633 break;
2634
2635 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage,
2636 pImage->uCurrentEndOfFile, pvBuf, cbBlock);
2637 if (RT_FAILURE(rc))
2638 break;
2639
2640 /* Zero out the old block area. */
2641 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage,
2642 offStartDataNew, pvZero, cbBlock);
2643 if (RT_FAILURE(rc))
2644 break;
2645
2646 /* Update block counter. */
2647 pImage->pBlockAllocationTable[idxBlock] = pImage->uCurrentEndOfFile / VHD_SECTOR_SIZE;
2648
2649 pImage->uCurrentEndOfFile += cbBlock;
2650
2651 /* Continue with the next block. */
2652 break;
2653 }
2654 }
2655
2656 if (RT_FAILURE(rc))
2657 break;
2658
2659 offStartDataNew += cbBlock;
2660 }
2661 } while (0);
2662
2663 if (pvBuf)
2664 RTMemFree(pvBuf);
2665 if (pvZero)
2666 RTMemFree(pvZero);
2667 }
2668
2669 /*
2670 * Relocation done, expand the block array and update the header with
2671 * the new data.
2672 */
2673 if (RT_SUCCESS(rc))
2674 {
2675 uint32_t *paBlocksNew = (uint32_t *)RTMemRealloc(pImage->pBlockAllocationTable, cBlocksNew * sizeof(uint32_t));
2676 if (paBlocksNew)
2677 {
2678 pImage->pBlockAllocationTable = paBlocksNew;
2679
2680 /* Mark the new blocks as unallocated. */
2681 for (unsigned idxBlock = cBlocksOld; idxBlock < cBlocksNew; idxBlock++)
2682 pImage->pBlockAllocationTable[idxBlock] = ~0U;
2683 }
2684 else
2685 rc = VERR_NO_MEMORY;
2686
2687 if (RT_SUCCESS(rc))
2688 {
2689 /* Write the block array before updating the rest. */
2690 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage,
2691 pImage->uBlockAllocationTableOffset,
2692 pImage->pBlockAllocationTable,
2693 cBlocksNew * sizeof(uint32_t));
2694 }
2695
2696 if (RT_SUCCESS(rc))
2697 {
2698 /* Update size and new block count. */
2699 pImage->cBlockAllocationTableEntries = cBlocksNew;
2700 pImage->cbSize = cbSize;
2701
2702 /* Update geometry. */
2703 pImage->PCHSGeometry = *pPCHSGeometry;
2704 pImage->LCHSGeometry = *pLCHSGeometry;
2705 }
2706 }
2707
2708 /* Update header information in base image file. */
2709 pImage->fDynHdrNeedsUpdate = true;
2710 vhdFlushImage(pImage);
2711 }
2712 /* Same size doesn't change the image at all. */
2713
2714 LogFlowFunc(("returns %Rrc\n", rc));
2715 return rc;
2716}
2717
2718/** @interface_method_impl{VDIMAGEBACKEND,pfnRepair} */
2719static DECLCALLBACK(int) vhdRepair(const char *pszFilename, PVDINTERFACE pVDIfsDisk,
2720 PVDINTERFACE pVDIfsImage, uint32_t fFlags)
2721{
2722 LogFlowFunc(("pszFilename=\"%s\" pVDIfsDisk=%#p pVDIfsImage=%#p\n", pszFilename, pVDIfsDisk, pVDIfsImage));
2723 int rc;
2724 PVDINTERFACEERROR pIfError;
2725 PVDINTERFACEIOINT pIfIo;
2726 PVDIOSTORAGE pStorage;
2727 uint64_t cbFile;
2728 VHDFooter vhdFooter;
2729 VHDDynamicDiskHeader dynamicDiskHeader;
2730 uint32_t *paBat = NULL;
2731 uint32_t *pu32BlockBitmap = NULL;
2732
2733 pIfIo = VDIfIoIntGet(pVDIfsImage);
2734 AssertPtrReturn(pIfIo, VERR_INVALID_PARAMETER);
2735
2736 pIfError = VDIfErrorGet(pVDIfsDisk);
2737
2738 do
2739 {
2740 uint64_t offDynamicDiskHeader = 0;
2741 uint64_t offBat = 0;
2742 uint64_t offFooter = 0;
2743 uint32_t cBatEntries = 0;
2744 bool fDynamic = false;
2745 bool fRepairFooter = false;
2746 bool fRepairBat = false;
2747 bool fRepairDynHeader = false;
2748
2749 rc = vdIfIoIntFileOpen(pIfIo, pszFilename,
2750 VDOpenFlagsToFileOpenFlags( fFlags & VD_REPAIR_DRY_RUN
2751 ? VD_OPEN_FLAGS_READONLY
2752 : 0,
2753 false /* fCreate */),
2754 &pStorage);
2755 if (RT_FAILURE(rc))
2756 {
2757 rc = vdIfError(pIfError, rc, RT_SRC_POS, "Failed to open image \"%s\"", pszFilename);
2758 break;
2759 }
2760
2761 rc = vdIfIoIntFileGetSize(pIfIo, pStorage, &cbFile);
2762 if (RT_FAILURE(rc))
2763 {
2764 rc = vdIfError(pIfError, rc, RT_SRC_POS, "Failed to query image size");
2765 break;
2766 }
2767
2768 if (cbFile < sizeof(VHDFooter))
2769 {
2770 rc = vdIfError(pIfError, VERR_VD_INVALID_SIZE, RT_SRC_POS,
2771 "Image must be at least %u bytes (got %llu)",
2772 sizeof(VHDFooter), cbFile);
2773 break;
2774 }
2775
2776 rc = vdIfIoIntFileReadSync(pIfIo, pStorage, cbFile - sizeof(VHDFooter),
2777 &vhdFooter, sizeof(VHDFooter));
2778 if (RT_FAILURE(rc))
2779 {
2780 rc = vdIfError(pIfError, rc, RT_SRC_POS, "Failed to read footer of image");
2781 break;
2782 }
2783
2784 if (memcmp(vhdFooter.Cookie, VHD_FOOTER_COOKIE, VHD_FOOTER_COOKIE_SIZE) != 0)
2785 {
2786 /* Dynamic images have a backup at the beginning of the image. */
2787 rc = vdIfIoIntFileReadSync(pIfIo, pStorage, 0,
2788 &vhdFooter, sizeof(VHDFooter));
2789 if (RT_FAILURE(rc))
2790 {
2791 rc = vdIfError(pIfError, rc, RT_SRC_POS, "Failed to read header of image");
2792 break;
2793 }
2794
2795 /*
2796 * Check for the header, if this fails the image is either completely corrupted
2797 * and impossible to repair or in another format.
2798 */
2799 if (memcmp(vhdFooter.Cookie, VHD_FOOTER_COOKIE, VHD_FOOTER_COOKIE_SIZE) != 0)
2800 {
2801 rc = vdIfError(pIfError, VERR_VD_IMAGE_REPAIR_IMPOSSIBLE, RT_SRC_POS,
2802 "No valid VHD structures found");
2803 break;
2804 }
2805 else
2806 vdIfErrorMessage(pIfError, "Missing footer structure, using backup\n");
2807
2808 /* Remember to fix the footer structure. */
2809 fRepairFooter = true;
2810 }
2811
2812 offFooter = cbFile - sizeof(VHDFooter);
2813
2814 /* Verify that checksums match. */
2815 uint32_t u32ChkSumOld = RT_BE2H_U32(vhdFooter.Checksum);
2816 vhdFooter.Checksum = 0;
2817 uint32_t u32ChkSum = vhdChecksum(&vhdFooter, sizeof(VHDFooter));
2818
2819 vhdFooter.Checksum = RT_H2BE_U32(u32ChkSum);
2820
2821 if (u32ChkSumOld != u32ChkSum)
2822 {
2823 vdIfErrorMessage(pIfError, "Checksum is invalid (should be %u got %u), repairing\n",
2824 u32ChkSum, u32ChkSumOld);
2825 fRepairFooter = true;
2826 break;
2827 }
2828
2829 switch (RT_BE2H_U32(vhdFooter.DiskType))
2830 {
2831 case VHD_FOOTER_DISK_TYPE_FIXED:
2832 fDynamic = false;
2833 break;
2834 case VHD_FOOTER_DISK_TYPE_DYNAMIC:
2835 fDynamic = true;
2836 break;
2837 case VHD_FOOTER_DISK_TYPE_DIFFERENCING:
2838 fDynamic = true;
2839 break;
2840 default:
2841 {
2842 rc = vdIfError(pIfError, VERR_VD_IMAGE_REPAIR_IMPOSSIBLE, RT_SRC_POS,
2843 "VHD image type %u is not supported",
2844 RT_BE2H_U32(vhdFooter.DiskType));
2845 break;
2846 }
2847 }
2848
2849 /* Load and check dynamic disk header if required. */
2850 if (fDynamic)
2851 {
2852 size_t cbBlock;
2853
2854 offDynamicDiskHeader = RT_BE2H_U64(vhdFooter.DataOffset);
2855 if (offDynamicDiskHeader + sizeof(VHDDynamicDiskHeader) > cbFile)
2856 {
2857 rc = vdIfError(pIfError, VERR_VD_IMAGE_REPAIR_IMPOSSIBLE, RT_SRC_POS,
2858 "VHD image type is not supported");
2859 break;
2860 }
2861
2862 rc = vdIfIoIntFileReadSync(pIfIo, pStorage, offDynamicDiskHeader,
2863 &dynamicDiskHeader, sizeof(VHDDynamicDiskHeader));
2864 if (RT_FAILURE(rc))
2865 {
2866 rc = vdIfError(pIfError, VERR_VD_IMAGE_REPAIR_IMPOSSIBLE, RT_SRC_POS,
2867 "Failed to read dynamic disk header (at %llu), %Rrc",
2868 offDynamicDiskHeader, rc);
2869 break;
2870 }
2871
2872 /* Verify that checksums match. */
2873 u32ChkSumOld = RT_BE2H_U32(dynamicDiskHeader.Checksum);
2874 dynamicDiskHeader.Checksum = 0;
2875 u32ChkSum = vhdChecksum(&dynamicDiskHeader, sizeof(VHDDynamicDiskHeader));
2876
2877 dynamicDiskHeader.Checksum = RT_H2BE_U32(u32ChkSum);
2878
2879 if (u32ChkSumOld != u32ChkSum)
2880 {
2881 vdIfErrorMessage(pIfError, "Checksum of dynamic disk header is invalid (should be %u got %u), repairing\n",
2882 u32ChkSum, u32ChkSumOld);
2883 fRepairDynHeader = true;
2884 break;
2885 }
2886
2887 /* Read the block allocation table and fix any inconsistencies. */
2888 offBat = RT_BE2H_U64(dynamicDiskHeader.TableOffset);
2889 cBatEntries = RT_BE2H_U32(dynamicDiskHeader.MaxTableEntries);
2890 cbBlock = RT_BE2H_U32(dynamicDiskHeader.BlockSize);
2891 cbBlock += cbBlock / VHD_SECTOR_SIZE / 8;
2892
2893 if (offBat + cBatEntries * sizeof(uint32_t) > cbFile)
2894 {
2895 rc = vdIfError(pIfError, VERR_VD_IMAGE_REPAIR_IMPOSSIBLE, RT_SRC_POS,
2896 "Block allocation table is not inside the image");
2897 break;
2898 }
2899
2900 paBat = (uint32_t *)RTMemAllocZ(cBatEntries * sizeof(uint32_t));
2901 if (!paBat)
2902 {
2903 rc = vdIfError(pIfError, VERR_VD_IMAGE_REPAIR_IMPOSSIBLE, RT_SRC_POS,
2904 "Could not allocate memory for the block allocation table (%u bytes)",
2905 cBatEntries * sizeof(uint32_t));
2906 break;
2907 }
2908
2909 rc = vdIfIoIntFileReadSync(pIfIo, pStorage, offBat, paBat,
2910 cBatEntries * sizeof(uint32_t));
2911 if (RT_FAILURE(rc))
2912 {
2913 rc = vdIfError(pIfError, VERR_VD_IMAGE_REPAIR_IMPOSSIBLE, RT_SRC_POS,
2914 "Could not read block allocation table (at %llu), %Rrc",
2915 offBat, rc);
2916 break;
2917 }
2918
2919 pu32BlockBitmap = (uint32_t *)RTMemAllocZ(RT_ALIGN_Z(cBatEntries / 8, 4));
2920 if (!pu32BlockBitmap)
2921 {
2922 rc = vdIfError(pIfError, VERR_NO_MEMORY, RT_SRC_POS,
2923 "Failed to allocate memory for block bitmap");
2924 break;
2925 }
2926
2927 uint32_t idxMinBlock = UINT32_C(0xffffffff);
2928 for (uint32_t i = 0; i < cBatEntries; i++)
2929 {
2930 paBat[i] = RT_BE2H_U32(paBat[i]);
2931 if (paBat[i] < idxMinBlock)
2932 idxMinBlock = paBat[i];
2933 }
2934
2935 vdIfErrorMessage(pIfError, "First data block at sector %u\n", idxMinBlock);
2936
2937 for (uint32_t i = 0; i < cBatEntries; i++)
2938 {
2939 if (paBat[i] != UINT32_C(0xffffffff))
2940 {
2941 uint64_t offBlock =(uint64_t)paBat[i] * VHD_SECTOR_SIZE;
2942
2943 /*
2944 * Check that the offsets are valid (inside of the image) and
2945 * that there are no double references.
2946 */
2947 if (offBlock + cbBlock > cbFile)
2948 {
2949 vdIfErrorMessage(pIfError, "Entry %u points to invalid offset %llu, clearing\n",
2950 i, offBlock);
2951 paBat[i] = UINT32_C(0xffffffff);
2952 fRepairBat = true;
2953 }
2954 else if (offBlock + cbBlock > offFooter)
2955 {
2956 vdIfErrorMessage(pIfError, "Entry %u intersects with footer, aligning footer\n",
2957 i);
2958 offFooter = offBlock + cbBlock;
2959 fRepairBat = true;
2960 }
2961
2962 if ( paBat[i] != UINT32_C(0xffffffff)
2963 && ASMBitTestAndSet(pu32BlockBitmap, (uint32_t)((paBat[i] - idxMinBlock) / (cbBlock / VHD_SECTOR_SIZE))))
2964 {
2965 vdIfErrorMessage(pIfError, "Entry %u points to an already referenced data block, clearing\n",
2966 i);
2967 paBat[i] = UINT32_C(0xffffffff);
2968 fRepairBat = true;
2969 }
2970 }
2971 }
2972 }
2973
2974 /* Write repaired structures now. */
2975 if (!(fRepairBat || fRepairDynHeader || fRepairFooter))
2976 vdIfErrorMessage(pIfError, "VHD image is in a consistent state, no repair required\n");
2977 else if (!(fFlags & VD_REPAIR_DRY_RUN))
2978 {
2979 if (fRepairBat)
2980 {
2981 for (uint32_t i = 0; i < cBatEntries; i++)
2982 paBat[i] = RT_H2BE_U32(paBat[i]);
2983
2984 vdIfErrorMessage(pIfError, "Writing repaired block allocation table...\n");
2985
2986 rc = vdIfIoIntFileWriteSync(pIfIo, pStorage, offBat, paBat,
2987 cBatEntries * sizeof(uint32_t));
2988 if (RT_FAILURE(rc))
2989 {
2990 rc = vdIfError(pIfError, VERR_VD_IMAGE_REPAIR_IMPOSSIBLE, RT_SRC_POS,
2991 "Could not write repaired block allocation table (at %llu), %Rrc",
2992 offBat, rc);
2993 break;
2994 }
2995 }
2996
2997 if (fRepairDynHeader)
2998 {
2999 Assert(fDynamic);
3000
3001 vdIfErrorMessage(pIfError, "Writing repaired dynamic disk header...\n");
3002 rc = vdIfIoIntFileWriteSync(pIfIo, pStorage, offDynamicDiskHeader, &dynamicDiskHeader,
3003 sizeof(VHDDynamicDiskHeader));
3004 if (RT_FAILURE(rc))
3005 {
3006 rc = vdIfError(pIfError, VERR_VD_IMAGE_REPAIR_IMPOSSIBLE, RT_SRC_POS,
3007 "Could not write repaired dynamic disk header (at %llu), %Rrc",
3008 offDynamicDiskHeader, rc);
3009 break;
3010 }
3011 }
3012
3013 if (fRepairFooter)
3014 {
3015 vdIfErrorMessage(pIfError, "Writing repaired Footer...\n");
3016
3017 if (fDynamic)
3018 {
3019 /* Write backup at image beginning. */
3020 rc = vdIfIoIntFileWriteSync(pIfIo, pStorage, 0, &vhdFooter,
3021 sizeof(VHDFooter));
3022 if (RT_FAILURE(rc))
3023 {
3024 rc = vdIfError(pIfError, VERR_VD_IMAGE_REPAIR_IMPOSSIBLE, RT_SRC_POS,
3025 "Could not write repaired backup footer (at %llu), %Rrc",
3026 0, rc);
3027 break;
3028 }
3029 }
3030
3031 rc = vdIfIoIntFileWriteSync(pIfIo, pStorage, offFooter, &vhdFooter,
3032 sizeof(VHDFooter));
3033 if (RT_FAILURE(rc))
3034 {
3035 rc = vdIfError(pIfError, VERR_VD_IMAGE_REPAIR_IMPOSSIBLE, RT_SRC_POS,
3036 "Could not write repaired footer (at %llu), %Rrc",
3037 cbFile - sizeof(VHDFooter), rc);
3038 break;
3039 }
3040 }
3041
3042 vdIfErrorMessage(pIfError, "Corrupted VHD image repaired successfully\n");
3043 }
3044 } while(0);
3045
3046 if (paBat)
3047 RTMemFree(paBat);
3048
3049 if (pu32BlockBitmap)
3050 RTMemFree(pu32BlockBitmap);
3051
3052 if (pStorage)
3053 {
3054 int rc2 = vdIfIoIntFileClose(pIfIo, pStorage);
3055 if (RT_SUCCESS(rc))
3056 rc = rc2; /* Propagate status code only when repairing the image was successful. */
3057 }
3058
3059 LogFlowFunc(("returns %Rrc\n", rc));
3060 return rc;
3061}
3062
3063
3064const VDIMAGEBACKEND g_VhdBackend =
3065{
3066 /* u32Version */
3067 VD_IMGBACKEND_VERSION,
3068 /* pszBackendName */
3069 "VHD",
3070 /* uBackendCaps */
3071 VD_CAP_UUID | VD_CAP_DIFF | VD_CAP_FILE |
3072 VD_CAP_CREATE_FIXED | VD_CAP_CREATE_DYNAMIC |
3073 VD_CAP_ASYNC | VD_CAP_VFS | VD_CAP_PREFERRED,
3074 /* paFileExtensions */
3075 s_aVhdFileExtensions,
3076 /* paConfigInfo */
3077 NULL,
3078 /* pfnProbe */
3079 vhdProbe,
3080 /* pfnOpen */
3081 vhdOpen,
3082 /* pfnCreate */
3083 vhdCreate,
3084 /* pfnRename */
3085 vhdRename,
3086 /* pfnClose */
3087 vhdClose,
3088 /* pfnRead */
3089 vhdRead,
3090 /* pfnWrite */
3091 vhdWrite,
3092 /* pfnFlush */
3093 vhdFlush,
3094 /* pfnDiscard */
3095 NULL,
3096 /* pfnGetVersion */
3097 vhdGetVersion,
3098 /* pfnGetFileSize */
3099 vhdGetFileSize,
3100 /* pfnGetPCHSGeometry */
3101 vhdGetPCHSGeometry,
3102 /* pfnSetPCHSGeometry */
3103 vhdSetPCHSGeometry,
3104 /* pfnGetLCHSGeometry */
3105 vhdGetLCHSGeometry,
3106 /* pfnSetLCHSGeometry */
3107 vhdSetLCHSGeometry,
3108 /* pfnQueryRegions */
3109 vhdQueryRegions,
3110 /* pfnRegionListRelease */
3111 vhdRegionListRelease,
3112 /* pfnGetImageFlags */
3113 vhdGetImageFlags,
3114 /* pfnGetOpenFlags */
3115 vhdGetOpenFlags,
3116 /* pfnSetOpenFlags */
3117 vhdSetOpenFlags,
3118 /* pfnGetComment */
3119 vhdGetComment,
3120 /* pfnSetComment */
3121 vhdSetComment,
3122 /* pfnGetUuid */
3123 vhdGetUuid,
3124 /* pfnSetUuid */
3125 vhdSetUuid,
3126 /* pfnGetModificationUuid */
3127 vhdGetModificationUuid,
3128 /* pfnSetModificationUuid */
3129 vhdSetModificationUuid,
3130 /* pfnGetParentUuid */
3131 vhdGetParentUuid,
3132 /* pfnSetParentUuid */
3133 vhdSetParentUuid,
3134 /* pfnGetParentModificationUuid */
3135 vhdGetParentModificationUuid,
3136 /* pfnSetParentModificationUuid */
3137 vhdSetParentModificationUuid,
3138 /* pfnDump */
3139 vhdDump,
3140 /* pfnGetTimestamp */
3141 vhdGetTimestamp,
3142 /* pfnGetParentTimestamp */
3143 vhdGetParentTimestamp,
3144 /* pfnSetParentTimestamp */
3145 vhdSetParentTimestamp,
3146 /* pfnGetParentFilename */
3147 vhdGetParentFilename,
3148 /* pfnSetParentFilename */
3149 vhdSetParentFilename,
3150 /* pfnComposeLocation */
3151 genericFileComposeLocation,
3152 /* pfnComposeName */
3153 genericFileComposeName,
3154 /* pfnCompact */
3155 vhdCompact,
3156 /* pfnResize */
3157 vhdResize,
3158 /* pfnRepair */
3159 vhdRepair,
3160 /* pfnTraverseMetadata */
3161 NULL,
3162 /* u32VersionEnd */
3163 VD_IMGBACKEND_VERSION
3164};
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