VirtualBox

source: vbox/trunk/src/VBox/Devices/Storage/VBoxHDD.cpp@ 452

Last change on this file since 452 was 294, checked in by vboxsync, 18 years ago

Fixed warning

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 153.4 KB
Line 
1/** @file
2 *
3 * VBox storage devices:
4 * VBox HDD container implementation
5 */
6
7/*
8 * Copyright (C) 2006 InnoTek Systemberatung GmbH
9 *
10 * This file is part of VirtualBox Open Source Edition (OSE), as
11 * available from http://www.virtualbox.org. This file is free software;
12 * you can redistribute it and/or modify it under the terms of the GNU
13 * General Public License as published by the Free Software Foundation,
14 * in version 2 as it comes in the "COPYING" file of the VirtualBox OSE
15 * distribution. VirtualBox OSE is distributed in the hope that it will
16 * be useful, but WITHOUT ANY WARRANTY of any kind.
17 *
18 * If you received this file as part of a commercial VirtualBox
19 * distribution, then only the terms of your commercial VirtualBox
20 * license agreement apply instead of the previous paragraph.
21 */
22
23/*******************************************************************************
24* Header Files *
25*******************************************************************************/
26#define LOG_GROUP LOG_GROUP_DRV_VBOXHDD
27#include <VBox/VBoxHDD.h>
28#include <VBox/pdm.h>
29#include <VBox/mm.h>
30#include <VBox/err.h>
31
32#include <VBox/log.h>
33#include <iprt/alloc.h>
34#include <iprt/assert.h>
35#include <iprt/uuid.h>
36#include <iprt/file.h>
37#include <iprt/string.h>
38
39#include "Builtins.h"
40
41/*******************************************************************************
42* Constants And Macros, Structures and Typedefs *
43*******************************************************************************/
44/** The Sector size.
45 * Currently we support only 512 bytes sectors.
46 */
47#define VDI_GEOMETRY_SECTOR_SIZE (512)
48/** 512 = 2^^9 */
49#define VDI_GEOMETRY_SECTOR_SHIFT (9)
50
51/**
52 * Harddisk geometry.
53 */
54#pragma pack(1)
55typedef struct VDIDISKGEOMETRY
56{
57 /** Cylinders. */
58 uint32_t cCylinders;
59 /** Heads. */
60 uint32_t cHeads;
61 /** Sectors per track. */
62 uint32_t cSectors;
63 /** Sector size. (bytes per sector) */
64 uint32_t cbSector;
65} VDIDISKGEOMETRY, *PVDIDISKGEOMETRY;
66#pragma pack()
67
68/** Image signature. */
69#define VDI_IMAGE_SIGNATURE (0xbeda107f)
70
71/**
72 * Pre-Header to be stored in image file - used for version control.
73 */
74#pragma pack(1)
75typedef struct VDIPREHEADER
76{
77 /** Just text info about image type, for eyes only. */
78 char szFileInfo[64];
79 /** The image signature (VDI_IMAGE_SIGNATURE). */
80 uint32_t u32Signature;
81 /** The image version (VDI_IMAGE_VERSION). */
82 uint32_t u32Version;
83} VDIPREHEADER, *PVDIPREHEADER;
84#pragma pack()
85
86/**
87 * Size of szComment field of HDD image header.
88 */
89#define VDI_IMAGE_COMMENT_SIZE 256
90
91/**
92 * Header to be stored in image file, VDI_IMAGE_VERSION_MAJOR = 0.
93 * Prepended by VDIPREHEADER.
94 */
95#pragma pack(1)
96typedef struct VDIHEADER0
97{
98 /** The image type (VDI_IMAGE_TYPE_*). */
99 uint32_t u32Type;
100 /** Image flags (VDI_IMAGE_FLAGS_*). */
101 uint32_t fFlags;
102 /** Image comment. (UTF-8) */
103 char szComment[VDI_IMAGE_COMMENT_SIZE];
104 /** Image geometry. */
105 VDIDISKGEOMETRY Geometry;
106 /** Size of disk (in bytes). */
107 uint64_t cbDisk;
108 /** Block size. (For instance VDI_IMAGE_BLOCK_SIZE.) */
109 uint32_t cbBlock;
110 /** Number of blocks. */
111 uint32_t cBlocks;
112 /** Number of allocated blocks. */
113 uint32_t cBlocksAllocated;
114 /** UUID of image. */
115 RTUUID uuidCreate;
116 /** UUID of image's last modification. */
117 RTUUID uuidModify;
118 /** Only for secondary images - UUID of primary image. */
119 RTUUID uuidLinkage;
120} VDIHEADER0, *PVDIHEADER0;
121#pragma pack()
122
123/**
124 * Header to be stored in image file, VDI_IMAGE_VERSION_MAJOR = 1.
125 * Prepended by VDIPREHEADER.
126 */
127#pragma pack(1)
128typedef struct VDIHEADER1
129{
130 /** Size of this structure in bytes. */
131 uint32_t cbHeader;
132 /** The image type (VDI_IMAGE_TYPE_*). */
133 uint32_t u32Type;
134 /** Image flags (VDI_IMAGE_FLAGS_*). */
135 uint32_t fFlags;
136 /** Image comment. (UTF-8) */
137 char szComment[VDI_IMAGE_COMMENT_SIZE];
138 /** Offset of Blocks array from the begining of image file.
139 * Should be sector-aligned for HDD access optimization. */
140 uint32_t offBlocks;
141 /** Offset of image data from the begining of image file.
142 * Should be sector-aligned for HDD access optimization. */
143 uint32_t offData;
144 /** Image geometry. */
145 VDIDISKGEOMETRY Geometry;
146 /** BIOS HDD translation mode, see PDMBIOSTRANSLATION. */
147 uint32_t u32Translation;
148 /** Size of disk (in bytes). */
149 uint64_t cbDisk;
150 /** Block size. (For instance VDI_IMAGE_BLOCK_SIZE.) Should be a power of 2! */
151 uint32_t cbBlock;
152 /** Size of additional service information of every data block.
153 * Prepended before block data. May be 0.
154 * Should be a power of 2 and sector-aligned for optimization reasons. */
155 uint32_t cbBlockExtra;
156 /** Number of blocks. */
157 uint32_t cBlocks;
158 /** Number of allocated blocks. */
159 uint32_t cBlocksAllocated;
160 /** UUID of image. */
161 RTUUID uuidCreate;
162 /** UUID of image's last modification. */
163 RTUUID uuidModify;
164 /** Only for secondary images - UUID of previous image. */
165 RTUUID uuidLinkage;
166 /** Only for secondary images - UUID of previous image's last modification. */
167 RTUUID uuidParentModify;
168} VDIHEADER1, *PVDIHEADER1;
169#pragma pack()
170
171/**
172 * Header structure for all versions.
173 */
174typedef struct VDIHEADER
175{
176 unsigned uVersion;
177 union
178 {
179 VDIHEADER0 v0;
180 VDIHEADER1 v1;
181 } u;
182} VDIHEADER, *PVDIHEADER;
183
184/** Block 'pointer'. */
185typedef uint32_t VDIIMAGEBLOCKPOINTER;
186/** Pointer to a block 'pointer'. */
187typedef VDIIMAGEBLOCKPOINTER *PVDIIMAGEBLOCKPOINTER;
188
189/**
190 * Block marked as free is not allocated in image file, read from this
191 * block may returns any random data.
192 */
193#define VDI_IMAGE_BLOCK_FREE ((VDIIMAGEBLOCKPOINTER)~0)
194
195/**
196 * Block marked as zero is not allocated in image file, read from this
197 * block returns zeroes.
198 */
199#define VDI_IMAGE_BLOCK_ZERO ((VDIIMAGEBLOCKPOINTER)~1)
200
201/**
202 * Block 'pointer' >= VDI_IMAGE_BLOCK_UNALLOCATED indicates block is not
203 * allocated in image file.
204 */
205#define VDI_IMAGE_BLOCK_UNALLOCATED (VDI_IMAGE_BLOCK_ZERO)
206#define IS_VDI_IMAGE_BLOCK_ALLOCATED(bp) (bp < VDI_IMAGE_BLOCK_UNALLOCATED)
207
208#define GET_MAJOR_HEADER_VERSION(ph) (VDI_GET_VERSION_MAJOR((ph)->uVersion))
209#define GET_MINOR_HEADER_VERSION(ph) (VDI_GET_VERSION_MINOR((ph)->uVersion))
210
211/*******************************************************************************
212* Internal Functions for header access *
213*******************************************************************************/
214static inline VDIIMAGETYPE getImageType(PVDIHEADER ph)
215{
216 switch (GET_MAJOR_HEADER_VERSION(ph))
217 {
218 case 0: return (VDIIMAGETYPE)ph->u.v0.u32Type;
219 case 1: return (VDIIMAGETYPE)ph->u.v1.u32Type;
220 }
221 AssertFailed();
222 return (VDIIMAGETYPE)0;
223}
224
225static inline unsigned getImageFlags(PVDIHEADER ph)
226{
227 switch (GET_MAJOR_HEADER_VERSION(ph))
228 {
229 case 0: return ph->u.v0.fFlags;
230 case 1: return ph->u.v1.fFlags;
231 }
232 AssertFailed();
233 return 0;
234}
235
236static inline char *getImageComment(PVDIHEADER ph)
237{
238 switch (GET_MAJOR_HEADER_VERSION(ph))
239 {
240 case 0: return &ph->u.v0.szComment[0];
241 case 1: return &ph->u.v1.szComment[0];
242 }
243 AssertFailed();
244 return NULL;
245}
246
247static inline unsigned getImageBlocksOffset(PVDIHEADER ph)
248{
249 switch (GET_MAJOR_HEADER_VERSION(ph))
250 {
251 case 0: return (sizeof(VDIPREHEADER) + sizeof(VDIHEADER0));
252 case 1: return ph->u.v1.offBlocks;
253 }
254 AssertFailed();
255 return 0;
256}
257
258static inline unsigned getImageDataOffset(PVDIHEADER ph)
259{
260 switch (GET_MAJOR_HEADER_VERSION(ph))
261 {
262 case 0: return sizeof(VDIPREHEADER) + sizeof(VDIHEADER0) + \
263 (ph->u.v0.cBlocks * sizeof(VDIIMAGEBLOCKPOINTER));
264 case 1: return ph->u.v1.offData;
265 }
266 AssertFailed();
267 return 0;
268}
269
270static inline PVDIDISKGEOMETRY getImageGeometry(PVDIHEADER ph)
271{
272 switch (GET_MAJOR_HEADER_VERSION(ph))
273 {
274 case 0: return &ph->u.v0.Geometry;
275 case 1: return &ph->u.v1.Geometry;
276 }
277 AssertFailed();
278 return NULL;
279}
280
281static inline PDMBIOSTRANSLATION getImageTranslation(PVDIHEADER ph)
282{
283 switch (GET_MAJOR_HEADER_VERSION(ph))
284 {
285 case 0: return PDMBIOSTRANSLATION_AUTO;
286 case 1: return (PDMBIOSTRANSLATION)ph->u.v1.u32Translation;
287 }
288 AssertFailed();
289 return PDMBIOSTRANSLATION_NONE;
290}
291
292static inline void setImageTranslation(PVDIHEADER ph, PDMBIOSTRANSLATION enmTranslation)
293{
294 switch (GET_MAJOR_HEADER_VERSION(ph))
295 {
296 case 0: return;
297 case 1: ph->u.v1.u32Translation = (uint32_t)enmTranslation; return;
298 }
299 AssertFailed();
300}
301
302static inline uint64_t getImageDiskSize(PVDIHEADER ph)
303{
304 switch (GET_MAJOR_HEADER_VERSION(ph))
305 {
306 case 0: return ph->u.v0.cbDisk;
307 case 1: return ph->u.v1.cbDisk;
308 }
309 AssertFailed();
310 return 0;
311}
312
313static inline unsigned getImageBlockSize(PVDIHEADER ph)
314{
315 switch (GET_MAJOR_HEADER_VERSION(ph))
316 {
317 case 0: return ph->u.v0.cbBlock;
318 case 1: return ph->u.v1.cbBlock;
319 }
320 AssertFailed();
321 return 0;
322}
323
324static inline unsigned getImageExtraBlockSize(PVDIHEADER ph)
325{
326 switch (GET_MAJOR_HEADER_VERSION(ph))
327 {
328 case 0: return 0;
329 case 1: return ph->u.v1.cbBlockExtra;
330 }
331 AssertFailed();
332 return 0;
333}
334
335static inline unsigned getImageBlocks(PVDIHEADER ph)
336{
337 switch (GET_MAJOR_HEADER_VERSION(ph))
338 {
339 case 0: return ph->u.v0.cBlocks;
340 case 1: return ph->u.v1.cBlocks;
341 }
342 AssertFailed();
343 return 0;
344}
345
346static inline unsigned getImageBlocksAllocated(PVDIHEADER ph)
347{
348 switch (GET_MAJOR_HEADER_VERSION(ph))
349 {
350 case 0: return ph->u.v0.cBlocksAllocated;
351 case 1: return ph->u.v1.cBlocksAllocated;
352 }
353 AssertFailed();
354 return 0;
355}
356
357static inline void setImageBlocksAllocated(PVDIHEADER ph, unsigned cBlocks)
358{
359 switch (GET_MAJOR_HEADER_VERSION(ph))
360 {
361 case 0: ph->u.v0.cBlocksAllocated = cBlocks; return;
362 case 1: ph->u.v1.cBlocksAllocated = cBlocks; return;
363 }
364 AssertFailed();
365}
366
367static inline PRTUUID getImageCreationUUID(PVDIHEADER ph)
368{
369 switch (GET_MAJOR_HEADER_VERSION(ph))
370 {
371 case 0: return &ph->u.v0.uuidCreate;
372 case 1: return &ph->u.v1.uuidCreate;
373 }
374 AssertFailed();
375 return NULL;
376}
377
378static inline PRTUUID getImageModificationUUID(PVDIHEADER ph)
379{
380 switch (GET_MAJOR_HEADER_VERSION(ph))
381 {
382 case 0: return &ph->u.v0.uuidModify;
383 case 1: return &ph->u.v1.uuidModify;
384 }
385 AssertFailed();
386 return NULL;
387}
388
389static inline PRTUUID getImageParentUUID(PVDIHEADER ph)
390{
391 switch (GET_MAJOR_HEADER_VERSION(ph))
392 {
393 case 0: return &ph->u.v0.uuidLinkage;
394 case 1: return &ph->u.v1.uuidLinkage;
395 }
396 AssertFailed();
397 return NULL;
398}
399
400static inline PRTUUID getImageParentModificationUUID(PVDIHEADER ph)
401{
402 switch (GET_MAJOR_HEADER_VERSION(ph))
403 {
404 case 1: return &ph->u.v1.uuidParentModify;
405 }
406 AssertFailed();
407 return NULL;
408}
409
410/**
411 * Default image block size, may be changed by setBlockSize/getBlockSize.
412 *
413 * Note: for speed reasons block size should be a power of 2 !
414 */
415#define VDI_IMAGE_DEFAULT_BLOCK_SIZE _1M
416
417/**
418 * fModified bit flags.
419 */
420#define VDI_IMAGE_MODIFIED_FLAG BIT(0)
421#define VDI_IMAGE_MODIFIED_FIRST BIT(1)
422#define VDI_IMAGE_MODIFIED_DISABLE_UUID_UPDATE BIT(2)
423
424/**
425 * Image structure
426 */
427typedef struct VDIIMAGEDESC
428{
429 /** Link to parent image descriptor, if any. */
430 struct VDIIMAGEDESC *pPrev;
431 /** Link to child image descriptor, if any. */
432 struct VDIIMAGEDESC *pNext;
433 /** File handle. */
434 RTFILE File;
435 /** True if the image is operating in readonly mode. */
436 bool fReadOnly;
437 /** Image open flags, VDI_OPEN_FLAGS_*. */
438 unsigned fOpen;
439 /** Image pre-header. */
440 VDIPREHEADER PreHeader;
441 /** Image header. */
442 VDIHEADER Header;
443 /** Pointer to a block array. */
444 PVDIIMAGEBLOCKPOINTER paBlocks;
445 /** fFlags copy from image header, for speed optimization. */
446 unsigned fFlags;
447 /** Start offset of block array in image file, here for speed optimization. */
448 unsigned offStartBlocks;
449 /** Start offset of data in image file, here for speed optimization. */
450 unsigned offStartData;
451 /** Block mask for getting the offset into a block from a byte hdd offset. */
452 unsigned uBlockMask;
453 /** Block shift value for converting byte hdd offset into paBlock index. */
454 unsigned uShiftOffset2Index;
455 /** Block shift value for converting block index into offset in image. */
456 unsigned uShiftIndex2Offset;
457 /** Offset of data from the beginning of block. */
458 unsigned offStartBlockData;
459 /** Image is modified flags (VDI_IMAGE_MODIFIED*). */
460 unsigned fModified;
461 /** Container filename. (UTF-8)
462 * @todo Make this variable length to save a bunch of bytes. (low prio) */
463 char szFilename[RTPATH_MAX];
464} VDIIMAGEDESC, *PVDIIMAGEDESC;
465
466/**
467 * Default work buffer size, may be changed by setBufferSize() method.
468 *
469 * For best speed performance it must be equal to image block size.
470 */
471#define VDIDISK_DEFAULT_BUFFER_SIZE (VDI_IMAGE_DEFAULT_BLOCK_SIZE)
472
473/** VDIDISK Signature. */
474#define VDIDISK_SIGNATURE (0xbedafeda)
475
476/**
477 * VBox HDD Container main structure, private part.
478 */
479struct VDIDISK
480{
481 /** Structure signature (VDIDISK_SIGNATURE). */
482 uint32_t u32Signature;
483
484 /** Number of opened images. */
485 unsigned cImages;
486
487 /** Base image. */
488 PVDIIMAGEDESC pBase;
489
490 /** Last opened image in the chain.
491 * The same as pBase if only one image is used or the last opened diff image. */
492 PVDIIMAGEDESC pLast;
493
494 /** Default block size for newly created images. */
495 unsigned cbBlock;
496
497 /** Working buffer size, allocated only while committing data,
498 * copying block from primary image to secondary and saving previously
499 * zero block. Buffer deallocated after operation complete.
500 * @remark For best performance buffer size must be equal to image's
501 * block size, however it may be decreased for memory saving.
502 */
503 unsigned cbBuf;
504
505 /** The media interface. */
506 PDMIMEDIA IMedia;
507 /** Pointer to the driver instance. */
508 PPDMDRVINS pDrvIns;
509};
510
511
512/** Converts a pointer to VDIDISK::IMedia to a PVDIDISK. */
513#define PDMIMEDIA_2_VDIDISK(pInterface) ( (PVDIDISK)((uintptr_t)pInterface - RT_OFFSETOF(VDIDISK, IMedia)) )
514
515/** Converts a pointer to PDMDRVINS::IBase to a PPDMDRVINS. */
516#define PDMIBASE_2_DRVINS(pInterface) ( (PPDMDRVINS)((uintptr_t)pInterface - RT_OFFSETOF(PDMDRVINS, IBase)) )
517
518/** Converts a pointer to PDMDRVINS::IBase to a PVDIDISK. */
519#define PDMIBASE_2_VDIDISK(pInterface) ( PDMINS2DATA(PDMIBASE_2_DRVINS(pInterface), PVDIDISK) )
520
521
522/*******************************************************************************
523* Internal Functions *
524*******************************************************************************/
525static unsigned getPowerOfTwo(unsigned uNumber);
526static void vdiInitPreHeader(PVDIPREHEADER pPreHdr);
527static int vdiValidatePreHeader(PVDIPREHEADER pPreHdr);
528static void vdiInitHeader(PVDIHEADER pHeader, VDIIMAGETYPE enmType, uint32_t fFlags,
529 const char *pszComment, uint64_t cbDisk, uint32_t cbBlock,
530 uint32_t cbBlockExtra);
531static int vdiValidateHeader(PVDIHEADER pHeader);
532static int vdiCreateImage(const char *pszFilename, VDIIMAGETYPE enmType, unsigned fFlags,
533 uint64_t cbSize, const char *pszComment, PVDIIMAGEDESC pParent,
534 PFNVMPROGRESS pfnProgress, void *pvUser);
535static void vdiInitImageDesc(PVDIIMAGEDESC pImage);
536static void vdiSetupImageDesc(PVDIIMAGEDESC pImage);
537static int vdiOpenImage(PVDIIMAGEDESC *ppImage, const char *pszFilename, unsigned fOpen,
538 PVDIIMAGEDESC pParent);
539static int vdiUpdateHeader(PVDIIMAGEDESC pImage);
540static int vdiUpdateBlockInfo(PVDIIMAGEDESC pImage, unsigned uBlock);
541static int vdiUpdateBlocks(PVDIIMAGEDESC pImage);
542static void vdiSetModifiedFlag(PVDIIMAGEDESC pImage);
543static void vdiResetModifiedFlag(PVDIIMAGEDESC pImage);
544static void vdiDisableLastModifiedUpdate(PVDIIMAGEDESC pImage);
545#if 0 /* unused */
546static void vdiEnableLastModifiedUpdate(PVDIIMAGEDESC pImage);
547#endif
548static void vdiFlushImage(PVDIIMAGEDESC pImage);
549static void vdiCloseImage(PVDIIMAGEDESC pImage);
550static int vdiReadInBlock(PVDIIMAGEDESC pImage, unsigned uBlock, unsigned offRead,
551 unsigned cbToRead, void *pvBuf);
552static int vdiFillBlockByZeroes(PVDIDISK pDisk, PVDIIMAGEDESC pImage, unsigned uBlock);
553static int vdiWriteInBlock(PVDIDISK pDisk, PVDIIMAGEDESC pImage, unsigned uBlock,
554 unsigned offWrite, unsigned cbToWrite, const void *pvBuf);
555static int vdiCopyBlock(PVDIDISK pDisk, PVDIIMAGEDESC pImage, unsigned uBlock);
556static int vdiMergeImages(PVDIIMAGEDESC pImageFrom, PVDIIMAGEDESC pImageTo, bool fParentToChild,
557 PFNVMPROGRESS pfnProgress, void *pvUser);
558static void vdiInitVDIDisk(PVDIDISK pDisk);
559static void vdiAddImageToList(PVDIDISK pDisk, PVDIIMAGEDESC pImage);
560static void vdiRemoveImageFromList(PVDIDISK pDisk, PVDIIMAGEDESC pImage);
561static PVDIIMAGEDESC vdiGetImageByNumber(PVDIDISK pDisk, int nImage);
562static int vdiChangeImageMode(PVDIIMAGEDESC pImage, bool fReadOnly);
563static int vdiUpdateReadOnlyHeader(PVDIIMAGEDESC pImage);
564
565static int vdiCommitToImage(PVDIDISK pDisk, PVDIIMAGEDESC pDstImage,
566 PFNVMPROGRESS pfnProgress, void *pvUser);
567static void vdiDumpImage(PVDIIMAGEDESC pImage);
568
569static DECLCALLBACK(int) vdiConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfgHandle);
570static DECLCALLBACK(void) vdiDestruct(PPDMDRVINS pDrvIns);
571static DECLCALLBACK(int) vdiRead(PPDMIMEDIA pInterface,
572 uint64_t off, void *pvBuf, size_t cbRead);
573static DECLCALLBACK(int) vdiWrite(PPDMIMEDIA pInterface,
574 uint64_t off, const void *pvBuf, size_t cbWrite);
575static DECLCALLBACK(int) vdiFlush(PPDMIMEDIA pInterface);
576static DECLCALLBACK(uint64_t) vdiGetSize(PPDMIMEDIA pInterface);
577static DECLCALLBACK(int) vdiBiosGetGeometry(PPDMIMEDIA pInterface, uint32_t *pcCylinders,
578 uint32_t *pcHeads, uint32_t *pcSectors);
579static DECLCALLBACK(int) vdiBiosSetGeometry(PPDMIMEDIA pInterface, uint32_t cCylinders,
580 uint32_t cHeads, uint32_t cSectors);
581static DECLCALLBACK(int) vdiGetUuid(PPDMIMEDIA pInterface, PRTUUID pUuid);
582static DECLCALLBACK(bool) vdiIsReadOnly(PPDMIMEDIA pInterface);
583static DECLCALLBACK(int) vdiBiosGetTranslation(PPDMIMEDIA pInterface,
584 PPDMBIOSTRANSLATION penmTranslation);
585static DECLCALLBACK(int) vdiBiosSetTranslation(PPDMIMEDIA pInterface,
586 PDMBIOSTRANSLATION enmTranslation);
587static DECLCALLBACK(void *) vdiQueryInterface(PPDMIBASE pInterface, PDMINTERFACE enmInterface);
588
589
590/**
591 * internal: return power of 2 or 0 if num error.
592 */
593static unsigned getPowerOfTwo(unsigned uNumber)
594{
595 if (uNumber == 0)
596 return 0;
597 unsigned uPower2 = 0;
598 while ((uNumber & 1) == 0)
599 {
600 uNumber >>= 1;
601 uPower2++;
602 }
603 return uNumber == 1 ? uPower2 : 0;
604}
605
606/**
607 * internal: init HDD preheader.
608 */
609static void vdiInitPreHeader(PVDIPREHEADER pPreHdr)
610{
611 pPreHdr->u32Signature = VDI_IMAGE_SIGNATURE;
612 pPreHdr->u32Version = VDI_IMAGE_VERSION;
613 memset(pPreHdr->szFileInfo, 0, sizeof(pPreHdr->szFileInfo));
614 strncat(pPreHdr->szFileInfo, VDI_IMAGE_FILE_INFO, sizeof(pPreHdr->szFileInfo));
615}
616
617/**
618 * internal: check HDD preheader.
619 */
620static int vdiValidatePreHeader(PVDIPREHEADER pPreHdr)
621{
622 if (pPreHdr->u32Signature != VDI_IMAGE_SIGNATURE)
623 return VERR_VDI_INVALID_SIGNATURE;
624
625 if ( pPreHdr->u32Version != VDI_IMAGE_VERSION
626 && pPreHdr->u32Version != 0x00000002) /* old version. */
627 return VERR_VDI_UNSUPPORTED_VERSION;
628
629 return VINF_SUCCESS;
630}
631
632/**
633 * internal: init HDD header. Always use latest header version.
634 * @param pHeader Assumes it was initially initialized to all zeros.
635 */
636static void vdiInitHeader(PVDIHEADER pHeader, VDIIMAGETYPE enmType, uint32_t fFlags,
637 const char *pszComment, uint64_t cbDisk, uint32_t cbBlock,
638 uint32_t cbBlockExtra)
639{
640 pHeader->uVersion = VDI_IMAGE_VERSION;
641 pHeader->u.v1.cbHeader = sizeof(VDIHEADER1);
642 pHeader->u.v1.u32Type = (uint32_t)enmType;
643 pHeader->u.v1.fFlags = fFlags;
644#ifdef VBOX_STRICT
645 char achZero[VDI_IMAGE_COMMENT_SIZE] = {0};
646 Assert(!memcmp(pHeader->u.v1.szComment, achZero, VDI_IMAGE_COMMENT_SIZE));
647#endif
648 pHeader->u.v1.szComment[0] = '\0';
649 if (pszComment)
650 {
651 AssertMsg(strlen(pszComment) < sizeof(pHeader->u.v1.szComment),
652 ("HDD Comment is too long, cb=%d\n", strlen(pszComment)));
653 strncat(pHeader->u.v1.szComment, pszComment, sizeof(pHeader->u.v1.szComment));
654 }
655
656 /* Mark the geometry not-calculated. */
657 pHeader->u.v1.Geometry.cCylinders = 0;
658 pHeader->u.v1.Geometry.cHeads = 0;
659 pHeader->u.v1.Geometry.cSectors = 0;
660 pHeader->u.v1.Geometry.cbSector = VDI_GEOMETRY_SECTOR_SIZE;
661 pHeader->u.v1.u32Translation = PDMBIOSTRANSLATION_AUTO;
662
663 pHeader->u.v1.cbDisk = cbDisk;
664 pHeader->u.v1.cbBlock = cbBlock;
665 pHeader->u.v1.cBlocks = (uint32_t)(cbDisk / cbBlock);
666 if (cbDisk % cbBlock)
667 pHeader->u.v1.cBlocks++;
668 pHeader->u.v1.cbBlockExtra = cbBlockExtra;
669 pHeader->u.v1.cBlocksAllocated = 0;
670
671 /* Init offsets. */
672 pHeader->u.v1.offBlocks = RT_ALIGN_32(sizeof(VDIPREHEADER) + sizeof(VDIHEADER1), VDI_GEOMETRY_SECTOR_SIZE);
673 pHeader->u.v1.offData = RT_ALIGN_32(pHeader->u.v1.offBlocks + (pHeader->u.v1.cBlocks * sizeof(VDIIMAGEBLOCKPOINTER)), VDI_GEOMETRY_SECTOR_SIZE);
674
675 /* Init uuids. */
676 RTUuidCreate(&pHeader->u.v1.uuidCreate);
677 RTUuidClear(&pHeader->u.v1.uuidModify);
678 RTUuidClear(&pHeader->u.v1.uuidLinkage);
679 RTUuidClear(&pHeader->u.v1.uuidParentModify);
680}
681
682/**
683 * internal: check HDD header.
684 */
685static int vdiValidateHeader(PVDIHEADER pHeader)
686{
687 /* Check verion-dependend header parameters. */
688 switch (GET_MAJOR_HEADER_VERSION(pHeader))
689 {
690 case 0:
691 {
692 /* Old header version. */
693 break;
694 }
695 case 1:
696 {
697 /* Current header version. */
698
699 if (pHeader->u.v1.cbHeader < sizeof(VDIHEADER1))
700 {
701 LogRel(("VDI: v1 header size wrong (%d < %d)\n",
702 pHeader->u.v1.cbHeader, sizeof(VDIHEADER1)));
703 return VERR_VDI_INVALID_HEADER;
704 }
705
706 if (getImageBlocksOffset(pHeader) < (sizeof(VDIPREHEADER) + sizeof(VDIHEADER1)))
707 {
708 LogRel(("VDI: v1 blocks offset wrong (%d < %d)\n",
709 getImageBlocksOffset(pHeader), sizeof(VDIPREHEADER) + sizeof(VDIHEADER1)));
710 return VERR_VDI_INVALID_HEADER;
711 }
712
713 if (getImageDataOffset(pHeader) < (getImageBlocksOffset(pHeader) + getImageBlocks(pHeader) * sizeof(VDIIMAGEBLOCKPOINTER)))
714 {
715 LogRel(("VDI: v1 image data offset wrong (%d < %d)\n",
716 getImageDataOffset(pHeader), getImageBlocksOffset(pHeader) + getImageBlocks(pHeader) * sizeof(VDIIMAGEBLOCKPOINTER)));
717 return VERR_VDI_INVALID_HEADER;
718 }
719
720 if ( getImageType(pHeader) == VDI_IMAGE_TYPE_UNDO
721 || getImageType(pHeader) == VDI_IMAGE_TYPE_DIFF)
722 {
723 if (RTUuidIsNull(getImageParentUUID(pHeader)))
724 {
725 LogRel(("VDI: v1 uuid of parent is 0)\n"));
726 return VERR_VDI_INVALID_HEADER;
727 }
728 if (RTUuidIsNull(getImageParentModificationUUID(pHeader)))
729 {
730 LogRel(("VDI: v1 uuid of parent modification is 0\n"));
731 return VERR_VDI_INVALID_HEADER;
732 }
733 }
734
735 break;
736 }
737 default:
738 /* Unsupported. */
739 return VERR_VDI_UNSUPPORTED_VERSION;
740 }
741
742 /* Check common header parameters. */
743
744 bool fFailed = false;
745
746 if ( getImageType(pHeader) < VDI_IMAGE_TYPE_FIRST
747 || getImageType(pHeader) > VDI_IMAGE_TYPE_LAST)
748 {
749 LogRel(("VDI: bad image type %d\n", getImageType(pHeader)));
750 fFailed = true;
751 }
752
753 if (getImageFlags(pHeader) & ~VDI_IMAGE_FLAGS_MASK)
754 {
755 LogRel(("VDI: bad image flags %08x\n", getImageFlags(pHeader)));
756 fFailed = true;
757 }
758
759 if ((getImageGeometry(pHeader))->cbSector != VDI_GEOMETRY_SECTOR_SIZE)
760 {
761 LogRel(("VDI: wrong sector size (%d != %d)\n",
762 (getImageGeometry(pHeader))->cbSector, VDI_GEOMETRY_SECTOR_SIZE));
763 fFailed = true;
764 }
765
766 if ( getImageDiskSize(pHeader) == 0
767 || getImageBlockSize(pHeader) == 0
768 || getImageBlocks(pHeader) == 0
769 || getPowerOfTwo(getImageBlockSize(pHeader)) == 0)
770 {
771 LogRel(("VDI: wrong size (%lld, %d, %d, %d)\n",
772 getImageDiskSize(pHeader), getImageBlockSize(pHeader),
773 getImageBlocks(pHeader), getPowerOfTwo(getImageBlockSize(pHeader))));
774 fFailed = true;
775 }
776
777 if (getImageBlocksAllocated(pHeader) > getImageBlocks(pHeader))
778 {
779 LogRel(("VDI: too many blocks allocated (%d > %d)\n"
780 " blocksize=%d disksize=%lld\n",
781 getImageBlocksAllocated(pHeader), getImageBlocks(pHeader),
782 getImageBlockSize(pHeader), getImageDiskSize(pHeader)));
783 fFailed = true;
784 }
785
786 if ( getImageExtraBlockSize(pHeader) != 0
787 && getPowerOfTwo(getImageExtraBlockSize(pHeader)) == 0)
788 {
789 LogRel(("VDI: wrong extra size (%d, %d)\n",
790 getImageExtraBlockSize(pHeader), getPowerOfTwo(getImageExtraBlockSize(pHeader))));
791 fFailed = true;
792 }
793
794 if ((uint64_t)getImageBlockSize(pHeader) * getImageBlocks(pHeader) < getImageDiskSize(pHeader))
795 {
796 LogRel(("VDI: wrong disk size (%d, %d, %lld)\n",
797 getImageBlockSize(pHeader), getImageBlocks(pHeader), getImageDiskSize(pHeader)));
798 fFailed = true;
799 }
800
801 if (RTUuidIsNull(getImageCreationUUID(pHeader)))
802 {
803 LogRel(("VDI: uuid of creator is 0\n"));
804 fFailed = true;
805 }
806
807 if (RTUuidIsNull(getImageModificationUUID(pHeader)))
808 {
809 LogRel(("VDI: uuid of modificator is 0\n"));
810 fFailed = true;
811 }
812
813 return fFailed ? VERR_VDI_INVALID_HEADER : VINF_SUCCESS;
814}
815
816/**
817 * internal: init VDIIMAGEDESC structure.
818 */
819static void vdiInitImageDesc(PVDIIMAGEDESC pImage)
820{
821 pImage->pPrev = NULL;
822 pImage->pNext = NULL;
823 pImage->File = NIL_RTFILE;
824 pImage->paBlocks = NULL;
825}
826
827/**
828 * internal: setup VDIIMAGEDESC structure by image header.
829 */
830static void vdiSetupImageDesc(PVDIIMAGEDESC pImage)
831{
832 pImage->fFlags = getImageFlags(&pImage->Header);
833 pImage->offStartBlocks = getImageBlocksOffset(&pImage->Header);
834 pImage->offStartData = getImageDataOffset(&pImage->Header);
835 pImage->uBlockMask = getImageBlockSize(&pImage->Header) - 1;
836 pImage->uShiftIndex2Offset =
837 pImage->uShiftOffset2Index = getPowerOfTwo(getImageBlockSize(&pImage->Header));
838 pImage->offStartBlockData = getImageExtraBlockSize(&pImage->Header);
839 if (pImage->offStartBlockData != 0)
840 pImage->uShiftIndex2Offset += getPowerOfTwo(pImage->offStartBlockData);
841}
842
843/**
844 * internal: create image.
845 */
846static int vdiCreateImage(const char *pszFilename, VDIIMAGETYPE enmType, unsigned fFlags,
847 uint64_t cbSize, const char *pszComment, PVDIIMAGEDESC pParent,
848 PFNVMPROGRESS pfnProgress, void *pvUser)
849{
850 /* Check args. */
851 Assert(pszFilename);
852 Assert(enmType >= VDI_IMAGE_TYPE_FIRST && enmType <= VDI_IMAGE_TYPE_LAST);
853 Assert(!(fFlags & ~VDI_IMAGE_FLAGS_MASK));
854 Assert(cbSize);
855
856 /* Special check for comment length. */
857 if ( pszComment
858 && strlen(pszComment) >= VDI_IMAGE_COMMENT_SIZE)
859 {
860 Log(("vdiCreateImage: pszComment is too long, cb=%d\n", strlen(pszComment)));
861 return VERR_VDI_COMMENT_TOO_LONG;
862 }
863
864 if ( enmType == VDI_IMAGE_TYPE_UNDO
865 || enmType == VDI_IMAGE_TYPE_DIFF)
866 {
867 Assert(pParent);
868 if ((pParent->PreHeader.u32Version >> 16) != VDI_IMAGE_VERSION_MAJOR)
869 {
870 /* Invalid parent image version. */
871 Log(("vdiCreateImage: unsupported parent version=%08X\n", pParent->PreHeader.u32Version));
872 return VERR_VDI_UNSUPPORTED_VERSION;
873 }
874
875 /* get image params from the parent image. */
876 fFlags = getImageFlags(&pParent->Header);
877 cbSize = getImageDiskSize(&pParent->Header);
878 }
879
880 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)RTMemAllocZ(sizeof(VDIIMAGEDESC));
881 if (!pImage)
882 return VERR_NO_MEMORY;
883 vdiInitImageDesc(pImage);
884
885 vdiInitPreHeader(&pImage->PreHeader);
886 vdiInitHeader(&pImage->Header, enmType, fFlags, pszComment, cbSize, VDI_IMAGE_DEFAULT_BLOCK_SIZE, 0);
887
888 if ( enmType == VDI_IMAGE_TYPE_UNDO
889 || enmType == VDI_IMAGE_TYPE_DIFF)
890 {
891 /* Set up linkage information. */
892 pImage->Header.u.v1.uuidLinkage = *getImageCreationUUID(&pParent->Header);
893 pImage->Header.u.v1.uuidParentModify = *getImageModificationUUID(&pParent->Header);
894 }
895
896 pImage->paBlocks = (PVDIIMAGEBLOCKPOINTER)RTMemAlloc(sizeof(VDIIMAGEBLOCKPOINTER) * getImageBlocks(&pImage->Header));
897 if (!pImage->paBlocks)
898 {
899 RTMemFree(pImage);
900 return VERR_NO_MEMORY;
901 }
902
903 if (enmType != VDI_IMAGE_TYPE_FIXED)
904 {
905 /* for growing images mark all blocks in paBlocks as free. */
906 for (unsigned i = 0; i < pImage->Header.u.v1.cBlocks; i++)
907 pImage->paBlocks[i] = VDI_IMAGE_BLOCK_FREE;
908 }
909 else
910 {
911 /* for fixed images mark all blocks in paBlocks as allocated */
912 for (unsigned i = 0; i < pImage->Header.u.v1.cBlocks; i++)
913 pImage->paBlocks[i] = i;
914 pImage->Header.u.v1.cBlocksAllocated = pImage->Header.u.v1.cBlocks;
915 }
916
917 /* Setup image parameters. */
918 vdiSetupImageDesc(pImage);
919
920 /* create file */
921 int rc = RTFileOpen(&pImage->File,
922 pszFilename,
923 RTFILE_O_READWRITE | RTFILE_O_CREATE | RTFILE_O_DENY_ALL);
924 if (VBOX_SUCCESS(rc))
925 {
926 /* Lock image exclusively to close any wrong access by VDI API calls. */
927 uint64_t cbLock = pImage->offStartData
928 + ((uint64_t)getImageBlocks(&pImage->Header) << pImage->uShiftIndex2Offset);
929 rc = RTFileLock(pImage->File,
930 RTFILE_LOCK_WRITE | RTFILE_LOCK_IMMEDIATELY, 0, cbLock);
931 if (VBOX_FAILURE(rc))
932 {
933 cbLock = 0; /* Not locked. */
934 goto l_create_failed;
935 }
936
937 if (enmType == VDI_IMAGE_TYPE_FIXED)
938 {
939 /*
940 * Allocate & commit whole file if fixed image, it must be more
941 * effective than expanding file by write operations.
942 */
943 rc = RTFileSetSize(pImage->File,
944 pImage->offStartData
945 + ((uint64_t)getImageBlocks(&pImage->Header) << pImage->uShiftIndex2Offset));
946 }
947 else
948 {
949 /* Set file size to hold header and blocks array. */
950 rc = RTFileSetSize(pImage->File, pImage->offStartData);
951 }
952 if (VBOX_FAILURE(rc))
953 goto l_create_failed;
954
955 /* Generate image last-modify uuid */
956 RTUuidCreate(getImageModificationUUID(&pImage->Header));
957
958 /* Write pre-header. */
959 rc = RTFileWrite(pImage->File, &pImage->PreHeader, sizeof(pImage->PreHeader), NULL);
960 if (VBOX_FAILURE(rc))
961 goto l_create_failed;
962
963 /* Write header. */
964 rc = RTFileWrite(pImage->File, &pImage->Header.u.v1, sizeof(pImage->Header.u.v1), NULL);
965 if (VBOX_FAILURE(rc))
966 goto l_create_failed;
967
968 /* Write blocks array. */
969 rc = RTFileSeek(pImage->File, pImage->offStartBlocks, RTFILE_SEEK_BEGIN, NULL);
970 if (VBOX_FAILURE(rc))
971 goto l_create_failed;
972 rc = RTFileWrite(pImage->File,
973 pImage->paBlocks,
974 getImageBlocks(&pImage->Header) * sizeof(VDIIMAGEBLOCKPOINTER),
975 NULL);
976 if (VBOX_FAILURE(rc))
977 goto l_create_failed;
978
979 if ( (enmType == VDI_IMAGE_TYPE_FIXED)
980 && (fFlags & VDI_IMAGE_FLAGS_ZERO_EXPAND))
981 {
982 /* Fill image with zeroes. */
983
984 rc = RTFileSeek(pImage->File, pImage->offStartData, RTFILE_SEEK_BEGIN, NULL);
985 if (VBOX_FAILURE(rc))
986 goto l_create_failed;
987
988 /* alloc tmp zero-filled buffer */
989 void *pvBuf = RTMemTmpAllocZ(VDIDISK_DEFAULT_BUFFER_SIZE);
990 if (pvBuf)
991 {
992 uint64_t cbFill = (uint64_t)getImageBlocks(&pImage->Header) << pImage->uShiftIndex2Offset;
993 uint64_t cbDisk = cbFill;
994
995 /* do loop to fill all image. */
996 while (cbFill > 0)
997 {
998 unsigned to_fill = (unsigned)RT_MIN(cbFill, VDIDISK_DEFAULT_BUFFER_SIZE);
999
1000 rc = RTFileWrite(pImage->File, pvBuf, to_fill, NULL);
1001 if (VBOX_FAILURE(rc))
1002 break;
1003
1004 cbFill -= to_fill;
1005
1006 if (pfnProgress)
1007 {
1008 rc = pfnProgress(NULL /* WARNING! pVM=NULL */,
1009 (unsigned)(((cbDisk - cbFill) * 100) / cbDisk),
1010 pvUser);
1011 if (VBOX_FAILURE(rc))
1012 break;
1013 }
1014 }
1015 RTMemTmpFree(pvBuf);
1016 }
1017 else
1018 {
1019 /* alloc error */
1020 rc = VERR_NO_MEMORY;
1021 }
1022 }
1023
1024 l_create_failed:
1025
1026 if (cbLock)
1027 RTFileUnlock(pImage->File, 0, cbLock);
1028
1029 RTFileClose(pImage->File);
1030
1031 /* Delete image file if error occured while creating */
1032 if (VBOX_FAILURE(rc))
1033 RTFileDelete(pszFilename);
1034 }
1035
1036 RTMemFree(pImage->paBlocks);
1037 RTMemFree(pImage);
1038
1039 if ( VBOX_SUCCESS(rc)
1040 && pfnProgress)
1041 pfnProgress(NULL /* WARNING! pVM=NULL */, 100, pvUser);
1042
1043 Log(("vdiCreateImage: done, filename=\"%s\", rc=%Vrc\n", pszFilename, rc));
1044
1045 return rc;
1046}
1047
1048/**
1049 * Open an image.
1050 * @internal
1051 */
1052static int vdiOpenImage(PVDIIMAGEDESC *ppImage, const char *pszFilename,
1053 unsigned fOpen, PVDIIMAGEDESC pParent)
1054{
1055 /*
1056 * Validate input.
1057 */
1058 Assert(ppImage);
1059 Assert(pszFilename);
1060 Assert(!(fOpen & ~VDI_OPEN_FLAGS_MASK));
1061
1062 PVDIIMAGEDESC pImage;
1063 size_t cchFilename = strlen(pszFilename);
1064 if (cchFilename >= sizeof(pImage->szFilename))
1065 {
1066 AssertMsgFailed(("filename=\"%s\" is too long (%d bytes)!\n", pszFilename, cchFilename));
1067 return VERR_FILENAME_TOO_LONG;
1068 }
1069
1070 pImage = (PVDIIMAGEDESC)RTMemAllocZ(sizeof(VDIIMAGEDESC));
1071 if (!pImage)
1072 return VERR_NO_MEMORY;
1073 vdiInitImageDesc(pImage);
1074
1075 memcpy(pImage->szFilename, pszFilename, cchFilename);
1076 pImage->fOpen = fOpen;
1077
1078 /*
1079 * Open the image.
1080 */
1081 int rc = RTFileOpen(&pImage->File,
1082 pImage->szFilename,
1083 fOpen & VDI_OPEN_FLAGS_READONLY
1084 ? RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE
1085 : RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
1086 if (VBOX_FAILURE(rc))
1087 {
1088 if (!(fOpen & VDI_OPEN_FLAGS_READONLY))
1089 {
1090 /* Try to open image for reading only. */
1091 rc = RTFileOpen(&pImage->File,
1092 pImage->szFilename,
1093 RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
1094 if (VBOX_SUCCESS(rc))
1095 pImage->fOpen |= VDI_OPEN_FLAGS_READONLY;
1096 }
1097 if (VBOX_FAILURE(rc))
1098 {
1099 RTMemFree(pImage);
1100 return rc;
1101 }
1102 }
1103 /* Set up current image r/w state. */
1104 pImage->fReadOnly = !!(pImage->fOpen & VDI_OPEN_FLAGS_READONLY);
1105
1106 /*
1107 * Set initial file lock for reading header only.
1108 * Length of lock doesn't matter, it just must include image header.
1109 */
1110 uint64_t cbLock = _1M;
1111 rc = RTFileLock(pImage->File, RTFILE_LOCK_READ | RTFILE_LOCK_IMMEDIATELY, 0, cbLock);
1112 if (VBOX_FAILURE(rc))
1113 {
1114 cbLock = 0;
1115 goto l_open_failed;
1116 }
1117
1118 /* Read pre-header. */
1119 rc = RTFileRead(pImage->File, &pImage->PreHeader, sizeof(pImage->PreHeader), NULL);
1120 if (VBOX_FAILURE(rc))
1121 goto l_open_failed;
1122 rc = vdiValidatePreHeader(&pImage->PreHeader);
1123 if (VBOX_FAILURE(rc))
1124 goto l_open_failed;
1125
1126 /* Read header. */
1127 pImage->Header.uVersion = pImage->PreHeader.u32Version;
1128 switch (GET_MAJOR_HEADER_VERSION(&pImage->Header))
1129 {
1130 case 0:
1131 rc = RTFileRead(pImage->File, &pImage->Header.u.v0, sizeof(pImage->Header.u.v0), NULL);
1132 break;
1133 case 1:
1134 rc = RTFileRead(pImage->File, &pImage->Header.u.v1, sizeof(pImage->Header.u.v1), NULL);
1135 break;
1136 default:
1137 rc = VERR_VDI_UNSUPPORTED_VERSION;
1138 break;
1139 }
1140 if (VBOX_FAILURE(rc))
1141 goto l_open_failed;
1142
1143 rc = vdiValidateHeader(&pImage->Header);
1144 if (VBOX_FAILURE(rc))
1145 goto l_open_failed;
1146
1147 /* Check diff image correctness. */
1148 if (pParent)
1149 {
1150 if (pImage->PreHeader.u32Version != pParent->PreHeader.u32Version)
1151 {
1152 rc = VERR_VDI_IMAGES_VERSION_MISMATCH;
1153 goto l_open_failed;
1154 }
1155
1156 if ( getImageType(&pImage->Header) != VDI_IMAGE_TYPE_UNDO
1157 && getImageType(&pImage->Header) != VDI_IMAGE_TYPE_DIFF)
1158 {
1159 rc = VERR_VDI_WRONG_DIFF_IMAGE;
1160 goto l_open_failed;
1161 }
1162
1163 if ( getImageDiskSize(&pImage->Header) != getImageDiskSize(&pParent->Header)
1164 || getImageBlockSize(&pImage->Header) != getImageBlockSize(&pParent->Header)
1165 || getImageBlocks(&pImage->Header) != getImageBlocks(&pParent->Header)
1166 || getImageExtraBlockSize(&pImage->Header) != getImageExtraBlockSize(&pParent->Header))
1167 {
1168 rc = VERR_VDI_WRONG_DIFF_IMAGE;
1169 goto l_open_failed;
1170 }
1171
1172 /* Check linkage data. */
1173 if ( RTUuidCompare(getImageParentUUID(&pImage->Header),
1174 getImageCreationUUID(&pParent->Header))
1175 || RTUuidCompare(getImageParentModificationUUID(&pImage->Header),
1176 getImageModificationUUID(&pParent->Header)))
1177 {
1178 rc = VERR_VDI_IMAGES_UUID_MISMATCH;
1179 goto l_open_failed;
1180 }
1181 }
1182
1183 /* Setup image parameters by header. */
1184 vdiSetupImageDesc(pImage);
1185
1186 /* reset modified flag into first-modified state. */
1187 pImage->fModified = VDI_IMAGE_MODIFIED_FIRST;
1188
1189 /* Image is validated, set working file lock on it. */
1190 rc = RTFileUnlock(pImage->File, 0, cbLock);
1191 AssertRC(rc);
1192 cbLock = pImage->offStartData
1193 + ((uint64_t)getImageBlocks(&pImage->Header) << pImage->uShiftIndex2Offset);
1194 rc = RTFileLock(pImage->File,
1195 (pImage->fReadOnly) ?
1196 RTFILE_LOCK_READ | RTFILE_LOCK_IMMEDIATELY :
1197 RTFILE_LOCK_WRITE | RTFILE_LOCK_IMMEDIATELY,
1198 0,
1199 cbLock);
1200 if ( VBOX_FAILURE(rc)
1201 && !pImage->fReadOnly)
1202 {
1203 /* Failed to lock image for writing, try read-only lock. */
1204 rc = RTFileLock(pImage->File,
1205 RTFILE_LOCK_READ | RTFILE_LOCK_IMMEDIATELY, 0, cbLock);
1206 if (VBOX_SUCCESS(rc))
1207 pImage->fReadOnly = true;
1208 }
1209 if (VBOX_FAILURE(rc))
1210 {
1211 cbLock = 0; /* Not locked. */
1212 goto l_open_failed;
1213 }
1214
1215 /* Allocate memory for blocks array. */
1216 pImage->paBlocks = (PVDIIMAGEBLOCKPOINTER)RTMemAlloc(sizeof(VDIIMAGEBLOCKPOINTER) * getImageBlocks(&pImage->Header));
1217 if (!pImage->paBlocks)
1218 {
1219 rc = VERR_NO_MEMORY;
1220 goto l_open_failed;
1221 }
1222
1223 /* Read blocks array. */
1224 rc = RTFileSeek(pImage->File, pImage->offStartBlocks, RTFILE_SEEK_BEGIN, NULL);
1225 if (VBOX_FAILURE(rc))
1226 goto l_open_failed;
1227 rc = RTFileRead(pImage->File, pImage->paBlocks,
1228 getImageBlocks(&pImage->Header) * sizeof(VDIIMAGEBLOCKPOINTER), NULL);
1229 if (VBOX_FAILURE(rc))
1230 goto l_open_failed;
1231
1232 /* all done. */
1233 *ppImage = pImage;
1234 return VINF_SUCCESS;
1235
1236l_open_failed:
1237 /* Clean up. */
1238 if (pImage->paBlocks)
1239 RTMemFree(pImage->paBlocks);
1240 if (cbLock)
1241 RTFileUnlock(pImage->File, 0, cbLock);
1242 RTFileClose(pImage->File);
1243 RTMemFree(pImage);
1244 Log(("vdiOpenImage: failed, filename=\"%s\", rc=%Vrc\n", pszFilename, rc));
1245 return rc;
1246}
1247
1248/**
1249 * internal: save header to file.
1250 */
1251static int vdiUpdateHeader(PVDIIMAGEDESC pImage)
1252{
1253 /* Seek to header start. */
1254 int rc = RTFileSeek(pImage->File, sizeof(VDIPREHEADER), RTFILE_SEEK_BEGIN, NULL);
1255 if (VBOX_SUCCESS(rc))
1256 {
1257 switch (GET_MAJOR_HEADER_VERSION(&pImage->Header))
1258 {
1259 case 0:
1260 rc = RTFileWrite(pImage->File, &pImage->Header.u.v0, sizeof(pImage->Header.u.v0), NULL);
1261 break;
1262 case 1:
1263 rc = RTFileWrite(pImage->File, &pImage->Header.u.v1, sizeof(pImage->Header.u.v1), NULL);
1264 break;
1265 default:
1266 rc = VERR_VDI_UNSUPPORTED_VERSION;
1267 break;
1268 }
1269 }
1270 AssertMsgRC(rc, ("vdiUpdateHeader failed, filename=\"%s\" rc=%Vrc\n", pImage->szFilename, rc));
1271 return rc;
1272}
1273
1274/**
1275 * internal: save block pointer to file, save header to file.
1276 */
1277static int vdiUpdateBlockInfo(PVDIIMAGEDESC pImage, unsigned uBlock)
1278{
1279 /* Update image header. */
1280 int rc = vdiUpdateHeader(pImage);
1281 if (VBOX_SUCCESS(rc))
1282 {
1283 /* write only one block pointer. */
1284 rc = RTFileSeek(pImage->File,
1285 pImage->offStartBlocks + uBlock * sizeof(VDIIMAGEBLOCKPOINTER),
1286 RTFILE_SEEK_BEGIN,
1287 NULL);
1288 if (VBOX_SUCCESS(rc))
1289 rc = RTFileWrite(pImage->File,
1290 &pImage->paBlocks[uBlock],
1291 sizeof(VDIIMAGEBLOCKPOINTER),
1292 NULL);
1293 AssertMsgRC(rc, ("vdiUpdateBlockInfo failed to update block=%u, filename=\"%s\", rc=%Vrc\n",
1294 uBlock, pImage->szFilename, rc));
1295 }
1296 return rc;
1297}
1298
1299/**
1300 * internal: save blocks array to file, save header to file.
1301 */
1302static int vdiUpdateBlocks(PVDIIMAGEDESC pImage)
1303{
1304 /* Update image header. */
1305 int rc = vdiUpdateHeader(pImage);
1306 if (VBOX_SUCCESS(rc))
1307 {
1308 /* write the block pointers array. */
1309 rc = RTFileSeek(pImage->File, pImage->offStartBlocks, RTFILE_SEEK_BEGIN, NULL);
1310 if (VBOX_SUCCESS(rc))
1311 rc = RTFileWrite(pImage->File,
1312 pImage->paBlocks,
1313 sizeof(VDIIMAGEBLOCKPOINTER) * getImageBlocks(&pImage->Header),
1314 NULL);
1315 AssertMsgRC(rc, ("vdiUpdateBlocks failed, filename=\"%s\", rc=%Vrc\n",
1316 pImage->szFilename, rc));
1317 }
1318 return rc;
1319}
1320
1321/**
1322 * internal: mark image as modified, if this is the first change - update image header
1323 * on disk with a new uuidModify value.
1324 */
1325static void vdiSetModifiedFlag(PVDIIMAGEDESC pImage)
1326{
1327 pImage->fModified |= VDI_IMAGE_MODIFIED_FLAG;
1328 if (pImage->fModified & VDI_IMAGE_MODIFIED_FIRST)
1329 {
1330 pImage->fModified &= ~VDI_IMAGE_MODIFIED_FIRST;
1331
1332 /* first modify - generate uuidModify and save to file. */
1333 vdiResetModifiedFlag(pImage);
1334
1335 if (!(pImage->fModified | VDI_IMAGE_MODIFIED_DISABLE_UUID_UPDATE))
1336 {
1337 /* save header to file,
1338 * note: no rc checking.
1339 */
1340 vdiUpdateHeader(pImage);
1341 }
1342 }
1343}
1344
1345/**
1346 * internal: generate new uuidModify if the image was changed.
1347 */
1348static void vdiResetModifiedFlag(PVDIIMAGEDESC pImage)
1349{
1350 if (pImage->fModified & VDI_IMAGE_MODIFIED_FLAG)
1351 {
1352 /* generate new last-modified uuid */
1353 if (!(pImage->fModified | VDI_IMAGE_MODIFIED_DISABLE_UUID_UPDATE))
1354 RTUuidCreate(getImageModificationUUID(&pImage->Header));
1355
1356 pImage->fModified &= ~VDI_IMAGE_MODIFIED_FLAG;
1357 }
1358}
1359
1360/**
1361 * internal: disables updates of the last-modified UUID
1362 * when performing image writes.
1363 */
1364static void vdiDisableLastModifiedUpdate(PVDIIMAGEDESC pImage)
1365{
1366 pImage->fModified |= VDI_IMAGE_MODIFIED_DISABLE_UUID_UPDATE;
1367}
1368
1369#if 0 /* unused */
1370/**
1371 * internal: enables updates of the last-modified UUID
1372 * when performing image writes.
1373 */
1374static void vdiEnableLastModifiedUpdate(PVDIIMAGEDESC pImage)
1375{
1376 pImage->fModified &= ~VDI_IMAGE_MODIFIED_DISABLE_UUID_UPDATE;
1377}
1378#endif
1379
1380/**
1381 * internal: flush image file to disk.
1382 */
1383static void vdiFlushImage(PVDIIMAGEDESC pImage)
1384{
1385 if (!pImage->fReadOnly)
1386 {
1387 /* Update last-modified uuid if need. */
1388 vdiResetModifiedFlag(pImage);
1389
1390 /* Save header. */
1391 int rc = vdiUpdateHeader(pImage);
1392 AssertMsgRC(rc, ("vdiUpdateHeader() failed, filename=\"%s\", rc=%Vrc\n",
1393 pImage->szFilename, rc));
1394 RTFileFlush(pImage->File);
1395 }
1396}
1397
1398/**
1399 * internal: close image file.
1400 */
1401static void vdiCloseImage(PVDIIMAGEDESC pImage)
1402{
1403 /* Params checking. */
1404 Assert(pImage);
1405 Assert(pImage->File != NIL_RTFILE);
1406
1407 vdiFlushImage(pImage);
1408 RTFileUnlock(pImage->File,
1409 0,
1410 pImage->offStartData
1411 + ((uint64_t)getImageBlocks(&pImage->Header) << pImage->uShiftIndex2Offset));
1412 RTFileClose(pImage->File);
1413
1414 /* free image resources */
1415 RTMemFree(pImage->paBlocks);
1416 RTMemFree(pImage);
1417}
1418
1419/**
1420 * internal: read data inside image block.
1421 *
1422 * note: uBlock must be valid, readed data must not overlap block bounds.
1423 */
1424static int vdiReadInBlock(PVDIIMAGEDESC pImage, unsigned uBlock, unsigned offRead,
1425 unsigned cbToRead, void *pvBuf)
1426{
1427 if (IS_VDI_IMAGE_BLOCK_ALLOCATED(pImage->paBlocks[uBlock]))
1428 {
1429 /* block present in image file */
1430 uint64_t u64Offset = ((uint64_t)pImage->paBlocks[uBlock] << pImage->uShiftIndex2Offset)
1431 + (pImage->offStartData + pImage->offStartBlockData + offRead);
1432 int rc = RTFileSeek(pImage->File, u64Offset, RTFILE_SEEK_BEGIN, NULL);
1433 if (VBOX_SUCCESS(rc))
1434 rc = RTFileRead(pImage->File, pvBuf, cbToRead, NULL);
1435 if (VBOX_FAILURE(rc))
1436 Log(("vdiReadInBlock: rc=%Vrc filename=\"%s\" uBlock=%u offRead=%u cbToRead=%u u64Offset=%llu\n",
1437 rc, pImage->szFilename, uBlock, offRead, cbToRead, u64Offset));
1438 return rc;
1439 }
1440
1441 /* Returns zeroes for both free and zero block types. */
1442 memset(pvBuf, 0, cbToRead);
1443 return VINF_SUCCESS;
1444}
1445
1446/**
1447 * Read data from virtual HDD.
1448 *
1449 * @returns VBox status code.
1450 * @param pDisk Pointer to VDI HDD container.
1451 * @param offStart Offset of first reading byte from start of disk.
1452 * @param pvBuf Pointer to buffer for reading data.
1453 * @param cbToRead Number of bytes to read.
1454 */
1455IDER3DECL(int) VDIDiskRead(PVDIDISK pDisk, uint64_t offStart, void *pvBuf, unsigned cbToRead)
1456{
1457 /* sanity check */
1458 Assert(pDisk);
1459 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
1460
1461 PVDIIMAGEDESC pImage = pDisk->pLast;
1462 Assert(pImage);
1463
1464 /* Check params. */
1465 if ( offStart + cbToRead > getImageDiskSize(&pImage->Header)
1466 || cbToRead == 0)
1467 {
1468 AssertMsgFailed(("offStart=%llu cbToRead=%u\n", offStart, cbToRead));
1469 return VERR_INVALID_PARAMETER;
1470 }
1471
1472 /* Calculate starting block number and offset inside it. */
1473 unsigned uBlock = (unsigned)(offStart >> pImage->uShiftOffset2Index);
1474 unsigned offRead = (unsigned)offStart & pImage->uBlockMask;
1475
1476 /* Save block size here for speed optimization. */
1477 unsigned cbBlock = getImageBlockSize(&pImage->Header);
1478
1479 /* loop through blocks */
1480 int rc;
1481 for (;;)
1482 {
1483 unsigned to_read;
1484 if ((offRead + cbToRead) <= cbBlock)
1485 to_read = cbToRead;
1486 else
1487 to_read = cbBlock - offRead;
1488
1489 if (pDisk->cImages > 1)
1490 {
1491 /* Differencing images are used, handle them. */
1492 pImage = pDisk->pLast;
1493
1494 /* Search for image with allocated block. */
1495 while (pImage->paBlocks[uBlock] == VDI_IMAGE_BLOCK_FREE)
1496 {
1497 pImage = pImage->pPrev;
1498 if (!pImage)
1499 {
1500 /* Block is not allocated in all images of chain. */
1501 pImage = pDisk->pLast;
1502 break;
1503 }
1504 }
1505 }
1506
1507 rc = vdiReadInBlock(pImage, uBlock, offRead, to_read, pvBuf);
1508
1509 cbToRead -= to_read;
1510 if ( cbToRead == 0
1511 || VBOX_FAILURE(rc))
1512 break;
1513
1514 /* goto next block */
1515 uBlock++;
1516 offRead = 0;
1517 pvBuf = (char *)pvBuf + to_read;
1518 }
1519
1520 return rc;
1521}
1522
1523/**
1524 * internal: fill the whole block with zeroes.
1525 *
1526 * note: block id must be valid, block must be already allocated in file.
1527 * note: if pDisk is NULL, the default buffer size is used
1528 */
1529static int vdiFillBlockByZeroes(PVDIDISK pDisk, PVDIIMAGEDESC pImage, unsigned uBlock)
1530{
1531 int rc;
1532
1533 /* seek to start of block in file. */
1534 uint64_t u64Offset = ((uint64_t)pImage->paBlocks[uBlock] << pImage->uShiftIndex2Offset)
1535 + (pImage->offStartData + pImage->offStartBlockData);
1536 rc = RTFileSeek(pImage->File, u64Offset, RTFILE_SEEK_BEGIN, NULL);
1537 if (VBOX_FAILURE(rc))
1538 {
1539 Log(("vdiFillBlockByZeroes: seek rc=%Vrc filename=\"%s\" uBlock=%u u64Offset=%llu\n",
1540 rc, pImage->szFilename, uBlock, u64Offset));
1541 return rc;
1542 }
1543
1544 /* alloc tmp zero-filled buffer */
1545 void *pvBuf = RTMemTmpAllocZ(pDisk ? pDisk->cbBuf : VDIDISK_DEFAULT_BUFFER_SIZE);
1546 if (!pvBuf)
1547 return VERR_NO_MEMORY;
1548
1549 unsigned cbFill = getImageBlockSize(&pImage->Header);
1550
1551 /* do loop, because buffer size may be less then block size */
1552 while (cbFill > 0)
1553 {
1554 unsigned to_fill = RT_MIN(cbFill, pDisk ? pDisk->cbBuf : VDIDISK_DEFAULT_BUFFER_SIZE);
1555 rc = RTFileWrite(pImage->File, pvBuf, to_fill, NULL);
1556 if (VBOX_FAILURE(rc))
1557 {
1558 Log(("vdiFillBlockByZeroes: write rc=%Vrc filename=\"%s\" uBlock=%u u64Offset=%llu cbFill=%u to_fill=%u\n",
1559 rc, pImage->szFilename, uBlock, u64Offset, cbFill, to_fill));
1560 break;
1561 }
1562
1563 cbFill -= to_fill;
1564 }
1565
1566 RTMemTmpFree(pvBuf);
1567 return rc;
1568}
1569
1570/**
1571 * internal: write data inside image block.
1572 *
1573 * note: uBlock must be valid, written data must not overlap block bounds.
1574 */
1575static int vdiWriteInBlock(PVDIDISK pDisk, PVDIIMAGEDESC pImage, unsigned uBlock, unsigned offWrite, unsigned cbToWrite, const void *pvBuf)
1576{
1577 int rc;
1578
1579 /* Check if we can write into file. */
1580 if (pImage->fReadOnly)
1581 {
1582 Log(("vdiWriteInBlock: failed, image \"%s\" is read-only!\n", pImage->szFilename));
1583 return VERR_WRITE_PROTECT;
1584 }
1585
1586 vdiSetModifiedFlag(pImage);
1587
1588 if (!IS_VDI_IMAGE_BLOCK_ALLOCATED(pImage->paBlocks[uBlock]))
1589 {
1590 /* need to allocate a new block in image file */
1591
1592 /* expand file by one block */
1593 uint64_t u64Size = (((uint64_t)(getImageBlocksAllocated(&pImage->Header) + 1)) << pImage->uShiftIndex2Offset)
1594 + pImage->offStartData;
1595 rc = RTFileSetSize(pImage->File, u64Size);
1596 if (VBOX_FAILURE(rc))
1597 {
1598 Log(("vdiWriteInBlock: set size rc=%Vrc filename=\"%s\" uBlock=%u u64Size=%llu\n",
1599 rc, pImage->szFilename, uBlock, u64Size));
1600 return rc;
1601 }
1602
1603 unsigned cBlocksAllocated = getImageBlocksAllocated(&pImage->Header);
1604 pImage->paBlocks[uBlock] = cBlocksAllocated;
1605 setImageBlocksAllocated(&pImage->Header, cBlocksAllocated + 1);
1606
1607 if ( pImage->fFlags & VDI_IMAGE_FLAGS_ZERO_EXPAND
1608 || pImage->paBlocks[uBlock] == VDI_IMAGE_BLOCK_ZERO)
1609 {
1610 /* Fill newly allocated block by zeroes. */
1611
1612 if (offWrite || cbToWrite != getImageBlockSize(&pImage->Header))
1613 {
1614 rc = vdiFillBlockByZeroes(pDisk, pImage, uBlock);
1615 if (VBOX_FAILURE(rc))
1616 return rc;
1617 }
1618 }
1619
1620 rc = vdiUpdateBlockInfo(pImage, uBlock);
1621 if (VBOX_FAILURE(rc))
1622 return rc;
1623 }
1624
1625 /* Now block present in image file, write data inside it. */
1626 uint64_t u64Offset = ((uint64_t)pImage->paBlocks[uBlock] << pImage->uShiftIndex2Offset)
1627 + (pImage->offStartData + pImage->offStartBlockData + offWrite);
1628 rc = RTFileSeek(pImage->File, u64Offset, RTFILE_SEEK_BEGIN, NULL);
1629 if (VBOX_SUCCESS(rc))
1630 {
1631 rc = RTFileWrite(pImage->File, pvBuf, cbToWrite, NULL);
1632 if (VBOX_FAILURE(rc))
1633 Log(("vdiWriteInBlock: write rc=%Vrc filename=\"%s\" uBlock=%u offWrite=%u u64Offset=%llu cbToWrite=%u\n",
1634 rc, pImage->szFilename, uBlock, offWrite, u64Offset, cbToWrite));
1635 }
1636 else
1637 Log(("vdiWriteInBlock: seek rc=%Vrc filename=\"%s\" uBlock=%u offWrite=%u u64Offset=%llu\n",
1638 rc, pImage->szFilename, uBlock, offWrite, u64Offset));
1639
1640 return rc;
1641}
1642
1643/**
1644 * internal: copy data block from one (parent) image to last image.
1645 */
1646static int vdiCopyBlock(PVDIDISK pDisk, PVDIIMAGEDESC pImage, unsigned uBlock)
1647{
1648 Assert(pImage != pDisk->pLast);
1649
1650 if (pImage->paBlocks[uBlock] == VDI_IMAGE_BLOCK_ZERO)
1651 {
1652 /*
1653 * if src block is zero, set dst block to zero too.
1654 */
1655 pDisk->pLast->paBlocks[uBlock] = VDI_IMAGE_BLOCK_ZERO;
1656 return VINF_SUCCESS;
1657 }
1658
1659 /* alloc tmp buffer */
1660 void *pvBuf = RTMemTmpAlloc(pDisk->cbBuf);
1661 if (!pvBuf)
1662 return VERR_NO_MEMORY;
1663
1664 int rc = VINF_SUCCESS;
1665
1666 unsigned cbCopy = getImageBlockSize(&pImage->Header);
1667 unsigned offCopy = 0;
1668
1669 /* do loop, because buffer size may be less then block size */
1670 while (cbCopy > 0)
1671 {
1672 unsigned to_copy = RT_MIN(cbCopy, pDisk->cbBuf);
1673 rc = vdiReadInBlock(pImage, uBlock, offCopy, to_copy, pvBuf);
1674 if (VBOX_FAILURE(rc))
1675 break;
1676
1677 rc = vdiWriteInBlock(pDisk, pDisk->pLast, uBlock, offCopy, to_copy, pvBuf);
1678 if (VBOX_FAILURE(rc))
1679 break;
1680
1681 cbCopy -= to_copy;
1682 offCopy += to_copy;
1683 }
1684
1685 RTMemTmpFree(pvBuf);
1686 return rc;
1687}
1688
1689/**
1690 * Write data to virtual HDD.
1691 *
1692 * @returns VBox status code.
1693 * @param pDisk Pointer to VDI HDD container.
1694 * @param offStart Offset of first writing byte from start of HDD.
1695 * @param pvBuf Pointer to buffer of writing data.
1696 * @param cbToWrite Number of bytes to write.
1697 */
1698IDER3DECL(int) VDIDiskWrite(PVDIDISK pDisk, uint64_t offStart, const void *pvBuf, unsigned cbToWrite)
1699{
1700 /* sanity check */
1701 Assert(pDisk);
1702 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
1703
1704 PVDIIMAGEDESC pImage = pDisk->pLast;
1705 Assert(pImage);
1706
1707 /* Check params. */
1708 if ( offStart + cbToWrite > getImageDiskSize(&pImage->Header)
1709 || cbToWrite == 0)
1710 {
1711 AssertMsgFailed(("offStart=%llu cbToWrite=%u\n", offStart, cbToWrite));
1712 return VERR_INVALID_PARAMETER;
1713 }
1714
1715 /* Calculate starting block number and offset inside it. */
1716 unsigned uBlock = (unsigned)(offStart >> pImage->uShiftOffset2Index);
1717 unsigned offWrite = (unsigned)offStart & pImage->uBlockMask;
1718 unsigned cbBlock = getImageBlockSize(&pImage->Header);
1719
1720 /* loop through blocks */
1721 int rc;
1722 for (;;)
1723 {
1724 unsigned to_write;
1725 if (offWrite + cbToWrite <= cbBlock)
1726 to_write = cbToWrite;
1727 else
1728 to_write = cbBlock - offWrite;
1729
1730 if (pDisk->cImages > 1)
1731 {
1732 /* Differencing images are used, handle them. */
1733
1734 /* Search for image with allocated block. */
1735 while (pImage->paBlocks[uBlock] == VDI_IMAGE_BLOCK_FREE)
1736 {
1737 pImage = pImage->pPrev;
1738 if (!pImage)
1739 {
1740 /* Block is not allocated in all images of chain. */
1741 pImage = pDisk->pLast;
1742 break;
1743 }
1744 }
1745
1746 if (pImage != pDisk->pLast)
1747 {
1748 /* One of parent image has a block data, copy it into last image. */
1749 rc = vdiCopyBlock(pDisk, pImage, uBlock);
1750 if (VBOX_FAILURE(rc))
1751 break;
1752 pImage = pDisk->pLast;
1753 }
1754 }
1755
1756 /* Actually write the data into block. */
1757 rc = vdiWriteInBlock(pDisk, pImage, uBlock, offWrite, to_write, pvBuf);
1758
1759 cbToWrite -= to_write;
1760 if ( cbToWrite == 0
1761 || VBOX_FAILURE(rc))
1762 break;
1763
1764 /* goto next block */
1765 uBlock++;
1766 offWrite = 0;
1767 pvBuf = (char *)pvBuf + to_write;
1768 }
1769
1770 return rc;
1771}
1772
1773/**
1774 * internal: commit one image to another, no changes to header, just
1775 * plain copy operation. Blocks that are not allocated in the source
1776 * image (i.e. inherited by its parent(s)) are not merged.
1777 *
1778 * @param pImageFrom source image
1779 * @param pImageTo target image (will receive all the modifications)
1780 * @param fParentToChild true if the source image is parent of the target one,
1781 * false of the target image is the parent of the source.
1782 * @param pfnProgress progress callback (NULL if not to be used)
1783 * @param pvUser user argument for the progress callback
1784 *
1785 * @note the target image has to be opened read/write
1786 * @note this method does not check whether merging is possible!
1787 */
1788static int vdiMergeImages(PVDIIMAGEDESC pImageFrom, PVDIIMAGEDESC pImageTo, bool fParentToChild,
1789 PFNVMPROGRESS pfnProgress, void *pvUser)
1790{
1791 Assert(pImageFrom);
1792 Assert(pImageTo);
1793
1794 Log(("vdiMergeImages: merging from image \"%s\" to image \"%s\" (fParentToChild=%d)\n",
1795 pImageFrom->szFilename, pImageTo->szFilename, fParentToChild));
1796
1797 /* alloc tmp buffer */
1798 void *pvBuf = RTMemTmpAlloc(VDIDISK_DEFAULT_BUFFER_SIZE);
1799 if (!pvBuf)
1800 return VERR_NO_MEMORY;
1801
1802 int rc = VINF_SUCCESS;
1803
1804 if (!fParentToChild)
1805 {
1806 /*
1807 * Commit the child image to the parent image.
1808 * Child is the source (from), parent is the target (to).
1809 */
1810
1811 unsigned cBlocks = getImageBlocks(&pImageFrom->Header);
1812
1813 for (unsigned uBlock = 0; uBlock < cBlocks; uBlock++)
1814 {
1815 /* only process blocks that are allocated in the source image */
1816 if (pImageFrom->paBlocks[uBlock] != VDI_IMAGE_BLOCK_FREE)
1817 {
1818 /* Found used block in source image, commit it. */
1819 if ( pImageFrom->paBlocks[uBlock] == VDI_IMAGE_BLOCK_ZERO
1820 && !IS_VDI_IMAGE_BLOCK_ALLOCATED(pImageTo->paBlocks[uBlock]))
1821 {
1822 /* Block is zero in the source image and not allocated in the target image. */
1823 pImageTo->paBlocks[uBlock] = VDI_IMAGE_BLOCK_ZERO;
1824 vdiSetModifiedFlag(pImageTo);
1825 }
1826 else
1827 {
1828 /* Block is not zero / allocated in source image. */
1829 unsigned cbCommit = getImageBlockSize(&pImageFrom->Header);
1830 unsigned offCommit = 0;
1831
1832 /* do loop, because buffer size may be less then block size */
1833 while (cbCommit > 0)
1834 {
1835 unsigned cbToCopy = RT_MIN(cbCommit, VDIDISK_DEFAULT_BUFFER_SIZE);
1836
1837 rc = vdiReadInBlock(pImageFrom, uBlock, offCommit, cbToCopy, pvBuf);
1838 if (VBOX_FAILURE(rc))
1839 break;
1840
1841 rc = vdiWriteInBlock(NULL, pImageTo, uBlock, offCommit, cbToCopy, pvBuf);
1842 if (VBOX_FAILURE(rc))
1843 break;
1844
1845 cbCommit -= cbToCopy;
1846 offCommit += cbToCopy;
1847 }
1848 if (VBOX_FAILURE(rc))
1849 break;
1850 }
1851 }
1852
1853 if (pfnProgress)
1854 {
1855 pfnProgress(NULL /* WARNING! pVM=NULL */,
1856 (uBlock * 100) / cBlocks,
1857 pvUser);
1858 /* Note: commiting is non breakable operation, skipping rc here. */
1859 }
1860 }
1861 }
1862 else
1863 {
1864 /*
1865 * Commit the parent image to the child image.
1866 * Parent is the source (from), child is the target (to).
1867 */
1868
1869 unsigned cBlocks = getImageBlocks(&pImageFrom->Header);
1870
1871 for (unsigned uBlock = 0; uBlock < cBlocks; uBlock++)
1872 {
1873 /*
1874 * only process blocks that are allocated or zero in the source image
1875 * and NEITHER allocated NOR zero in the target image
1876 */
1877 if (pImageFrom->paBlocks[uBlock] != VDI_IMAGE_BLOCK_FREE &&
1878 pImageTo->paBlocks[uBlock] == VDI_IMAGE_BLOCK_FREE)
1879 {
1880 /* Found used block in source image (but unused in target), commit it. */
1881 if ( pImageFrom->paBlocks[uBlock] == VDI_IMAGE_BLOCK_ZERO)
1882 {
1883 /* Block is zero in the source image and not allocated in the target image. */
1884 pImageTo->paBlocks[uBlock] = VDI_IMAGE_BLOCK_ZERO;
1885 vdiSetModifiedFlag(pImageTo);
1886 }
1887 else
1888 {
1889 /* Block is not zero / allocated in source image. */
1890 unsigned cbCommit = getImageBlockSize(&pImageFrom->Header);
1891 unsigned offCommit = 0;
1892
1893 /* do loop, because buffer size may be less then block size */
1894 while (cbCommit > 0)
1895 {
1896 unsigned cbToCopy = RT_MIN(cbCommit, VDIDISK_DEFAULT_BUFFER_SIZE);
1897
1898 rc = vdiReadInBlock(pImageFrom, uBlock, offCommit, cbToCopy, pvBuf);
1899 if (VBOX_FAILURE(rc))
1900 break;
1901
1902 rc = vdiWriteInBlock(NULL, pImageTo, uBlock, offCommit, cbToCopy, pvBuf);
1903 if (VBOX_FAILURE(rc))
1904 break;
1905
1906 cbCommit -= cbToCopy;
1907 offCommit += cbToCopy;
1908 }
1909 if (VBOX_FAILURE(rc))
1910 break;
1911 }
1912 }
1913
1914 if (pfnProgress)
1915 {
1916 pfnProgress(NULL /* WARNING! pVM=NULL */,
1917 (uBlock * 100) / cBlocks,
1918 pvUser);
1919 /* Note: commiting is non breakable operation, skipping rc here. */
1920 }
1921 }
1922 }
1923
1924 RTMemTmpFree(pvBuf);
1925 return rc;
1926}
1927
1928/**
1929 * internal: commit last image(s) to selected previous image.
1930 * note: all images accessed across this call must be opened in R/W mode.
1931 * @remark Only used by tstVDI.
1932 */
1933static int vdiCommitToImage(PVDIDISK pDisk, PVDIIMAGEDESC pDstImage,
1934 PFNVMPROGRESS pfnProgress, void *pvUser)
1935{
1936 /* sanity check */
1937 Assert(pDisk);
1938 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
1939 Assert(pDstImage);
1940
1941 PVDIIMAGEDESC pImage = pDisk->pLast;
1942 Assert(pImage);
1943 Log(("vdiCommitToImage: commiting from image \"%s\" to image \"%s\"\n",
1944 pImage->szFilename, pDstImage->szFilename));
1945 if (pDstImage == pImage)
1946 {
1947 Log(("vdiCommitToImage: attempt to commit to the same image!\n"));
1948 return VERR_VDI_NO_DIFF_IMAGES;
1949 }
1950
1951 /* Scan images for pDstImage. */
1952 while (pImage && pImage != pDstImage)
1953 pImage = pImage->pPrev;
1954 if (!pImage)
1955 {
1956 AssertMsgFailed(("Invalid arguments: pDstImage is not in images chain\n"));
1957 return VERR_INVALID_PARAMETER;
1958 }
1959 pImage = pDisk->pLast;
1960
1961 /* alloc tmp buffer */
1962 void *pvBuf = RTMemTmpAlloc(pDisk->cbBuf);
1963 if (!pvBuf)
1964 return VERR_NO_MEMORY;
1965
1966 int rc = VINF_SUCCESS;
1967 unsigned cBlocks = getImageBlocks(&pImage->Header);
1968
1969 for (unsigned uBlock = 0; uBlock < cBlocks; uBlock++)
1970 {
1971 pImage = pDisk->pLast;
1972
1973 /* Find allocated block to commit. */
1974 while ( pImage->paBlocks[uBlock] == VDI_IMAGE_BLOCK_FREE
1975 && pImage != pDstImage)
1976 pImage = pImage->pPrev;
1977
1978 if (pImage != pDstImage)
1979 {
1980 /* Found used block in diff image (pImage), commit it. */
1981 if ( pImage->paBlocks[uBlock] == VDI_IMAGE_BLOCK_ZERO
1982 && !IS_VDI_IMAGE_BLOCK_ALLOCATED(pDstImage->paBlocks[uBlock]))
1983 {
1984 /* Block is zero in difference image and not allocated in primary image. */
1985 pDstImage->paBlocks[uBlock] = VDI_IMAGE_BLOCK_ZERO;
1986 vdiSetModifiedFlag(pDstImage);
1987 }
1988 else
1989 {
1990 /* Block is not zero / allocated in primary image. */
1991 unsigned cbCommit = getImageBlockSize(&pImage->Header);
1992 unsigned offCommit = 0;
1993
1994 /* do loop, because buffer size may be less then block size */
1995 while (cbCommit > 0)
1996 {
1997 unsigned cbToCopy = RT_MIN(cbCommit, pDisk->cbBuf);
1998
1999 rc = vdiReadInBlock(pImage, uBlock, offCommit, cbToCopy, pvBuf);
2000 if (VBOX_FAILURE(rc))
2001 break;
2002
2003 rc = vdiWriteInBlock(pDisk, pDstImage, uBlock, offCommit, cbToCopy, pvBuf);
2004 if (VBOX_FAILURE(rc))
2005 break;
2006
2007 cbCommit -= cbToCopy;
2008 offCommit += cbToCopy;
2009 }
2010 if (VBOX_FAILURE(rc))
2011 break;
2012 }
2013 pImage->paBlocks[uBlock] = VDI_IMAGE_BLOCK_FREE;
2014 }
2015
2016 if (pfnProgress)
2017 {
2018 pfnProgress(NULL /* WARNING! pVM=NULL */,
2019 (uBlock * 100) / cBlocks,
2020 pvUser);
2021 /* Note: commiting is non breakable operation, skipping rc here. */
2022 }
2023 }
2024
2025 RTMemTmpFree(pvBuf);
2026
2027 /* Go forward and update linkage information. */
2028 for (pImage = pDstImage; pImage; pImage = pImage->pNext)
2029 {
2030 /* generate new last-modified uuid. */
2031 RTUuidCreate(getImageModificationUUID(&pImage->Header));
2032
2033 /* fix up linkage. */
2034 if (pImage != pDstImage)
2035 *getImageParentModificationUUID(&pImage->Header) = *getImageModificationUUID(&pImage->pPrev->Header);
2036
2037 /* reset modified flag. */
2038 pImage->fModified = 0;
2039 }
2040
2041 /* Process committed images - truncate them. */
2042 for (pImage = pDisk->pLast; pImage != pDstImage; pImage = pImage->pPrev)
2043 {
2044 /* note: can't understand how to do error works here? */
2045
2046 setImageBlocksAllocated(&pImage->Header, 0);
2047
2048 /* Truncate file. */
2049 int rc2 = RTFileSetSize(pImage->File, pImage->offStartData);
2050 if (VBOX_FAILURE(rc2))
2051 {
2052 rc = rc2;
2053 Log(("vdiCommitToImage: set size (truncate) rc=%Vrc filename=\"%s\"\n",
2054 rc, pImage->szFilename));
2055 }
2056
2057 /* Save header and blocks array. */
2058 rc2 = vdiUpdateBlocks(pImage);
2059 if (VBOX_FAILURE(rc2))
2060 {
2061 rc = rc2;
2062 Log(("vdiCommitToImage: update blocks and header rc=%Vrc filename=\"%s\"\n",
2063 rc, pImage->szFilename));
2064 }
2065 }
2066
2067 if (pfnProgress)
2068 {
2069 pfnProgress(NULL /* WARNING! pVM=NULL */, 100, pvUser);
2070 /* Note: commiting is non breakable operation, skipping rc here. */
2071 }
2072
2073 Log(("vdiCommitToImage: done, rc=%Vrc\n", rc));
2074
2075 return rc;
2076}
2077
2078/**
2079 * Checks if image is available and not broken, returns some useful image parameters if requested.
2080 *
2081 * @returns VBox status code.
2082 * @param pszFilename Name of the image file to check.
2083 * @param puVersion Where to store the version of image. NULL is ok.
2084 * @param penmType Where to store the type of image. NULL is ok.
2085 * @param pcbSize Where to store the size of image in bytes. NULL is ok.
2086 * @param pUuid Where to store the uuid of image creation. NULL is ok.
2087 * @param pParentUuid Where to store the UUID of the parent image. NULL is ok.
2088 * @param pszComment Where to store the comment string of image. NULL is ok.
2089 * @param cbComment The size of pszComment buffer. 0 is ok.
2090 */
2091IDER3DECL(int) VDICheckImage(const char *pszFilename, unsigned *puVersion, PVDIIMAGETYPE penmType,
2092 uint64_t *pcbSize, PRTUUID pUuid, PRTUUID pParentUuid,
2093 char *pszComment, unsigned cbComment)
2094{
2095 LogFlow(("VDICheckImage:\n"));
2096
2097 /* Check arguments. */
2098 if ( !pszFilename
2099 || *pszFilename == '\0')
2100 {
2101 AssertMsgFailed(("Invalid arguments: pszFilename=%p\n", pszFilename));
2102 return VERR_INVALID_PARAMETER;
2103 }
2104
2105 PVDIIMAGEDESC pImage;
2106 int rc = vdiOpenImage(&pImage, pszFilename, VDI_OPEN_FLAGS_READONLY, NULL);
2107 if (VBOX_SUCCESS(rc))
2108 {
2109 Log(("VDICheckImage: filename=\"%s\" version=%08X type=%X cbDisk=%llu uuid={%Vuuid}\n",
2110 pszFilename,
2111 pImage->PreHeader.u32Version,
2112 getImageType(&pImage->Header),
2113 getImageDiskSize(&pImage->Header),
2114 getImageCreationUUID(&pImage->Header)));
2115
2116 if ( pszComment
2117 && cbComment > 0)
2118 {
2119 char *pszTmp = getImageComment(&pImage->Header);
2120 unsigned cb = strlen(pszTmp);
2121 if (cbComment > cb)
2122 memcpy(pszComment, pszTmp, cb + 1);
2123 else
2124 rc = VERR_BUFFER_OVERFLOW;
2125 }
2126 if (VBOX_SUCCESS(rc))
2127 {
2128 if (puVersion)
2129 *puVersion = pImage->PreHeader.u32Version;
2130 if (penmType)
2131 *penmType = getImageType(&pImage->Header);
2132 if (pcbSize)
2133 *pcbSize = getImageDiskSize(&pImage->Header);
2134 if (pUuid)
2135 *pUuid = *getImageCreationUUID(&pImage->Header);
2136 if (pParentUuid)
2137 *pParentUuid = *getImageParentUUID(&pImage->Header);
2138 }
2139 vdiCloseImage(pImage);
2140 }
2141
2142 LogFlow(("VDICheckImage: returns %Vrc\n", rc));
2143 return rc;
2144}
2145
2146/**
2147 * Changes an image's comment string.
2148 *
2149 * @returns VBox status code.
2150 * @param pszFilename Name of the image file to operate on.
2151 * @param pszComment New comment string (UTF-8). NULL is allowed to reset the comment.
2152 */
2153IDER3DECL(int) VDISetImageComment(const char *pszFilename, const char *pszComment)
2154{
2155 LogFlow(("VDISetImageComment:\n"));
2156
2157 /*
2158 * Validate arguments.
2159 */
2160 if ( !pszFilename
2161 || *pszFilename == '\0')
2162 {
2163 AssertMsgFailed(("Invalid arguments: pszFilename=%p\n", pszFilename));
2164 return VERR_INVALID_PARAMETER;
2165 }
2166
2167 const size_t cchComment = pszComment ? strlen(pszComment) : 0;
2168 if (cchComment >= VDI_IMAGE_COMMENT_SIZE)
2169 {
2170 Log(("VDISetImageComment: pszComment is too long, %d bytes!\n", cchComment));
2171 return VERR_VDI_COMMENT_TOO_LONG;
2172 }
2173
2174 /*
2175 * Open the image for updating.
2176 */
2177 PVDIIMAGEDESC pImage;
2178 int rc = vdiOpenImage(&pImage, pszFilename, VDI_OPEN_FLAGS_NORMAL, NULL);
2179 if (VBOX_FAILURE(rc))
2180 {
2181 Log(("VDISetImageComment: vdiOpenImage rc=%Vrc filename=\"%s\"!\n", rc, pszFilename));
2182 return rc;
2183 }
2184 if (!pImage->fReadOnly)
2185 {
2186 /* we don't support old style images */
2187 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 1)
2188 {
2189 /*
2190 * Update the comment field, making sure to zero out all of the previous comment.
2191 */
2192 memset(pImage->Header.u.v1.szComment, '\0', VDI_IMAGE_COMMENT_SIZE);
2193 memcpy(pImage->Header.u.v1.szComment, pszComment, cchComment);
2194
2195 /* write out new the header */
2196 rc = vdiUpdateHeader(pImage);
2197 AssertMsgRC(rc, ("vdiUpdateHeader() failed, filename=\"%s\", rc=%Vrc\n",
2198 pImage->szFilename, rc));
2199 }
2200 else
2201 {
2202 Log(("VDISetImageComment: Unsupported version!\n"));
2203 rc = VERR_VDI_UNSUPPORTED_VERSION;
2204 }
2205 }
2206 else
2207 {
2208 Log(("VDISetImageComment: image \"%s\" is opened as read-only!\n", pszFilename));
2209 rc = VERR_VDI_IMAGE_READ_ONLY;
2210 }
2211
2212 vdiCloseImage(pImage);
2213 return rc;
2214}
2215
2216/**
2217 * Creates a new base image file.
2218 *
2219 * @returns VBox status code.
2220 * @param pszFilename Name of the creating image file.
2221 * @param enmType Image type, only base image types are acceptable.
2222 * @param cbSize Image size in bytes.
2223 * @param pszComment Pointer to image comment. NULL is ok.
2224 * @param pfnProgress Progress callback. Optional.
2225 * @param pvUser User argument for the progress callback.
2226 */
2227IDER3DECL(int) VDICreateBaseImage(const char *pszFilename, VDIIMAGETYPE enmType, uint64_t cbSize,
2228 const char *pszComment, PFNVMPROGRESS pfnProgress, void *pvUser)
2229{
2230 LogFlow(("VDICreateBaseImage:\n"));
2231
2232 /* Check arguments. */
2233 if ( !pszFilename
2234 || *pszFilename == '\0'
2235 || (enmType != VDI_IMAGE_TYPE_NORMAL && enmType != VDI_IMAGE_TYPE_FIXED)
2236 || cbSize < VDI_IMAGE_DEFAULT_BLOCK_SIZE)
2237 {
2238 AssertMsgFailed(("Invalid arguments: pszFilename=%p enmType=%x cbSize=%llu\n",
2239 pszFilename, enmType, cbSize));
2240 return VERR_INVALID_PARAMETER;
2241 }
2242
2243 int rc = vdiCreateImage(pszFilename, enmType, VDI_IMAGE_FLAGS_DEFAULT, cbSize, pszComment, NULL,
2244 pfnProgress, pvUser);
2245 LogFlow(("VDICreateBaseImage: returns %Vrc for filename=\"%s\"\n", rc, pszFilename));
2246 return rc;
2247}
2248
2249/**
2250 * Creates a differencing dynamically growing image file for specified parent image.
2251 *
2252 * @returns VBox status code.
2253 * @param pszFilename Name of the creating differencing image file.
2254 * @param pszParent Name of the parent image file. May be base or diff image type.
2255 * @param pszComment Pointer to image comment. NULL is ok.
2256 * @param pfnProgress Progress callback. Optional.
2257 * @param pvUser User argument for the progress callback.
2258 */
2259IDER3DECL(int) VDICreateDifferenceImage(const char *pszFilename, const char *pszParent,
2260 const char *pszComment, PFNVMPROGRESS pfnProgress,
2261 void *pvUser)
2262{
2263 LogFlow(("VDICreateDifferenceImage:\n"));
2264
2265 /* Check arguments. */
2266 if ( !pszFilename
2267 || *pszFilename == '\0'
2268 || !pszParent
2269 || *pszParent == '\0')
2270 {
2271 AssertMsgFailed(("Invalid arguments: pszFilename=%p pszParent=%p\n",
2272 pszFilename, pszParent));
2273 return VERR_INVALID_PARAMETER;
2274 }
2275
2276 PVDIIMAGEDESC pParent;
2277 int rc = vdiOpenImage(&pParent, pszParent, VDI_OPEN_FLAGS_READONLY, NULL);
2278 if (VBOX_SUCCESS(rc))
2279 {
2280 rc = vdiCreateImage(pszFilename, VDI_IMAGE_TYPE_DIFF, VDI_IMAGE_FLAGS_DEFAULT,
2281 getImageDiskSize(&pParent->Header), pszComment, pParent,
2282 pfnProgress, pvUser);
2283 vdiCloseImage(pParent);
2284 }
2285 LogFlow(("VDICreateDifferenceImage: returns %Vrc for filename=\"%s\"\n", rc, pszFilename));
2286 return rc;
2287}
2288
2289/**
2290 * Deletes an image. Only valid image files can be deleted by this call.
2291 *
2292 * @returns VBox status code.
2293 * @param pszFilename Name of the image file to check.
2294 */
2295IDER3DECL(int) VDIDeleteImage(const char *pszFilename)
2296{
2297 LogFlow(("VDIDeleteImage:\n"));
2298 /* Check arguments. */
2299 if ( !pszFilename
2300 || *pszFilename == '\0')
2301 {
2302 AssertMsgFailed(("Invalid arguments: pszFilename=%p\n", pszFilename));
2303 return VERR_INVALID_PARAMETER;
2304 }
2305
2306 int rc = VDICheckImage(pszFilename, NULL, NULL, NULL, NULL, NULL, NULL, 0);
2307 if (VBOX_SUCCESS(rc))
2308 rc = RTFileDelete(pszFilename);
2309
2310 LogFlow(("VDIDeleteImage: returns %Vrc for filename=\"%s\"\n", rc, pszFilename));
2311 return rc;
2312}
2313
2314/**
2315 * Makes a copy of image file with a new (other) creation uuid.
2316 *
2317 * @returns VBox status code.
2318 * @param pszDstFilename Name of the image file to create.
2319 * @param pszSrcFilename Name of the image file to copy from.
2320 * @param pszComment Pointer to image comment. If NULL specified comment
2321 * will be copied from source image.
2322 * @param pfnProgress Progress callback. Optional.
2323 * @param pvUser User argument for the progress callback.
2324 */
2325IDER3DECL(int) VDICopyImage(const char *pszDstFilename, const char *pszSrcFilename,
2326 const char *pszComment, PFNVMPROGRESS pfnProgress, void *pvUser)
2327{
2328 LogFlow(("VDICopyImage:\n"));
2329
2330 /* Check arguments. */
2331 if ( !pszDstFilename
2332 || *pszDstFilename == '\0'
2333 || !pszSrcFilename
2334 || *pszSrcFilename == '\0')
2335 {
2336 AssertMsgFailed(("Invalid arguments: pszDstFilename=%p pszSrcFilename=%p\n",
2337 pszDstFilename, pszSrcFilename));
2338 return VERR_INVALID_PARAMETER;
2339 }
2340
2341 /* Special check for comment length. */
2342 if ( pszComment
2343 && strlen(pszComment) >= VDI_IMAGE_COMMENT_SIZE)
2344 {
2345 Log(("VDICopyImage: pszComment is too long, cb=%d\n", strlen(pszComment)));
2346 return VERR_VDI_COMMENT_TOO_LONG;
2347 }
2348
2349 PVDIIMAGEDESC pImage;
2350 int rc = vdiOpenImage(&pImage, pszSrcFilename, VDI_OPEN_FLAGS_READONLY, NULL);
2351 if (VBOX_FAILURE(rc))
2352 {
2353 Log(("VDICopyImage: src image \"%s\" open failed rc=%Vrc\n", pszSrcFilename, rc));
2354 return rc;
2355 }
2356
2357 uint64_t cbFile = pImage->offStartData
2358 + ((uint64_t)getImageBlocksAllocated(&pImage->Header) << pImage->uShiftIndex2Offset);
2359
2360 /* create file */
2361 RTFILE File;
2362 rc = RTFileOpen(&File,
2363 pszDstFilename,
2364 RTFILE_O_READWRITE | RTFILE_O_CREATE | RTFILE_O_DENY_ALL);
2365 if (VBOX_SUCCESS(rc))
2366 {
2367 /* lock new image exclusively to close any wrong access by VDI API calls. */
2368 rc = RTFileLock(File, RTFILE_LOCK_WRITE | RTFILE_LOCK_IMMEDIATELY, 0, cbFile);
2369 if (VBOX_SUCCESS(rc))
2370 {
2371 /* Set the size of a new file. */
2372 rc = RTFileSetSize(File, cbFile);
2373 if (VBOX_SUCCESS(rc))
2374 {
2375 /* A dirty trick - use original image data to fill the new image. */
2376 RTFILE oldFileHandle = pImage->File;
2377 pImage->File = File;
2378 pImage->fReadOnly = false;
2379
2380 /* generate a new image creation uuid. */
2381 RTUuidCreate(getImageCreationUUID(&pImage->Header));
2382 /* generate a new image last-modified uuid. */
2383 RTUuidCreate(getImageModificationUUID(&pImage->Header));
2384 /* set image comment, if present. */
2385 if (pszComment)
2386 strncpy(getImageComment(&pImage->Header), pszComment, VDI_IMAGE_COMMENT_SIZE);
2387
2388 /* Write the pre-header to new image. */
2389 rc = RTFileSeek(pImage->File, 0, RTFILE_SEEK_BEGIN, NULL);
2390 if (VBOX_SUCCESS(rc))
2391 rc = RTFileWrite(pImage->File,
2392 &pImage->PreHeader,
2393 sizeof(pImage->PreHeader),
2394 NULL);
2395
2396 /* Write the header and the blocks array to new image. */
2397 if (VBOX_SUCCESS(rc))
2398 rc = vdiUpdateBlocks(pImage);
2399
2400 pImage->File = oldFileHandle;
2401 pImage->fReadOnly = true;
2402
2403 /* Seek to the data start in both images. */
2404 if (VBOX_SUCCESS(rc))
2405 rc = RTFileSeek(pImage->File,
2406 pImage->offStartData,
2407 RTFILE_SEEK_BEGIN,
2408 NULL);
2409 if (VBOX_SUCCESS(rc))
2410 rc = RTFileSeek(File,
2411 pImage->offStartData,
2412 RTFILE_SEEK_BEGIN,
2413 NULL);
2414
2415 if (VBOX_SUCCESS(rc))
2416 {
2417 /* alloc tmp buffer */
2418 void *pvBuf = RTMemTmpAlloc(VDIDISK_DEFAULT_BUFFER_SIZE);
2419 if (pvBuf)
2420 {
2421 /* Main copy loop. */
2422 uint64_t cbData = cbFile - pImage->offStartData;
2423 unsigned cBlocks = (unsigned)(cbData / VDIDISK_DEFAULT_BUFFER_SIZE);
2424 unsigned c = 0;
2425
2426 while (cbData)
2427 {
2428 unsigned cbToCopy = (unsigned)RT_MIN(cbData, VDIDISK_DEFAULT_BUFFER_SIZE);
2429
2430 /* Read. */
2431 rc = RTFileRead(pImage->File, pvBuf, cbToCopy, NULL);
2432 if (VBOX_FAILURE(rc))
2433 break;
2434
2435 /* Write. */
2436 rc = RTFileWrite(File, pvBuf, cbToCopy, NULL);
2437 if (VBOX_FAILURE(rc))
2438 break;
2439
2440 if (pfnProgress)
2441 {
2442 c++;
2443 rc = pfnProgress(NULL /* WARNING! pVM=NULL */,
2444 (c * 100) / cBlocks,
2445 pvUser);
2446 if (VBOX_FAILURE(rc))
2447 break;
2448 }
2449 cbData -= cbToCopy;
2450 }
2451
2452 RTMemTmpFree(pvBuf);
2453 }
2454 else
2455 rc = VERR_NO_MEMORY;
2456 }
2457 }
2458
2459 RTFileUnlock(File, 0, cbFile);
2460 }
2461
2462 RTFileClose(File);
2463
2464 if (VBOX_FAILURE(rc))
2465 RTFileDelete(pszDstFilename);
2466
2467 if (pfnProgress)
2468 pfnProgress(NULL /* WARNING! pVM=NULL */, 100, pvUser);
2469 }
2470
2471 vdiCloseImage(pImage);
2472
2473 LogFlow(("VDICopyImage: returns %Vrc for pszSrcFilename=\"%s\" pszDstFilename=\"%s\"\n",
2474 rc, pszSrcFilename, pszDstFilename));
2475 return rc;
2476}
2477
2478/**
2479 * Shrinks growing image file by removing zeroed data blocks.
2480 *
2481 * @returns VBox status code.
2482 * @param pszFilename Name of the image file to shrink.
2483 * @param pfnProgress Progress callback. Optional.
2484 * @param pvUser User argument for the progress callback.
2485 * @remark Only used by vditool
2486 */
2487IDER3DECL(int) VDIShrinkImage(const char *pszFilename, PFNVMPROGRESS pfnProgress, void *pvUser)
2488{
2489 LogFlow(("VDIShrinkImage:\n"));
2490
2491 /* Check arguments. */
2492 if ( !pszFilename
2493 || *pszFilename == '\0')
2494 {
2495 AssertMsgFailed(("Invalid arguments: pszFilename=%p\n", pszFilename));
2496 return VERR_INVALID_PARAMETER;
2497 }
2498
2499 PVDIIMAGEDESC pImage;
2500 int rc = vdiOpenImage(&pImage, pszFilename, VDI_OPEN_FLAGS_NORMAL, NULL);
2501 if (VBOX_FAILURE(rc))
2502 {
2503 Log(("VDIShrinkImage: vdiOpenImage rc=%Vrc filename=\"%s\"\n", rc, pszFilename));
2504 return rc;
2505 }
2506 if (pImage->fReadOnly)
2507 {
2508 Log(("VDIShrinkImage: image \"%s\" is opened as read-only!\n", pszFilename));
2509 vdiCloseImage(pImage);
2510 return VERR_VDI_IMAGE_READ_ONLY;
2511 }
2512
2513 /* Do debug dump. */
2514 vdiDumpImage(pImage);
2515
2516 /* Working data. */
2517 unsigned cbBlock = getImageBlockSize(&pImage->Header);
2518 unsigned cBlocks = getImageBlocks(&pImage->Header);
2519 unsigned cBlocksAllocated = getImageBlocksAllocated(&pImage->Header);
2520
2521 uint64_t cbFile;
2522 rc = RTFileGetSize(pImage->File, &cbFile);
2523 if (VBOX_FAILURE(rc))
2524 {
2525 Log(("VDIShrinkImage: RTFileGetSize rc=%Vrc for file=\"%s\"\n", rc, pszFilename));
2526 vdiCloseImage(pImage);
2527 return rc;
2528 }
2529
2530 uint64_t cbData = cbFile - pImage->offStartData;
2531 unsigned cBlocksAllocated2 = (unsigned)(cbData >> pImage->uShiftIndex2Offset);
2532 if (cbData != (uint64_t)cBlocksAllocated << pImage->uShiftIndex2Offset)
2533 Log(("VDIShrinkImage: invalid image file length, cbBlock=%u cBlocks=%u cBlocksAllocated=%u cBlocksAllocated2=%u cbData=%llu\n",
2534 cbBlock, cBlocks, cBlocksAllocated, cBlocksAllocated2, cbData));
2535
2536 /* Allocate second blocks array for back resolving. */
2537 PVDIIMAGEBLOCKPOINTER paBlocks2 =
2538 (PVDIIMAGEBLOCKPOINTER)RTMemTmpAlloc(sizeof(VDIIMAGEBLOCKPOINTER) * cBlocks);
2539 if (!paBlocks2)
2540 {
2541 Log(("VDIShrinkImage: failed to allocate paBlocks2 buffer (%u bytes)\n", sizeof(VDIIMAGEBLOCKPOINTER) * cBlocks));
2542 vdiCloseImage(pImage);
2543 return VERR_NO_MEMORY;
2544 }
2545
2546 /* Init second blocks array. */
2547 for (unsigned n = 0; n < cBlocks; n++)
2548 paBlocks2[n] = VDI_IMAGE_BLOCK_FREE;
2549
2550 /* Fill second blocks array, check for allocational errors. */
2551 for (unsigned n = 0; n < cBlocks; n++)
2552 {
2553 if (IS_VDI_IMAGE_BLOCK_ALLOCATED(pImage->paBlocks[n]))
2554 {
2555 unsigned uBlock = pImage->paBlocks[n];
2556 if (uBlock < cBlocksAllocated2)
2557 {
2558 if (paBlocks2[uBlock] == VDI_IMAGE_BLOCK_FREE)
2559 paBlocks2[uBlock] = n;
2560 else
2561 {
2562 Log(("VDIShrinkImage: block n=%u -> uBlock=%u is already in use!\n", n, uBlock));
2563 /* free second link to block. */
2564 pImage->paBlocks[n] = VDI_IMAGE_BLOCK_FREE;
2565 }
2566 }
2567 else
2568 {
2569 Log(("VDIShrinkImage: block n=%u -> uBlock=%u is out of blocks range! (cbBlock=%u cBlocks=%u cBlocksAllocated=%u cBlocksAllocated2=%u cbData=%llu)\n",
2570 n, uBlock, cbBlock, cBlocks, cBlocksAllocated, cBlocksAllocated2, cbData));
2571 /* free link to invalid block. */
2572 pImage->paBlocks[n] = VDI_IMAGE_BLOCK_FREE;
2573 }
2574 }
2575 }
2576
2577 /* Allocate a working buffer for one block. */
2578 void *pvBuf = RTMemTmpAlloc(cbBlock);
2579 if (pvBuf)
2580 {
2581 /* Main voodoo loop, search holes and fill it. */
2582 unsigned uBlockWrite = 0;
2583 for (unsigned uBlock = 0; uBlock < cBlocksAllocated2; uBlock++)
2584 {
2585 if (paBlocks2[uBlock] != VDI_IMAGE_BLOCK_FREE)
2586 {
2587 /* Read the block from file and check for zeroes. */
2588 uint64_t u64Offset = ((uint64_t)uBlock << pImage->uShiftIndex2Offset)
2589 + (pImage->offStartData + pImage->offStartBlockData);
2590 rc = RTFileSeek(pImage->File, u64Offset, RTFILE_SEEK_BEGIN, NULL);
2591 if (VBOX_FAILURE(rc))
2592 {
2593 Log(("VDIShrinkImage: seek rc=%Vrc filename=\"%s\" uBlock=%u cBlocks=%u cBlocksAllocated=%u cBlocksAllocated2=%u cbData=%llu\n",
2594 rc, pImage->szFilename, uBlock, cBlocks, cBlocksAllocated, cBlocksAllocated2, cbData));
2595 break;
2596 }
2597 rc = RTFileRead(pImage->File, pvBuf, cbBlock, NULL);
2598 if (VBOX_FAILURE(rc))
2599 {
2600 Log(("VDIShrinkImage: read rc=%Vrc filename=\"%s\" cbBlock=%u uBlock=%u cBlocks=%u cBlocksAllocated=%u cBlocksAllocated2=%u cbData=%llu\n",
2601 rc, pImage->szFilename, cbBlock, uBlock, cBlocks, cBlocksAllocated, cBlocksAllocated2, cbData));
2602 break;
2603 }
2604
2605 /* Check block for data. */
2606 bool flBlockZeroed = true; /* Block is zeroed flag. */
2607 for (unsigned i = 0; i < (cbBlock >> 2); i++)
2608 if (((uint32_t *)pvBuf)[i] != 0)
2609 {
2610 /* Block is not zeroed! */
2611 flBlockZeroed = false;
2612 break;
2613 }
2614
2615 if (!flBlockZeroed)
2616 {
2617 /* Block has a data, may be it must be moved. */
2618 if (uBlockWrite < uBlock)
2619 {
2620 /* Move the block. */
2621 u64Offset = ((uint64_t)uBlockWrite << pImage->uShiftIndex2Offset)
2622 + (pImage->offStartData + pImage->offStartBlockData);
2623 rc = RTFileSeek(pImage->File, u64Offset, RTFILE_SEEK_BEGIN, NULL);
2624 if (VBOX_FAILURE(rc))
2625 {
2626 Log(("VDIShrinkImage: seek(2) rc=%Vrc filename=\"%s\" uBlockWrite=%u cBlocks=%u cBlocksAllocated=%u cBlocksAllocated2=%u cbData=%llu\n",
2627 rc, pImage->szFilename, uBlockWrite, cBlocks, cBlocksAllocated, cBlocksAllocated2, cbData));
2628 break;
2629 }
2630 rc = RTFileWrite(pImage->File, pvBuf, cbBlock, NULL);
2631 if (VBOX_FAILURE(rc))
2632 {
2633 Log(("VDIShrinkImage: write rc=%Vrc filename=\"%s\" cbBlock=%u uBlockWrite=%u cBlocks=%u cBlocksAllocated=%u cBlocksAllocated2=%u cbData=%llu\n",
2634 rc, pImage->szFilename, cbBlock, uBlockWrite, cBlocks, cBlocksAllocated, cBlocksAllocated2, cbData));
2635 break;
2636 }
2637 }
2638 /* Fix the block pointer. */
2639 pImage->paBlocks[paBlocks2[uBlock]] = uBlockWrite;
2640 uBlockWrite++;
2641 }
2642 else
2643 {
2644 Log(("VDIShrinkImage: found a zeroed block, uBlock=%u\n", uBlock));
2645
2646 /* Fix the block pointer. */
2647 pImage->paBlocks[paBlocks2[uBlock]] = VDI_IMAGE_BLOCK_ZERO;
2648 }
2649 }
2650 else
2651 Log(("VDIShrinkImage: found an unused block, uBlock=%u\n", uBlock));
2652
2653 if (pfnProgress)
2654 {
2655 pfnProgress(NULL /* WARNING! pVM=NULL */,
2656 (uBlock * 100) / cBlocksAllocated2,
2657 pvUser);
2658 /* Shrink is unbreakable operation! */
2659 }
2660 }
2661
2662 RTMemTmpFree(pvBuf);
2663
2664 if ( VBOX_SUCCESS(rc)
2665 && uBlockWrite < cBlocksAllocated2)
2666 {
2667 /* File size must be shrinked. */
2668 Log(("VDIShrinkImage: shrinking file size from %llu to %llu bytes\n",
2669 cbFile,
2670 pImage->offStartData + ((uint64_t)uBlockWrite << pImage->uShiftIndex2Offset)));
2671 rc = RTFileSetSize(pImage->File,
2672 pImage->offStartData + ((uint64_t)uBlockWrite << pImage->uShiftIndex2Offset));
2673 if (VBOX_FAILURE(rc))
2674 Log(("VDIShrinkImage: RTFileSetSize rc=%Vrc\n", rc));
2675 }
2676 cBlocksAllocated2 = uBlockWrite;
2677 }
2678 else
2679 {
2680 Log(("VDIShrinkImage: failed to allocate working buffer (%u bytes)\n", cbBlock));
2681 rc = VERR_NO_MEMORY;
2682 }
2683
2684 /* Save header and blocks array. */
2685 if (VBOX_SUCCESS(rc))
2686 {
2687 setImageBlocksAllocated(&pImage->Header, cBlocksAllocated2);
2688 rc = vdiUpdateBlocks(pImage);
2689 if (pfnProgress)
2690 pfnProgress(NULL /* WARNING! pVM=NULL */, 100, pvUser);
2691 }
2692
2693 /* Do debug dump. */
2694 vdiDumpImage(pImage);
2695
2696 /* Clean up. */
2697 RTMemTmpFree(paBlocks2);
2698 vdiCloseImage(pImage);
2699
2700 LogFlow(("VDIShrinkImage: returns %Vrc for filename=\"%s\"\n", rc, pszFilename));
2701 return rc;
2702}
2703
2704/**
2705 * Converts image file from older VDI formats to current one.
2706 *
2707 * @returns VBox status code.
2708 * @param pszFilename Name of the image file to convert.
2709 * @param pfnProgress Progress callback. Optional.
2710 * @param pvUser User argument for the progress callback.
2711 * @remark Only used by vditool
2712 */
2713IDER3DECL(int) VDIConvertImage(const char *pszFilename, PFNVMPROGRESS pfnProgress, void *pvUser)
2714{
2715 LogFlow(("VDIConvertImage:\n"));
2716
2717 /* Check arguments. */
2718 if ( !pszFilename
2719 || *pszFilename == '\0')
2720 {
2721 AssertMsgFailed(("Invalid arguments: pszFilename=%p\n", pszFilename));
2722 return VERR_INVALID_PARAMETER;
2723 }
2724
2725 PVDIIMAGEDESC pImage;
2726 int rc = vdiOpenImage(&pImage, pszFilename, VDI_OPEN_FLAGS_NORMAL, NULL);
2727 if (VBOX_FAILURE(rc))
2728 {
2729 Log(("VDIConvertImage: vdiOpenImage rc=%Vrc filename=\"%s\"\n", rc, pszFilename));
2730 return rc;
2731 }
2732
2733 VDIHEADER Header = {0};
2734 int off;
2735 uint64_t cbFile;
2736 uint64_t cbData;
2737
2738 if (pImage->fReadOnly)
2739 {
2740 Log(("VDIConvertImage: image \"%s\" is opened as read-only!\n", pszFilename));
2741 rc = VERR_VDI_IMAGE_READ_ONLY;
2742 goto l_conversion_failed;
2743 }
2744
2745 if (pImage->PreHeader.u32Version != 0x00000002)
2746 {
2747 Log(("VDIConvertImage: unsupported version=%08X filename=\"%s\"\n",
2748 pImage->PreHeader.u32Version, pszFilename));
2749 rc = VERR_VDI_UNSUPPORTED_VERSION;
2750 goto l_conversion_failed;
2751 }
2752
2753 /* Build new version header from old one. */
2754 vdiInitHeader(&Header,
2755 getImageType(&pImage->Header),
2756 VDI_IMAGE_FLAGS_DEFAULT, /* Safety issue: Always use default flags. */
2757 getImageComment(&pImage->Header),
2758 getImageDiskSize(&pImage->Header),
2759 getImageBlockSize(&pImage->Header),
2760 0);
2761 setImageBlocksAllocated(&Header, getImageBlocksAllocated(&pImage->Header));
2762 *getImageGeometry(&Header) = *getImageGeometry(&pImage->Header);
2763 setImageTranslation(&Header, getImageTranslation(&pImage->Header));
2764 *getImageCreationUUID(&Header) = *getImageCreationUUID(&pImage->Header);
2765 *getImageModificationUUID(&Header) = *getImageModificationUUID(&pImage->Header);
2766
2767 /* Calc data offset. */
2768 off = getImageDataOffset(&Header) - getImageDataOffset(&pImage->Header);
2769 if (off <= 0)
2770 {
2771 rc = VERR_VDI_INVALID_HEADER;
2772 goto l_conversion_failed;
2773 }
2774
2775 rc = RTFileGetSize(pImage->File, &cbFile);
2776 if (VBOX_FAILURE(rc))
2777 goto l_conversion_failed;
2778
2779 /* Check file size. */
2780 cbData = cbFile - getImageDataOffset(&pImage->Header);
2781 if (cbData != (uint64_t)getImageBlocksAllocated(&pImage->Header) << pImage->uShiftIndex2Offset)
2782 {
2783 AssertMsgFailed(("Invalid file size, broken image?\n"));
2784 rc = VERR_VDI_INVALID_HEADER;
2785 goto l_conversion_failed;
2786 }
2787
2788 /* Expand file. */
2789 rc = RTFileSetSize(pImage->File, cbFile + off);
2790 if (VBOX_FAILURE(rc))
2791 goto l_conversion_failed;
2792
2793 if (cbData > 0)
2794 {
2795 /* Calc current file position to move data from. */
2796 uint64_t offFile;
2797 if (cbData > VDIDISK_DEFAULT_BUFFER_SIZE)
2798 offFile = cbFile - VDIDISK_DEFAULT_BUFFER_SIZE;
2799 else
2800 offFile = getImageDataOffset(&pImage->Header);
2801
2802 unsigned cMoves = (unsigned)(cbData / VDIDISK_DEFAULT_BUFFER_SIZE);
2803 unsigned c = 0;
2804
2805 /* alloc tmp buffer */
2806 void *pvBuf = RTMemTmpAlloc(VDIDISK_DEFAULT_BUFFER_SIZE);
2807 if (pvBuf)
2808 {
2809 /* Move data. */
2810 for (;;)
2811 {
2812 unsigned cbToMove = (unsigned)RT_MIN(cbData, VDIDISK_DEFAULT_BUFFER_SIZE);
2813
2814 /* Read. */
2815 rc = RTFileSeek(pImage->File, offFile, RTFILE_SEEK_BEGIN, NULL);
2816 if (VBOX_FAILURE(rc))
2817 break;
2818 rc = RTFileRead(pImage->File, pvBuf, cbToMove, NULL);
2819 if (VBOX_FAILURE(rc))
2820 break;
2821
2822 /* Write. */
2823 rc = RTFileSeek(pImage->File, offFile + off, RTFILE_SEEK_BEGIN, NULL);
2824 if (VBOX_FAILURE(rc))
2825 break;
2826 rc = RTFileWrite(pImage->File, pvBuf, cbToMove, NULL);
2827 if (VBOX_FAILURE(rc))
2828 break;
2829
2830 if (pfnProgress)
2831 {
2832 c++;
2833 pfnProgress(NULL /* WARNING! pVM=NULL */,
2834 (c * 100) / cMoves,
2835 pvUser);
2836 /* Note: conversion is non breakable operation, skipping rc here. */
2837 }
2838
2839 cbData -= cbToMove;
2840 if (cbData == 0)
2841 break;
2842
2843 if (cbData > VDIDISK_DEFAULT_BUFFER_SIZE)
2844 offFile -= VDIDISK_DEFAULT_BUFFER_SIZE;
2845 else
2846 offFile = getImageDataOffset(&pImage->Header);
2847 }
2848
2849 /* Fill the beginning of file with zeroes to wipe out old headers etc. */
2850 if (VBOX_SUCCESS(rc))
2851 {
2852 Assert(offFile + off <= VDIDISK_DEFAULT_BUFFER_SIZE);
2853 rc = RTFileSeek(pImage->File, 0, RTFILE_SEEK_BEGIN, NULL);
2854 if (VBOX_SUCCESS(rc))
2855 {
2856 memset(pvBuf, 0, (unsigned)offFile + off);
2857 rc = RTFileWrite(pImage->File, pvBuf, (unsigned)offFile + off, NULL);
2858 }
2859 }
2860
2861 RTMemTmpFree(pvBuf);
2862 }
2863 else
2864 rc = VERR_NO_MEMORY;
2865
2866 if (VBOX_FAILURE(rc))
2867 goto l_conversion_failed;
2868 }
2869
2870 if (pfnProgress)
2871 {
2872 pfnProgress(NULL /* WARNING! pVM=NULL */, 100, pvUser);
2873 /* Note: conversion is non breakable operation, skipping rc here. */
2874 }
2875
2876 /* Data moved, now we need to save new pre header, header and blocks array. */
2877
2878 vdiInitPreHeader(&pImage->PreHeader);
2879 pImage->Header = Header;
2880
2881 /* Setup image parameters by header. */
2882 vdiSetupImageDesc(pImage);
2883
2884 /* Write pre-header. */
2885 rc = RTFileSeek(pImage->File, 0, RTFILE_SEEK_BEGIN, NULL);
2886 if (VBOX_FAILURE(rc))
2887 goto l_conversion_failed;
2888 rc = RTFileWrite(pImage->File, &pImage->PreHeader, sizeof(pImage->PreHeader), NULL);
2889 if (VBOX_FAILURE(rc))
2890 goto l_conversion_failed;
2891
2892 /* Write header and blocks array. */
2893 rc = vdiUpdateBlocks(pImage);
2894
2895l_conversion_failed:
2896 vdiCloseImage(pImage);
2897
2898 LogFlow(("VDIConvertImage: returns %Vrc for filename=\"%s\"\n", rc, pszFilename));
2899 return rc;
2900}
2901
2902/**
2903 * Queries the image's UUID and parent UUIDs.
2904 *
2905 * @returns VBox status code.
2906 * @param pszFilename Name of the image file to operate on.
2907 * @param pUuid Where to store image UUID (can be NULL).
2908 * @param pModificationUuid Where to store modification UUID (can be NULL).
2909 * @param pParentUuuid Where to store parent UUID (can be NULL).
2910 * @param pParentModificationUuid Where to store parent modification UUID (can be NULL).
2911 */
2912IDER3DECL(int) VDIGetImageUUIDs(const char *pszFilename,
2913 PRTUUID pUuid, PRTUUID pModificationUuid,
2914 PRTUUID pParentUuid, PRTUUID pParentModificationUuid)
2915{
2916 LogFlow(("VDIGetImageUUIDs:\n"));
2917
2918 /* Check arguments. */
2919 if ( !pszFilename
2920 || *pszFilename == '\0')
2921 {
2922 AssertMsgFailed(("Invalid arguments: pszFilename=%p\n", pszFilename));
2923 return VERR_INVALID_PARAMETER;
2924 }
2925
2926 /*
2927 * Try open the specified image.
2928 */
2929 PVDIIMAGEDESC pImage;
2930 int rc = vdiOpenImage(&pImage, pszFilename, VDI_OPEN_FLAGS_NORMAL, NULL);
2931 if (VBOX_FAILURE(rc))
2932 {
2933 Log(("VDIGetImageUUIDs: vdiOpenImage rc=%Vrc filename=\"%s\"\n", rc, pszFilename));
2934 return rc;
2935 }
2936
2937 /*
2938 * Query data.
2939 */
2940 if (pUuid)
2941 {
2942 PCRTUUID pTmpUuid = getImageCreationUUID(&pImage->Header);
2943 if (pTmpUuid)
2944 *pUuid = *pTmpUuid;
2945 else
2946 RTUuidClear(pUuid);
2947 }
2948 if (pModificationUuid)
2949 {
2950 PCRTUUID pTmpUuid = getImageModificationUUID(&pImage->Header);
2951 if (pTmpUuid)
2952 *pModificationUuid = *pTmpUuid;
2953 else
2954 RTUuidClear(pModificationUuid);
2955 }
2956 if (pParentUuid)
2957 {
2958 PCRTUUID pTmpUuid = getImageParentUUID(&pImage->Header);
2959 if (pTmpUuid)
2960 *pParentUuid = *pTmpUuid;
2961 else
2962 RTUuidClear(pParentUuid);
2963 }
2964 if (pParentModificationUuid)
2965 {
2966 PCRTUUID pTmpUuid = getImageParentModificationUUID(&pImage->Header);
2967 if (pTmpUuid)
2968 *pParentModificationUuid = *pTmpUuid;
2969 else
2970 RTUuidClear(pParentModificationUuid);
2971 }
2972
2973 /*
2974 * Close the image.
2975 */
2976 vdiCloseImage(pImage);
2977
2978 return VINF_SUCCESS;
2979}
2980
2981/**
2982 * Changes the image's UUID and parent UUIDs.
2983 *
2984 * @returns VBox status code.
2985 * @param pszFilename Name of the image file to operate on.
2986 * @param pUuid Optional parameter, new UUID of the image.
2987 * @param pModificationUuid Optional parameter, new modification UUID of the image.
2988 * @param pParentUuuid Optional parameter, new parent UUID of the image.
2989 * @param pParentModificationUuid Optional parameter, new parent modification UUID of the image.
2990 */
2991IDER3DECL(int) VDISetImageUUIDs(const char *pszFilename,
2992 PCRTUUID pUuid, PCRTUUID pModificationUuid,
2993 PCRTUUID pParentUuid, PCRTUUID pParentModificationUuid)
2994{
2995 LogFlow(("VDISetImageUUIDs:\n"));
2996
2997 /* Check arguments. */
2998 if ( !pszFilename
2999 || *pszFilename == '\0')
3000 {
3001 AssertMsgFailed(("Invalid arguments: pszFilename=%p\n", pszFilename));
3002 return VERR_INVALID_PARAMETER;
3003 }
3004
3005 PVDIIMAGEDESC pImage;
3006 int rc = vdiOpenImage(&pImage, pszFilename, VDI_OPEN_FLAGS_NORMAL, NULL);
3007 if (VBOX_FAILURE(rc))
3008 {
3009 Log(("VDISetImageUUIDs: vdiOpenImage rc=%Vrc filename=\"%s\"\n", rc, pszFilename));
3010 return rc;
3011 }
3012 if (!pImage->fReadOnly)
3013 {
3014 /* we only support new images */
3015 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 1)
3016 {
3017 if (pUuid)
3018 pImage->Header.u.v1.uuidCreate = *pUuid;
3019
3020 if (pModificationUuid)
3021 pImage->Header.u.v1.uuidModify = *pModificationUuid;
3022
3023 if (pParentUuid)
3024 pImage->Header.u.v1.uuidLinkage = *pParentUuid;
3025
3026 if (pParentModificationUuid)
3027 pImage->Header.u.v1.uuidParentModify = *pParentModificationUuid;
3028
3029 /* write out new header */
3030 rc = vdiUpdateHeader(pImage);
3031 AssertMsgRC(rc, ("vdiUpdateHeader() failed, filename=\"%s\", rc=%Vrc\n",
3032 pImage->szFilename, rc));
3033 }
3034 else
3035 {
3036 Log(("VDISetImageUUIDs: Version is not supported!\n"));
3037 rc = VERR_VDI_UNSUPPORTED_VERSION;
3038 }
3039 }
3040 else
3041 {
3042 Log(("VDISetImageUUIDs: image \"%s\" is opened as read-only!\n", pszFilename));
3043 rc = VERR_VDI_IMAGE_READ_ONLY;
3044 }
3045
3046 vdiCloseImage(pImage);
3047 return rc;
3048}
3049
3050/**
3051 * Merges two images having a parent/child relationship (both directions).
3052 *
3053 * @returns VBox status code.
3054 * @param pszFilenameFrom Name of the image file to merge from.
3055 * @param pszFilenameTo Name of the image file to merge into.
3056 * @param pfnProgress Progress callback. Optional. NULL if not to be used.
3057 * @param pvUser User argument for the progress callback.
3058 */
3059IDER3DECL(int) VDIMergeImage(const char *pszFilenameFrom, const char *pszFilenameTo,
3060 PFNVMPROGRESS pfnProgress, void *pvUser)
3061{
3062 LogFlow(("VDIMergeImage:\n"));
3063
3064 /* Check arguments. */
3065 if ( !pszFilenameFrom
3066 || *pszFilenameFrom == '\0'
3067 || !pszFilenameTo
3068 || *pszFilenameTo == '\0')
3069 {
3070 AssertMsgFailed(("Invalid arguments: pszFilenameFrom=%p, pszFilenameTo=%p\n", pszFilenameFrom, pszFilenameTo));
3071 return VERR_INVALID_PARAMETER;
3072 }
3073
3074 PVDIIMAGEDESC pImageFrom;
3075 int rc = vdiOpenImage(&pImageFrom, pszFilenameFrom, VDI_OPEN_FLAGS_READONLY, NULL);
3076 if (VBOX_FAILURE(rc))
3077 {
3078 Log(("VDIMergeImage: vdiOpenImage rc=%Vrc pstFilenameFrom=\"%s\"\n", rc, pszFilenameFrom));
3079 return rc;
3080 }
3081
3082 PVDIIMAGEDESC pImageTo;
3083 rc = vdiOpenImage(&pImageTo, pszFilenameTo, VDI_OPEN_FLAGS_NORMAL, NULL);
3084 if (VBOX_FAILURE(rc))
3085 {
3086 Log(("VDIMergeImage: vdiOpenImage rc=%Vrc pszFilenameTo=\"%s\"\n", rc, pszFilenameTo));
3087 vdiCloseImage(pImageFrom);
3088 return rc;
3089 }
3090 if (pImageTo->fReadOnly)
3091 {
3092 Log(("VDIMergeImage: image \"%s\" is opened as read-only!\n", pszFilenameTo));
3093 vdiCloseImage(pImageFrom);
3094 vdiCloseImage(pImageTo);
3095 return VERR_VDI_IMAGE_READ_ONLY;
3096 }
3097
3098 /*
3099 * when merging, we should not update the modification uuid of the target
3100 * image, because from the point of view of its children, it hasn't been
3101 * logically changed after the successful merge.
3102 */
3103 vdiDisableLastModifiedUpdate(pImageTo);
3104
3105 /*
3106 * Check in which direction we merge
3107 */
3108
3109 bool bParentToChild = false;
3110 if ( getImageParentUUID(&pImageFrom->Header)
3111 && !RTUuidCompare(getImageParentUUID(&pImageFrom->Header),
3112 getImageCreationUUID(&pImageTo->Header))
3113 && !RTUuidCompare(getImageParentModificationUUID(&pImageFrom->Header),
3114 getImageModificationUUID(&pImageTo->Header)))
3115 {
3116 /* we merge from a child to its parent */
3117 }
3118 else
3119 if ( getImageParentUUID(&pImageTo->Header)
3120 && !RTUuidCompare(getImageParentUUID(&pImageTo->Header),
3121 getImageCreationUUID(&pImageFrom->Header))
3122 && !RTUuidCompare(getImageParentModificationUUID(&pImageTo->Header),
3123 getImageModificationUUID(&pImageFrom->Header)))
3124 {
3125 /* we merge from a parent to its child */
3126 bParentToChild = true;
3127 }
3128 else
3129 {
3130 /* the images are not related, we can't merge! */
3131 Log(("VDIMergeImages: images do not have a parent/child or child/parent relationship!\n"));
3132 rc = VERR_VDI_IMAGES_UUID_MISMATCH;
3133 }
3134
3135 rc = vdiMergeImages(pImageFrom, pImageTo, bParentToChild, pfnProgress, pvUser);
3136
3137 if (pfnProgress)
3138 {
3139 pfnProgress(NULL /* WARNING! pVM=NULL */, 100, pvUser);
3140 /* Note: commiting is non breakable operation, skipping rc here. */
3141 }
3142
3143 /* cleanup */
3144 vdiCloseImage(pImageFrom);
3145 vdiCloseImage(pImageTo);
3146
3147 Log(("VDIMergeImage: done, returning with rc = %Vrc\n", rc));
3148 return rc;
3149}
3150
3151
3152/**
3153 * internal: initialize VDIDISK structure.
3154 */
3155static void vdiInitVDIDisk(PVDIDISK pDisk)
3156{
3157 Assert(pDisk);
3158 pDisk->u32Signature = VDIDISK_SIGNATURE;
3159 pDisk->cImages = 0;
3160 pDisk->pBase = NULL;
3161 pDisk->pLast = NULL;
3162 pDisk->cbBlock = VDI_IMAGE_DEFAULT_BLOCK_SIZE;
3163 pDisk->cbBuf = VDIDISK_DEFAULT_BUFFER_SIZE;
3164}
3165
3166/**
3167 * internal: add image structure to the end of images list.
3168 */
3169static void vdiAddImageToList(PVDIDISK pDisk, PVDIIMAGEDESC pImage)
3170{
3171 pImage->pPrev = NULL;
3172 pImage->pNext = NULL;
3173
3174 if (pDisk->pBase)
3175 {
3176 Assert(pDisk->cImages > 0);
3177 pImage->pPrev = pDisk->pLast;
3178 pDisk->pLast->pNext = pImage;
3179 pDisk->pLast = pImage;
3180 }
3181 else
3182 {
3183 Assert(pDisk->cImages == 0);
3184 pDisk->pBase = pImage;
3185 pDisk->pLast = pImage;
3186 }
3187
3188 pDisk->cImages++;
3189}
3190
3191/**
3192 * internal: remove image structure from the images list.
3193 */
3194static void vdiRemoveImageFromList(PVDIDISK pDisk, PVDIIMAGEDESC pImage)
3195{
3196 Assert(pDisk->cImages > 0);
3197
3198 if (pImage->pPrev)
3199 pImage->pPrev->pNext = pImage->pNext;
3200 else
3201 pDisk->pBase = pImage->pNext;
3202
3203 if (pImage->pNext)
3204 pImage->pNext->pPrev = pImage->pPrev;
3205 else
3206 pDisk->pLast = pImage->pPrev;
3207
3208 pImage->pPrev = NULL;
3209 pImage->pNext = NULL;
3210
3211 pDisk->cImages--;
3212}
3213
3214/**
3215 * Allocates and initializes VDI HDD container.
3216 *
3217 * @returns Pointer to newly created HDD container with no one opened image file.
3218 * @returns NULL on failure, typically out of memory.
3219 */
3220IDER3DECL(PVDIDISK) VDIDiskCreate(void)
3221{
3222 PVDIDISK pDisk = (PVDIDISK)RTMemAllocZ(sizeof(VDIDISK));
3223 if (pDisk)
3224 vdiInitVDIDisk(pDisk);
3225 LogFlow(("VDIDiskCreate: returns pDisk=%X\n", pDisk));
3226 return pDisk;
3227}
3228
3229/**
3230 * Destroys VDI HDD container. If container has opened image files they will be closed.
3231 *
3232 * @param pDisk Pointer to VDI HDD container.
3233 */
3234IDER3DECL(void) VDIDiskDestroy(PVDIDISK pDisk)
3235{
3236 LogFlow(("VDIDiskDestroy: pDisk=%X\n", pDisk));
3237 /* sanity check */
3238 Assert(pDisk);
3239 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
3240
3241 if (pDisk)
3242 {
3243 VDIDiskCloseAllImages(pDisk);
3244 RTMemFree(pDisk);
3245 }
3246}
3247
3248/**
3249 * Get working buffer size of VDI HDD container.
3250 *
3251 * @returns Working buffer size in bytes.
3252 */
3253IDER3DECL(unsigned) VDIDiskGetBufferSize(PVDIDISK pDisk)
3254{
3255 /* sanity check */
3256 Assert(pDisk);
3257 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
3258
3259 LogFlow(("VDIDiskGetBufferSize: returns %u\n", pDisk->cbBuf));
3260 return pDisk->cbBuf;
3261}
3262
3263/**
3264 * Get read/write mode of VDI HDD.
3265 *
3266 * @returns Disk ReadOnly status.
3267 * @returns true if no one VDI image is opened in HDD container.
3268 */
3269IDER3DECL(bool) VDIDiskIsReadOnly(PVDIDISK pDisk)
3270{
3271 /* sanity check */
3272 Assert(pDisk);
3273 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
3274
3275 if (pDisk->pLast)
3276 {
3277 LogFlow(("VDIDiskIsReadOnly: returns %u\n", pDisk->pLast->fReadOnly));
3278 return pDisk->pLast->fReadOnly;
3279 }
3280
3281 AssertMsgFailed(("No one disk image is opened!\n"));
3282 return true;
3283}
3284
3285/**
3286 * Get disk size of VDI HDD container.
3287 *
3288 * @returns Virtual disk size in bytes.
3289 * @returns 0 if no one VDI image is opened in HDD container.
3290 */
3291IDER3DECL(uint64_t) VDIDiskGetSize(PVDIDISK pDisk)
3292{
3293 /* sanity check */
3294 Assert(pDisk);
3295 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
3296
3297 if (pDisk->pBase)
3298 {
3299 LogFlow(("VDIDiskGetSize: returns %llu\n", getImageDiskSize(&pDisk->pBase->Header)));
3300 return getImageDiskSize(&pDisk->pBase->Header);
3301 }
3302
3303 AssertMsgFailed(("No one disk image is opened!\n"));
3304 return 0;
3305}
3306
3307/**
3308 * Get block size of VDI HDD container.
3309 *
3310 * @returns VDI image block size in bytes.
3311 * @returns 0 if no one VDI image is opened in HDD container.
3312 */
3313IDER3DECL(unsigned) VDIDiskGetBlockSize(PVDIDISK pDisk)
3314{
3315 /* sanity check */
3316 Assert(pDisk);
3317 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
3318
3319 if (pDisk->pBase)
3320 {
3321 LogFlow(("VDIDiskGetBlockSize: returns %u\n", getImageBlockSize(&pDisk->pBase->Header)));
3322 return getImageBlockSize(&pDisk->pBase->Header);
3323 }
3324
3325 AssertMsgFailed(("No one disk image is opened!\n"));
3326 return 0;
3327}
3328
3329/**
3330 * Get virtual disk geometry stored in image file.
3331 *
3332 * @returns VBox status code.
3333 * @returns VERR_VDI_NOT_OPENED if no one VDI image is opened in HDD container.
3334 * @returns VERR_VDI_GEOMETRY_NOT_SET if no geometry has been setted.
3335 * @param pDisk Pointer to VDI HDD container.
3336 * @param pcCylinders Where to store the number of cylinders. NULL is ok.
3337 * @param pcHeads Where to store the number of heads. NULL is ok.
3338 * @param pcSectors Where to store the number of sectors. NULL is ok.
3339 */
3340IDER3DECL(int) VDIDiskGetGeometry(PVDIDISK pDisk, unsigned *pcCylinders, unsigned *pcHeads, unsigned *pcSectors)
3341{
3342 /* sanity check */
3343 Assert(pDisk);
3344 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
3345
3346 if (pDisk->pBase)
3347 {
3348 int rc = VINF_SUCCESS;
3349 PVDIDISKGEOMETRY pGeometry = getImageGeometry(&pDisk->pBase->Header);
3350 LogFlow(("VDIDiskGetGeometry: C/H/S = %u/%u/%u\n",
3351 pGeometry->cCylinders, pGeometry->cHeads, pGeometry->cSectors));
3352 if ( pGeometry->cCylinders > 0
3353 && pGeometry->cHeads > 0
3354 && pGeometry->cSectors > 0)
3355 {
3356 if (pcCylinders)
3357 *pcCylinders = pGeometry->cCylinders;
3358 if (pcHeads)
3359 *pcHeads = pGeometry->cHeads;
3360 if (pcSectors)
3361 *pcSectors = pGeometry->cSectors;
3362 }
3363 else
3364 rc = VERR_VDI_GEOMETRY_NOT_SET;
3365
3366 LogFlow(("VDIDiskGetGeometry: returns %Vrc\n", rc));
3367 return rc;
3368 }
3369
3370 AssertMsgFailed(("No one disk image is opened!\n"));
3371 return VERR_VDI_NOT_OPENED;
3372}
3373
3374/**
3375 * Store virtual disk geometry into base image file of HDD container.
3376 *
3377 * Note that in case of unrecoverable error all images of HDD container will be closed.
3378 *
3379 * @returns VBox status code.
3380 * @returns VERR_VDI_NOT_OPENED if no one VDI image is opened in HDD container.
3381 * @param pDisk Pointer to VDI HDD container.
3382 * @param cCylinders Number of cylinders.
3383 * @param cHeads Number of heads.
3384 * @param cSectors Number of sectors.
3385 */
3386IDER3DECL(int) VDIDiskSetGeometry(PVDIDISK pDisk, unsigned cCylinders, unsigned cHeads, unsigned cSectors)
3387{
3388 LogFlow(("VDIDiskSetGeometry: C/H/S = %u/%u/%u\n", cCylinders, cHeads, cSectors));
3389 /* sanity check */
3390 Assert(pDisk);
3391 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
3392
3393 if (pDisk->pBase)
3394 {
3395 PVDIDISKGEOMETRY pGeometry = getImageGeometry(&pDisk->pBase->Header);
3396 pGeometry->cCylinders = cCylinders;
3397 pGeometry->cHeads = cHeads;
3398 pGeometry->cSectors = cSectors;
3399 pGeometry->cbSector = VDI_GEOMETRY_SECTOR_SIZE;
3400
3401 /* Update header information in base image file. */
3402 int rc = vdiUpdateReadOnlyHeader(pDisk->pBase);
3403 LogFlow(("VDIDiskSetGeometry: returns %Vrc\n", rc));
3404 return rc;
3405 }
3406
3407 AssertMsgFailed(("No one disk image is opened!\n"));
3408 return VERR_VDI_NOT_OPENED;
3409}
3410
3411/**
3412 * Get virtual disk translation mode stored in image file.
3413 *
3414 * @returns VBox status code.
3415 * @returns VERR_VDI_NOT_OPENED if no one VDI image is opened in HDD container.
3416 * @param pDisk Pointer to VDI HDD container.
3417 * @param penmTranslation Where to store the translation mode (see pdm.h).
3418 */
3419IDER3DECL(int) VDIDiskGetTranslation(PVDIDISK pDisk, PPDMBIOSTRANSLATION penmTranslation)
3420{
3421 /* sanity check */
3422 Assert(pDisk);
3423 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
3424 Assert(penmTranslation);
3425
3426 if (pDisk->pBase)
3427 {
3428 *penmTranslation = getImageTranslation(&pDisk->pBase->Header);
3429 LogFlow(("VDIDiskGetTranslation: translation=%d\n", *penmTranslation));
3430 return VINF_SUCCESS;
3431 }
3432
3433 AssertMsgFailed(("No one disk image is opened!\n"));
3434 return VERR_VDI_NOT_OPENED;
3435}
3436
3437/**
3438 * Store virtual disk translation mode into base image file of HDD container.
3439 *
3440 * Note that in case of unrecoverable error all images of HDD container will be closed.
3441 *
3442 * @returns VBox status code.
3443 * @returns VERR_VDI_NOT_OPENED if no one VDI image is opened in HDD container.
3444 * @param pDisk Pointer to VDI HDD container.
3445 * @param enmTranslation Translation mode (see pdm.h).
3446 */
3447IDER3DECL(int) VDIDiskSetTranslation(PVDIDISK pDisk, PDMBIOSTRANSLATION enmTranslation)
3448{
3449 LogFlow(("VDIDiskSetTranslation: enmTranslation=%d\n", enmTranslation));
3450 /* sanity check */
3451 Assert(pDisk);
3452 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
3453
3454 if (pDisk->pBase)
3455 {
3456 setImageTranslation(&pDisk->pBase->Header, enmTranslation);
3457
3458 /* Update header information in base image file. */
3459 int rc = vdiUpdateReadOnlyHeader(pDisk->pBase);
3460 LogFlow(("VDIDiskSetTranslation: returns %Vrc\n", rc));
3461 return rc;
3462 }
3463
3464 AssertMsgFailed(("No one disk image is opened!\n"));
3465 return VERR_VDI_NOT_OPENED;
3466}
3467
3468/**
3469 * Get number of opened images in HDD container.
3470 *
3471 * @returns Number of opened images for HDD container. 0 if no images is opened.
3472 * @param pDisk Pointer to VDI HDD container.
3473 */
3474IDER3DECL(int) VDIDiskGetImagesCount(PVDIDISK pDisk)
3475{
3476 /* sanity check */
3477 Assert(pDisk);
3478 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
3479
3480 LogFlow(("VDIDiskGetImagesCount: returns %d\n", pDisk->cImages));
3481 return pDisk->cImages;
3482}
3483
3484static PVDIIMAGEDESC vdiGetImageByNumber(PVDIDISK pDisk, int nImage)
3485{
3486 PVDIIMAGEDESC pImage = pDisk->pBase;
3487 while (pImage && nImage)
3488 {
3489 pImage = pImage->pNext;
3490 nImage--;
3491 }
3492 return pImage;
3493}
3494
3495/**
3496 * Get version of opened image of HDD container.
3497 *
3498 * @returns VBox status code.
3499 * @returns VERR_VDI_IMAGE_NOT_FOUND if image with specified number was not opened.
3500 * @param pDisk Pointer to VDI HDD container.
3501 * @param nImage Image number, counts from 0. 0 is always base image of container.
3502 * @param puVersion Where to store the image version.
3503 */
3504IDER3DECL(int) VDIDiskGetImageVersion(PVDIDISK pDisk, int nImage, unsigned *puVersion)
3505{
3506 /* sanity check */
3507 Assert(pDisk);
3508 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
3509 Assert(puVersion);
3510
3511 PVDIIMAGEDESC pImage = vdiGetImageByNumber(pDisk, nImage);
3512 Assert(pImage);
3513
3514 if (pImage)
3515 {
3516 *puVersion = pImage->PreHeader.u32Version;
3517 LogFlow(("VDIDiskGetImageVersion: returns %08X\n", pImage->PreHeader.u32Version));
3518 return VINF_SUCCESS;
3519 }
3520
3521 AssertMsgFailed(("Image %d was not found (cImages=%d)\n", nImage, pDisk->cImages));
3522 return VERR_VDI_IMAGE_NOT_FOUND;
3523}
3524
3525/**
3526 * Get filename of opened image of HDD container.
3527 *
3528 * @returns VBox status code.
3529 * @returns VERR_VDI_IMAGE_NOT_FOUND if image with specified number was not opened.
3530 * @returns VERR_BUFFER_OVERFLOW if pszFilename buffer too small to hold filename.
3531 * @param pDisk Pointer to VDI HDD container.
3532 * @param nImage Image number, counts from 0. 0 is always base image of container.
3533 * @param pszFilename Where to store the image file name.
3534 * @param cbFilename Size of buffer pszFilename points to.
3535 */
3536IDER3DECL(int) VDIDiskGetImageFilename(PVDIDISK pDisk, int nImage, char *pszFilename, unsigned cbFilename)
3537{
3538 /* sanity check */
3539 Assert(pDisk);
3540 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
3541 Assert(pszFilename);
3542
3543 PVDIIMAGEDESC pImage = vdiGetImageByNumber(pDisk, nImage);
3544 Assert(pImage);
3545
3546 if (pImage)
3547 {
3548 unsigned cb = strlen(pImage->szFilename);
3549 if (cb < cbFilename)
3550 {
3551 /* memcpy is much better than strncpy. */
3552 memcpy(pszFilename, pImage->szFilename, cb + 1);
3553 LogFlow(("VDIDiskGetImageFilename: returns VINF_SUCCESS, filename=\"%s\" nImage=%d\n",
3554 pszFilename, nImage));
3555 return VINF_SUCCESS;
3556 }
3557 else
3558 {
3559 AssertMsgFailed(("Out of buffer space, cbFilename=%d needed=%d\n", cbFilename, cb + 1));
3560 return VERR_BUFFER_OVERFLOW;
3561 }
3562 }
3563
3564 AssertMsgFailed(("Image %d was not found (cImages=%d)\n", nImage, pDisk->cImages));
3565 return VERR_VDI_IMAGE_NOT_FOUND;
3566}
3567
3568/**
3569 * Get the comment line of opened image of HDD container.
3570 *
3571 * @returns VBox status code.
3572 * @returns VERR_VDI_IMAGE_NOT_FOUND if image with specified number was not opened.
3573 * @returns VERR_BUFFER_OVERFLOW if pszComment buffer too small to hold comment text.
3574 * @param pDisk Pointer to VDI HDD container.
3575 * @param nImage Image number, counts from 0. 0 is always base image of container.
3576 * @param pszComment Where to store the comment string of image. NULL is ok.
3577 * @param cbComment The size of pszComment buffer. 0 is ok.
3578 */
3579IDER3DECL(int) VDIDiskGetImageComment(PVDIDISK pDisk, int nImage, char *pszComment, unsigned cbComment)
3580{
3581 /* sanity check */
3582 Assert(pDisk);
3583 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
3584 Assert(pszComment);
3585
3586 PVDIIMAGEDESC pImage = vdiGetImageByNumber(pDisk, nImage);
3587 Assert(pImage);
3588
3589 if (pImage)
3590 {
3591 char *pszTmp = getImageComment(&pImage->Header);
3592 unsigned cb = strlen(pszTmp);
3593 if (cb < cbComment)
3594 {
3595 /* memcpy is much better than strncpy. */
3596 memcpy(pszComment, pszTmp, cb + 1);
3597 LogFlow(("VDIDiskGetImageComment: returns VINF_SUCCESS, comment=\"%s\" nImage=%d\n",
3598 pszTmp, nImage));
3599 return VINF_SUCCESS;
3600 }
3601 else
3602 {
3603 AssertMsgFailed(("Out of buffer space, cbComment=%d needed=%d\n", cbComment, cb + 1));
3604 return VERR_BUFFER_OVERFLOW;
3605 }
3606 }
3607
3608 AssertMsgFailed(("Image %d was not found (cImages=%d)\n", nImage, pDisk->cImages));
3609 return VERR_VDI_IMAGE_NOT_FOUND;
3610}
3611
3612/**
3613 * Get type of opened image of HDD container.
3614 *
3615 * @returns VBox status code.
3616 * @returns VERR_VDI_IMAGE_NOT_FOUND if image with specified number was not opened.
3617 * @param pDisk Pointer to VDI HDD container.
3618 * @param nImage Image number, counts from 0. 0 is always base image of container.
3619 * @param penmType Where to store the image type.
3620 */
3621IDER3DECL(int) VDIDiskGetImageType(PVDIDISK pDisk, int nImage, PVDIIMAGETYPE penmType)
3622{
3623 /* sanity check */
3624 Assert(pDisk);
3625 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
3626 Assert(penmType);
3627
3628 PVDIIMAGEDESC pImage = vdiGetImageByNumber(pDisk, nImage);
3629 Assert(pImage);
3630
3631 if (pImage)
3632 {
3633 *penmType = getImageType(&pImage->Header);
3634 LogFlow(("VDIDiskGetImageType: returns VINF_SUCCESS, type=%X nImage=%d\n",
3635 *penmType, nImage));
3636 return VINF_SUCCESS;
3637 }
3638
3639 AssertMsgFailed(("Image %d was not found (cImages=%d)\n", nImage, pDisk->cImages));
3640 return VERR_VDI_IMAGE_NOT_FOUND;
3641}
3642
3643/**
3644 * Get flags of opened image of HDD container.
3645 *
3646 * @returns VBox status code.
3647 * @returns VERR_VDI_IMAGE_NOT_FOUND if image with specified number was not opened.
3648 * @param pDisk Pointer to VDI HDD container.
3649 * @param nImage Image number, counts from 0. 0 is always base image of container.
3650 * @param pfFlags Where to store the image flags.
3651 */
3652IDER3DECL(int) VDIDiskGetImageFlags(PVDIDISK pDisk, int nImage, unsigned *pfFlags)
3653{
3654 /* sanity check */
3655 Assert(pDisk);
3656 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
3657 Assert(pfFlags);
3658
3659 PVDIIMAGEDESC pImage = vdiGetImageByNumber(pDisk, nImage);
3660 Assert(pImage);
3661
3662 if (pImage)
3663 {
3664 *pfFlags = getImageFlags(&pImage->Header);
3665 LogFlow(("VDIDiskGetImageFlags: returns VINF_SUCCESS, flags=%08X nImage=%d\n",
3666 *pfFlags, nImage));
3667 return VINF_SUCCESS;
3668 }
3669
3670 AssertMsgFailed(("Image %d was not found (cImages=%d)\n", nImage, pDisk->cImages));
3671 return VERR_VDI_IMAGE_NOT_FOUND;
3672}
3673
3674/**
3675 * Get Uuid of opened image of HDD container.
3676 *
3677 * @returns VBox status code.
3678 * @returns VERR_VDI_IMAGE_NOT_FOUND if image with specified number was not opened.
3679 * @param pDisk Pointer to VDI HDD container.
3680 * @param nImage Image number, counts from 0. 0 is always base image of container.
3681 * @param pUuid Where to store the image creation uuid.
3682 */
3683IDER3DECL(int) VDIDiskGetImageUuid(PVDIDISK pDisk, int nImage, PRTUUID pUuid)
3684{
3685 /* sanity check */
3686 Assert(pDisk);
3687 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
3688 Assert(pUuid);
3689
3690 PVDIIMAGEDESC pImage = vdiGetImageByNumber(pDisk, nImage);
3691 Assert(pImage);
3692
3693 if (pImage)
3694 {
3695 *pUuid = *getImageCreationUUID(&pImage->Header);
3696 LogFlow(("VDIDiskGetImageUuid: returns VINF_SUCCESS, uuid={%Vuuid} nImage=%d\n",
3697 pUuid, nImage));
3698 return VINF_SUCCESS;
3699 }
3700
3701 AssertMsgFailed(("Image %d was not found (cImages=%d)\n", nImage, pDisk->cImages));
3702 return VERR_VDI_IMAGE_NOT_FOUND;
3703}
3704
3705/**
3706 * Get last modification Uuid of opened image of HDD container.
3707 *
3708 * @returns VBox status code.
3709 * @returns VERR_VDI_IMAGE_NOT_FOUND if image with specified number was not opened.
3710 * @param pDisk Pointer to VDI HDD container.
3711 * @param nImage Image number, counts from 0. 0 is always base image of container.
3712 * @param pUuid Where to store the image modification uuid.
3713 */
3714IDER3DECL(int) VDIDiskGetImageModificationUuid(PVDIDISK pDisk, int nImage, PRTUUID pUuid)
3715{
3716 /* sanity check */
3717 Assert(pDisk);
3718 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
3719 Assert(pUuid);
3720
3721 PVDIIMAGEDESC pImage = vdiGetImageByNumber(pDisk, nImage);
3722 Assert(pImage);
3723
3724 if (pImage)
3725 {
3726 *pUuid = *getImageModificationUUID(&pImage->Header);
3727 LogFlow(("VDIDiskGetImageModificationUuid: returns VINF_SUCCESS, uuid={%Vuuid} nImage=%d\n",
3728 pUuid, nImage));
3729 return VINF_SUCCESS;
3730 }
3731
3732 AssertMsgFailed(("Image %d was not found (cImages=%d)\n", nImage, pDisk->cImages));
3733 return VERR_VDI_IMAGE_NOT_FOUND;
3734}
3735
3736/**
3737 * Get Uuid of opened image's parent image.
3738 *
3739 * @returns VBox status code.
3740 * @returns VERR_VDI_IMAGE_NOT_FOUND if image with specified number was not opened.
3741 * @param pDisk Pointer to VDI HDD container.
3742 * @param nImage Image number, counts from 0. 0 is always base image of the container.
3743 * @param pUuid Where to store the image creation uuid.
3744 */
3745IDER3DECL(int) VDIDiskGetParentImageUuid(PVDIDISK pDisk, int nImage, PRTUUID pUuid)
3746{
3747 /* sanity check */
3748 Assert(pDisk);
3749 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
3750 Assert(pUuid);
3751
3752 PVDIIMAGEDESC pImage = vdiGetImageByNumber(pDisk, nImage);
3753 if (pImage)
3754 {
3755 *pUuid = *getImageParentUUID(&pImage->Header);
3756 LogFlow(("VDIDiskGetParentImageUuid: returns VINF_SUCCESS, *pUuid={%Vuuid} nImage=%d\n",
3757 pUuid, nImage));
3758 return VINF_SUCCESS;
3759 }
3760
3761 AssertMsgFailed(("Image %d was not found (cImages=%d)\n", nImage, pDisk->cImages));
3762 return VERR_VDI_IMAGE_NOT_FOUND;
3763}
3764
3765/**
3766 * internal: Relock image as read/write or read-only.
3767 */
3768static int vdiChangeImageMode(PVDIIMAGEDESC pImage, bool fReadOnly)
3769{
3770 Assert(pImage);
3771
3772 if ( !fReadOnly
3773 && pImage->fOpen & VDI_OPEN_FLAGS_READONLY)
3774 {
3775 /* Can't switch read-only opened image to read-write mode. */
3776 Log(("vdiChangeImageMode: can't switch r/o image to r/w mode, filename=\"%s\" fOpen=%X\n",
3777 pImage->szFilename, pImage->fOpen));
3778 return VERR_VDI_IMAGE_READ_ONLY;
3779 }
3780
3781 /* Flush last image changes if was r/w mode. */
3782 vdiFlushImage(pImage);
3783
3784 /* Change image locking. */
3785 uint64_t cbLock = pImage->offStartData
3786 + ((uint64_t)getImageBlocks(&pImage->Header) << pImage->uShiftIndex2Offset);
3787 int rc = RTFileChangeLock(pImage->File,
3788 (fReadOnly) ?
3789 RTFILE_LOCK_READ | RTFILE_LOCK_IMMEDIATELY :
3790 RTFILE_LOCK_WRITE | RTFILE_LOCK_IMMEDIATELY,
3791 0,
3792 cbLock);
3793 if (VBOX_SUCCESS(rc))
3794 {
3795 pImage->fReadOnly = fReadOnly;
3796 Log(("vdiChangeImageMode: Image \"%s\" mode changed to %s\n",
3797 pImage->szFilename, (pImage->fReadOnly) ? "read-only" : "read/write"));
3798 return VINF_SUCCESS;
3799 }
3800
3801 /* Check for the most bad error in the world. Damn! It must never happens in real life! */
3802 if (rc == VERR_FILE_LOCK_LOST)
3803 {
3804 /* And what we can do now?! */
3805 AssertMsgFailed(("Image lock has been lost for file=\"%s\"", pImage->szFilename));
3806 Log(("vdiChangeImageMode: image lock has been lost for file=\"%s\", blocking on r/o lock wait",
3807 pImage->szFilename));
3808
3809 /* Try to obtain read lock in blocking mode. Maybe it's a very bad method. */
3810 rc = RTFileLock(pImage->File, RTFILE_LOCK_READ | RTFILE_LOCK_WAIT, 0, cbLock);
3811 AssertReleaseRC(rc);
3812
3813 pImage->fReadOnly = false;
3814 if (pImage->fReadOnly != fReadOnly)
3815 rc = VERR_FILE_LOCK_VIOLATION;
3816 }
3817
3818 Log(("vdiChangeImageMode: Image \"%s\" mode change failed with rc=%Vrc, mode is %s\n",
3819 pImage->szFilename, rc, (pImage->fReadOnly) ? "read-only" : "read/write"));
3820
3821 return rc;
3822}
3823
3824/**
3825 * internal: try to save header in image file even if image is in read-only mode.
3826 */
3827static int vdiUpdateReadOnlyHeader(PVDIIMAGEDESC pImage)
3828{
3829 int rc = VINF_SUCCESS;
3830
3831 if (pImage->fReadOnly)
3832 {
3833 rc = vdiChangeImageMode(pImage, false);
3834 if (VBOX_SUCCESS(rc))
3835 {
3836 vdiFlushImage(pImage);
3837 rc = vdiChangeImageMode(pImage, true);
3838 AssertReleaseRC(rc);
3839 }
3840 }
3841 else
3842 vdiFlushImage(pImage);
3843
3844 return rc;
3845}
3846
3847/**
3848 * Opens an image file.
3849 *
3850 * The first opened image file in a HDD container must have a base image type,
3851 * others (next opened images) must be a differencing or undo images.
3852 * Linkage is checked for differencing image to be in consistence with the previously opened image.
3853 * When a next differencing image is opened and the last image was opened in read/write access
3854 * mode, then the last image is reopened in read-only with deny write sharing mode. This allows
3855 * other processes to use images in read-only mode too.
3856 *
3857 * Note that the image can be opened in read-only mode if a read/write open is not possible.
3858 * Use VDIDiskIsReadOnly to check open mode.
3859 *
3860 * @returns VBox status code.
3861 * @param pDisk Pointer to VDI HDD container.
3862 * @param pszFilename Name of the image file to open.
3863 * @param fOpen Image file open mode, see VDI_OPEN_FLAGS_* constants.
3864 */
3865IDER3DECL(int) VDIDiskOpenImage(PVDIDISK pDisk, const char *pszFilename, unsigned fOpen)
3866{
3867 /* sanity check */
3868 Assert(pDisk);
3869 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
3870
3871 /* Check arguments. */
3872 if ( !pszFilename
3873 || *pszFilename == '\0'
3874 || (fOpen & ~VDI_OPEN_FLAGS_MASK))
3875 {
3876 AssertMsgFailed(("Invalid arguments: pszFilename=%p fOpen=%x\n", pszFilename, fOpen));
3877 return VERR_INVALID_PARAMETER;
3878 }
3879 LogFlow(("VDIDiskOpenImage: pszFilename=\"%s\" fOpen=%X\n", pszFilename, fOpen));
3880
3881 PVDIIMAGEDESC pImage;
3882 int rc = vdiOpenImage(&pImage, pszFilename, fOpen, pDisk->pLast);
3883 if (VBOX_SUCCESS(rc))
3884 {
3885 if (pDisk->pLast)
3886 {
3887 /* Opening differencing image. */
3888 if (!pDisk->pLast->fReadOnly)
3889 {
3890 /*
3891 * Previous image is opened in read/write mode -> switch it into read-only.
3892 */
3893 rc = vdiChangeImageMode(pDisk->pLast, true);
3894 }
3895 }
3896 else
3897 {
3898 /* Opening base image, check its type. */
3899 if ( getImageType(&pImage->Header) != VDI_IMAGE_TYPE_NORMAL
3900 && getImageType(&pImage->Header) != VDI_IMAGE_TYPE_FIXED)
3901 {
3902 rc = VERR_VDI_INVALID_TYPE;
3903 }
3904 }
3905
3906 if (VBOX_SUCCESS(rc))
3907 vdiAddImageToList(pDisk, pImage);
3908 else
3909 vdiCloseImage(pImage);
3910 }
3911
3912 LogFlow(("VDIDiskOpenImage: returns %Vrc\n", rc));
3913 return rc;
3914}
3915
3916/**
3917 * Closes the last opened image file in the HDD container. Leaves all changes inside it.
3918 * If previous image file was opened in read-only mode (that is normal) and closing image
3919 * was opened in read-write mode (the whole disk was in read-write mode) - the previous image
3920 * will be reopened in read/write mode.
3921 *
3922 * @param pDisk Pointer to VDI HDD container.
3923 */
3924IDER3DECL(void) VDIDiskCloseImage(PVDIDISK pDisk)
3925{
3926 /* sanity check */
3927 Assert(pDisk);
3928 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
3929
3930 PVDIIMAGEDESC pImage = pDisk->pLast;
3931 if (pImage)
3932 {
3933 LogFlow(("VDIDiskCloseImage: closing image \"%s\"\n", pImage->szFilename));
3934
3935 bool fWasReadOnly = pImage->fReadOnly;
3936 vdiRemoveImageFromList(pDisk, pImage);
3937 vdiCloseImage(pImage);
3938
3939 if ( !fWasReadOnly
3940 && pDisk->pLast
3941 && pDisk->pLast->fReadOnly
3942 && !(pDisk->pLast->fOpen & VDI_OPEN_FLAGS_READONLY))
3943 {
3944 /*
3945 * Closed image was opened in read/write mode, previous image was opened
3946 * in read-only mode, try to switch it into read/write.
3947 */
3948 int rc = vdiChangeImageMode(pDisk->pLast, false);
3949 NOREF(rc); /* gcc still hates unused variables... */
3950 }
3951
3952 return;
3953 }
3954 AssertMsgFailed(("No images to close\n"));
3955}
3956
3957/**
3958 * Closes all opened image files in HDD container.
3959 *
3960 * @param pDisk Pointer to VDI HDD container.
3961 */
3962IDER3DECL(void) VDIDiskCloseAllImages(PVDIDISK pDisk)
3963{
3964 LogFlow(("VDIDiskCloseAllImages:\n"));
3965 /* sanity check */
3966 Assert(pDisk);
3967 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
3968
3969 PVDIIMAGEDESC pImage = pDisk->pLast;
3970 while (pImage)
3971 {
3972 PVDIIMAGEDESC pPrev = pImage->pPrev;
3973 vdiRemoveImageFromList(pDisk, pImage);
3974 vdiCloseImage(pImage);
3975 pImage = pPrev;
3976 }
3977 Assert(pDisk->pLast == NULL);
3978}
3979
3980/**
3981 * Commits last opened differencing/undo image file of HDD container to previous one.
3982 * If previous image file was opened in read-only mode (that must be always so) it is reopened
3983 * as read/write to do commit operation.
3984 * After successfull commit the previous image file again reopened in read-only mode, last opened
3985 * image file is cleared of data and remains open and active in HDD container.
3986 * If you want to delete image after commit you must do it manually by VDIDiskCloseImage and
3987 * VDIDeleteImage calls.
3988 *
3989 * Note that in case of unrecoverable error all images of HDD container will be closed.
3990 *
3991 * @returns VBox status code.
3992 * @param pDisk Pointer to VDI HDD container.
3993 * @param pfnProgress Progress callback. Optional.
3994 * @param pvUser User argument for the progress callback.
3995 * @remark Only used by tstVDI.
3996 */
3997IDER3DECL(int) VDIDiskCommitLastDiff(PVDIDISK pDisk, PFNVMPROGRESS pfnProgress, void *pvUser)
3998{
3999 LogFlow(("VDIDiskCommitLastDiff:\n"));
4000 /* sanity check */
4001 Assert(pDisk);
4002 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
4003
4004 int rc = VINF_SUCCESS;
4005 PVDIIMAGEDESC pImage = pDisk->pLast;
4006 if (!pImage)
4007 {
4008 AssertMsgFailed(("No one disk image is opened!\n"));
4009 return VERR_VDI_NOT_OPENED;
4010 }
4011
4012 if (pImage->fReadOnly)
4013 {
4014 AssertMsgFailed(("Image \"%s\" is read-only!\n", pImage->szFilename));
4015 return VERR_VDI_IMAGE_READ_ONLY;
4016 }
4017
4018 if (!pImage->pPrev)
4019 {
4020 AssertMsgFailed(("No images to commit to!\n"));
4021 return VERR_VDI_NO_DIFF_IMAGES;
4022 }
4023
4024 bool fWasReadOnly = pImage->pPrev->fReadOnly;
4025 if (fWasReadOnly)
4026 {
4027 /* Change previous image mode to r/w. */
4028 rc = vdiChangeImageMode(pImage->pPrev, false);
4029 if (VBOX_FAILURE(rc))
4030 {
4031 Log(("VDIDiskCommitLastDiff: can't switch previous image into r/w mode, rc=%Vrc\n", rc));
4032 return rc;
4033 }
4034 }
4035
4036 rc = vdiCommitToImage(pDisk, pImage->pPrev, pfnProgress, pvUser);
4037 if (VBOX_SUCCESS(rc) && fWasReadOnly)
4038 {
4039 /* Change previous image mode back to r/o. */
4040 rc = vdiChangeImageMode(pImage->pPrev, true);
4041 }
4042
4043 if (VBOX_FAILURE(rc))
4044 {
4045 /* Failed! Close all images, can't work with VHDD at all. */
4046 VDIDiskCloseAllImages(pDisk);
4047 AssertMsgFailed(("Fatal: commit failed, rc=%Vrc\n", rc));
4048 }
4049
4050 return rc;
4051}
4052
4053/**
4054 * Creates and opens a new differencing image file in HDD container.
4055 * See comments for VDIDiskOpenImage function about differencing images.
4056 *
4057 * @returns VBox status code.
4058 * @param pDisk Pointer to VDI HDD container.
4059 * @param pszFilename Name of the image file to create and open.
4060 * @param pszComment Pointer to image comment. NULL is ok.
4061 * @param pfnProgress Progress callback. Optional.
4062 * @param pvUser User argument for the progress callback.
4063 * @remark Only used by tstVDI.
4064 */
4065IDER3DECL(int) VDIDiskCreateOpenDifferenceImage(PVDIDISK pDisk, const char *pszFilename,
4066 const char *pszComment, PFNVMPROGRESS pfnProgress,
4067 void *pvUser)
4068{
4069 LogFlow(("VDIDiskCreateOpenDifferenceImage:\n"));
4070 /* sanity check */
4071 Assert(pDisk);
4072 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
4073 Assert(pszFilename);
4074
4075 if (!pDisk->pLast)
4076 {
4077 AssertMsgFailed(("No one disk image is opened!\n"));
4078 return VERR_VDI_NOT_OPENED;
4079 }
4080
4081 /* Flush last parent image changes if possible. */
4082 vdiFlushImage(pDisk->pLast);
4083
4084 int rc = vdiCreateImage(pszFilename,
4085 VDI_IMAGE_TYPE_DIFF,
4086 VDI_IMAGE_FLAGS_DEFAULT,
4087 getImageDiskSize(&pDisk->pLast->Header),
4088 pszComment,
4089 pDisk->pLast,
4090 pfnProgress, pvUser);
4091 if (VBOX_SUCCESS(rc))
4092 {
4093 rc = VDIDiskOpenImage(pDisk, pszFilename, VDI_OPEN_FLAGS_NORMAL);
4094 if (VBOX_FAILURE(rc))
4095 VDIDeleteImage(pszFilename);
4096 }
4097 LogFlow(("VDIDiskCreateOpenDifferenceImage: returns %Vrc, filename=\"%s\"\n", rc, pszFilename));
4098 return rc;
4099}
4100
4101/**
4102 * internal: debug image dump.
4103 *
4104 * @remark Only used by tstVDI.
4105 */
4106static void vdiDumpImage(PVDIIMAGEDESC pImage)
4107{
4108 RTLogPrintf("Dumping VDI image \"%s\" mode=%s fOpen=%X File=%08X\n",
4109 pImage->szFilename,
4110 (pImage->fReadOnly) ? "r/o" : "r/w",
4111 pImage->fOpen,
4112 pImage->File);
4113 RTLogPrintf("Header: Version=%08X Type=%X Flags=%X Size=%llu\n",
4114 pImage->PreHeader.u32Version,
4115 getImageType(&pImage->Header),
4116 getImageFlags(&pImage->Header),
4117 getImageDiskSize(&pImage->Header));
4118 RTLogPrintf("Header: cbBlock=%u cbBlockExtra=%u cBlocks=%u cBlocksAllocated=%u\n",
4119 getImageBlockSize(&pImage->Header),
4120 getImageExtraBlockSize(&pImage->Header),
4121 getImageBlocks(&pImage->Header),
4122 getImageBlocksAllocated(&pImage->Header));
4123 RTLogPrintf("Header: offBlocks=%u offData=%u\n",
4124 getImageBlocksOffset(&pImage->Header),
4125 getImageDataOffset(&pImage->Header));
4126 PVDIDISKGEOMETRY pg = getImageGeometry(&pImage->Header);
4127 RTLogPrintf("Header: Geometry: C/H/S=%u/%u/%u cbSector=%u Mode=%u\n",
4128 pg->cCylinders, pg->cHeads, pg->cSectors, pg->cbSector,
4129 getImageTranslation(&pImage->Header));
4130 RTLogPrintf("Header: uuidCreation={%Vuuid}\n", getImageCreationUUID(&pImage->Header));
4131 RTLogPrintf("Header: uuidModification={%Vuuid}\n", getImageModificationUUID(&pImage->Header));
4132 RTLogPrintf("Header: uuidParent={%Vuuid}\n", getImageParentUUID(&pImage->Header));
4133 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) >= 1)
4134 RTLogPrintf("Header: uuidParentModification={%Vuuid}\n", getImageParentModificationUUID(&pImage->Header));
4135 RTLogPrintf("Image: fFlags=%08X offStartBlocks=%u offStartData=%u\n",
4136 pImage->fFlags, pImage->offStartBlocks, pImage->offStartData);
4137 RTLogPrintf("Image: uBlockMask=%08X uShiftIndex2Offset=%u uShiftOffset2Index=%u offStartBlockData=%u\n",
4138 pImage->uBlockMask,
4139 pImage->uShiftIndex2Offset,
4140 pImage->uShiftOffset2Index,
4141 pImage->offStartBlockData);
4142
4143 unsigned uBlock, cBlocksNotFree, cBadBlocks, cBlocks = getImageBlocks(&pImage->Header);
4144 for (uBlock=0, cBlocksNotFree=0, cBadBlocks=0; uBlock<cBlocks; uBlock++)
4145 {
4146 if (IS_VDI_IMAGE_BLOCK_ALLOCATED(pImage->paBlocks[uBlock]))
4147 {
4148 cBlocksNotFree++;
4149 if (pImage->paBlocks[uBlock] >= cBlocks)
4150 cBadBlocks++;
4151 }
4152 }
4153 if (cBlocksNotFree != getImageBlocksAllocated(&pImage->Header))
4154 {
4155 RTLogPrintf("!! WARNING: %u blocks actually allocated (cBlocksAllocated=%u) !!\n",
4156 cBlocksNotFree, getImageBlocksAllocated(&pImage->Header));
4157 }
4158 if (cBadBlocks)
4159 {
4160 RTLogPrintf("!! WARNING: %u bad blocks found !!\n",
4161 cBadBlocks);
4162 }
4163}
4164
4165/**
4166 * Debug helper - dumps all opened images of HDD container into the log file.
4167 *
4168 * @param pDisk Pointer to VDI HDD container.
4169 * @remark Only used by tstVDI and vditool
4170 */
4171IDER3DECL(void) VDIDiskDumpImages(PVDIDISK pDisk)
4172{
4173 /* sanity check */
4174 Assert(pDisk);
4175 AssertMsg(pDisk->u32Signature == VDIDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
4176
4177 RTLogPrintf("--- Dumping VDI Disk, Images=%u\n", pDisk->cImages);
4178 for (PVDIIMAGEDESC pImage = pDisk->pBase; pImage; pImage = pImage->pNext)
4179 vdiDumpImage(pImage);
4180}
4181
4182
4183/*******************************************************************************
4184* PDM interface *
4185*******************************************************************************/
4186
4187/**
4188 * Construct a VBox HDD media driver instance.
4189 *
4190 * @returns VBox status.
4191 * @param pDrvIns The driver instance data.
4192 * If the registration structure is needed, pDrvIns->pDrvReg points to it.
4193 * @param pCfgHandle Configuration node handle for the driver. Use this to obtain the configuration
4194 * of the driver instance. It's also found in pDrvIns->pCfgHandle, but like
4195 * iInstance it's expected to be used a bit in this function.
4196 */
4197static DECLCALLBACK(int) vdiConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfgHandle)
4198{
4199 LogFlow(("vdiConstruct:\n"));
4200 PVDIDISK pData = PDMINS2DATA(pDrvIns, PVDIDISK);
4201 char *pszName; /**< The path of the disk image file. */
4202 bool fReadOnly; /**< True if the media is readonly. */
4203
4204 /*
4205 * Init the static parts.
4206 */
4207 pDrvIns->IBase.pfnQueryInterface = vdiQueryInterface;
4208 pData->pDrvIns = pDrvIns;
4209
4210 vdiInitVDIDisk(pData);
4211
4212 /* IMedia */
4213 pData->IMedia.pfnRead = vdiRead;
4214 pData->IMedia.pfnWrite = vdiWrite;
4215 pData->IMedia.pfnFlush = vdiFlush;
4216 pData->IMedia.pfnGetSize = vdiGetSize;
4217 pData->IMedia.pfnGetUuid = vdiGetUuid;
4218 pData->IMedia.pfnIsReadOnly = vdiIsReadOnly;
4219 pData->IMedia.pfnBiosGetGeometry = vdiBiosGetGeometry;
4220 pData->IMedia.pfnBiosSetGeometry = vdiBiosSetGeometry;
4221 pData->IMedia.pfnBiosGetTranslation = vdiBiosGetTranslation;
4222 pData->IMedia.pfnBiosSetTranslation = vdiBiosSetTranslation;
4223
4224#if 1 /** @todo someone review this! it's a shot in the dark from my side. */
4225 /*
4226 * Validate configuration and find the great to the level of umpteen grandparent.
4227 * The parents are found in the 'Parent' subtree, so it's sorta up side down
4228 * from the image dependency tree.
4229 */
4230 unsigned iLevel = 0;
4231 PCFGMNODE pCurNode = pCfgHandle;
4232 for (;;)
4233 {
4234 if (!CFGMR3AreValuesValid(pCfgHandle, "Path\0ReadOnly\0"))
4235 return VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES;
4236
4237 PCFGMNODE pParent = CFGMR3GetChild(pCurNode, "Parent");
4238 if (!pParent)
4239 break;
4240 pCurNode = pParent;
4241 iLevel++;
4242 }
4243
4244 /*
4245 * Open the images.
4246 */
4247 int rc = VINF_SUCCESS;
4248 while (pCurNode && VBOX_SUCCESS(rc))
4249 {
4250 /*
4251 * Read the image configuration.
4252 */
4253 int rc = CFGMR3QueryStringAlloc(pCurNode, "Path", &pszName);
4254 if (VBOX_FAILURE(rc))
4255 return PDMDRV_SET_ERROR(pDrvIns, rc,
4256 N_("VHDD: Configuration error: Querying \"Path\" as string failed"));
4257
4258 rc = CFGMR3QueryBool(pCfgHandle, "ReadOnly", &fReadOnly);
4259 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
4260 fReadOnly = false;
4261 else if (VBOX_FAILURE(rc))
4262 {
4263 MMR3HeapFree(pszName);
4264 return PDMDRV_SET_ERROR(pDrvIns, rc,
4265 N_("VHDD: Configuration error: Querying \"ReadOnly\" as boolean failed"));
4266 }
4267
4268 /*
4269 * Open the image.
4270 */
4271 rc = VDIDiskOpenImage(pData, pszName, fReadOnly ? VDI_OPEN_FLAGS_READONLY
4272 : VDI_OPEN_FLAGS_NORMAL);
4273 if (VBOX_SUCCESS(rc))
4274 Log(("vdiConstruct: %d - Opened '%s' in %s mode\n",
4275 iLevel, pszName, VDIDiskIsReadOnly(pData) ? "read-only" : "read-write"));
4276 else
4277 AssertMsgFailed(("Failed to open image '%s' rc=%Vrc\n", pszName, rc));
4278 MMR3HeapFree(pszName);
4279
4280 /* next */
4281 iLevel--;
4282 pCurNode = CFGMR3GetParent(pCurNode);
4283 }
4284
4285 /* On failure, vdiDestruct will be called, so no need to clean up here. */
4286
4287#else /* old */
4288 /*
4289 * Validate and read top level configuration.
4290 */
4291 int rc = CFGMR3QueryStringAlloc(pCfgHandle, "Path", &pszName);
4292 if (VBOX_FAILURE(rc))
4293 return PDMDRV_SET_ERROR(pDrvIns, rc,
4294 N_("VHDD: Configuration error: Querying \"Path\" as string failed"));
4295
4296 rc = CFGMR3QueryBool(pCfgHandle, "ReadOnly", &fReadOnly);
4297 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
4298 fReadOnly = false;
4299 else if (VBOX_FAILURE(rc))
4300 {
4301 MMR3HeapFree(pszName);
4302 return PDMDRV_SET_ERROR(pDrvIns, rc,
4303 N_("VHDD: Configuration error: Querying \"ReadOnly\" as boolean failed"));
4304 }
4305
4306 /*
4307 * Open the image.
4308 */
4309 rc = VDIDiskOpenImage(pData, pszName, fReadOnly ? VDI_OPEN_FLAGS_READONLY
4310 : VDI_OPEN_FLAGS_NORMAL);
4311 if (VBOX_SUCCESS(rc))
4312 Log(("vdiConstruct: Opened '%s' in %s mode\n", pszName, VDIDiskIsReadOnly(pData) ? "read-only" : "read-write"));
4313 else
4314 AssertMsgFailed(("Failed to open image '%s' rc=%Vrc\n", pszName, rc));
4315
4316 MMR3HeapFree(pszName);
4317 pszName = NULL;
4318#endif
4319
4320 if (rc == VERR_ACCESS_DENIED)
4321 /* This should never happen here since this case is covered by Console::PowerUp */
4322 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS,
4323 N_("Cannot open virtual disk image '%s' for %s access"),
4324 pszName, fReadOnly ? "readonly" : "read/write");
4325
4326 return rc;
4327}
4328
4329/**
4330 * Destruct a driver instance.
4331 *
4332 * Most VM resources are freed by the VM. This callback is provided so that any non-VM
4333 * resources can be freed correctly.
4334 *
4335 * @param pDrvIns The driver instance data.
4336 */
4337static DECLCALLBACK(void) vdiDestruct(PPDMDRVINS pDrvIns)
4338{
4339 LogFlow(("vdiDestruct:\n"));
4340 PVDIDISK pData = PDMINS2DATA(pDrvIns, PVDIDISK);
4341 VDIDiskCloseAllImages(pData);
4342}
4343
4344/**
4345 * When the VM has been suspended we'll change the image mode to read-only
4346 * so that main and others can read the VDIs. This is important when
4347 * saving state and so forth.
4348 *
4349 * @param pDrvIns The driver instance data.
4350 */
4351static DECLCALLBACK(void) vdiSuspend(PPDMDRVINS pDrvIns)
4352{
4353 LogFlow(("vdiSuspend:\n"));
4354#if 1 // #ifdef DEBUG_dmik
4355 PVDIDISK pData = PDMINS2DATA(pDrvIns, PVDIDISK);
4356 if (!(pData->pLast->fOpen & VDI_OPEN_FLAGS_READONLY))
4357 {
4358 int rc = vdiChangeImageMode(pData->pLast, true);
4359 AssertRC(rc);
4360 }
4361#endif
4362}
4363
4364/**
4365 * Before the VM resumes we'll have to undo the read-only mode change
4366 * done in vdiSuspend.
4367 *
4368 * @param pDrvIns The driver instance data.
4369 */
4370static DECLCALLBACK(void) vdiResume(PPDMDRVINS pDrvIns)
4371{
4372 LogFlow(("vdiSuspend:\n"));
4373#if 1 //#ifdef DEBUG_dmik
4374 PVDIDISK pData = PDMINS2DATA(pDrvIns, PVDIDISK);
4375 if (!(pData->pLast->fOpen & VDI_OPEN_FLAGS_READONLY))
4376 {
4377 int rc = vdiChangeImageMode(pData->pLast, false);
4378 AssertRC(rc);
4379 }
4380#endif
4381}
4382
4383
4384/** @copydoc PDMIMEDIA::pfnGetSize */
4385static DECLCALLBACK(uint64_t) vdiGetSize(PPDMIMEDIA pInterface)
4386{
4387 PVDIDISK pData = PDMIMEDIA_2_VDIDISK(pInterface);
4388 uint64_t cb = VDIDiskGetSize(pData);
4389 LogFlow(("vdiGetSize: returns %#llx (%llu)\n", cb, cb));
4390 return cb;
4391}
4392
4393/**
4394 * Get stored media geometry - BIOS property.
4395 *
4396 * @see PDMIMEDIA::pfnBiosGetGeometry for details.
4397 */
4398static DECLCALLBACK(int) vdiBiosGetGeometry(PPDMIMEDIA pInterface, uint32_t *pcCylinders, uint32_t *pcHeads, uint32_t *pcSectors)
4399{
4400 PVDIDISK pData = PDMIMEDIA_2_VDIDISK(pInterface);
4401 int rc = VDIDiskGetGeometry(pData, pcCylinders, pcHeads, pcSectors);
4402 if (VBOX_SUCCESS(rc))
4403 {
4404 LogFlow(("vdiBiosGetGeometry: returns VINF_SUCCESS\n"));
4405 return VINF_SUCCESS;
4406 }
4407 Log(("vdiBiosGetGeometry: The Bios geometry data was not available.\n"));
4408 return VERR_PDM_GEOMETRY_NOT_SET;
4409}
4410
4411/**
4412 * Set stored media geometry - BIOS property.
4413 *
4414 * @see PDMIMEDIA::pfnBiosSetGeometry for details.
4415 */
4416static DECLCALLBACK(int) vdiBiosSetGeometry(PPDMIMEDIA pInterface, uint32_t cCylinders, uint32_t cHeads, uint32_t cSectors)
4417{
4418 PVDIDISK pData = PDMIMEDIA_2_VDIDISK(pInterface);
4419 int rc = VDIDiskSetGeometry(pData, cCylinders, cHeads, cSectors);
4420 LogFlow(("vdiBiosSetGeometry: returns %Vrc (%d,%d,%d)\n", rc, cCylinders, cHeads, cSectors));
4421 return rc;
4422}
4423
4424/**
4425 * Read bits.
4426 *
4427 * @see PDMIMEDIA::pfnRead for details.
4428 */
4429static DECLCALLBACK(int) vdiRead(PPDMIMEDIA pInterface, uint64_t off, void *pvBuf, size_t cbRead)
4430{
4431 LogFlow(("vdiRead: off=%#llx pvBuf=%p cbRead=%d\n", off, pvBuf, cbRead));
4432 PVDIDISK pData = PDMIMEDIA_2_VDIDISK(pInterface);
4433 int rc = VDIDiskRead(pData, off, pvBuf, cbRead);
4434 if (VBOX_SUCCESS(rc))
4435 Log2(("vdiRead: off=%#llx pvBuf=%p cbRead=%d\n"
4436 "%.*Vhxd\n",
4437 off, pvBuf, cbRead, cbRead, pvBuf));
4438 LogFlow(("vdiRead: returns %Vrc\n", rc));
4439 return rc;
4440}
4441
4442/**
4443 * Write bits.
4444 *
4445 * @see PDMIMEDIA::pfnWrite for details.
4446 */
4447static DECLCALLBACK(int) vdiWrite(PPDMIMEDIA pInterface, uint64_t off, const void *pvBuf, size_t cbWrite)
4448{
4449 LogFlow(("vdiWrite: off=%#llx pvBuf=%p cbWrite=%d\n", off, pvBuf, cbWrite));
4450 PVDIDISK pData = PDMIMEDIA_2_VDIDISK(pInterface);
4451 Log2(("vdiWrite: off=%#llx pvBuf=%p cbWrite=%d\n"
4452 "%.*Vhxd\n",
4453 off, pvBuf, cbWrite, cbWrite, pvBuf));
4454 int rc = VDIDiskWrite(pData, off, pvBuf, cbWrite);
4455 LogFlow(("vdiWrite: returns %Vrc\n", rc));
4456 return rc;
4457}
4458
4459/**
4460 * Flush bits to media.
4461 *
4462 * @see PDMIMEDIA::pfnFlush for details.
4463 */
4464static DECLCALLBACK(int) vdiFlush(PPDMIMEDIA pInterface)
4465{
4466 LogFlow(("vdiFlush:\n"));
4467 PVDIDISK pData = PDMIMEDIA_2_VDIDISK(pInterface);
4468 vdiFlushImage(pData->pLast);
4469 int rc = VINF_SUCCESS;
4470 LogFlow(("vdiFlush: returns %Vrc\n", rc));
4471 return rc;
4472}
4473
4474/** @copydoc PDMIMEDIA::pfnGetUuid */
4475static DECLCALLBACK(int) vdiGetUuid(PPDMIMEDIA pInterface, PRTUUID pUuid)
4476{
4477 PVDIDISK pData = PDMIMEDIA_2_VDIDISK(pInterface);
4478 int rc = VDIDiskGetImageUuid(pData, 0, pUuid);
4479 LogFlow(("vdiGetUuid: returns %Vrc ({%Vuuid})\n", rc, pUuid));
4480 return rc;
4481}
4482
4483/** @copydoc PDMIMEDIA::pfnIsReadOnly */
4484static DECLCALLBACK(bool) vdiIsReadOnly(PPDMIMEDIA pInterface)
4485{
4486 PVDIDISK pData = PDMIMEDIA_2_VDIDISK(pInterface);
4487 LogFlow(("vdiIsReadOnly: returns %d\n", VDIDiskIsReadOnly(pData)));
4488 return VDIDiskIsReadOnly(pData);
4489}
4490
4491/** @copydoc PDMIMEDIA::pfnBiosGetTranslation */
4492static DECLCALLBACK(int) vdiBiosGetTranslation(PPDMIMEDIA pInterface,
4493 PPDMBIOSTRANSLATION penmTranslation)
4494{
4495 PVDIDISK pData = PDMIMEDIA_2_VDIDISK(pInterface);
4496 int rc = VDIDiskGetTranslation(pData, penmTranslation);
4497 LogFlow(("vdiBiosGetTranslation: returns %Vrc (%d)\n", rc, *penmTranslation));
4498 return rc;
4499}
4500
4501/** @copydoc PDMIMEDIA::pfnBiosSetTranslation */
4502static DECLCALLBACK(int) vdiBiosSetTranslation(PPDMIMEDIA pInterface,
4503 PDMBIOSTRANSLATION enmTranslation)
4504{
4505 PVDIDISK pData = PDMIMEDIA_2_VDIDISK(pInterface);
4506 int rc = VDIDiskSetTranslation(pData, enmTranslation);
4507 LogFlow(("vdiBiosSetTranslation: returns %Vrc (%d)\n", rc, enmTranslation));
4508 return rc;
4509}
4510
4511
4512/**
4513 * Queries an interface to the driver.
4514 *
4515 * @returns Pointer to interface.
4516 * @returns NULL if the interface was not supported by the driver.
4517 * @param pInterface Pointer to this interface structure.
4518 * @param enmInterface The requested interface identification.
4519 * @thread Any thread.
4520 */
4521static DECLCALLBACK(void *) vdiQueryInterface(PPDMIBASE pInterface, PDMINTERFACE enmInterface)
4522{
4523 PPDMDRVINS pDrvIns = PDMIBASE_2_DRVINS(pInterface);
4524 PVDIDISK pData = PDMINS2DATA(pDrvIns, PVDIDISK);
4525 switch (enmInterface)
4526 {
4527 case PDMINTERFACE_BASE:
4528 return &pDrvIns->IBase;
4529 case PDMINTERFACE_MEDIA:
4530 return &pData->IMedia;
4531 default:
4532 return NULL;
4533 }
4534}
4535
4536
4537/**
4538 * VBox HDD driver registration record.
4539 */
4540const PDMDRVREG g_DrvVBoxHDD =
4541{
4542 /* u32Version */
4543 PDM_DRVREG_VERSION,
4544 /* szDriverName */
4545 "VBoxHDD",
4546 /* pszDescription */
4547 "VBoxHDD media driver.",
4548 /* fFlags */
4549 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
4550 /* fClass. */
4551 PDM_DRVREG_CLASS_MEDIA,
4552 /* cMaxInstances */
4553 ~0,
4554 /* cbInstance */
4555 sizeof(VDIDISK),
4556 /* pfnConstruct */
4557 vdiConstruct,
4558 /* pfnDestruct */
4559 vdiDestruct,
4560 /* pfnIOCtl */
4561 NULL,
4562 /* pfnPowerOn */
4563 NULL,
4564 /* pfnReset */
4565 NULL,
4566 /* pfnSuspend */
4567 vdiSuspend,
4568 /* pfnResume */
4569 vdiResume,
4570 /* pfnDetach */
4571 NULL
4572};
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