VirtualBox

Changeset 97839 in vbox for trunk/src/VBox/Storage


Ignore:
Timestamp:
Dec 20, 2022 9:48:25 AM (2 years ago)
Author:
vboxsync
svn:sync-xref-src-repo-rev:
154925
Message:

undo. bugref:8707

Location:
trunk/src/VBox/Storage
Files:
3 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/VBox/Storage/VMDK.cpp

    r97836 r97839  
    33 * VMDK disk image, core code.
    44 */
     5
    56/*
    67 * Copyright (C) 2006-2022 Oracle and/or its affiliates.
     
    3334#include <VBox/vd-plugin.h>
    3435#include <VBox/err.h>
     36
    3537#include <iprt/assert.h>
    3638#include <iprt/alloc.h>
     
    9294# define DKIOCUNLOCKPHYSICALEXTENTS _IO(  'd', 83)
    9395#endif /* RT_OS_DARWIN */
     96
    9497#include "VDBackends.h"
    9598
     
    98101*   Constants And Macros, Structures and Typedefs                                                                                *
    99102*********************************************************************************************************************************/
     103
    100104/** Maximum encoded string size (including NUL) we allow for VMDK images.
    101105 * Deliberately not set high to avoid running out of descriptor space. */
    102106#define VMDK_ENCODED_COMMENT_MAX 1024
     107
    103108/** VMDK descriptor DDB entry for PCHS cylinders. */
    104109#define VMDK_DDB_GEO_PCHS_CYLINDERS "ddb.geometry.cylinders"
     110
    105111/** VMDK descriptor DDB entry for PCHS heads. */
    106112#define VMDK_DDB_GEO_PCHS_HEADS "ddb.geometry.heads"
     113
    107114/** VMDK descriptor DDB entry for PCHS sectors. */
    108115#define VMDK_DDB_GEO_PCHS_SECTORS "ddb.geometry.sectors"
     116
    109117/** VMDK descriptor DDB entry for LCHS cylinders. */
    110118#define VMDK_DDB_GEO_LCHS_CYLINDERS "ddb.geometry.biosCylinders"
     119
    111120/** VMDK descriptor DDB entry for LCHS heads. */
    112121#define VMDK_DDB_GEO_LCHS_HEADS "ddb.geometry.biosHeads"
     122
    113123/** VMDK descriptor DDB entry for LCHS sectors. */
    114124#define VMDK_DDB_GEO_LCHS_SECTORS "ddb.geometry.biosSectors"
     125
    115126/** VMDK descriptor DDB entry for image UUID. */
    116127#define VMDK_DDB_IMAGE_UUID "ddb.uuid.image"
     128
    117129/** VMDK descriptor DDB entry for image modification UUID. */
    118130#define VMDK_DDB_MODIFICATION_UUID "ddb.uuid.modification"
     131
    119132/** VMDK descriptor DDB entry for parent image UUID. */
    120133#define VMDK_DDB_PARENT_UUID "ddb.uuid.parent"
     134
    121135/** VMDK descriptor DDB entry for parent image modification UUID. */
    122136#define VMDK_DDB_PARENT_MODIFICATION_UUID "ddb.uuid.parentmodification"
     137
    123138/** No compression for streamOptimized files. */
    124139#define VMDK_COMPRESSION_NONE 0
     140
    125141/** Deflate compression for streamOptimized files. */
    126142#define VMDK_COMPRESSION_DEFLATE 1
     143
    127144/** Marker that the actual GD value is stored in the footer. */
    128145#define VMDK_GD_AT_END 0xffffffffffffffffULL
     146
    129147/** Marker for end-of-stream in streamOptimized images. */
    130148#define VMDK_MARKER_EOS 0
     149
    131150/** Marker for grain table block in streamOptimized images. */
    132151#define VMDK_MARKER_GT 1
     152
    133153/** Marker for grain directory block in streamOptimized images. */
    134154#define VMDK_MARKER_GD 2
     155
    135156/** Marker for footer in streamOptimized images. */
    136157#define VMDK_MARKER_FOOTER 3
     158
    137159/** Marker for unknown purpose in streamOptimized images.
    138160 * Shows up in very recent images created by vSphere, but only sporadically.
    139161 * They "forgot" to document that one in the VMDK specification. */
    140162#define VMDK_MARKER_UNSPECIFIED 4
     163
    141164/** Dummy marker for "don't check the marker value". */
    142165#define VMDK_MARKER_IGNORE 0xffffffffU
     166
    143167/**
    144168 * Magic number for hosted images created by VMware Workstation 4, VMware
     
    146170 */
    147171#define VMDK_SPARSE_MAGICNUMBER 0x564d444b /* 'V' 'M' 'D' 'K' */
     172
    148173/** VMDK sector size in bytes. */
    149174#define VMDK_SECTOR_SIZE 512
     
    154179/** Grain table size in bytes */
    155180#define VMDK_GRAIN_TABLE_SIZE 2048
     181
    156182/**
    157183 * VMDK hosted binary extent header. The "Sparse" is a total misnomer, as
     
    181207} SparseExtentHeader;
    182208#pragma pack()
     209
    183210/** The maximum allowed descriptor size in the extent header in sectors. */
    184211#define VMDK_SPARSE_DESCRIPTOR_SIZE_MAX UINT64_C(20480) /* 10MB */
     212
    185213/** VMDK capacity for a single chunk when 2G splitting is turned on. Should be
    186214 * divisible by the default grain size (64K) */
    187215#define VMDK_2G_SPLIT_SIZE (2047 * 1024 * 1024)
     216
    188217/** VMDK streamOptimized file format marker. The type field may or may not
    189218 * be actually valid, but there's always data to read there. */
     
    196225} VMDKMARKER, *PVMDKMARKER;
    197226#pragma pack()
     227
     228
    198229/** Convert sector number/size to byte offset/size. */
    199230#define VMDK_SECTOR2BYTE(u) ((uint64_t)(u) << 9)
     231
    200232/** Convert byte offset/size to sector number/size. */
    201233#define VMDK_BYTE2SECTOR(u) ((u) >> 9)
     234
    202235/**
    203236 * VMDK extent type.
     
    214247    VMDKETYPE_VMFS
    215248} VMDKETYPE, *PVMDKETYPE;
     249
    216250/**
    217251 * VMDK access type for a extent.
     
    226260    VMDKACCESS_READWRITE
    227261} VMDKACCESS, *PVMDKACCESS;
     262
    228263/** Forward declaration for PVMDKIMAGE. */
    229264typedef struct VMDKIMAGE *PVMDKIMAGE;
     265
    230266/**
    231267 * Extents files entry. Used for opening a particular file only once.
     
    252288    struct VMDKFILE *pPrev;
    253289} VMDKFILE, *PVMDKFILE;
     290
    254291/**
    255292 * VMDK extent data structure.
     
    332369    struct VMDKIMAGE *pImage;
    333370} VMDKEXTENT, *PVMDKEXTENT;
     371
    334372/**
    335373 * Grain table cache size. Allocated per image.
    336374 */
    337375#define VMDK_GT_CACHE_SIZE 256
     376
    338377/**
    339378 * Grain table block size. Smaller than an actual grain table block to allow
     
    342381 */
    343382#define VMDK_GT_CACHELINE_SIZE 128
     383
     384
    344385/**
    345386 * Maximum number of lines in a descriptor file. Not worth the effort of
     
    349390 */
    350391#define VMDK_DESCRIPTOR_LINES_MAX   1100U
     392
    351393/**
    352394 * Parsed descriptor information. Allows easy access and update of the
     
    372414    unsigned    aNextLines[VMDK_DESCRIPTOR_LINES_MAX];
    373415} VMDKDESCRIPTOR, *PVMDKDESCRIPTOR;
     416
     417
    374418/**
    375419 * Cache entry for translating extent/sector to a sector number in that
     
    385429    uint32_t    aGTData[VMDK_GT_CACHELINE_SIZE];
    386430} VMDKGTCACHEENTRY, *PVMDKGTCACHEENTRY;
     431
    387432/**
    388433 * Cache data structure for blocks of grain table entries. For now this is a
     
    398443    unsigned            cEntries;
    399444} VMDKGTCACHE, *PVMDKGTCACHE;
     445
    400446/**
    401447 * Complete VMDK image data structure. Mainly a collection of extents and a few
     
    408454    /** Descriptor file if applicable. */
    409455    PVMDKFILE         pFile;
     456
    410457    /** Pointer to the per-disk VD interface list. */
    411458    PVDINTERFACE      pVDIfsDisk;
    412459    /** Pointer to the per-image VD interface list. */
    413460    PVDINTERFACE      pVDIfsImage;
     461
    414462    /** Error interface. */
    415463    PVDINTERFACEERROR pIfError;
    416464    /** I/O interface. */
    417465    PVDINTERFACEIOINT pIfIo;
     466
     467
    418468    /** Pointer to the image extents. */
    419469    PVMDKEXTENT     pExtents;
     
    423473     * times only once (happens mainly with raw partition access). */
    424474    PVMDKFILE       pFiles;
     475
    425476    /**
    426477     * Pointer to an array of segment entries for async I/O.
     
    432483    /** Entries available in the segments array. */
    433484    unsigned        cSegments;
     485
    434486    /** Open flags passed by VBoxHD layer. */
    435487    unsigned        uOpenFlags;
     
    450502    /** Parent image modification UUID. */
    451503    RTUUID          ParentModificationUuid;
     504
    452505    /** Pointer to grain table cache, if this image contains sparse extents. */
    453506    PVMDKGTCACHE    pGTCache;
     
    461514    VDREGIONLIST    RegionList;
    462515} VMDKIMAGE;
     516
     517
    463518/** State for the input/output callout of the inflate reader/deflate writer. */
    464519typedef struct VMDKCOMPRESSIO
     
    473528    void *pvCompGrain;
    474529} VMDKCOMPRESSIO;
     530
     531
    475532/** Tracks async grain allocation. */
    476533typedef struct VMDKGRAINALLOCASYNC
     
    494551    uint64_t    uRGTSector;
    495552} VMDKGRAINALLOCASYNC, *PVMDKGRAINALLOCASYNC;
     553
    496554/**
    497555 * State information for vmdkRename() and helpers.
     
    536594*   Static Variables                                                                                                             *
    537595*********************************************************************************************************************************/
     596
    538597/** NULL-terminated array of supported file extensions. */
    539598static const VDFILEEXTENSION s_aVmdkFileExtensions[] =
     
    542601    {NULL, VDTYPE_INVALID}
    543602};
     603
    544604/** NULL-terminated array of configuration option. */
    545605static const VDCONFIGINFO s_aVmdkConfigInfo[] =
     
    550610    { "BootSector",                     NULL,                             VDCFGVALUETYPE_BYTES,        0 },
    551611    { "Relative",                       NULL,                             VDCFGVALUETYPE_INTEGER,      0 },
     612
    552613    /* End of options list */
    553614    { NULL,                             NULL,                             VDCFGVALUETYPE_INTEGER,      0 }
     
    558619*   Internal Functions                                                                                                           *
    559620*********************************************************************************************************************************/
     621
    560622static void vmdkFreeStreamBuffers(PVMDKEXTENT pExtent);
    561623static int vmdkFreeExtentData(PVMDKIMAGE pImage, PVMDKEXTENT pExtent,
    562624                              bool fDelete);
     625
    563626static int vmdkCreateExtents(PVMDKIMAGE pImage, unsigned cExtents);
    564627static int vmdkFlushImage(PVMDKIMAGE pImage, PVDIOCTX pIoCtx);
    565628static int vmdkSetImageComment(PVMDKIMAGE pImage, const char *pszComment);
    566629static int vmdkFreeImage(PVMDKIMAGE pImage, bool fDelete, bool fFlush);
     630
    567631static DECLCALLBACK(int) vmdkAllocGrainComplete(void *pBackendData, PVDIOCTX pIoCtx,
    568632                                                void *pvUser, int rcReq);
     633
    569634/**
    570635 * Internal: open a file (using a file descriptor cache to ensure each file
     
    576641    int rc = VINF_SUCCESS;
    577642    PVMDKFILE pVmdkFile;
     643
    578644    for (pVmdkFile = pImage->pFiles;
    579645         pVmdkFile != NULL;
     
    584650            Assert(fOpen == pVmdkFile->fOpen);
    585651            pVmdkFile->uReferences++;
     652
    586653            *ppVmdkFile = pVmdkFile;
     654
    587655            return rc;
    588656        }
    589657    }
     658
    590659    /* If we get here, there's no matching entry in the cache. */
    591660    pVmdkFile = (PVMDKFILE)RTMemAllocZ(sizeof(VMDKFILE));
     
    595664        return VERR_NO_MEMORY;
    596665    }
     666
    597667    pVmdkFile->pszFilename = RTStrDup(pszFilename);
    598668    if (!pVmdkFile->pszFilename)
     
    602672        return VERR_NO_MEMORY;
    603673    }
     674
    604675    if (pszBasename)
    605676    {
     
    613684        }
    614685    }
     686
    615687    pVmdkFile->fOpen = fOpen;
     688
    616689    rc = vdIfIoIntFileOpen(pImage->pIfIo, pszFilename, fOpen,
    617690                           &pVmdkFile->pStorage);
     
    632705        *ppVmdkFile = NULL;
    633706    }
     707
    634708    return rc;
    635709}
     710
    636711/**
    637712 * Internal: close a file, updating the file descriptor cache.
     
    641716    int rc = VINF_SUCCESS;
    642717    PVMDKFILE pVmdkFile = *ppVmdkFile;
     718
    643719    AssertPtr(pVmdkFile);
     720
    644721    pVmdkFile->fDelete |= fDelete;
    645722    Assert(pVmdkFile->uReferences);
     
    649726        PVMDKFILE pPrev;
    650727        PVMDKFILE pNext;
     728
    651729        /* Unchain the element from the list. */
    652730        pPrev = pVmdkFile->pPrev;
    653731        pNext = pVmdkFile->pNext;
     732
    654733        if (pNext)
    655734            pNext->pPrev = pPrev;
     
    658737        else
    659738            pImage->pFiles = pNext;
     739
    660740        rc = vdIfIoIntFileClose(pImage->pIfIo, pVmdkFile->pStorage);
     741
    661742        bool fFileDel = pVmdkFile->fDelete;
    662743        if (   pVmdkFile->pszBasename
     
    671752                fFileDel = false;
    672753        }
     754
    673755        if (fFileDel)
    674756        {
     
    684766        RTMemFree(pVmdkFile);
    685767    }
     768
    686769    *ppVmdkFile = NULL;
    687770    return rc;
    688771}
     772
    689773/*#define VMDK_USE_BLOCK_DECOMP_API - test and enable */
    690774#ifndef VMDK_USE_BLOCK_DECOMP_API
     
    693777    VMDKCOMPRESSIO *pInflateState = (VMDKCOMPRESSIO *)pvUser;
    694778    size_t cbInjected = 0;
     779
    695780    Assert(cbBuf);
    696781    if (pInflateState->iOffset < 0)
     
    718803}
    719804#endif
     805
    720806/**
    721807 * Internal: read from a file and inflate the compressed data,
     
    733819    VMDKMARKER *pMarker = (VMDKMARKER *)pExtent->pvCompGrain;
    734820    size_t cbCompSize, cbActuallyRead;
     821
    735822    if (!pcvMarker)
    736823    {
     
    747834        pMarker->cbSize = RT_H2LE_U32(pMarker->cbSize);
    748835    }
     836
    749837    cbCompSize = RT_LE2H_U32(pMarker->cbSize);
    750838    if (cbCompSize == 0)
     
    753841        return VERR_VD_VMDK_INVALID_FORMAT;
    754842    }
     843
    755844    /* Sanity check - the expansion ratio should be much less than 2. */
    756845    Assert(cbCompSize < 2 * cbToRead);
    757846    if (cbCompSize >= 2 * cbToRead)
    758847        return VERR_VD_VMDK_INVALID_FORMAT;
     848
    759849    /* Compressed grain marker. Data follows immediately. */
    760850    rc = vdIfIoIntFileReadSync(pImage->pIfIo, pExtent->pFile->pStorage,
     
    766856                                          512)
    767857                               - RT_UOFFSETOF(VMDKMARKER, uType));
     858
    768859    if (puLBA)
    769860        *puLBA = RT_LE2H_U64(pMarker->uSector);
     
    772863                                  + RT_UOFFSETOF(VMDKMARKER, uType),
    773864                                  512);
     865
    774866#ifdef VMDK_USE_BLOCK_DECOMP_API
    775867    rc = RTZipBlockDecompress(RTZIPTYPE_ZLIB, 0 /*fFlags*/,
     
    782874    InflateState.cbCompGrain = cbCompSize + RT_UOFFSETOF(VMDKMARKER, uType);
    783875    InflateState.pvCompGrain = pExtent->pvCompGrain;
     876
    784877    rc = RTZipDecompCreate(&pZip, &InflateState, vmdkFileInflateHelper);
    785878    if (RT_FAILURE(rc))
     
    798891    return rc;
    799892}
     893
    800894static DECLCALLBACK(int) vmdkFileDeflateHelper(void *pvUser, const void *pvBuf, size_t cbBuf)
    801895{
    802896    VMDKCOMPRESSIO *pDeflateState = (VMDKCOMPRESSIO *)pvUser;
     897
    803898    Assert(cbBuf);
    804899    if (pDeflateState->iOffset < 0)
     
    817912    return VINF_SUCCESS;
    818913}
     914
    819915/**
    820916 * Internal: deflate the uncompressed data and write to a file,
     
    829925    PRTZIPCOMP pZip = NULL;
    830926    VMDKCOMPRESSIO DeflateState;
     927
    831928    DeflateState.pImage = pImage;
    832929    DeflateState.iOffset = -1;
    833930    DeflateState.cbCompGrain = pExtent->cbCompGrain;
    834931    DeflateState.pvCompGrain = pExtent->pvCompGrain;
     932
    835933    rc = RTZipCompCreate(&pZip, &DeflateState, vmdkFileDeflateHelper,
    836934                         RTZIPTYPE_ZLIB, RTZIPLEVEL_DEFAULT);
     
    845943        Assert(   DeflateState.iOffset > 0
    846944               && (size_t)DeflateState.iOffset <= DeflateState.cbCompGrain);
     945
    847946        /* pad with zeroes to get to a full sector size */
    848947        uint32_t uSize = DeflateState.iOffset;
     
    854953            uSize = uSizeAlign;
    855954        }
     955
    856956        if (pcbMarkerData)
    857957            *pcbMarkerData = uSize;
     958
    858959        /* Compressed grain marker. Data follows immediately. */
    859960        VMDKMARKER *pMarker = (VMDKMARKER *)pExtent->pvCompGrain;
     
    868969    return rc;
    869970}
     971
     972
    870973/**
    871974 * Internal: check if all files are closed, prevent leaking resources.
     
    875978    int rc = VINF_SUCCESS, rc2;
    876979    PVMDKFILE pVmdkFile;
     980
    877981    Assert(pImage->pFiles == NULL);
    878982    for (pVmdkFile = pImage->pFiles;
     
    883987                pVmdkFile->pszFilename));
    884988        pImage->pFiles = pVmdkFile->pNext;
     989
    885990        rc2 = vmdkFileClose(pImage, &pVmdkFile, pVmdkFile->fDelete);
     991
    886992        if (RT_SUCCESS(rc))
    887993            rc = rc2;
     
    889995    return rc;
    890996}
     997
    891998/**
    892999 * Internal: truncate a string (at a UTF8 code point boundary) and encode the
     
    8971004    char szEnc[VMDK_ENCODED_COMMENT_MAX + 3];
    8981005    char *pszDst = szEnc;
     1006
    8991007    AssertPtr(psz);
     1008
    9001009    for (; *psz; psz = RTStrNextCp(psz))
    9011010    {
     
    9281037    return RTStrDup(szEnc);
    9291038}
     1039
    9301040/**
    9311041 * Internal: decode a string and store it into the specified string.
     
    9351045    int rc = VINF_SUCCESS;
    9361046    char szBuf[4];
     1047
    9371048    if (!cb)
    9381049        return VERR_BUFFER_OVERFLOW;
     1050
    9391051    AssertPtr(psz);
     1052
    9401053    for (; *pszEncoded; pszEncoded = RTStrNextCp(pszEncoded))
    9411054    {
     
    9601073        else
    9611074            pszDst = RTStrPutCp(pszDst, Cp);
     1075
    9621076        /* Need to leave space for terminating NUL. */
    9631077        if ((size_t)(pszDst - szBuf) + 1 >= cb)
     
    9721086    return rc;
    9731087}
     1088
    9741089/**
    9751090 * Internal: free all buffers associated with grain directories.
     
    9881103    }
    9891104}
     1105
    9901106/**
    9911107 * Internal: allocate the compressed/uncompressed buffers for streamOptimized
     
    9951111{
    9961112    int rc = VINF_SUCCESS;
     1113
    9971114    if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
    9981115    {
     
    10131130            rc = VERR_NO_MEMORY;
    10141131    }
     1132
    10151133    if (RT_FAILURE(rc))
    10161134        vmdkFreeStreamBuffers(pExtent);
    10171135    return rc;
    10181136}
     1137
    10191138/**
    10201139 * Internal: allocate all buffers associated with grain directories.
     
    10251144    int rc = VINF_SUCCESS;
    10261145    size_t cbGD = pExtent->cGDEntries * sizeof(uint32_t);
     1146
    10271147    pExtent->pGD = (uint32_t *)RTMemAllocZ(cbGD);
    10281148    if (RT_LIKELY(pExtent->pGD))
     
    10371157    else
    10381158        rc = VERR_NO_MEMORY;
     1159
    10391160    if (RT_FAILURE(rc))
    10401161        vmdkFreeGrainDirectory(pExtent);
    10411162    return rc;
    10421163}
     1164
    10431165/**
    10441166 * Converts the grain directory from little to host endianess.
     
    10511173{
    10521174    uint32_t *pGDTmp = pGD;
     1175
    10531176    for (uint32_t i = 0; i < cGDEntries; i++, pGDTmp++)
    10541177        *pGDTmp = RT_LE2H_U32(*pGDTmp);
    10551178}
     1179
    10561180/**
    10571181 * Read the grain directory and allocated grain tables verifying them against
     
    10661190    int rc = VINF_SUCCESS;
    10671191    size_t cbGD = pExtent->cGDEntries * sizeof(uint32_t);
     1192
    10681193    AssertReturn((   pExtent->enmType == VMDKETYPE_HOSTED_SPARSE
    10691194                  && pExtent->uSectorGD != VMDK_GD_AT_END
    10701195                  && pExtent->uSectorRGD != VMDK_GD_AT_END), VERR_INTERNAL_ERROR);
     1196
    10711197    rc = vmdkAllocGrainDirectory(pImage, pExtent);
    10721198    if (RT_SUCCESS(rc))
     
    10801206        {
    10811207            vmdkGrainDirectoryConvToHost(pExtent->pGD, pExtent->cGDEntries);
     1208
    10821209            if (   pExtent->uSectorRGD
    10831210                && !(pImage->uOpenFlags & VD_OPEN_FLAGS_SKIP_CONSISTENCY_CHECKS))
     
    10911218                {
    10921219                    vmdkGrainDirectoryConvToHost(pExtent->pRGD, pExtent->cGDEntries);
     1220
    10931221                    /* Check grain table and redundant grain table for consistency. */
    10941222                    size_t cbGT = pExtent->cGTEntries * sizeof(uint32_t);
    10951223                    size_t cbGTBuffers = cbGT; /* Start with space for one GT. */
    10961224                    size_t cbGTBuffersMax = _1M;
     1225
    10971226                    uint32_t *pTmpGT1 = (uint32_t *)RTMemAlloc(cbGTBuffers);
    10981227                    uint32_t *pTmpGT2 = (uint32_t *)RTMemAlloc(cbGTBuffers);
     1228
    10991229                    if (   !pTmpGT1
    11001230                        || !pTmpGT2)
    11011231                        rc = VERR_NO_MEMORY;
     1232
    11021233                    size_t i = 0;
    11031234                    uint32_t *pGDTmp = pExtent->pGD;
    11041235                    uint32_t *pRGDTmp = pExtent->pRGD;
     1236
    11051237                    /* Loop through all entries. */
    11061238                    while (i < pExtent->cGDEntries)
     
    11091241                        uint32_t uRGTStart = *pRGDTmp;
    11101242                        size_t   cbGTRead = cbGT;
     1243
    11111244                        /* If no grain table is allocated skip the entry. */
    11121245                        if (*pGDTmp == 0 && *pRGDTmp == 0)
     
    11151248                            continue;
    11161249                        }
     1250
    11171251                        if (*pGDTmp == 0 || *pRGDTmp == 0 || *pGDTmp == *pRGDTmp)
    11181252                        {
     
    11241258                            break;
    11251259                        }
     1260
    11261261                        i++;
    11271262                        pGDTmp++;
    11281263                        pRGDTmp++;
     1264
    11291265                        /*
    11301266                         * Read a few tables at once if adjacent to decrease the number
     
    11401276                                continue;
    11411277                            }
     1278
    11421279                            if (*pGDTmp == 0 || *pRGDTmp == 0 || *pGDTmp == *pRGDTmp)
    11431280                            {
     
    11491286                                break;
    11501287                            }
     1288
    11511289                            /* Check that the start offsets are adjacent.*/
    11521290                            if (   VMDK_SECTOR2BYTE(uGTStart) + cbGTRead != VMDK_SECTOR2BYTE(*pGDTmp)
    11531291                                || VMDK_SECTOR2BYTE(uRGTStart) + cbGTRead != VMDK_SECTOR2BYTE(*pRGDTmp))
    11541292                                break;
     1293
    11551294                            i++;
    11561295                            pGDTmp++;
     
    11581297                            cbGTRead += cbGT;
    11591298                        }
     1299
    11601300                        /* Increase buffers if required. */
    11611301                        if (   RT_SUCCESS(rc)
     
    11751315                            else
    11761316                                rc = VERR_NO_MEMORY;
     1317
    11771318                            if (rc == VERR_NO_MEMORY)
    11781319                            {
     
    11811322                                i -= cbGTRead / cbGT;
    11821323                                cbGTRead = cbGT;
     1324
    11831325                                /* Don't try to increase the buffer again in the next run. */
    11841326                                cbGTBuffersMax = cbGTBuffers;
    11851327                            }
    11861328                        }
     1329
    11871330                        if (RT_SUCCESS(rc))
    11881331                        {
     
    12171360                        }
    12181361                    } /* while (i < pExtent->cGDEntries) */
     1362
    12191363                    /** @todo figure out what to do for unclean VMDKs. */
    12201364                    if (pTmpGT1)
     
    12321376                           N_("VMDK: could not read grain directory in '%s': %Rrc"), pExtent->pszFullname, rc);
    12331377    }
     1378
    12341379    if (RT_FAILURE(rc))
    12351380        vmdkFreeGrainDirectory(pExtent);
    12361381    return rc;
    12371382}
     1383
    12381384/**
    12391385 * Creates a new grain directory for the given extent at the given start sector.
     
    12541400    size_t cbGTRounded;
    12551401    uint64_t cbOverhead;
     1402
    12561403    if (fPreAlloc)
    12571404    {
     
    12671414        cbOverhead = VMDK_SECTOR2BYTE(uStartSector) + cbGDRounded;
    12681415    }
     1416
    12691417    /* For streamOptimized extents there is only one grain directory,
    12701418     * and for all others take redundant grain directory into account. */
     
    12811429        rc = vdIfIoIntFileSetSize(pImage->pIfIo, pExtent->pFile->pStorage, cbOverhead);
    12821430    }
     1431
    12831432    if (RT_SUCCESS(rc))
    12841433    {
    12851434        pExtent->uAppendPosition = cbOverhead;
    12861435        pExtent->cOverheadSectors = VMDK_BYTE2SECTOR(cbOverhead);
     1436
    12871437        if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
    12881438        {
     
    12951445            pExtent->uSectorGD = uStartSector + VMDK_BYTE2SECTOR(cbGDRounded + cbGTRounded);
    12961446        }
     1447
    12971448        rc = vmdkAllocStreamBuffers(pImage, pExtent);
    12981449        if (RT_SUCCESS(rc))
     
    13041455                uint32_t uGTSectorLE;
    13051456                uint64_t uOffsetSectors;
     1457
    13061458                if (pExtent->pRGD)
    13071459                {
     
    13231475                    }
    13241476                }
     1477
    13251478                if (RT_SUCCESS(rc))
    13261479                {
     
    13451498        }
    13461499    }
     1500
    13471501    if (RT_FAILURE(rc))
    13481502        vmdkFreeGrainDirectory(pExtent);
    13491503    return rc;
    13501504}
     1505
    13511506/**
    13521507 * Unquotes the given string returning the result in a separate buffer.
     
    13661521    char *pszQ;
    13671522    char *pszUnquoted;
     1523
    13681524    /* Skip over whitespace. */
    13691525    while (*pszStr == ' ' || *pszStr == '\t')
    13701526        pszStr++;
     1527
    13711528    if (*pszStr != '"')
    13721529    {
     
    13831540                             pImage->pszFilename, pszStart);
    13841541    }
     1542
    13851543    pszUnquoted = (char *)RTMemTmpAlloc(pszQ - pszStr + 1);
    13861544    if (!pszUnquoted)
     
    13931551    return VINF_SUCCESS;
    13941552}
     1553
    13951554static int vmdkDescInitStr(PVMDKIMAGE pImage, PVMDKDESCRIPTOR pDescriptor,
    13961555                           const char *pszLine)
     
    13981557    char *pEnd = pDescriptor->aLines[pDescriptor->cLines];
    13991558    ssize_t cbDiff = strlen(pszLine) + 1;
     1559
    14001560    if (    pDescriptor->cLines >= VMDK_DESCRIPTOR_LINES_MAX - 1
    14011561        &&  pEnd - pDescriptor->aLines[0] > (ptrdiff_t)pDescriptor->cbDescAlloc - cbDiff)
    14021562        return vdIfError(pImage->pIfError, VERR_BUFFER_OVERFLOW, RT_SRC_POS, N_("VMDK: descriptor too big in '%s'"), pImage->pszFilename);
     1563
    14031564    memcpy(pEnd, pszLine, cbDiff);
    14041565    pDescriptor->cLines++;
    14051566    pDescriptor->aLines[pDescriptor->cLines] = pEnd + cbDiff;
    14061567    pDescriptor->fDirty = true;
     1568
    14071569    return VINF_SUCCESS;
    14081570}
     1571
    14091572static bool vmdkDescGetStr(PVMDKDESCRIPTOR pDescriptor, unsigned uStart,
    14101573                           const char *pszKey, const char **ppszValue)
     
    14121575    size_t cbKey = strlen(pszKey);
    14131576    const char *pszValue;
     1577
    14141578    while (uStart != 0)
    14151579    {
     
    14301594    return !!uStart;
    14311595}
     1596
    14321597static int vmdkDescSetStr(PVMDKIMAGE pImage, PVMDKDESCRIPTOR pDescriptor,
    14331598                          unsigned uStart,
     
    14371602    size_t cbKey = strlen(pszKey);
    14381603    unsigned uLast = 0;
     1604
    14391605    while (uStart != 0)
    14401606    {
     
    14711637                > (ptrdiff_t)pDescriptor->cbDescAlloc - cbDiff)
    14721638                return vdIfError(pImage->pIfError, VERR_BUFFER_OVERFLOW, RT_SRC_POS, N_("VMDK: descriptor too big in '%s'"), pImage->pszFilename);
     1639
    14731640            memmove(pszTmp + cbNewVal, pszTmp + cbOldVal,
    14741641                    pDescriptor->aLines[pDescriptor->cLines] - pszTmp - cbOldVal);
     
    15331700        for (unsigned i = uStart + 1; i <= pDescriptor->cLines; i++)
    15341701            pDescriptor->aLines[i] += cbDiff;
     1702
    15351703        /* Adjust starting line numbers of following descriptor sections. */
    15361704        if (uStart <= pDescriptor->uFirstExtent)
     
    15421710    return VINF_SUCCESS;
    15431711}
     1712
    15441713static int vmdkDescBaseGetU32(PVMDKDESCRIPTOR pDescriptor, const char *pszKey,
    15451714                              uint32_t *puValue)
    15461715{
    15471716    const char *pszValue;
     1717
    15481718    if (!vmdkDescGetStr(pDescriptor, pDescriptor->uFirstDesc, pszKey,
    15491719                        &pszValue))
     
    15511721    return RTStrToUInt32Ex(pszValue, NULL, 10, puValue);
    15521722}
     1723
    15531724/**
    15541725 * Returns the value of the given key as a string allocating the necessary memory.
     
    15671738    const char *pszValue;
    15681739    char *pszValueUnquoted;
     1740
    15691741    if (!vmdkDescGetStr(pDescriptor, pDescriptor->uFirstDesc, pszKey,
    15701742                        &pszValue))
     
    15761748    return rc;
    15771749}
     1750
    15781751static int vmdkDescBaseSetStr(PVMDKIMAGE pImage, PVMDKDESCRIPTOR pDescriptor,
    15791752                              const char *pszKey, const char *pszValue)
    15801753{
    15811754    char *pszValueQuoted;
     1755
    15821756    RTStrAPrintf(&pszValueQuoted, "\"%s\"", pszValue);
    15831757    if (!pszValueQuoted)
     
    15881762    return rc;
    15891763}
     1764
    15901765static void vmdkDescExtRemoveDummy(PVMDKIMAGE pImage,
    15911766                                   PVMDKDESCRIPTOR pDescriptor)
     
    15941769    unsigned uEntry = pDescriptor->uFirstExtent;
    15951770    ssize_t cbDiff;
     1771
    15961772    if (!uEntry)
    15971773        return;
     1774
    15981775    cbDiff = strlen(pDescriptor->aLines[uEntry]) + 1;
    15991776    /* Move everything including \0 in the entry marking the end of buffer. */
     
    16111788    if (pDescriptor->uFirstDDB)
    16121789        pDescriptor->uFirstDDB--;
     1790
    16131791    return;
    16141792}
    1615 static void vmdkDescExtRemoveByLine(PVMDKIMAGE pImage,
    1616                                    PVMDKDESCRIPTOR pDescriptor, unsigned uLine)
    1617 {
    1618     RT_NOREF1(pImage);
    1619     unsigned uEntry = uLine;
    1620     ssize_t cbDiff;
    1621     if (!uEntry)
    1622         return;
    1623     cbDiff = strlen(pDescriptor->aLines[uEntry]) + 1;
    1624     /* Move everything including \0 in the entry marking the end of buffer. */
    1625     memmove(pDescriptor->aLines[uEntry], pDescriptor->aLines[uEntry + 1],
    1626             pDescriptor->aLines[pDescriptor->cLines] - pDescriptor->aLines[uEntry + 1] + 1);
    1627     for (unsigned i = uEntry; i <= pDescriptor->cLines; i++)
    1628     {
    1629         if (i != uEntry)
    1630             pDescriptor->aLines[i - 1] = pDescriptor->aLines[i] - cbDiff;
    1631         if (pDescriptor->aNextLines[i])
    1632             pDescriptor->aNextLines[i - 1] = pDescriptor->aNextLines[i] - 1;
    1633         else
    1634             pDescriptor->aNextLines[i - 1] = 0;
    1635     }
    1636     pDescriptor->cLines--;
    1637     if (pDescriptor->uFirstDDB)
    1638         pDescriptor->uFirstDDB--;
    1639     return;
    1640 }
     1793
    16411794static int vmdkDescExtInsert(PVMDKIMAGE pImage, PVMDKDESCRIPTOR pDescriptor,
    16421795                             VMDKACCESS enmAccess, uint64_t cNominalSectors,
     
    16501803    char szExt[1024];
    16511804    ssize_t cbDiff;
     1805
    16521806    Assert((unsigned)enmAccess < RT_ELEMENTS(apszAccess));
    16531807    Assert((unsigned)enmType < RT_ELEMENTS(apszType));
     1808
    16541809    /* Find last entry in extent description. */
    16551810    while (uStart)
     
    16591814        uStart = pDescriptor->aNextLines[uStart];
    16601815    }
     1816
    16611817    if (enmType == VMDKETYPE_ZERO)
    16621818    {
     
    16771833    }
    16781834    cbDiff = strlen(szExt) + 1;
     1835
    16791836    /* Check for buffer overflow. */
    16801837    if (   (pDescriptor->cLines >= VMDK_DESCRIPTOR_LINES_MAX - 1)
    16811838        || (  pDescriptor->aLines[pDescriptor->cLines]
    16821839            - pDescriptor->aLines[0] > (ptrdiff_t)pDescriptor->cbDescAlloc - cbDiff))
    1683     {
    1684         if ((pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_SPLIT_2G)
    1685             && !(pDescriptor->cLines >= VMDK_DESCRIPTOR_LINES_MAX - 1))
    1686         {
    1687             pImage->cbDescAlloc *= 2;
    1688             pDescriptor->cbDescAlloc *= 2;
    1689         }
    1690         else
    1691             return vdIfError(pImage->pIfError, VERR_BUFFER_OVERFLOW, RT_SRC_POS, N_("VMDK: descriptor too big in '%s'"), pImage->pszFilename);
    1692     }
     1840        return vdIfError(pImage->pIfError, VERR_BUFFER_OVERFLOW, RT_SRC_POS, N_("VMDK: descriptor too big in '%s'"), pImage->pszFilename);
    16931841
    16941842    for (unsigned i = pDescriptor->cLines + 1; i > uLast + 1; i--)
     
    17101858    for (unsigned i = uStart + 1; i <= pDescriptor->cLines; i++)
    17111859        pDescriptor->aLines[i] += cbDiff;
     1860
    17121861    /* Adjust starting line numbers of following descriptor sections. */
    17131862    if (uStart <= pDescriptor->uFirstDDB)
    17141863        pDescriptor->uFirstDDB++;
     1864
    17151865    pDescriptor->fDirty = true;
    17161866    return VINF_SUCCESS;
    17171867}
     1868
    17181869/**
    17191870 * Returns the value of the given key from the DDB as a string allocating
     
    17331884    const char *pszValue;
    17341885    char *pszValueUnquoted;
     1886
    17351887    if (!vmdkDescGetStr(pDescriptor, pDescriptor->uFirstDDB, pszKey,
    17361888                        &pszValue))
     
    17421894    return rc;
    17431895}
     1896
    17441897static int vmdkDescDDBGetU32(PVMDKIMAGE pImage, PVMDKDESCRIPTOR pDescriptor,
    17451898                             const char *pszKey, uint32_t *puValue)
     
    17471900    const char *pszValue;
    17481901    char *pszValueUnquoted;
     1902
    17491903    if (!vmdkDescGetStr(pDescriptor, pDescriptor->uFirstDDB, pszKey,
    17501904                        &pszValue))
     
    17571911    return rc;
    17581912}
     1913
    17591914static int vmdkDescDDBGetUuid(PVMDKIMAGE pImage, PVMDKDESCRIPTOR pDescriptor,
    17601915                              const char *pszKey, PRTUUID pUuid)
     
    17621917    const char *pszValue;
    17631918    char *pszValueUnquoted;
     1919
    17641920    if (!vmdkDescGetStr(pDescriptor, pDescriptor->uFirstDDB, pszKey,
    17651921                        &pszValue))
     
    17721928    return rc;
    17731929}
     1930
    17741931static int vmdkDescDDBSetStr(PVMDKIMAGE pImage, PVMDKDESCRIPTOR pDescriptor,
    17751932                             const char *pszKey, const char *pszVal)
     
    17771934    int rc;
    17781935    char *pszValQuoted;
     1936
    17791937    if (pszVal)
    17801938    {
     
    17911949    return rc;
    17921950}
     1951
    17931952static int vmdkDescDDBSetUuid(PVMDKIMAGE pImage, PVMDKDESCRIPTOR pDescriptor,
    17941953                              const char *pszKey, PCRTUUID pUuid)
    17951954{
    17961955    char *pszUuid;
     1956
    17971957    RTStrAPrintf(&pszUuid, "\"%RTuuid\"", pUuid);
    17981958    if (!pszUuid)
     
    18031963    return rc;
    18041964}
     1965
    18051966static int vmdkDescDDBSetU32(PVMDKIMAGE pImage, PVMDKDESCRIPTOR pDescriptor,
    18061967                             const char *pszKey, uint32_t uValue)
    18071968{
    18081969    char *pszValue;
     1970
    18091971    RTStrAPrintf(&pszValue, "\"%d\"", uValue);
    18101972    if (!pszValue)
     
    18151977    return rc;
    18161978}
     1979
    18171980/**
    18181981 * Splits the descriptor data into individual lines checking for correct line
     
    18281991    unsigned cLine = 0;
    18291992    int rc = VINF_SUCCESS;
     1993
    18301994    while (   RT_SUCCESS(rc)
    18311995           && *pszTmp != '\0')
     
    18382002            break;
    18392003        }
     2004
    18402005        while (*pszTmp != '\0' && *pszTmp != '\n')
    18412006        {
     
    18552020            pszTmp++;
    18562021        }
     2022
    18572023        if (RT_FAILURE(rc))
    18582024            break;
     2025
    18592026        /* Get rid of LF character. */
    18602027        if (*pszTmp == '\n')
     
    18642031        }
    18652032    }
     2033
    18662034    if (RT_SUCCESS(rc))
    18672035    {
     
    18702038        pDesc->aLines[cLine] = pszTmp;
    18712039    }
     2040
    18722041    return rc;
    18732042}
     2043
    18742044static int vmdkPreprocessDescriptor(PVMDKIMAGE pImage, char *pDescData,
    18752045                                    size_t cbDescData, PVMDKDESCRIPTOR pDescriptor)
     
    18882058        {
    18892059            unsigned uLastNonEmptyLine = 0;
     2060
    18902061            /* Initialize those, because we need to be able to reopen an image. */
    18912062            pDescriptor->uFirstDesc = 0;
     
    19532124        }
    19542125    }
     2126
    19552127    return rc;
    19562128}
     2129
    19572130static int vmdkDescSetPCHSGeometry(PVMDKIMAGE pImage,
    19582131                                   PCVDGEOMETRY pPCHSGeometry)
     
    19732146    return rc;
    19742147}
     2148
    19752149static int vmdkDescSetLCHSGeometry(PVMDKIMAGE pImage,
    19762150                                   PCVDGEOMETRY pLCHSGeometry)
     
    19832157    rc = vmdkDescDDBSetU32(pImage, &pImage->Descriptor,
    19842158                           VMDK_DDB_GEO_LCHS_HEADS,
     2159
    19852160                           pLCHSGeometry->cHeads);
    19862161    if (RT_FAILURE(rc))
     
    19912166    return rc;
    19922167}
     2168
    19932169static int vmdkCreateDescriptor(PVMDKIMAGE pImage, char *pDescData,
    19942170                                size_t cbDescData, PVMDKDESCRIPTOR pDescriptor)
     
    20022178    pDescriptor->aLines[pDescriptor->cLines] = pDescData;
    20032179    memset(pDescriptor->aNextLines, '\0', sizeof(pDescriptor->aNextLines));
     2180
    20042181    int rc = vmdkDescInitStr(pImage, pDescriptor, "# Disk DescriptorFile");
    20052182    if (RT_SUCCESS(rc))
     
    20332210    {
    20342211        pDescriptor->uFirstDDB = pDescriptor->cLines - 1;
     2212
    20352213        /* Now that the framework is in place, use the normal functions to insert
    20362214         * the remaining keys. */
     
    20452223    if (RT_SUCCESS(rc))
    20462224        rc = vmdkDescDDBSetStr(pImage, pDescriptor, "ddb.adapterType", "ide");
     2225
    20472226    return rc;
    20482227}
     2228
    20492229static int vmdkParseDescriptor(PVMDKIMAGE pImage, char *pDescData, size_t cbDescData)
    20502230{
     
    20532233    unsigned uLine;
    20542234    unsigned i;
     2235
    20552236    rc = vmdkPreprocessDescriptor(pImage, pDescData, cbDescData,
    20562237                                  &pImage->Descriptor);
    20572238    if (RT_FAILURE(rc))
    20582239        return rc;
     2240
    20592241    /* Check version, must be 1. */
    20602242    uint32_t uVersion;
     
    20642246    if (uVersion != 1)
    20652247        return vdIfError(pImage->pIfError, VERR_VD_VMDK_UNSUPPORTED_VERSION, RT_SRC_POS, N_("VMDK: unsupported format version in descriptor in '%s'"), pImage->pszFilename);
     2248
    20662249    /* Get image creation type and determine image flags. */
    20672250    char *pszCreateType = NULL;   /* initialized to make gcc shut up */
     
    20812264        pImage->uImageFlags |= VD_IMAGE_FLAGS_FIXED | VD_VMDK_IMAGE_FLAGS_ESX;
    20822265    RTMemTmpFree(pszCreateType);
     2266
    20832267    /* Count the number of extent config entries. */
    20842268    for (uLine = pImage->Descriptor.uFirstExtent, cExtents = 0;
     
    20862270         uLine = pImage->Descriptor.aNextLines[uLine], cExtents++)
    20872271        /* nothing */;
     2272
    20882273    if (!pImage->pDescData && cExtents != 1)
    20892274    {
     
    20912276        return vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: monolithic image may only have one extent in '%s'"), pImage->pszFilename);
    20922277    }
     2278
    20932279    if (pImage->pDescData)
    20942280    {
     
    20982284            return rc;
    20992285    }
     2286
    21002287    for (i = 0, uLine = pImage->Descriptor.uFirstExtent;
    21012288         i < cExtents; i++, uLine = pImage->Descriptor.aNextLines[uLine])
    21022289    {
    21032290        char *pszLine = pImage->Descriptor.aLines[uLine];
     2291
    21042292        /* Access type of the extent. */
    21052293        if (!strncmp(pszLine, "RW", 2))
     
    21222310        if (*pszLine++ != ' ')
    21232311            return vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: parse error in extent description in '%s'"), pImage->pszFilename);
     2312
    21242313        /* Nominal size of the extent. */
    21252314        rc = RTStrToUInt64Ex(pszLine, &pszLine, 10,
     
    21292318        if (*pszLine++ != ' ')
    21302319            return vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: parse error in extent description in '%s'"), pImage->pszFilename);
     2320
    21312321        /* Type of the extent. */
    21322322        if (!strncmp(pszLine, "SPARSE", 6))
     
    21522342        else
    21532343            return vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: parse error in extent description in '%s'"), pImage->pszFilename);
     2344
    21542345        if (pImage->pExtents[i].enmType == VMDKETYPE_ZERO)
    21552346        {
     
    21662357            if (*pszLine++ != ' ')
    21672358                return vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: parse error in extent description in '%s'"), pImage->pszFilename);
     2359
    21682360            /* Basename of the image. Surrounded by quotes. */
    21692361            char *pszBasename;
     
    21842376                }
    21852377            }
     2378
    21862379            if (*pszLine != '\0')
    21872380                return vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: parse error in extent description in '%s'"), pImage->pszFilename);
    21882381        }
    21892382    }
     2383
    21902384    /* Determine PCHS geometry (autogenerate if necessary). */
    21912385    rc = vmdkDescDDBGetU32(pImage, &pImage->Descriptor,
     
    22222416        pImage->PCHSGeometry.cSectors = 63;
    22232417    }
     2418
    22242419    /* Determine LCHS geometry (set to 0 if not specified). */
    22252420    rc = vmdkDescDDBGetU32(pImage, &pImage->Descriptor,
     
    22522447        pImage->LCHSGeometry.cSectors = 0;
    22532448    }
     2449
    22542450    /* Get image UUID. */
    22552451    rc = vmdkDescDDBGetUuid(pImage, &pImage->Descriptor, VMDK_DDB_IMAGE_UUID,
     
    22752471    else if (RT_FAILURE(rc))
    22762472        return rc;
     2473
    22772474    /* Get image modification UUID. */
    22782475    rc = vmdkDescDDBGetUuid(pImage, &pImage->Descriptor,
     
    23002497    else if (RT_FAILURE(rc))
    23012498        return rc;
     2499
    23022500    /* Get UUID of parent image. */
    23032501    rc = vmdkDescDDBGetUuid(pImage, &pImage->Descriptor, VMDK_DDB_PARENT_UUID,
     
    23232521    else if (RT_FAILURE(rc))
    23242522        return rc;
     2523
    23252524    /* Get parent image modification UUID. */
    23262525    rc = vmdkDescDDBGetUuid(pImage, &pImage->Descriptor,
     
    23462545    else if (RT_FAILURE(rc))
    23472546        return rc;
     2547
    23482548    return VINF_SUCCESS;
    23492549}
     2550
    23502551/**
    23512552 * Internal : Prepares the descriptor to write to the image.
     
    23552556{
    23562557    int rc = VINF_SUCCESS;
     2558
    23572559    /*
    23582560     * Allocate temporary descriptor buffer.
     
    23632565    char *pszDescriptor = (char *)RTMemAllocZ(cbDescriptor);
    23642566    size_t offDescriptor = 0;
     2567
    23652568    if (!pszDescriptor)
    23662569        return VERR_NO_MEMORY;
     2570
    23672571    for (unsigned i = 0; i < pImage->Descriptor.cLines; i++)
    23682572    {
    23692573        const char *psz = pImage->Descriptor.aLines[i];
    23702574        size_t cb = strlen(psz);
     2575
    23712576        /*
    23722577         * Increase the descriptor if there is no limit and
     
    23842589                char *pszDescriptorNew = NULL;
    23852590                LogFlow(("Increasing descriptor cache\n"));
     2591
    23862592                pszDescriptorNew = (char *)RTMemRealloc(pszDescriptor, cbDescriptor + cb + 4 * _1K);
    23872593                if (!pszDescriptorNew)
     
    23942600            }
    23952601        }
     2602
    23962603        if (cb > 0)
    23972604        {
     
    23992606            offDescriptor += cb;
    24002607        }
     2608
    24012609        memcpy(pszDescriptor + offDescriptor, "\n", 1);
    24022610        offDescriptor++;
    24032611    }
     2612
    24042613    if (RT_SUCCESS(rc))
    24052614    {
     
    24092618    else if (pszDescriptor)
    24102619        RTMemFree(pszDescriptor);
     2620
    24112621    return rc;
    24122622}
     2623
    24132624/**
    24142625 * Internal: write/update the descriptor part of the image.
     
    24222633    void *pvDescriptor = NULL;
    24232634    size_t cbDescriptor;
     2635
    24242636    if (pImage->pDescData)
    24252637    {
     
    24392651    if (pDescFile == NULL)
    24402652        return VERR_INVALID_PARAMETER;
     2653
    24412654    rc = vmdkDescriptorPrepare(pImage, cbLimit, &pvDescriptor, &cbDescriptor);
    24422655    if (RT_SUCCESS(rc))
     
    24502663            rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error writing descriptor in '%s'"), pImage->pszFilename);
    24512664    }
     2665
    24522666    if (RT_SUCCESS(rc) && !cbLimit)
    24532667    {
     
    24562670            rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: error truncating descriptor in '%s'"), pImage->pszFilename);
    24572671    }
     2672
    24582673    if (RT_SUCCESS(rc))
    24592674        pImage->Descriptor.fDirty = false;
     2675
    24602676    if (pvDescriptor)
    24612677        RTMemFree(pvDescriptor);
    24622678    return rc;
    2463 }
     2679
     2680}
     2681
    24642682/**
    24652683 * Internal: validate the consistency check values in a binary header.
     
    24952713    return rc;
    24962714}
     2715
    24972716/**
    24982717 * Internal: read metadata belonging to an extent with binary header, i.e.
     
    25042723    SparseExtentHeader Header;
    25052724    int rc;
     2725
    25062726    if (!fMagicAlreadyRead)
    25072727        rc = vdIfIoIntFileReadSync(pImage->pIfIo, pExtent->pFile->pStorage, 0,
     
    25162736                                   - RT_UOFFSETOF(SparseExtentHeader, version));
    25172737    }
     2738
    25182739    if (RT_SUCCESS(rc))
    25192740    {
     
    25222743        {
    25232744            uint64_t cbFile = 0;
     2745
    25242746            if (    (RT_LE2H_U32(Header.flags) & RT_BIT(17))
    25252747                &&  RT_LE2H_U64(Header.gdOffset) == VMDK_GD_AT_END)
    25262748                pExtent->fFooter = true;
     2749
    25272750            if (   !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
    25282751                || (   pExtent->fFooter
     
    25332756                    rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: cannot get size of '%s'"), pExtent->pszFullname);
    25342757            }
     2758
    25352759            if (RT_SUCCESS(rc))
    25362760            {
    25372761                if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
    25382762                    pExtent->uAppendPosition = RT_ALIGN_64(cbFile, 512);
     2763
    25392764                if (   pExtent->fFooter
    25402765                    && (   !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
     
    25502775                        rc = VERR_VD_VMDK_INVALID_HEADER;
    25512776                    }
     2777
    25522778                    if (RT_SUCCESS(rc))
    25532779                        rc = vmdkValidateHeader(pImage, pExtent, &Header);
     
    25552781                    pExtent->uAppendPosition = 0;
    25562782                }
     2783
    25572784                if (RT_SUCCESS(rc))
    25582785                {
     
    25772804                        pExtent->uSectorRGD     = 0;
    25782805                    }
     2806
    25792807                    if (pExtent->uDescriptorSector && !pExtent->cDescriptorSectors)
    25802808                        rc = vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS,
    25812809                                       N_("VMDK: inconsistent embedded descriptor config in '%s'"), pExtent->pszFullname);
     2810
    25822811                    if (   RT_SUCCESS(rc)
    25832812                        && (   pExtent->uSectorGD == VMDK_GD_AT_END
     
    25872816                        rc = vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS,
    25882817                                       N_("VMDK: cannot resolve grain directory offset in '%s'"), pExtent->pszFullname);
     2818
    25892819                    if (RT_SUCCESS(rc))
    25902820                    {
     
    25972827                            pExtent->cSectorsPerGDE = cSectorsPerGDE;
    25982828                            pExtent->cGDEntries = (pExtent->cSectors + cSectorsPerGDE - 1) / cSectorsPerGDE;
     2829
    25992830                            /* Fix up the number of descriptor sectors, as some flat images have
    26002831                             * really just one, and this causes failures when inserting the UUID
     
    26192850        rc = VERR_VD_VMDK_INVALID_HEADER;
    26202851    }
     2852
    26212853    if (RT_FAILURE(rc))
    26222854        vmdkFreeExtentData(pImage, pExtent, false);
     2855
    26232856    return rc;
    26242857}
     2858
    26252859/**
    26262860 * Internal: read additional metadata belonging to an extent. For those
     
    26302864{
    26312865    int rc = VINF_SUCCESS;
     2866
    26322867/* disabled the check as there are too many truncated vmdk images out there */
    26332868#ifdef VBOX_WITH_VMDK_STRICT_SIZE_CHECK
     
    26692904                    if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
    26702905                        pExtent->uAppendPosition = 0;
     2906
    26712907                    if (   !(pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
    26722908                        || !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
     
    26822918        }
    26832919    }
     2920
    26842921    if (RT_FAILURE(rc))
    26852922        vmdkFreeExtentData(pImage, pExtent, false);
     2923
    26862924    return rc;
    26872925}
     2926
    26882927/**
    26892928 * Internal: write/update the metadata for a sparse extent.
     
    26932932{
    26942933    SparseExtentHeader Header;
     2934
    26952935    memset(&Header, '\0', sizeof(Header));
    26962936    Header.magicNumber = RT_H2LE_U32(VMDK_SPARSE_MAGICNUMBER);
     
    27352975    Header.doubleEndLineChar2 = '\n';
    27362976    Header.compressAlgorithm = RT_H2LE_U16(pExtent->uCompression);
     2977
    27372978    int rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pExtent->pFile->pStorage,
    27382979                                    uOffset, &Header, sizeof(Header),
     
    27422983    return rc;
    27432984}
     2985
    27442986/**
    27452987 * Internal: free the buffers used for streamOptimized images.
     
    27583000    }
    27593001}
     3002
    27603003/**
    27613004 * Internal: free the memory used by the extent data structure, optionally
     
    27713014{
    27723015    int rc = VINF_SUCCESS;
     3016
    27733017    vmdkFreeGrainDirectory(pExtent);
    27743018    if (pExtent->pDescData)
     
    27973041    }
    27983042    vmdkFreeStreamBuffers(pExtent);
     3043
    27993044    return rc;
    28003045}
     3046
    28013047/**
    28023048 * Internal: allocate grain table cache if necessary for this image.
     
    28053051{
    28063052    PVMDKEXTENT pExtent;
     3053
    28073054    /* Allocate grain table cache if any sparse extent is present. */
    28083055    for (unsigned i = 0; i < pImage->cExtents; i++)
     
    28243071        }
    28253072    }
     3073
    28263074    return VINF_SUCCESS;
    28273075}
     3076
    28283077/**
    28293078 * Internal: allocate the given number of extents.
     
    28533102    else
    28543103        rc = VERR_NO_MEMORY;
     3104
    28553105    return rc;
    28563106}
    28573107
    28583108/**
    2859  * Internal: Create an additional file backed extent in split images.
    2860  * Supports split sparse and flat images.
    2861  *
    2862  * @returns VBox status code.
    2863  * @param   pImage              VMDK image instance.
    2864  * @param   cbSize              Desiried size in bytes of new extent.
     3109 * Internal: allocate and describes an additional, file-backed extent
     3110 * for the given size. Preserves original extents.
    28653111 */
    28663112static int vmdkAddFileBackedExtent(PVMDKIMAGE pImage, uint64_t cbSize)
    28673113{
    28683114    int rc = VINF_SUCCESS;
    2869     unsigned uImageFlags = pImage->uImageFlags;
    2870 
    2871     /* Check for unsupported image type. */
    2872     if ((uImageFlags & VD_VMDK_IMAGE_FLAGS_ESX)
    2873         || (uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
    2874         || (uImageFlags & VD_VMDK_IMAGE_FLAGS_RAWDISK))
    2875     {
    2876         return VERR_NOT_SUPPORTED;
    2877     }
    2878 
    2879     /* Allocate array of extents and copy existing extents to it. */
    28803115    PVMDKEXTENT pNewExtents = (PVMDKEXTENT)RTMemAllocZ((pImage->cExtents + 1) * sizeof(VMDKEXTENT));
    2881     if (!pNewExtents)
    2882     {
    2883         return VERR_NO_MEMORY;
    2884     }
    2885 
    2886     memcpy(pNewExtents, pImage->pExtents, pImage->cExtents * sizeof(VMDKEXTENT));
    2887     /** @todo r=jack - free old extent pointer */
    2888 
    2889     /* Locate newly created extent and populate default metadata. */
    2890     PVMDKEXTENT pExtent = &pNewExtents[pImage->cExtents];
    2891 
    2892     pExtent->pFile = NULL;
    2893     pExtent->pszBasename = NULL;
    2894     pExtent->pszFullname = NULL;
    2895     pExtent->pGD = NULL;
    2896     pExtent->pRGD = NULL;
    2897     pExtent->pDescData = NULL;
    2898     pExtent->uVersion = 1;
    2899     pExtent->uCompression = VMDK_COMPRESSION_NONE;
    2900     pExtent->uExtent = pImage->cExtents;
    2901     pExtent->pImage = pImage;
    2902     pExtent->cNominalSectors = VMDK_BYTE2SECTOR(cbSize);
    2903     pExtent->enmAccess = VMDKACCESS_READWRITE;
    2904     pExtent->uSectorOffset = 0;
    2905     pExtent->fMetaDirty = true;
    2906 
    2907     /* Apply image type specific meta data. */
    2908     if (uImageFlags & VD_IMAGE_FLAGS_FIXED)
    2909     {
     3116    if (pNewExtents)
     3117    {
     3118        memcpy(pNewExtents, pImage->pExtents, pImage->cExtents * sizeof(VMDKEXTENT));
     3119        PVMDKEXTENT pExtent = &pNewExtents[pImage->cExtents];
     3120
     3121        pExtent->pFile = NULL;
     3122        pExtent->pszBasename = NULL;
     3123        pExtent->pszFullname = NULL;
     3124        pExtent->pGD = NULL;
     3125        pExtent->pRGD = NULL;
     3126        pExtent->pDescData = NULL;
     3127        pExtent->uVersion = 1;
     3128        pExtent->uCompression = VMDK_COMPRESSION_NONE;
     3129        pExtent->uExtent = pImage->cExtents;
     3130        pExtent->pImage = pImage;
     3131        pExtent->cNominalSectors = VMDK_BYTE2SECTOR(cbSize);
    29103132        pExtent->enmType = VMDKETYPE_FLAT;
    2911     }
    2912     else
    2913     {
    2914         uint64_t cSectorsPerGDE, cSectorsPerGD;
    2915         pExtent->enmType = VMDKETYPE_HOSTED_SPARSE;
    2916         pExtent->cSectors = VMDK_BYTE2SECTOR(RT_ALIGN_64(cbSize, _64K));
    2917         pExtent->cSectorsPerGrain = VMDK_BYTE2SECTOR(_64K);
    2918         pExtent->cGTEntries = 512;
    2919         cSectorsPerGDE = pExtent->cGTEntries * pExtent->cSectorsPerGrain;
    2920         pExtent->cSectorsPerGDE = cSectorsPerGDE;
    2921         pExtent->cGDEntries = (pExtent->cSectors + cSectorsPerGDE - 1) / cSectorsPerGDE;
    2922         cSectorsPerGD = (pExtent->cGDEntries + (512 / sizeof(uint32_t) - 1)) / (512 / sizeof(uint32_t));
    2923     }
    2924 
    2925     /* Allocate and set file name for extent. */
    2926     char *pszBasenameSubstr = RTPathFilename(pImage->pszFilename);
    2927     AssertPtr(pszBasenameSubstr);
    2928 
    2929     char *pszBasenameSuff = RTPathSuffix(pszBasenameSubstr);
    2930     char *pszBasenameBase = RTStrDup(pszBasenameSubstr);
    2931     RTPathStripSuffix(pszBasenameBase);
    2932     char *pszTmp;
    2933     size_t cbTmp;
    2934 
    2935     if (pImage->uImageFlags & VD_IMAGE_FLAGS_FIXED)
    2936         RTStrAPrintf(&pszTmp, "%s-f%03d%s", pszBasenameBase,
    2937                         pExtent->uExtent + 1, pszBasenameSuff);
    2938     else
    2939         RTStrAPrintf(&pszTmp, "%s-s%03d%s", pszBasenameBase, pExtent->uExtent + 1,
    2940                         pszBasenameSuff);
    2941 
    2942     RTStrFree(pszBasenameBase);
    2943     if (!pszTmp)
    2944         return VERR_NO_STR_MEMORY;
    2945     cbTmp = strlen(pszTmp) + 1;
    2946     char *pszBasename = (char *)RTMemTmpAlloc(cbTmp);
    2947     if (!pszBasename)
    2948     {
     3133        pExtent->enmAccess = VMDKACCESS_READWRITE;
     3134        pExtent->uSectorOffset = 0;
     3135
     3136        char *pszBasenameSubstr = RTPathFilename(pImage->pszFilename);
     3137        AssertPtr(pszBasenameSubstr);
     3138
     3139        char *pszBasenameSuff = RTPathSuffix(pszBasenameSubstr);
     3140        char *pszBasenameBase = RTStrDup(pszBasenameSubstr);
     3141        RTPathStripSuffix(pszBasenameBase);
     3142        char *pszTmp;
     3143        size_t cbTmp;
     3144
     3145        if (pImage->uImageFlags & VD_IMAGE_FLAGS_FIXED)
     3146            RTStrAPrintf(&pszTmp, "%s-f%03d%s", pszBasenameBase,
     3147                         pExtent->uExtent + 1, pszBasenameSuff);
     3148        else
     3149            RTStrAPrintf(&pszTmp, "%s-s%03d%s", pszBasenameBase, pExtent->uExtent + 1,
     3150                         pszBasenameSuff);
     3151
     3152        RTStrFree(pszBasenameBase);
     3153        if (!pszTmp)
     3154            return VERR_NO_STR_MEMORY;
     3155        cbTmp = strlen(pszTmp) + 1;
     3156        char *pszBasename = (char *)RTMemTmpAlloc(cbTmp);
     3157        if (!pszBasename)
     3158        {
     3159            RTStrFree(pszTmp);
     3160            return VERR_NO_MEMORY;
     3161        }
     3162
     3163        memcpy(pszBasename, pszTmp, cbTmp);
    29493164        RTStrFree(pszTmp);
    2950         return VERR_NO_MEMORY;
    2951     }
    2952 
    2953     memcpy(pszBasename, pszTmp, cbTmp);
    2954     RTStrFree(pszTmp);
    2955 
    2956     pExtent->pszBasename = pszBasename;
    2957 
    2958     char *pszBasedirectory = RTStrDup(pImage->pszFilename);
    2959     if (!pszBasedirectory)
    2960         return VERR_NO_STR_MEMORY;
    2961     RTPathStripFilename(pszBasedirectory);
    2962     char *pszFullname = RTPathJoinA(pszBasedirectory, pExtent->pszBasename);
    2963     RTStrFree(pszBasedirectory);
    2964     if (!pszFullname)
    2965         return VERR_NO_STR_MEMORY;
    2966     pExtent->pszFullname = pszFullname;
    2967 
    2968     /* Create file for extent. */
    2969     rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszBasename, pExtent->pszFullname,
    2970                         VDOpenFlagsToFileOpenFlags(pImage->uOpenFlags,
    2971                                                     true /* fCreate */));
    2972     if (RT_FAILURE(rc))
    2973         return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not create new file '%s'"), pExtent->pszFullname);
    2974 
    2975     if (uImageFlags & VD_IMAGE_FLAGS_FIXED)
    2976     {
    2977         /* For flat images: Pre allocate file space. */
     3165
     3166        pExtent->pszBasename = pszBasename;
     3167
     3168        char *pszBasedirectory = RTStrDup(pImage->pszFilename);
     3169        if (!pszBasedirectory)
     3170            return VERR_NO_STR_MEMORY;
     3171        RTPathStripFilename(pszBasedirectory);
     3172        char *pszFullname = RTPathJoinA(pszBasedirectory, pExtent->pszBasename);
     3173        RTStrFree(pszBasedirectory);
     3174        if (!pszFullname)
     3175            return VERR_NO_STR_MEMORY;
     3176        pExtent->pszFullname = pszFullname;
     3177
     3178        /* Create file for extent. */
     3179        rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszBasename, pExtent->pszFullname,
     3180                          VDOpenFlagsToFileOpenFlags(pImage->uOpenFlags,
     3181                                                     true /* fCreate */));
     3182        if (RT_FAILURE(rc))
     3183            return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not create new file '%s'"), pExtent->pszFullname);
     3184
     3185        rc = vmdkDescExtInsert(pImage, &pImage->Descriptor, pExtent->enmAccess,
     3186                               pExtent->cNominalSectors, pExtent->enmType,
     3187                               pExtent->pszBasename, pExtent->uSectorOffset);
     3188        if (RT_FAILURE(rc))
     3189            return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not insert the extent list into descriptor in '%s'"), pImage->pszFilename);
     3190
    29783191        rc = vdIfIoIntFileSetAllocationSize(pImage->pIfIo, pExtent->pFile->pStorage, cbSize,
    29793192                                            0 /* fFlags */, NULL, 0, 0);
     3193
    29803194        if (RT_FAILURE(rc))
    29813195            return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not set size of new file '%s'"), pExtent->pszFullname);
     3196
     3197        pImage->pExtents = pNewExtents;
     3198        pImage->cExtents++;
    29823199    }
    29833200    else
    2984     {
    2985         /* For sparse images: Allocate new grain directories/tables. */
    2986         /* fPreAlloc should never be false because VMware can't use such images. */
    2987         rc = vmdkCreateGrainDirectory(pImage, pExtent,
    2988                                       RT_MAX( pExtent->uDescriptorSector
    2989                                               + pExtent->cDescriptorSectors,
    2990                                               1),
    2991                                       true /* fPreAlloc */);
    2992         if (RT_FAILURE(rc))
    2993             return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not create new grain directory in '%s'"), pExtent->pszFullname);
    2994     }
    2995 
    2996     /* Insert new extent into descriptor file. */
    2997     rc = vmdkDescExtInsert(pImage, &pImage->Descriptor, pExtent->enmAccess,
    2998                            pExtent->cNominalSectors, pExtent->enmType,
    2999                            pExtent->pszBasename, pExtent->uSectorOffset);
    3000     if (RT_FAILURE(rc))
    3001         return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not insert the extent list into descriptor in '%s'"), pImage->pszFilename);
    3002 
    3003     pImage->pExtents = pNewExtents;
    3004     pImage->cExtents++;
    3005 
     3201        rc = VERR_NO_MEMORY;
    30063202    return rc;
    30073203}
    3008 
    30093204/**
    30103205 * Reads and processes the descriptor embedded in sparse images.
     
    30543249                {
    30553250                    uint64_t cDescriptorSectorsOld = pExtent->cDescriptorSectors;
     3251
    30563252                    pExtent->cDescriptorSectors = 4;
    30573253                    if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
     
    31183314            rc = VERR_NO_MEMORY;
    31193315    }
     3316
    31203317    return rc;
    31213318}
     3319
    31223320/**
    31233321 * Reads the descriptor from a pure text file.
     
    32063404                        else
    32073405                            pExtent->pszFullname = NULL;
     3406
    32083407                        unsigned uOpenFlags = pImage->uOpenFlags | ((pExtent->enmAccess == VMDKACCESS_READONLY) ? VD_OPEN_FLAGS_READONLY : 0);
    32093408                        switch (pExtent->enmType)
     
    32263425                                if (RT_FAILURE(rc))
    32273426                                    break;
     3427
    32283428                                /* Mark extent as unclean if opened in read-write mode. */
    32293429                                if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
     
    32623462    else if (RT_SUCCESS(rc))
    32633463        rc = vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS, N_("VMDK: descriptor in '%s' is too short"), pImage->pszFilename);
     3464
    32643465    return rc;
    32653466}
     3467
    32663468/**
    32673469 * Read and process the descriptor based on the image type.
     
    32743476{
    32753477    uint32_t u32Magic;
     3478
    32763479    /* Read magic (if present). */
    32773480    int rc = vdIfIoIntFileReadSync(pImage->pIfIo, pFile->pStorage, 0,
     
    32903493        rc = VERR_VD_VMDK_INVALID_HEADER;
    32913494    }
     3495
    32923496    return rc;
    32933497}
     3498
    32943499/**
    32953500 * Internal: Open an image, constructing all necessary data structures.
     
    33013506    pImage->pIfIo      = VDIfIoIntGet(pImage->pVDIfsImage);
    33023507    AssertPtrReturn(pImage->pIfIo, VERR_INVALID_PARAMETER);
     3508
    33033509    /*
    33043510     * Open the image.
     
    33133519    {
    33143520        pImage->pFile = pFile;
     3521
    33153522        rc = vmdkDescriptorRead(pImage, pFile);
    33163523        if (RT_SUCCESS(rc))
     
    33303537                }
    33313538            }
     3539
    33323540            /* Update the image metadata now in case has changed. */
    33333541            rc = vmdkFlushImage(pImage, NULL);
     
    33493557                             ||  pExtent->enmType == VMDKETYPE_ZERO)
    33503558                        pImage->uImageFlags |= VD_IMAGE_FLAGS_FIXED;
     3559
    33513560                    pImage->cbSize += VMDK_SECTOR2BYTE(pExtent->cNominalSectors);
    33523561                }
     3562
    33533563                if (   !(pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
    33543564                    || !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
     
    33603570    /* else: Do NOT signal an appropriate error here, as the VD layer has the
    33613571     *       choice of retrying the open if it failed. */
     3572
    33623573    if (RT_SUCCESS(rc))
    33633574    {
     
    33653576        pImage->RegionList.fFlags   = 0;
    33663577        pImage->RegionList.cRegions = 1;
     3578
    33673579        pRegion->offRegion            = 0; /* Disk start. */
    33683580        pRegion->cbBlock              = 512;
     
    33773589    return rc;
    33783590}
     3591
    33793592/**
    33803593 * Frees a raw descriptor.
     
    33853598    if (!pRawDesc)
    33863599        return VINF_SUCCESS;
     3600
    33873601    RTStrFree(pRawDesc->pszRawDisk);
    33883602    pRawDesc->pszRawDisk = NULL;
     3603
    33893604    /* Partitions: */
    33903605    for (unsigned i = 0; i < pRawDesc->cPartDescs; i++)
     
    33923607        RTStrFree(pRawDesc->pPartDescs[i].pszRawDevice);
    33933608        pRawDesc->pPartDescs[i].pszRawDevice = NULL;
     3609
    33943610        RTMemFree(pRawDesc->pPartDescs[i].pvPartitionData);
    33953611        pRawDesc->pPartDescs[i].pvPartitionData = NULL;
    33963612    }
     3613
    33973614    RTMemFree(pRawDesc->pPartDescs);
    33983615    pRawDesc->pPartDescs = NULL;
     3616
    33993617    RTMemFree(pRawDesc);
    34003618    return VINF_SUCCESS;
    34013619}
     3620
    34023621/**
    34033622 * Helper that grows the raw partition descriptor table by @a cToAdd entries,
     
    34163635        pRawDesc->cPartDescs = cNew;
    34173636        pRawDesc->pPartDescs = paNew;
     3637
    34183638        *ppRet = &paNew[cOld];
    34193639        return VINF_SUCCESS;
     
    34243644                     pImage->pszFilename, cOld, cNew);
    34253645}
     3646
    34263647/**
    34273648 * @callback_method_impl{FNRTSORTCMP}
     
    34333654    return iDelta < 0 ? -1 : iDelta > 0 ? 1 : 0;
    34343655}
     3656
    34353657/**
    34363658 * Post processes the partition descriptors.
     
    34443666     */
    34453667    RTSortShell(pRawDesc->pPartDescs, pRawDesc->cPartDescs, sizeof(pRawDesc->pPartDescs[0]), vmdkRawDescPartComp, NULL);
     3668
    34463669    /*
    34473670     * Check that we don't have overlapping descriptors.  If we do, that's an
     
    34583681                             paPartDescs[i].pvPartitionData ? " (data)" : "");
    34593682        offLast -= 1;
     3683
    34603684        if (i + 1 < pRawDesc->cPartDescs && offLast >= paPartDescs[i + 1].offStartInVDisk)
    34613685            return vdIfError(pImage->pIfError, VERR_FILESYSTEM_CORRUPT /*?*/, RT_SRC_POS,
     
    34703694                             paPartDescs[i].pvPartitionData ? " (data)" : "", cbSize);
    34713695    }
     3696
    34723697    return VINF_SUCCESS;
    34733698}
     3699
     3700
    34743701#ifdef RT_OS_LINUX
    34753702/**
     
    34943721    size_t const cchDir = RTPathEnsureTrailingSeparator(pszBlockDevDir, cbBlockDevDir);
    34953722    AssertReturn(cchDir > 0, VERR_BUFFER_OVERFLOW);
     3723
    34963724    RTDIR hDir = NIL_RTDIR;
    34973725    int rc = RTDirOpen(&hDir, pszBlockDevDir);
     
    35113739                    rc = RTStrCopy(&pszBlockDevDir[cchDir], cbBlockDevDir - cchDir, Entry.szName);
    35123740                    AssertContinue(RT_SUCCESS(rc)); /* should not happen! */
     3741
    35133742                    dev_t uThisDevNo = ~uDevToLocate;
    35143743                    rc = RTLinuxSysFsReadDevNumFile(&uThisDevNo, "%s/dev", pszBlockDevDir);
     
    35403769}
    35413770#endif /* RT_OS_LINUX */
     3771
    35423772#ifdef RT_OS_FREEBSD
     3773
     3774
    35433775/**
    35443776 * Reads the config data from the provider and returns offset and size
     
    35533785    gconfig *pConfEntry;
    35543786    int rc = VERR_NOT_FOUND;
     3787
    35553788    /*
    35563789     * Required parameters are located in the list containing key/value pairs.
     
    35833816    return rc;
    35843817}
     3818
     3819
    35853820/**
    35863821 * Searches the partition specified by name and calculates its size and absolute offset.
     
    36013836    AssertReturn(pcbAbsoluteOffset,  VERR_INVALID_PARAMETER);
    36023837    AssertReturn(pcbSize,            VERR_INVALID_PARAMETER);
     3838
    36033839    ggeom *pParentGeom;
    36043840    int rc = VERR_NOT_FOUND;
     
    36133849    if (RT_FAILURE(rc))
    36143850        return rc;
     3851
    36153852    gprovider *pProvider;
    36163853    /*
     
    36243861            return vmdkReadPartitionsParamsFromProvider(pProvider, pcbAbsoluteOffset, pcbSize);
    36253862    }
     3863
    36263864    /*
    36273865     * No provider found. Go over the parent geom again
     
    36333871     * provider
    36343872     */
     3873
    36353874    LIST_FOREACH(pProvider, &pParentGeom->lg_provider, lg_provider)
    36363875    {
     
    36403879        if (RT_FAILURE(rc))
    36413880            return rc;
     3881
    36423882        uint64_t cbProviderOffset = 0;
    36433883        uint64_t cbProviderSize = 0;
     
    36503890        }
    36513891    }
     3892
    36523893    return VERR_NOT_FOUND;
    36533894}
    36543895#endif
     3896
     3897
    36553898/**
    36563899 * Attempts to verify the raw partition path.
     
    36623905{
    36633906    RT_NOREF(pImage, pPartDesc, idxPartition, pszRawDrive, hRawDrive, cbSector, hVol);
     3907
    36643908    /*
    36653909     * Try open the raw partition device.
     
    36713915                         N_("VMDK: Image path: '%s'. Failed to open partition #%u on '%s' via '%s' (%Rrc)"),
    36723916                         pImage->pszFilename, idxPartition, pszRawDrive, pPartDesc->pszRawDevice, rc);
     3917
    36733918    /*
    36743919     * Compare the partition UUID if we can get it.
     
    36763921#ifdef RT_OS_WINDOWS
    36773922    DWORD cbReturned;
     3923
    36783924    /* 1. Get the device numbers for both handles, they should have the same disk. */
    36793925    STORAGE_DEVICE_NUMBER DevNum1;
     
    36843930                       N_("VMDK: Image path: '%s'. IOCTL_STORAGE_GET_DEVICE_NUMBER failed on '%s': %u"),
    36853931                       pImage->pszFilename, pszRawDrive, GetLastError());
     3932
    36863933    STORAGE_DEVICE_NUMBER DevNum2;
    36873934    RT_ZERO(DevNum2);
     
    37754022            rc = VERR_NO_TMP_MEMORY;
    37764023    }
     4024
    37774025#elif defined(RT_OS_LINUX)
    37784026    RT_NOREF(hVol);
     4027
    37794028    /* Stat the two devices first to get their device numbers.  (We probably
    37804029       could make some assumptions here about the major & minor number assignments
     
    37974046        {
    37984047            rc = vmdkFindSysBlockDevPath(pImage, szSysPath, sizeof(szSysPath), StDrive.st_rdev, pszRawDrive);
     4048
    37994049            /* Now, scan the directories under that again for a partition device
    38004050               matching the hRawPart device's number: */
    38014051            if (RT_SUCCESS(rc))
    38024052                rc = vmdkFindSysBlockDevPath(pImage, szSysPath, sizeof(szSysPath), StPart.st_rdev, pPartDesc->pszRawDevice);
     4053
    38034054            /* Having found the /sys/block/device/partition/ path, we can finally
    38044055               read the partition attributes and compare with hVol. */
     
    38134064                                   pImage->pszFilename, idxPartition, pPartDesc->pszRawDevice, pszRawDrive, iLnxPartition, idxPartition);
    38144065                /* else: ignore failure? */
     4066
    38154067                /* start offset: */
    38164068                uint32_t const cbLnxSector = 512; /* It's hardcoded in the Linux kernel */
     
    38264078                    /* else: ignore failure? */
    38274079                }
     4080
    38284081                /* the size: */
    38294082                if (RT_SUCCESS(rc))
     
    38424095        /* else: We've got nothing to work on, so only do content comparison. */
    38434096    }
     4097
    38444098#elif defined(RT_OS_FREEBSD)
    38454099    char szDriveDevName[256];
     
    38724126                rc = vdIfError(pImage->pIfError, VERR_GENERAL_FAILURE, RT_SRC_POS,
    38734127                               N_("VMDK: Image path: '%s'. 'PART' class not found in the GEOM tree"), pImage->pszFilename);
     4128
     4129
    38744130            if (RT_SUCCESS(rc))
    38754131            {
     
    38944150                                   pImage->pszFilename, pPartDesc->pszRawDevice, pszRawDrive, rc);
    38954151            }
     4152
    38964153            geom_deletetree(&geomMesh);
    38974154        }
     
    39004157                           N_("VMDK: Image path: '%s'. geom_gettree failed: %d"), pImage->pszFilename, err);
    39014158    }
     4159
    39024160#elif defined(RT_OS_SOLARIS)
    39034161    RT_NOREF(hVol);
     4162
    39044163    dk_cinfo dkiDriveInfo;
    39054164    dk_cinfo dkiPartInfo;
     
    39494208             * using another way. If there is an error, it returns errno which will be handled below.
    39504209             */
     4210
    39514211            uint32_t numPartition = (uint32_t)dkiPartInfo.dki_partition;
    39524212            if (numPartition > NDKMAP)
     
    39834243                           N_("VMDK: Image path: '%s'. Partition #%u path ('%s') verification failed on '%s': Start offset %RI64, expected %RU64"),
    39844244                           pImage->pszFilename, idxPartition, pPartDesc->pszRawDevice, pszRawDrive, cbOffset, pPartDesc->offStartInVDisk);
     4245
    39854246        if (RT_SUCCESS(rc) && cbSize != pPartDesc->cbData)
    39864247            rc = vdIfError(pImage->pIfError, VERR_MISMATCH, RT_SRC_POS,
     
    40584319#else
    40594320    RT_NOREF(hVol); /* PORTME */
     4321    rc = VERR_NOT_SUPPORTED;
    40604322#endif
    40614323    if (RT_SUCCESS(rc))
     
    40734335        {
    40744336            uint8_t *pbSector2 = pbSector1 + cbToCompare;
     4337
    40754338            /* Do the comparing, we repeat if it fails and the data might be volatile. */
    40764339            uint64_t uPrevCrc1 = 0;
     
    40884351                        {
    40894352                            rc = VERR_MISMATCH;
     4353
    40904354                            /* Do data stability checks before repeating: */
    40914355                            uint64_t const uCrc1 = RTCrc64(pbSector1, cbToCompare);
     
    41204384                    offMissmatch++;
    41214385                int cbSample = (int)RT_MIN(cbToCompare - offMissmatch, 16);
     4386
    41224387                if (cStable > 0)
    41234388                    rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS,
     
    41334398                }
    41344399            }
     4400
    41354401            RTMemTmpFree(pbSector1);
    41364402        }
     
    41434409    return rc;
    41444410}
     4411
    41454412#ifdef RT_OS_WINDOWS
    41464413/**
     
    41644431}
    41654432#endif /* RT_OS_WINDOWS */
     4433
    41664434/**
    41674435 * Worker for vmdkMakeRawDescriptor that adds partition descriptors when the
     
    41804448{
    41814449    *phVolToRelease = NIL_RTDVMVOLUME;
     4450
    41824451    /* Check sanity/understanding. */
    41834452    Assert(fPartitions);
    41844453    Assert((fPartitions & fPartitionsReadOnly) == fPartitionsReadOnly); /* RO should be a sub-set */
     4454
    41854455    /*
    41864456     * Allocate on descriptor for each volume up front.
    41874457     */
    41884458    uint32_t const cVolumes = RTDvmMapGetValidVolumes(hVolMgr);
     4459
    41894460    PVDISKRAWPARTDESC paPartDescs = NULL;
    41904461    int rc = vmdkRawDescAppendPartDesc(pImage, pRawDesc, cVolumes, &paPartDescs);
    41914462    AssertRCReturn(rc, rc);
     4463
    41924464    /*
    41934465     * Enumerate the partitions (volumes) on the disk and create descriptors for each of them.
     
    42124484        Assert(cRefs != UINT32_MAX); RT_NOREF(cRefs);
    42134485        *phVolToRelease = hVol = hVolNext;
     4486
    42144487        /*
    42154488         * Depending on the fPartitions selector and associated read-only mask,
     
    42184491         */
    42194492        paPartDescs[i].cbData = RTDvmVolumeGetSize(hVol);
     4493
    42204494        uint64_t offVolumeEndIgnored = 0;
    42214495        rc = RTDvmVolumeQueryRange(hVol, &paPartDescs[i].offStartInVDisk, &offVolumeEndIgnored);
     
    42254499                             pImage->pszFilename, i, pszRawDrive, rc);
    42264500        Assert(paPartDescs[i].cbData == offVolumeEndIgnored + 1 - paPartDescs[i].offStartInVDisk);
     4501
    42274502        /* Note! The index must match IHostDrivePartition::number. */
    42284503        uint32_t idxPartition = RTDvmVolumeGetIndex(hVol, RTDVMVOLIDX_HOST);
     
    42334508            if (fPartitionsReadOnly & RT_BIT_32(idxPartition))
    42344509                paPartDescs[i].uFlags |= VDISKRAW_READONLY;
     4510
    42354511            if (!fRelative)
    42364512            {
     
    42534529                 */
    42544530                paPartDescs[i].offStartInDevice = 0;
     4531
    42554532#if defined(RT_OS_DARWIN) || defined(RT_OS_FREEBSD)
    42564533                /* /dev/rdisk1 -> /dev/rdisk1s2 (s=slice) */
     
    43064583#endif
    43074584                AssertPtrReturn(paPartDescs[i].pszRawDevice, VERR_NO_STR_MEMORY);
     4585
    43084586                rc = vmdkRawDescVerifyPartitionPath(pImage, &paPartDescs[i], idxPartition, pszRawDrive, hRawDrive, cbSector, hVol);
    43094587                AssertRCReturn(rc, rc);
     
    43174595        }
    43184596    } /* for each volume */
     4597
    43194598    RTDvmVolumeRelease(hVol);
    43204599    *phVolToRelease = NIL_RTDVMVOLUME;
     4600
    43214601    /*
    43224602     * Check that we found all the partitions the user selected.
     
    43334613                             pImage->pszFilename, pszRawDrive, szLeft);
    43344614    }
     4615
    43354616    return VINF_SUCCESS;
    43364617}
     4618
    43374619/**
    43384620 * Worker for vmdkMakeRawDescriptor that adds partition descriptors with copies
     
    43654647                         pImage->pszFilename, pszRawDrive, rc);
    43664648    AssertReturn(cLocations > 0 && cLocations < _16M, VERR_INTERNAL_ERROR_5);
     4649
    43674650    /* We can allocate the partition descriptors here to save an intentation level. */
    43684651    PVDISKRAWPARTDESC paPartDescs = NULL;
    43694652    rc = vmdkRawDescAppendPartDesc(pImage, pRawDesc, (uint32_t)cLocations, &paPartDescs);
    43704653    AssertRCReturn(rc, rc);
     4654
    43714655    /* Allocate the result table and repeat the location table query: */
    43724656    PRTDVMTABLELOCATION paLocations = (PRTDVMTABLELOCATION)RTMemAllocZ(sizeof(paLocations[0]) * cLocations);
     
    44484732    return rc;
    44494733}
     4734
    44504735/**
    44514736 * Opens the volume manager for the raw drive when in selected-partition mode.
     
    44634748{
    44644749    *phVolMgr = NIL_RTDVM;
     4750
    44654751    RTVFSFILE hVfsFile = NIL_RTVFSFILE;
    44664752    int rc = RTVfsFileFromRTFile(hRawDrive, RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE, true /*fLeaveOpen*/, &hVfsFile);
     
    44694755                         N_("VMDK: Image path: '%s'.  RTVfsFileFromRTFile failed for '%s' handle (%Rrc)"),
    44704756                         pImage->pszFilename, pszRawDrive, rc);
     4757
    44714758    RTDVM hVolMgr = NIL_RTDVM;
    44724759    rc = RTDvmCreate(&hVolMgr, hVfsFile, cbSector, 0 /*fFlags*/);
     4760
    44734761    RTVfsFileRelease(hVfsFile);
     4762
    44744763    if (RT_FAILURE(rc))
    44754764        return vdIfError(pImage->pIfError, rc, RT_SRC_POS,
    44764765                         N_("VMDK: Image path: '%s'. Failed to create volume manager instance for '%s' (%Rrc)"),
    44774766                         pImage->pszFilename, pszRawDrive, rc);
     4767
    44784768    rc = RTDvmMapOpen(hVolMgr);
    44794769    if (RT_SUCCESS(rc))
     
    44864776                     pImage->pszFilename, pszRawDrive, rc);
    44874777}
     4778
    44884779/**
    44894780 * Opens the raw drive device and get the sizes for it.
     
    45094800                         N_("VMDK: Image path: '%s'. Failed to open the raw drive '%s' for reading (%Rrc)"),
    45104801                         pImage->pszFilename, pszRawDrive, rc);
     4802
    45114803    /*
    45124804     * Get the sector size.
     
    45574849    return rc;
    45584850}
     4851
    45594852/**
    45604853 * Reads the raw disk configuration, leaving initalization and cleanup to the
     
    45734866        return vdIfError(pImage->pIfError, VERR_INVALID_PARAMETER, RT_SRC_POS,
    45744867                         N_("VMDK: Image path: '%s'. Getting config interface failed"), pImage->pszFilename);
     4868
    45754869    /*
    45764870     * RawDrive = path
     
    45814875                         N_("VMDK: Image path: '%s'. Getting 'RawDrive' configuration failed (%Rrc)"), pImage->pszFilename, rc);
    45824876    AssertPtrReturn(*ppszRawDrive, VERR_INTERNAL_ERROR_3);
     4877
    45834878    /*
    45844879     * Partitions=n[r][,...]
     
    45864881    uint32_t const cMaxPartitionBits = sizeof(*pfPartitions) * 8 /* ASSUMES 8 bits per char */;
    45874882    *pfPartitions = *pfPartitionsReadOnly = 0;
     4883
    45884884    rc = VDCFGQueryStringAlloc(pImgCfg, "Partitions", ppszFreeMe);
    45894885    if (RT_SUCCESS(rc))
     
    46194915                                 pImage->pszFilename, psz);
    46204916        }
     4917
    46214918        RTStrFree(*ppszFreeMe);
    46224919        *ppszFreeMe = NULL;
     
    46254922        return vdIfError(pImage->pIfError, rc, RT_SRC_POS,
    46264923                         N_("VMDK: Image path: '%s'. Getting 'Partitions' configuration failed (%Rrc)"), pImage->pszFilename, rc);
     4924
    46274925    /*
    46284926     * BootSector=base64
     
    46444942                             N_("VMDK: Image path: '%s'. Custom bootsector for '%s' is way too big: %zu bytes, max 4MB"),
    46454943                             pImage->pszFilename, *ppszRawDrive, cbBootSector);
     4944
    46464945        /* Refuse the boot sector if whole-drive.  This used to be done quietly,
    46474946           however, bird disagrees and thinks the user should be told that what
     
    46524951                             N_("VMDK: Image path: '%s'. Custom bootsector for '%s' is not supported for whole-drive configurations, only when selecting partitions"),
    46534952                             pImage->pszFilename, *ppszRawDrive);
     4953
    46544954        *pcbBootSector = (size_t)cbBootSector;
    46554955        *ppvBootSector = RTMemAlloc((size_t)cbBootSector);
     
    46584958                             N_("VMDK: Image path: '%s'. Failed to allocate %zd bytes for the custom bootsector for '%s'"),
    46594959                             pImage->pszFilename, cbBootSector, *ppszRawDrive);
     4960
    46604961        rc = RTBase64Decode(*ppszFreeMe, *ppvBootSector, cbBootSector, NULL /*pcbActual*/, NULL /*ppszEnd*/);
    46614962        if (RT_FAILURE(rc))
     
    46634964                              N_("VMDK: Image path: '%s'. Base64 decoding of the custom boot sector for '%s' failed (%Rrc)"),
    46644965                              pImage->pszFilename, *ppszRawDrive, rc);
     4966
    46654967        RTStrFree(*ppszFreeMe);
    46664968        *ppszFreeMe = NULL;
     
    46694971        return vdIfError(pImage->pIfError, rc, RT_SRC_POS,
    46704972                         N_("VMDK: Image path: '%s'. Getting 'BootSector' configuration failed (%Rrc)"), pImage->pszFilename, rc);
     4973
    46714974    /*
    46724975     * Relative=0/1
     
    46964999        *pfRelative = false;
    46975000#endif
     5001
    46985002    return VINF_SUCCESS;
    46995003}
     5004
    47005005/**
    47015006 * Creates a raw drive (nee disk) descriptor.
     
    47165021    /* Make sure it's NULL. */
    47175022    *ppRaw = NULL;
     5023
    47185024    /*
    47195025     * Read the configuration.
     
    47405046        if (RT_SUCCESS(rc))
    47415047        {
     5048            pImage->cbSize = cbSize;
    47425049            /*
    47435050             * Create the raw-drive descriptor
     
    47675074                    //pRawDesc->cPartDescs = 0;
    47685075                    //pRawDesc->pPartDescs = NULL;
     5076
    47695077                    /* We need to parse the partition map to complete the descriptor: */
    47705078                    RTDVM hVolMgr = NIL_RTDVM;
     
    47785086                            pRawDesc->enmPartitioningType = enmFormatType == RTDVMFORMATTYPE_MBR
    47795087                                                          ? VDISKPARTTYPE_MBR : VDISKPARTTYPE_GPT;
     5088
    47805089                            /* Add copies of the partition tables:  */
    47815090                            rc = vmdkRawDescDoCopyPartitionTables(pImage, hVolMgr, pRawDesc, pszRawDrive, hRawDrive,
     
    47895098                                                             fPartitions, fPartitionsReadOnly, fRelative, &hVolRelease);
    47905099                                RTDvmVolumeRelease(hVolRelease);
     5100
    47915101                                /* Finally, sort the partition and check consistency (overlaps, etc): */
    47925102                                if (RT_SUCCESS(rc))
     
    48325142    return rc;
    48335143}
     5144
    48345145/**
    48355146 * Internal: create VMDK images for raw disk/partition access.
     
    48405151    int rc = VINF_SUCCESS;
    48415152    PVMDKEXTENT pExtent;
     5153
    48425154    if (pRaw->uFlags & VDISKRAW_DISK)
    48435155    {
     
    48545166        if (RT_FAILURE(rc))
    48555167            return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not create new file '%s'"), pImage->pszFilename);
     5168
    48565169        /* Set up basename for extent description. Cannot use StrDup. */
    48575170        size_t cbBasename = strlen(pRaw->pszRawDisk) + 1;
     
    48705183        pExtent->enmAccess = (pRaw->uFlags & VDISKRAW_READONLY) ? VMDKACCESS_READONLY : VMDKACCESS_READWRITE;
    48715184        pExtent->fMetaDirty = false;
     5185
    48725186        /* Open flat image, the raw disk. */
    48735187        rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszBasename, pExtent->pszFullname,
     
    48825196         * file, write the partition information to a flat extent and
    48835197         * open all the (flat) raw disk partitions. */
     5198
    48845199        /* First pass over the partition data areas to determine how many
    48855200         * extents we need. One data area can require up to 2 extents, as
     
    48935208                return vdIfError(pImage->pIfError, VERR_INVALID_PARAMETER, RT_SRC_POS,
    48945209                                 N_("VMDK: incorrect partition data area ordering set up by the caller in '%s'"), pImage->pszFilename);
     5210
    48955211            if (uStart < pPart->offStartInVDisk)
    48965212                cExtents++;
     
    49015217        if (uStart != cbSize)
    49025218            cExtents++;
     5219
    49035220        rc = vmdkCreateExtents(pImage, cExtents);
    49045221        if (RT_FAILURE(rc))
    49055222            return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not create new extent list in '%s'"), pImage->pszFilename);
     5223
    49065224        /* Create raw partition descriptor file. */
    49075225        rc = vmdkFileOpen(pImage, &pImage->pFile, NULL, pImage->pszFilename,
     
    49105228        if (RT_FAILURE(rc))
    49115229            return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not create new file '%s'"), pImage->pszFilename);
     5230
    49125231        /* Create base filename for the partition table extent. */
    49135232        /** @todo remove fixed buffer without creating memory leaks. */
     
    49245243                    pszBaseBase, pszSuff);
    49255244        RTStrFree(pszBaseBase);
     5245
    49265246        /* Second pass over the partitions, now define all extents. */
    49275247        uint64_t uPartOffset = 0;
     
    49325252            PVDISKRAWPARTDESC pPart = &pRaw->pPartDescs[i];
    49335253            pExtent = &pImage->pExtents[cExtents++];
     5254
    49345255            if (uStart < pPart->offStartInVDisk)
    49355256            {
     
    49455266            }
    49465267            uStart = pPart->offStartInVDisk + pPart->cbData;
     5268
    49475269            if (pPart->pvPartitionData)
    49485270            {
     
    49545276                memcpy(pszBasename, pszPartition, cbBasename);
    49555277                pExtent->pszBasename = pszBasename;
     5278
    49565279                /* Set up full name for partition extent. */
    49575280                char *pszDirname = RTStrDup(pImage->pszFilename);
     
    49695292                pExtent->enmAccess = VMDKACCESS_READWRITE;
    49705293                pExtent->fMetaDirty = false;
     5294
    49715295                /* Create partition table flat image. */
    49725296                rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszBasename, pExtent->pszFullname,
     
    50035327                    pExtent->enmAccess = (pPart->uFlags & VDISKRAW_READONLY) ? VMDKACCESS_READONLY : VMDKACCESS_READWRITE;
    50045328                    pExtent->fMetaDirty = false;
     5329
    50055330                    /* Open flat image, the raw partition. */
    50065331                    rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszBasename, pExtent->pszFullname,
     
    50355360        }
    50365361    }
     5362
    50375363    rc = vmdkDescBaseSetStr(pImage, &pImage->Descriptor, "createType",
    50385364                            (pRaw->uFlags & VDISKRAW_DISK) ?
     
    50425368    return rc;
    50435369}
     5370
    50445371/**
    50455372 * Internal: create a regular (i.e. file-backed) VMDK image.
     
    50535380    uint64_t cbOffset = 0;
    50545381    uint64_t cbRemaining = cbSize;
     5382
    50555383    if (uImageFlags & VD_VMDK_IMAGE_FLAGS_SPLIT_2G)
    50565384    {
     
    50645392    if (RT_FAILURE(rc))
    50655393        return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not create new extent list in '%s'"), pImage->pszFilename);
     5394
    50665395    /* Basename strings needed for constructing the extent names. */
    50675396    char *pszBasenameSubstr = RTPathFilename(pImage->pszFilename);
    50685397    AssertPtr(pszBasenameSubstr);
    50695398    size_t cbBasenameSubstr = strlen(pszBasenameSubstr) + 1;
     5399
    50705400    /* Create separate descriptor file if necessary. */
    50715401    if (cExtents != 1 || (uImageFlags & VD_IMAGE_FLAGS_FIXED))
     
    50795409    else
    50805410        pImage->pFile = NULL;
     5411
    50815412    /* Set up all extents. */
    50825413    for (unsigned i = 0; i < cExtents; i++)
     
    50845415        PVMDKEXTENT pExtent = &pImage->pExtents[i];
    50855416        uint64_t cbExtent = cbRemaining;
     5417
    50865418        /* Set up fullname/basename for extent description. Cannot use StrDup
    50875419         * for basename, as it is not guaranteed that the memory can be freed
     
    51405472            return VERR_NO_STR_MEMORY;
    51415473        pExtent->pszFullname = pszFullname;
     5474
    51425475        /* Create file for extent. */
    51435476        rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszBasename, pExtent->pszFullname,
     
    51555488                return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not set size of new file '%s'"), pExtent->pszFullname);
    51565489        }
     5490
    51575491        /* Place descriptor file information (where integrated). */
    51585492        if (cExtents == 1 && !(uImageFlags & VD_IMAGE_FLAGS_FIXED))
     
    51645498            pImage->pDescData = NULL;
    51655499        }
     5500
    51665501        if (!(uImageFlags & VD_IMAGE_FLAGS_FIXED))
    51675502        {
     
    51915526                pExtent->enmType = VMDKETYPE_FLAT;
    51925527        }
     5528
    51935529        pExtent->enmAccess = VMDKACCESS_READWRITE;
    51945530        pExtent->fUncleanShutdown = true;
     
    51965532        pExtent->uSectorOffset = 0;
    51975533        pExtent->fMetaDirty = true;
     5534
    51985535        if (!(uImageFlags & VD_IMAGE_FLAGS_FIXED))
    51995536        {
     
    52075544                return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not create new grain directory in '%s'"), pExtent->pszFullname);
    52085545        }
     5546
    52095547        cbOffset += cbExtent;
     5548
    52105549        if (RT_SUCCESS(rc))
    52115550            vdIfProgress(pIfProgress, uPercentStart + cbOffset * uPercentSpan / cbSize);
     5551
    52125552        cbRemaining -= cbExtent;
    52135553    }
     5554
    52145555    if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_ESX)
    52155556    {
     
    52205561            return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not set controller type to lsilogic in '%s'"), pImage->pszFilename);
    52215562    }
     5563
    52225564    const char *pszDescType = NULL;
    52235565    if (uImageFlags & VD_IMAGE_FLAGS_FIXED)
     
    52455587    return rc;
    52465588}
     5589
    52475590/**
    52485591 * Internal: Create a real stream optimized VMDK using only linear writes.
     
    52535596    if (RT_FAILURE(rc))
    52545597        return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not create new extent list in '%s'"), pImage->pszFilename);
     5598
    52555599    /* Basename strings needed for constructing the extent names. */
    52565600    const char *pszBasenameSubstr = RTPathFilename(pImage->pszFilename);
    52575601    AssertPtr(pszBasenameSubstr);
    52585602    size_t cbBasenameSubstr = strlen(pszBasenameSubstr) + 1;
     5603
    52595604    /* No separate descriptor file. */
    52605605    pImage->pFile = NULL;
     5606
    52615607    /* Set up all extents. */
    52625608    PVMDKEXTENT pExtent = &pImage->pExtents[0];
     5609
    52635610    /* Set up fullname/basename for extent description. Cannot use StrDup
    52645611     * for basename, as it is not guaranteed that the memory can be freed
     
    52705617    memcpy(pszBasename, pszBasenameSubstr, cbBasenameSubstr);
    52715618    pExtent->pszBasename = pszBasename;
     5619
    52725620    char *pszBasedirectory = RTStrDup(pImage->pszFilename);
    52735621    RTPathStripFilename(pszBasedirectory);
     
    52775625        return VERR_NO_STR_MEMORY;
    52785626    pExtent->pszFullname = pszFullname;
     5627
    52795628    /* Create file for extent. Make it write only, no reading allowed. */
    52805629    rc = vmdkFileOpen(pImage, &pExtent->pFile, pExtent->pszBasename, pExtent->pszFullname,
     
    52845633    if (RT_FAILURE(rc))
    52855634        return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not create new file '%s'"), pExtent->pszFullname);
     5635
    52865636    /* Place descriptor file information. */
    52875637    pExtent->uDescriptorSector = 1;
     
    52905640    pExtent->pDescData = pImage->pDescData;
    52915641    pImage->pDescData = NULL;
     5642
    52925643    uint64_t cSectorsPerGDE, cSectorsPerGD;
    52935644    pExtent->enmType = VMDKETYPE_HOSTED_SPARSE;
     
    52995650    pExtent->cGDEntries = (pExtent->cSectors + cSectorsPerGDE - 1) / cSectorsPerGDE;
    53005651    cSectorsPerGD = (pExtent->cGDEntries + (512 / sizeof(uint32_t) - 1)) / (512 / sizeof(uint32_t));
     5652
    53015653    /* The spec says version is 1 for all VMDKs, but the vast
    53025654     * majority of streamOptimized VMDKs actually contain
     
    53055657    pExtent->uCompression = VMDK_COMPRESSION_DEFLATE;
    53065658    pExtent->fFooter = true;
     5659
    53075660    pExtent->enmAccess = VMDKACCESS_READONLY;
    53085661    pExtent->fUncleanShutdown = false;
     
    53105663    pExtent->uSectorOffset = 0;
    53115664    pExtent->fMetaDirty = true;
     5665
    53125666    /* Create grain directory, without preallocating it straight away. It will
    53135667     * be constructed on the fly when writing out the data and written when
     
    53185672    if (RT_FAILURE(rc))
    53195673        return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not create new grain directory in '%s'"), pExtent->pszFullname);
     5674
    53205675    rc = vmdkDescBaseSetStr(pImage, &pImage->Descriptor, "createType",
    53215676                            "streamOptimized");
    53225677    if (RT_FAILURE(rc))
    53235678        rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not set the image type in '%s'"), pImage->pszFilename);
     5679
    53245680    return rc;
    53255681}
     5682
    53265683/**
    53275684 * Initializes the UUID fields in the DDB.
     
    53595716        rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS,
    53605717                       N_("VMDK: error storing image UUID in new descriptor in '%s'"), pImage->pszFilename);
     5718
    53615719    return rc;
    53625720}
     5721
    53635722/**
    53645723 * Internal: The actual code for creating any VMDK variant currently in
     
    53735732{
    53745733    pImage->uImageFlags = uImageFlags;
     5734
    53755735    pImage->pIfError = VDIfErrorGet(pImage->pVDIfsDisk);
    53765736    pImage->pIfIo = VDIfIoIntGet(pImage->pVDIfsImage);
    53775737    AssertPtrReturn(pImage->pIfIo, VERR_INVALID_PARAMETER);
     5738
    53785739    int rc = vmdkCreateDescriptor(pImage, pImage->pDescData, pImage->cbDescAlloc,
    53795740                                  &pImage->Descriptor);
     
    53865747            rc = vmdkMakeRawDescriptor(pImage, &pRaw);
    53875748            if (RT_FAILURE(rc))
    5388                 return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could get raw descriptor for '%s'"), pImage->pszFilename);
     5749                return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not create raw descriptor for '%s'"),
     5750                    pImage->pszFilename);
     5751            if (!cbSize)
     5752                cbSize = pImage->cbSize;
     5753
    53895754            rc = vmdkCreateRawImage(pImage, pRaw, cbSize);
    53905755            vmdkRawDescFree(pRaw);
     
    54025767                                        uPercentSpan * 95 / 100);
    54035768        }
     5769
    54045770        if (RT_SUCCESS(rc))
    54055771        {
    54065772            vdIfProgress(pIfProgress, uPercentStart + uPercentSpan * 98 / 100);
     5773
    54075774            pImage->cbSize = cbSize;
     5775
    54085776            for (unsigned i = 0; i < pImage->cExtents; i++)
    54095777            {
    54105778                PVMDKEXTENT pExtent = &pImage->pExtents[i];
     5779
    54115780                rc = vmdkDescExtInsert(pImage, &pImage->Descriptor, pExtent->enmAccess,
    54125781                                       pExtent->cNominalSectors, pExtent->enmType,
     
    54185787                }
    54195788            }
     5789
    54205790            if (RT_SUCCESS(rc))
    54215791                vmdkDescExtRemoveDummy(pImage, &pImage->Descriptor);
    5422             if (   RT_SUCCESS(rc)
    5423                 && pPCHSGeometry->cCylinders != 0
    5424                 && pPCHSGeometry->cHeads != 0
    5425                 && pPCHSGeometry->cSectors != 0)
    5426                 rc = vmdkDescSetPCHSGeometry(pImage, pPCHSGeometry);
     5792
     5793            pImage->LCHSGeometry = *pLCHSGeometry;
     5794            pImage->PCHSGeometry = *pPCHSGeometry;
     5795
     5796            if (RT_SUCCESS(rc))
     5797            {
     5798                if (   pPCHSGeometry->cCylinders != 0
     5799                    && pPCHSGeometry->cHeads != 0
     5800                    && pPCHSGeometry->cSectors != 0)
     5801                    rc = vmdkDescSetPCHSGeometry(pImage, pPCHSGeometry);
     5802                else if (uImageFlags & VD_VMDK_IMAGE_FLAGS_RAWDISK)
     5803                {
     5804                    VDGEOMETRY RawDiskPCHSGeometry;
     5805                    RawDiskPCHSGeometry.cCylinders = (uint32_t)RT_MIN(pImage->cbSize / 512 / 16 / 63, 16383);
     5806                    RawDiskPCHSGeometry.cHeads = 16;
     5807                    RawDiskPCHSGeometry.cSectors = 63;
     5808                    rc = vmdkDescSetPCHSGeometry(pImage, &RawDiskPCHSGeometry);
     5809                }
     5810            }
     5811
    54275812            if (   RT_SUCCESS(rc)
    54285813                && pLCHSGeometry->cCylinders != 0
     
    54305815                && pLCHSGeometry->cSectors != 0)
    54315816                rc = vmdkDescSetLCHSGeometry(pImage, pLCHSGeometry);
    5432             pImage->LCHSGeometry = *pLCHSGeometry;
    5433             pImage->PCHSGeometry = *pPCHSGeometry;
     5817
    54345818            pImage->ImageUuid = *pUuid;
    54355819            RTUuidClear(&pImage->ParentUuid);
    54365820            RTUuidClear(&pImage->ModificationUuid);
    54375821            RTUuidClear(&pImage->ParentModificationUuid);
     5822
    54385823            if (RT_SUCCESS(rc))
    54395824                rc = vmdkCreateImageDdbUuidsInit(pImage);
     5825
    54405826            if (RT_SUCCESS(rc))
    54415827                rc = vmdkAllocateGrainTableCache(pImage);
     5828
    54425829            if (RT_SUCCESS(rc))
    54435830            {
     
    54465833                    rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: cannot set image comment in '%s'"), pImage->pszFilename);
    54475834            }
     5835
    54485836            if (RT_SUCCESS(rc))
    54495837            {
    54505838                vdIfProgress(pIfProgress, uPercentStart + uPercentSpan * 99 / 100);
     5839
    54515840                if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
    54525841                {
     
    54735862    else
    54745863        rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not create new descriptor in '%s'"), pImage->pszFilename);
     5864
     5865
    54755866    if (RT_SUCCESS(rc))
    54765867    {
     
    54785869        pImage->RegionList.fFlags   = 0;
    54795870        pImage->RegionList.cRegions = 1;
     5871
    54805872        pRegion->offRegion            = 0; /* Disk start. */
    54815873        pRegion->cbBlock              = 512;
     
    54855877        pRegion->cbMetadata           = 0;
    54865878        pRegion->cRegionBlocksOrBytes = pImage->cbSize;
     5879
    54875880        vdIfProgress(pIfProgress, uPercentStart + uPercentSpan);
    54885881    }
     
    54915884    return rc;
    54925885}
     5886
    54935887/**
    54945888 * Internal: Update image comment.
     
    55035897            return VERR_NO_MEMORY;
    55045898    }
     5899
    55055900    int rc = vmdkDescDDBSetStr(pImage, &pImage->Descriptor,
    55065901                               "ddb.comment", pszCommentEncoded);
     
    55115906    return VINF_SUCCESS;
    55125907}
     5908
    55135909/**
    55145910 * Internal. Clear the grain table buffer for real stream optimized writing.
     
    55215917               VMDK_GT_CACHELINE_SIZE * sizeof(uint32_t));
    55225918}
     5919
    55235920/**
    55245921 * Internal. Flush the grain table buffer for real stream optimized writing.
     
    55295926    int rc = VINF_SUCCESS;
    55305927    uint32_t cCacheLines = RT_ALIGN(pExtent->cGTEntries, VMDK_GT_CACHELINE_SIZE) / VMDK_GT_CACHELINE_SIZE;
     5928
    55315929    /* VMware does not write out completely empty grain tables in the case
    55325930     * of streamOptimized images, which according to my interpretation of
     
    55505948    if (fAllZero)
    55515949        return VINF_SUCCESS;
     5950
    55525951    uint64_t uFileOffset = pExtent->uAppendPosition;
    55535952    if (!uFileOffset)
     
    55555954    /* Align to sector, as the previous write could have been any size. */
    55565955    uFileOffset = RT_ALIGN_64(uFileOffset, 512);
     5956
    55575957    /* Grain table marker. */
    55585958    uint8_t aMarker[512];
     
    55655965    AssertRC(rc);
    55665966    uFileOffset += 512;
     5967
    55675968    if (!pExtent->pGD || pExtent->pGD[uGDEntry])
    55685969        return VERR_INTERNAL_ERROR;
     5970
    55695971    pExtent->pGD[uGDEntry] = VMDK_BYTE2SECTOR(uFileOffset);
     5972
    55705973    for (uint32_t i = 0; i < cCacheLines; i++)
    55715974    {
     
    55755978        for (uint32_t j = 0; j < VMDK_GT_CACHELINE_SIZE; j++, pGTTmp++)
    55765979            *pGTTmp = RT_H2LE_U32(*pGTTmp);
     5980
    55775981        rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pExtent->pFile->pStorage, uFileOffset,
    55785982                                    &pImage->pGTCache->aGTCache[i].aGTData[0],
     
    55865990    return rc;
    55875991}
     5992
    55885993/**
    55895994 * Internal. Free all allocated space for representing an image, and optionally
     
    55935998{
    55945999    int rc = VINF_SUCCESS;
     6000
    55956001    /* Freeing a never allocated image (e.g. because the open failed) is
    55966002     * not signalled as an error. After all nothing bad happens. */
     
    56186024                        pImage->pExtents[i].fMetaDirty = true;
    56196025                    }
     6026
    56206027                    /* From now on it's not safe to append any more data. */
    56216028                    pImage->pExtents[i].uAppendPosition = 0;
     
    56236030            }
    56246031        }
     6032
    56256033        if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
    56266034        {
     
    56416049                    AssertRC(rc);
    56426050                }
     6051
    56436052                uint64_t uFileOffset = pExtent->uAppendPosition;
    56446053                if (!uFileOffset)
    56456054                    return VERR_INTERNAL_ERROR;
    56466055                uFileOffset = RT_ALIGN_64(uFileOffset, 512);
     6056
    56476057                /* From now on it's not safe to append any more data. */
    56486058                pExtent->uAppendPosition = 0;
     6059
    56496060                /* Grain directory marker. */
    56506061                uint8_t aMarker[512];
     
    56576068                AssertRC(rc);
    56586069                uFileOffset += 512;
     6070
    56596071                /* Write grain directory in little endian style. The array will
    56606072                 * not be used after this, so convert in place. */
     
    56666078                                            pExtent->cGDEntries * sizeof(uint32_t));
    56676079                AssertRC(rc);
     6080
    56686081                pExtent->uSectorGD = VMDK_BYTE2SECTOR(uFileOffset);
    56696082                pExtent->uSectorRGD = VMDK_BYTE2SECTOR(uFileOffset);
     
    56716084                                          + pExtent->cGDEntries * sizeof(uint32_t),
    56726085                                          512);
     6086
    56736087                /* Footer marker. */
    56746088                memset(pMarker, '\0', sizeof(aMarker));
     
    56786092                                            uFileOffset, aMarker, sizeof(aMarker));
    56796093                AssertRC(rc);
     6094
    56806095                uFileOffset += 512;
    56816096                rc = vmdkWriteMetaSparseExtent(pImage, pExtent, uFileOffset, NULL);
    56826097                AssertRC(rc);
     6098
    56836099                uFileOffset += 512;
    56846100                /* End-of-stream marker. */
     
    56916107        else if (!fDelete && fFlush)
    56926108            vmdkFlushImage(pImage, NULL);
     6109
    56936110        if (pImage->pExtents != NULL)
    56946111        {
     
    57126129        if (RT_SUCCESS(rc))
    57136130            rc = rc2; /* Propogate any error when closing the file. */
     6131
    57146132        if (pImage->pGTCache)
    57156133        {
     
    57236141        }
    57246142    }
     6143
    57256144    LogFlowFunc(("returns %Rrc\n", rc));
    57266145    return rc;
    57276146}
     6147
    57286148/**
    57296149 * Internal. Flush image data (and metadata) to disk.
     
    57336153    PVMDKEXTENT pExtent;
    57346154    int rc = VINF_SUCCESS;
     6155
    57356156    /* Update descriptor if changed. */
    57366157    if (pImage->Descriptor.fDirty)
    57376158        rc = vmdkWriteDescriptor(pImage, pIoCtx);
     6159
    57386160    if (RT_SUCCESS(rc))
    57396161    {
     
    57716193                }
    57726194            }
     6195
    57736196            if (RT_FAILURE(rc))
    57746197                break;
     6198
    57756199            switch (pExtent->enmType)
    57766200            {
     
    57946218        }
    57956219    }
     6220
    57966221    return rc;
    57976222}
     6223
    57986224/**
    57996225 * Internal. Find extent corresponding to the sector number in the disk.
     
    58046230    PVMDKEXTENT pExtent = NULL;
    58056231    int rc = VINF_SUCCESS;
     6232
    58066233    for (unsigned i = 0; i < pImage->cExtents; i++)
    58076234    {
     
    58146241        offSector -= pImage->pExtents[i].cNominalSectors;
    58156242    }
     6243
    58166244    if (pExtent)
    58176245        *ppExtent = pExtent;
    58186246    else
    58196247        rc = VERR_IO_SECTOR_NOT_FOUND;
     6248
    58206249    return rc;
    58216250}
     6251
    58226252/**
    58236253 * Internal. Hash function for placing the grain table hash entries.
     
    58306260    return (uSector + uExtent) % pCache->cEntries;
    58316261}
     6262
    58326263/**
    58336264 * Internal. Get sector number in the extent file from the relative sector
     
    58446275    uint32_t aGTDataTmp[VMDK_GT_CACHELINE_SIZE];
    58456276    int rc;
     6277
    58466278    /* For newly created and readonly/sequentially opened streamOptimized
    58476279     * images this must be a no-op, as the grain directory is not there. */
     
    58556287        return VINF_SUCCESS;
    58566288    }
     6289
    58576290    uGDIndex = uSector / pExtent->cSectorsPerGDE;
    58586291    if (uGDIndex >= pExtent->cGDEntries)
     
    58666299        return VINF_SUCCESS;
    58676300    }
     6301
    58686302    uGTBlock = uSector / (pExtent->cSectorsPerGrain * VMDK_GT_CACHELINE_SIZE);
    58696303    uGTHash = vmdkGTCacheHash(pCache, uGTBlock, pExtent->uExtent);
     
    58946328    return VINF_SUCCESS;
    58956329}
     6330
    58966331/**
    58976332 * Internal. Writes the grain and also if necessary the grain tables.
     
    59086343    const void *pData;
    59096344    int rc;
     6345
    59106346    /* Very strict requirements: always write at least one full grain, with
    59116347     * proper alignment. Everything else would require reading of already
     
    59206356        || uSector + VMDK_BYTE2SECTOR(cbWrite) > pExtent->cNominalSectors)
    59216357        return VERR_INVALID_PARAMETER;
     6358
    59226359    /* Clip write range to at most the rest of the grain. */
    59236360    cbWrite = RT_MIN(cbWrite, VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain - uSector % pExtent->cSectorsPerGrain));
     6361
    59246362    /* Do not allow to go back. */
    59256363    uGrain = uSector / pExtent->cSectorsPerGrain;
     
    59306368    if (uGrain < pExtent->uLastGrainAccess)
    59316369        return VERR_VD_VMDK_INVALID_WRITE;
     6370
    59326371    /* Zero byte write optimization. Since we don't tell VBoxHDD that we need
    59336372     * to allocate something, we also need to detect the situation ourself. */
     
    59356374        && vdIfIoIntIoCtxIsZero(pImage->pIfIo, pIoCtx, cbWrite, true /* fAdvance */))
    59366375        return VINF_SUCCESS;
     6376
    59376377    if (uGDEntry != uLastGDEntry)
    59386378    {
     
    59486388        }
    59496389    }
     6390
    59506391    uint64_t uFileOffset;
    59516392    uFileOffset = pExtent->uAppendPosition;
     
    59546395    /* Align to sector, as the previous write could have been any size. */
    59556396    uFileOffset = RT_ALIGN_64(uFileOffset, 512);
     6397
    59566398    /* Paranoia check: extent type, grain table buffer presence and
    59576399     * grain table buffer space. Also grain table entry must be clear. */
     
    59616403        || pImage->pGTCache->aGTCache[uCacheLine].aGTData[uCacheEntry])
    59626404        return VERR_INTERNAL_ERROR;
     6405
    59636406    /* Update grain table entry. */
    59646407    pImage->pGTCache->aGTCache[uCacheLine].aGTData[uCacheEntry] = VMDK_BYTE2SECTOR(uFileOffset);
     6408
    59656409    if (cbWrite != VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain))
    59666410    {
     
    59756419        unsigned cSegments = 1;
    59766420        size_t cbSeg = 0;
     6421
    59776422        cbSeg = vdIfIoIntIoCtxSegArrayCreate(pImage->pIfIo, pIoCtx, &Segment,
    59786423                                             &cSegments, VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain));
     
    59916436    pExtent->uLastGrainAccess = uGrain;
    59926437    pExtent->uAppendPosition += cbGrain;
     6438
    59936439    return rc;
    59946440}
     6441
    59956442/**
    59966443 * Internal: Updates the grain table during grain allocation.
     
    60066453    uint64_t uSector = pGrainAlloc->uSector;
    60076454    PVMDKGTCACHEENTRY pGTCacheEntry;
     6455
    60086456    LogFlowFunc(("pImage=%#p pExtent=%#p pCache=%#p pIoCtx=%#p pGrainAlloc=%#p\n",
    60096457                 pImage, pExtent, pCache, pIoCtx, pGrainAlloc));
     6458
    60106459    uGTSector = pGrainAlloc->uGTSector;
    60116460    uRGTSector = pGrainAlloc->uRGTSector;
    60126461    LogFlow(("uGTSector=%llu uRGTSector=%llu\n", uGTSector, uRGTSector));
     6462
    60136463    /* Update the grain table (and the cache). */
    60146464    uGTBlock = uSector / (pExtent->cSectorsPerGrain * VMDK_GT_CACHELINE_SIZE);
     
    60736523            return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: cannot write updated backup grain table in '%s'"), pExtent->pszFullname);
    60746524    }
     6525
    60756526    LogFlowFunc(("leaving rc=%Rrc\n", rc));
    60766527    return rc;
    60776528}
     6529
    60786530/**
    60796531 * Internal - complete the grain allocation by updating disk grain table if required.
     
    60856537    PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
    60866538    PVMDKGRAINALLOCASYNC pGrainAlloc = (PVMDKGRAINALLOCASYNC)pvUser;
     6539
    60876540    LogFlowFunc(("pBackendData=%#p pIoCtx=%#p pvUser=%#p rcReq=%Rrc\n",
    60886541                 pBackendData, pIoCtx, pvUser, rcReq));
     6542
    60896543    pGrainAlloc->cIoXfersPending--;
    60906544    if (!pGrainAlloc->cIoXfersPending && pGrainAlloc->fGTUpdateNeeded)
    60916545        rc = vmdkAllocGrainGTUpdate(pImage, pGrainAlloc->pExtent, pIoCtx, pGrainAlloc);
     6546
    60926547    if (!pGrainAlloc->cIoXfersPending)
    60936548    {
     
    60956550        RTMemFree(pGrainAlloc);
    60966551    }
     6552
    60976553    LogFlowFunc(("Leaving rc=%Rrc\n", rc));
    60986554    return rc;
    60996555}
     6556
    61006557/**
    61016558 * Internal. Allocates a new grain table (if necessary).
     
    61096566    PVMDKGRAINALLOCASYNC pGrainAlloc = NULL;
    61106567    int rc;
     6568
    61116569    LogFlowFunc(("pCache=%#p pExtent=%#p pIoCtx=%#p uSector=%llu cbWrite=%llu\n",
    61126570                 pCache, pExtent, pIoCtx, uSector, cbWrite));
     6571
    61136572    pGrainAlloc = (PVMDKGRAINALLOCASYNC)RTMemAllocZ(sizeof(VMDKGRAINALLOCASYNC));
    61146573    if (!pGrainAlloc)
    61156574        return VERR_NO_MEMORY;
     6575
    61166576    pGrainAlloc->pExtent = pExtent;
    61176577    pGrainAlloc->uSector = uSector;
     6578
    61186579    uGDIndex = uSector / pExtent->cSectorsPerGDE;
    61196580    if (uGDIndex >= pExtent->cGDEntries)
     
    61306591    {
    61316592        LogFlow(("Allocating new grain table\n"));
     6593
    61326594        /* There is no grain table referenced by this grain directory
    61336595         * entry. So there is absolutely no data in this area. Allocate
     
    61406602        }
    61416603        Assert(!(uFileOffset % 512));
     6604
    61426605        uFileOffset = RT_ALIGN_64(uFileOffset, 512);
    61436606        uGTSector = VMDK_BYTE2SECTOR(uFileOffset);
     6607
    61446608        /* Normally the grain table is preallocated for hosted sparse extents
    61456609         * that support more than 32 bit sector numbers. So this shouldn't
     
    61506614            return VERR_VD_VMDK_INVALID_HEADER;
    61516615        }
     6616
    61526617        /* Write grain table by writing the required number of grain table
    61536618         * cache chunks. Allocate memory dynamically here or we flood the
     
    61556620        size_t cbGTDataTmp = pExtent->cGTEntries * sizeof(uint32_t);
    61566621        uint32_t *paGTDataTmp = (uint32_t *)RTMemTmpAllocZ(cbGTDataTmp);
     6622
    61576623        if (!paGTDataTmp)
    61586624        {
     
    61606626            return VERR_NO_MEMORY;
    61616627        }
     6628
    61626629        memset(paGTDataTmp, '\0', cbGTDataTmp);
    61636630        rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pExtent->pFile->pStorage,
     
    61756642        pExtent->uAppendPosition = RT_ALIGN_64(  pExtent->uAppendPosition
    61766643                                               + cbGTDataTmp, 512);
     6644
    61776645        if (pExtent->pRGD)
    61786646        {
     
    61836651            Assert(!(uFileOffset % 512));
    61846652            uRGTSector = VMDK_BYTE2SECTOR(uFileOffset);
     6653
    61856654            /* Normally the redundant grain table is preallocated for hosted
    61866655             * sparse extents that support more than 32 bit sector numbers. So
     
    61916660                return VERR_VD_VMDK_INVALID_HEADER;
    61926661            }
     6662
    61936663            /* Write grain table by writing the required number of grain table
    61946664             * cache chunks. Allocate memory dynamically here or we flood the
     
    62056675                return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: cannot write backup grain table allocation in '%s'"), pExtent->pszFullname);
    62066676            }
     6677
    62076678            pExtent->uAppendPosition = pExtent->uAppendPosition + cbGTDataTmp;
    62086679        }
     6680
    62096681        RTMemTmpFree(paGTDataTmp);
     6682
    62106683        /* Update the grain directory on disk (doing it before writing the
    62116684         * grain table will result in a garbled extent if the operation is
     
    62336706                return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: cannot write backup grain directory entry in '%s'"), pExtent->pszFullname);
    62346707        }
     6708
    62356709        /* As the final step update the in-memory copy of the GDs. */
    62366710        pExtent->pGD[uGDIndex] = uGTSector;
     
    62386712            pExtent->pRGD[uGDIndex] = uRGTSector;
    62396713    }
     6714
    62406715    LogFlow(("uGTSector=%llu uRGTSector=%llu\n", uGTSector, uRGTSector));
    62416716    pGrainAlloc->uGTSector = uGTSector;
    62426717    pGrainAlloc->uRGTSector = uRGTSector;
     6718
    62436719    uFileOffset = pExtent->uAppendPosition;
    62446720    if (!uFileOffset)
    62456721        return VERR_INTERNAL_ERROR;
    62466722    Assert(!(uFileOffset % 512));
     6723
    62476724    pGrainAlloc->uGrainOffset = uFileOffset;
     6725
    62486726    if (pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
    62496727    {
     
    62516729                        ("Accesses to stream optimized images must be synchronous\n"),
    62526730                        VERR_INVALID_STATE);
     6731
    62536732        if (cbWrite != VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain))
    62546733            return vdIfError(pImage->pIfError, VERR_INTERNAL_ERROR, RT_SRC_POS, N_("VMDK: not enough data for a compressed data block in '%s'"), pExtent->pszFullname);
     6734
    62556735        /* Invalidate cache, just in case some code incorrectly allows mixing
    62566736         * of reads and writes. Normally shouldn't be needed. */
    62576737        pExtent->uGrainSectorAbs = 0;
     6738
    62586739        /* Write compressed data block and the markers. */
    62596740        uint32_t cbGrain = 0;
     
    62616742        RTSGSEG Segment;
    62626743        unsigned cSegments = 1;
     6744
    62636745        cbSeg = vdIfIoIntIoCtxSegArrayCreate(pImage->pIfIo, pIoCtx, &Segment,
    62646746                                             &cSegments, cbWrite);
    62656747        Assert(cbSeg == cbWrite);
     6748
    62666749        rc = vmdkFileDeflateSync(pImage, pExtent, uFileOffset,
    62676750                                 Segment.pvSeg, cbWrite, uSector, &cbGrain);
     
    62846767        else if (RT_FAILURE(rc))
    62856768            return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: cannot write allocated data block in '%s'"), pExtent->pszFullname);
     6769
    62866770        pExtent->uAppendPosition += cbWrite;
    62876771    }
     6772
    62886773    rc = vmdkAllocGrainGTUpdate(pImage, pExtent, pIoCtx, pGrainAlloc);
     6774
    62896775    if (!pGrainAlloc->cIoXfersPending)
    62906776    {
     
    62926778        RTMemFree(pGrainAlloc);
    62936779    }
     6780
    62946781    LogFlowFunc(("leaving rc=%Rrc\n", rc));
     6782
    62956783    return rc;
    62966784}
     6785
    62976786/**
    62986787 * Internal. Reads the contents by sequentially going over the compressed
     
    63046793{
    63056794    int rc;
     6795
    63066796    LogFlowFunc(("pImage=%#p pExtent=%#p uSector=%llu pIoCtx=%#p cbRead=%llu\n",
    63076797                 pImage, pExtent, uSector, pIoCtx, cbRead));
     6798
    63086799    AssertMsgReturn(vdIfIoIntIoCtxIsSynchronous(pImage->pIfIo, pIoCtx),
    63096800                    ("Async I/O not supported for sequential stream optimized images\n"),
    63106801                    VERR_INVALID_STATE);
     6802
    63116803    /* Do not allow to go back. */
    63126804    uint32_t uGrain = uSector / pExtent->cSectorsPerGrain;
     
    63146806        return VERR_VD_VMDK_INVALID_STATE;
    63156807    pExtent->uLastGrainAccess = uGrain;
     6808
    63166809    /* After a previous error do not attempt to recover, as it would need
    63176810     * seeking (in the general case backwards which is forbidden). */
    63186811    if (!pExtent->uGrainSectorAbs)
    63196812        return VERR_VD_VMDK_INVALID_STATE;
     6813
    63206814    /* Check if we need to read something from the image or if what we have
    63216815     * in the buffer is good to fulfill the request. */
     
    63246818        uint32_t uGrainSectorAbs =   pExtent->uGrainSectorAbs
    63256819                                   + VMDK_BYTE2SECTOR(pExtent->cbGrainStreamRead);
     6820
    63266821        /* Get the marker from the next data block - and skip everything which
    63276822         * is not a compressed grain. If it's a compressed grain which is for
     
    63386833            Marker.uSector = RT_LE2H_U64(Marker.uSector);
    63396834            Marker.cbSize = RT_LE2H_U32(Marker.cbSize);
     6835
    63406836            if (Marker.cbSize == 0)
    63416837            {
     
    64166912            }
    64176913        } while (Marker.uType != VMDK_MARKER_EOS);
     6914
    64186915        pExtent->uGrainSectorAbs = uGrainSectorAbs;
     6916
    64196917        if (!pExtent->cbGrainStreamRead && Marker.uType == VMDK_MARKER_EOS)
    64206918        {
     
    64256923        }
    64266924    }
     6925
    64276926    if (pExtent->uGrain > uSector / pExtent->cSectorsPerGrain)
    64286927    {
     
    64326931        return VERR_VD_BLOCK_FREE;
    64336932    }
     6933
    64346934    uint32_t uSectorInGrain = uSector % pExtent->cSectorsPerGrain;
    64356935    vdIfIoIntIoCtxCopyTo(pImage->pIfIo, pIoCtx,
     
    64396939    return VINF_SUCCESS;
    64406940}
     6941
    64416942/**
    64426943 * Replaces a fragment of a string with the specified string.
     
    65077008    return pszNewStr;
    65087009}
     7010
     7011
    65097012/** @copydoc VDIMAGEBACKEND::pfnProbe */
    65107013static DECLCALLBACK(int) vmdkProbe(const char *pszFilename, PVDINTERFACE pVDIfsDisk,
     
    65347037        vmdkFreeImage(pImage, false, false /*fFlush*/);
    65357038        RTMemFree(pImage);
     7039
    65367040        if (RT_SUCCESS(rc))
    65377041            *penmType = VDTYPE_HDD;
     
    65397043    else
    65407044        rc = VERR_NO_MEMORY;
     7045
    65417046    LogFlowFunc(("returns %Rrc\n", rc));
    65427047    return rc;
    65437048}
     7049
    65447050/** @copydoc VDIMAGEBACKEND::pfnOpen */
    65457051static DECLCALLBACK(int) vmdkOpen(const char *pszFilename, unsigned uOpenFlags,
     
    65487054{
    65497055    RT_NOREF1(enmType); /**< @todo r=klaus make use of the type info. */
     7056
    65507057    LogFlowFunc(("pszFilename=\"%s\" uOpenFlags=%#x pVDIfsDisk=%#p pVDIfsImage=%#p enmType=%u ppBackendData=%#p\n",
    65517058                 pszFilename, uOpenFlags, pVDIfsDisk, pVDIfsImage, enmType, ppBackendData));
    65527059    int rc;
     7060
    65537061    /* Check open flags. All valid flags are supported. */
    65547062    AssertReturn(!(uOpenFlags & ~VD_OPEN_FLAGS_MASK), VERR_INVALID_PARAMETER);
    65557063    AssertPtrReturn(pszFilename, VERR_INVALID_POINTER);
    65567064    AssertReturn(*pszFilename != '\0', VERR_INVALID_PARAMETER);
     7065
    65577066
    65587067    PVMDKIMAGE pImage = (PVMDKIMAGE)RTMemAllocZ(RT_UOFFSETOF(VMDKIMAGE, RegionList.aRegions[1]));
     
    65677076        pImage->pVDIfsDisk = pVDIfsDisk;
    65687077        pImage->pVDIfsImage = pVDIfsImage;
     7078
    65697079        rc = vmdkOpenImage(pImage, uOpenFlags);
    65707080        if (RT_SUCCESS(rc))
     
    65757085    else
    65767086        rc = VERR_NO_MEMORY;
     7087
    65777088    LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
    65787089    return rc;
    65797090}
     7091
    65807092/** @copydoc VDIMAGEBACKEND::pfnCreate */
    65817093static DECLCALLBACK(int) vmdkCreate(const char *pszFilename, uint64_t cbSize,
     
    65917103                 pszFilename, cbSize, uImageFlags, pszComment, pPCHSGeometry, pLCHSGeometry, pUuid, uOpenFlags, uPercentStart, uPercentSpan, pVDIfsDisk, pVDIfsImage, pVDIfsOperation, enmType, ppBackendData));
    65927104    int rc;
     7105
    65937106    /* Check the VD container type and image flags. */
    65947107    if (   enmType != VDTYPE_HDD
    65957108        || (uImageFlags & ~VD_VMDK_IMAGE_FLAGS_MASK) != 0)
    65967109        return VERR_VD_INVALID_TYPE;
     7110
    65977111    /* Check size. Maximum 256TB-64K for sparse images, otherwise unlimited. */
    65987112    if (   !(uImageFlags & VD_VMDK_IMAGE_FLAGS_RAWDISK)
     
    66007114            || (!(uImageFlags & VD_IMAGE_FLAGS_FIXED) && cbSize >= _1T * 256 - _64K)))
    66017115        return VERR_VD_INVALID_SIZE;
     7116
    66027117    /* Check image flags for invalid combinations. */
    66037118    if (   (uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED)
    66047119        && (uImageFlags & ~(VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED | VD_IMAGE_FLAGS_DIFF)))
    66057120        return VERR_INVALID_PARAMETER;
     7121
    66067122    /* Check open flags. All valid flags are supported. */
    66077123    AssertReturn(!(uOpenFlags & ~VD_OPEN_FLAGS_MASK), VERR_INVALID_PARAMETER);
     
    66137129                   && !(uImageFlags & VD_IMAGE_FLAGS_FIXED)),
    66147130                 VERR_INVALID_PARAMETER);
     7131
    66157132    PVMDKIMAGE pImage = (PVMDKIMAGE)RTMemAllocZ(RT_UOFFSETOF(VMDKIMAGE, RegionList.aRegions[1]));
    66167133    if (RT_LIKELY(pImage))
    66177134    {
    66187135        PVDINTERFACEPROGRESS pIfProgress = VDIfProgressGet(pVDIfsOperation);
     7136
    66197137        pImage->pszFilename = pszFilename;
    66207138        pImage->pFile = NULL;
     
    66477165                    rc = vmdkOpenImage(pImage, uOpenFlags);
    66487166                }
     7167
    66497168                if (RT_SUCCESS(rc))
    66507169                    *ppBackendData = pImage;
    66517170            }
     7171
    66527172            if (RT_FAILURE(rc))
    66537173                RTMemFree(pImage->pDescData);
     
    66557175        else
    66567176            rc = VERR_NO_MEMORY;
     7177
    66577178        if (RT_FAILURE(rc))
    66587179            RTMemFree(pImage);
     
    66607181    else
    66617182        rc = VERR_NO_MEMORY;
     7183
    66627184    LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
    66637185    return rc;
    66647186}
     7187
    66657188/**
    66667189 * Prepares the state for renaming a VMDK image, setting up the state and allocating
     
    66757198{
    66767199    AssertReturn(RTPathFilename(pszFilename) != NULL, VERR_INVALID_PARAMETER);
     7200
    66777201    int rc = VINF_SUCCESS;
     7202
    66787203    memset(&pRenameState->DescriptorCopy, 0, sizeof(pRenameState->DescriptorCopy));
     7204
    66797205    /*
    66807206     * Allocate an array to store both old and new names of renamed files
     
    67027228            pRenameState->fEmbeddedDesc = true;
    67037229        }
     7230
    67047231        /* Save the descriptor content. */
    67057232        pRenameState->DescriptorCopy.cLines = pImage->Descriptor.cLines;
     
    67137240            }
    67147241        }
     7242
    67157243        if (RT_SUCCESS(rc))
    67167244        {
     
    67197247            AssertReturn(pRenameState->pszNewBaseName, VERR_NO_STR_MEMORY);
    67207248            RTPathStripSuffix(pRenameState->pszNewBaseName);
     7249
    67217250            pRenameState->pszOldBaseName = RTStrDup(RTPathFilename(pImage->pszFilename));
    67227251            AssertReturn(pRenameState->pszOldBaseName, VERR_NO_STR_MEMORY);
    67237252            RTPathStripSuffix(pRenameState->pszOldBaseName);
     7253
    67247254            /* Prepare both old and new full names used for string replacement.
    67257255               Note! Must abspath the stuff here, so the strstr weirdness later in
     
    67297259            AssertReturn(pRenameState->pszNewFullName, VERR_NO_STR_MEMORY);
    67307260            RTPathStripSuffix(pRenameState->pszNewFullName);
     7261
    67317262            pRenameState->pszOldFullName = RTPathAbsDup(pImage->pszFilename);
    67327263            AssertReturn(pRenameState->pszOldFullName, VERR_NO_STR_MEMORY);
    67337264            RTPathStripSuffix(pRenameState->pszOldFullName);
     7265
    67347266            /* Save the old name for easy access to the old descriptor file. */
    67357267            pRenameState->pszOldDescName = RTStrDup(pImage->pszFilename);
    67367268            AssertReturn(pRenameState->pszOldDescName, VERR_NO_STR_MEMORY);
     7269
    67377270            /* Save old image name. */
    67387271            pRenameState->pszOldImageName = pImage->pszFilename;
     
    67417274    else
    67427275        rc = VERR_NO_TMP_MEMORY;
     7276
    67437277    return rc;
    67447278}
     7279
    67457280/**
    67467281 * Destroys the given rename state, freeing all allocated memory.
     
    67867321        RTStrFree(pRenameState->pszNewFullName);
    67877322}
     7323
    67887324/**
    67897325 * Rolls back the rename operation to the original state.
     
    67967332{
    67977333    int rc = VINF_SUCCESS;
     7334
    67987335    if (!pRenameState->fImageFreed)
    67997336    {
     
    68047341        vmdkFreeImage(pImage, false, true /*fFlush*/);
    68057342    }
     7343
    68067344    /* Rename files back. */
    68077345    for (unsigned i = 0; i <= pRenameState->cExtents; i++)
     
    68427380    pImage->pszFilename = pRenameState->pszOldImageName;
    68437381    rc = vmdkOpenImage(pImage, pImage->uOpenFlags);
     7382
    68447383    return rc;
    68457384}
     7385
    68467386/**
    68477387 * Rename worker doing the real work.
     
    68567396    int rc = VINF_SUCCESS;
    68577397    unsigned i, line;
     7398
    68587399    /* Update the descriptor with modified extent names. */
    68597400    for (i = 0, line = pImage->Descriptor.uFirstExtent;
     
    68727413        pImage->Descriptor.aLines[line] = pRenameState->apszNewLines[i];
    68737414    }
     7415
    68747416    if (RT_SUCCESS(rc))
    68757417    {
     
    68787420        /* Flush the descriptor now, in case it is embedded. */
    68797421        vmdkFlushImage(pImage, NULL);
     7422
    68807423        /* Close and rename/move extents. */
    68817424        for (i = 0; i < pRenameState->cExtents; i++)
     
    68957438            if (RT_FAILURE(rc))
    68967439                break;;
     7440
    68977441            /* Rename the extent file. */
    68987442            rc = vdIfIoIntFileMove(pImage->pIfIo, pExtent->pszFullname, pRenameState->apszNewName[i], 0);
     
    69027446            pRenameState->apszOldName[i] = RTStrDup(pExtent->pszFullname);
    69037447        }
     7448
    69047449        if (RT_SUCCESS(rc))
    69057450        {
     
    69097454            {
    69107455                pRenameState->fImageFreed = true;
     7456
    69117457                /* Last elements of new/old name arrays are intended for
    69127458                 * storing descriptor's names.
     
    69237469                    }
    69247470                }
     7471
    69257472                /* Update pImage with the new information. */
    69267473                pImage->pszFilename = pszFilename;
     7474
    69277475                /* Open the new image. */
    69287476                rc = vmdkOpenImage(pImage, pImage->uOpenFlags);
     
    69307478        }
    69317479    }
     7480
    69327481    return rc;
    69337482}
     7483
    69347484/** @copydoc VDIMAGEBACKEND::pfnRename */
    69357485static DECLCALLBACK(int) vmdkRename(void *pBackendData, const char *pszFilename)
    69367486{
    69377487    LogFlowFunc(("pBackendData=%#p pszFilename=%#p\n", pBackendData, pszFilename));
     7488
    69387489    PVMDKIMAGE  pImage  = (PVMDKIMAGE)pBackendData;
    69397490    VMDKRENAMESTATE RenameState;
     7491
    69407492    memset(&RenameState, 0, sizeof(RenameState));
     7493
    69417494    /* Check arguments. */
    69427495    AssertPtrReturn(pImage, VERR_INVALID_POINTER);
     
    69447497    AssertReturn(*pszFilename != '\0', VERR_INVALID_PARAMETER);
    69457498    AssertReturn(!(pImage->uImageFlags & VD_VMDK_IMAGE_FLAGS_RAWDISK), VERR_INVALID_PARAMETER);
     7499
    69467500    int rc = vmdkRenameStatePrepare(pImage, &RenameState, pszFilename);
    69477501    if (RT_SUCCESS(rc))
    69487502    {
    69497503        /* --- Up to this point we have not done any damage yet. --- */
     7504
    69507505        rc = vmdkRenameWorker(pImage, &RenameState, pszFilename);
    69517506        /* Roll back all changes in case of failure. */
     
    69567511        }
    69577512    }
     7513
    69587514    vmdkRenameStateDestroy(&RenameState);
    69597515    LogFlowFunc(("returns %Rrc\n", rc));
    69607516    return rc;
    69617517}
     7518
    69627519/** @copydoc VDIMAGEBACKEND::pfnClose */
    69637520static DECLCALLBACK(int) vmdkClose(void *pBackendData, bool fDelete)
     
    69657522    LogFlowFunc(("pBackendData=%#p fDelete=%d\n", pBackendData, fDelete));
    69667523    PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
     7524
    69677525    int rc = vmdkFreeImage(pImage, fDelete, true /*fFlush*/);
    69687526    RTMemFree(pImage);
     7527
    69697528    LogFlowFunc(("returns %Rrc\n", rc));
    69707529    return rc;
    69717530}
     7531
    69727532/** @copydoc VDIMAGEBACKEND::pfnRead */
    69737533static DECLCALLBACK(int) vmdkRead(void *pBackendData, uint64_t uOffset, size_t cbToRead,
     
    69777537                 pBackendData, uOffset, pIoCtx, cbToRead, pcbActuallyRead));
    69787538    PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
     7539
    69797540    AssertPtr(pImage);
    69807541    Assert(uOffset % 512 == 0);
     
    69837544    AssertReturn(cbToRead, VERR_INVALID_PARAMETER);
    69847545    AssertReturn(uOffset + cbToRead <= pImage->cbSize, VERR_INVALID_PARAMETER);
     7546
    69857547    /* Find the extent and check access permissions as defined in the extent descriptor. */
    69867548    PVMDKEXTENT pExtent;
     
    69937555        /* Clip read range to remain in this extent. */
    69947556        cbToRead = RT_MIN(cbToRead, VMDK_SECTOR2BYTE(pExtent->uSectorOffset + pExtent->cNominalSectors - uSectorExtentRel));
     7557
    69957558        /* Handle the read according to the current extent type. */
    69967559        switch (pExtent->enmType)
     
    69997562            {
    70007563                uint64_t uSectorExtentAbs;
     7564
    70017565                rc = vmdkGetSector(pImage, pIoCtx, pExtent, uSectorExtentRel, &uSectorExtentAbs);
    70027566                if (RT_FAILURE(rc))
     
    70227586                        AssertMsg(vdIfIoIntIoCtxIsSynchronous(pImage->pIfIo, pIoCtx),
    70237587                                  ("Async I/O is not supported for stream optimized VMDK's\n"));
     7588
    70247589                        uint32_t uSectorInGrain = uSectorExtentRel % pExtent->cSectorsPerGrain;
    70257590                        uSectorExtentAbs -= uSectorInGrain;
     
    70627627            {
    70637628                size_t cbSet;
     7629
    70647630                cbSet = vdIfIoIntIoCtxSet(pImage->pIfIo, pIoCtx, 0, cbToRead);
    70657631                Assert(cbSet == cbToRead);
     
    70727638    else if (RT_SUCCESS(rc))
    70737639        rc = VERR_VD_VMDK_INVALID_STATE;
     7640
    70747641    LogFlowFunc(("returns %Rrc\n", rc));
    70757642    return rc;
    70767643}
     7644
    70777645/** @copydoc VDIMAGEBACKEND::pfnWrite */
    70787646static DECLCALLBACK(int) vmdkWrite(void *pBackendData, uint64_t uOffset, size_t cbToWrite,
     
    70847652    PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
    70857653    int rc;
     7654
    70867655    AssertPtr(pImage);
    70877656    Assert(uOffset % 512 == 0);
     
    70897658    AssertPtrReturn(pIoCtx, VERR_INVALID_POINTER);
    70907659    AssertReturn(cbToWrite, VERR_INVALID_PARAMETER);
     7660
    70917661    if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
    70927662    {
     
    70947664        uint64_t uSectorExtentRel;
    70957665        uint64_t uSectorExtentAbs;
     7666
    70967667        /* No size check here, will do that later when the extent is located.
    70977668         * There are sparse images out there which according to the spec are
     
    71007671         * grain boundaries, and with the nominal size not being a multiple of the
    71017672         * grain size), this would prevent writing to the last grain. */
     7673
    71027674        rc = vmdkFindExtent(pImage, VMDK_BYTE2SECTOR(uOffset),
    71037675                            &pExtent, &uSectorExtentRel);
     
    71977769                }
    71987770            }
     7771
    71997772            if (pcbWriteProcess)
    72007773                *pcbWriteProcess = cbToWrite;
     
    72037776    else
    72047777        rc = VERR_VD_IMAGE_READ_ONLY;
     7778
    72057779    LogFlowFunc(("returns %Rrc\n", rc));
    72067780    return rc;
    72077781}
     7782
    72087783/** @copydoc VDIMAGEBACKEND::pfnFlush */
    72097784static DECLCALLBACK(int) vmdkFlush(void *pBackendData, PVDIOCTX pIoCtx)
    72107785{
    72117786    PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
     7787
    72127788    return vmdkFlushImage(pImage, pIoCtx);
    72137789}
     7790
    72147791/** @copydoc VDIMAGEBACKEND::pfnGetVersion */
    72157792static DECLCALLBACK(unsigned) vmdkGetVersion(void *pBackendData)
     
    72177794    LogFlowFunc(("pBackendData=%#p\n", pBackendData));
    72187795    PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
     7796
    72197797    AssertPtrReturn(pImage, 0);
     7798
    72207799    return VMDK_IMAGE_VERSION;
    72217800}
     7801
    72227802/** @copydoc VDIMAGEBACKEND::pfnGetFileSize */
    72237803static DECLCALLBACK(uint64_t) vmdkGetFileSize(void *pBackendData)
     
    72267806    PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
    72277807    uint64_t cb = 0;
     7808
    72287809    AssertPtrReturn(pImage, 0);
     7810
    72297811    if (pImage->pFile != NULL)
    72307812    {
     
    72447826        }
    72457827    }
     7828
    72467829    LogFlowFunc(("returns %lld\n", cb));
    72477830    return cb;
    72487831}
     7832
    72497833/** @copydoc VDIMAGEBACKEND::pfnGetPCHSGeometry */
    72507834static DECLCALLBACK(int) vmdkGetPCHSGeometry(void *pBackendData, PVDGEOMETRY pPCHSGeometry)
     
    72537837    PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
    72547838    int rc = VINF_SUCCESS;
     7839
    72557840    AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
     7841
    72567842    if (pImage->PCHSGeometry.cCylinders)
    72577843        *pPCHSGeometry = pImage->PCHSGeometry;
    72587844    else
    72597845        rc = VERR_VD_GEOMETRY_NOT_SET;
     7846
    72607847    LogFlowFunc(("returns %Rrc (PCHS=%u/%u/%u)\n", rc, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
    72617848    return rc;
    72627849}
     7850
    72637851/** @copydoc VDIMAGEBACKEND::pfnSetPCHSGeometry */
    72647852static DECLCALLBACK(int) vmdkSetPCHSGeometry(void *pBackendData, PCVDGEOMETRY pPCHSGeometry)
     
    72687856    PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
    72697857    int rc = VINF_SUCCESS;
     7858
    72707859    AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
     7860
    72717861    if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
    72727862    {
     
    72827872    else
    72837873        rc = VERR_VD_IMAGE_READ_ONLY;
     7874
    72847875    LogFlowFunc(("returns %Rrc\n", rc));
    72857876    return rc;
    72867877}
     7878
    72877879/** @copydoc VDIMAGEBACKEND::pfnGetLCHSGeometry */
    72887880static DECLCALLBACK(int) vmdkGetLCHSGeometry(void *pBackendData, PVDGEOMETRY pLCHSGeometry)
     
    72917883    PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
    72927884    int rc = VINF_SUCCESS;
     7885
    72937886    AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
     7887
    72947888    if (pImage->LCHSGeometry.cCylinders)
    72957889        *pLCHSGeometry = pImage->LCHSGeometry;
    72967890    else
    72977891        rc = VERR_VD_GEOMETRY_NOT_SET;
     7892
    72987893    LogFlowFunc(("returns %Rrc (LCHS=%u/%u/%u)\n", rc, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
    72997894    return rc;
    73007895}
     7896
    73017897/** @copydoc VDIMAGEBACKEND::pfnSetLCHSGeometry */
    73027898static DECLCALLBACK(int) vmdkSetLCHSGeometry(void *pBackendData, PCVDGEOMETRY pLCHSGeometry)
     
    73067902    PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
    73077903    int rc = VINF_SUCCESS;
     7904
    73087905    AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
     7906
    73097907    if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
    73107908    {
     
    73207918    else
    73217919        rc = VERR_VD_IMAGE_READ_ONLY;
     7920
    73227921    LogFlowFunc(("returns %Rrc\n", rc));
    73237922    return rc;
    73247923}
     7924
    73257925/** @copydoc VDIMAGEBACKEND::pfnQueryRegions */
    73267926static DECLCALLBACK(int) vmdkQueryRegions(void *pBackendData, PCVDREGIONLIST *ppRegionList)
     
    73287928    LogFlowFunc(("pBackendData=%#p ppRegionList=%#p\n", pBackendData, ppRegionList));
    73297929    PVMDKIMAGE pThis = (PVMDKIMAGE)pBackendData;
     7930
    73307931    AssertPtrReturn(pThis, VERR_VD_NOT_OPENED);
     7932
    73317933    *ppRegionList = &pThis->RegionList;
    73327934    LogFlowFunc(("returns %Rrc\n", VINF_SUCCESS));
    73337935    return VINF_SUCCESS;
    73347936}
     7937
    73357938/** @copydoc VDIMAGEBACKEND::pfnRegionListRelease */
    73367939static DECLCALLBACK(void) vmdkRegionListRelease(void *pBackendData, PCVDREGIONLIST pRegionList)
     
    73407943    PVMDKIMAGE pThis = (PVMDKIMAGE)pBackendData;
    73417944    AssertPtr(pThis); RT_NOREF(pThis);
     7945
    73427946    /* Nothing to do here. */
    73437947}
     7948
    73447949/** @copydoc VDIMAGEBACKEND::pfnGetImageFlags */
    73457950static DECLCALLBACK(unsigned) vmdkGetImageFlags(void *pBackendData)
     
    73477952    LogFlowFunc(("pBackendData=%#p\n", pBackendData));
    73487953    PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
     7954
    73497955    AssertPtrReturn(pImage, 0);
     7956
    73507957    LogFlowFunc(("returns %#x\n", pImage->uImageFlags));
    73517958    return pImage->uImageFlags;
    73527959}
     7960
    73537961/** @copydoc VDIMAGEBACKEND::pfnGetOpenFlags */
    73547962static DECLCALLBACK(unsigned) vmdkGetOpenFlags(void *pBackendData)
     
    73567964    LogFlowFunc(("pBackendData=%#p\n", pBackendData));
    73577965    PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
     7966
    73587967    AssertPtrReturn(pImage, 0);
     7968
    73597969    LogFlowFunc(("returns %#x\n", pImage->uOpenFlags));
    73607970    return pImage->uOpenFlags;
    73617971}
     7972
    73627973/** @copydoc VDIMAGEBACKEND::pfnSetOpenFlags */
    73637974static DECLCALLBACK(int) vmdkSetOpenFlags(void *pBackendData, unsigned uOpenFlags)
     
    73667977    PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
    73677978    int rc;
     7979
    73687980    /* Image must be opened and the new flags must be valid. */
    73697981    if (!pImage || (uOpenFlags & ~(  VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO
     
    73888000        }
    73898001    }
     8002
    73908003    LogFlowFunc(("returns %Rrc\n", rc));
    73918004    return rc;
    73928005}
     8006
    73938007/** @copydoc VDIMAGEBACKEND::pfnGetComment */
    73948008static DECLCALLBACK(int) vmdkGetComment(void *pBackendData, char *pszComment, size_t cbComment)
     
    73968010    LogFlowFunc(("pBackendData=%#p pszComment=%#p cbComment=%zu\n", pBackendData, pszComment, cbComment));
    73978011    PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
     8012
    73988013    AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
     8014
    73998015    char *pszCommentEncoded = NULL;
    74008016    int rc = vmdkDescDDBGetStr(pImage, &pImage->Descriptor,
     
    74058021        rc = VINF_SUCCESS;
    74068022    }
     8023
    74078024    if (RT_SUCCESS(rc))
    74088025    {
     
    74118028        else if (pszComment)
    74128029                *pszComment = '\0';
     8030
    74138031        if (pszCommentEncoded)
    74148032            RTMemTmpFree(pszCommentEncoded);
    74158033    }
     8034
    74168035    LogFlowFunc(("returns %Rrc comment='%s'\n", rc, pszComment));
    74178036    return rc;
    74188037}
     8038
    74198039/** @copydoc VDIMAGEBACKEND::pfnSetComment */
    74208040static DECLCALLBACK(int) vmdkSetComment(void *pBackendData, const char *pszComment)
     
    74238043    PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
    74248044    int rc;
     8045
    74258046    AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
     8047
    74268048    if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
    74278049    {
     
    74338055    else
    74348056        rc = VERR_VD_IMAGE_READ_ONLY;
     8057
    74358058    LogFlowFunc(("returns %Rrc\n", rc));
    74368059    return rc;
    74378060}
     8061
    74388062/** @copydoc VDIMAGEBACKEND::pfnGetUuid */
    74398063static DECLCALLBACK(int) vmdkGetUuid(void *pBackendData, PRTUUID pUuid)
     
    74418065    LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
    74428066    PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
     8067
    74438068    AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
     8069
    74448070    *pUuid = pImage->ImageUuid;
     8071
    74458072    LogFlowFunc(("returns %Rrc (%RTuuid)\n", VINF_SUCCESS, pUuid));
    74468073    return VINF_SUCCESS;
    74478074}
     8075
    74488076/** @copydoc VDIMAGEBACKEND::pfnSetUuid */
    74498077static DECLCALLBACK(int) vmdkSetUuid(void *pBackendData, PCRTUUID pUuid)
     
    74528080    PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
    74538081    int rc = VINF_SUCCESS;
     8082
    74548083    AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
     8084
    74558085    if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
    74568086    {
     
    74698099    else
    74708100        rc = VERR_VD_IMAGE_READ_ONLY;
     8101
    74718102    LogFlowFunc(("returns %Rrc\n", rc));
    74728103    return rc;
    74738104}
     8105
    74748106/** @copydoc VDIMAGEBACKEND::pfnGetModificationUuid */
    74758107static DECLCALLBACK(int) vmdkGetModificationUuid(void *pBackendData, PRTUUID pUuid)
     
    74778109    LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
    74788110    PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
     8111
    74798112    AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
     8113
    74808114    *pUuid = pImage->ModificationUuid;
     8115
    74818116    LogFlowFunc(("returns %Rrc (%RTuuid)\n", VINF_SUCCESS, pUuid));
    74828117    return VINF_SUCCESS;
    74838118}
     8119
    74848120/** @copydoc VDIMAGEBACKEND::pfnSetModificationUuid */
    74858121static DECLCALLBACK(int) vmdkSetModificationUuid(void *pBackendData, PCRTUUID pUuid)
     
    74888124    PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
    74898125    int rc = VINF_SUCCESS;
     8126
    74908127    AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
     8128
    74918129    if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
    74928130    {
     
    75088146    else
    75098147        rc = VERR_VD_IMAGE_READ_ONLY;
     8148
    75108149    LogFlowFunc(("returns %Rrc\n", rc));
    75118150    return rc;
    75128151}
     8152
    75138153/** @copydoc VDIMAGEBACKEND::pfnGetParentUuid */
    75148154static DECLCALLBACK(int) vmdkGetParentUuid(void *pBackendData, PRTUUID pUuid)
     
    75168156    LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
    75178157    PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
     8158
    75188159    AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
     8160
    75198161    *pUuid = pImage->ParentUuid;
     8162
    75208163    LogFlowFunc(("returns %Rrc (%RTuuid)\n", VINF_SUCCESS, pUuid));
    75218164    return VINF_SUCCESS;
    75228165}
     8166
    75238167/** @copydoc VDIMAGEBACKEND::pfnSetParentUuid */
    75248168static DECLCALLBACK(int) vmdkSetParentUuid(void *pBackendData, PCRTUUID pUuid)
     
    75278171    PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
    75288172    int rc = VINF_SUCCESS;
     8173
    75298174    AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
     8175
    75308176    if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
    75318177    {
     
    75448190    else
    75458191        rc = VERR_VD_IMAGE_READ_ONLY;
     8192
    75468193    LogFlowFunc(("returns %Rrc\n", rc));
    75478194    return rc;
    75488195}
     8196
    75498197/** @copydoc VDIMAGEBACKEND::pfnGetParentModificationUuid */
    75508198static DECLCALLBACK(int) vmdkGetParentModificationUuid(void *pBackendData, PRTUUID pUuid)
     
    75528200    LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
    75538201    PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
     8202
    75548203    AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
     8204
    75558205    *pUuid = pImage->ParentModificationUuid;
     8206
    75568207    LogFlowFunc(("returns %Rrc (%RTuuid)\n", VINF_SUCCESS, pUuid));
    75578208    return VINF_SUCCESS;
    75588209}
     8210
    75598211/** @copydoc VDIMAGEBACKEND::pfnSetParentModificationUuid */
    75608212static DECLCALLBACK(int) vmdkSetParentModificationUuid(void *pBackendData, PCRTUUID pUuid)
     
    75638215    PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
    75648216    int rc = VINF_SUCCESS;
     8217
    75658218    AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
     8219
    75668220    if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
    75678221    {
     
    75798233    else
    75808234        rc = VERR_VD_IMAGE_READ_ONLY;
     8235
    75818236    LogFlowFunc(("returns %Rrc\n", rc));
    75828237    return rc;
    75838238}
     8239
    75848240/** @copydoc VDIMAGEBACKEND::pfnDump */
    75858241static DECLCALLBACK(void) vmdkDump(void *pBackendData)
    75868242{
    75878243    PVMDKIMAGE pImage = (PVMDKIMAGE)pBackendData;
     8244
    75888245    AssertPtrReturnVoid(pImage);
    75898246    vdIfErrorMessage(pImage->pIfError, "Header: Geometry PCHS=%u/%u/%u LCHS=%u/%u/%u cbSector=%llu\n",
     
    75978254}
    75988255
    7599 /**
    7600  * Returns the size, in bytes, of the sparse extent overhead for
    7601  * the number of desired total sectors and based on the current
    7602  * sectors of the extent.
    7603  *
    7604  * @returns uint64_t size of new overhead in bytes.
    7605  * @param   pExtent         VMDK extent instance.
    7606  * @param   cSectorsNew     Number of desired total sectors.
    7607  */
    7608 static uint64_t vmdkGetNewOverhead(PVMDKEXTENT pExtent, uint64_t cSectorsNew)
    7609 {
    7610     uint64_t cNewDirEntries = cSectorsNew / pExtent->cSectorsPerGDE;
    7611     if (cSectorsNew % pExtent->cSectorsPerGDE)
    7612         cNewDirEntries++;
    7613 
    7614     size_t cbNewGD = cNewDirEntries * sizeof(uint32_t);
    7615     uint64_t cbNewDirSize = RT_ALIGN_64(cbNewGD, 512);
    7616     uint64_t cbNewAllTablesSize = RT_ALIGN_64(cNewDirEntries * pExtent->cGTEntries * sizeof(uint32_t), 512);
    7617     uint64_t cbNewOverhead = RT_ALIGN_Z(RT_MAX(pExtent->uDescriptorSector
    7618                                                 + pExtent->cDescriptorSectors, 1)
    7619                                                 + cbNewDirSize + cbNewAllTablesSize, 512);
    7620     cbNewOverhead += cbNewDirSize + cbNewAllTablesSize;
    7621     cbNewOverhead = RT_ALIGN_64(cbNewOverhead,
    7622                                 VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain));
    7623 
    7624     return cbNewOverhead;
    7625 }
    7626 
    7627 /**
    7628  * Internal: Replaces the size (in sectors) of an extent in the descriptor file.
    7629  *
    7630  * @returns VBox status code.
    7631  * @param   pImage              VMDK image instance.
    7632  * @param   uLine                Line number of descriptor to change.
    7633  * @param   cSectorsOld         Existing number of sectors.
    7634  * @param   cSectorsNew         New number of sectors.
    7635  */
    7636 static int vmdkReplaceExtentSize(PVMDKIMAGE pImage, PVMDKEXTENT pExtent, unsigned uLine, uint64_t cSectorsOld,
    7637                                  uint64_t cSectorsNew)
    7638 {
    7639     char szOldExtentSectors[UINT64_MAX_BUFF_SIZE];
    7640     char szNewExtentSectors[UINT64_MAX_BUFF_SIZE];
    7641 
    7642     ssize_t cbWritten = RTStrPrintf2(szOldExtentSectors, sizeof(szOldExtentSectors), "%llu", cSectorsOld);
    7643     if (cbWritten <= 0 || cbWritten > (ssize_t)sizeof(szOldExtentSectors))
     8256static int vmdkRepaceExtentSize(PVMDKIMAGE pImage, unsigned line, uint64_t cSectorsOld,
     8257                                uint64_t cSectorsNew)
     8258{
     8259    char * szOldExtentSectors = (char *)RTMemAlloc(UINT64_MAX_BUFF_SIZE);
     8260    if (!szOldExtentSectors)
     8261        return VERR_NO_MEMORY;
     8262
     8263    int cbWritten = RTStrPrintf2(szOldExtentSectors, UINT64_MAX_BUFF_SIZE, "%llu", cSectorsOld);
     8264    if (cbWritten <= 0 || cbWritten > UINT64_MAX_BUFF_SIZE)
     8265    {
     8266        RTMemFree(szOldExtentSectors);
     8267        szOldExtentSectors = NULL;
     8268
    76448269        return VERR_BUFFER_OVERFLOW;
    7645 
    7646     cbWritten = RTStrPrintf2(szNewExtentSectors, sizeof(szNewExtentSectors), "%llu", cSectorsNew);
    7647     if (cbWritten <= 0 || cbWritten > (ssize_t)sizeof(szNewExtentSectors))
     8270    }
     8271
     8272    char * szNewExtentSectors = (char *)RTMemAlloc(UINT64_MAX_BUFF_SIZE);
     8273    if (!szNewExtentSectors)
     8274        return VERR_NO_MEMORY;
     8275
     8276    cbWritten = RTStrPrintf2(szNewExtentSectors, UINT64_MAX_BUFF_SIZE, "%llu", cSectorsNew);
     8277    if (cbWritten <= 0 || cbWritten > UINT64_MAX_BUFF_SIZE)
     8278    {
     8279        RTMemFree(szOldExtentSectors);
     8280        szOldExtentSectors = NULL;
     8281
     8282        RTMemFree(szNewExtentSectors);
     8283        szNewExtentSectors = NULL;
     8284
    76488285        return VERR_BUFFER_OVERFLOW;
    7649 
    7650     char *pszNewExtentLine = vmdkStrReplace(pImage->Descriptor.aLines[uLine],
     8286    }
     8287
     8288    char * szNewExtentLine = vmdkStrReplace(pImage->Descriptor.aLines[line],
    76518289                                            szOldExtentSectors,
    76528290                                            szNewExtentSectors);
    76538291
    7654     if (RT_UNLIKELY(!pszNewExtentLine))
     8292    RTMemFree(szOldExtentSectors);
     8293    szOldExtentSectors = NULL;
     8294
     8295    RTMemFree(szNewExtentSectors);
     8296    szNewExtentSectors = NULL;
     8297
     8298    if (!szNewExtentLine)
    76558299        return VERR_INVALID_PARAMETER;
    76568300
    7657     vmdkDescExtRemoveByLine(pImage, &pImage->Descriptor, uLine);
    7658     vmdkDescExtInsert(pImage, &pImage->Descriptor,
    7659                       pExtent->enmAccess, cSectorsNew,
    7660                       pExtent->enmType, pExtent->pszBasename, pExtent->uSectorOffset);
    7661 
    7662     RTStrFree(pszNewExtentLine);
    7663     pszNewExtentLine = NULL;
    7664 
    7665     pImage->Descriptor.fDirty = true;
     8301    pImage->Descriptor.aLines[line] = szNewExtentLine;
    76668302
    76678303    return VINF_SUCCESS;
    7668 }
    7669 
    7670 /**
    7671  * Moves sectors down to make room for new overhead.
    7672  * Used for sparse extent resize.
    7673  *
    7674  * @returns VBox status code.
    7675  * @param   pImage          VMDK image instance.
    7676  * @param   pExtent         VMDK extent instance.
    7677  * @param   cSectorsNew     Number of sectors after resize.
    7678  */
    7679 static int vmdkRelocateSectorsForSparseResize(PVMDKIMAGE pImage, PVMDKEXTENT pExtent,
    7680                                               uint64_t cSectorsNew)
    7681 {
    7682     int rc = VINF_SUCCESS;
    7683 
    7684     uint64_t cbNewOverhead = vmdkGetNewOverhead(pExtent, cSectorsNew);
    7685 
    7686     uint64_t cNewOverheadSectors = VMDK_BYTE2SECTOR(cbNewOverhead);
    7687     uint64_t cOverheadSectorDiff = cNewOverheadSectors - pExtent->cOverheadSectors;
    7688 
    7689     uint64_t cbFile = 0;
    7690     rc = vdIfIoIntFileGetSize(pImage->pIfIo, pExtent->pFile->pStorage, &cbFile);
    7691 
    7692     uint64_t uNewAppendPosition;
    7693 
    7694     /* Calculate how many sectors need to be relocated. */
    7695     unsigned cSectorsReloc = cOverheadSectorDiff;
    7696     if (cbNewOverhead % VMDK_SECTOR_SIZE)
    7697         cSectorsReloc++;
    7698 
    7699     if (cSectorsReloc < pExtent->cSectors)
    7700         uNewAppendPosition = RT_ALIGN_Z(cbFile + VMDK_SECTOR2BYTE(cOverheadSectorDiff), 512);
    7701     else
    7702         uNewAppendPosition = cbFile;
    7703 
    7704     /*
    7705     * Get the blocks we need to relocate first, they are appended to the end
    7706     * of the image.
    7707     */
    7708     void *pvBuf = NULL, *pvZero = NULL;
    7709     do
    7710     {
    7711         /* Allocate data buffer. */
    7712         pvBuf = RTMemAllocZ(VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain));
    7713         if (!pvBuf)
    7714         {
    7715             rc = VERR_NO_MEMORY;
    7716             break;
    7717         }
    7718 
    7719         /* Allocate buffer for overwriting with zeroes. */
    7720         pvZero = RTMemAllocZ(VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain));
    7721         if (!pvZero)
    7722         {
    7723             RTMemFree(pvBuf);
    7724             pvBuf = NULL;
    7725 
    7726             rc = VERR_NO_MEMORY;
    7727             break;
    7728         }
    7729 
    7730         uint32_t *aGTDataTmp = (uint32_t *)RTMemAllocZ(sizeof(uint32_t) * pExtent->cGTEntries);
    7731         if(!aGTDataTmp)
    7732         {
    7733             RTMemFree(pvBuf);
    7734             pvBuf = NULL;
    7735 
    7736             RTMemFree(pvZero);
    7737             pvZero = NULL;
    7738 
    7739             rc = VERR_NO_MEMORY;
    7740             break;
    7741         }
    7742 
    7743         uint32_t *aRGTDataTmp = (uint32_t *)RTMemAllocZ(sizeof(uint32_t) * pExtent->cGTEntries);
    7744         if(!aRGTDataTmp)
    7745         {
    7746             RTMemFree(pvBuf);
    7747             pvBuf = NULL;
    7748 
    7749             RTMemFree(pvZero);
    7750             pvZero = NULL;
    7751 
    7752             RTMemFree(aGTDataTmp);
    7753             aGTDataTmp = NULL;
    7754 
    7755             rc = VERR_NO_MEMORY;
    7756             break;
    7757         }
    7758 
    7759         /* Search for overlap sector in the grain table. */
    7760         for (uint32_t idxGD = 0; idxGD < pExtent->cGDEntries; idxGD++)
    7761         {
    7762             uint64_t uGTSector = pExtent->pGD[idxGD];
    7763             uint64_t uRGTSector = pExtent->pRGD[idxGD];
    7764 
    7765             rc = vdIfIoIntFileReadSync(pImage->pIfIo, pExtent->pFile->pStorage,
    7766                                         VMDK_SECTOR2BYTE(uGTSector),
    7767                                         aGTDataTmp, sizeof(uint32_t) * pExtent->cGTEntries);
    7768 
    7769             if (RT_FAILURE(rc))
    7770                 break;
    7771 
    7772             rc = vdIfIoIntFileReadSync(pImage->pIfIo, pExtent->pFile->pStorage,
    7773                                         VMDK_SECTOR2BYTE(uRGTSector),
    7774                                         aRGTDataTmp, sizeof(uint32_t) * pExtent->cGTEntries);
    7775 
    7776             if (RT_FAILURE(rc))
    7777                 break;
    7778 
    7779             for (uint32_t idxGT = 0; idxGT < pExtent->cGTEntries; idxGT++)
    7780             {
    7781                 uint64_t aGTEntryLE = RT_LE2H_U64(aGTDataTmp[idxGT]);
    7782                 uint64_t aRGTEntryLE = RT_LE2H_U64(aRGTDataTmp[idxGT]);
    7783 
    7784                 /**
    7785                  * Check if grain table is valid. If not dump out with an error.
    7786                  * Shoudln't ever get here (given other checks) but good sanity check.
    7787                 */
    7788                 if (aGTEntryLE != aRGTEntryLE)
    7789                 {
    7790                     rc = vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS,
    7791                                     N_("VMDK: inconsistent references within grain table in '%s'"), pExtent->pszFullname);
    7792                     break;
    7793                 }
    7794 
    7795                 if (aGTEntryLE < cNewOverheadSectors
    7796                     && aGTEntryLE != 0)
    7797                 {
    7798                     /* Read data and append grain to the end of the image. */
    7799                     rc = vdIfIoIntFileReadSync(pImage->pIfIo, pExtent->pFile->pStorage,
    7800                                                 VMDK_SECTOR2BYTE(aGTEntryLE), pvBuf,
    7801                                                 VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain));
    7802                     if (RT_FAILURE(rc))
    7803                         break;
    7804 
    7805                     rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pExtent->pFile->pStorage,
    7806                                                 uNewAppendPosition, pvBuf,
    7807                                                 VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain));
    7808                     if (RT_FAILURE(rc))
    7809                         break;
    7810 
    7811                     /* Zero out the old block area. */
    7812                     rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pExtent->pFile->pStorage,
    7813                                                 VMDK_SECTOR2BYTE(aGTEntryLE), pvZero,
    7814                                                 VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain));
    7815                     if (RT_FAILURE(rc))
    7816                         break;
    7817 
    7818                     /* Write updated grain tables to file */
    7819                     aGTDataTmp[idxGT] = VMDK_BYTE2SECTOR(uNewAppendPosition);
    7820                     aRGTDataTmp[idxGT] = VMDK_BYTE2SECTOR(uNewAppendPosition);
    7821 
    7822                     if (memcmp(aGTDataTmp, aRGTDataTmp, sizeof(uint32_t) * pExtent->cGTEntries))
    7823                     {
    7824                         rc = vdIfError(pImage->pIfError, VERR_VD_VMDK_INVALID_HEADER, RT_SRC_POS,
    7825                                     N_("VMDK: inconsistency between grain table and backup grain table in '%s'"), pExtent->pszFullname);
    7826                         break;
    7827                     }
    7828 
    7829                     rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pExtent->pFile->pStorage,
    7830                                                 VMDK_SECTOR2BYTE(uGTSector),
    7831                                                 aGTDataTmp, sizeof(uint32_t) * pExtent->cGTEntries);
    7832 
    7833                     if (RT_FAILURE(rc))
    7834                         break;
    7835 
    7836                     rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pExtent->pFile->pStorage,
    7837                                                 VMDK_SECTOR2BYTE(uRGTSector),
    7838                                                 aRGTDataTmp, sizeof(uint32_t) * pExtent->cGTEntries);
    7839 
    7840                     break;
    7841                 }
    7842             }
    7843         }
    7844 
    7845         RTMemFree(aGTDataTmp);
    7846         aGTDataTmp = NULL;
    7847 
    7848         RTMemFree(aRGTDataTmp);
    7849         aRGTDataTmp = NULL;
    7850 
    7851         if (RT_FAILURE(rc))
    7852             break;
    7853 
    7854         uNewAppendPosition += VMDK_SECTOR2BYTE(pExtent->cSectorsPerGrain);
    7855     } while (0);
    7856 
    7857     if (pvBuf)
    7858     {
    7859         RTMemFree(pvBuf);
    7860         pvBuf = NULL;
    7861     }
    7862 
    7863     if (pvZero)
    7864     {
    7865         RTMemFree(pvZero);
    7866         pvZero = NULL;
    7867     }
    7868 
    7869     // Update append position for extent
    7870     pExtent->uAppendPosition = uNewAppendPosition;
    7871 
    7872     return rc;
    7873 }
    7874 
    7875 /**
    7876  * Resizes meta/overhead for sparse extent resize.
    7877  *
    7878  * @returns VBox status code.
    7879  * @param   pImage          VMDK image instance.
    7880  * @param   pExtent         VMDK extent instance.
    7881  * @param   cSectorsNew     Number of sectors after resize.
    7882  */
    7883 static int vmdkResizeSparseMeta(PVMDKIMAGE pImage, PVMDKEXTENT pExtent,
    7884                                 uint64_t cSectorsNew)
    7885 {
    7886     int rc = VINF_SUCCESS;
    7887     uint32_t cOldGDEntries = pExtent->cGDEntries;
    7888 
    7889     uint64_t cNewDirEntries = cSectorsNew / pExtent->cSectorsPerGDE;
    7890     if (cSectorsNew % pExtent->cSectorsPerGDE)
    7891         cNewDirEntries++;
    7892 
    7893     size_t cbNewGD = cNewDirEntries * sizeof(uint32_t);
    7894 
    7895     uint64_t cbNewDirSize = RT_ALIGN_64(cbNewGD, 512);
    7896     uint64_t cbCurrDirSize = RT_ALIGN_64(pExtent->cGDEntries * VMDK_GRAIN_DIR_ENTRY_SIZE, 512);
    7897     uint64_t cDirSectorDiff = VMDK_BYTE2SECTOR(cbNewDirSize - cbCurrDirSize);
    7898 
    7899     uint64_t cbNewAllTablesSize = RT_ALIGN_64(cNewDirEntries * pExtent->cGTEntries * sizeof(uint32_t), 512);
    7900     uint64_t cbCurrAllTablesSize = RT_ALIGN_64(pExtent->cGDEntries * VMDK_GRAIN_TABLE_SIZE, 512);
    7901     uint64_t cTableSectorDiff = VMDK_BYTE2SECTOR(cbNewAllTablesSize - cbCurrAllTablesSize);
    7902 
    7903     uint64_t cbNewOverhead = vmdkGetNewOverhead(pExtent, cSectorsNew);
    7904     uint64_t cNewOverheadSectors = VMDK_BYTE2SECTOR(cbNewOverhead);
    7905     uint64_t cOverheadSectorDiff = cNewOverheadSectors - pExtent->cOverheadSectors;
    7906 
    7907     /*
    7908     * Get the blocks we need to relocate first, they are appended to the end
    7909     * of the image.
    7910     */
    7911     void *pvBuf = NULL, *pvZero = NULL;
    7912 
    7913     do
    7914     {
    7915         /* Allocate data buffer. */
    7916         pvBuf = RTMemAllocZ(VMDK_GRAIN_TABLE_SIZE);
    7917         if (!pvBuf)
    7918         {
    7919             rc = VERR_NO_MEMORY;
    7920             break;
    7921         }
    7922 
    7923         /* Allocate buffer for overwriting with zeroes. */
    7924         pvZero = RTMemAllocZ(VMDK_GRAIN_TABLE_SIZE);
    7925         if (!pvZero)
    7926         {
    7927             RTMemFree(pvBuf);
    7928             pvBuf = NULL;
    7929 
    7930             rc = VERR_NO_MEMORY;
    7931             break;
    7932         }
    7933 
    7934         uint32_t uGTStart = VMDK_SECTOR2BYTE(pExtent->uSectorGD) + (cOldGDEntries * VMDK_GRAIN_DIR_ENTRY_SIZE);
    7935 
    7936         // points to last element in the grain table
    7937         uint32_t uGTTail = uGTStart + (pExtent->cGDEntries * VMDK_GRAIN_TABLE_SIZE) - VMDK_GRAIN_TABLE_SIZE;
    7938         uint32_t cbGTOff = RT_ALIGN_Z(VMDK_SECTOR2BYTE(cDirSectorDiff + cTableSectorDiff + cDirSectorDiff), 512);
    7939 
    7940         for (int i = pExtent->cGDEntries - 1; i >= 0; i--)
    7941         {
    7942             rc = vdIfIoIntFileReadSync(pImage->pIfIo, pExtent->pFile->pStorage,
    7943                                         uGTTail, pvBuf,
    7944                                         VMDK_GRAIN_TABLE_SIZE);
    7945             if (RT_FAILURE(rc))
    7946                 break;
    7947 
    7948             rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pExtent->pFile->pStorage,
    7949                                         RT_ALIGN_Z(uGTTail + cbGTOff, 512), pvBuf,
    7950                                         VMDK_GRAIN_TABLE_SIZE);
    7951             if (RT_FAILURE(rc))
    7952                 break;
    7953 
    7954             // This overshoots when i == 0, but we don't need it anymore.
    7955             uGTTail -= VMDK_GRAIN_TABLE_SIZE;
    7956         }
    7957 
    7958 
    7959         /* Find the end of the grain directory and start bumping everything down. Update locations of GT entries. */
    7960         rc = vdIfIoIntFileReadSync(pImage->pIfIo, pExtent->pFile->pStorage,
    7961                                     VMDK_SECTOR2BYTE(pExtent->uSectorGD), pvBuf,
    7962                                     pExtent->cGDEntries * VMDK_GRAIN_DIR_ENTRY_SIZE);
    7963         if (RT_FAILURE(rc))
    7964             break;
    7965 
    7966         int * tmpBuf = (int *)pvBuf;
    7967 
    7968         for (uint32_t i = 0; i < pExtent->cGDEntries; i++)
    7969         {
    7970             tmpBuf[i] = tmpBuf[i] + VMDK_BYTE2SECTOR(cbGTOff);
    7971             pExtent->pGD[i] = pExtent->pGD[i] + VMDK_BYTE2SECTOR(cbGTOff);
    7972         }
    7973 
    7974         rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pExtent->pFile->pStorage,
    7975                                     RT_ALIGN_Z(VMDK_SECTOR2BYTE(pExtent->uSectorGD + cTableSectorDiff + cDirSectorDiff), 512), pvBuf,
    7976                                     pExtent->cGDEntries * VMDK_GRAIN_DIR_ENTRY_SIZE);
    7977         if (RT_FAILURE(rc))
    7978             break;
    7979 
    7980         pExtent->uSectorGD = pExtent->uSectorGD + cDirSectorDiff + cTableSectorDiff;
    7981 
    7982         /* Repeat both steps with the redundant grain table/directory. */
    7983 
    7984         uint32_t uRGTStart = VMDK_SECTOR2BYTE(pExtent->uSectorRGD) + (cOldGDEntries * VMDK_GRAIN_DIR_ENTRY_SIZE);
    7985 
    7986         // points to last element in the grain table
    7987         uint32_t uRGTTail = uRGTStart + (pExtent->cGDEntries * VMDK_GRAIN_TABLE_SIZE) - VMDK_GRAIN_TABLE_SIZE;
    7988         uint32_t cbRGTOff = RT_ALIGN_Z(VMDK_SECTOR2BYTE(cDirSectorDiff), 512);
    7989 
    7990         for (int i = pExtent->cGDEntries - 1; i >= 0; i--)
    7991         {
    7992             rc = vdIfIoIntFileReadSync(pImage->pIfIo, pExtent->pFile->pStorage,
    7993                                         uRGTTail, pvBuf,
    7994                                         VMDK_GRAIN_TABLE_SIZE);
    7995             if (RT_FAILURE(rc))
    7996                 break;
    7997 
    7998             rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pExtent->pFile->pStorage,
    7999                                         RT_ALIGN_Z(uRGTTail + cbRGTOff, 512), pvBuf,
    8000                                         VMDK_GRAIN_TABLE_SIZE);
    8001             if (RT_FAILURE(rc))
    8002                 break;
    8003 
    8004             // This overshoots when i == 0, but we don't need it anymore.
    8005             uRGTTail -= VMDK_GRAIN_TABLE_SIZE;
    8006         }
    8007 
    8008         /* Update locations of GT entries. */
    8009         rc = vdIfIoIntFileReadSync(pImage->pIfIo, pExtent->pFile->pStorage,
    8010                                     VMDK_SECTOR2BYTE(pExtent->uSectorRGD), pvBuf,
    8011                                     pExtent->cGDEntries * VMDK_GRAIN_DIR_ENTRY_SIZE);
    8012         if (RT_FAILURE(rc))
    8013             break;
    8014 
    8015         tmpBuf = (int *)pvBuf;
    8016 
    8017         for (uint32_t i = 0; i < pExtent->cGDEntries; i++)
    8018         {
    8019             tmpBuf[i] = tmpBuf[i] + cDirSectorDiff;
    8020             pExtent->pRGD[i] = pExtent->pRGD[i] + cDirSectorDiff;
    8021         }
    8022 
    8023         rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pExtent->pFile->pStorage,
    8024                                     VMDK_SECTOR2BYTE(pExtent->uSectorRGD), pvBuf,
    8025                                     pExtent->cGDEntries * VMDK_GRAIN_DIR_ENTRY_SIZE);
    8026         if (RT_FAILURE(rc))
    8027             break;
    8028 
    8029         pExtent->uSectorRGD = pExtent->uSectorRGD;
    8030         pExtent->cOverheadSectors += cOverheadSectorDiff;
    8031 
    8032     } while (0);
    8033 
    8034     if (pvBuf)
    8035     {
    8036         RTMemFree(pvBuf);
    8037         pvBuf = NULL;
    8038     }
    8039 
    8040     if (pvZero)
    8041     {
    8042         RTMemFree(pvZero);
    8043         pvZero = NULL;
    8044     }
    8045 
    8046     pExtent->cGDEntries = cNewDirEntries;
    8047 
    8048     /* Allocate buffer for overwriting with zeroes. */
    8049     pvZero = RTMemAllocZ(VMDK_GRAIN_TABLE_SIZE);
    8050     if (!pvZero)
    8051         return VERR_NO_MEMORY;
    8052 
    8053     // Allocate additional grain dir
    8054     pExtent->pGD = (uint32_t *) RTMemReallocZ(pExtent->pGD, pExtent->cGDEntries * sizeof(uint32_t), cbNewGD);
    8055     if (RT_LIKELY(pExtent->pGD))
    8056     {
    8057         if (pExtent->uSectorRGD)
    8058         {
    8059             pExtent->pRGD = (uint32_t *)RTMemReallocZ(pExtent->pRGD, pExtent->cGDEntries * sizeof(uint32_t), cbNewGD);
    8060             if (RT_UNLIKELY(!pExtent->pRGD))
    8061                 rc = VERR_NO_MEMORY;
    8062         }
    8063     }
    8064     else
    8065         return VERR_NO_MEMORY;
    8066 
    8067 
    8068     uint32_t uTmpDirVal = pExtent->pGD[cOldGDEntries - 1] + VMDK_GRAIN_DIR_ENTRY_SIZE;
    8069     for (uint32_t i = cOldGDEntries; i < pExtent->cGDEntries; i++)
    8070     {
    8071         pExtent->pGD[i] = uTmpDirVal;
    8072 
    8073         rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pExtent->pFile->pStorage,
    8074                                     VMDK_SECTOR2BYTE(uTmpDirVal), pvZero,
    8075                                     VMDK_GRAIN_TABLE_SIZE);
    8076 
    8077         if (RT_FAILURE(rc))
    8078             return rc;
    8079 
    8080         uTmpDirVal += VMDK_GRAIN_DIR_ENTRY_SIZE;
    8081     }
    8082 
    8083     uint32_t uRTmpDirVal = pExtent->pRGD[cOldGDEntries - 1] + VMDK_GRAIN_DIR_ENTRY_SIZE;
    8084     for (uint32_t i = cOldGDEntries; i < pExtent->cGDEntries; i++)
    8085     {
    8086         pExtent->pRGD[i] = uRTmpDirVal;
    8087 
    8088         rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pExtent->pFile->pStorage,
    8089                                     VMDK_SECTOR2BYTE(uRTmpDirVal), pvZero,
    8090                                     VMDK_GRAIN_TABLE_SIZE);
    8091 
    8092         if (RT_FAILURE(rc))
    8093             return rc;
    8094 
    8095         uRTmpDirVal += VMDK_GRAIN_DIR_ENTRY_SIZE;
    8096     }
    8097 
    8098     RTMemFree(pvZero);
    8099     pvZero = NULL;
    8100 
    8101     rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pExtent->pFile->pStorage,
    8102                                 VMDK_SECTOR2BYTE(pExtent->uSectorGD), pExtent->pGD,
    8103                                 pExtent->cGDEntries * VMDK_GRAIN_DIR_ENTRY_SIZE);
    8104     if (RT_FAILURE(rc))
    8105         return rc;
    8106 
    8107     rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pExtent->pFile->pStorage,
    8108                                 VMDK_SECTOR2BYTE(pExtent->uSectorRGD), pExtent->pRGD,
    8109                                 pExtent->cGDEntries * VMDK_GRAIN_DIR_ENTRY_SIZE);
    8110     if (RT_FAILURE(rc))
    8111         return rc;
    8112 
    8113     rc = vmdkReplaceExtentSize(pImage, pExtent, pImage->Descriptor.uFirstExtent + pExtent->uExtent,
    8114                                 pExtent->cNominalSectors, cSectorsNew);
    8115     if (RT_FAILURE(rc))
    8116         return rc;
    8117 
    8118     return rc;
    81198304}
    81208305
     
    81338318    unsigned uImageFlags = pImage->uImageFlags;
    81348319    PVMDKEXTENT pExtent = &pImage->pExtents[0];
    8135     pExtent->fMetaDirty = true;
    81368320
    81378321    uint64_t cSectorsNew = cbSize / VMDK_SECTOR_SIZE;   /** < New number of sectors in the image after the resize */
     
    81548338     */
    81558339    /** @todo implement making the image smaller, it is the responsibility of
    8156      * the user to know what they're doing. */
     8340     * the user to know what he's doing. */
    81578341    if (cbSize < pImage->cbSize)
    81588342        rc = VERR_VD_SHRINK_NOT_SUPPORTED;
     
    81748358                return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not set size of new file '%s'"), pExtent->pszFullname);
    81758359
    8176             rc = vmdkReplaceExtentSize(pImage, pExtent, pImage->Descriptor.uFirstExtent, cSectorsOld, cSectorsNew);
     8360            rc = vmdkRepaceExtentSize(pImage, pImage->Descriptor.uFirstExtent, cSectorsOld, cSectorsNew);
    81778361            if (RT_FAILURE(rc))
    81788362                return rc;
     
    81918375
    81928376            uint64_t cSectorsNeeded = cSectorsNew - cSectorsOld;
    8193 
    8194             /** Space remaining in current last extent file that we don't need to create another one. */
    81958377            if (fSpaceAvailible && cSectorsNeeded + cLastExtentRemSectors <= VMDK_BYTE2SECTOR(VMDK_2G_SPLIT_SIZE))
    81968378            {
     
    82028384                    return vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VMDK: could not set size of new file '%s'"), pExtent->pszFullname);
    82038385
    8204                 rc = vmdkReplaceExtentSize(pImage, pExtent, pImage->Descriptor.uFirstExtent + cExtents - 1,
    8205                                            pExtent->cNominalSectors, cSectorsNeeded + cLastExtentRemSectors);
     8386                rc = vmdkRepaceExtentSize(pImage, pImage->Descriptor.uFirstExtent + cExtents - 1,
     8387                                          pExtent->cNominalSectors, cSectorsNeeded + cLastExtentRemSectors);
    82068388                if (RT_FAILURE(rc))
    82078389                    return rc;
    82088390            }
    8209             //** Need more extent files to handle all the requested space. */
    82108391            else
    82118392            {
     
    82218402                    cSectorsNeeded = cSectorsNeeded - VMDK_BYTE2SECTOR(VMDK_2G_SPLIT_SIZE) + cLastExtentRemSectors;
    82228403
    8223                     rc = vmdkReplaceExtentSize(pImage, pExtent, pImage->Descriptor.uFirstExtent + cExtents - 1,
    8224                                                pExtent->cNominalSectors, VMDK_BYTE2SECTOR(VMDK_2G_SPLIT_SIZE));
     8404                    rc = vmdkRepaceExtentSize(pImage, pImage->Descriptor.uFirstExtent + cExtents - 1,
     8405                                              pExtent->cNominalSectors, VMDK_BYTE2SECTOR(VMDK_2G_SPLIT_SIZE));
    82258406                    if (RT_FAILURE(rc))
    82268407                        return rc;
     
    82548435        }
    82558436
    8256         /**
    8257          * monolithicSparse.
    8258          */
    8259         if (pExtent->enmType == VMDKETYPE_HOSTED_SPARSE && !(uImageFlags & VD_VMDK_IMAGE_FLAGS_SPLIT_2G))
    8260         {
    8261             // 1. Calculate sectors needed for new overhead.
    8262 
    8263             uint64_t cbNewOverhead = vmdkGetNewOverhead(pExtent, cSectorsNew);
    8264             uint64_t cNewOverheadSectors = VMDK_BYTE2SECTOR(cbNewOverhead);
    8265             uint64_t cOverheadSectorDiff = cNewOverheadSectors - pExtent->cOverheadSectors;
    8266 
    8267             // 2. Relocate sectors to make room for new GD/GT, update entries in GD/GT
    8268             if (cOverheadSectorDiff > 0)
    8269             {
    8270                 if (pExtent->cSectors > 0)
    8271                 {
    8272                     /* Do the relocation. */
    8273                     LogFlow(("Relocating VMDK sectors\n"));
    8274                     rc = vmdkRelocateSectorsForSparseResize(pImage, pExtent, cSectorsNew);
    8275                     if (RT_FAILURE(rc))
    8276                         return rc;
    8277 
    8278                     rc = vmdkFlushImage(pImage, NULL);
    8279                     if (RT_FAILURE(rc))
    8280                         return rc;
    8281                 }
    8282 
    8283                 rc = vmdkResizeSparseMeta(pImage, pExtent, cSectorsNew);
    8284                 if (RT_FAILURE(rc))
    8285                     return rc;
    8286             }
    8287         }
    8288 
    8289         /**
    8290          * twoGbSparseExtent
    8291          */
    8292         if (pExtent->enmType == VMDKETYPE_HOSTED_SPARSE && (uImageFlags & VD_VMDK_IMAGE_FLAGS_SPLIT_2G))
    8293         {
    8294             /* Check to see how much space remains in last extent */
    8295             bool fSpaceAvailible = false;
    8296             uint64_t cLastExtentRemSectors = cSectorsOld % VMDK_BYTE2SECTOR(VMDK_2G_SPLIT_SIZE);
    8297             if (cLastExtentRemSectors)
    8298                 fSpaceAvailible = true;
    8299 
    8300             uint64_t cSectorsNeeded = cSectorsNew - cSectorsOld;
    8301 
    8302             if (fSpaceAvailible && cSectorsNeeded + cLastExtentRemSectors <= VMDK_BYTE2SECTOR(VMDK_2G_SPLIT_SIZE))
    8303             {
    8304                 pExtent = &pImage->pExtents[cExtents - 1];
    8305                 rc = vmdkRelocateSectorsForSparseResize(pImage, pExtent, cSectorsNeeded + cLastExtentRemSectors);
    8306                 if (RT_FAILURE(rc))
    8307                     return rc;
    8308 
    8309                 rc = vmdkFlushImage(pImage, NULL);
    8310                 if (RT_FAILURE(rc))
    8311                     return rc;
    8312 
    8313                 rc = vmdkResizeSparseMeta(pImage, pExtent, cSectorsNeeded + cLastExtentRemSectors);
    8314                 if (RT_FAILURE(rc))
    8315                     return rc;
    8316             }
    8317             else
    8318             {
    8319                 if (fSpaceAvailible)
    8320                 {
    8321                     pExtent = &pImage->pExtents[cExtents - 1];
    8322                     rc = vmdkRelocateSectorsForSparseResize(pImage, pExtent, VMDK_BYTE2SECTOR(VMDK_2G_SPLIT_SIZE));
    8323                     if (RT_FAILURE(rc))
    8324                         return rc;
    8325 
    8326                     rc = vmdkFlushImage(pImage, NULL);
    8327                     if (RT_FAILURE(rc))
    8328                         return rc;
    8329 
    8330                     rc = vmdkResizeSparseMeta(pImage, pExtent, VMDK_BYTE2SECTOR(VMDK_2G_SPLIT_SIZE));
    8331                     if (RT_FAILURE(rc))
    8332                         return rc;
    8333 
    8334                     cSectorsNeeded = cSectorsNeeded - VMDK_BYTE2SECTOR(VMDK_2G_SPLIT_SIZE) + cLastExtentRemSectors;
    8335                 }
    8336 
    8337                 unsigned cNewExtents = VMDK_SECTOR2BYTE(cSectorsNeeded) / VMDK_2G_SPLIT_SIZE;
    8338                 if (cNewExtents % VMDK_2G_SPLIT_SIZE || cNewExtents < VMDK_2G_SPLIT_SIZE)
    8339                     cNewExtents++;
    8340 
    8341                 for (unsigned i = cExtents;
    8342                      i < cExtents + cNewExtents && cSectorsNeeded >= VMDK_BYTE2SECTOR(VMDK_2G_SPLIT_SIZE);
    8343                      i++)
    8344                 {
    8345                     rc = vmdkAddFileBackedExtent(pImage, VMDK_2G_SPLIT_SIZE);
    8346                     if (RT_FAILURE(rc))
    8347                         return rc;
    8348 
    8349                     pExtent = &pImage->pExtents[i];
    8350 
    8351                     rc = vmdkFlushImage(pImage, NULL);
    8352                     if (RT_FAILURE(rc))
    8353                         return rc;
    8354 
    8355                     pExtent->cSectors = VMDK_BYTE2SECTOR(VMDK_2G_SPLIT_SIZE);
    8356                     cSectorsNeeded -= VMDK_BYTE2SECTOR(VMDK_2G_SPLIT_SIZE);
    8357                 }
    8358 
    8359                 if (cSectorsNeeded)
    8360                 {
    8361                     rc = vmdkAddFileBackedExtent(pImage, VMDK_SECTOR2BYTE(cSectorsNeeded));
    8362                     if (RT_FAILURE(rc))
    8363                         return rc;
    8364 
    8365                     pExtent = &pImage->pExtents[pImage->cExtents];
    8366 
    8367                     rc = vmdkFlushImage(pImage, NULL);
    8368                     if (RT_FAILURE(rc))
    8369                         return rc;
    8370                 }
    8371             }
    8372         }
    8373 
    83748437        /* Successful resize. Update metadata */
    83758438        if (RT_SUCCESS(rc))
     
    83778440            /* Update size and new block count. */
    83788441            pImage->cbSize = cbSize;
    8379             pExtent->cNominalSectors = cSectorsNew;
    8380             pExtent->cSectors = cSectorsNew;
     8442            /** @todo r=jack: update cExtents if needed */
     8443            pExtent->cNominalSectors = VMDK_BYTE2SECTOR(cbSize);
    83818444
    83828445            /* Update geometry. */
     
    83868449
    83878450        /* Update header information in base image file. */
    8388         pImage->Descriptor.fDirty = true;
    83898451        rc = vmdkWriteDescriptor(pImage, NULL);
    83908452
    8391         if (RT_SUCCESS(rc))
    8392             rc = vmdkFlushImage(pImage, NULL);
     8453        if (RT_FAILURE(rc))
     8454            return rc;
     8455
     8456        rc = vmdkFlushImage(pImage, NULL);
     8457
     8458        if (RT_FAILURE(rc))
     8459            return rc;
    83938460    }
    83948461    /* Same size doesn't change the image at all. */
     
    83978464    return rc;
    83988465}
     8466
    83998467
    84008468const VDIMAGEBACKEND g_VmdkBackend =
  • trunk/src/VBox/Storage/testcase/tstVDIo.cpp

    r97836 r97839  
    567567    bool fBase = false;
    568568    bool fDynamic = true;
    569     bool fSplit = false;
    570569
    571570    const char *pcszDisk = paScriptArgs[0].psz;
     
    584583    else if (!RTStrICmp(paScriptArgs[3].psz, "dynamic"))
    585584        fDynamic = true;
    586     else if (!RTStrICmp(paScriptArgs[3].psz, "vmdk-dynamic-split"))
    587         fSplit = true;
    588     else if (!RTStrICmp(paScriptArgs[3].psz, "vmdk-fixed-split"))
    589     {
    590         fDynamic = false;
    591         fSplit = true;
    592     }
    593585    else
    594586    {
     
    617609            if (fHonorSame)
    618610                fOpenFlags |= VD_OPEN_FLAGS_HONOR_SAME;
    619 
    620             if (fSplit)
    621                 fImageFlags |= VD_VMDK_IMAGE_FLAGS_SPLIT_2G;
    622611
    623612            if (fBase)
     
    30233012    return RTEXITCODE_SUCCESS;
    30243013}
     3014
  • trunk/src/VBox/Storage/testcase/tstVDResize.vd

    r97836 r97839  
    4040    destroydisk("test");
    4141
    42     print("Testing VMDK Monolithic Flat");
    43     createdisk("test-vmdk-mflat", true);
    44     create("test-vmdk-mflat", "base", "test-vmdk-mflat.vmdk", "Fixed", "VMDK", 4G, false, false);
    45     io("test-vmdk-mflat", false, 1, "seq", 64K, 1G, 2G, 1G, 100, "none");
    46     resize("test-vmdk-mflat", 6000M);
    47     io("test-vmdk-mflat", false, 1, "seq", 64K, 4G, 5G, 1G, 100, "none");
    48     close("test-vmdk-mflat", "single", true /* fDelete */);
    49     destroydisk("test-vmdk-mflat");
    50 
    51     print("Testing VMDK Split Flat");
    52     createdisk("test-vmdk-sflat", true);
    53     create("test-vmdk-sflat", "base", "test-vmdk-sflat.vmdk", "vmdk-fixed-split", "VMDK", 4G, false, false);
    54     io("test-vmdk-sflat", false, 1, "seq", 64K, 1G, 2G, 1G, 100, "none");
    55     resize("test-vmdk-sflat", 6000M);
    56     io("test-vmdk-sflat", false, 1, "seq", 64K, 4G, 5G, 1G, 100, "none");
    57     close("test-vmdk-sflat", "single", true /* fDelete */);
    58     destroydisk("test-vmdk-sflat");
    59 
    60     print("Testing VMDK Sparse");
    61     createdisk("test-vmdk-sparse", true);
    62     create("test-vmdk-sparse", "base", "test-vmdk-sparse.vmdk", "Dynamic", "VMDK", 4G, false, false);
    63     io("test-vmdk-sparse", false, 1, "seq", 64K, 1G, 2G, 1G, 100, "none");
    64     resize("test-vmdk-sparse", 6000M);
    65     io("test-vmdk-sparse", false, 1, "seq", 64K, 4G, 5G, 1G, 100, "none");
    66     close("test-vmdk-sparse", "single", true /* fDelete */);
    67     destroydisk("test-vmdk-sparse");
    68 
    69     print("Testing VMDK Sparse Split");
    70     createdisk("test-vmdk-sparse-split", true);
    71     create("test-vmdk-sparse-split", "base", "test-vmdk-sparse-split.vmdk", "vmdk-dynamic-split", "VMDK", 4G, false, false);
    72     io("test-vmdk-sparse-split", false, 1, "seq", 64K, 1G, 2G, 1G, 100, "none");
    73     resize("test-vmdk-sparse-split", 6000M);
    74     io("test-vmdk-sparse-split", false, 1, "seq", 64K, 4G, 5G, 1G, 100, "none");
    75     close("test-vmdk-sparse-split", "single", true /* fDelete */);
    76     destroydisk("test-vmdk-sparse-split");
     42    print("Testing VMDK Flat");
     43    createdisk("test-vmdk-flat", true);
     44    create("test-vmdk-flat", "base", "test-vmdk-flat.vmdk", "fixed", "VMDK", 10G, false, false);
     45    io("test-vmdk-flat", false, 1, "seq", 64K, 1G, 2G, 10G, 100, "none");
     46    resize("test-vmdk-flat", 20000M);
     47    close("test-vmdk-flat", "single", true /* fDelete */);
     48    destroydisk("test-vmdk-flat");
    7749
    7850    iorngdestroy();
    7951}
     52
Note: See TracChangeset for help on using the changeset viewer.

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