VirtualBox

source: vbox/trunk/src/VBox/Devices/Storage/VDICore.cpp@ 5869

Last change on this file since 5869 was 5496, checked in by vboxsync, 17 years ago

todo

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 127.1 KB
Line 
1/** @file
2 * Virtual Disk Image (VDI), Core Code.
3 */
4
5/*
6 * Copyright (C) 2006-2007 innotek GmbH
7 *
8 * This file is part of VirtualBox Open Source Edition (OSE), as
9 * available from http://www.virtualbox.org. This file is free software;
10 * you can redistribute it and/or modify it under the terms of the GNU
11 * General Public License as published by the Free Software Foundation,
12 * in version 2 as it comes in the "COPYING" file of the VirtualBox OSE
13 * distribution. VirtualBox OSE is distributed in the hope that it will
14 * be useful, but WITHOUT ANY WARRANTY of any kind.
15 */
16
17/*******************************************************************************
18* Header Files *
19*******************************************************************************/
20#define LOG_GROUP LOG_GROUP_DRV_VBOXHDD
21#include <VBox/VBoxHDD.h>
22#include "VDICore.h"
23#include <VBox/err.h>
24
25#include <VBox/log.h>
26#include <iprt/alloc.h>
27#include <iprt/assert.h>
28#include <iprt/uuid.h>
29#include <iprt/file.h>
30#include <iprt/string.h>
31#include <iprt/asm.h>
32
33
34/*******************************************************************************
35* Internal Functions *
36*******************************************************************************/
37static unsigned getPowerOfTwo(unsigned uNumber);
38static void vdiInitPreHeader(PVDIPREHEADER pPreHdr);
39static int vdiValidatePreHeader(PVDIPREHEADER pPreHdr);
40static void vdiInitHeader(PVDIHEADER pHeader, VDIIMAGETYPE enmType, uint32_t fFlags,
41 const char *pszComment, uint64_t cbDisk, uint32_t cbBlock,
42 uint32_t cbBlockExtra);
43static int vdiValidateHeader(PVDIHEADER pHeader);
44static int vdiCreateImage(const char *pszFilename, VDIIMAGETYPE enmType, unsigned fFlags,
45 uint64_t cbSize, const char *pszComment, PVDIIMAGEDESC pParent,
46 PFNVMPROGRESS pfnProgress, void *pvUser);
47static void vdiInitImageDesc(PVDIIMAGEDESC pImage);
48static void vdiSetupImageDesc(PVDIIMAGEDESC pImage);
49static int vdiOpenImage(PVDIIMAGEDESC *ppImage, const char *pszFilename, unsigned fOpen,
50 PVDIIMAGEDESC pParent);
51static int vdiUpdateHeader(PVDIIMAGEDESC pImage);
52static int vdiUpdateBlockInfo(PVDIIMAGEDESC pImage, unsigned uBlock);
53static int vdiUpdateBlocks(PVDIIMAGEDESC pImage);
54static void vdiSetModifiedFlag(PVDIIMAGEDESC pImage);
55static void vdiResetModifiedFlag(PVDIIMAGEDESC pImage);
56static void vdiDisableLastModifiedUpdate(PVDIIMAGEDESC pImage);
57#if 0 /* unused */
58static void vdiEnableLastModifiedUpdate(PVDIIMAGEDESC pImage);
59#endif
60static void vdiCloseImage(PVDIIMAGEDESC pImage);
61static int vdiReadInBlock(PVDIIMAGEDESC pImage, unsigned uBlock, unsigned offRead,
62 size_t cbToRead, void *pvBuf);
63static int vdiFillBlockByZeroes(PVDIDISK pDisk, PVDIIMAGEDESC pImage, unsigned uBlock);
64static int vdiWriteInBlock(PVDIDISK pDisk, PVDIIMAGEDESC pImage, unsigned uBlock,
65 unsigned offWrite, size_t cbToWrite, const void *pvBuf);
66static int vdiCopyBlock(PVDIDISK pDisk, PVDIIMAGEDESC pImage, unsigned uBlock);
67static int vdiMergeImages(PVDIIMAGEDESC pImageFrom, PVDIIMAGEDESC pImageTo, bool fParentToChild,
68 PFNVMPROGRESS pfnProgress, void *pvUser);
69static void vdiAddImageToList(PVDIDISK pDisk, PVDIIMAGEDESC pImage);
70static void vdiRemoveImageFromList(PVDIDISK pDisk, PVDIIMAGEDESC pImage);
71static PVDIIMAGEDESC vdiGetImageByNumber(PVDIDISK pDisk, int nImage);
72static int vdiUpdateReadOnlyHeader(PVDIIMAGEDESC pImage);
73
74static int vdiCommitToImage(PVDIDISK pDisk, PVDIIMAGEDESC pDstImage,
75 PFNVMPROGRESS pfnProgress, void *pvUser);
76static void vdiDumpImage(PVDIIMAGEDESC pImage);
77
78
79/**
80 * internal: return power of 2 or 0 if num error.
81 */
82static unsigned getPowerOfTwo(unsigned uNumber)
83{
84 if (uNumber == 0)
85 return 0;
86 unsigned uPower2 = 0;
87 while ((uNumber & 1) == 0)
88 {
89 uNumber >>= 1;
90 uPower2++;
91 }
92 return uNumber == 1 ? uPower2 : 0;
93}
94
95/**
96 * internal: init HDD preheader.
97 */
98static void vdiInitPreHeader(PVDIPREHEADER pPreHdr)
99{
100 pPreHdr->u32Signature = VDI_IMAGE_SIGNATURE;
101 pPreHdr->u32Version = VDI_IMAGE_VERSION;
102 memset(pPreHdr->szFileInfo, 0, sizeof(pPreHdr->szFileInfo));
103 strncat(pPreHdr->szFileInfo, VDI_IMAGE_FILE_INFO, sizeof(pPreHdr->szFileInfo));
104}
105
106/**
107 * internal: check HDD preheader.
108 */
109static int vdiValidatePreHeader(PVDIPREHEADER pPreHdr)
110{
111 if (pPreHdr->u32Signature != VDI_IMAGE_SIGNATURE)
112 return VERR_VDI_INVALID_SIGNATURE;
113
114 if ( pPreHdr->u32Version != VDI_IMAGE_VERSION
115 && pPreHdr->u32Version != 0x00000002) /* old version. */
116 return VERR_VDI_UNSUPPORTED_VERSION;
117
118 return VINF_SUCCESS;
119}
120
121/**
122 * internal: init HDD header. Always use latest header version.
123 * @param pHeader Assumes it was initially initialized to all zeros.
124 */
125static void vdiInitHeader(PVDIHEADER pHeader, VDIIMAGETYPE enmType, uint32_t fFlags,
126 const char *pszComment, uint64_t cbDisk, uint32_t cbBlock,
127 uint32_t cbBlockExtra)
128{
129 pHeader->uVersion = VDI_IMAGE_VERSION;
130 pHeader->u.v1.cbHeader = sizeof(VDIHEADER1);
131 pHeader->u.v1.u32Type = (uint32_t)enmType;
132 pHeader->u.v1.fFlags = fFlags;
133#ifdef VBOX_STRICT
134 char achZero[VDI_IMAGE_COMMENT_SIZE] = {0};
135 Assert(!memcmp(pHeader->u.v1.szComment, achZero, VDI_IMAGE_COMMENT_SIZE));
136#endif
137 pHeader->u.v1.szComment[0] = '\0';
138 if (pszComment)
139 {
140 AssertMsg(strlen(pszComment) < sizeof(pHeader->u.v1.szComment),
141 ("HDD Comment is too long, cb=%d\n", strlen(pszComment)));
142 strncat(pHeader->u.v1.szComment, pszComment, sizeof(pHeader->u.v1.szComment));
143 }
144
145 /* Mark the geometry not-calculated. */
146 pHeader->u.v1.Geometry.cCylinders = 0;
147 pHeader->u.v1.Geometry.cHeads = 0;
148 pHeader->u.v1.Geometry.cSectors = 0;
149 pHeader->u.v1.Geometry.cbSector = VDI_GEOMETRY_SECTOR_SIZE;
150 pHeader->u.v1.u32Translation = PDMBIOSTRANSLATION_AUTO;
151
152 pHeader->u.v1.cbDisk = cbDisk;
153 pHeader->u.v1.cbBlock = cbBlock;
154 pHeader->u.v1.cBlocks = (uint32_t)(cbDisk / cbBlock);
155 if (cbDisk % cbBlock)
156 pHeader->u.v1.cBlocks++;
157 pHeader->u.v1.cbBlockExtra = cbBlockExtra;
158 pHeader->u.v1.cBlocksAllocated = 0;
159
160 /* Init offsets. */
161 pHeader->u.v1.offBlocks = RT_ALIGN_32(sizeof(VDIPREHEADER) + sizeof(VDIHEADER1), VDI_GEOMETRY_SECTOR_SIZE);
162 pHeader->u.v1.offData = RT_ALIGN_32(pHeader->u.v1.offBlocks + (pHeader->u.v1.cBlocks * sizeof(VDIIMAGEBLOCKPOINTER)), VDI_GEOMETRY_SECTOR_SIZE);
163
164 /* Init uuids. */
165 RTUuidCreate(&pHeader->u.v1.uuidCreate);
166 RTUuidClear(&pHeader->u.v1.uuidModify);
167 RTUuidClear(&pHeader->u.v1.uuidLinkage);
168 RTUuidClear(&pHeader->u.v1.uuidParentModify);
169}
170
171/**
172 * internal: check HDD header.
173 */
174static int vdiValidateHeader(PVDIHEADER pHeader)
175{
176 /* Check verion-dependend header parameters. */
177 switch (GET_MAJOR_HEADER_VERSION(pHeader))
178 {
179 case 0:
180 {
181 /* Old header version. */
182 break;
183 }
184 case 1:
185 {
186 /* Current header version. */
187
188 if (pHeader->u.v1.cbHeader < sizeof(VDIHEADER1))
189 {
190 LogRel(("VDI: v1 header size wrong (%d < %d)\n",
191 pHeader->u.v1.cbHeader, sizeof(VDIHEADER1)));
192 return VERR_VDI_INVALID_HEADER;
193 }
194
195 if (getImageBlocksOffset(pHeader) < (sizeof(VDIPREHEADER) + sizeof(VDIHEADER1)))
196 {
197 LogRel(("VDI: v1 blocks offset wrong (%d < %d)\n",
198 getImageBlocksOffset(pHeader), sizeof(VDIPREHEADER) + sizeof(VDIHEADER1)));
199 return VERR_VDI_INVALID_HEADER;
200 }
201
202 if (getImageDataOffset(pHeader) < (getImageBlocksOffset(pHeader) + getImageBlocks(pHeader) * sizeof(VDIIMAGEBLOCKPOINTER)))
203 {
204 LogRel(("VDI: v1 image data offset wrong (%d < %d)\n",
205 getImageDataOffset(pHeader), getImageBlocksOffset(pHeader) + getImageBlocks(pHeader) * sizeof(VDIIMAGEBLOCKPOINTER)));
206 return VERR_VDI_INVALID_HEADER;
207 }
208
209 if ( getImageType(pHeader) == VDI_IMAGE_TYPE_UNDO
210 || getImageType(pHeader) == VDI_IMAGE_TYPE_DIFF)
211 {
212 if (RTUuidIsNull(getImageParentUUID(pHeader)))
213 {
214 LogRel(("VDI: v1 uuid of parent is 0)\n"));
215 return VERR_VDI_INVALID_HEADER;
216 }
217 if (RTUuidIsNull(getImageParentModificationUUID(pHeader)))
218 {
219 LogRel(("VDI: v1 uuid of parent modification is 0\n"));
220 return VERR_VDI_INVALID_HEADER;
221 }
222 }
223
224 break;
225 }
226 default:
227 /* Unsupported. */
228 return VERR_VDI_UNSUPPORTED_VERSION;
229 }
230
231 /* Check common header parameters. */
232
233 bool fFailed = false;
234
235 if ( getImageType(pHeader) < VDI_IMAGE_TYPE_FIRST
236 || getImageType(pHeader) > VDI_IMAGE_TYPE_LAST)
237 {
238 LogRel(("VDI: bad image type %d\n", getImageType(pHeader)));
239 fFailed = true;
240 }
241
242 if (getImageFlags(pHeader) & ~VDI_IMAGE_FLAGS_MASK)
243 {
244 LogRel(("VDI: bad image flags %08x\n", getImageFlags(pHeader)));
245 fFailed = true;
246 }
247
248 if ((getImageGeometry(pHeader))->cbSector != VDI_GEOMETRY_SECTOR_SIZE)
249 {
250 LogRel(("VDI: wrong sector size (%d != %d)\n",
251 (getImageGeometry(pHeader))->cbSector, VDI_GEOMETRY_SECTOR_SIZE));
252 fFailed = true;
253 }
254
255 if ( getImageDiskSize(pHeader) == 0
256 || getImageBlockSize(pHeader) == 0
257 || getImageBlocks(pHeader) == 0
258 || getPowerOfTwo(getImageBlockSize(pHeader)) == 0)
259 {
260 LogRel(("VDI: wrong size (%lld, %d, %d, %d)\n",
261 getImageDiskSize(pHeader), getImageBlockSize(pHeader),
262 getImageBlocks(pHeader), getPowerOfTwo(getImageBlockSize(pHeader))));
263 fFailed = true;
264 }
265
266 if (getImageBlocksAllocated(pHeader) > getImageBlocks(pHeader))
267 {
268 LogRel(("VDI: too many blocks allocated (%d > %d)\n"
269 " blocksize=%d disksize=%lld\n",
270 getImageBlocksAllocated(pHeader), getImageBlocks(pHeader),
271 getImageBlockSize(pHeader), getImageDiskSize(pHeader)));
272 fFailed = true;
273 }
274
275 if ( getImageExtraBlockSize(pHeader) != 0
276 && getPowerOfTwo(getImageExtraBlockSize(pHeader)) == 0)
277 {
278 LogRel(("VDI: wrong extra size (%d, %d)\n",
279 getImageExtraBlockSize(pHeader), getPowerOfTwo(getImageExtraBlockSize(pHeader))));
280 fFailed = true;
281 }
282
283 if ((uint64_t)getImageBlockSize(pHeader) * getImageBlocks(pHeader) < getImageDiskSize(pHeader))
284 {
285 LogRel(("VDI: wrong disk size (%d, %d, %lld)\n",
286 getImageBlockSize(pHeader), getImageBlocks(pHeader), getImageDiskSize(pHeader)));
287 fFailed = true;
288 }
289
290 if (RTUuidIsNull(getImageCreationUUID(pHeader)))
291 {
292 LogRel(("VDI: uuid of creator is 0\n"));
293 fFailed = true;
294 }
295
296 if (RTUuidIsNull(getImageModificationUUID(pHeader)))
297 {
298 LogRel(("VDI: uuid of modificator is 0\n"));
299 fFailed = true;
300 }
301
302 return fFailed ? VERR_VDI_INVALID_HEADER : VINF_SUCCESS;
303}
304
305/**
306 * internal: init VDIIMAGEDESC structure.
307 */
308static void vdiInitImageDesc(PVDIIMAGEDESC pImage)
309{
310 pImage->pPrev = NULL;
311 pImage->pNext = NULL;
312 pImage->File = NIL_RTFILE;
313 pImage->paBlocks = NULL;
314}
315
316/**
317 * internal: setup VDIIMAGEDESC structure by image header.
318 */
319static void vdiSetupImageDesc(PVDIIMAGEDESC pImage)
320{
321 pImage->fFlags = getImageFlags(&pImage->Header);
322 pImage->offStartBlocks = getImageBlocksOffset(&pImage->Header);
323 pImage->offStartData = getImageDataOffset(&pImage->Header);
324 pImage->uBlockMask = getImageBlockSize(&pImage->Header) - 1;
325 pImage->uShiftIndex2Offset =
326 pImage->uShiftOffset2Index = getPowerOfTwo(getImageBlockSize(&pImage->Header));
327 pImage->offStartBlockData = getImageExtraBlockSize(&pImage->Header);
328 if (pImage->offStartBlockData != 0)
329 pImage->uShiftIndex2Offset += getPowerOfTwo(pImage->offStartBlockData);
330}
331
332/**
333 * internal: create image.
334 */
335static int vdiCreateImage(const char *pszFilename, VDIIMAGETYPE enmType, unsigned fFlags,
336 uint64_t cbSize, const char *pszComment, PVDIIMAGEDESC pParent,
337 PFNVMPROGRESS pfnProgress, void *pvUser)
338{
339 /* Check args. */
340 Assert(pszFilename);
341 Assert(enmType >= VDI_IMAGE_TYPE_FIRST && enmType <= VDI_IMAGE_TYPE_LAST);
342 Assert(!(fFlags & ~VDI_IMAGE_FLAGS_MASK));
343 Assert(cbSize);
344
345 /* Special check for comment length. */
346 if ( pszComment
347 && strlen(pszComment) >= VDI_IMAGE_COMMENT_SIZE)
348 {
349 Log(("vdiCreateImage: pszComment is too long, cb=%d\n", strlen(pszComment)));
350 return VERR_VDI_COMMENT_TOO_LONG;
351 }
352
353 if ( enmType == VDI_IMAGE_TYPE_UNDO
354 || enmType == VDI_IMAGE_TYPE_DIFF)
355 {
356 Assert(pParent);
357 if ((pParent->PreHeader.u32Version >> 16) != VDI_IMAGE_VERSION_MAJOR)
358 {
359 /* Invalid parent image version. */
360 Log(("vdiCreateImage: unsupported parent version=%08X\n", pParent->PreHeader.u32Version));
361 return VERR_VDI_UNSUPPORTED_VERSION;
362 }
363
364 /* get image params from the parent image. */
365 fFlags = getImageFlags(&pParent->Header);
366 cbSize = getImageDiskSize(&pParent->Header);
367 }
368
369 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)RTMemAllocZ(sizeof(VDIIMAGEDESC));
370 if (!pImage)
371 return VERR_NO_MEMORY;
372 vdiInitImageDesc(pImage);
373
374 vdiInitPreHeader(&pImage->PreHeader);
375 vdiInitHeader(&pImage->Header, enmType, fFlags, pszComment, cbSize, VDI_IMAGE_DEFAULT_BLOCK_SIZE, 0);
376
377 if ( enmType == VDI_IMAGE_TYPE_UNDO
378 || enmType == VDI_IMAGE_TYPE_DIFF)
379 {
380 /* Set up linkage information. */
381 pImage->Header.u.v1.uuidLinkage = *getImageCreationUUID(&pParent->Header);
382 pImage->Header.u.v1.uuidParentModify = *getImageModificationUUID(&pParent->Header);
383 }
384
385 pImage->paBlocks = (PVDIIMAGEBLOCKPOINTER)RTMemAlloc(sizeof(VDIIMAGEBLOCKPOINTER) * getImageBlocks(&pImage->Header));
386 if (!pImage->paBlocks)
387 {
388 RTMemFree(pImage);
389 return VERR_NO_MEMORY;
390 }
391
392 if (enmType != VDI_IMAGE_TYPE_FIXED)
393 {
394 /* for growing images mark all blocks in paBlocks as free. */
395 for (unsigned i = 0; i < pImage->Header.u.v1.cBlocks; i++)
396 pImage->paBlocks[i] = VDI_IMAGE_BLOCK_FREE;
397 }
398 else
399 {
400 /* for fixed images mark all blocks in paBlocks as allocated */
401 for (unsigned i = 0; i < pImage->Header.u.v1.cBlocks; i++)
402 pImage->paBlocks[i] = i;
403 pImage->Header.u.v1.cBlocksAllocated = pImage->Header.u.v1.cBlocks;
404 }
405
406 /* Setup image parameters. */
407 vdiSetupImageDesc(pImage);
408
409 /* create file */
410 int rc = RTFileOpen(&pImage->File,
411 pszFilename,
412 RTFILE_O_READWRITE | RTFILE_O_CREATE | RTFILE_O_DENY_ALL);
413 if (VBOX_SUCCESS(rc))
414 {
415 /* Lock image exclusively to close any wrong access by VDI API calls. */
416 uint64_t cbLock = pImage->offStartData
417 + ((uint64_t)getImageBlocks(&pImage->Header) << pImage->uShiftIndex2Offset);
418 rc = RTFileLock(pImage->File,
419 RTFILE_LOCK_WRITE | RTFILE_LOCK_IMMEDIATELY, 0, cbLock);
420 if (VBOX_FAILURE(rc))
421 {
422 cbLock = 0; /* Not locked. */
423 goto l_create_failed;
424 }
425
426 if (enmType == VDI_IMAGE_TYPE_FIXED)
427 {
428 /*
429 * Allocate & commit whole file if fixed image, it must be more
430 * effective than expanding file by write operations.
431 */
432 rc = RTFileSetSize(pImage->File,
433 pImage->offStartData
434 + ((uint64_t)getImageBlocks(&pImage->Header) << pImage->uShiftIndex2Offset));
435 }
436 else
437 {
438 /* Set file size to hold header and blocks array. */
439 rc = RTFileSetSize(pImage->File, pImage->offStartData);
440 }
441 if (VBOX_FAILURE(rc))
442 goto l_create_failed;
443
444 /* Generate image last-modify uuid */
445 RTUuidCreate(getImageModificationUUID(&pImage->Header));
446
447 /* Write pre-header. */
448 rc = RTFileWrite(pImage->File, &pImage->PreHeader, sizeof(pImage->PreHeader), NULL);
449 if (VBOX_FAILURE(rc))
450 goto l_create_failed;
451
452 /* Write header. */
453 rc = RTFileWrite(pImage->File, &pImage->Header.u.v1, sizeof(pImage->Header.u.v1), NULL);
454 if (VBOX_FAILURE(rc))
455 goto l_create_failed;
456
457 /* Write blocks array. */
458 rc = RTFileSeek(pImage->File, pImage->offStartBlocks, RTFILE_SEEK_BEGIN, NULL);
459 if (VBOX_FAILURE(rc))
460 goto l_create_failed;
461 rc = RTFileWrite(pImage->File,
462 pImage->paBlocks,
463 getImageBlocks(&pImage->Header) * sizeof(VDIIMAGEBLOCKPOINTER),
464 NULL);
465 if (VBOX_FAILURE(rc))
466 goto l_create_failed;
467
468 if ( (enmType == VDI_IMAGE_TYPE_FIXED)
469 && (fFlags & VDI_IMAGE_FLAGS_ZERO_EXPAND))
470 {
471 /* Fill image with zeroes. */
472
473 /** @todo Starting with Linux 2.6.23, there is an fallocate() system call.
474 * Currently supported file systems are ext4 and ocfs2. */
475
476 rc = RTFileSeek(pImage->File, pImage->offStartData, RTFILE_SEEK_BEGIN, NULL);
477 if (VBOX_FAILURE(rc))
478 goto l_create_failed;
479
480 /* alloc tmp zero-filled buffer */
481 void *pvBuf = RTMemTmpAllocZ(VDIDISK_DEFAULT_BUFFER_SIZE);
482 if (pvBuf)
483 {
484 uint64_t cbFill = (uint64_t)getImageBlocks(&pImage->Header) << pImage->uShiftIndex2Offset;
485 uint64_t cbDisk = cbFill;
486
487 /* do loop to fill all image. */
488 while (cbFill > 0)
489 {
490 unsigned to_fill = (unsigned)RT_MIN(cbFill, VDIDISK_DEFAULT_BUFFER_SIZE);
491
492 rc = RTFileWrite(pImage->File, pvBuf, to_fill, NULL);
493 if (VBOX_FAILURE(rc))
494 break;
495
496 cbFill -= to_fill;
497
498 if (pfnProgress)
499 {
500 rc = pfnProgress(NULL /* WARNING! pVM=NULL */,
501 (unsigned)(((cbDisk - cbFill) * 100) / cbDisk),
502 pvUser);
503 if (VBOX_FAILURE(rc))
504 break;
505 }
506 }
507 RTMemTmpFree(pvBuf);
508 }
509 else
510 {
511 /* alloc error */
512 rc = VERR_NO_MEMORY;
513 }
514 }
515
516 l_create_failed:
517
518 if (cbLock)
519 RTFileUnlock(pImage->File, 0, cbLock);
520
521 RTFileClose(pImage->File);
522
523 /* Delete image file if error occured while creating */
524 if (VBOX_FAILURE(rc))
525 RTFileDelete(pszFilename);
526 }
527
528 RTMemFree(pImage->paBlocks);
529 RTMemFree(pImage);
530
531 if ( VBOX_SUCCESS(rc)
532 && pfnProgress)
533 pfnProgress(NULL /* WARNING! pVM=NULL */, 100, pvUser);
534
535 Log(("vdiCreateImage: done, filename=\"%s\", rc=%Vrc\n", pszFilename, rc));
536
537 return rc;
538}
539
540/**
541 * Open an image.
542 * @internal
543 */
544static int vdiOpenImage(PVDIIMAGEDESC *ppImage, const char *pszFilename,
545 unsigned fOpen, PVDIIMAGEDESC pParent)
546{
547 /*
548 * Validate input.
549 */
550 Assert(ppImage);
551 Assert(pszFilename);
552 Assert(!(fOpen & ~VDI_OPEN_FLAGS_MASK));
553
554 PVDIIMAGEDESC pImage;
555 size_t cchFilename = strlen(pszFilename);
556 if (cchFilename >= sizeof(pImage->szFilename))
557 {
558 AssertMsgFailed(("filename=\"%s\" is too long (%d bytes)!\n", pszFilename, cchFilename));
559 return VERR_FILENAME_TOO_LONG;
560 }
561
562 pImage = (PVDIIMAGEDESC)RTMemAllocZ(sizeof(VDIIMAGEDESC));
563 if (!pImage)
564 return VERR_NO_MEMORY;
565 vdiInitImageDesc(pImage);
566
567 memcpy(pImage->szFilename, pszFilename, cchFilename);
568 pImage->fOpen = fOpen;
569
570 /*
571 * Open the image.
572 */
573 int rc = RTFileOpen(&pImage->File,
574 pImage->szFilename,
575 fOpen & VDI_OPEN_FLAGS_READONLY
576 ? RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE
577 : RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
578 if (VBOX_FAILURE(rc))
579 {
580 if (!(fOpen & VDI_OPEN_FLAGS_READONLY))
581 {
582 /* Try to open image for reading only. */
583 rc = RTFileOpen(&pImage->File,
584 pImage->szFilename,
585 RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
586 if (VBOX_SUCCESS(rc))
587 pImage->fOpen |= VDI_OPEN_FLAGS_READONLY;
588 }
589 if (VBOX_FAILURE(rc))
590 {
591 RTMemFree(pImage);
592 return rc;
593 }
594 }
595 /* Set up current image r/w state. */
596 pImage->fReadOnly = !!(pImage->fOpen & VDI_OPEN_FLAGS_READONLY);
597
598 /*
599 * Set initial file lock for reading header only.
600 * Length of lock doesn't matter, it just must include image header.
601 */
602 uint64_t cbLock = _1M;
603 rc = RTFileLock(pImage->File, RTFILE_LOCK_READ | RTFILE_LOCK_IMMEDIATELY, 0, cbLock);
604 if (VBOX_FAILURE(rc))
605 {
606 cbLock = 0;
607 goto l_open_failed;
608 }
609
610 /* Read pre-header. */
611 rc = RTFileRead(pImage->File, &pImage->PreHeader, sizeof(pImage->PreHeader), NULL);
612 if (VBOX_FAILURE(rc))
613 goto l_open_failed;
614 rc = vdiValidatePreHeader(&pImage->PreHeader);
615 if (VBOX_FAILURE(rc))
616 goto l_open_failed;
617
618 /* Read header. */
619 pImage->Header.uVersion = pImage->PreHeader.u32Version;
620 switch (GET_MAJOR_HEADER_VERSION(&pImage->Header))
621 {
622 case 0:
623 rc = RTFileRead(pImage->File, &pImage->Header.u.v0, sizeof(pImage->Header.u.v0), NULL);
624 break;
625 case 1:
626 rc = RTFileRead(pImage->File, &pImage->Header.u.v1, sizeof(pImage->Header.u.v1), NULL);
627 break;
628 default:
629 rc = VERR_VDI_UNSUPPORTED_VERSION;
630 break;
631 }
632 if (VBOX_FAILURE(rc))
633 goto l_open_failed;
634
635 rc = vdiValidateHeader(&pImage->Header);
636 if (VBOX_FAILURE(rc))
637 goto l_open_failed;
638
639 /* Check diff image correctness. */
640 if (pParent)
641 {
642 if (pImage->PreHeader.u32Version != pParent->PreHeader.u32Version)
643 {
644 rc = VERR_VDI_IMAGES_VERSION_MISMATCH;
645 goto l_open_failed;
646 }
647
648 if ( getImageType(&pImage->Header) != VDI_IMAGE_TYPE_UNDO
649 && getImageType(&pImage->Header) != VDI_IMAGE_TYPE_DIFF)
650 {
651 rc = VERR_VDI_WRONG_DIFF_IMAGE;
652 goto l_open_failed;
653 }
654
655 if ( getImageDiskSize(&pImage->Header) != getImageDiskSize(&pParent->Header)
656 || getImageBlockSize(&pImage->Header) != getImageBlockSize(&pParent->Header)
657 || getImageBlocks(&pImage->Header) != getImageBlocks(&pParent->Header)
658 || getImageExtraBlockSize(&pImage->Header) != getImageExtraBlockSize(&pParent->Header))
659 {
660 rc = VERR_VDI_WRONG_DIFF_IMAGE;
661 goto l_open_failed;
662 }
663
664 /* Check linkage data. */
665 if ( RTUuidCompare(getImageParentUUID(&pImage->Header),
666 getImageCreationUUID(&pParent->Header))
667 || RTUuidCompare(getImageParentModificationUUID(&pImage->Header),
668 getImageModificationUUID(&pParent->Header)))
669 {
670 rc = VERR_VDI_IMAGES_UUID_MISMATCH;
671 goto l_open_failed;
672 }
673 }
674
675 /* Setup image parameters by header. */
676 vdiSetupImageDesc(pImage);
677
678 /* reset modified flag into first-modified state. */
679 pImage->fModified = VDI_IMAGE_MODIFIED_FIRST;
680
681 /* Image is validated, set working file lock on it. */
682 rc = RTFileUnlock(pImage->File, 0, cbLock);
683 AssertRC(rc);
684 cbLock = pImage->offStartData
685 + ((uint64_t)getImageBlocks(&pImage->Header) << pImage->uShiftIndex2Offset);
686 rc = RTFileLock(pImage->File,
687 (pImage->fReadOnly) ?
688 RTFILE_LOCK_READ | RTFILE_LOCK_IMMEDIATELY :
689 RTFILE_LOCK_WRITE | RTFILE_LOCK_IMMEDIATELY,
690 0,
691 cbLock);
692 if ( VBOX_FAILURE(rc)
693 && !pImage->fReadOnly)
694 {
695 /* Failed to lock image for writing, try read-only lock. */
696 rc = RTFileLock(pImage->File,
697 RTFILE_LOCK_READ | RTFILE_LOCK_IMMEDIATELY, 0, cbLock);
698 if (VBOX_SUCCESS(rc))
699 pImage->fReadOnly = true;
700 }
701 if (VBOX_FAILURE(rc))
702 {
703 cbLock = 0; /* Not locked. */
704 goto l_open_failed;
705 }
706
707 /* Allocate memory for blocks array. */
708 pImage->paBlocks = (PVDIIMAGEBLOCKPOINTER)RTMemAlloc(sizeof(VDIIMAGEBLOCKPOINTER) * getImageBlocks(&pImage->Header));
709 if (!pImage->paBlocks)
710 {
711 rc = VERR_NO_MEMORY;
712 goto l_open_failed;
713 }
714
715 /* Read blocks array. */
716 rc = RTFileSeek(pImage->File, pImage->offStartBlocks, RTFILE_SEEK_BEGIN, NULL);
717 if (VBOX_FAILURE(rc))
718 goto l_open_failed;
719 rc = RTFileRead(pImage->File, pImage->paBlocks,
720 getImageBlocks(&pImage->Header) * sizeof(VDIIMAGEBLOCKPOINTER), NULL);
721 if (VBOX_FAILURE(rc))
722 goto l_open_failed;
723
724 /* all done. */
725 *ppImage = pImage;
726 return VINF_SUCCESS;
727
728l_open_failed:
729 /* Clean up. */
730 if (pImage->paBlocks)
731 RTMemFree(pImage->paBlocks);
732 if (cbLock)
733 RTFileUnlock(pImage->File, 0, cbLock);
734 RTFileClose(pImage->File);
735 RTMemFree(pImage);
736 Log(("vdiOpenImage: failed, filename=\"%s\", rc=%Vrc\n", pszFilename, rc));
737 return rc;
738}
739
740/**
741 * internal: save header to file.
742 */
743static int vdiUpdateHeader(PVDIIMAGEDESC pImage)
744{
745 /* Seek to header start. */
746 int rc = RTFileSeek(pImage->File, sizeof(VDIPREHEADER), RTFILE_SEEK_BEGIN, NULL);
747 if (VBOX_SUCCESS(rc))
748 {
749 switch (GET_MAJOR_HEADER_VERSION(&pImage->Header))
750 {
751 case 0:
752 rc = RTFileWrite(pImage->File, &pImage->Header.u.v0, sizeof(pImage->Header.u.v0), NULL);
753 break;
754 case 1:
755 rc = RTFileWrite(pImage->File, &pImage->Header.u.v1, sizeof(pImage->Header.u.v1), NULL);
756 break;
757 default:
758 rc = VERR_VDI_UNSUPPORTED_VERSION;
759 break;
760 }
761 }
762 AssertMsgRC(rc, ("vdiUpdateHeader failed, filename=\"%s\" rc=%Vrc\n", pImage->szFilename, rc));
763 return rc;
764}
765
766/**
767 * internal: save block pointer to file, save header to file.
768 */
769static int vdiUpdateBlockInfo(PVDIIMAGEDESC pImage, unsigned uBlock)
770{
771 /* Update image header. */
772 int rc = vdiUpdateHeader(pImage);
773 if (VBOX_SUCCESS(rc))
774 {
775 /* write only one block pointer. */
776 rc = RTFileSeek(pImage->File,
777 pImage->offStartBlocks + uBlock * sizeof(VDIIMAGEBLOCKPOINTER),
778 RTFILE_SEEK_BEGIN,
779 NULL);
780 if (VBOX_SUCCESS(rc))
781 rc = RTFileWrite(pImage->File,
782 &pImage->paBlocks[uBlock],
783 sizeof(VDIIMAGEBLOCKPOINTER),
784 NULL);
785 AssertMsgRC(rc, ("vdiUpdateBlockInfo failed to update block=%u, filename=\"%s\", rc=%Vrc\n",
786 uBlock, pImage->szFilename, rc));
787 }
788 return rc;
789}
790
791/**
792 * internal: save blocks array to file, save header to file.
793 */
794static int vdiUpdateBlocks(PVDIIMAGEDESC pImage)
795{
796 /* Update image header. */
797 int rc = vdiUpdateHeader(pImage);
798 if (VBOX_SUCCESS(rc))
799 {
800 /* write the block pointers array. */
801 rc = RTFileSeek(pImage->File, pImage->offStartBlocks, RTFILE_SEEK_BEGIN, NULL);
802 if (VBOX_SUCCESS(rc))
803 rc = RTFileWrite(pImage->File,
804 pImage->paBlocks,
805 sizeof(VDIIMAGEBLOCKPOINTER) * getImageBlocks(&pImage->Header),
806 NULL);
807 AssertMsgRC(rc, ("vdiUpdateBlocks failed, filename=\"%s\", rc=%Vrc\n",
808 pImage->szFilename, rc));
809 }
810 return rc;
811}
812
813/**
814 * internal: mark image as modified, if this is the first change - update image header
815 * on disk with a new uuidModify value.
816 */
817static void vdiSetModifiedFlag(PVDIIMAGEDESC pImage)
818{
819 pImage->fModified |= VDI_IMAGE_MODIFIED_FLAG;
820 if (pImage->fModified & VDI_IMAGE_MODIFIED_FIRST)
821 {
822 pImage->fModified &= ~VDI_IMAGE_MODIFIED_FIRST;
823
824 /* first modify - generate uuidModify and save to file. */
825 vdiResetModifiedFlag(pImage);
826
827 if (!(pImage->fModified | VDI_IMAGE_MODIFIED_DISABLE_UUID_UPDATE))
828 {
829 /* save header to file,
830 * note: no rc checking.
831 */
832 vdiUpdateHeader(pImage);
833 }
834 }
835}
836
837/**
838 * internal: generate new uuidModify if the image was changed.
839 */
840static void vdiResetModifiedFlag(PVDIIMAGEDESC pImage)
841{
842 if (pImage->fModified & VDI_IMAGE_MODIFIED_FLAG)
843 {
844 /* generate new last-modified uuid */
845 if (!(pImage->fModified | VDI_IMAGE_MODIFIED_DISABLE_UUID_UPDATE))
846 RTUuidCreate(getImageModificationUUID(&pImage->Header));
847
848 pImage->fModified &= ~VDI_IMAGE_MODIFIED_FLAG;
849 }
850}
851
852/**
853 * internal: disables updates of the last-modified UUID
854 * when performing image writes.
855 */
856static void vdiDisableLastModifiedUpdate(PVDIIMAGEDESC pImage)
857{
858 pImage->fModified |= VDI_IMAGE_MODIFIED_DISABLE_UUID_UPDATE;
859}
860
861#if 0 /* unused */
862/**
863 * internal: enables updates of the last-modified UUID
864 * when performing image writes.
865 */
866static void vdiEnableLastModifiedUpdate(PVDIIMAGEDESC pImage)
867{
868 pImage->fModified &= ~VDI_IMAGE_MODIFIED_DISABLE_UUID_UPDATE;
869}
870#endif
871
872/**
873 * Flush the image file to disk.
874 */
875void vdiFlushImage(PVDIIMAGEDESC pImage)
876{
877 if (!pImage->fReadOnly)
878 {
879 /* Update last-modified uuid if need. */
880 vdiResetModifiedFlag(pImage);
881
882 /* Save header. */
883 int rc = vdiUpdateHeader(pImage);
884 AssertMsgRC(rc, ("vdiUpdateHeader() failed, filename=\"%s\", rc=%Vrc\n",
885 pImage->szFilename, rc));
886 RTFileFlush(pImage->File);
887 }
888}
889
890/**
891 * internal: close image file.
892 */
893static void vdiCloseImage(PVDIIMAGEDESC pImage)
894{
895 /* Params checking. */
896 Assert(pImage);
897 Assert(pImage->File != NIL_RTFILE);
898
899 vdiFlushImage(pImage);
900 RTFileUnlock(pImage->File,
901 0,
902 pImage->offStartData
903 + ((uint64_t)getImageBlocks(&pImage->Header) << pImage->uShiftIndex2Offset));
904 RTFileClose(pImage->File);
905
906 /* free image resources */
907 RTMemFree(pImage->paBlocks);
908 RTMemFree(pImage);
909}
910
911/**
912 * internal: read data inside image block.
913 *
914 * note: uBlock must be valid, readed data must not overlap block bounds.
915 */
916static int vdiReadInBlock(PVDIIMAGEDESC pImage, unsigned uBlock, unsigned offRead,
917 size_t cbToRead, void *pvBuf)
918{
919 if (IS_VDI_IMAGE_BLOCK_ALLOCATED(pImage->paBlocks[uBlock]))
920 {
921 /* block present in image file */
922 uint64_t u64Offset = ((uint64_t)pImage->paBlocks[uBlock] << pImage->uShiftIndex2Offset)
923 + (pImage->offStartData + pImage->offStartBlockData + offRead);
924 int rc = RTFileSeek(pImage->File, u64Offset, RTFILE_SEEK_BEGIN, NULL);
925 if (VBOX_SUCCESS(rc))
926 rc = RTFileRead(pImage->File, pvBuf, cbToRead, NULL);
927 if (VBOX_FAILURE(rc))
928 Log(("vdiReadInBlock: rc=%Vrc filename=\"%s\" uBlock=%u offRead=%u cbToRead=%u u64Offset=%llu\n",
929 rc, pImage->szFilename, uBlock, offRead, cbToRead, u64Offset));
930 return rc;
931 }
932
933 /* Returns zeroes for both free and zero block types. */
934 memset(pvBuf, 0, cbToRead);
935 return VINF_SUCCESS;
936}
937
938/**
939 * Read data from virtual HDD.
940 *
941 * @returns VBox status code.
942 * @param pDisk Pointer to VDI HDD container.
943 * @param offStart Offset of first reading byte from start of disk.
944 * @param pvBuf Pointer to buffer for reading data.
945 * @param cbToRead Number of bytes to read.
946 */
947VBOXDDU_DECL(int) VDIDiskRead(PVDIDISK pDisk, uint64_t offStart, void *pvBuf, size_t cbToRead)
948{
949 /* sanity check */
950 Assert(pDisk);
951 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
952
953 PVDIIMAGEDESC pImage = pDisk->pLast;
954 Assert(pImage);
955
956 /* Check params. */
957 if ( offStart + cbToRead > getImageDiskSize(&pImage->Header)
958 || cbToRead == 0)
959 {
960 AssertMsgFailed(("offStart=%llu cbToRead=%u\n", offStart, cbToRead));
961 return VERR_INVALID_PARAMETER;
962 }
963
964 /* Calculate starting block number and offset inside it. */
965 unsigned uBlock = (unsigned)(offStart >> pImage->uShiftOffset2Index);
966 unsigned offRead = (unsigned)offStart & pImage->uBlockMask;
967
968 /* Save block size here for speed optimization. */
969 unsigned cbBlock = getImageBlockSize(&pImage->Header);
970
971 /* loop through blocks */
972 int rc;
973 for (;;)
974 {
975 size_t to_read;
976 if ((offRead + cbToRead) <= cbBlock)
977 to_read = cbToRead;
978 else
979 to_read = cbBlock - offRead;
980
981 if (pDisk->cImages > 1)
982 {
983 /* Differencing images are used, handle them. */
984 pImage = pDisk->pLast;
985
986 /* Search for image with allocated block. */
987 while (pImage->paBlocks[uBlock] == VDI_IMAGE_BLOCK_FREE)
988 {
989 pImage = pImage->pPrev;
990 if (!pImage)
991 {
992 /* Block is not allocated in all images of chain. */
993 pImage = pDisk->pLast;
994 break;
995 }
996 }
997 }
998
999 rc = vdiReadInBlock(pImage, uBlock, offRead, to_read, pvBuf);
1000
1001 cbToRead -= to_read;
1002 if ( cbToRead == 0
1003 || VBOX_FAILURE(rc))
1004 break;
1005
1006 /* goto next block */
1007 uBlock++;
1008 offRead = 0;
1009 pvBuf = (char *)pvBuf + to_read;
1010 }
1011
1012 return rc;
1013}
1014
1015/**
1016 * internal: fill the whole block with zeroes.
1017 *
1018 * note: block id must be valid, block must be already allocated in file.
1019 * note: if pDisk is NULL, the default buffer size is used
1020 */
1021static int vdiFillBlockByZeroes(PVDIDISK pDisk, PVDIIMAGEDESC pImage, unsigned uBlock)
1022{
1023 int rc;
1024
1025 /* seek to start of block in file. */
1026 uint64_t u64Offset = ((uint64_t)pImage->paBlocks[uBlock] << pImage->uShiftIndex2Offset)
1027 + (pImage->offStartData + pImage->offStartBlockData);
1028 rc = RTFileSeek(pImage->File, u64Offset, RTFILE_SEEK_BEGIN, NULL);
1029 if (VBOX_FAILURE(rc))
1030 {
1031 Log(("vdiFillBlockByZeroes: seek rc=%Vrc filename=\"%s\" uBlock=%u u64Offset=%llu\n",
1032 rc, pImage->szFilename, uBlock, u64Offset));
1033 return rc;
1034 }
1035
1036 /* alloc tmp zero-filled buffer */
1037 void *pvBuf = RTMemTmpAllocZ(pDisk ? pDisk->cbBuf : VDIDISK_DEFAULT_BUFFER_SIZE);
1038 if (!pvBuf)
1039 return VERR_NO_MEMORY;
1040
1041 unsigned cbFill = getImageBlockSize(&pImage->Header);
1042
1043 /* do loop, because buffer size may be less then block size */
1044 while (cbFill > 0)
1045 {
1046 unsigned to_fill = RT_MIN(cbFill, pDisk ? pDisk->cbBuf : VDIDISK_DEFAULT_BUFFER_SIZE);
1047 rc = RTFileWrite(pImage->File, pvBuf, to_fill, NULL);
1048 if (VBOX_FAILURE(rc))
1049 {
1050 Log(("vdiFillBlockByZeroes: write rc=%Vrc filename=\"%s\" uBlock=%u u64Offset=%llu cbFill=%u to_fill=%u\n",
1051 rc, pImage->szFilename, uBlock, u64Offset, cbFill, to_fill));
1052 break;
1053 }
1054
1055 cbFill -= to_fill;
1056 }
1057
1058 RTMemTmpFree(pvBuf);
1059 return rc;
1060}
1061
1062/**
1063 * internal: write data inside image block.
1064 *
1065 * note: uBlock must be valid, written data must not overlap block bounds.
1066 */
1067static int vdiWriteInBlock(PVDIDISK pDisk, PVDIIMAGEDESC pImage, unsigned uBlock, unsigned offWrite, size_t cbToWrite, const void *pvBuf)
1068{
1069 int rc;
1070
1071 /* Check if we can write into file. */
1072 if (pImage->fReadOnly)
1073 {
1074 Log(("vdiWriteInBlock: failed, image \"%s\" is read-only!\n", pImage->szFilename));
1075 return VERR_WRITE_PROTECT;
1076 }
1077
1078 /* This could be optimized a little (not setting it when writing zeroes
1079 * to a zeroed block). Won't buy us much, because it's very unlikely
1080 * that only such zero data block writes occur while the VDI is opened. */
1081 vdiSetModifiedFlag(pImage);
1082
1083 if (!IS_VDI_IMAGE_BLOCK_ALLOCATED(pImage->paBlocks[uBlock]))
1084 {
1085 if (!pDisk || !pDisk->fHonorZeroWrites)
1086 {
1087 /* If the destination block is unallocated at this point, it's either
1088 * a zero block or a block which hasn't been used so far (which also
1089 * means that it's a zero block. Don't need to write anything to this
1090 * block if the data consists of just zeroes. */
1091 Assert(cbToWrite % 4 == 0);
1092 if (ASMBitFirstSet((volatile void *)pvBuf, cbToWrite * 8) == -1)
1093 {
1094 pImage->paBlocks[uBlock] = VDI_IMAGE_BLOCK_ZERO;
1095 return VINF_SUCCESS;
1096 }
1097 }
1098
1099 /* need to allocate a new block in image file */
1100
1101 /* expand file by one block */
1102 uint64_t u64Size = (((uint64_t)(getImageBlocksAllocated(&pImage->Header) + 1)) << pImage->uShiftIndex2Offset)
1103 + pImage->offStartData;
1104 rc = RTFileSetSize(pImage->File, u64Size);
1105 if (VBOX_FAILURE(rc))
1106 {
1107 Log(("vdiWriteInBlock: set size rc=%Vrc filename=\"%s\" uBlock=%u u64Size=%llu\n",
1108 rc, pImage->szFilename, uBlock, u64Size));
1109 return rc;
1110 }
1111
1112 unsigned cBlocksAllocated = getImageBlocksAllocated(&pImage->Header);
1113 pImage->paBlocks[uBlock] = cBlocksAllocated;
1114 setImageBlocksAllocated(&pImage->Header, cBlocksAllocated + 1);
1115
1116 if ( pImage->fFlags & VDI_IMAGE_FLAGS_ZERO_EXPAND
1117 || pImage->paBlocks[uBlock] == VDI_IMAGE_BLOCK_ZERO)
1118 {
1119 /* Fill newly allocated block by zeroes. */
1120
1121 if (offWrite || cbToWrite != getImageBlockSize(&pImage->Header))
1122 {
1123 rc = vdiFillBlockByZeroes(pDisk, pImage, uBlock);
1124 if (VBOX_FAILURE(rc))
1125 return rc;
1126 }
1127 }
1128
1129 rc = vdiUpdateBlockInfo(pImage, uBlock);
1130 if (VBOX_FAILURE(rc))
1131 return rc;
1132 }
1133
1134 /* Now block present in image file, write data inside it. */
1135 uint64_t u64Offset = ((uint64_t)pImage->paBlocks[uBlock] << pImage->uShiftIndex2Offset)
1136 + (pImage->offStartData + pImage->offStartBlockData + offWrite);
1137 rc = RTFileSeek(pImage->File, u64Offset, RTFILE_SEEK_BEGIN, NULL);
1138 if (VBOX_SUCCESS(rc))
1139 {
1140 rc = RTFileWrite(pImage->File, pvBuf, cbToWrite, NULL);
1141 if (VBOX_FAILURE(rc))
1142 Log(("vdiWriteInBlock: write rc=%Vrc filename=\"%s\" uBlock=%u offWrite=%u u64Offset=%llu cbToWrite=%u\n",
1143 rc, pImage->szFilename, uBlock, offWrite, u64Offset, cbToWrite));
1144 }
1145 else
1146 Log(("vdiWriteInBlock: seek rc=%Vrc filename=\"%s\" uBlock=%u offWrite=%u u64Offset=%llu\n",
1147 rc, pImage->szFilename, uBlock, offWrite, u64Offset));
1148
1149 return rc;
1150}
1151
1152/**
1153 * internal: copy data block from one (parent) image to last image.
1154 */
1155static int vdiCopyBlock(PVDIDISK pDisk, PVDIIMAGEDESC pImage, unsigned uBlock)
1156{
1157 Assert(pImage != pDisk->pLast);
1158
1159 if (pImage->paBlocks[uBlock] == VDI_IMAGE_BLOCK_ZERO)
1160 {
1161 /*
1162 * if src block is zero, set dst block to zero too.
1163 */
1164 pDisk->pLast->paBlocks[uBlock] = VDI_IMAGE_BLOCK_ZERO;
1165 return VINF_SUCCESS;
1166 }
1167
1168 /* alloc tmp buffer */
1169 void *pvBuf = RTMemTmpAlloc(pDisk->cbBuf);
1170 if (!pvBuf)
1171 return VERR_NO_MEMORY;
1172
1173 int rc = VINF_SUCCESS;
1174
1175 unsigned cbCopy = getImageBlockSize(&pImage->Header);
1176 unsigned offCopy = 0;
1177
1178 /* do loop, because buffer size may be less then block size */
1179 while (cbCopy > 0)
1180 {
1181 unsigned to_copy = RT_MIN(cbCopy, pDisk->cbBuf);
1182 rc = vdiReadInBlock(pImage, uBlock, offCopy, to_copy, pvBuf);
1183 if (VBOX_FAILURE(rc))
1184 break;
1185
1186 rc = vdiWriteInBlock(pDisk, pDisk->pLast, uBlock, offCopy, to_copy, pvBuf);
1187 if (VBOX_FAILURE(rc))
1188 break;
1189
1190 cbCopy -= to_copy;
1191 offCopy += to_copy;
1192 }
1193
1194 RTMemTmpFree(pvBuf);
1195 return rc;
1196}
1197
1198/**
1199 * Write data to virtual HDD.
1200 *
1201 * @returns VBox status code.
1202 * @param pDisk Pointer to VDI HDD container.
1203 * @param offStart Offset of first writing byte from start of HDD.
1204 * @param pvBuf Pointer to buffer of writing data.
1205 * @param cbToWrite Number of bytes to write.
1206 */
1207VBOXDDU_DECL(int) VDIDiskWrite(PVDIDISK pDisk, uint64_t offStart, const void *pvBuf, size_t cbToWrite)
1208{
1209 /* sanity check */
1210 Assert(pDisk);
1211 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
1212
1213 PVDIIMAGEDESC pImage = pDisk->pLast;
1214 Assert(pImage);
1215
1216 /* Check params. */
1217 if ( offStart + cbToWrite > getImageDiskSize(&pImage->Header)
1218 || cbToWrite == 0)
1219 {
1220 AssertMsgFailed(("offStart=%llu cbToWrite=%u\n", offStart, cbToWrite));
1221 return VERR_INVALID_PARAMETER;
1222 }
1223
1224 /* Calculate starting block number and offset inside it. */
1225 unsigned uBlock = (unsigned)(offStart >> pImage->uShiftOffset2Index);
1226 unsigned offWrite = (unsigned)offStart & pImage->uBlockMask;
1227 unsigned cbBlock = getImageBlockSize(&pImage->Header);
1228
1229 /* loop through blocks */
1230 int rc;
1231 for (;;)
1232 {
1233 unsigned to_write;
1234 if (offWrite + cbToWrite <= cbBlock)
1235 to_write = cbToWrite;
1236 else
1237 to_write = cbBlock - offWrite;
1238
1239 /* All callers write less than a VDI block right now (assuming
1240 * default VDI block size). So not worth optimizing for the case
1241 * where a full block is overwritten (no copying required).
1242 * Checking whether a block is all zeroes after the write is too
1243 * expensive (would require reading the rest of the block). */
1244
1245 if (pDisk->cImages > 1)
1246 {
1247 /* Differencing images are used, handle them. */
1248
1249 /* Search for image with allocated block. */
1250 while (pImage->paBlocks[uBlock] == VDI_IMAGE_BLOCK_FREE)
1251 {
1252 pImage = pImage->pPrev;
1253 if (!pImage)
1254 {
1255 /* Block is not allocated in all images of chain. */
1256 pImage = pDisk->pLast;
1257 break;
1258 }
1259 }
1260
1261 if (pImage != pDisk->pLast)
1262 {
1263 /* One of parent image has a block data, copy it into last image. */
1264 rc = vdiCopyBlock(pDisk, pImage, uBlock);
1265 if (VBOX_FAILURE(rc))
1266 break;
1267 pImage = pDisk->pLast;
1268 }
1269 }
1270
1271 /* Actually write the data into block. */
1272 rc = vdiWriteInBlock(pDisk, pImage, uBlock, offWrite, to_write, pvBuf);
1273
1274 cbToWrite -= to_write;
1275 if ( cbToWrite == 0
1276 || VBOX_FAILURE(rc))
1277 break;
1278
1279 /* goto next block */
1280 uBlock++;
1281 offWrite = 0;
1282 pvBuf = (char *)pvBuf + to_write;
1283 }
1284
1285 return rc;
1286}
1287
1288/**
1289 * internal: commit one image to another, no changes to header, just
1290 * plain copy operation. Blocks that are not allocated in the source
1291 * image (i.e. inherited by its parent(s)) are not merged.
1292 *
1293 * @param pImageFrom source image
1294 * @param pImageTo target image (will receive all the modifications)
1295 * @param fParentToChild true if the source image is parent of the target one,
1296 * false of the target image is the parent of the source.
1297 * @param pfnProgress progress callback (NULL if not to be used)
1298 * @param pvUser user argument for the progress callback
1299 *
1300 * @note the target image has to be opened read/write
1301 * @note this method does not check whether merging is possible!
1302 */
1303static int vdiMergeImages(PVDIIMAGEDESC pImageFrom, PVDIIMAGEDESC pImageTo, bool fParentToChild,
1304 PFNVMPROGRESS pfnProgress, void *pvUser)
1305{
1306 Assert(pImageFrom);
1307 Assert(pImageTo);
1308
1309 Log(("vdiMergeImages: merging from image \"%s\" to image \"%s\" (fParentToChild=%d)\n",
1310 pImageFrom->szFilename, pImageTo->szFilename, fParentToChild));
1311
1312 /* alloc tmp buffer */
1313 void *pvBuf = RTMemTmpAlloc(VDIDISK_DEFAULT_BUFFER_SIZE);
1314 if (!pvBuf)
1315 return VERR_NO_MEMORY;
1316
1317 int rc = VINF_SUCCESS;
1318
1319 if (!fParentToChild)
1320 {
1321 /*
1322 * Commit the child image to the parent image.
1323 * Child is the source (from), parent is the target (to).
1324 */
1325
1326 unsigned cBlocks = getImageBlocks(&pImageFrom->Header);
1327
1328 for (unsigned uBlock = 0; uBlock < cBlocks; uBlock++)
1329 {
1330 /* only process blocks that are allocated in the source image */
1331 if (pImageFrom->paBlocks[uBlock] != VDI_IMAGE_BLOCK_FREE)
1332 {
1333 /* Found used block in source image, commit it. */
1334 if ( pImageFrom->paBlocks[uBlock] == VDI_IMAGE_BLOCK_ZERO
1335 && !IS_VDI_IMAGE_BLOCK_ALLOCATED(pImageTo->paBlocks[uBlock]))
1336 {
1337 /* Block is zero in the source image and not allocated in the target image. */
1338 pImageTo->paBlocks[uBlock] = VDI_IMAGE_BLOCK_ZERO;
1339 vdiSetModifiedFlag(pImageTo);
1340 }
1341 else
1342 {
1343 /* Block is not zero / allocated in source image. */
1344 unsigned cbCommit = getImageBlockSize(&pImageFrom->Header);
1345 unsigned offCommit = 0;
1346
1347 /* do loop, because buffer size may be less then block size */
1348 while (cbCommit > 0)
1349 {
1350 unsigned cbToCopy = RT_MIN(cbCommit, VDIDISK_DEFAULT_BUFFER_SIZE);
1351
1352 rc = vdiReadInBlock(pImageFrom, uBlock, offCommit, cbToCopy, pvBuf);
1353 if (VBOX_FAILURE(rc))
1354 break;
1355
1356 rc = vdiWriteInBlock(NULL, pImageTo, uBlock, offCommit, cbToCopy, pvBuf);
1357 if (VBOX_FAILURE(rc))
1358 break;
1359
1360 cbCommit -= cbToCopy;
1361 offCommit += cbToCopy;
1362 }
1363 if (VBOX_FAILURE(rc))
1364 break;
1365 }
1366 }
1367
1368 if (pfnProgress)
1369 {
1370 pfnProgress(NULL /* WARNING! pVM=NULL */,
1371 (uBlock * 100) / cBlocks,
1372 pvUser);
1373 /* Note: commiting is non breakable operation, skipping rc here. */
1374 }
1375 }
1376 }
1377 else
1378 {
1379 /*
1380 * Commit the parent image to the child image.
1381 * Parent is the source (from), child is the target (to).
1382 */
1383
1384 unsigned cBlocks = getImageBlocks(&pImageFrom->Header);
1385
1386 for (unsigned uBlock = 0; uBlock < cBlocks; uBlock++)
1387 {
1388 /*
1389 * only process blocks that are allocated or zero in the source image
1390 * and NEITHER allocated NOR zero in the target image
1391 */
1392 if (pImageFrom->paBlocks[uBlock] != VDI_IMAGE_BLOCK_FREE &&
1393 pImageTo->paBlocks[uBlock] == VDI_IMAGE_BLOCK_FREE)
1394 {
1395 /* Found used block in source image (but unused in target), commit it. */
1396 if ( pImageFrom->paBlocks[uBlock] == VDI_IMAGE_BLOCK_ZERO)
1397 {
1398 /* Block is zero in the source image and not allocated in the target image. */
1399 pImageTo->paBlocks[uBlock] = VDI_IMAGE_BLOCK_ZERO;
1400 vdiSetModifiedFlag(pImageTo);
1401 }
1402 else
1403 {
1404 /* Block is not zero / allocated in source image. */
1405 unsigned cbCommit = getImageBlockSize(&pImageFrom->Header);
1406 unsigned offCommit = 0;
1407
1408 /* do loop, because buffer size may be less then block size */
1409 while (cbCommit > 0)
1410 {
1411 unsigned cbToCopy = RT_MIN(cbCommit, VDIDISK_DEFAULT_BUFFER_SIZE);
1412
1413 rc = vdiReadInBlock(pImageFrom, uBlock, offCommit, cbToCopy, pvBuf);
1414 if (VBOX_FAILURE(rc))
1415 break;
1416
1417 rc = vdiWriteInBlock(NULL, pImageTo, uBlock, offCommit, cbToCopy, pvBuf);
1418 if (VBOX_FAILURE(rc))
1419 break;
1420
1421 cbCommit -= cbToCopy;
1422 offCommit += cbToCopy;
1423 }
1424 if (VBOX_FAILURE(rc))
1425 break;
1426 }
1427 }
1428
1429 if (pfnProgress)
1430 {
1431 pfnProgress(NULL /* WARNING! pVM=NULL */,
1432 (uBlock * 100) / cBlocks,
1433 pvUser);
1434 /* Note: commiting is non breakable operation, skipping rc here. */
1435 }
1436 }
1437 }
1438
1439 RTMemTmpFree(pvBuf);
1440 return rc;
1441}
1442
1443/**
1444 * internal: commit last image(s) to selected previous image.
1445 * note: all images accessed across this call must be opened in R/W mode.
1446 * @remark Only used by tstVDI.
1447 */
1448static int vdiCommitToImage(PVDIDISK pDisk, PVDIIMAGEDESC pDstImage,
1449 PFNVMPROGRESS pfnProgress, void *pvUser)
1450{
1451 /* sanity check */
1452 Assert(pDisk);
1453 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
1454 Assert(pDstImage);
1455
1456 PVDIIMAGEDESC pImage = pDisk->pLast;
1457 Assert(pImage);
1458 Log(("vdiCommitToImage: commiting from image \"%s\" to image \"%s\"\n",
1459 pImage->szFilename, pDstImage->szFilename));
1460 if (pDstImage == pImage)
1461 {
1462 Log(("vdiCommitToImage: attempt to commit to the same image!\n"));
1463 return VERR_VDI_NO_DIFF_IMAGES;
1464 }
1465
1466 /* Scan images for pDstImage. */
1467 while (pImage && pImage != pDstImage)
1468 pImage = pImage->pPrev;
1469 if (!pImage)
1470 {
1471 AssertMsgFailed(("Invalid arguments: pDstImage is not in images chain\n"));
1472 return VERR_INVALID_PARAMETER;
1473 }
1474 pImage = pDisk->pLast;
1475
1476 /* alloc tmp buffer */
1477 void *pvBuf = RTMemTmpAlloc(pDisk->cbBuf);
1478 if (!pvBuf)
1479 return VERR_NO_MEMORY;
1480
1481 int rc = VINF_SUCCESS;
1482 unsigned cBlocks = getImageBlocks(&pImage->Header);
1483
1484 for (unsigned uBlock = 0; uBlock < cBlocks; uBlock++)
1485 {
1486 pImage = pDisk->pLast;
1487
1488 /* Find allocated block to commit. */
1489 while ( pImage->paBlocks[uBlock] == VDI_IMAGE_BLOCK_FREE
1490 && pImage != pDstImage)
1491 pImage = pImage->pPrev;
1492
1493 if (pImage != pDstImage)
1494 {
1495 /* Found used block in diff image (pImage), commit it. */
1496 if ( pImage->paBlocks[uBlock] == VDI_IMAGE_BLOCK_ZERO
1497 && !IS_VDI_IMAGE_BLOCK_ALLOCATED(pDstImage->paBlocks[uBlock]))
1498 {
1499 /* Block is zero in difference image and not allocated in primary image. */
1500 pDstImage->paBlocks[uBlock] = VDI_IMAGE_BLOCK_ZERO;
1501 vdiSetModifiedFlag(pDstImage);
1502 }
1503 else
1504 {
1505 /* Block is not zero / allocated in primary image. */
1506 unsigned cbCommit = getImageBlockSize(&pImage->Header);
1507 unsigned offCommit = 0;
1508
1509 /* do loop, because buffer size may be less then block size */
1510 while (cbCommit > 0)
1511 {
1512 unsigned cbToCopy = RT_MIN(cbCommit, pDisk->cbBuf);
1513
1514 rc = vdiReadInBlock(pImage, uBlock, offCommit, cbToCopy, pvBuf);
1515 if (VBOX_FAILURE(rc))
1516 break;
1517
1518 rc = vdiWriteInBlock(pDisk, pDstImage, uBlock, offCommit, cbToCopy, pvBuf);
1519 if (VBOX_FAILURE(rc))
1520 break;
1521
1522 cbCommit -= cbToCopy;
1523 offCommit += cbToCopy;
1524 }
1525 if (VBOX_FAILURE(rc))
1526 break;
1527 }
1528 pImage->paBlocks[uBlock] = VDI_IMAGE_BLOCK_FREE;
1529 }
1530
1531 if (pfnProgress)
1532 {
1533 pfnProgress(NULL /* WARNING! pVM=NULL */,
1534 (uBlock * 100) / cBlocks,
1535 pvUser);
1536 /* Note: commiting is non breakable operation, skipping rc here. */
1537 }
1538 }
1539
1540 RTMemTmpFree(pvBuf);
1541
1542 /* Go forward and update linkage information. */
1543 for (pImage = pDstImage; pImage; pImage = pImage->pNext)
1544 {
1545 /* generate new last-modified uuid. */
1546 RTUuidCreate(getImageModificationUUID(&pImage->Header));
1547
1548 /* fix up linkage. */
1549 if (pImage != pDstImage)
1550 *getImageParentModificationUUID(&pImage->Header) = *getImageModificationUUID(&pImage->pPrev->Header);
1551
1552 /* reset modified flag. */
1553 pImage->fModified = 0;
1554 }
1555
1556 /* Process committed images - truncate them. */
1557 for (pImage = pDisk->pLast; pImage != pDstImage; pImage = pImage->pPrev)
1558 {
1559 /* note: can't understand how to do error works here? */
1560
1561 setImageBlocksAllocated(&pImage->Header, 0);
1562
1563 /* Truncate file. */
1564 int rc2 = RTFileSetSize(pImage->File, pImage->offStartData);
1565 if (VBOX_FAILURE(rc2))
1566 {
1567 rc = rc2;
1568 Log(("vdiCommitToImage: set size (truncate) rc=%Vrc filename=\"%s\"\n",
1569 rc, pImage->szFilename));
1570 }
1571
1572 /* Save header and blocks array. */
1573 rc2 = vdiUpdateBlocks(pImage);
1574 if (VBOX_FAILURE(rc2))
1575 {
1576 rc = rc2;
1577 Log(("vdiCommitToImage: update blocks and header rc=%Vrc filename=\"%s\"\n",
1578 rc, pImage->szFilename));
1579 }
1580 }
1581
1582 if (pfnProgress)
1583 {
1584 pfnProgress(NULL /* WARNING! pVM=NULL */, 100, pvUser);
1585 /* Note: commiting is non breakable operation, skipping rc here. */
1586 }
1587
1588 Log(("vdiCommitToImage: done, rc=%Vrc\n", rc));
1589
1590 return rc;
1591}
1592
1593/**
1594 * Checks if image is available and not broken, returns some useful image parameters if requested.
1595 *
1596 * @returns VBox status code.
1597 * @param pszFilename Name of the image file to check.
1598 * @param puVersion Where to store the version of image. NULL is ok.
1599 * @param penmType Where to store the type of image. NULL is ok.
1600 * @param pcbSize Where to store the size of image in bytes. NULL is ok.
1601 * @param pUuid Where to store the uuid of image creation. NULL is ok.
1602 * @param pParentUuid Where to store the UUID of the parent image. NULL is ok.
1603 * @param pszComment Where to store the comment string of image. NULL is ok.
1604 * @param cbComment The size of pszComment buffer. 0 is ok.
1605 */
1606VBOXDDU_DECL(int) VDICheckImage(const char *pszFilename, unsigned *puVersion, PVDIIMAGETYPE penmType,
1607 uint64_t *pcbSize, PRTUUID pUuid, PRTUUID pParentUuid,
1608 char *pszComment, unsigned cbComment)
1609{
1610 LogFlow(("VDICheckImage:\n"));
1611
1612 /* Check arguments. */
1613 if ( !pszFilename
1614 || *pszFilename == '\0')
1615 {
1616 AssertMsgFailed(("Invalid arguments: pszFilename=%p\n", pszFilename));
1617 return VERR_INVALID_PARAMETER;
1618 }
1619
1620 PVDIIMAGEDESC pImage;
1621 int rc = vdiOpenImage(&pImage, pszFilename, VDI_OPEN_FLAGS_READONLY, NULL);
1622 if (VBOX_SUCCESS(rc))
1623 {
1624 Log(("VDICheckImage: filename=\"%s\" version=%08X type=%X cbDisk=%llu uuid={%Vuuid}\n",
1625 pszFilename,
1626 pImage->PreHeader.u32Version,
1627 getImageType(&pImage->Header),
1628 getImageDiskSize(&pImage->Header),
1629 getImageCreationUUID(&pImage->Header)));
1630
1631 if ( pszComment
1632 && cbComment > 0)
1633 {
1634 char *pszTmp = getImageComment(&pImage->Header);
1635 unsigned cb = strlen(pszTmp);
1636 if (cbComment > cb)
1637 memcpy(pszComment, pszTmp, cb + 1);
1638 else
1639 rc = VERR_BUFFER_OVERFLOW;
1640 }
1641 if (VBOX_SUCCESS(rc))
1642 {
1643 if (puVersion)
1644 *puVersion = pImage->PreHeader.u32Version;
1645 if (penmType)
1646 *penmType = getImageType(&pImage->Header);
1647 if (pcbSize)
1648 *pcbSize = getImageDiskSize(&pImage->Header);
1649 if (pUuid)
1650 *pUuid = *getImageCreationUUID(&pImage->Header);
1651 if (pParentUuid)
1652 *pParentUuid = *getImageParentUUID(&pImage->Header);
1653 }
1654 vdiCloseImage(pImage);
1655 }
1656
1657 LogFlow(("VDICheckImage: returns %Vrc\n", rc));
1658 return rc;
1659}
1660
1661/**
1662 * Changes an image's comment string.
1663 *
1664 * @returns VBox status code.
1665 * @param pszFilename Name of the image file to operate on.
1666 * @param pszComment New comment string (UTF-8). NULL is allowed to reset the comment.
1667 */
1668VBOXDDU_DECL(int) VDISetImageComment(const char *pszFilename, const char *pszComment)
1669{
1670 LogFlow(("VDISetImageComment:\n"));
1671
1672 /*
1673 * Validate arguments.
1674 */
1675 if ( !pszFilename
1676 || *pszFilename == '\0')
1677 {
1678 AssertMsgFailed(("Invalid arguments: pszFilename=%p\n", pszFilename));
1679 return VERR_INVALID_PARAMETER;
1680 }
1681
1682 const size_t cchComment = pszComment ? strlen(pszComment) : 0;
1683 if (cchComment >= VDI_IMAGE_COMMENT_SIZE)
1684 {
1685 Log(("VDISetImageComment: pszComment is too long, %d bytes!\n", cchComment));
1686 return VERR_VDI_COMMENT_TOO_LONG;
1687 }
1688
1689 /*
1690 * Open the image for updating.
1691 */
1692 PVDIIMAGEDESC pImage;
1693 int rc = vdiOpenImage(&pImage, pszFilename, VDI_OPEN_FLAGS_NORMAL, NULL);
1694 if (VBOX_FAILURE(rc))
1695 {
1696 Log(("VDISetImageComment: vdiOpenImage rc=%Vrc filename=\"%s\"!\n", rc, pszFilename));
1697 return rc;
1698 }
1699 if (!pImage->fReadOnly)
1700 {
1701 /* we don't support old style images */
1702 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 1)
1703 {
1704 /*
1705 * Update the comment field, making sure to zero out all of the previous comment.
1706 */
1707 memset(pImage->Header.u.v1.szComment, '\0', VDI_IMAGE_COMMENT_SIZE);
1708 memcpy(pImage->Header.u.v1.szComment, pszComment, cchComment);
1709
1710 /* write out new the header */
1711 rc = vdiUpdateHeader(pImage);
1712 AssertMsgRC(rc, ("vdiUpdateHeader() failed, filename=\"%s\", rc=%Vrc\n",
1713 pImage->szFilename, rc));
1714 }
1715 else
1716 {
1717 Log(("VDISetImageComment: Unsupported version!\n"));
1718 rc = VERR_VDI_UNSUPPORTED_VERSION;
1719 }
1720 }
1721 else
1722 {
1723 Log(("VDISetImageComment: image \"%s\" is opened as read-only!\n", pszFilename));
1724 rc = VERR_VDI_IMAGE_READ_ONLY;
1725 }
1726
1727 vdiCloseImage(pImage);
1728 return rc;
1729}
1730
1731/**
1732 * Creates a new base image file.
1733 *
1734 * @returns VBox status code.
1735 * @param pszFilename Name of the creating image file.
1736 * @param enmType Image type, only base image types are acceptable.
1737 * @param cbSize Image size in bytes.
1738 * @param pszComment Pointer to image comment. NULL is ok.
1739 * @param pfnProgress Progress callback. Optional.
1740 * @param pvUser User argument for the progress callback.
1741 */
1742VBOXDDU_DECL(int) VDICreateBaseImage(const char *pszFilename, VDIIMAGETYPE enmType, uint64_t cbSize,
1743 const char *pszComment, PFNVMPROGRESS pfnProgress, void *pvUser)
1744{
1745 LogFlow(("VDICreateBaseImage:\n"));
1746
1747 /* Check arguments. */
1748 if ( !pszFilename
1749 || *pszFilename == '\0'
1750 || (enmType != VDI_IMAGE_TYPE_NORMAL && enmType != VDI_IMAGE_TYPE_FIXED)
1751 || cbSize < VDI_IMAGE_DEFAULT_BLOCK_SIZE)
1752 {
1753 AssertMsgFailed(("Invalid arguments: pszFilename=%p enmType=%x cbSize=%llu\n",
1754 pszFilename, enmType, cbSize));
1755 return VERR_INVALID_PARAMETER;
1756 }
1757
1758 int rc = vdiCreateImage(pszFilename, enmType, VDI_IMAGE_FLAGS_DEFAULT, cbSize, pszComment, NULL,
1759 pfnProgress, pvUser);
1760 LogFlow(("VDICreateBaseImage: returns %Vrc for filename=\"%s\"\n", rc, pszFilename));
1761 return rc;
1762}
1763
1764/**
1765 * Creates a differencing dynamically growing image file for specified parent image.
1766 *
1767 * @returns VBox status code.
1768 * @param pszFilename Name of the creating differencing image file.
1769 * @param pszParent Name of the parent image file. May be base or diff image type.
1770 * @param pszComment Pointer to image comment. NULL is ok.
1771 * @param pfnProgress Progress callback. Optional.
1772 * @param pvUser User argument for the progress callback.
1773 */
1774VBOXDDU_DECL(int) VDICreateDifferenceImage(const char *pszFilename, const char *pszParent,
1775 const char *pszComment, PFNVMPROGRESS pfnProgress,
1776 void *pvUser)
1777{
1778 LogFlow(("VDICreateDifferenceImage:\n"));
1779
1780 /* Check arguments. */
1781 if ( !pszFilename
1782 || *pszFilename == '\0'
1783 || !pszParent
1784 || *pszParent == '\0')
1785 {
1786 AssertMsgFailed(("Invalid arguments: pszFilename=%p pszParent=%p\n",
1787 pszFilename, pszParent));
1788 return VERR_INVALID_PARAMETER;
1789 }
1790
1791 PVDIIMAGEDESC pParent;
1792 int rc = vdiOpenImage(&pParent, pszParent, VDI_OPEN_FLAGS_READONLY, NULL);
1793 if (VBOX_SUCCESS(rc))
1794 {
1795 rc = vdiCreateImage(pszFilename, VDI_IMAGE_TYPE_DIFF, VDI_IMAGE_FLAGS_DEFAULT,
1796 getImageDiskSize(&pParent->Header), pszComment, pParent,
1797 pfnProgress, pvUser);
1798 vdiCloseImage(pParent);
1799 }
1800 LogFlow(("VDICreateDifferenceImage: returns %Vrc for filename=\"%s\"\n", rc, pszFilename));
1801 return rc;
1802}
1803
1804/**
1805 * Deletes an image. Only valid image files can be deleted by this call.
1806 *
1807 * @returns VBox status code.
1808 * @param pszFilename Name of the image file to check.
1809 */
1810VBOXDDU_DECL(int) VDIDeleteImage(const char *pszFilename)
1811{
1812 LogFlow(("VDIDeleteImage:\n"));
1813 /* Check arguments. */
1814 if ( !pszFilename
1815 || *pszFilename == '\0')
1816 {
1817 AssertMsgFailed(("Invalid arguments: pszFilename=%p\n", pszFilename));
1818 return VERR_INVALID_PARAMETER;
1819 }
1820
1821 int rc = VDICheckImage(pszFilename, NULL, NULL, NULL, NULL, NULL, NULL, 0);
1822 if (VBOX_SUCCESS(rc))
1823 rc = RTFileDelete(pszFilename);
1824
1825 LogFlow(("VDIDeleteImage: returns %Vrc for filename=\"%s\"\n", rc, pszFilename));
1826 return rc;
1827}
1828
1829/**
1830 * Makes a copy of image file with a new (other) creation uuid.
1831 *
1832 * @returns VBox status code.
1833 * @param pszDstFilename Name of the image file to create.
1834 * @param pszSrcFilename Name of the image file to copy from.
1835 * @param pszComment Pointer to image comment. If NULL specified comment
1836 * will be copied from source image.
1837 * @param pfnProgress Progress callback. Optional.
1838 * @param pvUser User argument for the progress callback.
1839 */
1840VBOXDDU_DECL(int) VDICopyImage(const char *pszDstFilename, const char *pszSrcFilename,
1841 const char *pszComment, PFNVMPROGRESS pfnProgress, void *pvUser)
1842{
1843 LogFlow(("VDICopyImage:\n"));
1844
1845 /* Check arguments. */
1846 if ( !pszDstFilename
1847 || *pszDstFilename == '\0'
1848 || !pszSrcFilename
1849 || *pszSrcFilename == '\0')
1850 {
1851 AssertMsgFailed(("Invalid arguments: pszDstFilename=%p pszSrcFilename=%p\n",
1852 pszDstFilename, pszSrcFilename));
1853 return VERR_INVALID_PARAMETER;
1854 }
1855
1856 /* Special check for comment length. */
1857 if ( pszComment
1858 && strlen(pszComment) >= VDI_IMAGE_COMMENT_SIZE)
1859 {
1860 Log(("VDICopyImage: pszComment is too long, cb=%d\n", strlen(pszComment)));
1861 return VERR_VDI_COMMENT_TOO_LONG;
1862 }
1863
1864 PVDIIMAGEDESC pImage;
1865 int rc = vdiOpenImage(&pImage, pszSrcFilename, VDI_OPEN_FLAGS_READONLY, NULL);
1866 if (VBOX_FAILURE(rc))
1867 {
1868 Log(("VDICopyImage: src image \"%s\" open failed rc=%Vrc\n", pszSrcFilename, rc));
1869 return rc;
1870 }
1871
1872 uint64_t cbFile = pImage->offStartData
1873 + ((uint64_t)getImageBlocksAllocated(&pImage->Header) << pImage->uShiftIndex2Offset);
1874
1875 /* create file */
1876 RTFILE File;
1877 rc = RTFileOpen(&File,
1878 pszDstFilename,
1879 RTFILE_O_READWRITE | RTFILE_O_CREATE | RTFILE_O_DENY_ALL);
1880 if (VBOX_SUCCESS(rc))
1881 {
1882 /* lock new image exclusively to close any wrong access by VDI API calls. */
1883 rc = RTFileLock(File, RTFILE_LOCK_WRITE | RTFILE_LOCK_IMMEDIATELY, 0, cbFile);
1884 if (VBOX_SUCCESS(rc))
1885 {
1886 /* Set the size of a new file. */
1887 rc = RTFileSetSize(File, cbFile);
1888 if (VBOX_SUCCESS(rc))
1889 {
1890 /* A dirty trick - use original image data to fill the new image. */
1891 RTFILE oldFileHandle = pImage->File;
1892 pImage->File = File;
1893 pImage->fReadOnly = false;
1894
1895 /* generate a new image creation uuid. */
1896 RTUuidCreate(getImageCreationUUID(&pImage->Header));
1897 /* generate a new image last-modified uuid. */
1898 RTUuidCreate(getImageModificationUUID(&pImage->Header));
1899 /* set image comment, if present. */
1900 if (pszComment)
1901 strncpy(getImageComment(&pImage->Header), pszComment, VDI_IMAGE_COMMENT_SIZE);
1902
1903 /* Write the pre-header to new image. */
1904 rc = RTFileSeek(pImage->File, 0, RTFILE_SEEK_BEGIN, NULL);
1905 if (VBOX_SUCCESS(rc))
1906 rc = RTFileWrite(pImage->File,
1907 &pImage->PreHeader,
1908 sizeof(pImage->PreHeader),
1909 NULL);
1910
1911 /* Write the header and the blocks array to new image. */
1912 if (VBOX_SUCCESS(rc))
1913 rc = vdiUpdateBlocks(pImage);
1914
1915 pImage->File = oldFileHandle;
1916 pImage->fReadOnly = true;
1917
1918 /* Seek to the data start in both images. */
1919 if (VBOX_SUCCESS(rc))
1920 rc = RTFileSeek(pImage->File,
1921 pImage->offStartData,
1922 RTFILE_SEEK_BEGIN,
1923 NULL);
1924 if (VBOX_SUCCESS(rc))
1925 rc = RTFileSeek(File,
1926 pImage->offStartData,
1927 RTFILE_SEEK_BEGIN,
1928 NULL);
1929
1930 if (VBOX_SUCCESS(rc))
1931 {
1932 /* alloc tmp buffer */
1933 void *pvBuf = RTMemTmpAlloc(VDIDISK_DEFAULT_BUFFER_SIZE);
1934 if (pvBuf)
1935 {
1936 /* Main copy loop. */
1937 uint64_t cbData = cbFile - pImage->offStartData;
1938 unsigned cBlocks = (unsigned)(cbData / VDIDISK_DEFAULT_BUFFER_SIZE);
1939 unsigned c = 0;
1940
1941 while (cbData)
1942 {
1943 unsigned cbToCopy = (unsigned)RT_MIN(cbData, VDIDISK_DEFAULT_BUFFER_SIZE);
1944
1945 /* Read. */
1946 rc = RTFileRead(pImage->File, pvBuf, cbToCopy, NULL);
1947 if (VBOX_FAILURE(rc))
1948 break;
1949
1950 /* Write. */
1951 rc = RTFileWrite(File, pvBuf, cbToCopy, NULL);
1952 if (VBOX_FAILURE(rc))
1953 break;
1954
1955 if (pfnProgress)
1956 {
1957 c++;
1958 rc = pfnProgress(NULL /* WARNING! pVM=NULL */,
1959 (c * 100) / cBlocks,
1960 pvUser);
1961 if (VBOX_FAILURE(rc))
1962 break;
1963 }
1964 cbData -= cbToCopy;
1965 }
1966
1967 RTMemTmpFree(pvBuf);
1968 }
1969 else
1970 rc = VERR_NO_MEMORY;
1971 }
1972 }
1973
1974 RTFileUnlock(File, 0, cbFile);
1975 }
1976
1977 RTFileClose(File);
1978
1979 if (VBOX_FAILURE(rc))
1980 RTFileDelete(pszDstFilename);
1981
1982 if (pfnProgress)
1983 pfnProgress(NULL /* WARNING! pVM=NULL */, 100, pvUser);
1984 }
1985
1986 vdiCloseImage(pImage);
1987
1988 LogFlow(("VDICopyImage: returns %Vrc for pszSrcFilename=\"%s\" pszDstFilename=\"%s\"\n",
1989 rc, pszSrcFilename, pszDstFilename));
1990 return rc;
1991}
1992
1993/**
1994 * Shrinks growing image file by removing zeroed data blocks.
1995 *
1996 * @returns VBox status code.
1997 * @param pszFilename Name of the image file to shrink.
1998 * @param pfnProgress Progress callback. Optional.
1999 * @param pvUser User argument for the progress callback.
2000 */
2001VBOXDDU_DECL(int) VDIShrinkImage(const char *pszFilename, PFNVMPROGRESS pfnProgress, void *pvUser)
2002{
2003 LogFlow(("VDIShrinkImage:\n"));
2004
2005 /* Check arguments. */
2006 if ( !pszFilename
2007 || *pszFilename == '\0')
2008 {
2009 AssertMsgFailed(("Invalid arguments: pszFilename=%p\n", pszFilename));
2010 return VERR_INVALID_PARAMETER;
2011 }
2012
2013 PVDIIMAGEDESC pImage;
2014 int rc = vdiOpenImage(&pImage, pszFilename, VDI_OPEN_FLAGS_NORMAL, NULL);
2015 if (VBOX_FAILURE(rc))
2016 {
2017 Log(("VDIShrinkImage: vdiOpenImage rc=%Vrc filename=\"%s\"\n", rc, pszFilename));
2018 return rc;
2019 }
2020 if (pImage->fReadOnly)
2021 {
2022 Log(("VDIShrinkImage: image \"%s\" is opened as read-only!\n", pszFilename));
2023 vdiCloseImage(pImage);
2024 return VERR_VDI_IMAGE_READ_ONLY;
2025 }
2026
2027 /* Do debug dump. */
2028 vdiDumpImage(pImage);
2029
2030 /* Working data. */
2031 unsigned cbBlock = getImageBlockSize(&pImage->Header);
2032 unsigned cBlocks = getImageBlocks(&pImage->Header);
2033 unsigned cBlocksAllocated = getImageBlocksAllocated(&pImage->Header);
2034
2035 uint64_t cbFile;
2036 rc = RTFileGetSize(pImage->File, &cbFile);
2037 if (VBOX_FAILURE(rc))
2038 {
2039 Log(("VDIShrinkImage: RTFileGetSize rc=%Vrc for file=\"%s\"\n", rc, pszFilename));
2040 vdiCloseImage(pImage);
2041 return rc;
2042 }
2043
2044 uint64_t cbData = cbFile - pImage->offStartData;
2045 unsigned cBlocksAllocated2 = (unsigned)(cbData >> pImage->uShiftIndex2Offset);
2046 if (cbData != (uint64_t)cBlocksAllocated << pImage->uShiftIndex2Offset)
2047 Log(("VDIShrinkImage: invalid image file length, cbBlock=%u cBlocks=%u cBlocksAllocated=%u cBlocksAllocated2=%u cbData=%llu\n",
2048 cbBlock, cBlocks, cBlocksAllocated, cBlocksAllocated2, cbData));
2049
2050 /* Allocate second blocks array for back resolving. */
2051 PVDIIMAGEBLOCKPOINTER paBlocks2 =
2052 (PVDIIMAGEBLOCKPOINTER)RTMemTmpAlloc(sizeof(VDIIMAGEBLOCKPOINTER) * cBlocks);
2053 if (!paBlocks2)
2054 {
2055 Log(("VDIShrinkImage: failed to allocate paBlocks2 buffer (%u bytes)\n", sizeof(VDIIMAGEBLOCKPOINTER) * cBlocks));
2056 vdiCloseImage(pImage);
2057 return VERR_NO_MEMORY;
2058 }
2059
2060 /* Init second blocks array. */
2061 for (unsigned n = 0; n < cBlocks; n++)
2062 paBlocks2[n] = VDI_IMAGE_BLOCK_FREE;
2063
2064 /* Fill second blocks array, check for allocational errors. */
2065 for (unsigned n = 0; n < cBlocks; n++)
2066 {
2067 if (IS_VDI_IMAGE_BLOCK_ALLOCATED(pImage->paBlocks[n]))
2068 {
2069 unsigned uBlock = pImage->paBlocks[n];
2070 if (uBlock < cBlocksAllocated2)
2071 {
2072 if (paBlocks2[uBlock] == VDI_IMAGE_BLOCK_FREE)
2073 paBlocks2[uBlock] = n;
2074 else
2075 {
2076 Log(("VDIShrinkImage: block n=%u -> uBlock=%u is already in use!\n", n, uBlock));
2077 /* free second link to block. */
2078 pImage->paBlocks[n] = VDI_IMAGE_BLOCK_FREE;
2079 }
2080 }
2081 else
2082 {
2083 Log(("VDIShrinkImage: block n=%u -> uBlock=%u is out of blocks range! (cbBlock=%u cBlocks=%u cBlocksAllocated=%u cBlocksAllocated2=%u cbData=%llu)\n",
2084 n, uBlock, cbBlock, cBlocks, cBlocksAllocated, cBlocksAllocated2, cbData));
2085 /* free link to invalid block. */
2086 pImage->paBlocks[n] = VDI_IMAGE_BLOCK_FREE;
2087 }
2088 }
2089 }
2090
2091 /* Allocate a working buffer for one block. */
2092 void *pvBuf = RTMemTmpAlloc(cbBlock);
2093 if (pvBuf)
2094 {
2095 /* Main voodoo loop, search holes and fill it. */
2096 unsigned uBlockWrite = 0;
2097 for (unsigned uBlock = 0; uBlock < cBlocksAllocated2; uBlock++)
2098 {
2099 if (paBlocks2[uBlock] != VDI_IMAGE_BLOCK_FREE)
2100 {
2101 /* Read the block from file and check for zeroes. */
2102 uint64_t u64Offset = ((uint64_t)uBlock << pImage->uShiftIndex2Offset)
2103 + (pImage->offStartData + pImage->offStartBlockData);
2104 rc = RTFileSeek(pImage->File, u64Offset, RTFILE_SEEK_BEGIN, NULL);
2105 if (VBOX_FAILURE(rc))
2106 {
2107 Log(("VDIShrinkImage: seek rc=%Vrc filename=\"%s\" uBlock=%u cBlocks=%u cBlocksAllocated=%u cBlocksAllocated2=%u cbData=%llu\n",
2108 rc, pImage->szFilename, uBlock, cBlocks, cBlocksAllocated, cBlocksAllocated2, cbData));
2109 break;
2110 }
2111 rc = RTFileRead(pImage->File, pvBuf, cbBlock, NULL);
2112 if (VBOX_FAILURE(rc))
2113 {
2114 Log(("VDIShrinkImage: read rc=%Vrc filename=\"%s\" cbBlock=%u uBlock=%u cBlocks=%u cBlocksAllocated=%u cBlocksAllocated2=%u cbData=%llu\n",
2115 rc, pImage->szFilename, cbBlock, uBlock, cBlocks, cBlocksAllocated, cBlocksAllocated2, cbData));
2116 break;
2117 }
2118
2119 /* Check block for data. */
2120 Assert(cbBlock % 4 == 0);
2121 if (ASMBitFirstSet(pvBuf, cbBlock * 8) != -1)
2122 {
2123 /* Block has a data, may be it must be moved. */
2124 if (uBlockWrite < uBlock)
2125 {
2126 /* Move the block. */
2127 u64Offset = ((uint64_t)uBlockWrite << pImage->uShiftIndex2Offset)
2128 + (pImage->offStartData + pImage->offStartBlockData);
2129 rc = RTFileSeek(pImage->File, u64Offset, RTFILE_SEEK_BEGIN, NULL);
2130 if (VBOX_FAILURE(rc))
2131 {
2132 Log(("VDIShrinkImage: seek(2) rc=%Vrc filename=\"%s\" uBlockWrite=%u cBlocks=%u cBlocksAllocated=%u cBlocksAllocated2=%u cbData=%llu\n",
2133 rc, pImage->szFilename, uBlockWrite, cBlocks, cBlocksAllocated, cBlocksAllocated2, cbData));
2134 break;
2135 }
2136 rc = RTFileWrite(pImage->File, pvBuf, cbBlock, NULL);
2137 if (VBOX_FAILURE(rc))
2138 {
2139 Log(("VDIShrinkImage: write rc=%Vrc filename=\"%s\" cbBlock=%u uBlockWrite=%u cBlocks=%u cBlocksAllocated=%u cBlocksAllocated2=%u cbData=%llu\n",
2140 rc, pImage->szFilename, cbBlock, uBlockWrite, cBlocks, cBlocksAllocated, cBlocksAllocated2, cbData));
2141 break;
2142 }
2143 }
2144 /* Fix the block pointer. */
2145 pImage->paBlocks[paBlocks2[uBlock]] = uBlockWrite;
2146 uBlockWrite++;
2147 }
2148 else
2149 {
2150 Log(("VDIShrinkImage: found a zeroed block, uBlock=%u\n", uBlock));
2151
2152 /* Fix the block pointer. */
2153 pImage->paBlocks[paBlocks2[uBlock]] = VDI_IMAGE_BLOCK_ZERO;
2154 }
2155 }
2156 else
2157 Log(("VDIShrinkImage: found an unused block, uBlock=%u\n", uBlock));
2158
2159 if (pfnProgress)
2160 {
2161 pfnProgress(NULL /* WARNING! pVM=NULL */,
2162 (uBlock * 100) / cBlocksAllocated2,
2163 pvUser);
2164 /* Shrink is unbreakable operation! */
2165 }
2166 }
2167
2168 RTMemTmpFree(pvBuf);
2169
2170 if ( VBOX_SUCCESS(rc)
2171 && uBlockWrite < cBlocksAllocated2)
2172 {
2173 /* File size must be shrinked. */
2174 Log(("VDIShrinkImage: shrinking file size from %llu to %llu bytes\n",
2175 cbFile,
2176 pImage->offStartData + ((uint64_t)uBlockWrite << pImage->uShiftIndex2Offset)));
2177 rc = RTFileSetSize(pImage->File,
2178 pImage->offStartData + ((uint64_t)uBlockWrite << pImage->uShiftIndex2Offset));
2179 if (VBOX_FAILURE(rc))
2180 Log(("VDIShrinkImage: RTFileSetSize rc=%Vrc\n", rc));
2181 }
2182 cBlocksAllocated2 = uBlockWrite;
2183 }
2184 else
2185 {
2186 Log(("VDIShrinkImage: failed to allocate working buffer (%u bytes)\n", cbBlock));
2187 rc = VERR_NO_MEMORY;
2188 }
2189
2190 /* Save header and blocks array. */
2191 if (VBOX_SUCCESS(rc))
2192 {
2193 setImageBlocksAllocated(&pImage->Header, cBlocksAllocated2);
2194 rc = vdiUpdateBlocks(pImage);
2195 if (pfnProgress)
2196 pfnProgress(NULL /* WARNING! pVM=NULL */, 100, pvUser);
2197 }
2198
2199 /* Do debug dump. */
2200 vdiDumpImage(pImage);
2201
2202 /* Clean up. */
2203 RTMemTmpFree(paBlocks2);
2204 vdiCloseImage(pImage);
2205
2206 LogFlow(("VDIShrinkImage: returns %Vrc for filename=\"%s\"\n", rc, pszFilename));
2207 return rc;
2208}
2209
2210/**
2211 * Converts image file from older VDI formats to current one.
2212 *
2213 * @returns VBox status code.
2214 * @param pszFilename Name of the image file to convert.
2215 * @param pfnProgress Progress callback. Optional.
2216 * @param pvUser User argument for the progress callback.
2217 * @remark Only used by vditool
2218 */
2219VBOXDDU_DECL(int) VDIConvertImage(const char *pszFilename, PFNVMPROGRESS pfnProgress, void *pvUser)
2220{
2221 LogFlow(("VDIConvertImage:\n"));
2222
2223 /* Check arguments. */
2224 if ( !pszFilename
2225 || *pszFilename == '\0')
2226 {
2227 AssertMsgFailed(("Invalid arguments: pszFilename=%p\n", pszFilename));
2228 return VERR_INVALID_PARAMETER;
2229 }
2230
2231 PVDIIMAGEDESC pImage;
2232 int rc = vdiOpenImage(&pImage, pszFilename, VDI_OPEN_FLAGS_NORMAL, NULL);
2233 if (VBOX_FAILURE(rc))
2234 {
2235 Log(("VDIConvertImage: vdiOpenImage rc=%Vrc filename=\"%s\"\n", rc, pszFilename));
2236 return rc;
2237 }
2238
2239 VDIHEADER Header = {0};
2240 int off;
2241 uint64_t cbFile;
2242 uint64_t cbData;
2243
2244 if (pImage->fReadOnly)
2245 {
2246 Log(("VDIConvertImage: image \"%s\" is opened as read-only!\n", pszFilename));
2247 rc = VERR_VDI_IMAGE_READ_ONLY;
2248 goto l_conversion_failed;
2249 }
2250
2251 if (pImage->PreHeader.u32Version != 0x00000002)
2252 {
2253 Log(("VDIConvertImage: unsupported version=%08X filename=\"%s\"\n",
2254 pImage->PreHeader.u32Version, pszFilename));
2255 rc = VERR_VDI_UNSUPPORTED_VERSION;
2256 goto l_conversion_failed;
2257 }
2258
2259 /* Build new version header from old one. */
2260 vdiInitHeader(&Header,
2261 getImageType(&pImage->Header),
2262 VDI_IMAGE_FLAGS_DEFAULT, /* Safety issue: Always use default flags. */
2263 getImageComment(&pImage->Header),
2264 getImageDiskSize(&pImage->Header),
2265 getImageBlockSize(&pImage->Header),
2266 0);
2267 setImageBlocksAllocated(&Header, getImageBlocksAllocated(&pImage->Header));
2268 *getImageGeometry(&Header) = *getImageGeometry(&pImage->Header);
2269 setImageTranslation(&Header, getImageTranslation(&pImage->Header));
2270 *getImageCreationUUID(&Header) = *getImageCreationUUID(&pImage->Header);
2271 *getImageModificationUUID(&Header) = *getImageModificationUUID(&pImage->Header);
2272
2273 /* Calc data offset. */
2274 off = getImageDataOffset(&Header) - getImageDataOffset(&pImage->Header);
2275 if (off <= 0)
2276 {
2277 rc = VERR_VDI_INVALID_HEADER;
2278 goto l_conversion_failed;
2279 }
2280
2281 rc = RTFileGetSize(pImage->File, &cbFile);
2282 if (VBOX_FAILURE(rc))
2283 goto l_conversion_failed;
2284
2285 /* Check file size. */
2286 cbData = cbFile - getImageDataOffset(&pImage->Header);
2287 if (cbData != (uint64_t)getImageBlocksAllocated(&pImage->Header) << pImage->uShiftIndex2Offset)
2288 {
2289 AssertMsgFailed(("Invalid file size, broken image?\n"));
2290 rc = VERR_VDI_INVALID_HEADER;
2291 goto l_conversion_failed;
2292 }
2293
2294 /* Expand file. */
2295 rc = RTFileSetSize(pImage->File, cbFile + off);
2296 if (VBOX_FAILURE(rc))
2297 goto l_conversion_failed;
2298
2299 if (cbData > 0)
2300 {
2301 /* Calc current file position to move data from. */
2302 uint64_t offFile;
2303 if (cbData > VDIDISK_DEFAULT_BUFFER_SIZE)
2304 offFile = cbFile - VDIDISK_DEFAULT_BUFFER_SIZE;
2305 else
2306 offFile = getImageDataOffset(&pImage->Header);
2307
2308 unsigned cMoves = (unsigned)(cbData / VDIDISK_DEFAULT_BUFFER_SIZE);
2309 unsigned c = 0;
2310
2311 /* alloc tmp buffer */
2312 void *pvBuf = RTMemTmpAlloc(VDIDISK_DEFAULT_BUFFER_SIZE);
2313 if (pvBuf)
2314 {
2315 /* Move data. */
2316 for (;;)
2317 {
2318 unsigned cbToMove = (unsigned)RT_MIN(cbData, VDIDISK_DEFAULT_BUFFER_SIZE);
2319
2320 /* Read. */
2321 rc = RTFileSeek(pImage->File, offFile, RTFILE_SEEK_BEGIN, NULL);
2322 if (VBOX_FAILURE(rc))
2323 break;
2324 rc = RTFileRead(pImage->File, pvBuf, cbToMove, NULL);
2325 if (VBOX_FAILURE(rc))
2326 break;
2327
2328 /* Write. */
2329 rc = RTFileSeek(pImage->File, offFile + off, RTFILE_SEEK_BEGIN, NULL);
2330 if (VBOX_FAILURE(rc))
2331 break;
2332 rc = RTFileWrite(pImage->File, pvBuf, cbToMove, NULL);
2333 if (VBOX_FAILURE(rc))
2334 break;
2335
2336 if (pfnProgress)
2337 {
2338 c++;
2339 pfnProgress(NULL /* WARNING! pVM=NULL */,
2340 (c * 100) / cMoves,
2341 pvUser);
2342 /* Note: conversion is non breakable operation, skipping rc here. */
2343 }
2344
2345 cbData -= cbToMove;
2346 if (cbData == 0)
2347 break;
2348
2349 if (cbData > VDIDISK_DEFAULT_BUFFER_SIZE)
2350 offFile -= VDIDISK_DEFAULT_BUFFER_SIZE;
2351 else
2352 offFile = getImageDataOffset(&pImage->Header);
2353 }
2354
2355 /* Fill the beginning of file with zeroes to wipe out old headers etc. */
2356 if (VBOX_SUCCESS(rc))
2357 {
2358 Assert(offFile + off <= VDIDISK_DEFAULT_BUFFER_SIZE);
2359 rc = RTFileSeek(pImage->File, 0, RTFILE_SEEK_BEGIN, NULL);
2360 if (VBOX_SUCCESS(rc))
2361 {
2362 memset(pvBuf, 0, (unsigned)offFile + off);
2363 rc = RTFileWrite(pImage->File, pvBuf, (unsigned)offFile + off, NULL);
2364 }
2365 }
2366
2367 RTMemTmpFree(pvBuf);
2368 }
2369 else
2370 rc = VERR_NO_MEMORY;
2371
2372 if (VBOX_FAILURE(rc))
2373 goto l_conversion_failed;
2374 }
2375
2376 if (pfnProgress)
2377 {
2378 pfnProgress(NULL /* WARNING! pVM=NULL */, 100, pvUser);
2379 /* Note: conversion is non breakable operation, skipping rc here. */
2380 }
2381
2382 /* Data moved, now we need to save new pre header, header and blocks array. */
2383
2384 vdiInitPreHeader(&pImage->PreHeader);
2385 pImage->Header = Header;
2386
2387 /* Setup image parameters by header. */
2388 vdiSetupImageDesc(pImage);
2389
2390 /* Write pre-header. */
2391 rc = RTFileSeek(pImage->File, 0, RTFILE_SEEK_BEGIN, NULL);
2392 if (VBOX_FAILURE(rc))
2393 goto l_conversion_failed;
2394 rc = RTFileWrite(pImage->File, &pImage->PreHeader, sizeof(pImage->PreHeader), NULL);
2395 if (VBOX_FAILURE(rc))
2396 goto l_conversion_failed;
2397
2398 /* Write header and blocks array. */
2399 rc = vdiUpdateBlocks(pImage);
2400
2401l_conversion_failed:
2402 vdiCloseImage(pImage);
2403
2404 LogFlow(("VDIConvertImage: returns %Vrc for filename=\"%s\"\n", rc, pszFilename));
2405 return rc;
2406}
2407
2408/**
2409 * Queries the image's UUID and parent UUIDs.
2410 *
2411 * @returns VBox status code.
2412 * @param pszFilename Name of the image file to operate on.
2413 * @param pUuid Where to store image UUID (can be NULL).
2414 * @param pModificationUuid Where to store modification UUID (can be NULL).
2415 * @param pParentUuuid Where to store parent UUID (can be NULL).
2416 * @param pParentModificationUuid Where to store parent modification UUID (can be NULL).
2417 */
2418VBOXDDU_DECL(int) VDIGetImageUUIDs(const char *pszFilename,
2419 PRTUUID pUuid, PRTUUID pModificationUuid,
2420 PRTUUID pParentUuid, PRTUUID pParentModificationUuid)
2421{
2422 LogFlow(("VDIGetImageUUIDs:\n"));
2423
2424 /* Check arguments. */
2425 if ( !pszFilename
2426 || *pszFilename == '\0')
2427 {
2428 AssertMsgFailed(("Invalid arguments: pszFilename=%p\n", pszFilename));
2429 return VERR_INVALID_PARAMETER;
2430 }
2431
2432 /*
2433 * Try open the specified image.
2434 */
2435 PVDIIMAGEDESC pImage;
2436 int rc = vdiOpenImage(&pImage, pszFilename, VDI_OPEN_FLAGS_NORMAL, NULL);
2437 if (VBOX_FAILURE(rc))
2438 {
2439 Log(("VDIGetImageUUIDs: vdiOpenImage rc=%Vrc filename=\"%s\"\n", rc, pszFilename));
2440 return rc;
2441 }
2442
2443 /*
2444 * Query data.
2445 */
2446 if (pUuid)
2447 {
2448 PCRTUUID pTmpUuid = getImageCreationUUID(&pImage->Header);
2449 if (pTmpUuid)
2450 *pUuid = *pTmpUuid;
2451 else
2452 RTUuidClear(pUuid);
2453 }
2454 if (pModificationUuid)
2455 {
2456 PCRTUUID pTmpUuid = getImageModificationUUID(&pImage->Header);
2457 if (pTmpUuid)
2458 *pModificationUuid = *pTmpUuid;
2459 else
2460 RTUuidClear(pModificationUuid);
2461 }
2462 if (pParentUuid)
2463 {
2464 PCRTUUID pTmpUuid = getImageParentUUID(&pImage->Header);
2465 if (pTmpUuid)
2466 *pParentUuid = *pTmpUuid;
2467 else
2468 RTUuidClear(pParentUuid);
2469 }
2470 if (pParentModificationUuid)
2471 {
2472 PCRTUUID pTmpUuid = getImageParentModificationUUID(&pImage->Header);
2473 if (pTmpUuid)
2474 *pParentModificationUuid = *pTmpUuid;
2475 else
2476 RTUuidClear(pParentModificationUuid);
2477 }
2478
2479 /*
2480 * Close the image.
2481 */
2482 vdiCloseImage(pImage);
2483
2484 return VINF_SUCCESS;
2485}
2486
2487/**
2488 * Changes the image's UUID and parent UUIDs.
2489 *
2490 * @returns VBox status code.
2491 * @param pszFilename Name of the image file to operate on.
2492 * @param pUuid Optional parameter, new UUID of the image.
2493 * @param pModificationUuid Optional parameter, new modification UUID of the image.
2494 * @param pParentUuuid Optional parameter, new parent UUID of the image.
2495 * @param pParentModificationUuid Optional parameter, new parent modification UUID of the image.
2496 */
2497VBOXDDU_DECL(int) VDISetImageUUIDs(const char *pszFilename,
2498 PCRTUUID pUuid, PCRTUUID pModificationUuid,
2499 PCRTUUID pParentUuid, PCRTUUID pParentModificationUuid)
2500{
2501 LogFlow(("VDISetImageUUIDs:\n"));
2502
2503 /* Check arguments. */
2504 if ( !pszFilename
2505 || *pszFilename == '\0')
2506 {
2507 AssertMsgFailed(("Invalid arguments: pszFilename=%p\n", pszFilename));
2508 return VERR_INVALID_PARAMETER;
2509 }
2510
2511 PVDIIMAGEDESC pImage;
2512 int rc = vdiOpenImage(&pImage, pszFilename, VDI_OPEN_FLAGS_NORMAL, NULL);
2513 if (VBOX_FAILURE(rc))
2514 {
2515 Log(("VDISetImageUUIDs: vdiOpenImage rc=%Vrc filename=\"%s\"\n", rc, pszFilename));
2516 return rc;
2517 }
2518 if (!pImage->fReadOnly)
2519 {
2520 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 1)
2521 {
2522 if (pUuid)
2523 pImage->Header.u.v1.uuidCreate = *pUuid;
2524
2525 if (pModificationUuid)
2526 pImage->Header.u.v1.uuidModify = *pModificationUuid;
2527
2528 if (pParentUuid)
2529 pImage->Header.u.v1.uuidLinkage = *pParentUuid;
2530
2531 if (pParentModificationUuid)
2532 pImage->Header.u.v1.uuidParentModify = *pParentModificationUuid;
2533
2534 /* write out new header */
2535 rc = vdiUpdateHeader(pImage);
2536 AssertMsgRC(rc, ("vdiUpdateHeader() failed, filename=\"%s\", rc=%Vrc\n",
2537 pImage->szFilename, rc));
2538 }
2539 /* Make it possible to clone old VDIs. */
2540 else if ( GET_MAJOR_HEADER_VERSION(&pImage->Header) == 0
2541 && !pParentUuid
2542 && !pParentModificationUuid)
2543 {
2544 if (pUuid)
2545 pImage->Header.u.v0.uuidCreate = *pUuid;
2546
2547 if (pModificationUuid)
2548 pImage->Header.u.v0.uuidModify = *pModificationUuid;
2549
2550 /* write out new header */
2551 rc = vdiUpdateHeader(pImage);
2552 AssertMsgRC(rc, ("vdiUpdateHeader() failed, filename=\"%s\", rc=%Vrc\n",
2553 pImage->szFilename, rc));
2554 }
2555 else
2556 {
2557 Log(("VDISetImageUUIDs: Version is not supported!\n"));
2558 rc = VERR_VDI_UNSUPPORTED_VERSION;
2559 }
2560 }
2561 else
2562 {
2563 Log(("VDISetImageUUIDs: image \"%s\" is opened as read-only!\n", pszFilename));
2564 rc = VERR_VDI_IMAGE_READ_ONLY;
2565 }
2566
2567 vdiCloseImage(pImage);
2568 return rc;
2569}
2570
2571/**
2572 * Merges two images having a parent/child relationship (both directions).
2573 *
2574 * @returns VBox status code.
2575 * @param pszFilenameFrom Name of the image file to merge from.
2576 * @param pszFilenameTo Name of the image file to merge into.
2577 * @param pfnProgress Progress callback. Optional. NULL if not to be used.
2578 * @param pvUser User argument for the progress callback.
2579 */
2580VBOXDDU_DECL(int) VDIMergeImage(const char *pszFilenameFrom, const char *pszFilenameTo,
2581 PFNVMPROGRESS pfnProgress, void *pvUser)
2582{
2583 LogFlow(("VDIMergeImage:\n"));
2584
2585 /* Check arguments. */
2586 if ( !pszFilenameFrom
2587 || *pszFilenameFrom == '\0'
2588 || !pszFilenameTo
2589 || *pszFilenameTo == '\0')
2590 {
2591 AssertMsgFailed(("Invalid arguments: pszFilenameFrom=%p, pszFilenameTo=%p\n", pszFilenameFrom, pszFilenameTo));
2592 return VERR_INVALID_PARAMETER;
2593 }
2594
2595 PVDIIMAGEDESC pImageFrom;
2596 int rc = vdiOpenImage(&pImageFrom, pszFilenameFrom, VDI_OPEN_FLAGS_READONLY, NULL);
2597 if (VBOX_FAILURE(rc))
2598 {
2599 Log(("VDIMergeImage: vdiOpenImage rc=%Vrc pstFilenameFrom=\"%s\"\n", rc, pszFilenameFrom));
2600 return rc;
2601 }
2602
2603 PVDIIMAGEDESC pImageTo;
2604 rc = vdiOpenImage(&pImageTo, pszFilenameTo, VDI_OPEN_FLAGS_NORMAL, NULL);
2605 if (VBOX_FAILURE(rc))
2606 {
2607 Log(("VDIMergeImage: vdiOpenImage rc=%Vrc pszFilenameTo=\"%s\"\n", rc, pszFilenameTo));
2608 vdiCloseImage(pImageFrom);
2609 return rc;
2610 }
2611 if (pImageTo->fReadOnly)
2612 {
2613 Log(("VDIMergeImage: image \"%s\" is opened as read-only!\n", pszFilenameTo));
2614 vdiCloseImage(pImageFrom);
2615 vdiCloseImage(pImageTo);
2616 return VERR_VDI_IMAGE_READ_ONLY;
2617 }
2618
2619 /*
2620 * when merging, we should not update the modification uuid of the target
2621 * image, because from the point of view of its children, it hasn't been
2622 * logically changed after the successful merge.
2623 */
2624 vdiDisableLastModifiedUpdate(pImageTo);
2625
2626 /*
2627 * Check in which direction we merge
2628 */
2629
2630 bool bParentToChild = false;
2631 if ( getImageParentUUID(&pImageFrom->Header)
2632 && !RTUuidCompare(getImageParentUUID(&pImageFrom->Header),
2633 getImageCreationUUID(&pImageTo->Header))
2634 && !RTUuidCompare(getImageParentModificationUUID(&pImageFrom->Header),
2635 getImageModificationUUID(&pImageTo->Header)))
2636 {
2637 /* we merge from a child to its parent */
2638 }
2639 else
2640 if ( getImageParentUUID(&pImageTo->Header)
2641 && !RTUuidCompare(getImageParentUUID(&pImageTo->Header),
2642 getImageCreationUUID(&pImageFrom->Header))
2643 && !RTUuidCompare(getImageParentModificationUUID(&pImageTo->Header),
2644 getImageModificationUUID(&pImageFrom->Header)))
2645 {
2646 /* we merge from a parent to its child */
2647 bParentToChild = true;
2648 }
2649 else
2650 {
2651 /* the images are not related, we can't merge! */
2652 Log(("VDIMergeImages: images do not have a parent/child or child/parent relationship!\n"));
2653 rc = VERR_VDI_IMAGES_UUID_MISMATCH;
2654 }
2655
2656 rc = vdiMergeImages(pImageFrom, pImageTo, bParentToChild, pfnProgress, pvUser);
2657
2658 if (pfnProgress)
2659 {
2660 pfnProgress(NULL /* WARNING! pVM=NULL */, 100, pvUser);
2661 /* Note: commiting is non breakable operation, skipping rc here. */
2662 }
2663
2664 /* cleanup */
2665 vdiCloseImage(pImageFrom);
2666 vdiCloseImage(pImageTo);
2667
2668 Log(("VDIMergeImage: done, returning with rc = %Vrc\n", rc));
2669 return rc;
2670}
2671
2672
2673/**
2674 * Initialize the VDIDISK structure.
2675 */
2676void vdiInitVDIDisk(PVDIDISK pDisk)
2677{
2678 Assert(pDisk);
2679 pDisk->u32Signature = VDIDISK_SIGNATURE;
2680 pDisk->cImages = 0;
2681 pDisk->pBase = NULL;
2682 pDisk->pLast = NULL;
2683 pDisk->cbBlock = VDI_IMAGE_DEFAULT_BLOCK_SIZE;
2684 pDisk->cbBuf = VDIDISK_DEFAULT_BUFFER_SIZE;
2685 pDisk->fHonorZeroWrites = false;
2686}
2687
2688/**
2689 * internal: add image structure to the end of images list.
2690 */
2691static void vdiAddImageToList(PVDIDISK pDisk, PVDIIMAGEDESC pImage)
2692{
2693 pImage->pPrev = NULL;
2694 pImage->pNext = NULL;
2695
2696 if (pDisk->pBase)
2697 {
2698 Assert(pDisk->cImages > 0);
2699 pImage->pPrev = pDisk->pLast;
2700 pDisk->pLast->pNext = pImage;
2701 pDisk->pLast = pImage;
2702 }
2703 else
2704 {
2705 Assert(pDisk->cImages == 0);
2706 pDisk->pBase = pImage;
2707 pDisk->pLast = pImage;
2708 }
2709
2710 pDisk->cImages++;
2711}
2712
2713/**
2714 * internal: remove image structure from the images list.
2715 */
2716static void vdiRemoveImageFromList(PVDIDISK pDisk, PVDIIMAGEDESC pImage)
2717{
2718 Assert(pDisk->cImages > 0);
2719
2720 if (pImage->pPrev)
2721 pImage->pPrev->pNext = pImage->pNext;
2722 else
2723 pDisk->pBase = pImage->pNext;
2724
2725 if (pImage->pNext)
2726 pImage->pNext->pPrev = pImage->pPrev;
2727 else
2728 pDisk->pLast = pImage->pPrev;
2729
2730 pImage->pPrev = NULL;
2731 pImage->pNext = NULL;
2732
2733 pDisk->cImages--;
2734}
2735
2736/**
2737 * Allocates and initializes VDI HDD container.
2738 *
2739 * @returns Pointer to newly created HDD container with no one opened image file.
2740 * @returns NULL on failure, typically out of memory.
2741 */
2742VBOXDDU_DECL(PVDIDISK) VDIDiskCreate(void)
2743{
2744 PVDIDISK pDisk = (PVDIDISK)RTMemAllocZ(sizeof(VDIDISK));
2745 if (pDisk)
2746 vdiInitVDIDisk(pDisk);
2747 LogFlow(("VDIDiskCreate: returns pDisk=%X\n", pDisk));
2748 return pDisk;
2749}
2750
2751/**
2752 * Destroys VDI HDD container. If container has opened image files they will be closed.
2753 *
2754 * @param pDisk Pointer to VDI HDD container.
2755 */
2756VBOXDDU_DECL(void) VDIDiskDestroy(PVDIDISK pDisk)
2757{
2758 LogFlow(("VDIDiskDestroy: pDisk=%X\n", pDisk));
2759 /* sanity check */
2760 Assert(pDisk);
2761 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
2762
2763 if (pDisk)
2764 {
2765 VDIDiskCloseAllImages(pDisk);
2766 RTMemFree(pDisk);
2767 }
2768}
2769
2770/**
2771 * Get working buffer size of VDI HDD container.
2772 *
2773 * @returns Working buffer size in bytes.
2774 */
2775VBOXDDU_DECL(unsigned) VDIDiskGetBufferSize(PVDIDISK pDisk)
2776{
2777 /* sanity check */
2778 Assert(pDisk);
2779 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
2780
2781 LogFlow(("VDIDiskGetBufferSize: returns %u\n", pDisk->cbBuf));
2782 return pDisk->cbBuf;
2783}
2784
2785/**
2786 * Get read/write mode of VDI HDD.
2787 *
2788 * @returns Disk ReadOnly status.
2789 * @returns true if no one VDI image is opened in HDD container.
2790 */
2791VBOXDDU_DECL(bool) VDIDiskIsReadOnly(PVDIDISK pDisk)
2792{
2793 /* sanity check */
2794 Assert(pDisk);
2795 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
2796
2797 if (pDisk->pLast)
2798 {
2799 LogFlow(("VDIDiskIsReadOnly: returns %u\n", pDisk->pLast->fReadOnly));
2800 return pDisk->pLast->fReadOnly;
2801 }
2802
2803 AssertMsgFailed(("No one disk image is opened!\n"));
2804 return true;
2805}
2806
2807/**
2808 * Get disk size of VDI HDD container.
2809 *
2810 * @returns Virtual disk size in bytes.
2811 * @returns 0 if no one VDI image is opened in HDD container.
2812 */
2813VBOXDDU_DECL(uint64_t) VDIDiskGetSize(PVDIDISK pDisk)
2814{
2815 /* sanity check */
2816 Assert(pDisk);
2817 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
2818
2819 if (pDisk->pBase)
2820 {
2821 LogFlow(("VDIDiskGetSize: returns %llu\n", getImageDiskSize(&pDisk->pBase->Header)));
2822 return getImageDiskSize(&pDisk->pBase->Header);
2823 }
2824
2825 AssertMsgFailed(("No one disk image is opened!\n"));
2826 return 0;
2827}
2828
2829/**
2830 * Get block size of VDI HDD container.
2831 *
2832 * @returns VDI image block size in bytes.
2833 * @returns 0 if no one VDI image is opened in HDD container.
2834 */
2835VBOXDDU_DECL(unsigned) VDIDiskGetBlockSize(PVDIDISK pDisk)
2836{
2837 /* sanity check */
2838 Assert(pDisk);
2839 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
2840
2841 if (pDisk->pBase)
2842 {
2843 LogFlow(("VDIDiskGetBlockSize: returns %u\n", getImageBlockSize(&pDisk->pBase->Header)));
2844 return getImageBlockSize(&pDisk->pBase->Header);
2845 }
2846
2847 AssertMsgFailed(("No one disk image is opened!\n"));
2848 return 0;
2849}
2850
2851/**
2852 * Get virtual disk geometry stored in image file.
2853 *
2854 * @returns VBox status code.
2855 * @returns VERR_VDI_NOT_OPENED if no one VDI image is opened in HDD container.
2856 * @returns VERR_VDI_GEOMETRY_NOT_SET if no geometry has been setted.
2857 * @param pDisk Pointer to VDI HDD container.
2858 * @param pcCylinders Where to store the number of cylinders. NULL is ok.
2859 * @param pcHeads Where to store the number of heads. NULL is ok.
2860 * @param pcSectors Where to store the number of sectors. NULL is ok.
2861 */
2862VBOXDDU_DECL(int) VDIDiskGetGeometry(PVDIDISK pDisk, unsigned *pcCylinders, unsigned *pcHeads, unsigned *pcSectors)
2863{
2864 /* sanity check */
2865 Assert(pDisk);
2866 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
2867
2868 if (pDisk->pBase)
2869 {
2870 int rc = VINF_SUCCESS;
2871 PVDIDISKGEOMETRY pGeometry = getImageGeometry(&pDisk->pBase->Header);
2872 LogFlow(("VDIDiskGetGeometry: C/H/S = %u/%u/%u\n",
2873 pGeometry->cCylinders, pGeometry->cHeads, pGeometry->cSectors));
2874 if ( pGeometry->cCylinders > 0
2875 && pGeometry->cHeads > 0
2876 && pGeometry->cSectors > 0)
2877 {
2878 if (pcCylinders)
2879 *pcCylinders = pGeometry->cCylinders;
2880 if (pcHeads)
2881 *pcHeads = pGeometry->cHeads;
2882 if (pcSectors)
2883 *pcSectors = pGeometry->cSectors;
2884 }
2885 else
2886 rc = VERR_VDI_GEOMETRY_NOT_SET;
2887
2888 LogFlow(("VDIDiskGetGeometry: returns %Vrc\n", rc));
2889 return rc;
2890 }
2891
2892 AssertMsgFailed(("No one disk image is opened!\n"));
2893 return VERR_VDI_NOT_OPENED;
2894}
2895
2896/**
2897 * Store virtual disk geometry into base image file of HDD container.
2898 *
2899 * Note that in case of unrecoverable error all images of HDD container will be closed.
2900 *
2901 * @returns VBox status code.
2902 * @returns VERR_VDI_NOT_OPENED if no one VDI image is opened in HDD container.
2903 * @param pDisk Pointer to VDI HDD container.
2904 * @param cCylinders Number of cylinders.
2905 * @param cHeads Number of heads.
2906 * @param cSectors Number of sectors.
2907 */
2908VBOXDDU_DECL(int) VDIDiskSetGeometry(PVDIDISK pDisk, unsigned cCylinders, unsigned cHeads, unsigned cSectors)
2909{
2910 LogFlow(("VDIDiskSetGeometry: C/H/S = %u/%u/%u\n", cCylinders, cHeads, cSectors));
2911 /* sanity check */
2912 Assert(pDisk);
2913 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
2914
2915 if (pDisk->pBase)
2916 {
2917 PVDIDISKGEOMETRY pGeometry = getImageGeometry(&pDisk->pBase->Header);
2918 pGeometry->cCylinders = cCylinders;
2919 pGeometry->cHeads = cHeads;
2920 pGeometry->cSectors = cSectors;
2921 pGeometry->cbSector = VDI_GEOMETRY_SECTOR_SIZE;
2922
2923 /* Update header information in base image file. */
2924 int rc = vdiUpdateReadOnlyHeader(pDisk->pBase);
2925 LogFlow(("VDIDiskSetGeometry: returns %Vrc\n", rc));
2926 return rc;
2927 }
2928
2929 AssertMsgFailed(("No one disk image is opened!\n"));
2930 return VERR_VDI_NOT_OPENED;
2931}
2932
2933/**
2934 * Get virtual disk translation mode stored in image file.
2935 *
2936 * @returns VBox status code.
2937 * @returns VERR_VDI_NOT_OPENED if no one VDI image is opened in HDD container.
2938 * @param pDisk Pointer to VDI HDD container.
2939 * @param penmTranslation Where to store the translation mode (see pdm.h).
2940 */
2941VBOXDDU_DECL(int) VDIDiskGetTranslation(PVDIDISK pDisk, PPDMBIOSTRANSLATION penmTranslation)
2942{
2943 /* sanity check */
2944 Assert(pDisk);
2945 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
2946 Assert(penmTranslation);
2947
2948 if (pDisk->pBase)
2949 {
2950 *penmTranslation = getImageTranslation(&pDisk->pBase->Header);
2951 LogFlow(("VDIDiskGetTranslation: translation=%d\n", *penmTranslation));
2952 return VINF_SUCCESS;
2953 }
2954
2955 AssertMsgFailed(("No one disk image is opened!\n"));
2956 return VERR_VDI_NOT_OPENED;
2957}
2958
2959/**
2960 * Store virtual disk translation mode into base image file of HDD container.
2961 *
2962 * Note that in case of unrecoverable error all images of HDD container will be closed.
2963 *
2964 * @returns VBox status code.
2965 * @returns VERR_VDI_NOT_OPENED if no one VDI image is opened in HDD container.
2966 * @param pDisk Pointer to VDI HDD container.
2967 * @param enmTranslation Translation mode (see pdm.h).
2968 */
2969VBOXDDU_DECL(int) VDIDiskSetTranslation(PVDIDISK pDisk, PDMBIOSTRANSLATION enmTranslation)
2970{
2971 LogFlow(("VDIDiskSetTranslation: enmTranslation=%d\n", enmTranslation));
2972 /* sanity check */
2973 Assert(pDisk);
2974 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
2975
2976 if (pDisk->pBase)
2977 {
2978 setImageTranslation(&pDisk->pBase->Header, enmTranslation);
2979
2980 /* Update header information in base image file. */
2981 int rc = vdiUpdateReadOnlyHeader(pDisk->pBase);
2982 LogFlow(("VDIDiskSetTranslation: returns %Vrc\n", rc));
2983 return rc;
2984 }
2985
2986 AssertMsgFailed(("No one disk image is opened!\n"));
2987 return VERR_VDI_NOT_OPENED;
2988}
2989
2990/**
2991 * Get number of opened images in HDD container.
2992 *
2993 * @returns Number of opened images for HDD container. 0 if no images is opened.
2994 * @param pDisk Pointer to VDI HDD container.
2995 */
2996VBOXDDU_DECL(int) VDIDiskGetImagesCount(PVDIDISK pDisk)
2997{
2998 /* sanity check */
2999 Assert(pDisk);
3000 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
3001
3002 LogFlow(("VDIDiskGetImagesCount: returns %d\n", pDisk->cImages));
3003 return pDisk->cImages;
3004}
3005
3006static PVDIIMAGEDESC vdiGetImageByNumber(PVDIDISK pDisk, int nImage)
3007{
3008 PVDIIMAGEDESC pImage = pDisk->pBase;
3009 while (pImage && nImage)
3010 {
3011 pImage = pImage->pNext;
3012 nImage--;
3013 }
3014 return pImage;
3015}
3016
3017/**
3018 * Get version of opened image of HDD container.
3019 *
3020 * @returns VBox status code.
3021 * @returns VERR_VDI_IMAGE_NOT_FOUND if image with specified number was not opened.
3022 * @param pDisk Pointer to VDI HDD container.
3023 * @param nImage Image number, counts from 0. 0 is always base image of container.
3024 * @param puVersion Where to store the image version.
3025 */
3026VBOXDDU_DECL(int) VDIDiskGetImageVersion(PVDIDISK pDisk, int nImage, unsigned *puVersion)
3027{
3028 /* sanity check */
3029 Assert(pDisk);
3030 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
3031 Assert(puVersion);
3032
3033 PVDIIMAGEDESC pImage = vdiGetImageByNumber(pDisk, nImage);
3034 Assert(pImage);
3035
3036 if (pImage)
3037 {
3038 *puVersion = pImage->PreHeader.u32Version;
3039 LogFlow(("VDIDiskGetImageVersion: returns %08X\n", pImage->PreHeader.u32Version));
3040 return VINF_SUCCESS;
3041 }
3042
3043 AssertMsgFailed(("Image %d was not found (cImages=%d)\n", nImage, pDisk->cImages));
3044 return VERR_VDI_IMAGE_NOT_FOUND;
3045}
3046
3047/**
3048 * Get filename of opened image of HDD container.
3049 *
3050 * @returns VBox status code.
3051 * @returns VERR_VDI_IMAGE_NOT_FOUND if image with specified number was not opened.
3052 * @returns VERR_BUFFER_OVERFLOW if pszFilename buffer too small to hold filename.
3053 * @param pDisk Pointer to VDI HDD container.
3054 * @param nImage Image number, counts from 0. 0 is always base image of container.
3055 * @param pszFilename Where to store the image file name.
3056 * @param cbFilename Size of buffer pszFilename points to.
3057 */
3058VBOXDDU_DECL(int) VDIDiskGetImageFilename(PVDIDISK pDisk, int nImage, char *pszFilename, unsigned cbFilename)
3059{
3060 /* sanity check */
3061 Assert(pDisk);
3062 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
3063 Assert(pszFilename);
3064
3065 PVDIIMAGEDESC pImage = vdiGetImageByNumber(pDisk, nImage);
3066 Assert(pImage);
3067
3068 if (pImage)
3069 {
3070 unsigned cb = strlen(pImage->szFilename);
3071 if (cb < cbFilename)
3072 {
3073 /* memcpy is much better than strncpy. */
3074 memcpy(pszFilename, pImage->szFilename, cb + 1);
3075 LogFlow(("VDIDiskGetImageFilename: returns VINF_SUCCESS, filename=\"%s\" nImage=%d\n",
3076 pszFilename, nImage));
3077 return VINF_SUCCESS;
3078 }
3079 else
3080 {
3081 AssertMsgFailed(("Out of buffer space, cbFilename=%d needed=%d\n", cbFilename, cb + 1));
3082 return VERR_BUFFER_OVERFLOW;
3083 }
3084 }
3085
3086 AssertMsgFailed(("Image %d was not found (cImages=%d)\n", nImage, pDisk->cImages));
3087 return VERR_VDI_IMAGE_NOT_FOUND;
3088}
3089
3090/**
3091 * Get the comment line of opened image of HDD container.
3092 *
3093 * @returns VBox status code.
3094 * @returns VERR_VDI_IMAGE_NOT_FOUND if image with specified number was not opened.
3095 * @returns VERR_BUFFER_OVERFLOW if pszComment buffer too small to hold comment text.
3096 * @param pDisk Pointer to VDI HDD container.
3097 * @param nImage Image number, counts from 0. 0 is always base image of container.
3098 * @param pszComment Where to store the comment string of image. NULL is ok.
3099 * @param cbComment The size of pszComment buffer. 0 is ok.
3100 */
3101VBOXDDU_DECL(int) VDIDiskGetImageComment(PVDIDISK pDisk, int nImage, char *pszComment, unsigned cbComment)
3102{
3103 /* sanity check */
3104 Assert(pDisk);
3105 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
3106 Assert(pszComment);
3107
3108 PVDIIMAGEDESC pImage = vdiGetImageByNumber(pDisk, nImage);
3109 Assert(pImage);
3110
3111 if (pImage)
3112 {
3113 char *pszTmp = getImageComment(&pImage->Header);
3114 unsigned cb = strlen(pszTmp);
3115 if (cb < cbComment)
3116 {
3117 /* memcpy is much better than strncpy. */
3118 memcpy(pszComment, pszTmp, cb + 1);
3119 LogFlow(("VDIDiskGetImageComment: returns VINF_SUCCESS, comment=\"%s\" nImage=%d\n",
3120 pszTmp, nImage));
3121 return VINF_SUCCESS;
3122 }
3123 else
3124 {
3125 AssertMsgFailed(("Out of buffer space, cbComment=%d needed=%d\n", cbComment, cb + 1));
3126 return VERR_BUFFER_OVERFLOW;
3127 }
3128 }
3129
3130 AssertMsgFailed(("Image %d was not found (cImages=%d)\n", nImage, pDisk->cImages));
3131 return VERR_VDI_IMAGE_NOT_FOUND;
3132}
3133
3134/**
3135 * Get type of opened image of HDD container.
3136 *
3137 * @returns VBox status code.
3138 * @returns VERR_VDI_IMAGE_NOT_FOUND if image with specified number was not opened.
3139 * @param pDisk Pointer to VDI HDD container.
3140 * @param nImage Image number, counts from 0. 0 is always base image of container.
3141 * @param penmType Where to store the image type.
3142 */
3143VBOXDDU_DECL(int) VDIDiskGetImageType(PVDIDISK pDisk, int nImage, PVDIIMAGETYPE penmType)
3144{
3145 /* sanity check */
3146 Assert(pDisk);
3147 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
3148 Assert(penmType);
3149
3150 PVDIIMAGEDESC pImage = vdiGetImageByNumber(pDisk, nImage);
3151 Assert(pImage);
3152
3153 if (pImage)
3154 {
3155 *penmType = getImageType(&pImage->Header);
3156 LogFlow(("VDIDiskGetImageType: returns VINF_SUCCESS, type=%X nImage=%d\n",
3157 *penmType, nImage));
3158 return VINF_SUCCESS;
3159 }
3160
3161 AssertMsgFailed(("Image %d was not found (cImages=%d)\n", nImage, pDisk->cImages));
3162 return VERR_VDI_IMAGE_NOT_FOUND;
3163}
3164
3165/**
3166 * Get flags of opened image of HDD container.
3167 *
3168 * @returns VBox status code.
3169 * @returns VERR_VDI_IMAGE_NOT_FOUND if image with specified number was not opened.
3170 * @param pDisk Pointer to VDI HDD container.
3171 * @param nImage Image number, counts from 0. 0 is always base image of container.
3172 * @param pfFlags Where to store the image flags.
3173 */
3174VBOXDDU_DECL(int) VDIDiskGetImageFlags(PVDIDISK pDisk, int nImage, unsigned *pfFlags)
3175{
3176 /* sanity check */
3177 Assert(pDisk);
3178 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
3179 Assert(pfFlags);
3180
3181 PVDIIMAGEDESC pImage = vdiGetImageByNumber(pDisk, nImage);
3182 Assert(pImage);
3183
3184 if (pImage)
3185 {
3186 *pfFlags = getImageFlags(&pImage->Header);
3187 LogFlow(("VDIDiskGetImageFlags: returns VINF_SUCCESS, flags=%08X nImage=%d\n",
3188 *pfFlags, nImage));
3189 return VINF_SUCCESS;
3190 }
3191
3192 AssertMsgFailed(("Image %d was not found (cImages=%d)\n", nImage, pDisk->cImages));
3193 return VERR_VDI_IMAGE_NOT_FOUND;
3194}
3195
3196/**
3197 * Get Uuid of opened image of HDD container.
3198 *
3199 * @returns VBox status code.
3200 * @returns VERR_VDI_IMAGE_NOT_FOUND if image with specified number was not opened.
3201 * @param pDisk Pointer to VDI HDD container.
3202 * @param nImage Image number, counts from 0. 0 is always base image of container.
3203 * @param pUuid Where to store the image creation uuid.
3204 */
3205VBOXDDU_DECL(int) VDIDiskGetImageUuid(PVDIDISK pDisk, int nImage, PRTUUID pUuid)
3206{
3207 /* sanity check */
3208 Assert(pDisk);
3209 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
3210 Assert(pUuid);
3211
3212 PVDIIMAGEDESC pImage = vdiGetImageByNumber(pDisk, nImage);
3213 Assert(pImage);
3214
3215 if (pImage)
3216 {
3217 *pUuid = *getImageCreationUUID(&pImage->Header);
3218 LogFlow(("VDIDiskGetImageUuid: returns VINF_SUCCESS, uuid={%Vuuid} nImage=%d\n",
3219 pUuid, nImage));
3220 return VINF_SUCCESS;
3221 }
3222
3223 AssertMsgFailed(("Image %d was not found (cImages=%d)\n", nImage, pDisk->cImages));
3224 return VERR_VDI_IMAGE_NOT_FOUND;
3225}
3226
3227/**
3228 * Get last modification Uuid of opened image of HDD container.
3229 *
3230 * @returns VBox status code.
3231 * @returns VERR_VDI_IMAGE_NOT_FOUND if image with specified number was not opened.
3232 * @param pDisk Pointer to VDI HDD container.
3233 * @param nImage Image number, counts from 0. 0 is always base image of container.
3234 * @param pUuid Where to store the image modification uuid.
3235 */
3236VBOXDDU_DECL(int) VDIDiskGetImageModificationUuid(PVDIDISK pDisk, int nImage, PRTUUID pUuid)
3237{
3238 /* sanity check */
3239 Assert(pDisk);
3240 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
3241 Assert(pUuid);
3242
3243 PVDIIMAGEDESC pImage = vdiGetImageByNumber(pDisk, nImage);
3244 Assert(pImage);
3245
3246 if (pImage)
3247 {
3248 *pUuid = *getImageModificationUUID(&pImage->Header);
3249 LogFlow(("VDIDiskGetImageModificationUuid: returns VINF_SUCCESS, uuid={%Vuuid} nImage=%d\n",
3250 pUuid, nImage));
3251 return VINF_SUCCESS;
3252 }
3253
3254 AssertMsgFailed(("Image %d was not found (cImages=%d)\n", nImage, pDisk->cImages));
3255 return VERR_VDI_IMAGE_NOT_FOUND;
3256}
3257
3258/**
3259 * Get Uuid of opened image's parent image.
3260 *
3261 * @returns VBox status code.
3262 * @returns VERR_VDI_IMAGE_NOT_FOUND if image with specified number was not opened.
3263 * @param pDisk Pointer to VDI HDD container.
3264 * @param nImage Image number, counts from 0. 0 is always base image of the container.
3265 * @param pUuid Where to store the image creation uuid.
3266 */
3267VBOXDDU_DECL(int) VDIDiskGetParentImageUuid(PVDIDISK pDisk, int nImage, PRTUUID pUuid)
3268{
3269 /* sanity check */
3270 Assert(pDisk);
3271 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
3272 Assert(pUuid);
3273
3274 PVDIIMAGEDESC pImage = vdiGetImageByNumber(pDisk, nImage);
3275 if (pImage)
3276 {
3277 *pUuid = *getImageParentUUID(&pImage->Header);
3278 LogFlow(("VDIDiskGetParentImageUuid: returns VINF_SUCCESS, *pUuid={%Vuuid} nImage=%d\n",
3279 pUuid, nImage));
3280 return VINF_SUCCESS;
3281 }
3282
3283 AssertMsgFailed(("Image %d was not found (cImages=%d)\n", nImage, pDisk->cImages));
3284 return VERR_VDI_IMAGE_NOT_FOUND;
3285}
3286
3287/**
3288 * Relock the image as read/write or read-only.
3289 */
3290int vdiChangeImageMode(PVDIIMAGEDESC pImage, bool fReadOnly)
3291{
3292 Assert(pImage);
3293
3294 if ( !fReadOnly
3295 && pImage->fOpen & VDI_OPEN_FLAGS_READONLY)
3296 {
3297 /* Can't switch read-only opened image to read-write mode. */
3298 Log(("vdiChangeImageMode: can't switch r/o image to r/w mode, filename=\"%s\" fOpen=%X\n",
3299 pImage->szFilename, pImage->fOpen));
3300 return VERR_VDI_IMAGE_READ_ONLY;
3301 }
3302
3303 /* Flush last image changes if was r/w mode. */
3304 vdiFlushImage(pImage);
3305
3306 /* Change image locking. */
3307 uint64_t cbLock = pImage->offStartData
3308 + ((uint64_t)getImageBlocks(&pImage->Header) << pImage->uShiftIndex2Offset);
3309 int rc = RTFileChangeLock(pImage->File,
3310 (fReadOnly) ?
3311 RTFILE_LOCK_READ | RTFILE_LOCK_IMMEDIATELY :
3312 RTFILE_LOCK_WRITE | RTFILE_LOCK_IMMEDIATELY,
3313 0,
3314 cbLock);
3315 if (VBOX_SUCCESS(rc))
3316 {
3317 pImage->fReadOnly = fReadOnly;
3318 Log(("vdiChangeImageMode: Image \"%s\" mode changed to %s\n",
3319 pImage->szFilename, (pImage->fReadOnly) ? "read-only" : "read/write"));
3320 return VINF_SUCCESS;
3321 }
3322
3323 /* Check for the most bad error in the world. Damn! It must never happens in real life! */
3324 if (rc == VERR_FILE_LOCK_LOST)
3325 {
3326 /* And what we can do now?! */
3327 AssertMsgFailed(("Image lock has been lost for file=\"%s\"", pImage->szFilename));
3328 Log(("vdiChangeImageMode: image lock has been lost for file=\"%s\", blocking on r/o lock wait",
3329 pImage->szFilename));
3330
3331 /* Try to obtain read lock in blocking mode. Maybe it's a very bad method. */
3332 rc = RTFileLock(pImage->File, RTFILE_LOCK_READ | RTFILE_LOCK_WAIT, 0, cbLock);
3333 AssertReleaseRC(rc);
3334
3335 pImage->fReadOnly = false;
3336 if (pImage->fReadOnly != fReadOnly)
3337 rc = VERR_FILE_LOCK_VIOLATION;
3338 }
3339
3340 Log(("vdiChangeImageMode: Image \"%s\" mode change failed with rc=%Vrc, mode is %s\n",
3341 pImage->szFilename, rc, (pImage->fReadOnly) ? "read-only" : "read/write"));
3342
3343 return rc;
3344}
3345
3346/**
3347 * internal: try to save header in image file even if image is in read-only mode.
3348 */
3349static int vdiUpdateReadOnlyHeader(PVDIIMAGEDESC pImage)
3350{
3351 int rc = VINF_SUCCESS;
3352
3353 if (pImage->fReadOnly)
3354 {
3355 rc = vdiChangeImageMode(pImage, false);
3356 if (VBOX_SUCCESS(rc))
3357 {
3358 vdiFlushImage(pImage);
3359 rc = vdiChangeImageMode(pImage, true);
3360 AssertReleaseRC(rc);
3361 }
3362 }
3363 else
3364 vdiFlushImage(pImage);
3365
3366 return rc;
3367}
3368
3369/**
3370 * Opens an image file.
3371 *
3372 * The first opened image file in a HDD container must have a base image type,
3373 * others (next opened images) must be a differencing or undo images.
3374 * Linkage is checked for differencing image to be in consistence with the previously opened image.
3375 * When a next differencing image is opened and the last image was opened in read/write access
3376 * mode, then the last image is reopened in read-only with deny write sharing mode. This allows
3377 * other processes to use images in read-only mode too.
3378 *
3379 * Note that the image can be opened in read-only mode if a read/write open is not possible.
3380 * Use VDIDiskIsReadOnly to check open mode.
3381 *
3382 * @returns VBox status code.
3383 * @param pDisk Pointer to VDI HDD container.
3384 * @param pszFilename Name of the image file to open.
3385 * @param fOpen Image file open mode, see VDI_OPEN_FLAGS_* constants.
3386 */
3387VBOXDDU_DECL(int) VDIDiskOpenImage(PVDIDISK pDisk, const char *pszFilename, unsigned fOpen)
3388{
3389 /* sanity check */
3390 Assert(pDisk);
3391 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
3392
3393 /* Check arguments. */
3394 if ( !pszFilename
3395 || *pszFilename == '\0'
3396 || (fOpen & ~VDI_OPEN_FLAGS_MASK))
3397 {
3398 AssertMsgFailed(("Invalid arguments: pszFilename=%p fOpen=%x\n", pszFilename, fOpen));
3399 return VERR_INVALID_PARAMETER;
3400 }
3401 LogFlow(("VDIDiskOpenImage: pszFilename=\"%s\" fOpen=%X\n", pszFilename, fOpen));
3402
3403 PVDIIMAGEDESC pImage;
3404 int rc = vdiOpenImage(&pImage, pszFilename, fOpen, pDisk->pLast);
3405 if (VBOX_SUCCESS(rc))
3406 {
3407 if (pDisk->pLast)
3408 {
3409 /* Opening differencing image. */
3410 if (!pDisk->pLast->fReadOnly)
3411 {
3412 /*
3413 * Previous image is opened in read/write mode -> switch it into read-only.
3414 */
3415 rc = vdiChangeImageMode(pDisk->pLast, true);
3416 }
3417 }
3418 else
3419 {
3420 /* Opening base image, check its type. */
3421 if ( getImageType(&pImage->Header) != VDI_IMAGE_TYPE_NORMAL
3422 && getImageType(&pImage->Header) != VDI_IMAGE_TYPE_FIXED)
3423 {
3424 rc = VERR_VDI_INVALID_TYPE;
3425 }
3426 }
3427
3428 if (VBOX_SUCCESS(rc))
3429 vdiAddImageToList(pDisk, pImage);
3430 else
3431 vdiCloseImage(pImage);
3432 }
3433
3434 LogFlow(("VDIDiskOpenImage: returns %Vrc\n", rc));
3435 return rc;
3436}
3437
3438/**
3439 * Closes the last opened image file in the HDD container. Leaves all changes inside it.
3440 * If previous image file was opened in read-only mode (that is normal) and closing image
3441 * was opened in read-write mode (the whole disk was in read-write mode) - the previous image
3442 * will be reopened in read/write mode.
3443 *
3444 * @param pDisk Pointer to VDI HDD container.
3445 */
3446VBOXDDU_DECL(void) VDIDiskCloseImage(PVDIDISK pDisk)
3447{
3448 /* sanity check */
3449 Assert(pDisk);
3450 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
3451
3452 PVDIIMAGEDESC pImage = pDisk->pLast;
3453 if (pImage)
3454 {
3455 LogFlow(("VDIDiskCloseImage: closing image \"%s\"\n", pImage->szFilename));
3456
3457 bool fWasReadOnly = pImage->fReadOnly;
3458 vdiRemoveImageFromList(pDisk, pImage);
3459 vdiCloseImage(pImage);
3460
3461 if ( !fWasReadOnly
3462 && pDisk->pLast
3463 && pDisk->pLast->fReadOnly
3464 && !(pDisk->pLast->fOpen & VDI_OPEN_FLAGS_READONLY))
3465 {
3466 /*
3467 * Closed image was opened in read/write mode, previous image was opened
3468 * in read-only mode, try to switch it into read/write.
3469 */
3470 int rc = vdiChangeImageMode(pDisk->pLast, false);
3471 NOREF(rc); /* gcc still hates unused variables... */
3472 }
3473
3474 return;
3475 }
3476 AssertMsgFailed(("No images to close\n"));
3477}
3478
3479/**
3480 * Closes all opened image files in HDD container.
3481 *
3482 * @param pDisk Pointer to VDI HDD container.
3483 */
3484VBOXDDU_DECL(void) VDIDiskCloseAllImages(PVDIDISK pDisk)
3485{
3486 LogFlow(("VDIDiskCloseAllImages:\n"));
3487 /* sanity check */
3488 Assert(pDisk);
3489 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
3490
3491 PVDIIMAGEDESC pImage = pDisk->pLast;
3492 while (pImage)
3493 {
3494 PVDIIMAGEDESC pPrev = pImage->pPrev;
3495 vdiRemoveImageFromList(pDisk, pImage);
3496 vdiCloseImage(pImage);
3497 pImage = pPrev;
3498 }
3499 Assert(pDisk->pLast == NULL);
3500}
3501
3502/**
3503 * Commits last opened differencing/undo image file of HDD container to previous one.
3504 * If previous image file was opened in read-only mode (that must be always so) it is reopened
3505 * as read/write to do commit operation.
3506 * After successfull commit the previous image file again reopened in read-only mode, last opened
3507 * image file is cleared of data and remains open and active in HDD container.
3508 * If you want to delete image after commit you must do it manually by VDIDiskCloseImage and
3509 * VDIDeleteImage calls.
3510 *
3511 * Note that in case of unrecoverable error all images of HDD container will be closed.
3512 *
3513 * @returns VBox status code.
3514 * @param pDisk Pointer to VDI HDD container.
3515 * @param pfnProgress Progress callback. Optional.
3516 * @param pvUser User argument for the progress callback.
3517 * @remark Only used by tstVDI.
3518 */
3519VBOXDDU_DECL(int) VDIDiskCommitLastDiff(PVDIDISK pDisk, PFNVMPROGRESS pfnProgress, void *pvUser)
3520{
3521 LogFlow(("VDIDiskCommitLastDiff:\n"));
3522 /* sanity check */
3523 Assert(pDisk);
3524 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
3525
3526 int rc = VINF_SUCCESS;
3527 PVDIIMAGEDESC pImage = pDisk->pLast;
3528 if (!pImage)
3529 {
3530 AssertMsgFailed(("No one disk image is opened!\n"));
3531 return VERR_VDI_NOT_OPENED;
3532 }
3533
3534 if (pImage->fReadOnly)
3535 {
3536 AssertMsgFailed(("Image \"%s\" is read-only!\n", pImage->szFilename));
3537 return VERR_VDI_IMAGE_READ_ONLY;
3538 }
3539
3540 if (!pImage->pPrev)
3541 {
3542 AssertMsgFailed(("No images to commit to!\n"));
3543 return VERR_VDI_NO_DIFF_IMAGES;
3544 }
3545
3546 bool fWasReadOnly = pImage->pPrev->fReadOnly;
3547 if (fWasReadOnly)
3548 {
3549 /* Change previous image mode to r/w. */
3550 rc = vdiChangeImageMode(pImage->pPrev, false);
3551 if (VBOX_FAILURE(rc))
3552 {
3553 Log(("VDIDiskCommitLastDiff: can't switch previous image into r/w mode, rc=%Vrc\n", rc));
3554 return rc;
3555 }
3556 }
3557
3558 rc = vdiCommitToImage(pDisk, pImage->pPrev, pfnProgress, pvUser);
3559 if (VBOX_SUCCESS(rc) && fWasReadOnly)
3560 {
3561 /* Change previous image mode back to r/o. */
3562 rc = vdiChangeImageMode(pImage->pPrev, true);
3563 }
3564
3565 if (VBOX_FAILURE(rc))
3566 {
3567 /* Failed! Close all images, can't work with VHDD at all. */
3568 VDIDiskCloseAllImages(pDisk);
3569 AssertMsgFailed(("Fatal: commit failed, rc=%Vrc\n", rc));
3570 }
3571
3572 return rc;
3573}
3574
3575/**
3576 * Creates and opens a new differencing image file in HDD container.
3577 * See comments for VDIDiskOpenImage function about differencing images.
3578 *
3579 * @returns VBox status code.
3580 * @param pDisk Pointer to VDI HDD container.
3581 * @param pszFilename Name of the image file to create and open.
3582 * @param pszComment Pointer to image comment. NULL is ok.
3583 * @param pfnProgress Progress callback. Optional.
3584 * @param pvUser User argument for the progress callback.
3585 * @remark Only used by tstVDI.
3586 */
3587VBOXDDU_DECL(int) VDIDiskCreateOpenDifferenceImage(PVDIDISK pDisk, const char *pszFilename,
3588 const char *pszComment, PFNVMPROGRESS pfnProgress,
3589 void *pvUser)
3590{
3591 LogFlow(("VDIDiskCreateOpenDifferenceImage:\n"));
3592 /* sanity check */
3593 Assert(pDisk);
3594 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
3595 Assert(pszFilename);
3596
3597 if (!pDisk->pLast)
3598 {
3599 AssertMsgFailed(("No one disk image is opened!\n"));
3600 return VERR_VDI_NOT_OPENED;
3601 }
3602
3603 /* Flush last parent image changes if possible. */
3604 vdiFlushImage(pDisk->pLast);
3605
3606 int rc = vdiCreateImage(pszFilename,
3607 VDI_IMAGE_TYPE_DIFF,
3608 VDI_IMAGE_FLAGS_DEFAULT,
3609 getImageDiskSize(&pDisk->pLast->Header),
3610 pszComment,
3611 pDisk->pLast,
3612 pfnProgress, pvUser);
3613 if (VBOX_SUCCESS(rc))
3614 {
3615 rc = VDIDiskOpenImage(pDisk, pszFilename, VDI_OPEN_FLAGS_NORMAL);
3616 if (VBOX_FAILURE(rc))
3617 VDIDeleteImage(pszFilename);
3618 }
3619 LogFlow(("VDIDiskCreateOpenDifferenceImage: returns %Vrc, filename=\"%s\"\n", rc, pszFilename));
3620 return rc;
3621}
3622
3623/**
3624 * internal: debug image dump.
3625 *
3626 * @remark Only used by tstVDI.
3627 */
3628static void vdiDumpImage(PVDIIMAGEDESC pImage)
3629{
3630 RTLogPrintf("Dumping VDI image \"%s\" mode=%s fOpen=%X File=%08X\n",
3631 pImage->szFilename,
3632 (pImage->fReadOnly) ? "r/o" : "r/w",
3633 pImage->fOpen,
3634 pImage->File);
3635 RTLogPrintf("Header: Version=%08X Type=%X Flags=%X Size=%llu\n",
3636 pImage->PreHeader.u32Version,
3637 getImageType(&pImage->Header),
3638 getImageFlags(&pImage->Header),
3639 getImageDiskSize(&pImage->Header));
3640 RTLogPrintf("Header: cbBlock=%u cbBlockExtra=%u cBlocks=%u cBlocksAllocated=%u\n",
3641 getImageBlockSize(&pImage->Header),
3642 getImageExtraBlockSize(&pImage->Header),
3643 getImageBlocks(&pImage->Header),
3644 getImageBlocksAllocated(&pImage->Header));
3645 RTLogPrintf("Header: offBlocks=%u offData=%u\n",
3646 getImageBlocksOffset(&pImage->Header),
3647 getImageDataOffset(&pImage->Header));
3648 PVDIDISKGEOMETRY pg = getImageGeometry(&pImage->Header);
3649 RTLogPrintf("Header: Geometry: C/H/S=%u/%u/%u cbSector=%u Mode=%u\n",
3650 pg->cCylinders, pg->cHeads, pg->cSectors, pg->cbSector,
3651 getImageTranslation(&pImage->Header));
3652 RTLogPrintf("Header: uuidCreation={%Vuuid}\n", getImageCreationUUID(&pImage->Header));
3653 RTLogPrintf("Header: uuidModification={%Vuuid}\n", getImageModificationUUID(&pImage->Header));
3654 RTLogPrintf("Header: uuidParent={%Vuuid}\n", getImageParentUUID(&pImage->Header));
3655 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) >= 1)
3656 RTLogPrintf("Header: uuidParentModification={%Vuuid}\n", getImageParentModificationUUID(&pImage->Header));
3657 RTLogPrintf("Image: fFlags=%08X offStartBlocks=%u offStartData=%u\n",
3658 pImage->fFlags, pImage->offStartBlocks, pImage->offStartData);
3659 RTLogPrintf("Image: uBlockMask=%08X uShiftIndex2Offset=%u uShiftOffset2Index=%u offStartBlockData=%u\n",
3660 pImage->uBlockMask,
3661 pImage->uShiftIndex2Offset,
3662 pImage->uShiftOffset2Index,
3663 pImage->offStartBlockData);
3664
3665 unsigned uBlock, cBlocksNotFree, cBadBlocks, cBlocks = getImageBlocks(&pImage->Header);
3666 for (uBlock=0, cBlocksNotFree=0, cBadBlocks=0; uBlock<cBlocks; uBlock++)
3667 {
3668 if (IS_VDI_IMAGE_BLOCK_ALLOCATED(pImage->paBlocks[uBlock]))
3669 {
3670 cBlocksNotFree++;
3671 if (pImage->paBlocks[uBlock] >= cBlocks)
3672 cBadBlocks++;
3673 }
3674 }
3675 if (cBlocksNotFree != getImageBlocksAllocated(&pImage->Header))
3676 {
3677 RTLogPrintf("!! WARNING: %u blocks actually allocated (cBlocksAllocated=%u) !!\n",
3678 cBlocksNotFree, getImageBlocksAllocated(&pImage->Header));
3679 }
3680 if (cBadBlocks)
3681 {
3682 RTLogPrintf("!! WARNING: %u bad blocks found !!\n",
3683 cBadBlocks);
3684 }
3685}
3686
3687/**
3688 * Debug helper - dumps all opened images of HDD container into the log file.
3689 *
3690 * @param pDisk Pointer to VDI HDD container.
3691 * @remark Only used by tstVDI and vditool
3692 */
3693VBOXDDU_DECL(void) VDIDiskDumpImages(PVDIDISK pDisk)
3694{
3695 /* sanity check */
3696 Assert(pDisk);
3697 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
3698
3699 RTLogPrintf("--- Dumping VDI Disk, Images=%u\n", pDisk->cImages);
3700 for (PVDIIMAGEDESC pImage = pDisk->pBase; pImage; pImage = pImage->pNext)
3701 vdiDumpImage(pImage);
3702}
3703
Note: See TracBrowser for help on using the repository browser.

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