VirtualBox

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

最後變更 在這個檔案從729是 710,由 vboxsync 提交於 18 年 前

Moved and fixed zero data block write detection (could lead to write
being lost for situation with diff VDIs).

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

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