VirtualBox

source: vbox/trunk/src/VBox/Storage/VDI.cpp@ 103524

Last change on this file since 103524 was 103524, checked in by vboxsync, 4 months ago

Storage/VDI.cpp: Some unused variable and macro double expansion fixes, bugref:3409

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 128.3 KB
Line 
1/* $Id: VDI.cpp 103524 2024-02-22 11:17:44Z vboxsync $ */
2/** @file
3 * Virtual Disk Image (VDI), Core Code.
4 */
5
6/*
7 * Copyright (C) 2006-2023 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * SPDX-License-Identifier: GPL-3.0-only
26 */
27
28
29/*********************************************************************************************************************************
30* Header Files *
31*********************************************************************************************************************************/
32#define LOG_GROUP LOG_GROUP_VD_VDI
33#include <VBox/vd-plugin.h>
34#include "VDICore.h"
35#include <VBox/err.h>
36
37#include <VBox/log.h>
38#include <iprt/alloc.h>
39#include <iprt/assert.h>
40#include <iprt/uuid.h>
41#include <iprt/string.h>
42#include <iprt/asm.h>
43
44#include "VDBackends.h"
45
46#define VDI_IMAGE_DEFAULT_BLOCK_SIZE _1M
47
48/** Macros for endianess conversion. */
49#define SET_ENDIAN_U32(conv, u32) (conv == VDIECONV_H2F ? RT_H2LE_U32(u32) : RT_LE2H_U32(u32))
50#define SET_ENDIAN_U64(conv, u64) (conv == VDIECONV_H2F ? RT_H2LE_U64(u64) : RT_LE2H_U64(u64))
51
52static const char *vdiAllocationBlockSize = "1048576";
53
54static const VDCONFIGINFO vdiConfigInfo[] =
55{
56 { "AllocationBlockSize", vdiAllocationBlockSize, VDCFGVALUETYPE_INTEGER, VD_CFGKEY_CREATEONLY },
57 { NULL, NULL, VDCFGVALUETYPE_INTEGER, 0 }
58};
59
60
61/*********************************************************************************************************************************
62* Static Variables *
63*********************************************************************************************************************************/
64
65/** NULL-terminated array of supported file extensions. */
66static const VDFILEEXTENSION s_aVdiFileExtensions[] =
67{
68 {"vdi", VDTYPE_HDD},
69 {NULL, VDTYPE_INVALID}
70};
71
72
73/*********************************************************************************************************************************
74* Internal Functions *
75*********************************************************************************************************************************/
76static unsigned getPowerOfTwo(unsigned uNumber);
77static void vdiInitPreHeader(PVDIPREHEADER pPreHdr);
78static int vdiValidatePreHeader(PVDIPREHEADER pPreHdr);
79static int vdiValidateHeader(PVDIHEADER pHeader);
80static void vdiSetupImageDesc(PVDIIMAGEDESC pImage);
81static int vdiUpdateHeader(PVDIIMAGEDESC pImage);
82static int vdiUpdateBlockInfo(PVDIIMAGEDESC pImage, unsigned uBlock);
83static int vdiUpdateHeaderAsync(PVDIIMAGEDESC pImage, PVDIOCTX pIoCtx);
84static int vdiUpdateBlockInfoAsync(PVDIIMAGEDESC pImage, unsigned uBlock, PVDIOCTX pIoCtx,
85 bool fUpdateHdr);
86
87/**
88 * Internal: Convert the PreHeader fields to the appropriate endianess.
89 * @param enmConv Direction of the conversion.
90 * @param pPreHdrConv Where to store the converted pre header.
91 * @param pPreHdr PreHeader pointer.
92 */
93static void vdiConvPreHeaderEndianess(VDIECONV enmConv, PVDIPREHEADER pPreHdrConv,
94 PVDIPREHEADER pPreHdr)
95{
96 memcpy(pPreHdrConv->szFileInfo, pPreHdr->szFileInfo, sizeof(pPreHdr->szFileInfo));
97 pPreHdrConv->u32Signature = SET_ENDIAN_U32(enmConv, pPreHdr->u32Signature);
98 pPreHdrConv->u32Version = SET_ENDIAN_U32(enmConv, pPreHdr->u32Version);
99}
100
101/**
102 * Internal: Convert the VDIDISKGEOMETRY fields to the appropriate endianess.
103 * @param enmConv Direction of the conversion.
104 * @param pDiskGeoConv Where to store the converted geometry.
105 * @param pDiskGeo Pointer to the disk geometry to convert.
106 */
107static void vdiConvGeometryEndianess(VDIECONV enmConv, PVDIDISKGEOMETRY pDiskGeoConv,
108 PVDIDISKGEOMETRY pDiskGeo)
109{
110 pDiskGeoConv->cCylinders = SET_ENDIAN_U32(enmConv, pDiskGeo->cCylinders);
111 pDiskGeoConv->cHeads = SET_ENDIAN_U32(enmConv, pDiskGeo->cHeads);
112 pDiskGeoConv->cSectors = SET_ENDIAN_U32(enmConv, pDiskGeo->cSectors);
113 pDiskGeoConv->cbSector = SET_ENDIAN_U32(enmConv, pDiskGeo->cbSector);
114}
115
116/**
117 * Internal: Convert the Header - version 0 fields to the appropriate endianess.
118 * @param enmConv Direction of the conversion.
119 * @param pHdrConv Where to store the converted header.
120 * @param pHdr Pointer to the version 0 header.
121 */
122static void vdiConvHeaderEndianessV0(VDIECONV enmConv, PVDIHEADER0 pHdrConv,
123 PVDIHEADER0 pHdr)
124{
125 memmove(pHdrConv->szComment, pHdr->szComment, sizeof(pHdr->szComment));
126 pHdrConv->u32Type = SET_ENDIAN_U32(enmConv, pHdr->u32Type);
127 pHdrConv->fFlags = SET_ENDIAN_U32(enmConv, pHdr->fFlags);
128 vdiConvGeometryEndianess(enmConv, &pHdrConv->LegacyGeometry, &pHdr->LegacyGeometry);
129 pHdrConv->cbDisk = SET_ENDIAN_U64(enmConv, pHdr->cbDisk);
130 pHdrConv->cbBlock = SET_ENDIAN_U32(enmConv, pHdr->cbBlock);
131 pHdrConv->cBlocks = SET_ENDIAN_U32(enmConv, pHdr->cBlocks);
132 pHdrConv->cBlocksAllocated = SET_ENDIAN_U32(enmConv, pHdr->cBlocksAllocated);
133 /* Don't convert the RTUUID fields. */
134 pHdrConv->uuidCreate = pHdr->uuidCreate;
135 pHdrConv->uuidModify = pHdr->uuidModify;
136 pHdrConv->uuidLinkage = pHdr->uuidLinkage;
137}
138
139/**
140 * Internal: Set the Header - version 1 fields to the appropriate endianess.
141 * @param enmConv Direction of the conversion.
142 * @param pHdrConv Where to store the converted header.
143 * @param pHdr Version 1 Header pointer.
144 */
145static void vdiConvHeaderEndianessV1(VDIECONV enmConv, PVDIHEADER1 pHdrConv,
146 PVDIHEADER1 pHdr)
147{
148 memmove(pHdrConv->szComment, pHdr->szComment, sizeof(pHdr->szComment));
149 pHdrConv->cbHeader = SET_ENDIAN_U32(enmConv, pHdr->cbHeader);
150 pHdrConv->u32Type = SET_ENDIAN_U32(enmConv, pHdr->u32Type);
151 pHdrConv->fFlags = SET_ENDIAN_U32(enmConv, pHdr->fFlags);
152 pHdrConv->offBlocks = SET_ENDIAN_U32(enmConv, pHdr->offBlocks);
153 pHdrConv->offData = SET_ENDIAN_U32(enmConv, pHdr->offData);
154 vdiConvGeometryEndianess(enmConv, &pHdrConv->LegacyGeometry, &pHdr->LegacyGeometry);
155 pHdrConv->u32Dummy = SET_ENDIAN_U32(enmConv, pHdr->u32Dummy);
156 pHdrConv->cbDisk = SET_ENDIAN_U64(enmConv, pHdr->cbDisk);
157 pHdrConv->cbBlock = SET_ENDIAN_U32(enmConv, pHdr->cbBlock);
158 pHdrConv->cbBlockExtra = SET_ENDIAN_U32(enmConv, pHdr->cbBlockExtra);
159 pHdrConv->cBlocks = SET_ENDIAN_U32(enmConv, pHdr->cBlocks);
160 pHdrConv->cBlocksAllocated = SET_ENDIAN_U32(enmConv, pHdr->cBlocksAllocated);
161 /* Don't convert the RTUUID fields. */
162 pHdrConv->uuidCreate = pHdr->uuidCreate;
163 pHdrConv->uuidModify = pHdr->uuidModify;
164 pHdrConv->uuidLinkage = pHdr->uuidLinkage;
165 pHdrConv->uuidParentModify = pHdr->uuidParentModify;
166}
167
168/**
169 * Internal: Set the Header - version 1plus fields to the appropriate endianess.
170 * @param enmConv Direction of the conversion.
171 * @param pHdrConv Where to store the converted header.
172 * @param pHdr Version 1+ Header pointer.
173 */
174static void vdiConvHeaderEndianessV1p(VDIECONV enmConv, PVDIHEADER1PLUS pHdrConv,
175 PVDIHEADER1PLUS pHdr)
176{
177 memmove(pHdrConv->szComment, pHdr->szComment, sizeof(pHdr->szComment));
178 pHdrConv->cbHeader = SET_ENDIAN_U32(enmConv, pHdr->cbHeader);
179 pHdrConv->u32Type = SET_ENDIAN_U32(enmConv, pHdr->u32Type);
180 pHdrConv->fFlags = SET_ENDIAN_U32(enmConv, pHdr->fFlags);
181 pHdrConv->offBlocks = SET_ENDIAN_U32(enmConv, pHdr->offBlocks);
182 pHdrConv->offData = SET_ENDIAN_U32(enmConv, pHdr->offData);
183 vdiConvGeometryEndianess(enmConv, &pHdrConv->LegacyGeometry, &pHdr->LegacyGeometry);
184 pHdrConv->u32Dummy = SET_ENDIAN_U32(enmConv, pHdr->u32Dummy);
185 pHdrConv->cbDisk = SET_ENDIAN_U64(enmConv, pHdr->cbDisk);
186 pHdrConv->cbBlock = SET_ENDIAN_U32(enmConv, pHdr->cbBlock);
187 pHdrConv->cbBlockExtra = SET_ENDIAN_U32(enmConv, pHdr->cbBlockExtra);
188 pHdrConv->cBlocks = SET_ENDIAN_U32(enmConv, pHdr->cBlocks);
189 pHdrConv->cBlocksAllocated = SET_ENDIAN_U32(enmConv, pHdr->cBlocksAllocated);
190 /* Don't convert the RTUUID fields. */
191 pHdrConv->uuidCreate = pHdr->uuidCreate;
192 pHdrConv->uuidModify = pHdr->uuidModify;
193 pHdrConv->uuidLinkage = pHdr->uuidLinkage;
194 pHdrConv->uuidParentModify = pHdr->uuidParentModify;
195 vdiConvGeometryEndianess(enmConv, &pHdrConv->LCHSGeometry, &pHdr->LCHSGeometry);
196}
197
198
199/**
200 * Internal: Set the appropriate endianess on all the Blocks pointed.
201 * @param enmConv Direction of the conversion.
202 * @param paBlocks Pointer to the block array.
203 * @param cEntries Number of entries in the block array.
204 *
205 * @note Unlike the other conversion functions this method does an in place conversion
206 * to avoid temporary memory allocations when writing the block array.
207 */
208static void vdiConvBlocksEndianess(VDIECONV enmConv, PVDIIMAGEBLOCKPOINTER paBlocks,
209 unsigned cEntries)
210{
211 for (unsigned i = 0; i < cEntries; i++)
212 paBlocks[i] = SET_ENDIAN_U32(enmConv, paBlocks[i]);
213}
214
215/**
216 * Internal: Flush the image file to disk.
217 */
218static void vdiFlushImage(PVDIIMAGEDESC pImage)
219{
220 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
221 {
222 /* Save header. */
223 int rc = vdiUpdateHeader(pImage);
224 AssertMsgRC(rc, ("vdiUpdateHeader() failed, filename=\"%s\", rc=%Rrc\n",
225 pImage->pszFilename, rc));
226 vdIfIoIntFileFlushSync(pImage->pIfIo, pImage->pStorage);
227 }
228}
229
230/**
231 * Internal: Free all allocated space for representing an image, and optionally
232 * delete the image from disk.
233 */
234static int vdiFreeImage(PVDIIMAGEDESC pImage, bool fDelete)
235{
236 int rc = VINF_SUCCESS;
237
238 /* Freeing a never allocated image (e.g. because the open failed) is
239 * not signalled as an error. After all nothing bad happens. */
240 if (pImage)
241 {
242 if (pImage->pStorage)
243 {
244 /* No point updating the file that is deleted anyway. */
245 if (!fDelete)
246 vdiFlushImage(pImage);
247
248 rc = vdIfIoIntFileClose(pImage->pIfIo, pImage->pStorage);
249 pImage->pStorage = NULL;
250 }
251
252 if (pImage->paBlocks)
253 {
254 RTMemFree(pImage->paBlocks);
255 pImage->paBlocks = NULL;
256 }
257
258 if (pImage->paBlocksRev)
259 {
260 RTMemFree(pImage->paBlocksRev);
261 pImage->paBlocksRev = NULL;
262 }
263
264 if (fDelete && pImage->pszFilename)
265 {
266 int rc2 = vdIfIoIntFileDelete(pImage->pIfIo, pImage->pszFilename);
267 if (RT_SUCCESS(rc))
268 rc = rc2;
269 }
270 }
271
272 LogFlowFunc(("returns %Rrc\n", rc));
273 return rc;
274}
275
276/**
277 * internal: return power of 2 or 0 if num error.
278 */
279static unsigned getPowerOfTwo(unsigned uNumber)
280{
281 if (uNumber == 0)
282 return 0;
283 unsigned uPower2 = 0;
284 while ((uNumber & 1) == 0)
285 {
286 uNumber >>= 1;
287 uPower2++;
288 }
289 return uNumber == 1 ? uPower2 : 0;
290}
291
292/**
293 * Internal: Init VDI preheader.
294 */
295static void vdiInitPreHeader(PVDIPREHEADER pPreHdr)
296{
297 pPreHdr->u32Signature = VDI_IMAGE_SIGNATURE;
298 pPreHdr->u32Version = VDI_IMAGE_VERSION;
299 memset(pPreHdr->szFileInfo, 0, sizeof(pPreHdr->szFileInfo));
300 strncat(pPreHdr->szFileInfo, VDI_IMAGE_FILE_INFO, sizeof(pPreHdr->szFileInfo)-1);
301}
302
303/**
304 * Internal: check VDI preheader.
305 */
306static int vdiValidatePreHeader(PVDIPREHEADER pPreHdr)
307{
308 if (pPreHdr->u32Signature != VDI_IMAGE_SIGNATURE)
309 return VERR_VD_VDI_INVALID_HEADER;
310
311 if ( VDI_GET_VERSION_MAJOR(pPreHdr->u32Version) != VDI_IMAGE_VERSION_MAJOR
312 && pPreHdr->u32Version != 0x00000002) /* old version. */
313 return VERR_VD_VDI_UNSUPPORTED_VERSION;
314
315 return VINF_SUCCESS;
316}
317
318/**
319 * Internal: translate VD image flags to VDI image type enum.
320 */
321static VDIIMAGETYPE vdiTranslateImageFlags2VDI(unsigned uImageFlags)
322{
323 if (uImageFlags & VD_IMAGE_FLAGS_FIXED)
324 return VDI_IMAGE_TYPE_FIXED;
325 else if (uImageFlags & VD_IMAGE_FLAGS_DIFF)
326 return VDI_IMAGE_TYPE_DIFF;
327 else
328 return VDI_IMAGE_TYPE_NORMAL;
329}
330
331/**
332 * Internal: translate VDI image type enum to VD image type enum.
333 */
334static unsigned vdiTranslateVDI2ImageFlags(VDIIMAGETYPE enmType)
335{
336 switch (enmType)
337 {
338 case VDI_IMAGE_TYPE_NORMAL:
339 return VD_IMAGE_FLAGS_NONE;
340 case VDI_IMAGE_TYPE_FIXED:
341 return VD_IMAGE_FLAGS_FIXED;
342 case VDI_IMAGE_TYPE_DIFF:
343 return VD_IMAGE_FLAGS_DIFF;
344 default:
345 AssertMsgFailed(("invalid VDIIMAGETYPE enmType=%d\n", (int)enmType));
346 return VD_IMAGE_FLAGS_NONE;
347 }
348}
349
350/**
351 * Internal: Init VDI header. Always use latest header version.
352 *
353 * @param pHeader Assumes it was initially initialized to all zeros.
354 * @param uImageFlags Flags for this image.
355 * @param pszComment Optional comment to set for the image.
356 * @param cbDisk Size of the disk in bytes.
357 * @param cbBlock Size of one block in the image.
358 * @param cbBlockExtra Extra data for one block private to the image.
359 * @param cbDataAlign The alignment for all data structures.
360 */
361static void vdiInitHeader(PVDIHEADER pHeader, uint32_t uImageFlags,
362 const char *pszComment, uint64_t cbDisk,
363 uint32_t cbBlock, uint32_t cbBlockExtra,
364 uint32_t cbDataAlign)
365{
366 pHeader->uVersion = VDI_IMAGE_VERSION;
367 pHeader->u.v1plus.cbHeader = sizeof(VDIHEADER1PLUS);
368 pHeader->u.v1plus.u32Type = (uint32_t)vdiTranslateImageFlags2VDI(uImageFlags);
369 pHeader->u.v1plus.fFlags = (uImageFlags & VD_VDI_IMAGE_FLAGS_ZERO_EXPAND) ? 1 : 0;
370#ifdef VBOX_STRICT
371 char achZero[VDI_IMAGE_COMMENT_SIZE] = {0};
372 Assert(!memcmp(pHeader->u.v1plus.szComment, achZero, VDI_IMAGE_COMMENT_SIZE));
373#endif
374 pHeader->u.v1plus.szComment[0] = '\0';
375 if (pszComment)
376 {
377 AssertMsg(strlen(pszComment) < sizeof(pHeader->u.v1plus.szComment),
378 ("HDD Comment is too long, cb=%d\n", strlen(pszComment)));
379 strncat(pHeader->u.v1plus.szComment, pszComment, sizeof(pHeader->u.v1plus.szComment)-1);
380 }
381
382 /* Mark the legacy geometry not-calculated. */
383 pHeader->u.v1plus.LegacyGeometry.cCylinders = 0;
384 pHeader->u.v1plus.LegacyGeometry.cHeads = 0;
385 pHeader->u.v1plus.LegacyGeometry.cSectors = 0;
386 pHeader->u.v1plus.LegacyGeometry.cbSector = VDI_GEOMETRY_SECTOR_SIZE;
387 pHeader->u.v1plus.u32Dummy = 0; /* used to be the translation value */
388
389 pHeader->u.v1plus.cbDisk = cbDisk;
390 pHeader->u.v1plus.cbBlock = cbBlock;
391 pHeader->u.v1plus.cBlocks = (uint32_t)(cbDisk / cbBlock);
392 if (cbDisk % cbBlock)
393 pHeader->u.v1plus.cBlocks++;
394 pHeader->u.v1plus.cbBlockExtra = cbBlockExtra;
395 pHeader->u.v1plus.cBlocksAllocated = 0;
396
397 /* Init offsets. */
398 pHeader->u.v1plus.offBlocks = RT_ALIGN_32(sizeof(VDIPREHEADER) + sizeof(VDIHEADER1PLUS), cbDataAlign);
399 pHeader->u.v1plus.offData = RT_ALIGN_32(pHeader->u.v1plus.offBlocks + (pHeader->u.v1plus.cBlocks * sizeof(VDIIMAGEBLOCKPOINTER)), cbDataAlign);
400
401 /* Init uuids. */
402#ifdef _MSC_VER
403# pragma warning(disable:4366) /* (harmless "misalignment") */
404#endif
405 RTUuidCreate(&pHeader->u.v1plus.uuidCreate);
406 RTUuidClear(&pHeader->u.v1plus.uuidModify);
407 RTUuidClear(&pHeader->u.v1plus.uuidLinkage);
408 RTUuidClear(&pHeader->u.v1plus.uuidParentModify);
409#ifdef _MSC_VER
410# pragma warning(default:4366)
411#endif
412
413 /* Mark LCHS geometry not-calculated. */
414 pHeader->u.v1plus.LCHSGeometry.cCylinders = 0;
415 pHeader->u.v1plus.LCHSGeometry.cHeads = 0;
416 pHeader->u.v1plus.LCHSGeometry.cSectors = 0;
417 pHeader->u.v1plus.LCHSGeometry.cbSector = VDI_GEOMETRY_SECTOR_SIZE;
418}
419
420/**
421 * Internal: Check VDI header.
422 */
423static int vdiValidateHeader(PVDIHEADER pHeader)
424{
425 /* Check version-dependent header parameters. */
426 switch (GET_MAJOR_HEADER_VERSION(pHeader))
427 {
428 case 0:
429 {
430 /* Old header version. */
431 break;
432 }
433 case 1:
434 {
435 /* Current header version. */
436
437 if (pHeader->u.v1.cbHeader < sizeof(VDIHEADER1))
438 {
439 LogRel(("VDI: v1 header size wrong (%d < %d)\n",
440 pHeader->u.v1.cbHeader, sizeof(VDIHEADER1)));
441 return VERR_VD_VDI_INVALID_HEADER;
442 }
443
444 if (getImageBlocksOffset(pHeader) < (sizeof(VDIPREHEADER) + sizeof(VDIHEADER1)))
445 {
446 LogRel(("VDI: v1 blocks offset wrong (%d < %d)\n",
447 getImageBlocksOffset(pHeader), sizeof(VDIPREHEADER) + sizeof(VDIHEADER1)));
448 return VERR_VD_VDI_INVALID_HEADER;
449 }
450
451 if (getImageDataOffset(pHeader) < (getImageBlocksOffset(pHeader) + getImageBlocks(pHeader) * sizeof(VDIIMAGEBLOCKPOINTER)))
452 {
453 LogRel(("VDI: v1 image data offset wrong (%d < %d)\n",
454 getImageDataOffset(pHeader), getImageBlocksOffset(pHeader) + getImageBlocks(pHeader) * sizeof(VDIIMAGEBLOCKPOINTER)));
455 return VERR_VD_VDI_INVALID_HEADER;
456 }
457
458 break;
459 }
460 default:
461 /* Unsupported. */
462 return VERR_VD_VDI_UNSUPPORTED_VERSION;
463 }
464
465 /* Check common header parameters. */
466
467 bool fFailed = false;
468
469 if ( getImageType(pHeader) < VDI_IMAGE_TYPE_FIRST
470 || getImageType(pHeader) > VDI_IMAGE_TYPE_LAST)
471 {
472 LogRel(("VDI: bad image type %d\n", getImageType(pHeader)));
473 fFailed = true;
474 }
475
476 if (getImageFlags(pHeader) & ~VD_VDI_IMAGE_FLAGS_MASK)
477 {
478 LogRel(("VDI: bad image flags %08x\n", getImageFlags(pHeader)));
479 fFailed = true;
480 }
481
482 PVDIDISKGEOMETRY pLCHSGeom = getImageLCHSGeometry(pHeader);
483 if ( pLCHSGeom
484 && pLCHSGeom->cbSector != VDI_GEOMETRY_SECTOR_SIZE)
485 {
486 LogRel(("VDI: wrong sector size (%d != %d)\n", pLCHSGeom->cbSector, VDI_GEOMETRY_SECTOR_SIZE));
487 fFailed = true;
488 }
489
490 if ( getImageDiskSize(pHeader) == 0
491 || getImageBlockSize(pHeader) == 0
492 || getImageBlocks(pHeader) == 0
493 || getPowerOfTwo(getImageBlockSize(pHeader)) == 0)
494 {
495 LogRel(("VDI: wrong size (%lld, %d, %d, %d)\n",
496 getImageDiskSize(pHeader), getImageBlockSize(pHeader),
497 getImageBlocks(pHeader), getPowerOfTwo(getImageBlockSize(pHeader))));
498 fFailed = true;
499 }
500
501 if (getImageBlocksAllocated(pHeader) > getImageBlocks(pHeader))
502 {
503 LogRel(("VDI: too many blocks allocated (%d > %d)\n"
504 " blocksize=%d disksize=%lld\n",
505 getImageBlocksAllocated(pHeader), getImageBlocks(pHeader),
506 getImageBlockSize(pHeader), getImageDiskSize(pHeader)));
507 fFailed = true;
508 }
509
510 if ( getImageExtraBlockSize(pHeader) != 0
511 && getPowerOfTwo(getImageExtraBlockSize(pHeader)) == 0)
512 {
513 LogRel(("VDI: wrong extra size (%d, %d)\n",
514 getImageExtraBlockSize(pHeader), getPowerOfTwo(getImageExtraBlockSize(pHeader))));
515 fFailed = true;
516 }
517
518 if ((uint64_t)getImageBlockSize(pHeader) * getImageBlocks(pHeader) < getImageDiskSize(pHeader))
519 {
520 LogRel(("VDI: wrong disk size (%d, %d, %lld)\n",
521 getImageBlockSize(pHeader), getImageBlocks(pHeader), getImageDiskSize(pHeader)));
522 fFailed = true;
523 }
524
525 if (RTUuidIsNull(getImageCreationUUID(pHeader)))
526 {
527 LogRel(("VDI: uuid of creator is 0\n"));
528 fFailed = true;
529 }
530
531 if (RTUuidIsNull(getImageModificationUUID(pHeader)))
532 {
533 LogRel(("VDI: uuid of modifier is 0\n"));
534 fFailed = true;
535 }
536
537 return fFailed ? VERR_VD_VDI_INVALID_HEADER : VINF_SUCCESS;
538}
539
540/**
541 * Internal: Set up VDIIMAGEDESC structure by image header.
542 */
543static void vdiSetupImageDesc(PVDIIMAGEDESC pImage)
544{
545 pImage->uImageFlags = getImageFlags(&pImage->Header);
546 pImage->uImageFlags |= vdiTranslateVDI2ImageFlags(getImageType(&pImage->Header));
547 pImage->offStartBlocks = getImageBlocksOffset(&pImage->Header);
548 pImage->offStartData = getImageDataOffset(&pImage->Header);
549 pImage->uBlockMask = getImageBlockSize(&pImage->Header) - 1;
550 pImage->uShiftOffset2Index = getPowerOfTwo(getImageBlockSize(&pImage->Header));
551 pImage->offStartBlockData = getImageExtraBlockSize(&pImage->Header);
552 pImage->cbAllocationBlock = getImageBlockSize(&pImage->Header);
553 pImage->cbTotalBlockData = pImage->offStartBlockData
554 + getImageBlockSize(&pImage->Header);
555}
556
557/**
558 * Sets up the complete image state from the given parameters.
559 *
560 * @returns VBox status code.
561 * @param pImage The VDI image descriptor.
562 * @param uImageFlags Image flags.
563 * @param pszComment The comment for the image (optional).
564 * @param cbSize Size of the resulting image in bytes.
565 * @param cbAllocationBlock Size of blocks allocated
566 * @param cbDataAlign Data alignment in bytes.
567 * @param pPCHSGeometry Physical CHS geometry for the image.
568 * @param pLCHSGeometry Logical CHS geometry for the image.
569 */
570static int vdiSetupImageState(PVDIIMAGEDESC pImage, unsigned uImageFlags, const char *pszComment,
571 uint64_t cbSize, uint32_t cbAllocationBlock, uint32_t cbDataAlign, PCVDGEOMETRY pPCHSGeometry,
572 PCVDGEOMETRY pLCHSGeometry)
573{
574 int rc = VINF_SUCCESS;
575
576 vdiInitPreHeader(&pImage->PreHeader);
577 vdiInitHeader(&pImage->Header, uImageFlags, pszComment, cbSize, cbAllocationBlock, 0,
578 cbDataAlign);
579 /* Save PCHS geometry. Not much work, and makes the flow of information
580 * quite a bit clearer - relying on the higher level isn't obvious. */
581 pImage->PCHSGeometry = *pPCHSGeometry;
582 /* Set LCHS geometry (legacy geometry is ignored for the current 1.1+). */
583 pImage->Header.u.v1plus.LCHSGeometry.cCylinders = pLCHSGeometry->cCylinders;
584 pImage->Header.u.v1plus.LCHSGeometry.cHeads = pLCHSGeometry->cHeads;
585 pImage->Header.u.v1plus.LCHSGeometry.cSectors = pLCHSGeometry->cSectors;
586 pImage->Header.u.v1plus.LCHSGeometry.cbSector = VDI_GEOMETRY_SECTOR_SIZE;
587
588 pImage->paBlocks = (PVDIIMAGEBLOCKPOINTER)RTMemAlloc(sizeof(VDIIMAGEBLOCKPOINTER) * getImageBlocks(&pImage->Header));
589 if (RT_LIKELY(pImage->paBlocks))
590 {
591 if (!(uImageFlags & VD_IMAGE_FLAGS_FIXED))
592 {
593 /* for growing images mark all blocks in paBlocks as free. */
594 for (unsigned i = 0; i < pImage->Header.u.v1.cBlocks; i++)
595 pImage->paBlocks[i] = VDI_IMAGE_BLOCK_FREE;
596 }
597 else
598 {
599 /* for fixed images mark all blocks in paBlocks as allocated */
600 for (unsigned i = 0; i < pImage->Header.u.v1.cBlocks; i++)
601 pImage->paBlocks[i] = i;
602 pImage->Header.u.v1.cBlocksAllocated = pImage->Header.u.v1.cBlocks;
603 }
604
605 /* Setup image parameters. */
606 vdiSetupImageDesc(pImage);
607 }
608 else
609 rc = VERR_NO_MEMORY;
610
611 return rc;
612}
613
614/**
615 * Creates the image file from the given descriptor.
616 *
617 * @returns VBox status code.
618 * @param pImage The VDI image descriptor.
619 * @param uOpenFlags Open flags.
620 * @param pIfProgress The progress interface.
621 * @param uPercentStart Progress starting point.
622 * @param uPercentSpan How many percent for this part of the operation is used.
623 */
624static int vdiImageCreateFile(PVDIIMAGEDESC pImage, unsigned uOpenFlags,
625 PVDINTERFACEPROGRESS pIfProgress, unsigned uPercentStart,
626 unsigned uPercentSpan)
627{
628 int rc = vdIfIoIntFileOpen(pImage->pIfIo, pImage->pszFilename,
629 VDOpenFlagsToFileOpenFlags(uOpenFlags & ~VD_OPEN_FLAGS_READONLY,
630 true /* fCreate */),
631 &pImage->pStorage);
632 if (RT_SUCCESS(rc))
633 {
634 if (pImage->uImageFlags & VD_IMAGE_FLAGS_FIXED)
635 {
636 uint64_t cbTotal = pImage->offStartData
637 + (uint64_t)getImageBlocks(&pImage->Header) * pImage->cbTotalBlockData;
638
639 /* Check the free space on the disk and leave early if there is not
640 * sufficient space available. */
641 int64_t cbFree = 0;
642 rc = vdIfIoIntFileGetFreeSpace(pImage->pIfIo, pImage->pszFilename, &cbFree);
643 if (RT_SUCCESS(rc) /* ignore errors */ && ((uint64_t)cbFree < cbTotal))
644 rc = vdIfError(pImage->pIfError, VERR_DISK_FULL, RT_SRC_POS,
645 N_("VDI: disk would overflow creating image '%s'"), pImage->pszFilename);
646 else
647 {
648 /*
649 * Allocate & commit whole file if fixed image, it must be more
650 * effective than expanding file by write operations.
651 */
652 rc = vdIfIoIntFileSetAllocationSize(pImage->pIfIo, pImage->pStorage, cbTotal, 0 /* fFlags */,
653 pIfProgress, uPercentStart, uPercentSpan);
654 pImage->cbImage = cbTotal;
655 }
656 }
657 else
658 {
659 /* Set file size to hold header and blocks array. */
660 rc = vdIfIoIntFileSetSize(pImage->pIfIo, pImage->pStorage, pImage->offStartData);
661 pImage->cbImage = pImage->offStartData;
662 }
663 if (RT_SUCCESS(rc))
664 {
665 /* Write pre-header. */
666 VDIPREHEADER PreHeader;
667 vdiConvPreHeaderEndianess(VDIECONV_H2F, &PreHeader, &pImage->PreHeader);
668 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage, 0,
669 &PreHeader, sizeof(PreHeader));
670 if (RT_SUCCESS(rc))
671 {
672 /* Write header. */
673 VDIHEADER1PLUS Hdr;
674 vdiConvHeaderEndianessV1p(VDIECONV_H2F, &Hdr, &pImage->Header.u.v1plus);
675 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage, sizeof(pImage->PreHeader),
676 &Hdr, sizeof(Hdr));
677 if (RT_SUCCESS(rc))
678 {
679 vdiConvBlocksEndianess(VDIECONV_H2F, pImage->paBlocks, getImageBlocks(&pImage->Header));
680 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage, pImage->offStartBlocks, pImage->paBlocks,
681 getImageBlocks(&pImage->Header) * sizeof(VDIIMAGEBLOCKPOINTER));
682 vdiConvBlocksEndianess(VDIECONV_F2H, pImage->paBlocks, getImageBlocks(&pImage->Header));
683 if (RT_FAILURE(rc))
684 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VDI: writing block pointers failed for '%s'"),
685 pImage->pszFilename);
686 }
687 else
688 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VDI: writing header failed for '%s'"),
689 pImage->pszFilename);
690 }
691 else
692 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VDI: writing pre-header failed for '%s'"),
693 pImage->pszFilename);
694 }
695 else
696 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VDI: setting image size failed for '%s'"),
697 pImage->pszFilename);
698 }
699 else
700 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VDI: cannot create image '%s'"),
701 pImage->pszFilename);
702
703 return rc;
704}
705
706/**
707 * Internal: Create VDI image file.
708 */
709static int vdiCreateImage(PVDIIMAGEDESC pImage, uint64_t cbSize,
710 unsigned uImageFlags, const char *pszComment,
711 PCVDGEOMETRY pPCHSGeometry, PCVDGEOMETRY pLCHSGeometry,
712 PCRTUUID pUuid, unsigned uOpenFlags,
713 PVDINTERFACEPROGRESS pIfProgress, unsigned uPercentStart,
714 unsigned uPercentSpan, PVDINTERFACECONFIG pIfCfg)
715{
716 int rc = VINF_SUCCESS;
717 uint32_t cbDataAlign = VDI_DATA_ALIGN;
718 AssertPtr(pPCHSGeometry);
719 AssertPtr(pLCHSGeometry);
720
721 pImage->pIfError = VDIfErrorGet(pImage->pVDIfsDisk);
722 pImage->pIfIo = VDIfIoIntGet(pImage->pVDIfsImage);
723 AssertPtrReturn(pImage->pIfIo, VERR_INVALID_PARAMETER);
724
725 /* Special check for comment length. */
726 if ( RT_VALID_PTR(pszComment)
727 && strlen(pszComment) >= VDI_IMAGE_COMMENT_SIZE)
728 rc = vdIfError(pImage->pIfError, VERR_VD_VDI_COMMENT_TOO_LONG, RT_SRC_POS,
729 N_("VDI: comment is too long for '%s'"), pImage->pszFilename);
730
731 PVDINTERFACECONFIG pImgCfg = VDIfConfigGet(pImage->pVDIfsImage);
732 if (pImgCfg)
733 {
734 rc = VDCFGQueryU32Def(pImgCfg, "AllocationBlockSize",
735 &pImage->cbAllocationBlock, VDI_IMAGE_DEFAULT_BLOCK_SIZE);
736 if (RT_FAILURE(rc))
737 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS,
738 N_("VDI: Getting AllocationBlockSize for '%s' failed (%Rrc)"), pImage->pszFilename, rc);
739 } else
740 pImage->cbAllocationBlock = VDI_IMAGE_DEFAULT_BLOCK_SIZE;
741
742 if (pIfCfg)
743 {
744 rc = VDCFGQueryU32Def(pIfCfg, "DataAlignment", &cbDataAlign, VDI_DATA_ALIGN);
745 if (RT_FAILURE(rc))
746 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS,
747 N_("VDI: Getting data alignment for '%s' failed (%Rrc)"), pImage->pszFilename, rc);
748 }
749
750 if (RT_SUCCESS(rc))
751 {
752
753 rc = vdiSetupImageState(pImage, uImageFlags, pszComment, cbSize,
754 pImage->cbAllocationBlock, cbDataAlign, pPCHSGeometry, pLCHSGeometry);
755
756 if (RT_SUCCESS(rc))
757 {
758 /* Use specified image uuid */
759 *getImageCreationUUID(&pImage->Header) = *pUuid;
760 /* Generate image last-modify uuid */
761 RTUuidCreate(getImageModificationUUID(&pImage->Header));
762
763 rc = vdiImageCreateFile(pImage, uOpenFlags, pIfProgress,
764 uPercentStart, uPercentSpan);
765 }
766 }
767
768 if (RT_SUCCESS(rc))
769 {
770 PVDREGIONDESC pRegion = &pImage->RegionList.aRegions[0];
771 pImage->RegionList.fFlags = 0;
772 pImage->RegionList.cRegions = 1;
773
774 pRegion->offRegion = 0; /* Disk start. */
775 pRegion->cbBlock = 512;
776 pRegion->enmDataForm = VDREGIONDATAFORM_RAW;
777 pRegion->enmMetadataForm = VDREGIONMETADATAFORM_NONE;
778 pRegion->cbData = 512;
779 pRegion->cbMetadata = 0;
780 pRegion->cRegionBlocksOrBytes = getImageDiskSize(&pImage->Header);
781
782 vdIfProgress(pIfProgress, uPercentStart + uPercentSpan);
783 }
784
785 if (RT_FAILURE(rc))
786 vdiFreeImage(pImage, rc != VERR_ALREADY_EXISTS);
787 return rc;
788}
789
790/**
791 * Reads and validates the header for the given image descriptor.
792 *
793 * @returns VBox status code.
794 * @param pImage The VDI image descriptor.
795 */
796static int vdiImageReadHeader(PVDIIMAGEDESC pImage)
797{
798 /* Get file size. */
799 int rc = vdIfIoIntFileGetSize(pImage->pIfIo, pImage->pStorage,
800 &pImage->cbImage);
801 if (RT_SUCCESS(rc))
802 {
803 /* Read pre-header. */
804 VDIPREHEADER PreHeader;
805 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage, 0,
806 &PreHeader, sizeof(PreHeader));
807 if (RT_SUCCESS(rc))
808 {
809 vdiConvPreHeaderEndianess(VDIECONV_F2H, &pImage->PreHeader, &PreHeader);
810 rc = vdiValidatePreHeader(&pImage->PreHeader);
811 if (RT_SUCCESS(rc))
812 {
813 /* Read header. */
814 pImage->Header.uVersion = pImage->PreHeader.u32Version;
815 switch (GET_MAJOR_HEADER_VERSION(&pImage->Header))
816 {
817 case 0:
818 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage, sizeof(pImage->PreHeader),
819 &pImage->Header.u.v0, sizeof(pImage->Header.u.v0));
820 if (RT_SUCCESS(rc))
821 vdiConvHeaderEndianessV0(VDIECONV_F2H, &pImage->Header.u.v0, &pImage->Header.u.v0);
822 else
823 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VDI: error reading v0 header in '%s'"), pImage->pszFilename);
824 break;
825 case 1:
826 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage, sizeof(pImage->PreHeader),
827 &pImage->Header.u.v1, sizeof(pImage->Header.u.v1));
828 if (RT_SUCCESS(rc))
829 {
830 vdiConvHeaderEndianessV1(VDIECONV_F2H, &pImage->Header.u.v1, &pImage->Header.u.v1);
831 /* Convert VDI 1.1 images to VDI 1.1+ on open in read/write mode.
832 * Conversion is harmless, as any VirtualBox version supporting VDI
833 * 1.1 doesn't touch fields it doesn't know about. */
834 if ( !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
835 && GET_MINOR_HEADER_VERSION(&pImage->Header) == 1
836 && pImage->Header.u.v1.cbHeader < sizeof(pImage->Header.u.v1plus))
837 {
838 pImage->Header.u.v1plus.cbHeader = sizeof(pImage->Header.u.v1plus);
839 /* Mark LCHS geometry not-calculated. */
840 pImage->Header.u.v1plus.LCHSGeometry.cCylinders = 0;
841 pImage->Header.u.v1plus.LCHSGeometry.cHeads = 0;
842 pImage->Header.u.v1plus.LCHSGeometry.cSectors = 0;
843 pImage->Header.u.v1plus.LCHSGeometry.cbSector = VDI_GEOMETRY_SECTOR_SIZE;
844 }
845 else if (pImage->Header.u.v1.cbHeader >= sizeof(pImage->Header.u.v1plus))
846 {
847 /* Read the actual VDI 1.1+ header completely. */
848 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage, sizeof(pImage->PreHeader),
849 &pImage->Header.u.v1plus,
850 sizeof(pImage->Header.u.v1plus));
851 if (RT_SUCCESS(rc))
852 vdiConvHeaderEndianessV1p(VDIECONV_F2H, &pImage->Header.u.v1plus, &pImage->Header.u.v1plus);
853 else
854 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VDI: error reading v1.1+ header in '%s'"), pImage->pszFilename);
855 }
856 }
857 else
858 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VDI: error reading v1 header in '%s'"), pImage->pszFilename);
859 break;
860 default:
861 rc = vdIfError(pImage->pIfError, VERR_VD_VDI_UNSUPPORTED_VERSION, RT_SRC_POS,
862 N_("VDI: unsupported major version %u in '%s'"), GET_MAJOR_HEADER_VERSION(&pImage->Header), pImage->pszFilename);
863 }
864
865 if (RT_SUCCESS(rc))
866 {
867 rc = vdiValidateHeader(&pImage->Header);
868 if (RT_SUCCESS(rc))
869 {
870 /* Setup image parameters by header. */
871 vdiSetupImageDesc(pImage);
872
873 /*
874 * Until revision r111992 there was no check that the size was sector aligned
875 * when creating a new image and a bug in the VirtualBox GUI on OS X resulted
876 * in such images being created which caused issues when writing to the
877 * end of the image.
878 *
879 * Detect such images and repair the small damage by rounding down to the next
880 * aligned size. This is no problem as the guest would see a sector count
881 * only anyway from the device emulations so it already sees only the smaller
882 * size as result of the integer division of the size and sector size.
883 *
884 * This might not be written to the image if it is opened readonly
885 * which is not much of a problem because only writing to the last block
886 * causes trouble.
887 */
888 uint64_t cbDisk = getImageDiskSize(&pImage->Header);
889 if (cbDisk & 0x1ff)
890 setImageDiskSize(&pImage->Header, cbDisk & ~UINT64_C(0x1ff));
891 }
892 else
893 rc = vdIfError(pImage->pIfError, VERR_VD_VDI_INVALID_HEADER, RT_SRC_POS,
894 N_("VDI: invalid header in '%s'"), pImage->pszFilename);
895 }
896 }
897 else
898 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VDI: invalid pre-header in '%s'"), pImage->pszFilename);
899 }
900 else
901 {
902 vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VDI: error reading pre-header in '%s'"), pImage->pszFilename);
903 rc = VERR_VD_VDI_INVALID_HEADER;
904 }
905 }
906 else
907 {
908 vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VDI: error getting the image size in '%s'"), pImage->pszFilename);
909 rc = VERR_VD_VDI_INVALID_HEADER;
910 }
911
912 return rc;
913}
914
915/**
916 * Creates the back resolving table for the image for the discard operation.
917 *
918 * @returns VBox status code.
919 * @param pImage The VDI image descriptor.
920 */
921static int vdiImageBackResolvTblCreate(PVDIIMAGEDESC pImage)
922{
923 int rc = VINF_SUCCESS;
924
925 /*
926 * Any error or inconsistency results in a fail because this might
927 * get us into trouble later on.
928 */
929 pImage->paBlocksRev = (unsigned *)RTMemAllocZ(sizeof(unsigned) * getImageBlocks(&pImage->Header));
930 if (pImage->paBlocksRev)
931 {
932 unsigned cBlocksAllocated = getImageBlocksAllocated(&pImage->Header);
933 unsigned cBlocks = getImageBlocks(&pImage->Header);
934
935 for (unsigned i = 0; i < cBlocks; i++)
936 pImage->paBlocksRev[i] = VDI_IMAGE_BLOCK_FREE;
937
938 for (unsigned i = 0; i < cBlocks; i++)
939 {
940 VDIIMAGEBLOCKPOINTER ptrBlock = pImage->paBlocks[i];
941 if (IS_VDI_IMAGE_BLOCK_ALLOCATED(ptrBlock))
942 {
943 if (ptrBlock < cBlocksAllocated)
944 {
945 if (pImage->paBlocksRev[ptrBlock] == VDI_IMAGE_BLOCK_FREE)
946 pImage->paBlocksRev[ptrBlock] = i;
947 else
948 {
949 rc = VERR_VD_VDI_INVALID_HEADER;
950 break;
951 }
952 }
953 else
954 {
955 rc = VERR_VD_VDI_INVALID_HEADER;
956 break;
957 }
958 }
959 }
960 }
961 else
962 rc = VERR_NO_MEMORY;
963
964 return rc;
965}
966
967/**
968 * Internal: Open a VDI image.
969 */
970static int vdiOpenImage(PVDIIMAGEDESC pImage, unsigned uOpenFlags)
971{
972 pImage->uOpenFlags = uOpenFlags;
973
974 pImage->pIfError = VDIfErrorGet(pImage->pVDIfsDisk);
975 pImage->pIfIo = VDIfIoIntGet(pImage->pVDIfsImage);
976 AssertPtrReturn(pImage->pIfIo, VERR_INVALID_PARAMETER);
977
978 /*
979 * Open the image.
980 */
981 int rc = vdIfIoIntFileOpen(pImage->pIfIo, pImage->pszFilename,
982 VDOpenFlagsToFileOpenFlags(uOpenFlags, false /* fCreate */),
983 &pImage->pStorage);
984 if (RT_SUCCESS(rc))
985 {
986 rc = vdiImageReadHeader(pImage);
987 if (RT_SUCCESS(rc))
988 {
989 /* Allocate memory for blocks array. */
990 pImage->paBlocks = (PVDIIMAGEBLOCKPOINTER)RTMemAlloc(sizeof(VDIIMAGEBLOCKPOINTER) * getImageBlocks(&pImage->Header));
991 if (RT_LIKELY(pImage->paBlocks))
992 {
993 /* Read blocks array. */
994 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage, pImage->offStartBlocks, pImage->paBlocks,
995 getImageBlocks(&pImage->Header) * sizeof(VDIIMAGEBLOCKPOINTER));
996 if (RT_SUCCESS(rc))
997 {
998 vdiConvBlocksEndianess(VDIECONV_F2H, pImage->paBlocks, getImageBlocks(&pImage->Header));
999
1000 if (uOpenFlags & VD_OPEN_FLAGS_DISCARD)
1001 rc = vdiImageBackResolvTblCreate(pImage);
1002 }
1003 else
1004 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VDI: Error reading the block table in '%s'"), pImage->pszFilename);
1005 }
1006 else
1007 rc = vdIfError(pImage->pIfError, VERR_NO_MEMORY, RT_SRC_POS,
1008 N_("VDI: Error allocating memory for the block table in '%s'"), pImage->pszFilename);;
1009 }
1010 }
1011 /* else: Do NOT signal an appropriate error here, as the VD layer has the
1012 * choice of retrying the open if it failed. */
1013
1014 if (RT_SUCCESS(rc))
1015 {
1016 PVDREGIONDESC pRegion = &pImage->RegionList.aRegions[0];
1017 pImage->RegionList.fFlags = 0;
1018 pImage->RegionList.cRegions = 1;
1019
1020 pRegion->offRegion = 0; /* Disk start. */
1021 pRegion->cbBlock = 512;
1022 pRegion->enmDataForm = VDREGIONDATAFORM_RAW;
1023 pRegion->enmMetadataForm = VDREGIONMETADATAFORM_NONE;
1024 pRegion->cbData = 512;
1025 pRegion->cbMetadata = 0;
1026 pRegion->cRegionBlocksOrBytes = getImageDiskSize(&pImage->Header);
1027 if (uOpenFlags & VD_OPEN_FLAGS_INFO)
1028 {
1029 PVDINTERFACECONFIG pImgCfg = VDIfConfigGet(pImage->pVDIfsImage);
1030 if (pImgCfg)
1031 {
1032 rc = VDCFGUpdateU64(pImgCfg, true, "AllocationBlockSize", pImage->cbAllocationBlock);
1033 if (RT_FAILURE(rc))
1034 return rc;
1035 }
1036 }
1037 }
1038 else
1039 vdiFreeImage(pImage, false);
1040 return rc;
1041}
1042
1043/**
1044 * Internal: Save header to file.
1045 */
1046static int vdiUpdateHeader(PVDIIMAGEDESC pImage)
1047{
1048 int rc;
1049 switch (GET_MAJOR_HEADER_VERSION(&pImage->Header))
1050 {
1051 case 0:
1052 {
1053 VDIHEADER0 Hdr;
1054 vdiConvHeaderEndianessV0(VDIECONV_H2F, &Hdr, &pImage->Header.u.v0);
1055 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage, sizeof(VDIPREHEADER),
1056 &Hdr, sizeof(Hdr));
1057 break;
1058 }
1059 case 1:
1060 if (pImage->Header.u.v1plus.cbHeader < sizeof(pImage->Header.u.v1plus))
1061 {
1062 VDIHEADER1 Hdr;
1063 vdiConvHeaderEndianessV1(VDIECONV_H2F, &Hdr, &pImage->Header.u.v1);
1064 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage, sizeof(VDIPREHEADER),
1065 &Hdr, sizeof(Hdr));
1066 }
1067 else
1068 {
1069 VDIHEADER1PLUS Hdr;
1070 vdiConvHeaderEndianessV1p(VDIECONV_H2F, &Hdr, &pImage->Header.u.v1plus);
1071 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage, sizeof(VDIPREHEADER),
1072 &Hdr, sizeof(Hdr));
1073 }
1074 break;
1075 default:
1076 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
1077 break;
1078 }
1079 AssertMsgRC(rc, ("vdiUpdateHeader failed, filename=\"%s\" rc=%Rrc\n", pImage->pszFilename, rc));
1080 return rc;
1081}
1082
1083/**
1084 * Internal: Save header to file - async version.
1085 */
1086static int vdiUpdateHeaderAsync(PVDIIMAGEDESC pImage, PVDIOCTX pIoCtx)
1087{
1088 int rc;
1089 switch (GET_MAJOR_HEADER_VERSION(&pImage->Header))
1090 {
1091 case 0:
1092 {
1093 VDIHEADER0 Hdr;
1094 vdiConvHeaderEndianessV0(VDIECONV_H2F, &Hdr, &pImage->Header.u.v0);
1095 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
1096 sizeof(VDIPREHEADER), &Hdr, sizeof(Hdr),
1097 pIoCtx, NULL, NULL);
1098 break;
1099 }
1100 case 1:
1101 if (pImage->Header.u.v1plus.cbHeader < sizeof(pImage->Header.u.v1plus))
1102 {
1103 VDIHEADER1 Hdr;
1104 vdiConvHeaderEndianessV1(VDIECONV_H2F, &Hdr, &pImage->Header.u.v1);
1105 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
1106 sizeof(VDIPREHEADER), &Hdr, sizeof(Hdr),
1107 pIoCtx, NULL, NULL);
1108 }
1109 else
1110 {
1111 VDIHEADER1PLUS Hdr;
1112 vdiConvHeaderEndianessV1p(VDIECONV_H2F, &Hdr, &pImage->Header.u.v1plus);
1113 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
1114 sizeof(VDIPREHEADER), &Hdr, sizeof(Hdr),
1115 pIoCtx, NULL, NULL);
1116 }
1117 break;
1118 default:
1119 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
1120 break;
1121 }
1122 AssertMsg(RT_SUCCESS(rc) || rc == VERR_VD_ASYNC_IO_IN_PROGRESS,
1123 ("vdiUpdateHeader failed, filename=\"%s\" rc=%Rrc\n", pImage->pszFilename, rc));
1124 return rc;
1125}
1126
1127/**
1128 * Internal: Save block pointer to file, save header to file.
1129 */
1130static int vdiUpdateBlockInfo(PVDIIMAGEDESC pImage, unsigned uBlock)
1131{
1132 /* Update image header. */
1133 int rc = vdiUpdateHeader(pImage);
1134 if (RT_SUCCESS(rc))
1135 {
1136 /* write only one block pointer. */
1137 VDIIMAGEBLOCKPOINTER ptrBlock = RT_H2LE_U32(pImage->paBlocks[uBlock]);
1138 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage,
1139 pImage->offStartBlocks + uBlock * sizeof(VDIIMAGEBLOCKPOINTER),
1140 &ptrBlock, sizeof(VDIIMAGEBLOCKPOINTER));
1141 AssertMsgRC(rc, ("vdiUpdateBlockInfo failed to update block=%u, filename=\"%s\", rc=%Rrc\n",
1142 uBlock, pImage->pszFilename, rc));
1143 }
1144 return rc;
1145}
1146
1147/**
1148 * Internal: Save block pointer to file, save header to file - async version.
1149 */
1150static int vdiUpdateBlockInfoAsync(PVDIIMAGEDESC pImage, unsigned uBlock,
1151 PVDIOCTX pIoCtx, bool fUpdateHdr)
1152{
1153 int rc = VINF_SUCCESS;
1154
1155 /* Update image header. */
1156 if (fUpdateHdr)
1157 rc = vdiUpdateHeaderAsync(pImage, pIoCtx);
1158
1159 if (RT_SUCCESS(rc) || rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1160 {
1161 /* write only one block pointer. */
1162 VDIIMAGEBLOCKPOINTER ptrBlock = RT_H2LE_U32(pImage->paBlocks[uBlock]);
1163 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
1164 pImage->offStartBlocks + uBlock * sizeof(VDIIMAGEBLOCKPOINTER),
1165 &ptrBlock, sizeof(VDIIMAGEBLOCKPOINTER),
1166 pIoCtx, NULL, NULL);
1167 AssertMsg(RT_SUCCESS(rc) || rc == VERR_VD_ASYNC_IO_IN_PROGRESS,
1168 ("vdiUpdateBlockInfo failed to update block=%u, filename=\"%s\", rc=%Rrc\n",
1169 uBlock, pImage->pszFilename, rc));
1170 }
1171 return rc;
1172}
1173
1174/**
1175 * Internal: Flush the image file to disk - async version.
1176 */
1177static int vdiFlushImageIoCtx(PVDIIMAGEDESC pImage, PVDIOCTX pIoCtx)
1178{
1179 int rc = VINF_SUCCESS;
1180
1181 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
1182 {
1183 /* Save header. */
1184 rc = vdiUpdateHeaderAsync(pImage, pIoCtx);
1185 AssertMsg(RT_SUCCESS(rc) || rc == VERR_VD_ASYNC_IO_IN_PROGRESS,
1186 ("vdiUpdateHeaderAsync() failed, filename=\"%s\", rc=%Rrc\n",
1187 pImage->pszFilename, rc));
1188 rc = vdIfIoIntFileFlush(pImage->pIfIo, pImage->pStorage, pIoCtx, NULL, NULL);
1189 AssertMsg(RT_SUCCESS(rc) || rc == VERR_VD_ASYNC_IO_IN_PROGRESS,
1190 ("Flushing data to disk failed rc=%Rrc\n", rc));
1191 }
1192
1193 return rc;
1194}
1195
1196/**
1197 * Completion callback for meta/userdata reads or writes.
1198 *
1199 * @return VBox status code.
1200 * VINF_SUCCESS if everything was successful and the transfer can continue.
1201 * VERR_VD_ASYNC_IO_IN_PROGRESS if there is another data transfer pending.
1202 * @param pBackendData The opaque backend data.
1203 * @param pIoCtx I/O context associated with this request.
1204 * @param pvUser Opaque user data passed during a read/write request.
1205 * @param rcReq Status code for the completed request.
1206 */
1207static DECLCALLBACK(int) vdiDiscardBlockAsyncUpdate(void *pBackendData, PVDIOCTX pIoCtx, void *pvUser, int rcReq)
1208{
1209 RT_NOREF1(rcReq);
1210 int rc = VINF_SUCCESS;
1211 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1212 PVDIBLOCKDISCARDASYNC pDiscardAsync = (PVDIBLOCKDISCARDASYNC)pvUser;
1213
1214 switch (pDiscardAsync->enmState)
1215 {
1216 case VDIBLOCKDISCARDSTATE_READ_BLOCK:
1217 {
1218 PVDMETAXFER pMetaXfer;
1219 uint64_t u64Offset = (uint64_t)pDiscardAsync->idxLastBlock * pImage->cbTotalBlockData + pImage->offStartData;
1220 rc = vdIfIoIntFileReadMeta(pImage->pIfIo, pImage->pStorage, u64Offset,
1221 pDiscardAsync->pvBlock, pImage->cbTotalBlockData, pIoCtx,
1222 &pMetaXfer, vdiDiscardBlockAsyncUpdate, pDiscardAsync);
1223 if (RT_FAILURE(rc))
1224 break;
1225
1226 /* Release immediately and go to next step. */
1227 vdIfIoIntMetaXferRelease(pImage->pIfIo, pMetaXfer);
1228 pDiscardAsync->enmState = VDIBLOCKDISCARDSTATE_WRITE_BLOCK;
1229 }
1230 RT_FALL_THRU();
1231 case VDIBLOCKDISCARDSTATE_WRITE_BLOCK:
1232 {
1233 /* Block read complete. Write to the new location (discarded block). */
1234 uint64_t u64Offset = (uint64_t)pDiscardAsync->ptrBlockDiscard * pImage->cbTotalBlockData + pImage->offStartData;
1235 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage, u64Offset,
1236 pDiscardAsync->pvBlock, pImage->cbTotalBlockData, pIoCtx,
1237 vdiDiscardBlockAsyncUpdate, pDiscardAsync);
1238
1239 pDiscardAsync->enmState = VDIBLOCKDISCARDSTATE_UPDATE_METADATA;
1240 if (RT_FAILURE(rc))
1241 break;
1242 }
1243 RT_FALL_THRU();
1244 case VDIBLOCKDISCARDSTATE_UPDATE_METADATA:
1245 {
1246 int rc2;
1247
1248 /* Block write complete. Update metadata. */
1249 pImage->paBlocksRev[pDiscardAsync->idxLastBlock] = VDI_IMAGE_BLOCK_FREE;
1250 pImage->paBlocks[pDiscardAsync->uBlock] = VDI_IMAGE_BLOCK_ZERO;
1251
1252 if (pDiscardAsync->idxLastBlock != pDiscardAsync->ptrBlockDiscard)
1253 {
1254 pImage->paBlocks[pDiscardAsync->uBlockLast] = pDiscardAsync->ptrBlockDiscard;
1255 pImage->paBlocksRev[pDiscardAsync->ptrBlockDiscard] = pDiscardAsync->uBlockLast;
1256
1257 rc = vdiUpdateBlockInfoAsync(pImage, pDiscardAsync->uBlockLast, pIoCtx, false /* fUpdateHdr */);
1258 if ( RT_FAILURE(rc)
1259 && rc != VERR_VD_ASYNC_IO_IN_PROGRESS)
1260 break;
1261 }
1262
1263 setImageBlocksAllocated(&pImage->Header, pDiscardAsync->idxLastBlock);
1264 rc = vdiUpdateBlockInfoAsync(pImage, pDiscardAsync->uBlock, pIoCtx, true /* fUpdateHdr */);
1265 if ( RT_FAILURE(rc)
1266 && rc != VERR_VD_ASYNC_IO_IN_PROGRESS)
1267 break;
1268
1269 pImage->cbImage -= pImage->cbTotalBlockData;
1270 LogFlowFunc(("Set new size %llu\n", pImage->cbImage));
1271 rc2 = vdIfIoIntFileSetSize(pImage->pIfIo, pImage->pStorage, pImage->cbImage);
1272 if (RT_FAILURE(rc2))
1273 rc = rc2;
1274
1275 /* Free discard state. */
1276 RTMemFree(pDiscardAsync->pvBlock);
1277 RTMemFree(pDiscardAsync);
1278 break;
1279 }
1280 default:
1281 AssertMsgFailed(("Invalid state %d\n", pDiscardAsync->enmState));
1282 }
1283
1284 if (rc == VERR_VD_NOT_ENOUGH_METADATA)
1285 rc = VERR_VD_ASYNC_IO_IN_PROGRESS;
1286
1287 return rc;
1288}
1289
1290/**
1291 * Internal: Discard a whole block from the image filling the created hole with
1292 * data from another block - async I/O version.
1293 *
1294 * @returns VBox status code.
1295 * @param pImage VDI image instance data.
1296 * @param pIoCtx I/O context associated with this request.
1297 * @param uBlock The block to discard.
1298 * @param pvBlock Memory to use for the I/O.
1299 */
1300static int vdiDiscardBlockAsync(PVDIIMAGEDESC pImage, PVDIOCTX pIoCtx,
1301 unsigned uBlock, void *pvBlock)
1302{
1303 int rc = VINF_SUCCESS;
1304 PVDIBLOCKDISCARDASYNC pDiscardAsync = NULL;
1305
1306 LogFlowFunc(("pImage=%#p uBlock=%u pvBlock=%#p\n",
1307 pImage, uBlock, pvBlock));
1308
1309 pDiscardAsync = (PVDIBLOCKDISCARDASYNC)RTMemAllocZ(sizeof(VDIBLOCKDISCARDASYNC));
1310 if (RT_UNLIKELY(!pDiscardAsync))
1311 return VERR_NO_MEMORY;
1312
1313 /* Init block discard state. */
1314 pDiscardAsync->uBlock = uBlock;
1315 pDiscardAsync->pvBlock = pvBlock;
1316 pDiscardAsync->ptrBlockDiscard = pImage->paBlocks[uBlock];
1317 pDiscardAsync->idxLastBlock = getImageBlocksAllocated(&pImage->Header) - 1;
1318 pDiscardAsync->uBlockLast = pImage->paBlocksRev[pDiscardAsync->idxLastBlock];
1319
1320 /*
1321 * The block is empty, remove it.
1322 * Read the last block of the image first.
1323 */
1324 if (pDiscardAsync->idxLastBlock != pDiscardAsync->ptrBlockDiscard)
1325 {
1326 LogFlowFunc(("Moving block [%u]=%u into [%u]=%u\n",
1327 pDiscardAsync->uBlockLast, pDiscardAsync->idxLastBlock,
1328 uBlock, pImage->paBlocks[uBlock]));
1329 pDiscardAsync->enmState = VDIBLOCKDISCARDSTATE_READ_BLOCK;
1330 }
1331 else
1332 {
1333 pDiscardAsync->enmState = VDIBLOCKDISCARDSTATE_UPDATE_METADATA; /* Start immediately to shrink the image. */
1334 LogFlowFunc(("Discard last block [%u]=%u\n", uBlock, pImage->paBlocks[uBlock]));
1335 }
1336
1337 /* Call the update callback directly. */
1338 rc = vdiDiscardBlockAsyncUpdate(pImage, pIoCtx, pDiscardAsync, VINF_SUCCESS);
1339
1340 LogFlowFunc(("returns rc=%Rrc\n", rc));
1341 return rc;
1342}
1343
1344/**
1345 * Internal: Creates a allocation bitmap from the given data.
1346 * Sectors which contain only 0 are marked as unallocated and sectors with
1347 * other data as allocated.
1348 *
1349 * @returns Pointer to the allocation bitmap or NULL on failure.
1350 * @param pvData The data to create the allocation bitmap for.
1351 * @param cbData Number of bytes in the buffer.
1352 */
1353static void *vdiAllocationBitmapCreate(void *pvData, size_t cbData)
1354{
1355 Assert(cbData <= UINT32_MAX / 8);
1356 uint32_t cSectors = (uint32_t)(cbData / 512);
1357 uint32_t uSectorCur = 0;
1358 void *pbmAllocationBitmap = NULL;
1359
1360 Assert(!(cbData % 512));
1361 Assert(!(cSectors % 8));
1362
1363 pbmAllocationBitmap = RTMemAllocZ(cSectors / 8);
1364 if (!pbmAllocationBitmap)
1365 return NULL;
1366
1367 while (uSectorCur < cSectors)
1368 {
1369 int idxSet = ASMBitFirstSet((uint8_t *)pvData + uSectorCur * 512, (uint32_t)cbData * 8);
1370
1371 if (idxSet != -1)
1372 {
1373 unsigned idxSectorAlloc = idxSet / 8 / 512;
1374 ASMBitSet(pbmAllocationBitmap, uSectorCur + idxSectorAlloc);
1375
1376 uSectorCur += idxSectorAlloc + 1;
1377 cbData -= (idxSectorAlloc + 1) * 512;
1378 }
1379 else
1380 break;
1381 }
1382
1383 return pbmAllocationBitmap;
1384}
1385
1386
1387/**
1388 * Updates the state of the async cluster allocation.
1389 *
1390 * @returns VBox status code.
1391 * @param pBackendData The opaque backend data.
1392 * @param pIoCtx I/O context associated with this request.
1393 * @param pvUser Opaque user data passed during a read/write request.
1394 * @param rcReq Status code for the completed request.
1395 */
1396static DECLCALLBACK(int) vdiBlockAllocUpdate(void *pBackendData, PVDIOCTX pIoCtx, void *pvUser, int rcReq)
1397{
1398 int rc = VINF_SUCCESS;
1399 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1400 PVDIASYNCBLOCKALLOC pBlockAlloc = (PVDIASYNCBLOCKALLOC)pvUser;
1401
1402 if (RT_SUCCESS(rcReq))
1403 {
1404 pImage->cbImage += pImage->cbTotalBlockData;
1405 pImage->paBlocks[pBlockAlloc->uBlock] = pBlockAlloc->cBlocksAllocated;
1406
1407 if (pImage->paBlocksRev)
1408 pImage->paBlocksRev[pBlockAlloc->cBlocksAllocated] = pBlockAlloc->uBlock;
1409
1410 setImageBlocksAllocated(&pImage->Header, pBlockAlloc->cBlocksAllocated + 1);
1411 rc = vdiUpdateBlockInfoAsync(pImage, pBlockAlloc->uBlock, pIoCtx,
1412 true /* fUpdateHdr */);
1413 }
1414 /* else: I/O error don't update the block table. */
1415
1416 RTMemFree(pBlockAlloc);
1417 return rc;
1418}
1419
1420/** @copydoc VDIMAGEBACKEND::pfnProbe */
1421static DECLCALLBACK(int) vdiProbe(const char *pszFilename, PVDINTERFACE pVDIfsDisk,
1422 PVDINTERFACE pVDIfsImage, VDTYPE enmDesiredType, VDTYPE *penmType)
1423{
1424 RT_NOREF(enmDesiredType);
1425 LogFlowFunc(("pszFilename=\"%s\"\n", pszFilename));
1426 int rc = VINF_SUCCESS;
1427
1428 AssertPtrReturn(pszFilename, VERR_INVALID_POINTER);
1429 AssertReturn(*pszFilename != '\0', VERR_INVALID_PARAMETER);
1430
1431
1432 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)RTMemAllocZ(RT_UOFFSETOF(VDIIMAGEDESC, RegionList.aRegions[1]));
1433 if (RT_LIKELY(pImage))
1434 {
1435 pImage->pszFilename = pszFilename;
1436 pImage->pStorage = NULL;
1437 pImage->paBlocks = NULL;
1438 pImage->pVDIfsDisk = pVDIfsDisk;
1439 pImage->pVDIfsImage = pVDIfsImage;
1440
1441 rc = vdiOpenImage(pImage, VD_OPEN_FLAGS_INFO | VD_OPEN_FLAGS_READONLY);
1442 vdiFreeImage(pImage, false);
1443 RTMemFree(pImage);
1444
1445 if (RT_SUCCESS(rc))
1446 *penmType = VDTYPE_HDD;
1447 }
1448 else
1449 rc = VERR_NO_MEMORY;
1450
1451 LogFlowFunc(("returns %Rrc\n", rc));
1452 return rc;
1453}
1454
1455/** @copydoc VDIMAGEBACKEND::pfnOpen */
1456static DECLCALLBACK(int) vdiOpen(const char *pszFilename, unsigned uOpenFlags,
1457 PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
1458 VDTYPE enmType, void **ppBackendData)
1459{
1460 RT_NOREF1(enmType); /**< @todo r=klaus make use of the type info. */
1461
1462 LogFlowFunc(("pszFilename=\"%s\" uOpenFlags=%#x pVDIfsDisk=%#p pVDIfsImage=%#p enmType=%u ppBackendData=%#p\n",
1463 pszFilename, uOpenFlags, pVDIfsDisk, pVDIfsImage, enmType, ppBackendData));
1464 int rc;
1465
1466 /* Check open flags. All valid flags are supported. */
1467 AssertReturn(!(uOpenFlags & ~VD_OPEN_FLAGS_MASK), VERR_INVALID_PARAMETER);
1468 AssertPtrReturn(pszFilename, VERR_INVALID_POINTER);
1469 AssertReturn(*pszFilename != '\0', VERR_INVALID_PARAMETER);
1470
1471
1472 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)RTMemAllocZ(RT_UOFFSETOF(VDIIMAGEDESC, RegionList.aRegions[1]));
1473 if (RT_LIKELY(pImage))
1474 {
1475 pImage->pszFilename = pszFilename;
1476 pImage->pStorage = NULL;
1477 pImage->paBlocks = NULL;
1478 pImage->pVDIfsDisk = pVDIfsDisk;
1479 pImage->pVDIfsImage = pVDIfsImage;
1480
1481 rc = vdiOpenImage(pImage, uOpenFlags);
1482 if (RT_SUCCESS(rc))
1483 *ppBackendData = pImage;
1484 else
1485 RTMemFree(pImage);
1486 }
1487 else
1488 rc = VERR_NO_MEMORY;
1489
1490 LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
1491 return rc;
1492}
1493
1494/** @copydoc VDIMAGEBACKEND::pfnCreate */
1495static DECLCALLBACK(int) vdiCreate(const char *pszFilename, uint64_t cbSize,
1496 unsigned uImageFlags, const char *pszComment,
1497 PCVDGEOMETRY pPCHSGeometry, PCVDGEOMETRY pLCHSGeometry,
1498 PCRTUUID pUuid, unsigned uOpenFlags,
1499 unsigned uPercentStart, unsigned uPercentSpan,
1500 PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
1501 PVDINTERFACE pVDIfsOperation, VDTYPE enmType,
1502 void **ppBackendData)
1503{
1504 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\n",
1505 pszFilename, cbSize, uImageFlags, pszComment, pPCHSGeometry, pLCHSGeometry, pUuid, uOpenFlags, uPercentStart, uPercentSpan, pVDIfsDisk, pVDIfsImage, pVDIfsOperation, enmType, ppBackendData));
1506 int rc;
1507
1508 /* Check the VD container type and image flags. */
1509 if ( enmType != VDTYPE_HDD
1510 || (uImageFlags & ~VD_VDI_IMAGE_FLAGS_MASK) != 0)
1511 return VERR_VD_INVALID_TYPE;
1512
1513 /* Check size. Maximum 4PB-3M. No tricks with adjusting the 1M block size
1514 * so far, which would extend the size. */
1515 if ( cbSize >= _1P * 4 - _1M * 3
1516 || cbSize < VDI_IMAGE_DEFAULT_BLOCK_SIZE
1517 || (cbSize % 512))
1518 return VERR_VD_INVALID_SIZE;
1519
1520 /* Check open flags. All valid flags are supported. */
1521 AssertReturn(!(uOpenFlags & ~VD_OPEN_FLAGS_MASK), VERR_INVALID_PARAMETER);
1522 AssertPtrReturn(pszFilename, VERR_INVALID_POINTER);
1523 AssertReturn(*pszFilename != '\0', VERR_INVALID_PARAMETER);
1524 AssertPtrReturn(pPCHSGeometry, VERR_INVALID_POINTER);
1525 AssertPtrReturn(pLCHSGeometry, VERR_INVALID_POINTER);
1526
1527 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)RTMemAllocZ(RT_UOFFSETOF(VDIIMAGEDESC, RegionList.aRegions[1]));
1528 if (RT_LIKELY(pImage))
1529 {
1530 PVDINTERFACEPROGRESS pIfProgress = VDIfProgressGet(pVDIfsOperation);
1531 PVDINTERFACECONFIG pIfCfg = VDIfConfigGet(pVDIfsOperation);
1532 pImage->pszFilename = pszFilename;
1533 pImage->pStorage = NULL;
1534 pImage->paBlocks = NULL;
1535 pImage->pVDIfsDisk = pVDIfsDisk;
1536 pImage->pVDIfsImage = pVDIfsImage;
1537
1538 rc = vdiCreateImage(pImage, cbSize, uImageFlags, pszComment,
1539 pPCHSGeometry, pLCHSGeometry, pUuid, uOpenFlags,
1540 pIfProgress, uPercentStart, uPercentSpan, pIfCfg);
1541 if (RT_SUCCESS(rc))
1542 {
1543 /* So far the image is opened in read/write mode. Make sure the
1544 * image is opened in read-only mode if the caller requested that. */
1545 if (uOpenFlags & VD_OPEN_FLAGS_READONLY)
1546 {
1547 vdiFreeImage(pImage, false);
1548 rc = vdiOpenImage(pImage, uOpenFlags);
1549 }
1550
1551 if (RT_SUCCESS(rc))
1552 *ppBackendData = pImage;
1553 }
1554
1555 if (RT_FAILURE(rc))
1556 RTMemFree(pImage);
1557 }
1558 else
1559 rc = VERR_NO_MEMORY;
1560
1561 LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
1562 return rc;
1563}
1564
1565/** @copydoc VDIMAGEBACKEND::pfnRename */
1566static DECLCALLBACK(int) vdiRename(void *pBackendData, const char *pszFilename)
1567{
1568 LogFlowFunc(("pBackendData=%#p pszFilename=%#p\n", pBackendData, pszFilename));
1569 int rc = VINF_SUCCESS;
1570 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1571
1572 /* Check arguments. */
1573 AssertReturn((pImage && pszFilename && *pszFilename), VERR_INVALID_PARAMETER);
1574
1575 /* Close the image. */
1576 rc = vdiFreeImage(pImage, false);
1577 if (RT_SUCCESS(rc))
1578 {
1579 /* Rename the file. */
1580 rc = vdIfIoIntFileMove(pImage->pIfIo, pImage->pszFilename, pszFilename, 0);
1581 if (RT_SUCCESS(rc))
1582 {
1583 /* Update pImage with the new information. */
1584 pImage->pszFilename = pszFilename;
1585
1586 /* Open the new image. */
1587 rc = vdiOpenImage(pImage, pImage->uOpenFlags);
1588 }
1589 else
1590 {
1591 /* The move failed, try to reopen the original image. */
1592 int rc2 = vdiOpenImage(pImage, pImage->uOpenFlags);
1593 if (RT_FAILURE(rc2))
1594 rc = rc2;
1595 }
1596 }
1597
1598 LogFlowFunc(("returns %Rrc\n", rc));
1599 return rc;
1600}
1601
1602/** @copydoc VDIMAGEBACKEND::pfnClose */
1603static DECLCALLBACK(int) vdiClose(void *pBackendData, bool fDelete)
1604{
1605 LogFlowFunc(("pBackendData=%#p fDelete=%d\n", pBackendData, fDelete));
1606 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1607
1608 int rc = vdiFreeImage(pImage, fDelete);
1609 RTMemFree(pImage);
1610
1611 LogFlowFunc(("returns %Rrc\n", rc));
1612 return rc;
1613}
1614
1615static DECLCALLBACK(int) vdiRead(void *pBackendData, uint64_t uOffset, size_t cbToRead,
1616 PVDIOCTX pIoCtx, size_t *pcbActuallyRead)
1617{
1618 LogFlowFunc(("pBackendData=%#p uOffset=%llu pIoCtx=%#p cbToRead=%zu pcbActuallyRead=%#p\n",
1619 pBackendData, uOffset, pIoCtx, cbToRead, pcbActuallyRead));
1620 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1621 unsigned uBlock;
1622 unsigned offRead;
1623 int rc = VINF_SUCCESS;
1624
1625 AssertPtr(pImage);
1626 Assert(!(uOffset % 512));
1627 Assert(!(cbToRead % 512));
1628 AssertPtrReturn(pIoCtx, VERR_INVALID_POINTER);
1629 AssertReturn(cbToRead, VERR_INVALID_PARAMETER);
1630 AssertReturn(uOffset + cbToRead <= getImageDiskSize(&pImage->Header), VERR_INVALID_PARAMETER);
1631
1632 /* Calculate starting block number and offset inside it. */
1633 uBlock = (unsigned)(uOffset >> pImage->uShiftOffset2Index);
1634 offRead = (unsigned)uOffset & pImage->uBlockMask;
1635
1636 /* Clip read range to at most the rest of the block. */
1637 size_t cbBlockRem = getImageBlockSize(&pImage->Header) - offRead;
1638 cbToRead = RT_MIN(cbToRead, cbBlockRem);
1639 Assert(!(cbToRead % 512));
1640
1641 if (pImage->paBlocks[uBlock] == VDI_IMAGE_BLOCK_FREE)
1642 rc = VERR_VD_BLOCK_FREE;
1643 else if (pImage->paBlocks[uBlock] == VDI_IMAGE_BLOCK_ZERO)
1644 {
1645 size_t cbSet;
1646
1647 cbSet = vdIfIoIntIoCtxSet(pImage->pIfIo, pIoCtx, 0, cbToRead);
1648 Assert(cbSet == cbToRead); RT_NOREF(cbSet);
1649 }
1650 else
1651 {
1652 /* Block present in image file, read relevant data. */
1653 uint64_t u64Offset = (uint64_t)pImage->paBlocks[uBlock] * pImage->cbTotalBlockData
1654 + (pImage->offStartData + pImage->offStartBlockData + offRead);
1655
1656 if (u64Offset + cbToRead <= pImage->cbImage)
1657 rc = vdIfIoIntFileReadUser(pImage->pIfIo, pImage->pStorage, u64Offset,
1658 pIoCtx, cbToRead);
1659 else
1660 {
1661 LogRel(("VDI: Out of range access (%llu) in image %s, image size %llu\n",
1662 u64Offset, pImage->pszFilename, pImage->cbImage));
1663 vdIfIoIntIoCtxSet(pImage->pIfIo, pIoCtx, 0, cbToRead);
1664 rc = VERR_VD_READ_OUT_OF_RANGE;
1665 }
1666 }
1667
1668 if (pcbActuallyRead)
1669 *pcbActuallyRead = cbToRead;
1670
1671 LogFlowFunc(("returns %Rrc\n", rc));
1672 return rc;
1673}
1674
1675static DECLCALLBACK(int) vdiWrite(void *pBackendData, uint64_t uOffset, size_t cbToWrite,
1676 PVDIOCTX pIoCtx, size_t *pcbWriteProcess, size_t *pcbPreRead,
1677 size_t *pcbPostRead, unsigned fWrite)
1678{
1679 LogFlowFunc(("pBackendData=%#p uOffset=%llu pIoCtx=%#p cbToWrite=%zu pcbWriteProcess=%#p pcbPreRead=%#p pcbPostRead=%#p\n",
1680 pBackendData, uOffset, pIoCtx, cbToWrite, pcbWriteProcess, pcbPreRead, pcbPostRead));
1681 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1682 unsigned uBlock;
1683 unsigned offWrite;
1684 int rc = VINF_SUCCESS;
1685
1686 AssertPtr(pImage);
1687 Assert(!(uOffset % 512));
1688 Assert(!(cbToWrite % 512));
1689 AssertPtrReturn(pIoCtx, VERR_INVALID_POINTER);
1690 AssertReturn(cbToWrite, VERR_INVALID_PARAMETER);
1691
1692 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
1693 {
1694 /* No size check here, will do that later. For dynamic images which are
1695 * not multiples of the block size in length, this would prevent writing to
1696 * the last block. */
1697
1698 /* Calculate starting block number and offset inside it. */
1699 uBlock = (unsigned)(uOffset >> pImage->uShiftOffset2Index);
1700 offWrite = (unsigned)uOffset & pImage->uBlockMask;
1701
1702 /* Clip write range to at most the rest of the block. */
1703 size_t cbBlockRem = getImageBlockSize(&pImage->Header) - offWrite;
1704 cbToWrite = RT_MIN(cbToWrite, cbBlockRem);
1705 Assert(!(cbToWrite % 512));
1706
1707 do
1708 {
1709 if (!IS_VDI_IMAGE_BLOCK_ALLOCATED(pImage->paBlocks[uBlock]))
1710 {
1711 /* Block is either free or zero. */
1712 if ( !(pImage->uOpenFlags & VD_OPEN_FLAGS_HONOR_ZEROES)
1713 && ( pImage->paBlocks[uBlock] == VDI_IMAGE_BLOCK_ZERO
1714 || cbToWrite == getImageBlockSize(&pImage->Header)))
1715 {
1716 /* If the destination block is unallocated at this point, it's
1717 * either a zero block or a block which hasn't been used so far
1718 * (which also means that it's a zero block. Don't need to write
1719 * anything to this block if the data consists of just zeroes. */
1720 if (vdIfIoIntIoCtxIsZero(pImage->pIfIo, pIoCtx, cbToWrite, true))
1721 {
1722 pImage->paBlocks[uBlock] = VDI_IMAGE_BLOCK_ZERO;
1723 *pcbPreRead = 0;
1724 *pcbPostRead = 0;
1725 break;
1726 }
1727 }
1728
1729 if ( cbToWrite == getImageBlockSize(&pImage->Header)
1730 && !(fWrite & VD_WRITE_NO_ALLOC))
1731 {
1732 /* Full block write to previously unallocated block.
1733 * Allocate block and write data. */
1734 Assert(!offWrite);
1735 PVDIASYNCBLOCKALLOC pBlockAlloc = (PVDIASYNCBLOCKALLOC)RTMemAllocZ(sizeof(VDIASYNCBLOCKALLOC));
1736 if (!pBlockAlloc)
1737 {
1738 rc = VERR_NO_MEMORY;
1739 break;
1740 }
1741
1742 unsigned cBlocksAllocated = getImageBlocksAllocated(&pImage->Header);
1743 uint64_t u64Offset = (uint64_t)cBlocksAllocated * pImage->cbTotalBlockData
1744 + (pImage->offStartData + pImage->offStartBlockData);
1745
1746 pBlockAlloc->cBlocksAllocated = cBlocksAllocated;
1747 pBlockAlloc->uBlock = uBlock;
1748
1749 *pcbPreRead = 0;
1750 *pcbPostRead = 0;
1751
1752 rc = vdIfIoIntFileWriteUser(pImage->pIfIo, pImage->pStorage,
1753 u64Offset, pIoCtx, cbToWrite,
1754 vdiBlockAllocUpdate, pBlockAlloc);
1755 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1756 break;
1757 else if (RT_FAILURE(rc))
1758 {
1759 RTMemFree(pBlockAlloc);
1760 break;
1761 }
1762
1763 rc = vdiBlockAllocUpdate(pImage, pIoCtx, pBlockAlloc, rc);
1764 }
1765 else
1766 {
1767 /* Trying to do a partial write to an unallocated block. Don't do
1768 * anything except letting the upper layer know what to do. */
1769 *pcbPreRead = offWrite % getImageBlockSize(&pImage->Header);
1770 *pcbPostRead = getImageBlockSize(&pImage->Header) - cbToWrite - *pcbPreRead;
1771 rc = VERR_VD_BLOCK_FREE;
1772 }
1773 }
1774 else
1775 {
1776 /* Block present in image file, write relevant data. */
1777 uint64_t u64Offset = (uint64_t)pImage->paBlocks[uBlock] * pImage->cbTotalBlockData
1778 + (pImage->offStartData + pImage->offStartBlockData + offWrite);
1779 rc = vdIfIoIntFileWriteUser(pImage->pIfIo, pImage->pStorage,
1780 u64Offset, pIoCtx, cbToWrite, NULL, NULL);
1781 }
1782 } while (0);
1783
1784 if (pcbWriteProcess)
1785 *pcbWriteProcess = cbToWrite;
1786 }
1787 else
1788 rc = VERR_VD_IMAGE_READ_ONLY;
1789
1790 LogFlowFunc(("returns %Rrc\n", rc));
1791 return rc;
1792}
1793
1794static DECLCALLBACK(int) vdiFlush(void *pBackendData, PVDIOCTX pIoCtx)
1795{
1796 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1797 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1798 int rc = VINF_SUCCESS;
1799
1800 Assert(pImage);
1801
1802 rc = vdiFlushImageIoCtx(pImage, pIoCtx);
1803 LogFlowFunc(("returns %Rrc\n", rc));
1804 return rc;
1805}
1806
1807/** @copydoc VDIMAGEBACKEND::pfnGetVersion */
1808static DECLCALLBACK(unsigned) vdiGetVersion(void *pBackendData)
1809{
1810 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1811 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1812
1813 AssertPtrReturn(pImage, 0);
1814
1815 LogFlowFunc(("returns %#x\n", pImage->PreHeader.u32Version));
1816 return pImage->PreHeader.u32Version;
1817}
1818
1819/** @copydoc VDIMAGEBACKEND::pfnGetFileSize */
1820static DECLCALLBACK(uint64_t) vdiGetFileSize(void *pBackendData)
1821{
1822 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1823 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1824 uint64_t cb = 0;
1825
1826 AssertPtrReturn(pImage, 0);
1827
1828 if (pImage->pStorage)
1829 {
1830 uint64_t cbFile;
1831 int rc = vdIfIoIntFileGetSize(pImage->pIfIo, pImage->pStorage, &cbFile);
1832 if (RT_SUCCESS(rc))
1833 cb += cbFile;
1834 }
1835
1836 LogFlowFunc(("returns %lld\n", cb));
1837 return cb;
1838}
1839
1840/** @copydoc VDIMAGEBACKEND::pfnGetPCHSGeometry */
1841static DECLCALLBACK(int) vdiGetPCHSGeometry(void *pBackendData, PVDGEOMETRY pPCHSGeometry)
1842{
1843 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p\n", pBackendData, pPCHSGeometry));
1844 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1845 int rc = VINF_SUCCESS;
1846
1847 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
1848
1849 if (pImage->PCHSGeometry.cCylinders)
1850 *pPCHSGeometry = pImage->PCHSGeometry;
1851 else
1852 rc = VERR_VD_GEOMETRY_NOT_SET;
1853
1854 LogFlowFunc(("returns %Rrc (PCHS=%u/%u/%u)\n", rc, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
1855 return rc;
1856}
1857
1858/** @copydoc VDIMAGEBACKEND::pfnSetPCHSGeometry */
1859static DECLCALLBACK(int) vdiSetPCHSGeometry(void *pBackendData, PCVDGEOMETRY pPCHSGeometry)
1860{
1861 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p PCHS=%u/%u/%u\n",
1862 pBackendData, pPCHSGeometry, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
1863 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1864 int rc = VINF_SUCCESS;
1865
1866 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
1867
1868 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
1869 rc = VERR_VD_IMAGE_READ_ONLY;
1870 else
1871 pImage->PCHSGeometry = *pPCHSGeometry;
1872
1873 LogFlowFunc(("returns %Rrc\n", rc));
1874 return rc;
1875}
1876
1877/** @copydoc VDIMAGEBACKEND::pfnGetLCHSGeometry */
1878static DECLCALLBACK(int) vdiGetLCHSGeometry(void *pBackendData, PVDGEOMETRY pLCHSGeometry)
1879{
1880 LogFlowFunc(("pBackendData=%#p pLCHSGeometry=%#p\n", pBackendData, pLCHSGeometry));
1881 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1882
1883 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
1884
1885 int rc = VINF_SUCCESS;
1886 VDIDISKGEOMETRY DummyGeo = { 0, 0, 0, VDI_GEOMETRY_SECTOR_SIZE };
1887 PVDIDISKGEOMETRY pGeometry = getImageLCHSGeometry(&pImage->Header);
1888 if (!pGeometry)
1889 pGeometry = &DummyGeo;
1890
1891 if ( pGeometry->cCylinders > 0
1892 && pGeometry->cHeads > 0
1893 && pGeometry->cSectors > 0)
1894 {
1895 pLCHSGeometry->cCylinders = pGeometry->cCylinders;
1896 pLCHSGeometry->cHeads = pGeometry->cHeads;
1897 pLCHSGeometry->cSectors = pGeometry->cSectors;
1898 }
1899 else
1900 rc = VERR_VD_GEOMETRY_NOT_SET;
1901
1902 LogFlowFunc(("returns %Rrc (LCHS=%u/%u/%u)\n", rc, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
1903 return rc;
1904}
1905
1906/** @copydoc VDIMAGEBACKEND::pfnSetLCHSGeometry */
1907static DECLCALLBACK(int) vdiSetLCHSGeometry(void *pBackendData, PCVDGEOMETRY pLCHSGeometry)
1908{
1909 LogFlowFunc(("pBackendData=%#p pLCHSGeometry=%#p LCHS=%u/%u/%u\n",
1910 pBackendData, pLCHSGeometry, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
1911 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1912 PVDIDISKGEOMETRY pGeometry;
1913 int rc = VINF_SUCCESS;
1914
1915 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
1916
1917 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
1918 {
1919 pGeometry = getImageLCHSGeometry(&pImage->Header);
1920 if (pGeometry)
1921 {
1922 pGeometry->cCylinders = pLCHSGeometry->cCylinders;
1923 pGeometry->cHeads = pLCHSGeometry->cHeads;
1924 pGeometry->cSectors = pLCHSGeometry->cSectors;
1925 pGeometry->cbSector = VDI_GEOMETRY_SECTOR_SIZE;
1926
1927 /* Update header information in base image file. */
1928 vdiFlushImage(pImage);
1929 }
1930 }
1931 else
1932 rc = VERR_VD_IMAGE_READ_ONLY;
1933
1934 LogFlowFunc(("returns %Rrc\n", rc));
1935 return rc;
1936}
1937
1938/** @copydoc VDIMAGEBACKEND::pfnQueryRegions */
1939static DECLCALLBACK(int) vdiQueryRegions(void *pBackendData, PCVDREGIONLIST *ppRegionList)
1940{
1941 LogFlowFunc(("pBackendData=%#p ppRegionList=%#p\n", pBackendData, ppRegionList));
1942 PVDIIMAGEDESC pThis = (PVDIIMAGEDESC)pBackendData;
1943
1944 AssertPtrReturn(pThis, VERR_VD_NOT_OPENED);
1945
1946 *ppRegionList = &pThis->RegionList;
1947 LogFlowFunc(("returns %Rrc\n", VINF_SUCCESS));
1948 return VINF_SUCCESS;
1949}
1950
1951/** @copydoc VDIMAGEBACKEND::pfnRegionListRelease */
1952static DECLCALLBACK(void) vdiRegionListRelease(void *pBackendData, PCVDREGIONLIST pRegionList)
1953{
1954 RT_NOREF1(pRegionList);
1955 LogFlowFunc(("pBackendData=%#p pRegionList=%#p\n", pBackendData, pRegionList));
1956 PVDIIMAGEDESC pThis = (PVDIIMAGEDESC)pBackendData;
1957 AssertPtr(pThis); RT_NOREF(pThis);
1958
1959 /* Nothing to do here. */
1960}
1961
1962/** @copydoc VDIMAGEBACKEND::pfnGetImageFlags */
1963static DECLCALLBACK(unsigned) vdiGetImageFlags(void *pBackendData)
1964{
1965 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1966 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1967
1968 AssertPtrReturn(pImage, 0);
1969
1970 LogFlowFunc(("returns %#x\n", pImage->uImageFlags));
1971 return pImage->uImageFlags;
1972}
1973
1974/** @copydoc VDIMAGEBACKEND::pfnGetOpenFlags */
1975static DECLCALLBACK(unsigned) vdiGetOpenFlags(void *pBackendData)
1976{
1977 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1978 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1979
1980 AssertPtrReturn(pImage, 0);
1981
1982 LogFlowFunc(("returns %#x\n", pImage->uOpenFlags));
1983 return pImage->uOpenFlags;
1984}
1985
1986/** @copydoc VDIMAGEBACKEND::pfnSetOpenFlags */
1987static DECLCALLBACK(int) vdiSetOpenFlags(void *pBackendData, unsigned uOpenFlags)
1988{
1989 LogFlowFunc(("pBackendData=%#p uOpenFlags=%#x\n", pBackendData, uOpenFlags));
1990 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1991 int rc;
1992
1993 /* Image must be opened and the new flags must be valid. */
1994 if (!pImage || (uOpenFlags & ~( VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO
1995 | VD_OPEN_FLAGS_ASYNC_IO | VD_OPEN_FLAGS_SHAREABLE
1996 | VD_OPEN_FLAGS_SEQUENTIAL | VD_OPEN_FLAGS_DISCARD
1997 | VD_OPEN_FLAGS_SKIP_CONSISTENCY_CHECKS)))
1998 rc = VERR_INVALID_PARAMETER;
1999 else
2000 {
2001 /* Implement this operation via reopening the image. */
2002 rc = vdiFreeImage(pImage, false);
2003 if (RT_SUCCESS(rc))
2004 rc = vdiOpenImage(pImage, uOpenFlags);
2005 }
2006
2007 LogFlowFunc(("returns %Rrc\n", rc));
2008 return rc;
2009}
2010
2011/** @copydoc VDIMAGEBACKEND::pfnGetComment */
2012static DECLCALLBACK(int) vdiGetComment(void *pBackendData, char *pszComment,
2013 size_t cbComment)
2014{
2015 LogFlowFunc(("pBackendData=%#p pszComment=%#p cbComment=%zu\n", pBackendData, pszComment, cbComment));
2016 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2017
2018 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2019
2020 int rc = VINF_SUCCESS;
2021 char *pszTmp = getImageComment(&pImage->Header);
2022 /* Make this foolproof even if the image doesn't have the zero
2023 * termination. With some luck the repaired header will be saved. */
2024 size_t cb = RTStrNLen(pszTmp, VDI_IMAGE_COMMENT_SIZE);
2025 if (cb == VDI_IMAGE_COMMENT_SIZE)
2026 {
2027 pszTmp[VDI_IMAGE_COMMENT_SIZE-1] = '\0';
2028 cb--;
2029 }
2030 if (cb < cbComment)
2031 {
2032 /* memcpy is much better than strncpy. */
2033 memcpy(pszComment, pszTmp, cb + 1);
2034 }
2035 else
2036 rc = VERR_BUFFER_OVERFLOW;
2037
2038 LogFlowFunc(("returns %Rrc comment=\"%s\"\n", rc, pszComment));
2039 return rc;
2040}
2041
2042/** @copydoc VDIMAGEBACKEND::pfnSetComment */
2043static DECLCALLBACK(int) vdiSetComment(void *pBackendData, const char *pszComment)
2044{
2045 LogFlowFunc(("pBackendData=%#p pszComment=\"%s\"\n", pBackendData, pszComment));
2046 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2047 int rc;
2048
2049 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2050
2051 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
2052 {
2053 size_t cchComment = pszComment ? strlen(pszComment) : 0;
2054 if (cchComment < VDI_IMAGE_COMMENT_SIZE)
2055 {
2056 /* we don't support old style images */
2057 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 1)
2058 {
2059 /*
2060 * Update the comment field, making sure to zero out all of the previous comment.
2061 */
2062 memset(pImage->Header.u.v1.szComment, '\0', VDI_IMAGE_COMMENT_SIZE);
2063 memcpy(pImage->Header.u.v1.szComment, pszComment, cchComment);
2064
2065 /* write out new the header */
2066 rc = vdiUpdateHeader(pImage);
2067 }
2068 else
2069 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
2070 }
2071 else
2072 {
2073 LogFunc(("pszComment is too long, %d bytes!\n", cchComment));
2074 rc = VERR_VD_VDI_COMMENT_TOO_LONG;
2075 }
2076 }
2077 else
2078 rc = VERR_VD_IMAGE_READ_ONLY;
2079
2080 LogFlowFunc(("returns %Rrc\n", rc));
2081 return rc;
2082}
2083
2084/** @copydoc VDIMAGEBACKEND::pfnGetUuid */
2085static DECLCALLBACK(int) vdiGetUuid(void *pBackendData, PRTUUID pUuid)
2086{
2087 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
2088 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2089
2090 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2091
2092 *pUuid = *getImageCreationUUID(&pImage->Header);
2093
2094 LogFlowFunc(("returns %Rrc (%RTuuid)\n", VINF_SUCCESS, pUuid));
2095 return VINF_SUCCESS;
2096}
2097
2098/** @copydoc VDIMAGEBACKEND::pfnSetUuid */
2099static DECLCALLBACK(int) vdiSetUuid(void *pBackendData, PCRTUUID pUuid)
2100{
2101 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
2102 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2103
2104 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2105
2106 int rc = VINF_SUCCESS;
2107 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
2108 {
2109 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 1)
2110 pImage->Header.u.v1.uuidCreate = *pUuid;
2111 /* Make it possible to clone old VDIs. */
2112 else if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 0)
2113 pImage->Header.u.v0.uuidCreate = *pUuid;
2114 else
2115 {
2116 LogFunc(("Version is not supported!\n"));
2117 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
2118 }
2119 }
2120 else
2121 rc = VERR_VD_IMAGE_READ_ONLY;
2122
2123 LogFlowFunc(("returns %Rrc\n", rc));
2124 return rc;
2125}
2126
2127/** @copydoc VDIMAGEBACKEND::pfnGetModificationUuid */
2128static DECLCALLBACK(int) vdiGetModificationUuid(void *pBackendData, PRTUUID pUuid)
2129{
2130 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
2131 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2132
2133 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2134
2135 *pUuid = *getImageModificationUUID(&pImage->Header);
2136
2137 LogFlowFunc(("returns %Rrc (%RTuuid)\n", VINF_SUCCESS, pUuid));
2138 return VINF_SUCCESS;
2139}
2140
2141/** @copydoc VDIMAGEBACKEND::pfnSetModificationUuid */
2142static DECLCALLBACK(int) vdiSetModificationUuid(void *pBackendData, PCRTUUID pUuid)
2143{
2144 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
2145 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2146
2147 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2148
2149 int rc = VINF_SUCCESS;
2150 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
2151 {
2152 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 1)
2153 pImage->Header.u.v1.uuidModify = *pUuid;
2154 /* Make it possible to clone old VDIs. */
2155 else if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 0)
2156 pImage->Header.u.v0.uuidModify = *pUuid;
2157 else
2158 {
2159 LogFunc(("Version is not supported!\n"));
2160 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
2161 }
2162 }
2163 else
2164 rc = VERR_VD_IMAGE_READ_ONLY;
2165
2166 LogFlowFunc(("returns %Rrc\n", rc));
2167 return rc;
2168}
2169
2170/** @copydoc VDIMAGEBACKEND::pfnGetParentUuid */
2171static DECLCALLBACK(int) vdiGetParentUuid(void *pBackendData, PRTUUID pUuid)
2172{
2173 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
2174 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2175
2176 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2177
2178 *pUuid = *getImageParentUUID(&pImage->Header);
2179
2180 LogFlowFunc(("returns %Rrc (%RTuuid)\n", VINF_SUCCESS, pUuid));
2181 return VINF_SUCCESS;
2182}
2183
2184/** @copydoc VDIMAGEBACKEND::pfnSetParentUuid */
2185static DECLCALLBACK(int) vdiSetParentUuid(void *pBackendData, PCRTUUID pUuid)
2186{
2187 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
2188 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2189
2190 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2191
2192 int rc = VINF_SUCCESS;
2193 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
2194 {
2195 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 1)
2196 pImage->Header.u.v1.uuidLinkage = *pUuid;
2197 /* Make it possible to clone old VDIs. */
2198 else if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 0)
2199 pImage->Header.u.v0.uuidLinkage = *pUuid;
2200 else
2201 {
2202 LogFunc(("Version is not supported!\n"));
2203 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
2204 }
2205 }
2206 else
2207 rc = VERR_VD_IMAGE_READ_ONLY;
2208
2209 LogFlowFunc(("returns %Rrc\n", rc));
2210 return rc;
2211}
2212
2213/** @copydoc VDIMAGEBACKEND::pfnGetParentModificationUuid */
2214static DECLCALLBACK(int) vdiGetParentModificationUuid(void *pBackendData, PRTUUID pUuid)
2215{
2216 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
2217 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2218
2219 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2220
2221 *pUuid = *getImageParentModificationUUID(&pImage->Header);
2222
2223 LogFlowFunc(("returns %Rrc (%RTuuid)\n", VINF_SUCCESS, pUuid));
2224 return VINF_SUCCESS;
2225}
2226
2227/** @copydoc VDIMAGEBACKEND::pfnSetParentModificationUuid */
2228static DECLCALLBACK(int) vdiSetParentModificationUuid(void *pBackendData, PCRTUUID pUuid)
2229{
2230 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
2231 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2232
2233 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2234
2235 int rc = VINF_SUCCESS;
2236 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
2237 {
2238 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 1)
2239 pImage->Header.u.v1.uuidParentModify = *pUuid;
2240 else
2241 {
2242 LogFunc(("Version is not supported!\n"));
2243 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
2244 }
2245 }
2246 else
2247 rc = VERR_VD_IMAGE_READ_ONLY;
2248
2249 LogFlowFunc(("returns %Rrc\n", rc));
2250 return rc;
2251}
2252
2253/** @copydoc VDIMAGEBACKEND::pfnDump */
2254static DECLCALLBACK(void) vdiDump(void *pBackendData)
2255{
2256 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2257
2258 AssertPtrReturnVoid(pImage);
2259 vdIfErrorMessage(pImage->pIfError, "Dumping VDI image \"%s\" mode=%s uOpenFlags=%X File=%#p\n",
2260 pImage->pszFilename,
2261 (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY) ? "r/o" : "r/w",
2262 pImage->uOpenFlags,
2263 pImage->pStorage);
2264 vdIfErrorMessage(pImage->pIfError, "Header: Version=%08X Type=%X Flags=%X Size=%llu\n",
2265 pImage->PreHeader.u32Version,
2266 getImageType(&pImage->Header),
2267 getImageFlags(&pImage->Header),
2268 getImageDiskSize(&pImage->Header));
2269 vdIfErrorMessage(pImage->pIfError, "Header: cbBlock=%u cbBlockExtra=%u cBlocks=%u cBlocksAllocated=%u\n",
2270 getImageBlockSize(&pImage->Header),
2271 getImageExtraBlockSize(&pImage->Header),
2272 getImageBlocks(&pImage->Header),
2273 getImageBlocksAllocated(&pImage->Header));
2274 vdIfErrorMessage(pImage->pIfError, "Header: offBlocks=%u offData=%u\n",
2275 getImageBlocksOffset(&pImage->Header),
2276 getImageDataOffset(&pImage->Header));
2277 PVDIDISKGEOMETRY pg = getImageLCHSGeometry(&pImage->Header);
2278 if (pg)
2279 vdIfErrorMessage(pImage->pIfError, "Header: Geometry: C/H/S=%u/%u/%u cbSector=%u\n",
2280 pg->cCylinders, pg->cHeads, pg->cSectors, pg->cbSector);
2281 vdIfErrorMessage(pImage->pIfError, "Header: uuidCreation={%RTuuid}\n", getImageCreationUUID(&pImage->Header));
2282 vdIfErrorMessage(pImage->pIfError, "Header: uuidModification={%RTuuid}\n", getImageModificationUUID(&pImage->Header));
2283 vdIfErrorMessage(pImage->pIfError, "Header: uuidParent={%RTuuid}\n", getImageParentUUID(&pImage->Header));
2284 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) >= 1)
2285 vdIfErrorMessage(pImage->pIfError, "Header: uuidParentModification={%RTuuid}\n", getImageParentModificationUUID(&pImage->Header));
2286 vdIfErrorMessage(pImage->pIfError, "Image: fFlags=%08X offStartBlocks=%u offStartData=%u\n",
2287 pImage->uImageFlags, pImage->offStartBlocks, pImage->offStartData);
2288 vdIfErrorMessage(pImage->pIfError, "Image: uBlockMask=%08X cbTotalBlockData=%u uShiftOffset2Index=%u offStartBlockData=%u\n",
2289 pImage->uBlockMask,
2290 pImage->cbTotalBlockData,
2291 pImage->uShiftOffset2Index,
2292 pImage->offStartBlockData);
2293
2294 unsigned uBlock, cBlocksNotFree, cBadBlocks, cBlocks = getImageBlocks(&pImage->Header);
2295 for (uBlock=0, cBlocksNotFree=0, cBadBlocks=0; uBlock<cBlocks; uBlock++)
2296 {
2297 if (IS_VDI_IMAGE_BLOCK_ALLOCATED(pImage->paBlocks[uBlock]))
2298 {
2299 cBlocksNotFree++;
2300 if (pImage->paBlocks[uBlock] >= cBlocks)
2301 cBadBlocks++;
2302 }
2303 }
2304 if (cBlocksNotFree != getImageBlocksAllocated(&pImage->Header))
2305 {
2306 vdIfErrorMessage(pImage->pIfError, "!! WARNING: %u blocks actually allocated (cBlocksAllocated=%u) !!\n",
2307 cBlocksNotFree, getImageBlocksAllocated(&pImage->Header));
2308 }
2309 if (cBadBlocks)
2310 {
2311 vdIfErrorMessage(pImage->pIfError, "!! WARNING: %u bad blocks found !!\n",
2312 cBadBlocks);
2313 }
2314}
2315
2316/** @copydoc VDIMAGEBACKEND::pfnCompact */
2317static DECLCALLBACK(int) vdiCompact(void *pBackendData, unsigned uPercentStart,
2318 unsigned uPercentSpan, PVDINTERFACE pVDIfsDisk,
2319 PVDINTERFACE pVDIfsImage, PVDINTERFACE pVDIfsOperation)
2320{
2321 RT_NOREF2(pVDIfsDisk, pVDIfsImage);
2322 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2323 int rc = VINF_SUCCESS;
2324 void *pvBuf = NULL, *pvTmp = NULL;
2325 unsigned *paBlocks2 = NULL;
2326
2327 PFNVDPARENTREAD pfnParentRead = NULL;
2328 void *pvParent = NULL;
2329 PVDINTERFACEPARENTSTATE pIfParentState = VDIfParentStateGet(pVDIfsOperation);
2330 if (pIfParentState)
2331 {
2332 pfnParentRead = pIfParentState->pfnParentRead;
2333 pvParent = pIfParentState->Core.pvUser;
2334 }
2335
2336 PVDINTERFACEPROGRESS pIfProgress = VDIfProgressGet(pVDIfsOperation);
2337 PVDINTERFACEQUERYRANGEUSE pIfQueryRangeUse = VDIfQueryRangeUseGet(pVDIfsOperation);
2338
2339 do
2340 {
2341 AssertBreakStmt(pImage, rc = VERR_INVALID_PARAMETER);
2342
2343 AssertBreakStmt(!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY),
2344 rc = VERR_VD_IMAGE_READ_ONLY);
2345
2346 unsigned cBlocks;
2347 unsigned cBlocksToMove = 0;
2348 size_t cbBlock;
2349 cBlocks = getImageBlocks(&pImage->Header);
2350 cbBlock = getImageBlockSize(&pImage->Header);
2351 if (pfnParentRead)
2352 {
2353 pvBuf = RTMemTmpAlloc(cbBlock);
2354 AssertBreakStmt(pvBuf, rc = VERR_NO_MEMORY);
2355 }
2356 pvTmp = RTMemTmpAlloc(cbBlock);
2357 AssertBreakStmt(pvTmp, rc = VERR_NO_MEMORY);
2358
2359 uint64_t cbFile;
2360 rc = vdIfIoIntFileGetSize(pImage->pIfIo, pImage->pStorage, &cbFile);
2361 AssertRCBreak(rc);
2362 unsigned cBlocksAllocated = (unsigned)((cbFile - pImage->offStartData - pImage->offStartBlockData) >> pImage->uShiftOffset2Index);
2363 if (cBlocksAllocated == 0)
2364 {
2365 /* No data blocks in this image, no need to compact. */
2366 rc = VINF_SUCCESS;
2367 break;
2368 }
2369
2370 /* Allocate block array for back resolving. */
2371 paBlocks2 = (unsigned *)RTMemAlloc(sizeof(unsigned *) * cBlocksAllocated);
2372 AssertBreakStmt(paBlocks2, rc = VERR_NO_MEMORY);
2373 /* Fill out back resolving, check/fix allocation errors before
2374 * compacting the image, just to be on the safe side. Update the
2375 * image contents straight away, as this enables cancelling. */
2376 for (unsigned i = 0; i < cBlocksAllocated; i++)
2377 paBlocks2[i] = VDI_IMAGE_BLOCK_FREE;
2378 rc = VINF_SUCCESS;
2379 for (unsigned i = 0; i < cBlocks; i++)
2380 {
2381 VDIIMAGEBLOCKPOINTER ptrBlock = pImage->paBlocks[i];
2382 if (IS_VDI_IMAGE_BLOCK_ALLOCATED(ptrBlock))
2383 {
2384 if (ptrBlock < cBlocksAllocated)
2385 {
2386 if (paBlocks2[ptrBlock] == VDI_IMAGE_BLOCK_FREE)
2387 paBlocks2[ptrBlock] = i;
2388 else
2389 {
2390 LogFunc(("Freed cross-linked block %u in file \"%s\"\n",
2391 i, pImage->pszFilename));
2392 pImage->paBlocks[i] = VDI_IMAGE_BLOCK_FREE;
2393 rc = vdiUpdateBlockInfo(pImage, i);
2394 if (RT_FAILURE(rc))
2395 break;
2396 }
2397 }
2398 else
2399 {
2400 LogFunc(("Freed out of bounds reference for block %u in file \"%s\"\n",
2401 i, pImage->pszFilename));
2402 pImage->paBlocks[i] = VDI_IMAGE_BLOCK_FREE;
2403 rc = vdiUpdateBlockInfo(pImage, i);
2404 if (RT_FAILURE(rc))
2405 break;
2406 }
2407 }
2408 }
2409 if (RT_FAILURE(rc))
2410 break;
2411
2412 /* Find redundant information and update the block pointers
2413 * accordingly, creating bubbles. Keep disk up to date, as this
2414 * enables cancelling. */
2415 for (unsigned i = 0; i < cBlocks; i++)
2416 {
2417 VDIIMAGEBLOCKPOINTER ptrBlock = pImage->paBlocks[i];
2418 if (IS_VDI_IMAGE_BLOCK_ALLOCATED(ptrBlock))
2419 {
2420 /* Block present in image file, read relevant data. */
2421 uint64_t u64Offset = (uint64_t)ptrBlock * pImage->cbTotalBlockData
2422 + (pImage->offStartData + pImage->offStartBlockData);
2423 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage, u64Offset, pvTmp, cbBlock);
2424 if (RT_FAILURE(rc))
2425 break;
2426
2427 if (ASMBitFirstSet((volatile void *)pvTmp, (uint32_t)cbBlock * 8) == -1)
2428 {
2429 pImage->paBlocks[i] = VDI_IMAGE_BLOCK_ZERO;
2430 rc = vdiUpdateBlockInfo(pImage, i);
2431 if (RT_FAILURE(rc))
2432 break;
2433 paBlocks2[ptrBlock] = VDI_IMAGE_BLOCK_FREE;
2434 /* Adjust progress info, one block to be relocated. */
2435 cBlocksToMove++;
2436 }
2437 else if (pfnParentRead)
2438 {
2439 rc = pfnParentRead(pvParent, (uint64_t)i * cbBlock, pvBuf, cbBlock);
2440 if (RT_FAILURE(rc))
2441 break;
2442 if (!memcmp(pvTmp, pvBuf, cbBlock))
2443 {
2444 pImage->paBlocks[i] = VDI_IMAGE_BLOCK_FREE;
2445 rc = vdiUpdateBlockInfo(pImage, i);
2446 if (RT_FAILURE(rc))
2447 break;
2448 paBlocks2[ptrBlock] = VDI_IMAGE_BLOCK_FREE;
2449 /* Adjust progress info, one block to be relocated. */
2450 cBlocksToMove++;
2451 }
2452 }
2453 }
2454
2455 /* Check if the range is in use if the block is still allocated. */
2456 ptrBlock = pImage->paBlocks[i];
2457 if ( IS_VDI_IMAGE_BLOCK_ALLOCATED(ptrBlock)
2458 && pIfQueryRangeUse)
2459 {
2460 bool fUsed = true;
2461
2462 rc = vdIfQueryRangeUse(pIfQueryRangeUse, (uint64_t)i * cbBlock, cbBlock, &fUsed);
2463 if (RT_FAILURE(rc))
2464 break;
2465 if (!fUsed)
2466 {
2467 pImage->paBlocks[i] = VDI_IMAGE_BLOCK_ZERO;
2468 rc = vdiUpdateBlockInfo(pImage, i);
2469 if (RT_FAILURE(rc))
2470 break;
2471 paBlocks2[ptrBlock] = VDI_IMAGE_BLOCK_FREE;
2472 /* Adjust progress info, one block to be relocated. */
2473 cBlocksToMove++;
2474 }
2475 }
2476
2477 vdIfProgress(pIfProgress, (uint64_t)i * uPercentSpan / (cBlocks + cBlocksToMove) + uPercentStart);
2478 if (RT_FAILURE(rc))
2479 break;
2480 }
2481 if (RT_FAILURE(rc))
2482 break;
2483
2484 /* Fill bubbles with other data (if available). */
2485 unsigned cBlocksMoved = 0;
2486 unsigned uBlockUsedPos = cBlocksAllocated;
2487 for (unsigned i = 0; i < cBlocksAllocated; i++)
2488 {
2489 unsigned uBlock = paBlocks2[i];
2490 if (uBlock == VDI_IMAGE_BLOCK_FREE)
2491 {
2492 unsigned uBlockData = VDI_IMAGE_BLOCK_FREE;
2493 while (uBlockUsedPos > i && uBlockData == VDI_IMAGE_BLOCK_FREE)
2494 {
2495 uBlockUsedPos--;
2496 uBlockData = paBlocks2[uBlockUsedPos];
2497 }
2498 /* Terminate early if there is no block which needs copying. */
2499 if (uBlockUsedPos == i)
2500 break;
2501 uint64_t u64Offset = (uint64_t)uBlockUsedPos * pImage->cbTotalBlockData
2502 + (pImage->offStartData + pImage->offStartBlockData);
2503 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage, u64Offset,
2504 pvTmp, cbBlock);
2505 if (RT_FAILURE(rc))
2506 break;
2507
2508 u64Offset = (uint64_t)i * pImage->cbTotalBlockData
2509 + (pImage->offStartData + pImage->offStartBlockData);
2510 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage, u64Offset,
2511 pvTmp, cbBlock);
2512 if (RT_FAILURE(rc))
2513 break;
2514
2515 pImage->paBlocks[uBlockData] = i;
2516 setImageBlocksAllocated(&pImage->Header, cBlocksAllocated - cBlocksMoved);
2517 rc = vdiUpdateBlockInfo(pImage, uBlockData);
2518 if (RT_FAILURE(rc))
2519 break;
2520 paBlocks2[i] = uBlockData;
2521 paBlocks2[uBlockUsedPos] = VDI_IMAGE_BLOCK_FREE;
2522 cBlocksMoved++;
2523 }
2524
2525 rc = vdIfProgress(pIfProgress, (uint64_t)(cBlocks + cBlocksMoved) * uPercentSpan / (cBlocks + cBlocksToMove) + uPercentStart);
2526 if (RT_FAILURE(rc))
2527 break;
2528 }
2529 if (RT_FAILURE(rc))
2530 break;
2531
2532 /* Update image header. */
2533 setImageBlocksAllocated(&pImage->Header, uBlockUsedPos);
2534 vdiUpdateHeader(pImage);
2535
2536 /* Truncate the image to the proper size to finish compacting. */
2537 rc = vdIfIoIntFileSetSize(pImage->pIfIo, pImage->pStorage,
2538 (uint64_t)uBlockUsedPos * pImage->cbTotalBlockData
2539 + pImage->offStartData + pImage->offStartBlockData);
2540 } while (0);
2541
2542 if (paBlocks2)
2543 RTMemTmpFree(paBlocks2);
2544 if (pvTmp)
2545 RTMemTmpFree(pvTmp);
2546 if (pvBuf)
2547 RTMemTmpFree(pvBuf);
2548
2549 if (RT_SUCCESS(rc))
2550 vdIfProgress(pIfProgress, uPercentStart + uPercentSpan);
2551
2552 LogFlowFunc(("returns %Rrc\n", rc));
2553 return rc;
2554}
2555
2556
2557/** @copydoc VDIMAGEBACKEND::pfnResize */
2558static DECLCALLBACK(int) vdiResize(void *pBackendData, uint64_t cbSize,
2559 PCVDGEOMETRY pPCHSGeometry, PCVDGEOMETRY pLCHSGeometry,
2560 unsigned uPercentStart, unsigned uPercentSpan,
2561 PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
2562 PVDINTERFACE pVDIfsOperation)
2563{
2564 RT_NOREF5(uPercentStart, uPercentSpan, pVDIfsDisk, pVDIfsImage, pVDIfsOperation);
2565 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2566 int rc = VINF_SUCCESS;
2567
2568 /* Check size. Maximum 4PB-3M. No tricks with adjusting the 1M block size
2569 * so far, which would extend the size. */
2570 if ( cbSize >= _1P * 4 - _1M * 3
2571 || cbSize < VDI_IMAGE_DEFAULT_BLOCK_SIZE)
2572 return VERR_VD_INVALID_SIZE;
2573
2574 /*
2575 * Making the image smaller is not supported at the moment.
2576 * Resizing is also not supported for fixed size images and
2577 * very old images.
2578 */
2579 /** @todo implement making the image smaller, it is the responsibility of
2580 * the user to know what he's doing. */
2581 if (cbSize < getImageDiskSize(&pImage->Header))
2582 rc = VERR_VD_SHRINK_NOT_SUPPORTED;
2583 else if ( GET_MAJOR_HEADER_VERSION(&pImage->Header) == 0
2584 || pImage->uImageFlags & VD_IMAGE_FLAGS_FIXED)
2585 rc = VERR_NOT_SUPPORTED;
2586 else if (cbSize > getImageDiskSize(&pImage->Header))
2587 {
2588 unsigned cBlocksAllocated = getImageBlocksAllocated(&pImage->Header); /** < Blocks currently allocated, doesn't change during resize */
2589 unsigned const cbBlock = getImageBlockSize(&pImage->Header);
2590 uint32_t cBlocksNew = cbSize / cbBlock; /** < New number of blocks in the image after the resize */
2591 if (cbSize % cbBlock)
2592 cBlocksNew++;
2593
2594 uint32_t cBlocksOld = getImageBlocks(&pImage->Header); /** < Number of blocks before the resize. */
2595 uint64_t cbBlockspaceNew = cBlocksNew * sizeof(VDIIMAGEBLOCKPOINTER); /** < Required space for the block array after the resize. */
2596 uint64_t offStartDataNew = RT_ALIGN_32(pImage->offStartBlocks + cbBlockspaceNew, VDI_DATA_ALIGN); /** < New start offset for block data after the resize */
2597
2598 if (pImage->offStartData < offStartDataNew)
2599 {
2600 if (cBlocksAllocated > 0)
2601 {
2602 /* Calculate how many sectors need to be relocated. */
2603 uint64_t cbOverlapping = offStartDataNew - pImage->offStartData;
2604 unsigned cBlocksReloc = cbOverlapping / cbBlock;
2605 if (cbOverlapping % cbBlock)
2606 cBlocksReloc++;
2607
2608 /* Since only full blocks can be relocated the new data start is
2609 * determined by moving it block by block. */
2610 cBlocksReloc = RT_MIN(cBlocksReloc, cBlocksAllocated);
2611 offStartDataNew = pImage->offStartData;
2612
2613 /* Do the relocation. */
2614 LogFlow(("Relocating %u blocks\n", cBlocksReloc));
2615
2616 /*
2617 * Get the blocks we need to relocate first, they are appended to the end
2618 * of the image.
2619 */
2620 void *pvBuf = NULL, *pvZero = NULL;
2621 do
2622 {
2623 /* Allocate data buffer. */
2624 pvBuf = RTMemAllocZ(pImage->cbTotalBlockData);
2625 if (!pvBuf)
2626 {
2627 rc = VERR_NO_MEMORY;
2628 break;
2629 }
2630
2631 /* Allocate buffer for overwriting with zeroes. */
2632 pvZero = RTMemAllocZ(pImage->cbTotalBlockData);
2633 if (!pvZero)
2634 {
2635 rc = VERR_NO_MEMORY;
2636 break;
2637 }
2638
2639 for (unsigned i = 0; i < cBlocksReloc; i++)
2640 {
2641 /* Search the index in the block table. */
2642 for (unsigned idxBlock = 0; idxBlock < cBlocksOld; idxBlock++)
2643 {
2644 if (!pImage->paBlocks[idxBlock])
2645 {
2646 /* Read data and append to the end of the image. */
2647 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage,
2648 offStartDataNew, pvBuf,
2649 pImage->cbTotalBlockData);
2650 if (RT_FAILURE(rc))
2651 break;
2652
2653 uint64_t offBlockAppend;
2654 rc = vdIfIoIntFileGetSize(pImage->pIfIo, pImage->pStorage, &offBlockAppend);
2655 if (RT_FAILURE(rc))
2656 break;
2657
2658 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage,
2659 offBlockAppend, pvBuf,
2660 pImage->cbTotalBlockData);
2661 if (RT_FAILURE(rc))
2662 break;
2663
2664 /* Zero out the old block area. */
2665 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage,
2666 offStartDataNew, pvZero,
2667 pImage->cbTotalBlockData);
2668 if (RT_FAILURE(rc))
2669 break;
2670
2671 /* Update block counter. */
2672 pImage->paBlocks[idxBlock] = cBlocksAllocated - 1;
2673
2674 /*
2675 * Decrease the block number of all other entries in the array.
2676 * They were moved one block to the front.
2677 * Doing it as a separate step iterating over the array again
2678 * because an error while relocating the block might end up
2679 * in a corrupted image otherwise.
2680 */
2681 for (unsigned idxBlock2 = 0; idxBlock2 < cBlocksOld; idxBlock2++)
2682 {
2683 if ( idxBlock2 != idxBlock
2684 && IS_VDI_IMAGE_BLOCK_ALLOCATED(pImage->paBlocks[idxBlock2]))
2685 pImage->paBlocks[idxBlock2]--;
2686 }
2687
2688 /* Continue with the next block. */
2689 break;
2690 }
2691 }
2692
2693 if (RT_FAILURE(rc))
2694 break;
2695
2696 offStartDataNew += pImage->cbTotalBlockData;
2697 }
2698 } while (0);
2699
2700 if (pvBuf)
2701 RTMemFree(pvBuf);
2702 if (pvZero)
2703 RTMemFree(pvZero);
2704 }
2705
2706 /*
2707 * We need to update the new offsets for the image data in the out of memory
2708 * case too because we relocated the blocks already.
2709 */
2710 pImage->offStartData = offStartDataNew;
2711 setImageDataOffset(&pImage->Header, offStartDataNew);
2712 }
2713
2714 /*
2715 * Relocation done, expand the block array and update the header with
2716 * the new data.
2717 */
2718 if (RT_SUCCESS(rc))
2719 {
2720 PVDIIMAGEBLOCKPOINTER paBlocksNew = (PVDIIMAGEBLOCKPOINTER)RTMemRealloc(pImage->paBlocks, cbBlockspaceNew);
2721 if (paBlocksNew)
2722 {
2723 pImage->paBlocks = paBlocksNew;
2724
2725 /* Mark the new blocks as unallocated. */
2726 for (unsigned idxBlock = cBlocksOld; idxBlock < cBlocksNew; idxBlock++)
2727 pImage->paBlocks[idxBlock] = VDI_IMAGE_BLOCK_FREE;
2728
2729 /* Write the block array before updating the rest. */
2730 vdiConvBlocksEndianess(VDIECONV_H2F, pImage->paBlocks, cBlocksNew);
2731 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage, pImage->offStartBlocks,
2732 pImage->paBlocks, cbBlockspaceNew);
2733 vdiConvBlocksEndianess(VDIECONV_F2H, pImage->paBlocks, cBlocksNew);
2734
2735 if (RT_SUCCESS(rc))
2736 {
2737 /* Update size and new block count. */
2738 setImageDiskSize(&pImage->Header, cbSize);
2739 setImageBlocks(&pImage->Header, cBlocksNew);
2740 /* Update geometry. */
2741 pImage->PCHSGeometry = *pPCHSGeometry;
2742 pImage->cbImage = cbSize;
2743
2744 PVDIDISKGEOMETRY pGeometry = getImageLCHSGeometry(&pImage->Header);
2745 if (pGeometry)
2746 {
2747 pGeometry->cCylinders = pLCHSGeometry->cCylinders;
2748 pGeometry->cHeads = pLCHSGeometry->cHeads;
2749 pGeometry->cSectors = pLCHSGeometry->cSectors;
2750 pGeometry->cbSector = VDI_GEOMETRY_SECTOR_SIZE;
2751 }
2752 }
2753 }
2754 else
2755 rc = VERR_NO_MEMORY;
2756 }
2757
2758 /* Update header information in base image file. */
2759 vdiFlushImage(pImage);
2760 }
2761 /* Same size doesn't change the image at all. */
2762
2763 LogFlowFunc(("returns %Rrc\n", rc));
2764 return rc;
2765}
2766
2767/** @copydoc VDIMAGEBACKEND::pfnDiscard */
2768static DECLCALLBACK(int) vdiDiscard(void *pBackendData, PVDIOCTX pIoCtx,
2769 uint64_t uOffset, size_t cbDiscard,
2770 size_t *pcbPreAllocated, size_t *pcbPostAllocated,
2771 size_t *pcbActuallyDiscarded, void **ppbmAllocationBitmap,
2772 unsigned fDiscard)
2773{
2774 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2775 unsigned uBlock;
2776 unsigned offDiscard;
2777 int rc = VINF_SUCCESS;
2778 void *pvBlock = NULL;
2779
2780 LogFlowFunc(("pBackendData=%#p pIoCtx=%#p uOffset=%llu cbDiscard=%zu pcbPreAllocated=%#p pcbPostAllocated=%#p pcbActuallyDiscarded=%#p ppbmAllocationBitmap=%#p fDiscard=%#x\n",
2781 pBackendData, pIoCtx, uOffset, cbDiscard, pcbPreAllocated, pcbPostAllocated, pcbActuallyDiscarded, ppbmAllocationBitmap, fDiscard));
2782
2783 AssertPtr(pImage);
2784 Assert(!(uOffset % 512));
2785 Assert(!(cbDiscard % 512));
2786
2787 AssertMsgReturn(!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY),
2788 ("Image is readonly\n"), VERR_VD_IMAGE_READ_ONLY);
2789 AssertMsgReturn( uOffset + cbDiscard <= getImageDiskSize(&pImage->Header)
2790 && cbDiscard,
2791 ("Invalid parameters uOffset=%llu cbDiscard=%zu\n",
2792 uOffset, cbDiscard),
2793 VERR_INVALID_PARAMETER);
2794
2795 do
2796 {
2797 AssertMsgBreakStmt(!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY),
2798 ("Image is opened readonly\n"),
2799 rc = VERR_VD_IMAGE_READ_ONLY);
2800
2801 AssertMsgBreakStmt(cbDiscard,
2802 ("cbDiscard=%u\n", cbDiscard),
2803 rc = VERR_INVALID_PARAMETER);
2804
2805 /* Calculate starting block number and offset inside it. */
2806 uBlock = (unsigned)(uOffset >> pImage->uShiftOffset2Index);
2807 offDiscard = (unsigned)uOffset & pImage->uBlockMask;
2808
2809 /* Clip range to at most the rest of the block. */
2810 size_t cbBlockRem = getImageBlockSize(&pImage->Header) - offDiscard;
2811 cbDiscard = RT_MIN(cbDiscard, cbBlockRem);
2812 Assert(!(cbDiscard % 512));
2813
2814 if (pcbPreAllocated)
2815 *pcbPreAllocated = 0;
2816
2817 if (pcbPostAllocated)
2818 *pcbPostAllocated = 0;
2819
2820 if (IS_VDI_IMAGE_BLOCK_ALLOCATED(pImage->paBlocks[uBlock]))
2821 {
2822 unsigned const cbBlock = getImageBlockSize(&pImage->Header);
2823 size_t const cbPreAllocated = offDiscard % cbBlock;
2824 size_t const cbPostAllocated = getImageBlockSize(&pImage->Header) - cbDiscard - cbPreAllocated;
2825 uint8_t *pbBlockData;
2826
2827 /* Read the block data. */
2828 pvBlock = RTMemAlloc(pImage->cbTotalBlockData);
2829 if (!pvBlock)
2830 {
2831 rc = VERR_NO_MEMORY;
2832 break;
2833 }
2834
2835 if (!cbPreAllocated && !cbPostAllocated)
2836 {
2837 /*
2838 * Discarding a whole block, don't check for allocated sectors.
2839 * It is possible to just remove the whole block which avoids
2840 * one read and checking the whole block for data.
2841 */
2842 rc = vdiDiscardBlockAsync(pImage, pIoCtx, uBlock, pvBlock);
2843 }
2844 else if (fDiscard & VD_DISCARD_MARK_UNUSED)
2845 {
2846 /* Just zero out the given range. */
2847 memset(pvBlock, 0, cbDiscard);
2848
2849 uint64_t u64Offset = (uint64_t)pImage->paBlocks[uBlock] * pImage->cbTotalBlockData + pImage->offStartData + offDiscard;
2850 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
2851 u64Offset, pvBlock, cbDiscard, pIoCtx,
2852 NULL, NULL);
2853 RTMemFree(pvBlock);
2854 }
2855 else
2856 {
2857 /*
2858 * Read complete block as metadata, the I/O context has no memory buffer
2859 * and we need to access the content directly anyway.
2860 */
2861 PVDMETAXFER pMetaXfer;
2862 pbBlockData = (uint8_t *)pvBlock + pImage->offStartBlockData;
2863
2864 uint64_t u64Offset = (uint64_t)pImage->paBlocks[uBlock] * pImage->cbTotalBlockData + pImage->offStartData;
2865 rc = vdIfIoIntFileReadMeta(pImage->pIfIo, pImage->pStorage, u64Offset,
2866 pbBlockData, pImage->cbTotalBlockData,
2867 pIoCtx, &pMetaXfer, NULL, NULL);
2868 if (RT_FAILURE(rc))
2869 {
2870 RTMemFree(pvBlock);
2871 break;
2872 }
2873
2874 vdIfIoIntMetaXferRelease(pImage->pIfIo, pMetaXfer);
2875
2876 /* Clear data. */
2877 memset(pbBlockData + offDiscard , 0, cbDiscard);
2878
2879 Assert(!(cbDiscard % 4));
2880 Assert(getImageBlockSize(&pImage->Header) * 8 <= UINT32_MAX);
2881 if (ASMBitFirstSet((volatile void *)pbBlockData, getImageBlockSize(&pImage->Header) * 8) == -1)
2882 rc = vdiDiscardBlockAsync(pImage, pIoCtx, uBlock, pvBlock);
2883 else
2884 {
2885 /* Block has data, create allocation bitmap. */
2886 *pcbPreAllocated = cbPreAllocated;
2887 *pcbPostAllocated = cbPostAllocated;
2888 *ppbmAllocationBitmap = vdiAllocationBitmapCreate(pbBlockData, getImageBlockSize(&pImage->Header));
2889 if (RT_UNLIKELY(!*ppbmAllocationBitmap))
2890 rc = VERR_NO_MEMORY;
2891 else
2892 rc = VERR_VD_DISCARD_ALIGNMENT_NOT_MET;
2893
2894 RTMemFree(pvBlock);
2895 }
2896 } /* if: no complete block discarded */
2897 } /* if: Block is allocated. */
2898 /* else: nothing to do. */
2899 } while (0);
2900
2901 if (pcbActuallyDiscarded)
2902 *pcbActuallyDiscarded = cbDiscard;
2903
2904 LogFlowFunc(("returns %Rrc\n", rc));
2905 return rc;
2906}
2907
2908/** @copydoc VDIMAGEBACKEND::pfnRepair */
2909static DECLCALLBACK(int) vdiRepair(const char *pszFilename, PVDINTERFACE pVDIfsDisk,
2910 PVDINTERFACE pVDIfsImage, uint32_t fFlags)
2911{
2912 LogFlowFunc(("pszFilename=\"%s\" pVDIfsDisk=%#p pVDIfsImage=%#p\n", pszFilename, pVDIfsDisk, pVDIfsImage));
2913 int rc;
2914 PVDINTERFACEERROR pIfError;
2915 PVDINTERFACEIOINT pIfIo;
2916 PVDIOSTORAGE pStorage = NULL;
2917 uint64_t cbFile;
2918 PVDIIMAGEBLOCKPOINTER paBlocks = NULL;
2919 uint32_t *pu32BlockBitmap = NULL;
2920 VDIPREHEADER PreHdr;
2921 VDIHEADER Hdr;
2922
2923 pIfIo = VDIfIoIntGet(pVDIfsImage);
2924 AssertPtrReturn(pIfIo, VERR_INVALID_PARAMETER);
2925
2926 pIfError = VDIfErrorGet(pVDIfsDisk);
2927
2928 do
2929 {
2930 bool fRepairBlockArray = false;
2931 bool fRepairHdr = false;
2932
2933 rc = vdIfIoIntFileOpen(pIfIo, pszFilename,
2934 VDOpenFlagsToFileOpenFlags( fFlags & VD_REPAIR_DRY_RUN
2935 ? VD_OPEN_FLAGS_READONLY
2936 : 0,
2937 false /* fCreate */),
2938 &pStorage);
2939 if (RT_FAILURE(rc))
2940 {
2941 rc = vdIfError(pIfError, rc, RT_SRC_POS, "VDI: Failed to open image \"%s\"", pszFilename);
2942 break;
2943 }
2944
2945 rc = vdIfIoIntFileGetSize(pIfIo, pStorage, &cbFile);
2946 if (RT_FAILURE(rc))
2947 {
2948 rc = vdIfError(pIfError, rc, RT_SRC_POS, "VDI: Failed to query image size");
2949 break;
2950 }
2951
2952 /* Read pre-header. */
2953 rc = vdIfIoIntFileReadSync(pIfIo, pStorage, 0, &PreHdr, sizeof(PreHdr));
2954 if (RT_FAILURE(rc))
2955 {
2956 rc = vdIfError(pIfError, rc, RT_SRC_POS, N_("VDI: Error reading pre-header in '%s'"), pszFilename);
2957 break;
2958 }
2959 vdiConvPreHeaderEndianess(VDIECONV_F2H, &PreHdr, &PreHdr);
2960 rc = vdiValidatePreHeader(&PreHdr);
2961 if (RT_FAILURE(rc))
2962 {
2963 rc = vdIfError(pIfError, VERR_VD_IMAGE_REPAIR_IMPOSSIBLE, RT_SRC_POS,
2964 N_("VDI: invalid pre-header in '%s'"), pszFilename);
2965 break;
2966 }
2967
2968 /* Read header. */
2969 Hdr.uVersion = PreHdr.u32Version;
2970 switch (GET_MAJOR_HEADER_VERSION(&Hdr))
2971 {
2972 case 0:
2973 rc = vdIfIoIntFileReadSync(pIfIo, pStorage, sizeof(PreHdr),
2974 &Hdr.u.v0, sizeof(Hdr.u.v0));
2975 if (RT_FAILURE(rc))
2976 rc = vdIfError(pIfError, rc, RT_SRC_POS, N_("VDI: error reading v0 header in '%s'"),
2977 pszFilename);
2978 vdiConvHeaderEndianessV0(VDIECONV_F2H, &Hdr.u.v0, &Hdr.u.v0);
2979 break;
2980 case 1:
2981 rc = vdIfIoIntFileReadSync(pIfIo, pStorage, sizeof(PreHdr),
2982 &Hdr.u.v1, sizeof(Hdr.u.v1));
2983 if (RT_FAILURE(rc))
2984 {
2985 rc = vdIfError(pIfError, rc, RT_SRC_POS, N_("VDI: error reading v1 header in '%s'"),
2986 pszFilename);
2987 }
2988 vdiConvHeaderEndianessV1(VDIECONV_F2H, &Hdr.u.v1, &Hdr.u.v1);
2989 if (Hdr.u.v1.cbHeader >= sizeof(Hdr.u.v1plus))
2990 {
2991 /* Read the VDI 1.1+ header completely. */
2992 rc = vdIfIoIntFileReadSync(pIfIo, pStorage, sizeof(PreHdr),
2993 &Hdr.u.v1plus, sizeof(Hdr.u.v1plus));
2994 if (RT_FAILURE(rc))
2995 rc = vdIfError(pIfError, rc, RT_SRC_POS, N_("VDI: error reading v1.1+ header in '%s'"),
2996 pszFilename);
2997 vdiConvHeaderEndianessV1p(VDIECONV_F2H, &Hdr.u.v1plus, &Hdr.u.v1plus);
2998 }
2999 break;
3000 default:
3001 rc = vdIfError(pIfError, VERR_VD_IMAGE_REPAIR_IMPOSSIBLE, RT_SRC_POS,
3002 N_("VDI: unsupported major version %u in '%s'"),
3003 GET_MAJOR_HEADER_VERSION(&Hdr), pszFilename);
3004 break;
3005 }
3006
3007 if (RT_SUCCESS(rc))
3008 {
3009 rc = vdiValidateHeader(&Hdr);
3010 if (RT_FAILURE(rc))
3011 {
3012 rc = vdIfError(pIfError, VERR_VD_IMAGE_REPAIR_IMPOSSIBLE, RT_SRC_POS,
3013 N_("VDI: invalid header in '%s'"), pszFilename);
3014 break;
3015 }
3016 }
3017
3018 /*
3019 * Check that the disk size is correctly aligned,
3020 * see comment above the same check in vdiImageReadHeader().
3021 */
3022 uint64_t cbDisk = getImageDiskSize(&Hdr);
3023 if (cbDisk & 0x1ff)
3024 {
3025 uint64_t cbDiskNew = cbDisk & ~UINT64_C(0x1ff);
3026 vdIfErrorMessage(pIfError, "Disk size in the header is not sector aligned, rounding down (%llu -> %llu)\n",
3027 cbDisk, cbDiskNew);
3028 setImageDiskSize(&Hdr, cbDiskNew);
3029 fRepairHdr = true;
3030 }
3031
3032 /* Setup image parameters by header. */
3033 uint64_t offStartBlocks, offStartData;
3034 size_t cbTotalBlockData;
3035
3036 offStartBlocks = getImageBlocksOffset(&Hdr);
3037 offStartData = getImageDataOffset(&Hdr);
3038 cbTotalBlockData = getImageExtraBlockSize(&Hdr) + getImageBlockSize(&Hdr);
3039
3040 /* Allocate memory for blocks array. */
3041 paBlocks = (PVDIIMAGEBLOCKPOINTER)RTMemAlloc(sizeof(VDIIMAGEBLOCKPOINTER) * getImageBlocks(&Hdr));
3042 if (!paBlocks)
3043 {
3044 rc = vdIfError(pIfError, VERR_NO_MEMORY, RT_SRC_POS,
3045 "Failed to allocate memory for block array");
3046 break;
3047 }
3048
3049 /* Read blocks array. */
3050 rc = vdIfIoIntFileReadSync(pIfIo, pStorage, offStartBlocks, paBlocks,
3051 getImageBlocks(&Hdr) * sizeof(VDIIMAGEBLOCKPOINTER));
3052 if (RT_FAILURE(rc))
3053 {
3054 rc = vdIfError(pIfError, VERR_VD_IMAGE_REPAIR_IMPOSSIBLE, RT_SRC_POS,
3055 "Failed to read block array (at %llu), %Rrc",
3056 offStartBlocks, rc);
3057 break;
3058 }
3059 vdiConvBlocksEndianess(VDIECONV_F2H, paBlocks, getImageBlocks(&Hdr));
3060
3061 pu32BlockBitmap = (uint32_t *)RTMemAllocZ(RT_ALIGN_Z(getImageBlocks(&Hdr) / 8, 4));
3062 if (!pu32BlockBitmap)
3063 {
3064 rc = vdIfError(pIfError, VERR_NO_MEMORY, RT_SRC_POS,
3065 "Failed to allocate memory for block bitmap");
3066 break;
3067 }
3068
3069 for (uint32_t i = 0; i < getImageBlocks(&Hdr); i++)
3070 {
3071 if (IS_VDI_IMAGE_BLOCK_ALLOCATED(paBlocks[i]))
3072 {
3073 uint64_t offBlock = (uint64_t)paBlocks[i] * cbTotalBlockData
3074 + offStartData;
3075
3076 /*
3077 * Check that the offsets are valid (inside of the image) and
3078 * that there are no double references.
3079 */
3080 if (offBlock + cbTotalBlockData > cbFile)
3081 {
3082 vdIfErrorMessage(pIfError, "Entry %u points to invalid offset %llu, clearing\n",
3083 i, offBlock);
3084 paBlocks[i] = VDI_IMAGE_BLOCK_FREE;
3085 fRepairBlockArray = true;
3086 }
3087 else if (ASMBitTestAndSet(pu32BlockBitmap, paBlocks[i]))
3088 {
3089 vdIfErrorMessage(pIfError, "Entry %u points to an already referenced data block, clearing\n",
3090 i);
3091 paBlocks[i] = VDI_IMAGE_BLOCK_FREE;
3092 fRepairBlockArray = true;
3093 }
3094 }
3095 }
3096
3097 /* Write repaired structures now. */
3098 if (!fRepairBlockArray && !fRepairHdr)
3099 vdIfErrorMessage(pIfError, "VDI image is in a consistent state, no repair required\n");
3100 else if (!(fFlags & VD_REPAIR_DRY_RUN))
3101 {
3102 if (fRepairHdr)
3103 {
3104 switch (GET_MAJOR_HEADER_VERSION(&Hdr))
3105 {
3106 case 0:
3107 {
3108 VDIHEADER0 Hdr0;
3109 vdiConvHeaderEndianessV0(VDIECONV_H2F, &Hdr0, &Hdr.u.v0);
3110 rc = vdIfIoIntFileWriteSync(pIfIo, pStorage, sizeof(VDIPREHEADER),
3111 &Hdr0, sizeof(Hdr0));
3112 break;
3113 }
3114 case 1:
3115 if (Hdr.u.v1plus.cbHeader < sizeof(Hdr.u.v1plus))
3116 {
3117 VDIHEADER1 Hdr1;
3118 vdiConvHeaderEndianessV1(VDIECONV_H2F, &Hdr1, &Hdr.u.v1);
3119 rc = vdIfIoIntFileWriteSync(pIfIo, pStorage, sizeof(VDIPREHEADER),
3120 &Hdr1, sizeof(Hdr1));
3121 }
3122 else
3123 {
3124 VDIHEADER1PLUS Hdr1plus;
3125 vdiConvHeaderEndianessV1p(VDIECONV_H2F, &Hdr1plus, &Hdr.u.v1plus);
3126 rc = vdIfIoIntFileWriteSync(pIfIo, pStorage, sizeof(VDIPREHEADER),
3127 &Hdr1plus, sizeof(Hdr1plus));
3128 }
3129 break;
3130 default:
3131 AssertMsgFailed(("Header indicates unsupported version which should not happen here!\n"));
3132 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
3133 break;
3134 }
3135 }
3136
3137 if (fRepairBlockArray)
3138 {
3139 vdIfErrorMessage(pIfError, "Writing repaired block allocation table...\n");
3140
3141 vdiConvBlocksEndianess(VDIECONV_H2F, paBlocks, getImageBlocks(&Hdr));
3142 rc = vdIfIoIntFileWriteSync(pIfIo, pStorage, offStartBlocks, paBlocks,
3143 getImageBlocks(&Hdr) * sizeof(VDIIMAGEBLOCKPOINTER));
3144 if (RT_FAILURE(rc))
3145 {
3146 rc = vdIfError(pIfError, VERR_VD_IMAGE_REPAIR_IMPOSSIBLE, RT_SRC_POS,
3147 "Could not write repaired block allocation table (at %llu), %Rrc",
3148 offStartBlocks, rc);
3149 break;
3150 }
3151 }
3152 }
3153
3154 vdIfErrorMessage(pIfError, "Corrupted VDI image repaired successfully\n");
3155 } while(0);
3156
3157 if (paBlocks)
3158 RTMemFree(paBlocks);
3159
3160 if (pu32BlockBitmap)
3161 RTMemFree(pu32BlockBitmap);
3162
3163 if (pStorage)
3164 {
3165 int rc2 = vdIfIoIntFileClose(pIfIo, pStorage);
3166 if (RT_SUCCESS(rc))
3167 rc = rc2; /* Propagate error code only if repairing was successful. */
3168 }
3169
3170 LogFlowFunc(("returns %Rrc\n", rc));
3171 return rc;
3172}
3173
3174const VDIMAGEBACKEND g_VDIBackend =
3175{
3176 /* u32Version */
3177 VD_IMGBACKEND_VERSION,
3178 /* pszBackendName */
3179 "VDI",
3180 /* uBackendCaps */
3181 VD_CAP_UUID | VD_CAP_CREATE_FIXED | VD_CAP_CREATE_DYNAMIC
3182 | VD_CAP_DIFF | VD_CAP_FILE | VD_CAP_ASYNC | VD_CAP_VFS | VD_CAP_DISCARD
3183 | VD_CAP_PREFERRED,
3184 /* paFileExtensions */
3185 s_aVdiFileExtensions,
3186 /* paConfigInfo */
3187 vdiConfigInfo,
3188 /* pfnProbe */
3189 vdiProbe,
3190 /* pfnOpen */
3191 vdiOpen,
3192 /* pfnCreate */
3193 vdiCreate,
3194 /* pfnRename */
3195 vdiRename,
3196 /* pfnClose */
3197 vdiClose,
3198 /* pfnRead */
3199 vdiRead,
3200 /* pfnWrite */
3201 vdiWrite,
3202 /* pfnFlush */
3203 vdiFlush,
3204 /* pfnDiscard */
3205 vdiDiscard,
3206 /* pfnGetVersion */
3207 vdiGetVersion,
3208 /* pfnGetFileSize */
3209 vdiGetFileSize,
3210 /* pfnGetPCHSGeometry */
3211 vdiGetPCHSGeometry,
3212 /* pfnSetPCHSGeometry */
3213 vdiSetPCHSGeometry,
3214 /* pfnGetLCHSGeometry */
3215 vdiGetLCHSGeometry,
3216 /* pfnSetLCHSGeometry */
3217 vdiSetLCHSGeometry,
3218 /* pfnQueryRegions */
3219 vdiQueryRegions,
3220 /* pfnRegionListRelease */
3221 vdiRegionListRelease,
3222 /* pfnGetImageFlags */
3223 vdiGetImageFlags,
3224 /* pfnGetOpenFlags */
3225 vdiGetOpenFlags,
3226 /* pfnSetOpenFlags */
3227 vdiSetOpenFlags,
3228 /* pfnGetComment */
3229 vdiGetComment,
3230 /* pfnSetComment */
3231 vdiSetComment,
3232 /* pfnGetUuid */
3233 vdiGetUuid,
3234 /* pfnSetUuid */
3235 vdiSetUuid,
3236 /* pfnGetModificationUuid */
3237 vdiGetModificationUuid,
3238 /* pfnSetModificationUuid */
3239 vdiSetModificationUuid,
3240 /* pfnGetParentUuid */
3241 vdiGetParentUuid,
3242 /* pfnSetParentUuid */
3243 vdiSetParentUuid,
3244 /* pfnGetParentModificationUuid */
3245 vdiGetParentModificationUuid,
3246 /* pfnSetParentModificationUuid */
3247 vdiSetParentModificationUuid,
3248 /* pfnDump */
3249 vdiDump,
3250 /* pfnGetTimestamp */
3251 NULL,
3252 /* pfnGetParentTimestamp */
3253 NULL,
3254 /* pfnSetParentTimestamp */
3255 NULL,
3256 /* pfnGetParentFilename */
3257 NULL,
3258 /* pfnSetParentFilename */
3259 NULL,
3260 /* pfnComposeLocation */
3261 genericFileComposeLocation,
3262 /* pfnComposeName */
3263 genericFileComposeName,
3264 /* pfnCompact */
3265 vdiCompact,
3266 /* pfnResize */
3267 vdiResize,
3268 /* pfnRepair */
3269 vdiRepair,
3270 /* pfnTraverseMetadata */
3271 NULL,
3272 /* u32VersionEnd */
3273 VD_IMGBACKEND_VERSION
3274};
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use