LCOV - code coverage report
Current view: top level - gcore - gdaldriver.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 1093 1269 86.1 %
Date: 2026-06-13 02:54:04 Functions: 49 53 92.5 %

          Line data    Source code
       1             : /******************************************************************************
       2             :  *
       3             :  * Project:  GDAL Core
       4             :  * Purpose:  Implementation of GDALDriver class (and C wrappers)
       5             :  * Author:   Frank Warmerdam, warmerdam@pobox.com
       6             :  *
       7             :  ******************************************************************************
       8             :  * Copyright (c) 1998, 2000, Frank Warmerdam
       9             :  * Copyright (c) 2007-2014, Even Rouault <even dot rouault at spatialys.com>
      10             :  *
      11             :  * SPDX-License-Identifier: MIT
      12             :  ****************************************************************************/
      13             : 
      14             : #include "cpl_port.h"
      15             : #include "gdal.h"
      16             : #include "gdal_priv.h"
      17             : #include "gdal_rat.h"
      18             : #include "gdalalgorithm.h"
      19             : #include "gdal_known_connection_prefixes.h"
      20             : 
      21             : #include <algorithm>
      22             : #include <cerrno>
      23             : #include <cstdlib>
      24             : #include <cstring>
      25             : #include <set>
      26             : #include <sys/stat.h>
      27             : 
      28             : #include "cpl_conv.h"
      29             : #include "cpl_error.h"
      30             : #include "cpl_minixml.h"
      31             : #include "cpl_multiproc.h"
      32             : #include "cpl_progress.h"
      33             : #include "cpl_string.h"
      34             : #include "cpl_vsi.h"
      35             : #include "ograpispy.h"
      36             : #include "ogr_core.h"
      37             : #include "ogrsf_frmts.h"
      38             : 
      39             : /************************************************************************/
      40             : /*                             GDALDriver()                             */
      41             : /************************************************************************/
      42             : 
      43             : GDALDriver::GDALDriver() = default;
      44             : 
      45             : /************************************************************************/
      46             : /*                            ~GDALDriver()                             */
      47             : /************************************************************************/
      48             : 
      49      530754 : GDALDriver::~GDALDriver()
      50             : 
      51             : {
      52      299152 :     if (pfnUnloadDriver != nullptr)
      53        9229 :         pfnUnloadDriver(this);
      54      530754 : }
      55             : 
      56             : /************************************************************************/
      57             : /*                          GDALCreateDriver()                          */
      58             : /************************************************************************/
      59             : 
      60             : /**
      61             :  * \brief Create a GDALDriver.
      62             :  *
      63             :  * Creates a driver in the GDAL heap.
      64             :  */
      65             : 
      66         233 : GDALDriverH CPL_STDCALL GDALCreateDriver()
      67             : {
      68         233 :     return new GDALDriver();
      69             : }
      70             : 
      71             : /************************************************************************/
      72             : /*                         GDALDestroyDriver()                          */
      73             : /************************************************************************/
      74             : 
      75             : /**
      76             :  * \brief Destroy a GDALDriver.
      77             :  *
      78             :  * This is roughly equivalent to deleting the driver, but is guaranteed
      79             :  * to take place in the GDAL heap.  It is important this that function
      80             :  * not be called on a driver that is registered with the GDALDriverManager.
      81             :  *
      82             :  * @param hDriver the driver to destroy.
      83             :  */
      84             : 
      85           0 : void CPL_STDCALL GDALDestroyDriver(GDALDriverH hDriver)
      86             : 
      87             : {
      88           0 :     if (hDriver != nullptr)
      89           0 :         delete GDALDriver::FromHandle(hDriver);
      90           0 : }
      91             : 
      92             : /************************************************************************/
      93             : /*                                Open()                                */
      94             : /************************************************************************/
      95             : 
      96             : //! @cond Doxygen_Suppress
      97             : 
      98      523152 : GDALDataset *GDALDriver::Open(GDALOpenInfo *poOpenInfo, bool bSetOpenOptions)
      99             : {
     100             : 
     101      523152 :     GDALDataset *poDS = nullptr;
     102      523152 :     pfnOpen = GetOpenCallback();
     103      523152 :     if (pfnOpen != nullptr)
     104             :     {
     105      523149 :         poDS = pfnOpen(poOpenInfo);
     106             :     }
     107           3 :     else if (pfnOpenWithDriverArg != nullptr)
     108             :     {
     109           3 :         poDS = pfnOpenWithDriverArg(this, poOpenInfo);
     110             :     }
     111             : 
     112      523152 :     if (poDS)
     113             :     {
     114             :         // Only set GDAL_OF_THREAD_SAFE if the driver itself has set it in
     115             :         // poDS->nOpenFlags
     116       62675 :         int nOpenFlags = poOpenInfo->nOpenFlags &
     117             :                          ~(GDAL_OF_FROM_GDALOPEN | GDAL_OF_THREAD_SAFE);
     118       62675 :         if (poDS->nOpenFlags & GDAL_OF_THREAD_SAFE)
     119         915 :             nOpenFlags |= GDAL_OF_THREAD_SAFE;
     120       62675 :         poDS->nOpenFlags = nOpenFlags;
     121             : 
     122       62675 :         if (strlen(poDS->GetDescription()) == 0)
     123       14251 :             poDS->SetDescription(poOpenInfo->pszFilename);
     124             : 
     125       62675 :         if (poDS->poDriver == nullptr)
     126       58698 :             poDS->poDriver = this;
     127             : 
     128       62675 :         if (poDS->papszOpenOptions == nullptr && bSetOpenOptions)
     129             :         {
     130          29 :             poDS->papszOpenOptions = CSLDuplicate(poOpenInfo->papszOpenOptions);
     131             :         }
     132             : 
     133       62675 :         if (!(poOpenInfo->nOpenFlags & GDAL_OF_INTERNAL))
     134             :         {
     135       50115 :             if (CPLGetPID() != GDALGetResponsiblePIDForCurrentThread())
     136           6 :                 CPLDebug(
     137             :                     "GDAL",
     138             :                     "GDALOpen(%s, this=%p) succeeds as "
     139             :                     "%s (pid=%d, responsiblePID=%d).",
     140           6 :                     poOpenInfo->pszFilename, poDS, GetDescription(),
     141           6 :                     static_cast<int>(CPLGetPID()),
     142           6 :                     static_cast<int>(GDALGetResponsiblePIDForCurrentThread()));
     143             :             else
     144       50109 :                 CPLDebug("GDAL", "GDALOpen(%s, this=%p) succeeds as %s.",
     145       50109 :                          poOpenInfo->pszFilename, poDS, GetDescription());
     146             : 
     147       50115 :             poDS->AddToDatasetOpenList();
     148             :         }
     149             :     }
     150             : 
     151      523152 :     return poDS;
     152             : }
     153             : 
     154             : //! @endcond
     155             : 
     156             : /************************************************************************/
     157             : /*                               Create()                               */
     158             : /************************************************************************/
     159             : 
     160             : /**
     161             :  * \brief Create a new dataset with this driver.
     162             :  *
     163             :  * What argument values are legal for particular drivers is driver specific,
     164             :  * and there is no way to query in advance to establish legal values.
     165             :  *
     166             :  * That function will try to validate the creation option list passed to the
     167             :  * driver with the GDALValidateCreationOptions() method. This check can be
     168             :  * disabled by defining the configuration option
     169             :  * GDAL_VALIDATE_CREATION_OPTIONS=NO.
     170             :  *
     171             :  * After you have finished working with the returned dataset, it is
     172             :  * <b>required</b> to close it with GDALClose(). This does not only close the
     173             :  * file handle, but also ensures that all the data and metadata has been written
     174             :  * to the dataset (GDALFlushCache() is not sufficient for that purpose).
     175             :  *
     176             :  * The arguments nXSize, nYSize and nBands can be passed to 0 when
     177             :  * creating a vector-only dataset for a compatible driver.
     178             :  *
     179             :  * Equivalent of the C function GDALCreate().
     180             :  *
     181             :  * @param pszFilename the name of the dataset to create.  UTF-8 encoded.
     182             :  * @param nXSize width of created raster in pixels.
     183             :  * @param nYSize height of created raster in pixels.
     184             :  * @param nBands number of bands.
     185             :  * @param eType type of raster.
     186             :  * @param papszOptions list of driver specific control parameters.
     187             :  * The APPEND_SUBDATASET=YES option can be
     188             :  * specified to avoid prior destruction of existing dataset.
     189             :  *
     190             :  * @return NULL on failure, or a new GDALDataset.
     191             :  */
     192             : 
     193       25704 : GDALDataset *GDALDriver::Create(const char *pszFilename, int nXSize, int nYSize,
     194             :                                 int nBands, GDALDataType eType,
     195             :                                 CSLConstList papszOptions)
     196             : 
     197             : {
     198             :     /* -------------------------------------------------------------------- */
     199             :     /*      Does this format support creation.                              */
     200             :     /* -------------------------------------------------------------------- */
     201       25704 :     pfnCreate = GetCreateCallback();
     202       25704 :     if (CPL_UNLIKELY(pfnCreate == nullptr && pfnCreateEx == nullptr &&
     203             :                      pfnCreateVectorOnly == nullptr))
     204             :     {
     205           1 :         CPLError(CE_Failure, CPLE_NotSupported,
     206             :                  "GDALDriver::Create() ... no create method implemented"
     207             :                  " for this format.");
     208             : 
     209           1 :         return nullptr;
     210             :     }
     211             :     /* -------------------------------------------------------------------- */
     212             :     /*      Do some rudimentary argument checking.                          */
     213             :     /* -------------------------------------------------------------------- */
     214       25703 :     if (CPL_UNLIKELY(nBands < 0))
     215             :     {
     216           1 :         CPLError(CE_Failure, CPLE_AppDefined,
     217             :                  "Attempt to create dataset with %d bands is illegal, "
     218             :                  "Must be >= 0.",
     219             :                  nBands);
     220           1 :         return nullptr;
     221             :     }
     222             : 
     223       25702 :     if (CPL_UNLIKELY(GetMetadataItem(GDAL_DCAP_RASTER) != nullptr &&
     224             :                      GetMetadataItem(GDAL_DCAP_VECTOR) == nullptr &&
     225       25702 :                      (nXSize < 1 || nYSize < 1)))
     226             :     {
     227           2 :         CPLError(CE_Failure, CPLE_AppDefined,
     228             :                  "Attempt to create %dx%d dataset is illegal, "
     229             :                  "sizes must be larger than zero.",
     230             :                  nXSize, nYSize);
     231           2 :         return nullptr;
     232             :     }
     233             : 
     234       25700 :     if (CPL_UNLIKELY(nBands != 0 &&
     235             :                      (eType == GDT_Unknown || eType == GDT_TypeCount)))
     236             :     {
     237           1 :         CPLError(CE_Failure, CPLE_IllegalArg,
     238             :                  "Illegal GDT_Unknown/GDT_TypeCount argument");
     239           1 :         return nullptr;
     240             :     }
     241             : 
     242             :     /* -------------------------------------------------------------------- */
     243             :     /*      Make sure we cleanup if there is an existing dataset of this    */
     244             :     /*      name.  But even if that seems to fail we will continue since    */
     245             :     /*      it might just be a corrupt file or something.                   */
     246             :     /* -------------------------------------------------------------------- */
     247       25699 :     if (!CPLFetchBool(papszOptions, "APPEND_SUBDATASET", false))
     248             :     {
     249             :         // Someone issuing Create("foo.tif") on a
     250             :         // memory driver doesn't expect files with those names to be deleted
     251             :         // on a file system...
     252             :         // This is somewhat messy. Ideally there should be a way for the
     253             :         // driver to overload the default behavior
     254       25680 :         if (!EQUAL(GetDescription(), "MEM") &&
     255       39500 :             !EQUAL(GetDescription(), "Memory") &&
     256             :             // ogr2ogr -f PostgreSQL might reach the Delete method of the
     257             :             // PostgisRaster driver which is undesirable
     258       13820 :             !EQUAL(GetDescription(), "PostgreSQL"))
     259             :         {
     260       13818 :             QuietDelete(pszFilename);
     261             :         }
     262             :     }
     263             : 
     264             :     /* -------------------------------------------------------------------- */
     265             :     /*      Validate creation options.                                      */
     266             :     /* -------------------------------------------------------------------- */
     267       25699 :     if (CPLTestBool(
     268             :             CPLGetConfigOption("GDAL_VALIDATE_CREATION_OPTIONS", "YES")))
     269       25699 :         GDALValidateCreationOptions(this, papszOptions);
     270             : 
     271             :     /* -------------------------------------------------------------------- */
     272             :     /*      Proceed with creation.                                          */
     273             :     /* -------------------------------------------------------------------- */
     274       51398 :     CPLDebug("GDAL", "GDALDriver::Create(%s,%s,%d,%d,%d,%s,%p)",
     275       25699 :              GetDescription(), pszFilename, nXSize, nYSize, nBands,
     276             :              GDALGetDataTypeName(eType), papszOptions);
     277             : 
     278       25699 :     GDALDataset *poDS = nullptr;
     279       25699 :     if (pfnCreateEx != nullptr)
     280             :     {
     281           0 :         poDS = pfnCreateEx(this, pszFilename, nXSize, nYSize, nBands, eType,
     282             :                            const_cast<char **>(papszOptions));
     283             :     }
     284       25699 :     else if (pfnCreate != nullptr)
     285             :     {
     286       25699 :         poDS = pfnCreate(pszFilename, nXSize, nYSize, nBands, eType,
     287             :                          const_cast<char **>(papszOptions));
     288             :     }
     289           0 :     else if (nBands < 1)
     290             :     {
     291           0 :         poDS = pfnCreateVectorOnly(this, pszFilename,
     292             :                                    const_cast<char **>(papszOptions));
     293             :     }
     294             : 
     295       25699 :     if (poDS != nullptr)
     296             :     {
     297       48734 :         if (poDS->GetDescription() == nullptr ||
     298       24367 :             strlen(poDS->GetDescription()) == 0)
     299       21676 :             poDS->SetDescription(pszFilename);
     300             : 
     301       24367 :         if (poDS->poDriver == nullptr)
     302       23873 :             poDS->poDriver = this;
     303             : 
     304       24367 :         poDS->AddToDatasetOpenList();
     305             :     }
     306             : 
     307       25699 :     return poDS;
     308             : }
     309             : 
     310             : /************************************************************************/
     311             : /*                             GDALCreate()                             */
     312             : /************************************************************************/
     313             : 
     314             : /**
     315             :  * \brief Create a new dataset with this driver.
     316             :  *
     317             :  * @see GDALDriver::Create()
     318             :  */
     319             : 
     320       21134 : GDALDatasetH CPL_DLL CPL_STDCALL GDALCreate(GDALDriverH hDriver,
     321             :                                             const char *pszFilename, int nXSize,
     322             :                                             int nYSize, int nBands,
     323             :                                             GDALDataType eBandType,
     324             :                                             CSLConstList papszOptions)
     325             : 
     326             : {
     327       21134 :     VALIDATE_POINTER1(hDriver, "GDALCreate", nullptr);
     328             : 
     329       21134 :     GDALDatasetH hDS = GDALDriver::FromHandle(hDriver)->Create(
     330             :         pszFilename, nXSize, nYSize, nBands, eBandType, papszOptions);
     331             : 
     332             : #ifdef OGRAPISPY_ENABLED
     333       21134 :     if (nBands < 1)
     334             :     {
     335        3975 :         OGRAPISpyCreateDataSource(hDriver, pszFilename,
     336             :                                   const_cast<char **>(papszOptions), hDS);
     337             :     }
     338             : #endif
     339             : 
     340       21134 :     return hDS;
     341             : }
     342             : 
     343             : /************************************************************************/
     344             : /*                       CreateMultiDimensional()                       */
     345             : /************************************************************************/
     346             : 
     347             : /**
     348             :  * \brief Create a new multidimensional dataset with this driver.
     349             :  *
     350             :  * Only drivers that advertise the GDAL_DCAP_MULTIDIM_RASTER capability and
     351             :  * implement the pfnCreateMultiDimensional method might return a non nullptr
     352             :  * GDALDataset.
     353             :  *
     354             :  * This is the same as the C function GDALCreateMultiDimensional().
     355             :  *
     356             :  * @param pszFilename  the name of the dataset to create.  UTF-8 encoded.
     357             :  * @param papszRootGroupOptions driver specific options regarding the creation
     358             :  *                              of the root group. Might be nullptr.
     359             :  * @param papszOptions driver specific options regarding the creation
     360             :  *                     of the dataset. Might be nullptr.
     361             :  * @return a new dataset, or nullptr in case of failure.
     362             :  *
     363             :  * @since GDAL 3.1
     364             :  */
     365             : 
     366             : GDALDataset *
     367         571 : GDALDriver::CreateMultiDimensional(const char *pszFilename,
     368             :                                    CSLConstList papszRootGroupOptions,
     369             :                                    CSLConstList papszOptions)
     370             : 
     371             : {
     372             :     /* -------------------------------------------------------------------- */
     373             :     /*      Does this format support creation.                              */
     374             :     /* -------------------------------------------------------------------- */
     375         571 :     pfnCreateMultiDimensional = GetCreateMultiDimensionalCallback();
     376         571 :     if (pfnCreateMultiDimensional == nullptr)
     377             :     {
     378           0 :         CPLError(CE_Failure, CPLE_NotSupported,
     379             :                  "GDALDriver::CreateMultiDimensional() ... "
     380             :                  "no CreateMultiDimensional method implemented "
     381             :                  "for this format.");
     382             : 
     383           0 :         return nullptr;
     384             :     }
     385             : 
     386             :     /* -------------------------------------------------------------------- */
     387             :     /*      Validate creation options.                                      */
     388             :     /* -------------------------------------------------------------------- */
     389         571 :     if (CPLTestBool(
     390             :             CPLGetConfigOption("GDAL_VALIDATE_CREATION_OPTIONS", "YES")))
     391             :     {
     392             :         const char *pszOptionList =
     393         571 :             GetMetadataItem(GDAL_DMD_MULTIDIM_DATASET_CREATIONOPTIONLIST);
     394        1142 :         CPLString osDriver;
     395         571 :         osDriver.Printf("driver %s", GetDescription());
     396         571 :         GDALValidateOptions(GDALDriver::ToHandle(this), pszOptionList,
     397             :                             papszOptions, "creation option", osDriver);
     398             :     }
     399             : 
     400         571 :     auto poDstDS = pfnCreateMultiDimensional(pszFilename, papszRootGroupOptions,
     401             :                                              papszOptions);
     402             : 
     403         571 :     if (poDstDS != nullptr)
     404             :     {
     405        1138 :         if (poDstDS->GetDescription() == nullptr ||
     406         569 :             strlen(poDstDS->GetDescription()) == 0)
     407         148 :             poDstDS->SetDescription(pszFilename);
     408             : 
     409         569 :         if (poDstDS->poDriver == nullptr)
     410         567 :             poDstDS->poDriver = this;
     411             :     }
     412             : 
     413         571 :     return poDstDS;
     414             : }
     415             : 
     416             : /************************************************************************/
     417             : /*                     GDALCreateMultiDimensional()                     */
     418             : /************************************************************************/
     419             : 
     420             : /** \brief Create a new multidimensional dataset with this driver.
     421             :  *
     422             :  * This is the same as the C++ method GDALDriver::CreateMultiDimensional().
     423             :  */
     424         518 : GDALDatasetH GDALCreateMultiDimensional(GDALDriverH hDriver,
     425             :                                         const char *pszName,
     426             :                                         CSLConstList papszRootGroupOptions,
     427             :                                         CSLConstList papszOptions)
     428             : {
     429         518 :     VALIDATE_POINTER1(hDriver, __func__, nullptr);
     430         518 :     VALIDATE_POINTER1(pszName, __func__, nullptr);
     431         518 :     return GDALDataset::ToHandle(
     432             :         GDALDriver::FromHandle(hDriver)->CreateMultiDimensional(
     433         518 :             pszName, papszRootGroupOptions, papszOptions));
     434             : }
     435             : 
     436             : /************************************************************************/
     437             : /*                 DefaultCreateCopyMultiDimensional()                  */
     438             : /************************************************************************/
     439             : 
     440             : //! @cond Doxygen_Suppress
     441             : 
     442          28 : CPLErr GDALDriver::DefaultCreateCopyMultiDimensional(
     443             :     GDALDataset *poSrcDS, GDALDataset *poDstDS, bool bStrict,
     444             :     CSLConstList papszOptions, GDALProgressFunc pfnProgress,
     445             :     void *pProgressData)
     446             : {
     447          28 :     if (pfnProgress == nullptr)
     448           3 :         pfnProgress = GDALDummyProgress;
     449             : 
     450          56 :     auto poSrcRG = poSrcDS->GetRootGroup();
     451          28 :     if (!poSrcRG)
     452           0 :         return CE_Failure;
     453          56 :     auto poDstRG = poDstDS->GetRootGroup();
     454          28 :     if (!poDstRG)
     455           0 :         return CE_Failure;
     456          28 :     GUInt64 nCurCost = 0;
     457          56 :     return poDstRG->CopyFrom(poDstRG, poSrcDS, poSrcRG, bStrict, nCurCost,
     458             :                              poSrcRG->GetTotalCopyCost(), pfnProgress,
     459          28 :                              pProgressData, papszOptions)
     460          28 :                ? CE_None
     461          28 :                : CE_Failure;
     462             : }
     463             : 
     464             : //! @endcond
     465             : 
     466             : /************************************************************************/
     467             : /*                          DefaultCopyMasks()                          */
     468             : /************************************************************************/
     469             : 
     470             : //! @cond Doxygen_Suppress
     471        6296 : CPLErr GDALDriver::DefaultCopyMasks(GDALDataset *poSrcDS, GDALDataset *poDstDS,
     472             :                                     int bStrict)
     473             : 
     474             : {
     475        6296 :     return DefaultCopyMasks(poSrcDS, poDstDS, bStrict, nullptr, nullptr,
     476        6296 :                             nullptr);
     477             : }
     478             : 
     479        8391 : CPLErr GDALDriver::DefaultCopyMasks(GDALDataset *poSrcDS, GDALDataset *poDstDS,
     480             :                                     int bStrict, CSLConstList /*papszOptions*/,
     481             :                                     GDALProgressFunc pfnProgress,
     482             :                                     void *pProgressData)
     483             : 
     484             : {
     485        8391 :     if (pfnProgress == nullptr)
     486        6296 :         pfnProgress = GDALDummyProgress;
     487             : 
     488        8391 :     int nBands = poSrcDS->GetRasterCount();
     489        8391 :     if (nBands == 0)
     490           0 :         return CE_None;
     491             : 
     492             :     /* -------------------------------------------------------------------- */
     493             :     /*      Try to copy mask if it seems appropriate.                       */
     494             :     /* -------------------------------------------------------------------- */
     495        8391 :     const char *papszOptions[2] = {"COMPRESSED=YES", nullptr};
     496        8391 :     CPLErr eErr = CE_None;
     497             : 
     498        8391 :     int nTotalBandsWithMask = 0;
     499       29007 :     for (int iBand = 0; iBand < nBands; ++iBand)
     500             :     {
     501       20616 :         GDALRasterBand *poSrcBand = poSrcDS->GetRasterBand(iBand + 1);
     502             : 
     503       20616 :         int nMaskFlags = poSrcBand->GetMaskFlags();
     504       20616 :         if (!(nMaskFlags &
     505             :               (GMF_ALL_VALID | GMF_PER_DATASET | GMF_ALPHA | GMF_NODATA)))
     506             :         {
     507           8 :             nTotalBandsWithMask++;
     508             :         }
     509             :     }
     510             : 
     511        8391 :     int iBandWithMask = 0;
     512       29007 :     for (int iBand = 0; eErr == CE_None && iBand < nBands; ++iBand)
     513             :     {
     514       20616 :         GDALRasterBand *poSrcBand = poSrcDS->GetRasterBand(iBand + 1);
     515             : 
     516       20616 :         int nMaskFlags = poSrcBand->GetMaskFlags();
     517       20616 :         if (eErr == CE_None && !(nMaskFlags & (GMF_ALL_VALID | GMF_PER_DATASET |
     518             :                                                GMF_ALPHA | GMF_NODATA)))
     519             :         {
     520           8 :             GDALRasterBand *poDstBand = poDstDS->GetRasterBand(iBand + 1);
     521           8 :             if (poDstBand != nullptr)
     522             :             {
     523           8 :                 eErr = poDstBand->CreateMaskBand(nMaskFlags);
     524           8 :                 if (eErr == CE_None)
     525             :                 {
     526          24 :                     void *pScaledData = GDALCreateScaledProgress(
     527           8 :                         double(iBandWithMask) /
     528           8 :                             std::max(1, nTotalBandsWithMask),
     529           8 :                         double(iBandWithMask + 1) /
     530           8 :                             std::max(1, nTotalBandsWithMask),
     531             :                         pfnProgress, pProgressData);
     532          16 :                     eErr = GDALRasterBandCopyWholeRaster(
     533           8 :                         poSrcBand->GetMaskBand(), poDstBand->GetMaskBand(),
     534             :                         papszOptions, GDALScaledProgress, pScaledData);
     535           8 :                     GDALDestroyScaledProgress(pScaledData);
     536             :                 }
     537           0 :                 else if (!bStrict)
     538             :                 {
     539           0 :                     eErr = CE_None;
     540             :                 }
     541             :             }
     542             :         }
     543             :     }
     544             : 
     545             :     /* -------------------------------------------------------------------- */
     546             :     /*      Try to copy a per-dataset mask if we have one.                  */
     547             :     /* -------------------------------------------------------------------- */
     548        8391 :     const int nMaskFlags = poSrcDS->GetRasterBand(1)->GetMaskFlags();
     549        8391 :     if (eErr == CE_None &&
     550        8391 :         !(nMaskFlags & (GMF_ALL_VALID | GMF_ALPHA | GMF_NODATA)) &&
     551          13 :         (nMaskFlags & GMF_PER_DATASET))
     552             :     {
     553           8 :         eErr = poDstDS->CreateMaskBand(nMaskFlags);
     554           8 :         if (eErr == CE_None)
     555             :         {
     556           8 :             eErr = GDALRasterBandCopyWholeRaster(
     557           8 :                 poSrcDS->GetRasterBand(1)->GetMaskBand(),
     558           8 :                 poDstDS->GetRasterBand(1)->GetMaskBand(), papszOptions,
     559             :                 pfnProgress, pProgressData);
     560             :         }
     561           0 :         else if (!bStrict)
     562             :         {
     563           0 :             eErr = CE_None;
     564             :         }
     565             :     }
     566             : 
     567        8391 :     return eErr;
     568             : }
     569             : 
     570             : /************************************************************************/
     571             : /*                         DefaultCreateCopy()                          */
     572             : /************************************************************************/
     573             : 
     574        1491 : GDALDataset *GDALDriver::DefaultCreateCopy(const char *pszFilename,
     575             :                                            GDALDataset *poSrcDS, int bStrict,
     576             :                                            CSLConstList papszOptions,
     577             :                                            GDALProgressFunc pfnProgress,
     578             :                                            void *pProgressData)
     579             : 
     580             : {
     581        1491 :     if (pfnProgress == nullptr)
     582           0 :         pfnProgress = GDALDummyProgress;
     583             : 
     584        1491 :     CPLErrorReset();
     585             : 
     586             :     /* -------------------------------------------------------------------- */
     587             :     /*      Use multidimensional raster API if available.                   */
     588             :     /* -------------------------------------------------------------------- */
     589        2982 :     auto poSrcGroup = poSrcDS->GetRootGroup();
     590        1491 :     if (poSrcGroup != nullptr && GetMetadataItem(GDAL_DCAP_MULTIDIM_RASTER))
     591             :     {
     592          50 :         CPLStringList aosDatasetCO;
     593          32 :         for (const char *pszOption : cpl::Iterate(papszOptions))
     594             :         {
     595           7 :             if (!STARTS_WITH_CI(pszOption, "ARRAY:"))
     596           0 :                 aosDatasetCO.AddString(pszOption);
     597             :         }
     598             :         auto poDstDS = std::unique_ptr<GDALDataset>(
     599          50 :             CreateMultiDimensional(pszFilename, nullptr, aosDatasetCO.List()));
     600          25 :         if (!poDstDS)
     601           0 :             return nullptr;
     602          50 :         auto poDstGroup = poDstDS->GetRootGroup();
     603          25 :         if (!poDstGroup)
     604           0 :             return nullptr;
     605          25 :         if (DefaultCreateCopyMultiDimensional(
     606          25 :                 poSrcDS, poDstDS.get(), CPL_TO_BOOL(bStrict), papszOptions,
     607          25 :                 pfnProgress, pProgressData) != CE_None)
     608           0 :             return nullptr;
     609          25 :         return poDstDS.release();
     610             :     }
     611             : 
     612             :     /* -------------------------------------------------------------------- */
     613             :     /*      Validate that we can create the output as requested.            */
     614             :     /* -------------------------------------------------------------------- */
     615        1466 :     const int nXSize = poSrcDS->GetRasterXSize();
     616        1466 :     const int nYSize = poSrcDS->GetRasterYSize();
     617        1466 :     const int nBands = poSrcDS->GetRasterCount();
     618             : 
     619        1466 :     CPLDebug("GDAL", "Using default GDALDriver::CreateCopy implementation.");
     620             : 
     621        1466 :     const int nLayerCount = poSrcDS->GetLayerCount();
     622        1490 :     if (nBands == 0 && nLayerCount == 0 &&
     623          24 :         GetMetadataItem(GDAL_DCAP_VECTOR) == nullptr)
     624             :     {
     625          17 :         CPLError(CE_Failure, CPLE_NotSupported,
     626             :                  "GDALDriver::DefaultCreateCopy does not support zero band");
     627          17 :         return nullptr;
     628             :     }
     629        1449 :     if (poSrcDS->GetDriver() != nullptr &&
     630        1419 :         poSrcDS->GetDriver()->GetMetadataItem(GDAL_DCAP_RASTER) != nullptr &&
     631        1412 :         poSrcDS->GetDriver()->GetMetadataItem(GDAL_DCAP_VECTOR) == nullptr &&
     632        2871 :         GetMetadataItem(GDAL_DCAP_RASTER) == nullptr &&
     633           3 :         GetMetadataItem(GDAL_DCAP_VECTOR) != nullptr)
     634             :     {
     635           3 :         CPLError(CE_Failure, CPLE_NotSupported,
     636             :                  "Source driver is raster-only whereas output driver is "
     637             :                  "vector-only");
     638           3 :         return nullptr;
     639             :     }
     640        1446 :     else if (poSrcDS->GetDriver() != nullptr &&
     641        1416 :              poSrcDS->GetDriver()->GetMetadataItem(GDAL_DCAP_RASTER) ==
     642           7 :                  nullptr &&
     643           7 :              poSrcDS->GetDriver()->GetMetadataItem(GDAL_DCAP_VECTOR) !=
     644           7 :                  nullptr &&
     645        2862 :              GetMetadataItem(GDAL_DCAP_RASTER) != nullptr &&
     646           0 :              GetMetadataItem(GDAL_DCAP_VECTOR) == nullptr)
     647             :     {
     648           0 :         CPLError(CE_Failure, CPLE_NotSupported,
     649             :                  "Source driver is vector-only whereas output driver is "
     650             :                  "raster-only");
     651           0 :         return nullptr;
     652             :     }
     653             : 
     654        1446 :     if (!pfnProgress(0.0, nullptr, pProgressData))
     655             :     {
     656           2 :         CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated");
     657           2 :         return nullptr;
     658             :     }
     659             : 
     660             :     /* -------------------------------------------------------------------- */
     661             :     /*      Propagate some specific structural metadata as options if it    */
     662             :     /*      appears to be supported by the target driver and the caller     */
     663             :     /*      didn't provide values.                                          */
     664             :     /* -------------------------------------------------------------------- */
     665        1444 :     char **papszCreateOptions = CSLDuplicate(papszOptions);
     666        1444 :     const char *const apszOptItems[] = {GDALMD_NBITS, GDAL_MDD_IMAGE_STRUCTURE,
     667             :                                         "PIXELTYPE", GDAL_MDD_IMAGE_STRUCTURE,
     668             :                                         nullptr};
     669             : 
     670        4300 :     for (int iOptItem = 0; nBands > 0 && apszOptItems[iOptItem] != nullptr;
     671        2856 :          iOptItem += 2)
     672             :     {
     673             :         // does the source have this metadata item on the first band?
     674        2856 :         auto poBand = poSrcDS->GetRasterBand(1);
     675        2856 :         poBand->EnablePixelTypeSignedByteWarning(false);
     676        5712 :         const char *pszValue = poBand->GetMetadataItem(
     677        2856 :             apszOptItems[iOptItem], apszOptItems[iOptItem + 1]);
     678        2856 :         poBand->EnablePixelTypeSignedByteWarning(true);
     679             : 
     680        2856 :         if (pszValue == nullptr)
     681        2854 :             continue;
     682             : 
     683             :         // Do not override provided value.
     684           2 :         if (CSLFetchNameValue(papszCreateOptions, pszValue) != nullptr)
     685           0 :             continue;
     686             : 
     687             :         // Does this appear to be a supported creation option on this driver?
     688             :         const char *pszOptionList =
     689           2 :             GetMetadataItem(GDAL_DMD_CREATIONOPTIONLIST);
     690             : 
     691           2 :         if (pszOptionList == nullptr ||
     692           2 :             strstr(pszOptionList, apszOptItems[iOptItem]) == nullptr)
     693           0 :             continue;
     694             : 
     695           2 :         papszCreateOptions = CSLSetNameValue(papszCreateOptions,
     696           2 :                                              apszOptItems[iOptItem], pszValue);
     697             :     }
     698             : 
     699             :     /* -------------------------------------------------------------------- */
     700             :     /*      Create destination dataset.                                     */
     701             :     /* -------------------------------------------------------------------- */
     702        1444 :     GDALDataType eType = GDT_Unknown;
     703             : 
     704        1444 :     if (nBands > 0)
     705        1428 :         eType = poSrcDS->GetRasterBand(1)->GetRasterDataType();
     706             :     GDALDataset *poDstDS =
     707        1444 :         Create(pszFilename, nXSize, nYSize, nBands, eType, papszCreateOptions);
     708             : 
     709        1444 :     CSLDestroy(papszCreateOptions);
     710             : 
     711        1444 :     if (poDstDS == nullptr)
     712         326 :         return nullptr;
     713             : 
     714        1118 :     int nDstBands = poDstDS->GetRasterCount();
     715        1118 :     CPLErr eErr = CE_None;
     716        1118 :     if (nDstBands != nBands)
     717             :     {
     718           0 :         if (GetMetadataItem(GDAL_DCAP_RASTER) != nullptr)
     719             :         {
     720             :             // Should not happen for a well-behaved driver.
     721           0 :             CPLError(
     722             :                 CE_Failure, CPLE_AppDefined,
     723             :                 "Output driver created only %d bands whereas %d were expected",
     724             :                 nDstBands, nBands);
     725           0 :             eErr = CE_Failure;
     726             :         }
     727           0 :         nDstBands = 0;
     728             :     }
     729             : 
     730             :     /* -------------------------------------------------------------------- */
     731             :     /*      Try setting the projection and geotransform if it seems         */
     732             :     /*      suitable.                                                       */
     733             :     /* -------------------------------------------------------------------- */
     734        1118 :     if (nDstBands == 0 && !bStrict)
     735           4 :         CPLTurnFailureIntoWarning(true);
     736             : 
     737        1118 :     GDALGeoTransform gt;
     738        2109 :     if (eErr == CE_None && poSrcDS->GetGeoTransform(gt) == CE_None &&
     739        2109 :         gt != GDALGeoTransform())
     740             :     {
     741         989 :         eErr = poDstDS->SetGeoTransform(gt);
     742         989 :         if (!bStrict)
     743         632 :             eErr = CE_None;
     744             :     }
     745             : 
     746        1118 :     if (eErr == CE_None)
     747             :     {
     748        1109 :         const auto poSrcSRS = poSrcDS->GetSpatialRefRasterOnly();
     749        1109 :         if (poSrcSRS && !poSrcSRS->IsEmpty())
     750             :         {
     751         927 :             eErr = poDstDS->SetSpatialRef(poSrcSRS);
     752         927 :             if (!bStrict)
     753         602 :                 eErr = CE_None;
     754             :         }
     755             :     }
     756             : 
     757             :     /* -------------------------------------------------------------------- */
     758             :     /*      Copy GCPs.                                                      */
     759             :     /* -------------------------------------------------------------------- */
     760        1118 :     if (poSrcDS->GetGCPCount() > 0 && eErr == CE_None)
     761             :     {
     762           2 :         eErr = poDstDS->SetGCPs(poSrcDS->GetGCPCount(), poSrcDS->GetGCPs(),
     763             :                                 poSrcDS->GetGCPProjection());
     764           2 :         if (!bStrict)
     765           1 :             eErr = CE_None;
     766             :     }
     767             : 
     768        1118 :     if (nDstBands == 0 && !bStrict)
     769           4 :         CPLTurnFailureIntoWarning(false);
     770             : 
     771             :     /* -------------------------------------------------------------------- */
     772             :     /*      Copy metadata.                                                  */
     773             :     /* -------------------------------------------------------------------- */
     774        1118 :     DefaultCopyMetadata(poSrcDS, poDstDS, papszOptions, nullptr);
     775             : 
     776             :     /* -------------------------------------------------------------------- */
     777             :     /*      Loop copying bands.                                             */
     778             :     /* -------------------------------------------------------------------- */
     779        2895 :     for (int iBand = 0; eErr == CE_None && iBand < nDstBands; ++iBand)
     780             :     {
     781        1777 :         GDALRasterBand *const poSrcBand = poSrcDS->GetRasterBand(iBand + 1);
     782        1777 :         GDALRasterBand *const poDstBand = poDstDS->GetRasterBand(iBand + 1);
     783             : 
     784             :         /* --------------------------------------------------------------------
     785             :          */
     786             :         /*      Do we need to copy a colortable. */
     787             :         /* --------------------------------------------------------------------
     788             :          */
     789        1777 :         GDALColorTable *const poCT = poSrcBand->GetColorTable();
     790        1777 :         if (poCT != nullptr)
     791          41 :             poDstBand->SetColorTable(poCT);
     792             : 
     793             :         /* --------------------------------------------------------------------
     794             :          */
     795             :         /*      Do we need to copy other metadata?  Most of this is */
     796             :         /*      non-critical, so lets not bother folks if it fails are we */
     797             :         /*      are not in strict mode. */
     798             :         /* --------------------------------------------------------------------
     799             :          */
     800        1777 :         if (!bStrict)
     801        1143 :             CPLTurnFailureIntoWarning(true);
     802             : 
     803        1777 :         if (strlen(poSrcBand->GetDescription()) > 0)
     804          53 :             poDstBand->SetDescription(poSrcBand->GetDescription());
     805             : 
     806        1777 :         if (CSLCount(poSrcBand->GetMetadata()) > 0)
     807         116 :             poDstBand->SetMetadata(poSrcBand->GetMetadata());
     808             : 
     809        1777 :         int bSuccess = FALSE;
     810        1777 :         double dfValue = poSrcBand->GetOffset(&bSuccess);
     811        1777 :         if (bSuccess && dfValue != 0.0)
     812           5 :             poDstBand->SetOffset(dfValue);
     813             : 
     814        1777 :         dfValue = poSrcBand->GetScale(&bSuccess);
     815        1777 :         if (bSuccess && dfValue != 1.0)
     816           4 :             poDstBand->SetScale(dfValue);
     817             : 
     818        1777 :         GDALCopyNoDataValue(poDstBand, poSrcBand);
     819             : 
     820        2959 :         if (poSrcBand->GetColorInterpretation() != GCI_Undefined &&
     821        1182 :             poSrcBand->GetColorInterpretation() !=
     822        1182 :                 poDstBand->GetColorInterpretation())
     823         950 :             poDstBand->SetColorInterpretation(
     824         950 :                 poSrcBand->GetColorInterpretation());
     825             : 
     826        1777 :         char **papszCatNames = poSrcBand->GetCategoryNames();
     827        1777 :         if (nullptr != papszCatNames)
     828           1 :             poDstBand->SetCategoryNames(papszCatNames);
     829             : 
     830             :         // Only copy RAT if it is of reasonable size to fit in memory
     831        1777 :         GDALRasterAttributeTable *poRAT = poSrcBand->GetDefaultRAT();
     832        1779 :         if (poRAT != nullptr && static_cast<GIntBig>(poRAT->GetColumnCount()) *
     833           2 :                                         poRAT->GetRowCount() <
     834             :                                     1024 * 1024)
     835             :         {
     836           2 :             poDstBand->SetDefaultRAT(poRAT);
     837             :         }
     838             : 
     839        1777 :         if (!bStrict)
     840             :         {
     841        1143 :             CPLTurnFailureIntoWarning(false);
     842             :         }
     843             :         else
     844             :         {
     845         634 :             eErr = CPLGetLastErrorType();
     846             :         }
     847             :     }
     848             : 
     849             :     /* -------------------------------------------------------------------- */
     850             :     /*      Copy image data.                                                */
     851             :     /* -------------------------------------------------------------------- */
     852        1118 :     if (eErr == CE_None && nDstBands > 0)
     853             :     {
     854        1074 :         const char *const apszCopyRasterOptionsSkipHoles[] = {"SKIP_HOLES=YES",
     855             :                                                               nullptr};
     856        1074 :         const bool bSkipHoles = CPLTestBool(
     857             :             CSLFetchNameValueDef(papszOptions, "SKIP_HOLES", "FALSE"));
     858        1074 :         eErr = GDALDatasetCopyWholeRaster(
     859             :             poSrcDS, poDstDS,
     860             :             bSkipHoles ? apszCopyRasterOptionsSkipHoles : nullptr, pfnProgress,
     861             :             pProgressData);
     862             :     }
     863             : 
     864             :     /* -------------------------------------------------------------------- */
     865             :     /*      Should we copy some masks over?                                 */
     866             :     /* -------------------------------------------------------------------- */
     867        1118 :     if (eErr == CE_None && nDstBands > 0)
     868        1055 :         eErr = DefaultCopyMasks(poSrcDS, poDstDS, eErr);
     869             : 
     870             :     /* -------------------------------------------------------------------- */
     871             :     /*      Copy vector layers                                              */
     872             :     /* -------------------------------------------------------------------- */
     873        1118 :     if (eErr == CE_None)
     874             :     {
     875        1068 :         if (nLayerCount > 0 && poDstDS->TestCapability(ODsCCreateLayer))
     876             :         {
     877          20 :             for (int iLayer = 0; iLayer < nLayerCount; ++iLayer)
     878             :             {
     879          10 :                 OGRLayer *poLayer = poSrcDS->GetLayer(iLayer);
     880             : 
     881          10 :                 if (poLayer == nullptr)
     882           0 :                     continue;
     883             : 
     884          10 :                 poDstDS->CopyLayer(poLayer, poLayer->GetName(), nullptr);
     885             :             }
     886             :         }
     887             :     }
     888             : 
     889             :     /* -------------------------------------------------------------------- */
     890             :     /*      Try to cleanup the output dataset if the translation failed.    */
     891             :     /* -------------------------------------------------------------------- */
     892        1118 :     if (eErr != CE_None)
     893             :     {
     894          50 :         delete poDstDS;
     895          50 :         if (!CPLFetchBool(papszOptions, "APPEND_SUBDATASET", false))
     896             :         {
     897             :             // Only delete if creating a new file
     898          50 :             Delete(pszFilename);
     899             :         }
     900          50 :         return nullptr;
     901             :     }
     902             :     else
     903             :     {
     904        1068 :         CPLErrorReset();
     905             :     }
     906             : 
     907        1068 :     return poDstDS;
     908             : }
     909             : 
     910             : /************************************************************************/
     911             : /*                        DefaultCopyMetadata()                         */
     912             : /************************************************************************/
     913             : 
     914        5502 : void GDALDriver::DefaultCopyMetadata(GDALDataset *poSrcDS, GDALDataset *poDstDS,
     915             :                                      CSLConstList papszOptions,
     916             :                                      CSLConstList papszExcludedDomains)
     917             : {
     918             :     const char *pszCopySrcMDD =
     919        5502 :         CSLFetchNameValueDef(papszOptions, "COPY_SRC_MDD", "AUTO");
     920        5502 :     char **papszSrcMDD = CSLFetchNameValueMultiple(papszOptions, "SRC_MDD");
     921        5502 :     if (EQUAL(pszCopySrcMDD, "AUTO") || CPLTestBool(pszCopySrcMDD) ||
     922             :         papszSrcMDD)
     923             :     {
     924           4 :         if ((!papszSrcMDD || CSLFindString(papszSrcMDD, "") >= 0 ||
     925           2 :              CSLFindString(papszSrcMDD, "_DEFAULT_") >= 0) &&
     926       10851 :             CSLFindString(papszExcludedDomains, "") < 0 &&
     927        5347 :             CSLFindString(papszExcludedDomains, "_DEFAULT_") < 0)
     928             :         {
     929        5347 :             if (poSrcDS->GetMetadata() != nullptr)
     930         879 :                 poDstDS->SetMetadata(poSrcDS->GetMetadata());
     931             :         }
     932             : 
     933             :         /* -------------------------------------------------------------------- */
     934             :         /*      Copy transportable special domain metadata.                     */
     935             :         /*      It would be nice to copy geolocation, but it is pretty fragile. */
     936             :         /* -------------------------------------------------------------------- */
     937        5500 :         constexpr const char *apszDefaultDomains[] = {
     938             :             GDAL_MDD_RPC, "xml:XMP", "json:ISIS3", "json:VICAR"};
     939       27500 :         for (const char *pszDomain : apszDefaultDomains)
     940             :         {
     941       43984 :             if ((!papszSrcMDD || CSLFindString(papszSrcMDD, pszDomain) >= 0) &&
     942       21984 :                 CSLFindString(papszExcludedDomains, pszDomain) < 0)
     943             :             {
     944       21984 :                 CSLConstList papszMD = poSrcDS->GetMetadata(pszDomain);
     945       21984 :                 if (papszMD)
     946           5 :                     poDstDS->SetMetadata(papszMD, pszDomain);
     947             :             }
     948             :         }
     949             : 
     950        5500 :         if ((!EQUAL(pszCopySrcMDD, "AUTO") && CPLTestBool(pszCopySrcMDD)) ||
     951             :             papszSrcMDD)
     952             :         {
     953          24 :             for (const char *pszDomain :
     954          30 :                  CPLStringList(poSrcDS->GetMetadataDomainList()))
     955             :             {
     956          36 :                 if (pszDomain[0] != 0 &&
     957          12 :                     (!papszSrcMDD ||
     958          12 :                      CSLFindString(papszSrcMDD, pszDomain) >= 0))
     959             :                 {
     960          10 :                     bool bCanCopy = true;
     961          10 :                     if (CSLFindString(papszExcludedDomains, pszDomain) >= 0)
     962             :                     {
     963           0 :                         bCanCopy = false;
     964             :                     }
     965             :                     else
     966             :                     {
     967          50 :                         for (const char *pszOtherDomain : apszDefaultDomains)
     968             :                         {
     969          40 :                             if (EQUAL(pszDomain, pszOtherDomain))
     970             :                             {
     971           0 :                                 bCanCopy = false;
     972           0 :                                 break;
     973             :                             }
     974             :                         }
     975          10 :                         if (!papszSrcMDD)
     976             :                         {
     977           6 :                             constexpr const char *const apszReservedDomains[] =
     978             :                                 {GDAL_MDD_IMAGE_STRUCTURE,
     979             :                                  "DERIVED_SUBDATASETS"};
     980           6 :                             for (const char *pszOtherDomain :
     981          12 :                                  apszReservedDomains)
     982             :                             {
     983          10 :                                 if (EQUAL(pszDomain, pszOtherDomain))
     984             :                                 {
     985           4 :                                     bCanCopy = false;
     986           4 :                                     break;
     987             :                                 }
     988             :                             }
     989             :                         }
     990             :                     }
     991          10 :                     if (bCanCopy)
     992             :                     {
     993           6 :                         poDstDS->SetMetadata(poSrcDS->GetMetadata(pszDomain),
     994           6 :                                              pszDomain);
     995             :                     }
     996             :                 }
     997             :             }
     998             :         }
     999             :     }
    1000        5502 :     CSLDestroy(papszSrcMDD);
    1001        5502 : }
    1002             : 
    1003             : /************************************************************************/
    1004             : /*                      QuietDeleteForCreateCopy()                      */
    1005             : /************************************************************************/
    1006             : 
    1007       12379 : CPLErr GDALDriver::QuietDeleteForCreateCopy(const char *pszFilename,
    1008             :                                             GDALDataset *poSrcDS)
    1009             : {
    1010             :     // Someone issuing CreateCopy("foo.tif") on a
    1011             :     // memory driver doesn't expect files with those names to be deleted
    1012             :     // on a file system...
    1013             :     // This is somewhat messy. Ideally there should be a way for the
    1014             :     // driver to overload the default behavior
    1015       24117 :     if (!EQUAL(GetDescription(), "MEM") && !EQUAL(GetDescription(), "Memory") &&
    1016             :         // VRT with empty name is a un-materialized dataset
    1017       11738 :         !(EQUAL(GetDescription(), "VRT") && pszFilename[0] == 0) &&
    1018             :         // Also exclude database formats for which there's no file list
    1019             :         // and whose opening might be slow (GeoRaster in particular)
    1020       35144 :         !EQUAL(GetDescription(), "GeoRaster") &&
    1021       11027 :         !EQUAL(GetDescription(), "PostGISRaster"))
    1022             :     {
    1023             :         /* --------------------------------------------------------------------
    1024             :          */
    1025             :         /*      Establish list of files of output dataset if it already
    1026             :          * exists. */
    1027             :         /* --------------------------------------------------------------------
    1028             :          */
    1029       22018 :         std::set<std::string> oSetExistingDestFiles;
    1030             :         {
    1031       22018 :             CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler);
    1032       11009 :             const char *const apszAllowedDrivers[] = {GetDescription(),
    1033       11009 :                                                       nullptr};
    1034             :             auto poExistingOutputDS =
    1035             :                 std::unique_ptr<GDALDataset>(GDALDataset::Open(
    1036       22018 :                     pszFilename, GDAL_OF_RASTER, apszAllowedDrivers));
    1037       11009 :             if (poExistingOutputDS)
    1038             :             {
    1039         682 :                 for (const char *pszFileInList :
    1040         648 :                      CPLStringList(poExistingOutputDS->GetFileList()))
    1041             :                 {
    1042             :                     oSetExistingDestFiles.insert(
    1043         341 :                         CPLString(pszFileInList).replaceAll('\\', '/'));
    1044             :                 }
    1045             :             }
    1046             :         }
    1047             : 
    1048             :         /* --------------------------------------------------------------------
    1049             :          */
    1050             :         /*      Check if the source dataset shares some files with the dest
    1051             :          * one.*/
    1052             :         /* --------------------------------------------------------------------
    1053             :          */
    1054       22018 :         std::set<std::string> oSetExistingDestFilesFoundInSource;
    1055       11009 :         if (!oSetExistingDestFiles.empty())
    1056             :         {
    1057         614 :             CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler);
    1058             :             // We need to reopen in a temporary dataset for the particular
    1059             :             // case of overwritten a .tif.ovr file from a .tif
    1060             :             // If we probe the file list of the .tif, it will then open the
    1061             :             // .tif.ovr !
    1062         307 :             const char *const apszAllowedDrivers[] = {
    1063         307 :                 poSrcDS->GetDriver() ? poSrcDS->GetDriver()->GetDescription()
    1064             :                                      : nullptr,
    1065         307 :                 nullptr};
    1066             :             auto poSrcDSTmp = std::unique_ptr<GDALDataset>(GDALDataset::Open(
    1067         307 :                 poSrcDS->GetDescription(), GDAL_OF_RASTER, apszAllowedDrivers,
    1068         614 :                 poSrcDS->papszOpenOptions));
    1069         307 :             if (poSrcDSTmp)
    1070             :             {
    1071         212 :                 for (const char *pszFileInList :
    1072         412 :                      CPLStringList(poSrcDSTmp->GetFileList()))
    1073             :                 {
    1074         424 :                     CPLString osFilename(pszFileInList);
    1075         212 :                     osFilename.replaceAll('\\', '/');
    1076         212 :                     if (cpl::contains(oSetExistingDestFiles, osFilename))
    1077             :                     {
    1078             :                         oSetExistingDestFilesFoundInSource.insert(
    1079          16 :                             std::move(osFilename));
    1080             :                     }
    1081             :                 }
    1082             :             }
    1083             :         }
    1084             : 
    1085             :         // If the source file(s) and the dest one share some files in
    1086             :         // common, only remove the files that are *not* in common
    1087       11009 :         if (!oSetExistingDestFilesFoundInSource.empty())
    1088             :         {
    1089          36 :             for (const std::string &osFilename : oSetExistingDestFiles)
    1090             :             {
    1091          21 :                 if (!cpl::contains(oSetExistingDestFilesFoundInSource,
    1092             :                                    osFilename))
    1093             :                 {
    1094           5 :                     VSIUnlink(osFilename.c_str());
    1095             :                 }
    1096             :             }
    1097             :         }
    1098             : 
    1099       11009 :         QuietDelete(pszFilename);
    1100             :     }
    1101             : 
    1102       12379 :     return CE_None;
    1103             : }
    1104             : 
    1105             : //! @endcond
    1106             : 
    1107             : /************************************************************************/
    1108             : /*                             CreateCopy()                             */
    1109             : /************************************************************************/
    1110             : 
    1111             : /**
    1112             :  * \brief Create a copy of a dataset.
    1113             :  *
    1114             :  * This method will attempt to create a copy of a raster dataset with the
    1115             :  * indicated filename, and in this drivers format.  Band number, size,
    1116             :  * type, projection, geotransform and so forth are all to be copied from
    1117             :  * the provided template dataset.
    1118             :  *
    1119             :  * Note that many sequential write once formats (such as JPEG and PNG) don't
    1120             :  * implement the Create() method but do implement this CreateCopy() method.
    1121             :  * If the driver doesn't implement CreateCopy(), but does implement Create()
    1122             :  * then the default CreateCopy() mechanism built on calling Create() will
    1123             :  * be used.
    1124             :  * So to test if CreateCopy() is available, you can test if GDAL_DCAP_CREATECOPY
    1125             :  * or GDAL_DCAP_CREATE is set in the GDAL metadata.
    1126             :  *
    1127             :  * It is intended that CreateCopy() will often be used with a source dataset
    1128             :  * which is a virtual dataset allowing configuration of band types, and other
    1129             :  * information without actually duplicating raster data (see the VRT driver).
    1130             :  * This is what is done by the gdal_translate utility for example.
    1131             :  *
    1132             :  * That function will try to validate the creation option list passed to the
    1133             :  * driver with the GDALValidateCreationOptions() method. This check can be
    1134             :  * disabled by defining the configuration option
    1135             :  * GDAL_VALIDATE_CREATION_OPTIONS=NO.
    1136             :  *
    1137             :  * This function copy all metadata from the default domain ("")
    1138             :  *
    1139             :  * Even is bStrict is TRUE, only the <b>value</b> of the data is equivalent,
    1140             :  * but the data layout (INTERLEAVE as PIXEL/LINE/BAND) of the dst dataset is
    1141             :  * controlled by the papszOptions creation options, and may differ from the
    1142             :  * poSrcDS src dataset.
    1143             :  * Starting from GDAL 3.5, if no INTERLEAVE and COMPRESS creation option has
    1144             :  * been specified in papszOptions, and if the driver supports equivalent
    1145             :  * interleaving as the src dataset, the CreateCopy() will internally add the
    1146             :  * proper creation option to get the same data interleaving.
    1147             :  *
    1148             :  * After you have finished working with the returned dataset, it is
    1149             :  * <b>required</b> to close it with GDALClose(). This does not only close the
    1150             :  * file handle, but also ensures that all the data and metadata has been written
    1151             :  * to the dataset (GDALFlushCache() is not sufficient for that purpose).
    1152             :  *
    1153             :  * For multidimensional datasets, papszOptions can contain array creation
    1154             :  * options, if they are prefixed with "ARRAY:". \see GDALGroup::CopyFrom()
    1155             :  * documentation for further details regarding such options.
    1156             :  *
    1157             :  * @param pszFilename the name for the new dataset.  UTF-8 encoded.
    1158             :  * @param poSrcDS the dataset being duplicated.
    1159             :  * @param bStrict TRUE if the copy must be strictly equivalent, or more
    1160             :  * normally FALSE indicating that the copy may adapt as needed for the
    1161             :  * output format.
    1162             :  * @param papszOptions additional format dependent options controlling
    1163             :  * creation of the output file.
    1164             :  * The APPEND_SUBDATASET=YES option can be specified to avoid prior destruction
    1165             :  * of existing dataset.
    1166             :  * Starting with GDAL 3.8.0, the following options are recognized by the
    1167             :  * GTiff, COG, VRT, PNG au JPEG drivers:
    1168             :  * <ul>
    1169             :  * <li>COPY_SRC_MDD=AUTO/YES/NO: whether metadata domains of the source dataset
    1170             :  * should be copied to the destination dataset. In the default AUTO mode, only
    1171             :  * "safe" domains will be copied, which include the default metadata domain
    1172             :  * (some drivers may include other domains such as IMD, RPC, GEOLOCATION). When
    1173             :  * setting YES, all domains will be copied (but a few reserved ones like
    1174             :  * IMAGE_STRUCTURE or DERIVED_SUBDATASETS). When setting NO, no source metadata
    1175             :  * will be copied.
    1176             :  * </li>
    1177             :  *<li>SRC_MDD=domain_name: which source metadata domain should be copied.
    1178             :  * This option restricts the list of source metadata domains to be copied
    1179             :  * (it implies COPY_SRC_MDD=YES if it is not set). This option may be specified
    1180             :  * as many times as they are source domains. The default metadata domain is the
    1181             :  * empty string "" ("_DEFAULT_") may also be used when empty string is not practical)
    1182             :  * </li>
    1183             :  * </ul>
    1184             :  * @param pfnProgress a function to be used to report progress of the copy.
    1185             :  * @param pProgressData application data passed into progress function.
    1186             :  *
    1187             :  * @return a pointer to the newly created dataset (may be read-only access).
    1188             :  */
    1189             : 
    1190       11791 : GDALDataset *GDALDriver::CreateCopy(const char *pszFilename,
    1191             :                                     GDALDataset *poSrcDS, int bStrict,
    1192             :                                     CSLConstList papszOptions,
    1193             :                                     GDALProgressFunc pfnProgress,
    1194             :                                     void *pProgressData)
    1195             : 
    1196             : {
    1197       11791 :     if (pfnProgress == nullptr)
    1198        8897 :         pfnProgress = GDALDummyProgress;
    1199             : 
    1200       11791 :     const int nBandCount = poSrcDS->GetRasterCount();
    1201             : 
    1202             :     /* -------------------------------------------------------------------- */
    1203             :     /*      If no INTERLEAVE creation option is given, we will try to add   */
    1204             :     /*      one that matches the current srcDS interleaving                 */
    1205             :     /* -------------------------------------------------------------------- */
    1206       11791 :     char **papszOptionsToDelete = nullptr;
    1207             :     const char *srcInterleave =
    1208       11791 :         poSrcDS->GetMetadataItem(GDALMD_INTERLEAVE, GDAL_MDD_IMAGE_STRUCTURE);
    1209        6999 :     if (nBandCount > 1 && srcInterleave != nullptr &&
    1210       25394 :         CSLFetchNameValue(papszOptions, GDALMD_INTERLEAVE) == nullptr &&
    1211        6604 :         EQUAL(CSLFetchNameValueDef(papszOptions, "COMPRESS", "NONE"), "NONE"))
    1212             :     {
    1213             : 
    1214             :         // look for INTERLEAVE values of the driver
    1215        6419 :         char **interleavesCSL = nullptr;
    1216             :         const char *pszOptionList =
    1217        6419 :             this->GetMetadataItem(GDAL_DMD_CREATIONOPTIONLIST);
    1218             :         CPLXMLNode *xmlNode =
    1219        6419 :             !pszOptionList ? nullptr : CPLParseXMLString(pszOptionList);
    1220        6419 :         for (CPLXMLNode *child = !xmlNode ? nullptr : xmlNode->psChild;
    1221      134276 :              child != nullptr; child = child->psNext)
    1222             :         {
    1223      127857 :             if ((child->eType == CXT_Element) &&
    1224      127857 :                 EQUAL(child->pszValue, "Option"))
    1225             :             {
    1226             :                 const char *nameAttribute =
    1227      127857 :                     CPLGetXMLValue(child, "name", nullptr);
    1228      127857 :                 const bool isInterleaveAttribute =
    1229      127857 :                     nameAttribute && EQUAL(nameAttribute, GDALMD_INTERLEAVE);
    1230      127857 :                 if (isInterleaveAttribute)
    1231             :                 {
    1232        1189 :                     for (CPLXMLNode *optionChild = child->psChild;
    1233        7203 :                          optionChild != nullptr;
    1234        6014 :                          optionChild = optionChild->psNext)
    1235             :                     {
    1236        6014 :                         if ((optionChild->eType == CXT_Element) &&
    1237        2432 :                             EQUAL(optionChild->pszValue, "Value"))
    1238             :                         {
    1239        2432 :                             CPLXMLNode *optionChildValue = optionChild->psChild;
    1240        2432 :                             if (optionChildValue &&
    1241        2432 :                                 (optionChildValue->eType == CXT_Text))
    1242             :                             {
    1243        2432 :                                 interleavesCSL = CSLAddString(
    1244        2432 :                                     interleavesCSL, optionChildValue->pszValue);
    1245             :                             }
    1246             :                         }
    1247             :                     }
    1248             :                 }
    1249             :             }
    1250             :         }
    1251        6419 :         CPLDestroyXMLNode(xmlNode);
    1252             : 
    1253             :         const char *dstInterleaveBand =
    1254       11673 :             (CSLFindString(interleavesCSL, "BAND") >= 0)  ? "BAND"
    1255        5254 :             : (CSLFindString(interleavesCSL, "BSQ") >= 0) ? "BSQ"
    1256        6419 :                                                           : nullptr;
    1257             :         const char *dstInterleaveLine =
    1258       12838 :             (CSLFindString(interleavesCSL, "LINE") >= 0)  ? "LINE"
    1259        6419 :             : (CSLFindString(interleavesCSL, "BIL") >= 0) ? "BIL"
    1260        6419 :                                                           : nullptr;
    1261             :         const char *dstInterleavePixel =
    1262       11673 :             (CSLFindString(interleavesCSL, "PIXEL") >= 0) ? "PIXEL"
    1263        5254 :             : (CSLFindString(interleavesCSL, "BIP") >= 0) ? "BIP"
    1264        6419 :                                                           : nullptr;
    1265        6419 :         const char *dstInterleave =
    1266        6736 :             EQUAL(srcInterleave, "BAND")    ? dstInterleaveBand
    1267         632 :             : EQUAL(srcInterleave, "LINE")  ? dstInterleaveLine
    1268         315 :             : EQUAL(srcInterleave, "PIXEL") ? dstInterleavePixel
    1269             :                                             : nullptr;
    1270        6419 :         CSLDestroy(interleavesCSL);
    1271             : 
    1272        6419 :         if (dstInterleave != nullptr)
    1273             :         {
    1274        1189 :             papszOptionsToDelete = CSLDuplicate(papszOptions);
    1275        1189 :             papszOptionsToDelete = CSLSetNameValue(
    1276             :                 papszOptionsToDelete, GDALMD_INTERLEAVE, dstInterleave);
    1277        1189 :             papszOptionsToDelete = CSLSetNameValue(
    1278             :                 papszOptionsToDelete, "@INTERLEAVE_ADDED_AUTOMATICALLY", "YES");
    1279        1189 :             papszOptions = papszOptionsToDelete;
    1280             :         }
    1281             :     }
    1282             : 
    1283             :     /* -------------------------------------------------------------------- */
    1284             :     /*      Make sure we cleanup if there is an existing dataset of this    */
    1285             :     /*      name.  But even if that seems to fail we will continue since    */
    1286             :     /*      it might just be a corrupt file or something.                   */
    1287             :     /* -------------------------------------------------------------------- */
    1288             :     const bool bAppendSubdataset =
    1289       11791 :         CPLFetchBool(papszOptions, "APPEND_SUBDATASET", false);
    1290             :     // Note: @QUIET_DELETE_ON_CREATE_COPY is set to NO by the KMLSuperOverlay
    1291             :     // driver when writing a .kmz file. Also by GDALTranslate() if it has
    1292             :     // already done a similar job.
    1293       23557 :     if (!bAppendSubdataset &&
    1294       11766 :         CPLFetchBool(papszOptions, "@QUIET_DELETE_ON_CREATE_COPY", true))
    1295             :     {
    1296        9023 :         QuietDeleteForCreateCopy(pszFilename, poSrcDS);
    1297             :     }
    1298             : 
    1299             :     int iIdxQuietDeleteOnCreateCopy =
    1300       11791 :         CSLPartialFindString(papszOptions, "@QUIET_DELETE_ON_CREATE_COPY=");
    1301       11791 :     if (iIdxQuietDeleteOnCreateCopy >= 0)
    1302             :     {
    1303        2743 :         if (papszOptionsToDelete == nullptr)
    1304        1689 :             papszOptionsToDelete = CSLDuplicate(papszOptions);
    1305        2743 :         papszOptionsToDelete = CSLRemoveStrings(
    1306             :             papszOptionsToDelete, iIdxQuietDeleteOnCreateCopy, 1, nullptr);
    1307        2743 :         papszOptions = papszOptionsToDelete;
    1308             :     }
    1309             : 
    1310             :     /* -------------------------------------------------------------------- */
    1311             :     /*      If _INTERNAL_DATASET=YES, the returned dataset will not be      */
    1312             :     /*      registered in the global list of open datasets.                 */
    1313             :     /* -------------------------------------------------------------------- */
    1314             :     const int iIdxInternalDataset =
    1315       11791 :         CSLPartialFindString(papszOptions, "_INTERNAL_DATASET=");
    1316       11791 :     bool bInternalDataset = false;
    1317       11791 :     if (iIdxInternalDataset >= 0)
    1318             :     {
    1319             :         bInternalDataset =
    1320        4213 :             CPLFetchBool(papszOptions, "_INTERNAL_DATASET", false);
    1321        4213 :         if (papszOptionsToDelete == nullptr)
    1322        4213 :             papszOptionsToDelete = CSLDuplicate(papszOptions);
    1323        4213 :         papszOptionsToDelete = CSLRemoveStrings(
    1324             :             papszOptionsToDelete, iIdxInternalDataset, 1, nullptr);
    1325        4213 :         papszOptions = papszOptionsToDelete;
    1326             :     }
    1327             : 
    1328             :     /* -------------------------------------------------------------------- */
    1329             :     /*      Validate creation options.                                      */
    1330             :     /* -------------------------------------------------------------------- */
    1331       11791 :     if (CPLTestBool(
    1332             :             CPLGetConfigOption("GDAL_VALIDATE_CREATION_OPTIONS", "YES")))
    1333             :     {
    1334       23582 :         auto poSrcGroup = poSrcDS->GetRootGroup();
    1335       11791 :         if (poSrcGroup != nullptr && GetMetadataItem(GDAL_DCAP_MULTIDIM_RASTER))
    1336             :         {
    1337         228 :             CPLStringList aosDatasetCO;
    1338         121 :             for (const char *pszOption : cpl::Iterate(papszOptions))
    1339             :             {
    1340           7 :                 if (!STARTS_WITH_CI(pszOption, "ARRAY:"))
    1341           0 :                     aosDatasetCO.AddString(pszOption);
    1342             :             }
    1343         114 :             GDALValidateCreationOptions(this, aosDatasetCO.List());
    1344             :         }
    1345             :         else
    1346             :         {
    1347       11677 :             GDALValidateCreationOptions(this, papszOptions);
    1348             :         }
    1349             :     }
    1350             : 
    1351             :     /* -------------------------------------------------------------------- */
    1352             :     /*      Advise the source raster that we are going to read it completely */
    1353             :     /* -------------------------------------------------------------------- */
    1354             : 
    1355       11791 :     const int nXSize = poSrcDS->GetRasterXSize();
    1356       11791 :     const int nYSize = poSrcDS->GetRasterYSize();
    1357       11791 :     GDALDataType eDT = GDT_Unknown;
    1358       11791 :     if (nBandCount > 0)
    1359             :     {
    1360       11553 :         GDALRasterBand *poSrcBand = poSrcDS->GetRasterBand(1);
    1361       11553 :         if (poSrcBand)
    1362       11553 :             eDT = poSrcBand->GetRasterDataType();
    1363             :     }
    1364       11791 :     poSrcDS->AdviseRead(0, 0, nXSize, nYSize, nXSize, nYSize, eDT, nBandCount,
    1365       11791 :                         nullptr, nullptr);
    1366             : 
    1367             :     /* -------------------------------------------------------------------- */
    1368             :     /*      If the format provides a CreateCopy() method use that,          */
    1369             :     /*      otherwise fallback to the internal implementation using the     */
    1370             :     /*      Create() method.                                                */
    1371             :     /* -------------------------------------------------------------------- */
    1372       11791 :     GDALDataset *poDstDS = nullptr;
    1373       11791 :     auto l_pfnCreateCopy = GetCreateCopyCallback();
    1374       22405 :     if (l_pfnCreateCopy != nullptr &&
    1375       10614 :         !CPLTestBool(CPLGetConfigOption("GDAL_DEFAULT_CREATE_COPY", "NO")))
    1376             :     {
    1377       10614 :         poDstDS = l_pfnCreateCopy(pszFilename, poSrcDS, bStrict,
    1378             :                                   const_cast<char **>(papszOptions),
    1379             :                                   pfnProgress, pProgressData);
    1380       10614 :         if (poDstDS != nullptr)
    1381             :         {
    1382       18672 :             if (poDstDS->GetDescription() == nullptr ||
    1383        9336 :                 strlen(poDstDS->GetDescription()) == 0)
    1384         452 :                 poDstDS->SetDescription(pszFilename);
    1385             : 
    1386        9336 :             if (poDstDS->poDriver == nullptr)
    1387        8438 :                 poDstDS->poDriver = this;
    1388             : 
    1389        9336 :             if (!bInternalDataset)
    1390        5123 :                 poDstDS->AddToDatasetOpenList();
    1391             :         }
    1392             :     }
    1393             :     else
    1394             :     {
    1395        1177 :         poDstDS = DefaultCreateCopy(pszFilename, poSrcDS, bStrict, papszOptions,
    1396             :                                     pfnProgress, pProgressData);
    1397             :     }
    1398             : 
    1399       11791 :     CSLDestroy(papszOptionsToDelete);
    1400       11791 :     return poDstDS;
    1401             : }
    1402             : 
    1403             : /************************************************************************/
    1404             : /*                           GDALCreateCopy()                           */
    1405             : /************************************************************************/
    1406             : 
    1407             : /**
    1408             :  * \brief Create a copy of a dataset.
    1409             :  *
    1410             :  * @see GDALDriver::CreateCopy()
    1411             :  */
    1412             : 
    1413        6865 : GDALDatasetH CPL_STDCALL GDALCreateCopy(GDALDriverH hDriver,
    1414             :                                         const char *pszFilename,
    1415             :                                         GDALDatasetH hSrcDS, int bStrict,
    1416             :                                         CSLConstList papszOptions,
    1417             :                                         GDALProgressFunc pfnProgress,
    1418             :                                         void *pProgressData)
    1419             : 
    1420             : {
    1421        6865 :     VALIDATE_POINTER1(hDriver, "GDALCreateCopy", nullptr);
    1422        6865 :     VALIDATE_POINTER1(hSrcDS, "GDALCreateCopy", nullptr);
    1423             : 
    1424        6865 :     return GDALDriver::FromHandle(hDriver)->CreateCopy(
    1425             :         pszFilename, GDALDataset::FromHandle(hSrcDS), bStrict, papszOptions,
    1426        6865 :         pfnProgress, pProgressData);
    1427             : }
    1428             : 
    1429             : /************************************************************************/
    1430             : /*                       CanVectorTranslateFrom()                       */
    1431             : /************************************************************************/
    1432             : 
    1433             : /** Returns whether the driver can translate from a vector dataset,
    1434             :  * using the arguments passed to GDALVectorTranslate() stored in
    1435             :  * papszVectorTranslateArguments.
    1436             :  *
    1437             :  * This is used to determine if the driver supports the VectorTranslateFrom()
    1438             :  * operation.
    1439             :  *
    1440             :  * @param pszDestName Target dataset name
    1441             :  * @param poSourceDS  Source dataset
    1442             :  * @param papszVectorTranslateArguments Non-positional arguments passed to
    1443             :  *                                      GDALVectorTranslate() (may be nullptr)
    1444             :  * @param[out] ppapszFailureReasons nullptr, or a pointer to an null-terminated
    1445             :  * array of strings to record the reason(s) for the impossibility.
    1446             :  * @return true if VectorTranslateFrom() can be called with the same arguments.
    1447             :  * @since GDAL 3.8
    1448             :  */
    1449        1002 : bool GDALDriver::CanVectorTranslateFrom(
    1450             :     const char *pszDestName, GDALDataset *poSourceDS,
    1451             :     CSLConstList papszVectorTranslateArguments, char ***ppapszFailureReasons)
    1452             : 
    1453             : {
    1454        1002 :     if (ppapszFailureReasons)
    1455             :     {
    1456           0 :         *ppapszFailureReasons = nullptr;
    1457             :     }
    1458             : 
    1459        1002 :     if (!pfnCanVectorTranslateFrom)
    1460             :     {
    1461         996 :         if (ppapszFailureReasons)
    1462             :         {
    1463           0 :             *ppapszFailureReasons = CSLAddString(
    1464             :                 nullptr,
    1465             :                 "CanVectorTranslateFrom() not implemented for this driver");
    1466             :         }
    1467         996 :         return false;
    1468             :     }
    1469             : 
    1470           6 :     char **papszFailureReasons = nullptr;
    1471           6 :     bool bRet = pfnCanVectorTranslateFrom(
    1472             :         pszDestName, poSourceDS, papszVectorTranslateArguments,
    1473             :         ppapszFailureReasons ? ppapszFailureReasons : &papszFailureReasons);
    1474           6 :     if (!ppapszFailureReasons)
    1475             :     {
    1476           2 :         for (const char *pszReason :
    1477          10 :              cpl::Iterate(static_cast<CSLConstList>(papszFailureReasons)))
    1478             :         {
    1479           2 :             CPLDebug("GDAL", "%s", pszReason);
    1480             :         }
    1481           6 :         CSLDestroy(papszFailureReasons);
    1482             :     }
    1483           6 :     return bRet;
    1484             : }
    1485             : 
    1486             : /************************************************************************/
    1487             : /*                           HasOpenOption()                            */
    1488             : /************************************************************************/
    1489             : 
    1490         193 : bool GDALDriver::HasOpenOption(const char *pszOpenOptionName) const
    1491             : {
    1492         193 :     if (pszOpenOptionName == nullptr)
    1493           0 :         return false;
    1494             : 
    1495             :     // Const cast is safe here since we are only reading the metadata
    1496         386 :     auto pszOOMd{const_cast<GDALDriver *>(this)->GetMetadataItem(
    1497         193 :         GDAL_DMD_OPENOPTIONLIST)};
    1498         193 :     if (pszOOMd == nullptr)
    1499          74 :         return false;
    1500             : 
    1501         238 :     const CPLXMLTreeCloser oXml{CPLParseXMLString(pszOOMd)};
    1502        1259 :     for (CPLXMLNode *option = oXml->psChild; option != nullptr;
    1503        1140 :          option = option->psNext)
    1504             :     {
    1505        1141 :         if (EQUAL(CPLGetXMLValue(CPLGetXMLNode(option, "name"), nullptr, ""),
    1506             :                   pszOpenOptionName))
    1507           1 :             return true;
    1508             :     }
    1509         118 :     return false;
    1510             : }
    1511             : 
    1512             : /************************************************************************/
    1513             : /*                       HasLayerCreationOption()                       */
    1514             : /************************************************************************/
    1515             : 
    1516           7 : bool GDALDriver::HasLayerCreationOption(const char *pszOptionName) const
    1517             : {
    1518           7 :     if (pszOptionName == nullptr)
    1519           0 :         return false;
    1520             : 
    1521             :     // Const cast is safe here since we are only reading the metadata
    1522          14 :     auto pszXML{const_cast<GDALDriver *>(this)->GetMetadataItem(
    1523           7 :         GDAL_DS_LAYER_CREATIONOPTIONLIST)};
    1524           7 :     if (pszXML == nullptr)
    1525           0 :         return false;
    1526             : 
    1527          14 :     const CPLXMLTreeCloser oXml{CPLParseXMLString(pszXML)};
    1528          49 :     for (CPLXMLNode *option = oXml->psChild; option != nullptr;
    1529          42 :          option = option->psNext)
    1530             :     {
    1531          49 :         if (EQUAL(CPLGetXMLValue(CPLGetXMLNode(option, "name"), nullptr, ""),
    1532             :                   pszOptionName))
    1533           7 :             return true;
    1534             :     }
    1535           0 :     return false;
    1536             : }
    1537             : 
    1538             : /************************************************************************/
    1539             : /*                        VectorTranslateFrom()                         */
    1540             : /************************************************************************/
    1541             : 
    1542             : /** Create a copy of a vector dataset, using the arguments passed to
    1543             :  * GDALVectorTranslate() stored in papszVectorTranslateArguments.
    1544             :  *
    1545             :  * This may be implemented by some drivers that can convert from an existing
    1546             :  * dataset in an optimized way.
    1547             :  *
    1548             :  * This is for example used by the PMTiles to convert from MBTiles.
    1549             :  *
    1550             :  * @param pszDestName Target dataset name
    1551             :  * @param poSourceDS  Source dataset
    1552             :  * @param papszVectorTranslateArguments Non-positional arguments passed to
    1553             :  *                                      GDALVectorTranslate() (may be nullptr)
    1554             :  * @param pfnProgress a function to be used to report progress of the copy.
    1555             :  * @param pProgressData application data passed into progress function.
    1556             :  * @return a new dataset in case of success, or nullptr in case of error.
    1557             :  * @since GDAL 3.8
    1558             :  */
    1559           4 : GDALDataset *GDALDriver::VectorTranslateFrom(
    1560             :     const char *pszDestName, GDALDataset *poSourceDS,
    1561             :     CSLConstList papszVectorTranslateArguments, GDALProgressFunc pfnProgress,
    1562             :     void *pProgressData)
    1563             : 
    1564             : {
    1565           4 :     if (!pfnVectorTranslateFrom)
    1566             :     {
    1567           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    1568             :                  "VectorTranslateFrom() not implemented for this driver");
    1569           0 :         return nullptr;
    1570             :     }
    1571             : 
    1572           4 :     return pfnVectorTranslateFrom(pszDestName, poSourceDS,
    1573             :                                   papszVectorTranslateArguments, pfnProgress,
    1574           4 :                                   pProgressData);
    1575             : }
    1576             : 
    1577             : /************************************************************************/
    1578             : /*                            QuietDelete()                             */
    1579             : /************************************************************************/
    1580             : 
    1581             : /**
    1582             :  * \brief Delete dataset if found.
    1583             :  *
    1584             :  * This is a helper method primarily used by Create() and
    1585             :  * CreateCopy() to predelete any dataset of the name soon to be
    1586             :  * created.  It will attempt to delete the named dataset if
    1587             :  * one is found, otherwise it does nothing.  An error is only
    1588             :  * returned if the dataset is found but the delete fails.
    1589             :  *
    1590             :  * This is a static method and it doesn't matter what driver instance
    1591             :  * it is invoked on.  It will attempt to discover the correct driver
    1592             :  * using Identify().
    1593             :  *
    1594             :  * @param pszName the dataset name to try and delete.
    1595             :  * @param papszAllowedDrivers NULL to consider all candidate drivers, or a NULL
    1596             :  * terminated list of strings with the driver short names that must be
    1597             :  * considered. (Note: implemented only starting with GDAL 3.4.1)
    1598             :  * @return CE_None if the dataset does not exist, or is deleted without issues.
    1599             :  */
    1600             : 
    1601       24827 : CPLErr GDALDriver::QuietDelete(const char *pszName,
    1602             :                                CSLConstList papszAllowedDrivers)
    1603             : 
    1604             : {
    1605             :     VSIStatBufL sStat;
    1606             :     const bool bExists =
    1607       24827 :         VSIStatExL(pszName, &sStat,
    1608       24827 :                    VSI_STAT_EXISTS_FLAG | VSI_STAT_NATURE_FLAG) == 0;
    1609             : 
    1610             : #ifdef S_ISFIFO
    1611       24827 :     if (bExists && S_ISFIFO(sStat.st_mode))
    1612           0 :         return CE_None;
    1613             : #endif
    1614             : 
    1615       24827 :     GDALDriver *poDriver = nullptr;
    1616       24827 :     if (papszAllowedDrivers)
    1617             :     {
    1618           0 :         GDALOpenInfo oOpenInfo(pszName, GDAL_OF_ALL);
    1619           0 :         for (const char *pszDriverName : cpl::Iterate(papszAllowedDrivers))
    1620             :         {
    1621             :             GDALDriver *poTmpDriver =
    1622           0 :                 GDALDriver::FromHandle(GDALGetDriverByName(pszDriverName));
    1623           0 :             if (poTmpDriver)
    1624             :             {
    1625             :                 const bool bIdentifyRes =
    1626           0 :                     poTmpDriver->pfnIdentifyEx
    1627           0 :                         ? poTmpDriver->pfnIdentifyEx(poTmpDriver, &oOpenInfo) >
    1628             :                               0
    1629           0 :                         : poTmpDriver->pfnIdentify &&
    1630           0 :                               poTmpDriver->pfnIdentify(&oOpenInfo) > 0;
    1631           0 :                 if (bIdentifyRes)
    1632             :                 {
    1633           0 :                     poDriver = poTmpDriver;
    1634           0 :                     break;
    1635             :                 }
    1636             :             }
    1637             :         }
    1638             :     }
    1639             :     else
    1640             :     {
    1641       49654 :         CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler);
    1642       24827 :         poDriver = GDALDriver::FromHandle(GDALIdentifyDriver(pszName, nullptr));
    1643             :     }
    1644             : 
    1645       24827 :     if (poDriver == nullptr)
    1646       23952 :         return CE_None;
    1647             : 
    1648         908 :     if (bExists && VSI_ISDIR(sStat.st_mode) &&
    1649          33 :         (EQUAL(poDriver->GetDescription(), "MapInfo File") ||
    1650          33 :          EQUAL(poDriver->GetDescription(), "ESRI Shapefile")))
    1651             :     {
    1652             :         // Those drivers are a bit special and handle directories as container
    1653             :         // of layers, but it is quite common to found other files too, and
    1654             :         // removing the directory might be non-desirable.
    1655          33 :         return CE_None;
    1656             :     }
    1657             : 
    1658         842 :     CPLDebug("GDAL", "QuietDelete(%s) invoking Delete()", pszName);
    1659             : 
    1660         842 :     poDriver->pfnDelete = poDriver->GetDeleteCallback();
    1661         880 :     const bool bQuiet = !bExists && poDriver->pfnDelete == nullptr &&
    1662          38 :                         poDriver->pfnDeleteDataSource == nullptr;
    1663         842 :     if (bQuiet)
    1664             :     {
    1665          76 :         CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler);
    1666          38 :         return poDriver->Delete(pszName);
    1667             :     }
    1668             :     else
    1669             :     {
    1670         804 :         return poDriver->Delete(pszName);
    1671             :     }
    1672             : }
    1673             : 
    1674             : /************************************************************************/
    1675             : /*                               Delete()                               */
    1676             : /************************************************************************/
    1677             : 
    1678             : /**
    1679             :  * \brief Delete named dataset.
    1680             :  *
    1681             :  * The driver will attempt to delete the named dataset in a driver specific
    1682             :  * fashion.  Full featured drivers will delete all associated files,
    1683             :  * database objects, or whatever is appropriate.  The default behavior when
    1684             :  * no driver specific behavior is provided is to attempt to delete all the
    1685             :  * files that are returned by GDALGetFileList() on the dataset handle.
    1686             :  *
    1687             :  * It is unwise to have open dataset handles on this dataset when it is
    1688             :  * deleted.
    1689             :  *
    1690             :  * Equivalent of the C function GDALDeleteDataset().
    1691             :  *
    1692             :  * @param pszFilename name of dataset to delete.
    1693             :  *
    1694             :  * @return CE_None on success, or CE_Failure if the operation fails.
    1695             :  */
    1696             : 
    1697        4361 : CPLErr GDALDriver::Delete(const char *pszFilename)
    1698             : 
    1699             : {
    1700        4361 :     pfnDelete = GetDeleteCallback();
    1701        4361 :     if (pfnDelete != nullptr)
    1702        1047 :         return pfnDelete(pszFilename);
    1703        3314 :     else if (pfnDeleteDataSource != nullptr)
    1704           0 :         return pfnDeleteDataSource(this, pszFilename);
    1705             : 
    1706             :     /* -------------------------------------------------------------------- */
    1707             :     /*      Collect file list.                                              */
    1708             :     /* -------------------------------------------------------------------- */
    1709        3314 :     GDALDatasetH hDS = GDALOpenEx(pszFilename, GDAL_OF_VERBOSE_ERROR, nullptr,
    1710             :                                   nullptr, nullptr);
    1711             : 
    1712        3314 :     if (hDS == nullptr)
    1713             :     {
    1714         237 :         if (CPLGetLastErrorNo() == 0)
    1715           0 :             CPLError(CE_Failure, CPLE_OpenFailed,
    1716             :                      "Unable to open %s to obtain file list.", pszFilename);
    1717             : 
    1718         237 :         return CE_Failure;
    1719             :     }
    1720             : 
    1721        6154 :     const CPLStringList aosFileList(GDALGetFileList(hDS));
    1722             : 
    1723        3077 :     GDALClose(hDS);
    1724        3077 :     hDS = nullptr;
    1725             : 
    1726        3077 :     if (aosFileList.empty())
    1727             :     {
    1728           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    1729             :                  "Unable to determine files associated with %s, "
    1730             :                  "delete fails.",
    1731             :                  pszFilename);
    1732           0 :         return CE_Failure;
    1733             :     }
    1734             : 
    1735        3077 :     return Delete(nullptr, aosFileList.List());
    1736             : }
    1737             : 
    1738             : /************************************************************************/
    1739             : /*                               Delete()                               */
    1740             : /************************************************************************/
    1741             : 
    1742             : /**
    1743             :  * \brief Delete a currently opened dataset
    1744             :  *
    1745             :  * The driver will attempt to delete the passed dataset in a driver specific
    1746             :  * fashion.  Full featured drivers will delete all associated files,
    1747             :  * database objects, or whatever is appropriate.  The default behavior when
    1748             :  * no driver specific behavior is provided is to attempt to delete all the
    1749             :  * files that are returned by GDALGetFileList() on the dataset handle.
    1750             :  *
    1751             :  * Note that this will generally not work on Windows systems that don't accept
    1752             :  * deleting opened files.
    1753             :  *
    1754             :  * At least one of poDS or papszFileList must not be NULL
    1755             :  *
    1756             :  * @param poDS dataset to delete, or NULL
    1757             :  * @param papszFileList File list to delete, typically obtained with
    1758             :  *                      poDS->GetFileList(), or NULL
    1759             :  *
    1760             :  * @return CE_None on success, or CE_Failure if the operation fails.
    1761             :  *
    1762             :  * @since 3.12
    1763             :  */
    1764             : 
    1765        3089 : CPLErr GDALDriver::Delete(GDALDataset *poDS, CSLConstList papszFileList)
    1766             : 
    1767             : {
    1768        3089 :     if (poDS)
    1769             :     {
    1770          11 :         pfnDelete = GetDeleteCallback();
    1771          11 :         if (pfnDelete != nullptr)
    1772           7 :             return pfnDelete(poDS->GetDescription());
    1773           4 :         else if (pfnDeleteDataSource != nullptr)
    1774           0 :             return pfnDeleteDataSource(this, poDS->GetDescription());
    1775             :     }
    1776             : 
    1777             :     /* -------------------------------------------------------------------- */
    1778             :     /*      Delete all files.                                               */
    1779             :     /* -------------------------------------------------------------------- */
    1780        3082 :     CPLErr eErr = CE_None;
    1781        6817 :     for (int i = 0; papszFileList && papszFileList[i]; ++i)
    1782             :     {
    1783        3735 :         if (VSIUnlink(papszFileList[i]) != 0)
    1784             :         {
    1785           4 :             CPLError(CE_Failure, CPLE_AppDefined, "Deleting %s failed:\n%s",
    1786           2 :                      papszFileList[i], VSIStrerror(errno));
    1787           2 :             eErr = CE_Failure;
    1788             :         }
    1789             :     }
    1790             : 
    1791        3082 :     return eErr;
    1792             : }
    1793             : 
    1794             : /************************************************************************/
    1795             : /*                         GDALDeleteDataset()                          */
    1796             : /************************************************************************/
    1797             : 
    1798             : /**
    1799             :  * \brief Delete named dataset.
    1800             :  *
    1801             :  * @see GDALDriver::Delete()
    1802             :  */
    1803             : 
    1804        2352 : CPLErr CPL_STDCALL GDALDeleteDataset(GDALDriverH hDriver,
    1805             :                                      const char *pszFilename)
    1806             : 
    1807             : {
    1808        2352 :     if (hDriver == nullptr)
    1809          10 :         hDriver = GDALIdentifyDriver(pszFilename, nullptr);
    1810             : 
    1811        2352 :     if (hDriver == nullptr)
    1812             :     {
    1813           1 :         CPLError(CE_Failure, CPLE_AppDefined, "No identifiable driver for %s.",
    1814             :                  pszFilename);
    1815           1 :         return CE_Failure;
    1816             :     }
    1817             : 
    1818             : #ifdef OGRAPISPY_ENABLED
    1819        2351 :     if (GDALGetMetadataItem(hDriver, GDAL_DCAP_VECTOR, nullptr))
    1820             :     {
    1821         452 :         OGRAPISpyDeleteDataSource(hDriver, pszFilename);
    1822             :     }
    1823             : #endif
    1824             : 
    1825        2351 :     return GDALDriver::FromHandle(hDriver)->Delete(pszFilename);
    1826             : }
    1827             : 
    1828             : /************************************************************************/
    1829             : /*                           DefaultRename()                            */
    1830             : /*                                                                      */
    1831             : /*      The generic implementation based on the file list used when     */
    1832             : /*      there is no format specific implementation.                     */
    1833             : /************************************************************************/
    1834             : 
    1835             : //! @cond Doxygen_Suppress
    1836         175 : CPLErr GDALDriver::DefaultRename(const char *pszNewName, const char *pszOldName)
    1837             : 
    1838             : {
    1839             :     /* -------------------------------------------------------------------- */
    1840             :     /*      Collect file list.                                              */
    1841             :     /* -------------------------------------------------------------------- */
    1842             :     auto poDS = std::unique_ptr<GDALDataset>(
    1843             :         GDALDataset::Open(pszOldName, GDAL_OF_ALL | GDAL_OF_VERBOSE_ERROR,
    1844         350 :                           nullptr, nullptr, nullptr));
    1845             : 
    1846         175 :     if (!poDS)
    1847             :     {
    1848           0 :         if (CPLGetLastErrorNo() == 0)
    1849           0 :             CPLError(CE_Failure, CPLE_OpenFailed,
    1850             :                      "Unable to open %s to obtain file list.", pszOldName);
    1851             : 
    1852           0 :         return CE_Failure;
    1853             :     }
    1854             : 
    1855         350 :     const CPLStringList aosFileList(poDS->GetFileList());
    1856             : 
    1857         175 :     poDS.reset();
    1858             : 
    1859         175 :     if (aosFileList.empty())
    1860             :     {
    1861           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    1862             :                  "Unable to determine files associated with %s,\n"
    1863             :                  "rename fails.",
    1864             :                  pszOldName);
    1865             : 
    1866           0 :         return CE_Failure;
    1867             :     }
    1868             : 
    1869             :     /* -------------------------------------------------------------------- */
    1870             :     /*      Produce a list of new filenames that correspond to the old      */
    1871             :     /*      names.                                                          */
    1872             :     /* -------------------------------------------------------------------- */
    1873         175 :     CPLErr eErr = CE_None;
    1874             :     const CPLStringList aosNewFileList(
    1875         350 :         CPLCorrespondingPaths(pszOldName, pszNewName, aosFileList.List()));
    1876             : 
    1877         175 :     if (aosNewFileList.empty())
    1878           0 :         return CE_Failure;
    1879             : 
    1880             :     // Guaranteed by CPLCorrespondingPaths()
    1881         175 :     CPLAssert(aosNewFileList.size() == aosFileList.size());
    1882             : 
    1883             :     VSIStatBufL sStatBuf;
    1884         177 :     if (VSIStatL(pszOldName, &sStatBuf) == 0 && VSI_ISDIR(sStatBuf.st_mode) &&
    1885           2 :         VSIStatL(pszNewName, &sStatBuf) != 0)
    1886             :     {
    1887           2 :         if (VSIMkdirRecursive(pszNewName, 0755) != 0)
    1888             :         {
    1889           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    1890             :                      "Cannot create directory '%s'", pszNewName);
    1891           1 :             return CE_Failure;
    1892             :         }
    1893             :     }
    1894             : 
    1895         358 :     for (int i = 0; i < aosFileList.size(); ++i)
    1896             :     {
    1897         184 :         if (CPLMoveFile(aosNewFileList[i], aosFileList[i]) != 0)
    1898             :         {
    1899             :             // Above method will have emitted an error in case of failure.
    1900           0 :             eErr = CE_Failure;
    1901             :             // Try to put the ones we moved back.
    1902           0 :             for (--i; i >= 0; i--)
    1903             :             {
    1904             :                 // Nothing we can do if the moving back doesn't work...
    1905           0 :                 CPL_IGNORE_RET_VAL(
    1906           0 :                     CPLMoveFile(aosFileList[i], aosNewFileList[i]));
    1907             :             }
    1908           0 :             break;
    1909             :         }
    1910             :     }
    1911             : 
    1912         174 :     return eErr;
    1913             : }
    1914             : 
    1915             : //! @endcond
    1916             : 
    1917             : /************************************************************************/
    1918             : /*                               Rename()                               */
    1919             : /************************************************************************/
    1920             : 
    1921             : /**
    1922             :  * \brief Rename a dataset.
    1923             :  *
    1924             :  * Rename a dataset. This may including moving the dataset to a new directory
    1925             :  * or even a new filesystem.
    1926             :  *
    1927             :  * It is unwise to have open dataset handles on this dataset when it is
    1928             :  * being renamed.
    1929             :  *
    1930             :  * Equivalent of the C function GDALRenameDataset().
    1931             :  *
    1932             :  * @param pszNewName new name for the dataset.
    1933             :  * @param pszOldName old name for the dataset.
    1934             :  *
    1935             :  * @return CE_None on success, or CE_Failure if the operation fails.
    1936             :  */
    1937             : 
    1938         177 : CPLErr GDALDriver::Rename(const char *pszNewName, const char *pszOldName)
    1939             : 
    1940             : {
    1941         177 :     pfnRename = GetRenameCallback();
    1942         177 :     if (pfnRename != nullptr)
    1943           3 :         return pfnRename(pszNewName, pszOldName);
    1944             : 
    1945         174 :     return DefaultRename(pszNewName, pszOldName);
    1946             : }
    1947             : 
    1948             : /************************************************************************/
    1949             : /*                         GDALRenameDataset()                          */
    1950             : /************************************************************************/
    1951             : 
    1952             : /**
    1953             :  * \brief Rename a dataset.
    1954             :  *
    1955             :  * @see GDALDriver::Rename()
    1956             :  */
    1957             : 
    1958         178 : CPLErr CPL_STDCALL GDALRenameDataset(GDALDriverH hDriver,
    1959             :                                      const char *pszNewName,
    1960             :                                      const char *pszOldName)
    1961             : 
    1962             : {
    1963         178 :     if (hDriver == nullptr)
    1964           5 :         hDriver = GDALIdentifyDriver(pszOldName, nullptr);
    1965             : 
    1966         178 :     if (hDriver == nullptr)
    1967             :     {
    1968           1 :         CPLError(CE_Failure, CPLE_AppDefined, "No identifiable driver for %s.",
    1969             :                  pszOldName);
    1970           1 :         return CE_Failure;
    1971             :     }
    1972             : 
    1973         177 :     return GDALDriver::FromHandle(hDriver)->Rename(pszNewName, pszOldName);
    1974             : }
    1975             : 
    1976             : /************************************************************************/
    1977             : /*                          DefaultCopyFiles()                          */
    1978             : /*                                                                      */
    1979             : /*      The default implementation based on file lists used when        */
    1980             : /*      there is no format specific implementation.                     */
    1981             : /************************************************************************/
    1982             : 
    1983             : //! @cond Doxygen_Suppress
    1984          12 : CPLErr GDALDriver::DefaultCopyFiles(const char *pszNewName,
    1985             :                                     const char *pszOldName)
    1986             : 
    1987             : {
    1988             :     /* -------------------------------------------------------------------- */
    1989             :     /*      Collect file list.                                              */
    1990             :     /* -------------------------------------------------------------------- */
    1991             :     auto poDS = std::unique_ptr<GDALDataset>(
    1992             :         GDALDataset::Open(pszOldName, GDAL_OF_ALL | GDAL_OF_VERBOSE_ERROR,
    1993          24 :                           nullptr, nullptr, nullptr));
    1994             : 
    1995          12 :     if (!poDS)
    1996             :     {
    1997           0 :         if (CPLGetLastErrorNo() == 0)
    1998           0 :             CPLError(CE_Failure, CPLE_OpenFailed,
    1999             :                      "Unable to open %s to obtain file list.", pszOldName);
    2000             : 
    2001           0 :         return CE_Failure;
    2002             :     }
    2003             : 
    2004          24 :     const CPLStringList aosFileList(poDS->GetFileList());
    2005             : 
    2006          12 :     poDS.reset();
    2007             : 
    2008          12 :     if (aosFileList.empty())
    2009             :     {
    2010           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    2011             :                  "Unable to determine files associated with %s,\n"
    2012             :                  "copy fails.",
    2013             :                  pszOldName);
    2014             : 
    2015           0 :         return CE_Failure;
    2016             :     }
    2017             : 
    2018             :     /* -------------------------------------------------------------------- */
    2019             :     /*      Produce a list of new filenames that correspond to the old      */
    2020             :     /*      names.                                                          */
    2021             :     /* -------------------------------------------------------------------- */
    2022          12 :     CPLErr eErr = CE_None;
    2023             :     const CPLStringList aosNewFileList(
    2024          24 :         CPLCorrespondingPaths(pszOldName, pszNewName, aosFileList.List()));
    2025             : 
    2026          12 :     if (aosNewFileList.empty())
    2027           0 :         return CE_Failure;
    2028             : 
    2029             :     // Guaranteed by CPLCorrespondingPaths()
    2030          12 :     CPLAssert(aosNewFileList.size() == aosFileList.size());
    2031             : 
    2032             :     VSIStatBufL sStatBuf;
    2033          14 :     if (VSIStatL(pszOldName, &sStatBuf) == 0 && VSI_ISDIR(sStatBuf.st_mode) &&
    2034           2 :         VSIStatL(pszNewName, &sStatBuf) != 0)
    2035             :     {
    2036           2 :         if (VSIMkdirRecursive(pszNewName, 0755) != 0)
    2037             :         {
    2038           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    2039             :                      "Cannot create directory '%s'", pszNewName);
    2040           1 :             return CE_Failure;
    2041             :         }
    2042             :     }
    2043             : 
    2044          33 :     for (int i = 0; i < aosFileList.size(); ++i)
    2045             :     {
    2046          22 :         if (CPLCopyFile(aosNewFileList[i], aosFileList[i]) != 0)
    2047             :         {
    2048             :             // Above method will have emitted an error in case of failure.
    2049           0 :             eErr = CE_Failure;
    2050             :             // Try to put the ones we moved back.
    2051           0 :             for (--i; i >= 0; --i)
    2052             :             {
    2053           0 :                 if (VSIUnlink(aosNewFileList[i]) != 0)
    2054             :                 {
    2055           0 :                     CPLError(CE_Warning, CPLE_AppDefined, "Cannot delete '%s'",
    2056             :                              aosNewFileList[i]);
    2057             :                 }
    2058             :             }
    2059           0 :             break;
    2060             :         }
    2061             :     }
    2062             : 
    2063          11 :     return eErr;
    2064             : }
    2065             : 
    2066             : //! @endcond
    2067             : 
    2068             : /************************************************************************/
    2069             : /*                             CopyFiles()                              */
    2070             : /************************************************************************/
    2071             : 
    2072             : /**
    2073             :  * \brief Copy the files of a dataset.
    2074             :  *
    2075             :  * Copy all the files associated with a dataset.
    2076             :  *
    2077             :  * Equivalent of the C function GDALCopyDatasetFiles().
    2078             :  *
    2079             :  * @param pszNewName new name for the dataset.
    2080             :  * @param pszOldName old name for the dataset.
    2081             :  *
    2082             :  * @return CE_None on success, or CE_Failure if the operation fails.
    2083             :  */
    2084             : 
    2085          14 : CPLErr GDALDriver::CopyFiles(const char *pszNewName, const char *pszOldName)
    2086             : 
    2087             : {
    2088          14 :     pfnCopyFiles = GetCopyFilesCallback();
    2089          14 :     if (pfnCopyFiles != nullptr)
    2090           3 :         return pfnCopyFiles(pszNewName, pszOldName);
    2091             : 
    2092          11 :     return DefaultCopyFiles(pszNewName, pszOldName);
    2093             : }
    2094             : 
    2095             : /************************************************************************/
    2096             : /*                        GDALCopyDatasetFiles()                        */
    2097             : /************************************************************************/
    2098             : 
    2099             : /**
    2100             :  * \brief Copy the files of a dataset.
    2101             :  *
    2102             :  * @see GDALDriver::CopyFiles()
    2103             :  */
    2104             : 
    2105          15 : CPLErr CPL_STDCALL GDALCopyDatasetFiles(GDALDriverH hDriver,
    2106             :                                         const char *pszNewName,
    2107             :                                         const char *pszOldName)
    2108             : 
    2109             : {
    2110          15 :     if (hDriver == nullptr)
    2111          10 :         hDriver = GDALIdentifyDriver(pszOldName, nullptr);
    2112             : 
    2113          15 :     if (hDriver == nullptr)
    2114             :     {
    2115           1 :         CPLError(CE_Failure, CPLE_AppDefined, "No identifiable driver for %s.",
    2116             :                  pszOldName);
    2117           1 :         return CE_Failure;
    2118             :     }
    2119             : 
    2120          14 :     return GDALDriver::FromHandle(hDriver)->CopyFiles(pszNewName, pszOldName);
    2121             : }
    2122             : 
    2123             : /************************************************************************/
    2124             : /*                      GDALDriverHasOpenOption()                       */
    2125             : /************************************************************************/
    2126             : 
    2127             : /**
    2128             :  * \brief Returns TRUE if the given open option is supported by the driver.
    2129             :  * @param hDriver the handle of the driver
    2130             :  * @param pszOpenOptionName name of the open option to be checked
    2131             :  * @return TRUE if the driver supports the open option
    2132             :  * @since GDAL 3.11
    2133             :  */
    2134           2 : bool GDALDriverHasOpenOption(GDALDriverH hDriver, const char *pszOpenOptionName)
    2135             : {
    2136           2 :     VALIDATE_POINTER1(hDriver, "GDALDriverHasOpenOption", false);
    2137           2 :     return GDALDriver::FromHandle(hDriver)->HasOpenOption(pszOpenOptionName);
    2138             : }
    2139             : 
    2140             : /************************************************************************/
    2141             : /*                       GDALGetDriverShortName()                       */
    2142             : /************************************************************************/
    2143             : 
    2144             : /**
    2145             :  * \brief Return the short name of a driver
    2146             :  *
    2147             :  * This is the string that can be
    2148             :  * passed to the GDALGetDriverByName() function.
    2149             :  *
    2150             :  * For the GeoTIFF driver, this is "GTiff"
    2151             :  *
    2152             :  * @param hDriver the handle of the driver
    2153             :  * @return the short name of the driver. The
    2154             :  *         returned string should not be freed and is owned by the driver.
    2155             :  */
    2156             : 
    2157     8905660 : const char *CPL_STDCALL GDALGetDriverShortName(GDALDriverH hDriver)
    2158             : 
    2159             : {
    2160     8905660 :     VALIDATE_POINTER1(hDriver, "GDALGetDriverShortName", nullptr);
    2161             : 
    2162     8905660 :     return GDALDriver::FromHandle(hDriver)->GetDescription();
    2163             : }
    2164             : 
    2165             : /************************************************************************/
    2166             : /*                       GDALGetDriverLongName()                        */
    2167             : /************************************************************************/
    2168             : 
    2169             : /**
    2170             :  * \brief Return the long name of a driver
    2171             :  *
    2172             :  * For the GeoTIFF driver, this is "GeoTIFF"
    2173             :  *
    2174             :  * @param hDriver the handle of the driver
    2175             :  * @return the long name of the driver or empty string. The
    2176             :  *         returned string should not be freed and is owned by the driver.
    2177             :  */
    2178             : 
    2179         511 : const char *CPL_STDCALL GDALGetDriverLongName(GDALDriverH hDriver)
    2180             : 
    2181             : {
    2182         511 :     VALIDATE_POINTER1(hDriver, "GDALGetDriverLongName", nullptr);
    2183             : 
    2184             :     const char *pszLongName =
    2185         511 :         GDALDriver::FromHandle(hDriver)->GetMetadataItem(GDAL_DMD_LONGNAME);
    2186             : 
    2187         511 :     if (pszLongName == nullptr)
    2188           0 :         return "";
    2189             : 
    2190         511 :     return pszLongName;
    2191             : }
    2192             : 
    2193             : /************************************************************************/
    2194             : /*                       GDALGetDriverHelpTopic()                       */
    2195             : /************************************************************************/
    2196             : 
    2197             : /**
    2198             :  * \brief Return the URL to the help that describes the driver
    2199             :  *
    2200             :  * That URL is relative to the GDAL documentation directory.
    2201             :  *
    2202             :  * For the GeoTIFF driver, this is "frmt_gtiff.html"
    2203             :  *
    2204             :  * @param hDriver the handle of the driver
    2205             :  * @return the URL to the help that describes the driver or NULL. The
    2206             :  *         returned string should not be freed and is owned by the driver.
    2207             :  */
    2208             : 
    2209           0 : const char *CPL_STDCALL GDALGetDriverHelpTopic(GDALDriverH hDriver)
    2210             : 
    2211             : {
    2212           0 :     VALIDATE_POINTER1(hDriver, "GDALGetDriverHelpTopic", nullptr);
    2213             : 
    2214           0 :     return GDALDriver::FromHandle(hDriver)->GetMetadataItem(GDAL_DMD_HELPTOPIC);
    2215             : }
    2216             : 
    2217             : /************************************************************************/
    2218             : /*                  GDALGetDriverCreationOptionList()                   */
    2219             : /************************************************************************/
    2220             : 
    2221             : /**
    2222             :  * \brief Return the list of creation options of the driver
    2223             :  *
    2224             :  * Return the list of creation options of the driver used by Create() and
    2225             :  * CreateCopy() as an XML string
    2226             :  *
    2227             :  * @param hDriver the handle of the driver
    2228             :  * @return an XML string that describes the list of creation options or
    2229             :  *         empty string. The returned string should not be freed and is
    2230             :  *         owned by the driver.
    2231             :  */
    2232             : 
    2233           0 : const char *CPL_STDCALL GDALGetDriverCreationOptionList(GDALDriverH hDriver)
    2234             : 
    2235             : {
    2236           0 :     VALIDATE_POINTER1(hDriver, "GDALGetDriverCreationOptionList", nullptr);
    2237             : 
    2238             :     const char *pszOptionList =
    2239           0 :         GDALDriver::FromHandle(hDriver)->GetMetadataItem(
    2240           0 :             GDAL_DMD_CREATIONOPTIONLIST);
    2241             : 
    2242           0 :     if (pszOptionList == nullptr)
    2243           0 :         return "";
    2244             : 
    2245           0 :     return pszOptionList;
    2246             : }
    2247             : 
    2248             : /************************************************************************/
    2249             : /*                    GDALValidateCreationOptions()                     */
    2250             : /************************************************************************/
    2251             : 
    2252             : /**
    2253             :  * \brief Validate the list of creation options that are handled by a driver
    2254             :  *
    2255             :  * This is a helper method primarily used by Create() and
    2256             :  * CreateCopy() to validate that the passed in list of creation options
    2257             :  * is compatible with the GDAL_DMD_CREATIONOPTIONLIST metadata item defined
    2258             :  * by some drivers. @see GDALGetDriverCreationOptionList()
    2259             :  *
    2260             :  * If the GDAL_DMD_CREATIONOPTIONLIST metadata item is not defined, this
    2261             :  * function will return TRUE. Otherwise it will check that the keys and values
    2262             :  * in the list of creation options are compatible with the capabilities declared
    2263             :  * by the GDAL_DMD_CREATIONOPTIONLIST metadata item. In case of incompatibility
    2264             :  * a (non fatal) warning will be emitted and FALSE will be returned.
    2265             :  *
    2266             :  * @param hDriver the handle of the driver with whom the lists of creation
    2267             :  * option must be validated
    2268             :  * @param papszCreationOptions the list of creation options. An array of
    2269             :  * strings, whose last element is a NULL pointer
    2270             :  * @return TRUE if the list of creation options is compatible with the Create()
    2271             :  *         and CreateCopy() method of the driver, FALSE otherwise.
    2272             :  */
    2273             : 
    2274       37653 : int CPL_STDCALL GDALValidateCreationOptions(GDALDriverH hDriver,
    2275             :                                             CSLConstList papszCreationOptions)
    2276             : {
    2277       37653 :     VALIDATE_POINTER1(hDriver, "GDALValidateCreationOptions", FALSE);
    2278             :     const char *pszOptionList =
    2279       37653 :         GDALDriver::FromHandle(hDriver)->GetMetadataItem(
    2280       37653 :             GDAL_DMD_CREATIONOPTIONLIST);
    2281       37653 :     CPLString osDriver;
    2282             :     osDriver.Printf("driver %s",
    2283       37653 :                     GDALDriver::FromHandle(hDriver)->GetDescription());
    2284       37653 :     bool bFoundOptionToRemove = false;
    2285       37653 :     constexpr const char *const apszExcludedOptions[] = {
    2286             :         "APPEND_SUBDATASET", "COPY_SRC_MDD", "SRC_MDD", "SKIP_HOLES"};
    2287       55322 :     for (const char *pszCO : cpl::Iterate(papszCreationOptions))
    2288             :     {
    2289       88996 :         for (const char *pszExcludedOptions : apszExcludedOptions)
    2290             :         {
    2291       71327 :             if (STARTS_WITH_CI(pszCO, pszExcludedOptions) &&
    2292         207 :                 pszCO[strlen(pszExcludedOptions)] == '=')
    2293             :             {
    2294         207 :                 bFoundOptionToRemove = true;
    2295         207 :                 break;
    2296             :             }
    2297             :         }
    2298       17876 :         if (bFoundOptionToRemove)
    2299         207 :             break;
    2300             :     }
    2301       37653 :     CSLConstList papszOptionsToValidate = papszCreationOptions;
    2302       37653 :     char **papszOptionsToFree = nullptr;
    2303       37653 :     if (bFoundOptionToRemove)
    2304             :     {
    2305         632 :         for (const char *pszCO : cpl::Iterate(papszCreationOptions))
    2306             :         {
    2307         425 :             bool bMatch = false;
    2308        1721 :             for (const char *pszExcludedOptions : apszExcludedOptions)
    2309             :             {
    2310        1516 :                 if (STARTS_WITH_CI(pszCO, pszExcludedOptions) &&
    2311         220 :                     pszCO[strlen(pszExcludedOptions)] == '=')
    2312             :                 {
    2313         220 :                     bMatch = true;
    2314         220 :                     break;
    2315             :                 }
    2316             :             }
    2317         425 :             if (!bMatch)
    2318         205 :                 papszOptionsToFree = CSLAddString(papszOptionsToFree, pszCO);
    2319             :         }
    2320         207 :         papszOptionsToValidate = papszOptionsToFree;
    2321             :     }
    2322             : 
    2323       37653 :     const bool bRet = CPL_TO_BOOL(
    2324             :         GDALValidateOptions(hDriver, pszOptionList, papszOptionsToValidate,
    2325             :                             "creation option", osDriver));
    2326       37653 :     CSLDestroy(papszOptionsToFree);
    2327       37653 :     return bRet;
    2328             : }
    2329             : 
    2330             : /************************************************************************/
    2331             : /*                      GDALValidateOpenOptions()                       */
    2332             : /************************************************************************/
    2333             : 
    2334       63842 : int GDALValidateOpenOptions(GDALDriverH hDriver,
    2335             :                             const char *const *papszOpenOptions)
    2336             : {
    2337       63842 :     VALIDATE_POINTER1(hDriver, "GDALValidateOpenOptions", FALSE);
    2338             :     const char *pszOptionList =
    2339       63842 :         GDALDriver::FromHandle(hDriver)->GetMetadataItem(
    2340       63842 :             GDAL_DMD_OPENOPTIONLIST);
    2341      127684 :     CPLString osDriver;
    2342             :     osDriver.Printf("driver %s",
    2343       63842 :                     GDALDriver::FromHandle(hDriver)->GetDescription());
    2344       63842 :     return GDALValidateOptions(hDriver, pszOptionList, papszOpenOptions,
    2345       63842 :                                "open option", osDriver);
    2346             : }
    2347             : 
    2348             : /************************************************************************/
    2349             : /*                        GDALValidateOptions()                         */
    2350             : /************************************************************************/
    2351             : 
    2352      116346 : int GDALValidateOptions(GDALDriverH hDriver, const char *pszOptionList,
    2353             :                         const char *const *papszOptionsToValidate,
    2354             :                         const char *pszErrorMessageOptionType,
    2355             :                         const char *pszErrorMessageContainerName)
    2356             : {
    2357      116346 :     if (papszOptionsToValidate == nullptr || *papszOptionsToValidate == nullptr)
    2358       97951 :         return TRUE;
    2359       18395 :     if (pszOptionList == nullptr)
    2360         181 :         return TRUE;
    2361             : 
    2362       18214 :     CPLXMLNode *psNode = CPLParseXMLString(pszOptionList);
    2363       18214 :     if (psNode == nullptr)
    2364             :     {
    2365           0 :         CPLError(CE_Warning, CPLE_AppDefined,
    2366             :                  "Could not parse %s list of %s. Assuming options are valid.",
    2367             :                  pszErrorMessageOptionType, pszErrorMessageContainerName);
    2368           0 :         return TRUE;
    2369             :     }
    2370             : 
    2371       18214 :     bool bRet = true;
    2372       49486 :     while (*papszOptionsToValidate)
    2373             :     {
    2374       31272 :         char *pszKey = nullptr;
    2375             :         const char *pszValue =
    2376       31272 :             CPLParseNameValue(*papszOptionsToValidate, &pszKey);
    2377       31272 :         if (pszKey == nullptr)
    2378             :         {
    2379           1 :             CPLError(CE_Warning, CPLE_NotSupported,
    2380             :                      "%s '%s' is not formatted with the key=value format",
    2381             :                      pszErrorMessageOptionType, *papszOptionsToValidate);
    2382           1 :             bRet = false;
    2383             : 
    2384           1 :             ++papszOptionsToValidate;
    2385        2394 :             continue;
    2386             :         }
    2387             : 
    2388       31271 :         if (EQUAL(pszKey, "VALIDATE_OPEN_OPTIONS"))
    2389             :         {
    2390           0 :             ++papszOptionsToValidate;
    2391           0 :             CPLFree(pszKey);
    2392           0 :             continue;
    2393             :         }
    2394             : 
    2395             :         // Must we be forgiving in case of missing option ?
    2396       31271 :         bool bWarnIfMissingKey = true;
    2397       31271 :         if (pszKey[0] == '@')
    2398             :         {
    2399        2374 :             bWarnIfMissingKey = false;
    2400        2374 :             memmove(pszKey, pszKey + 1, strlen(pszKey + 1) + 1);
    2401             :         }
    2402             : 
    2403       31271 :         CPLXMLNode *psChildNode = psNode->psChild;
    2404      313754 :         while (psChildNode)
    2405             :         {
    2406      311361 :             if (EQUAL(psChildNode->pszValue, "OPTION"))
    2407             :             {
    2408             :                 const char *pszOptionName =
    2409      311361 :                     CPLGetXMLValue(psChildNode, "name", "");
    2410             :                 /* For option names terminated by wildcard (NITF BLOCKA option
    2411             :                  * names for example) */
    2412      311361 :                 if (strlen(pszOptionName) > 0 &&
    2413      311361 :                     pszOptionName[strlen(pszOptionName) - 1] == '*' &&
    2414        1288 :                     EQUALN(pszOptionName, pszKey, strlen(pszOptionName) - 1))
    2415             :                 {
    2416         216 :                     break;
    2417             :                 }
    2418             : 
    2419             :                 /* For option names beginning by a wildcard */
    2420      311145 :                 if (pszOptionName[0] == '*' &&
    2421          57 :                     strlen(pszKey) > strlen(pszOptionName) &&
    2422           9 :                     EQUAL(pszKey + strlen(pszKey) - strlen(pszOptionName + 1),
    2423             :                           pszOptionName + 1))
    2424             :                 {
    2425           2 :                     break;
    2426             :                 }
    2427             : 
    2428             :                 // For options names with * in the middle
    2429      311143 :                 const char *pszStarInOptionName = strchr(pszOptionName, '*');
    2430      311143 :                 if (pszStarInOptionName &&
    2431        1093 :                     pszStarInOptionName != pszOptionName &&
    2432             :                     pszStarInOptionName !=
    2433        1093 :                         pszOptionName + strlen(pszOptionName) - 1 &&
    2434          21 :                     strlen(pszKey) > static_cast<size_t>(pszStarInOptionName -
    2435          12 :                                                          pszOptionName) &&
    2436          12 :                     EQUALN(pszKey, pszOptionName,
    2437             :                            static_cast<size_t>(pszStarInOptionName -
    2438          12 :                                                pszOptionName)) &&
    2439          12 :                     EQUAL(pszKey +
    2440             :                               static_cast<size_t>(pszStarInOptionName -
    2441             :                                                   pszOptionName) +
    2442             :                               1,
    2443             :                           pszStarInOptionName + 1))
    2444             :                 {
    2445           6 :                     break;
    2446             :                 }
    2447             : 
    2448      311137 :                 if (EQUAL(pszOptionName, pszKey))
    2449             :                 {
    2450       28542 :                     break;
    2451             :                 }
    2452             :                 const char *pszAlias =
    2453      282595 :                     CPLGetXMLValue(psChildNode, "alias", nullptr);
    2454             :                 const char *pszDeprecatedAlias =
    2455      282595 :                     pszAlias ? nullptr
    2456      281654 :                              : CPLGetXMLValue(psChildNode, "deprecated_alias",
    2457      282595 :                                               nullptr);
    2458      282595 :                 if (!pszAlias && pszDeprecatedAlias)
    2459         166 :                     pszAlias = pszDeprecatedAlias;
    2460      282595 :                 if (pszAlias && EQUAL(pszAlias, pszKey))
    2461             :                 {
    2462         112 :                     if (pszDeprecatedAlias)
    2463             :                     {
    2464           0 :                         CPLDebug(
    2465             :                             "GDAL",
    2466             :                             "Using deprecated alias '%s'. New name is '%s'",
    2467             :                             pszAlias, pszOptionName);
    2468             :                     }
    2469         112 :                     break;
    2470             :                 }
    2471             :             }
    2472      282483 :             psChildNode = psChildNode->psNext;
    2473             :         }
    2474       31271 :         if (psChildNode == nullptr)
    2475             :         {
    2476        2419 :             if (bWarnIfMissingKey &&
    2477          26 :                 (!EQUAL(pszErrorMessageOptionType, "open option") ||
    2478           2 :                  CPLFetchBool(papszOptionsToValidate, "VALIDATE_OPEN_OPTIONS",
    2479             :                               true)))
    2480             :             {
    2481          26 :                 const char *pszAdditionalMsg = "";
    2482          26 :                 if (hDriver &&
    2483          21 :                     EQUAL(pszErrorMessageOptionType, "creation option"))
    2484             :                 {
    2485             :                     const char *pszLCOList =
    2486          16 :                         GDALDriver::FromHandle(hDriver)->GetMetadataItem(
    2487          16 :                             GDAL_DS_LAYER_CREATIONOPTIONLIST);
    2488          22 :                     if (pszLCOList &&
    2489          22 :                         (CPLString(pszLCOList)
    2490           6 :                                  .ifind(CPLSPrintf("\"%s\"", pszKey)) !=
    2491          12 :                              std::string::npos ||
    2492          22 :                          CPLString(pszLCOList)
    2493           6 :                                  .ifind(CPLSPrintf("'%s'", pszKey)) !=
    2494             :                              std::string::npos))
    2495             :                     {
    2496           1 :                         pszAdditionalMsg = ", but a layer creation option of "
    2497             :                                            "that name exists.";
    2498          16 :                     }
    2499             :                 }
    2500          10 :                 else if (hDriver && EQUAL(pszErrorMessageOptionType,
    2501             :                                           "layer creation option"))
    2502             :                 {
    2503             :                     const char *pszLCOList =
    2504           3 :                         GDALDriver::FromHandle(hDriver)->GetMetadataItem(
    2505           3 :                             GDAL_DMD_CREATIONOPTIONLIST);
    2506           6 :                     if (pszLCOList &&
    2507           6 :                         (CPLString(pszLCOList)
    2508           3 :                                  .ifind(CPLSPrintf("\"%s\"", pszKey)) !=
    2509           6 :                              std::string::npos ||
    2510           6 :                          CPLString(pszLCOList)
    2511           3 :                                  .ifind(CPLSPrintf("'%s'", pszKey)) !=
    2512             :                              std::string::npos))
    2513             :                     {
    2514           1 :                         pszAdditionalMsg = ", but a creation option of "
    2515             :                                            "that name exists.";
    2516             :                     }
    2517             :                 }
    2518             : 
    2519          26 :                 CPLError(CE_Warning, CPLE_NotSupported,
    2520             :                          "%s does not support %s %s%s",
    2521             :                          pszErrorMessageContainerName,
    2522             :                          pszErrorMessageOptionType, pszKey, pszAdditionalMsg);
    2523          26 :                 bRet = false;
    2524             :             }
    2525             : 
    2526        2393 :             CPLFree(pszKey);
    2527        2393 :             ++papszOptionsToValidate;
    2528        2393 :             continue;
    2529             :         }
    2530             : 
    2531             : #ifdef DEBUG
    2532       28878 :         CPLXMLNode *psChildSubNode = psChildNode->psChild;
    2533      171042 :         while (psChildSubNode)
    2534             :         {
    2535      142164 :             if (psChildSubNode->eType == CXT_Attribute)
    2536             :             {
    2537      100132 :                 if (!(EQUAL(psChildSubNode->pszValue, "name") ||
    2538       71254 :                       EQUAL(psChildSubNode->pszValue, "alias") ||
    2539       71059 :                       EQUAL(psChildSubNode->pszValue, "deprecated_alias") ||
    2540       70965 :                       EQUAL(psChildSubNode->pszValue, "alt_config_option") ||
    2541       70945 :                       EQUAL(psChildSubNode->pszValue, "description") ||
    2542       46590 :                       EQUAL(psChildSubNode->pszValue, "type") ||
    2543       17712 :                       EQUAL(psChildSubNode->pszValue, "min") ||
    2544       17394 :                       EQUAL(psChildSubNode->pszValue, "max") ||
    2545       17007 :                       EQUAL(psChildSubNode->pszValue, "default") ||
    2546        1078 :                       EQUAL(psChildSubNode->pszValue, "maxsize") ||
    2547        1048 :                       EQUAL(psChildSubNode->pszValue, "required") ||
    2548         993 :                       EQUAL(psChildSubNode->pszValue, "scope")))
    2549             :                 {
    2550             :                     /* Driver error */
    2551           0 :                     CPLError(CE_Warning, CPLE_NotSupported,
    2552             :                              "%s : unhandled attribute '%s' for %s %s.",
    2553             :                              pszErrorMessageContainerName,
    2554             :                              psChildSubNode->pszValue, pszKey,
    2555             :                              pszErrorMessageOptionType);
    2556             :                 }
    2557             :             }
    2558      142164 :             psChildSubNode = psChildSubNode->psNext;
    2559             :         }
    2560             : #endif
    2561             : 
    2562       28878 :         const char *pszType = CPLGetXMLValue(psChildNode, "type", nullptr);
    2563       28878 :         const char *pszMin = CPLGetXMLValue(psChildNode, "min", nullptr);
    2564       28878 :         const char *pszMax = CPLGetXMLValue(psChildNode, "max", nullptr);
    2565       28878 :         if (pszType != nullptr)
    2566             :         {
    2567       28878 :             if (EQUAL(pszType, "INT") || EQUAL(pszType, "INTEGER"))
    2568             :             {
    2569        8854 :                 const char *pszValueIter = pszValue;
    2570       22702 :                 while (*pszValueIter)
    2571             :                 {
    2572       13898 :                     if (!((*pszValueIter >= '0' && *pszValueIter <= '9') ||
    2573          69 :                           *pszValueIter == '+' || *pszValueIter == '-'))
    2574             :                     {
    2575          50 :                         CPLError(CE_Warning, CPLE_NotSupported,
    2576             :                                  "'%s' is an unexpected value for %s %s of "
    2577             :                                  "type int.",
    2578             :                                  pszValue, pszKey, pszErrorMessageOptionType);
    2579          50 :                         bRet = false;
    2580          50 :                         break;
    2581             :                     }
    2582       13848 :                     ++pszValueIter;
    2583             :                 }
    2584        8854 :                 if (*pszValueIter == '\0')
    2585             :                 {
    2586        8804 :                     if (pszMin && atoi(pszValue) < atoi(pszMin))
    2587             :                     {
    2588          10 :                         CPLError(CE_Warning, CPLE_NotSupported,
    2589             :                                  "'%s' is an unexpected value for %s %s that "
    2590             :                                  "should be >= %s.",
    2591             :                                  pszValue, pszKey, pszErrorMessageOptionType,
    2592             :                                  pszMin);
    2593          10 :                         bRet = false;
    2594             :                     }
    2595        8804 :                     if (pszMax && atoi(pszValue) > atoi(pszMax))
    2596             :                     {
    2597          12 :                         CPLError(CE_Warning, CPLE_NotSupported,
    2598             :                                  "'%s' is an unexpected value for %s %s that "
    2599             :                                  "should be <= %s.",
    2600             :                                  pszValue, pszKey, pszErrorMessageOptionType,
    2601             :                                  pszMax);
    2602          12 :                         bRet = false;
    2603             :                     }
    2604        8854 :                 }
    2605             :             }
    2606       20024 :             else if (EQUAL(pszType, "UNSIGNED INT"))
    2607             :             {
    2608           3 :                 const char *pszValueIter = pszValue;
    2609          10 :                 while (*pszValueIter)
    2610             :                 {
    2611           7 :                     if (!((*pszValueIter >= '0' && *pszValueIter <= '9') ||
    2612           0 :                           *pszValueIter == '+'))
    2613             :                     {
    2614           0 :                         CPLError(CE_Warning, CPLE_NotSupported,
    2615             :                                  "'%s' is an unexpected value for %s %s of "
    2616             :                                  "type unsigned int.",
    2617             :                                  pszValue, pszKey, pszErrorMessageOptionType);
    2618           0 :                         bRet = false;
    2619           0 :                         break;
    2620             :                     }
    2621           7 :                     ++pszValueIter;
    2622             :                 }
    2623           3 :                 if (*pszValueIter == '\0')
    2624             :                 {
    2625           3 :                     if (pszMin && atoi(pszValue) < atoi(pszMin))
    2626             :                     {
    2627           0 :                         CPLError(CE_Warning, CPLE_NotSupported,
    2628             :                                  "'%s' is an unexpected value for %s %s that "
    2629             :                                  "should be >= %s.",
    2630             :                                  pszValue, pszKey, pszErrorMessageOptionType,
    2631             :                                  pszMin);
    2632           0 :                         bRet = false;
    2633             :                     }
    2634           3 :                     if (pszMax && atoi(pszValue) > atoi(pszMax))
    2635             :                     {
    2636           0 :                         CPLError(CE_Warning, CPLE_NotSupported,
    2637             :                                  "'%s' is an unexpected value for %s %s that "
    2638             :                                  "should be <= %s.",
    2639             :                                  pszValue, pszKey, pszErrorMessageOptionType,
    2640             :                                  pszMax);
    2641           0 :                         bRet = false;
    2642             :                     }
    2643             :                 }
    2644             :             }
    2645       20021 :             else if (EQUAL(pszType, "FLOAT"))
    2646             :             {
    2647         776 :                 char *endPtr = nullptr;
    2648         776 :                 double dfVal = CPLStrtod(pszValue, &endPtr);
    2649         776 :                 if (!(endPtr == nullptr || *endPtr == '\0'))
    2650             :                 {
    2651           2 :                     CPLError(
    2652             :                         CE_Warning, CPLE_NotSupported,
    2653             :                         "'%s' is an unexpected value for %s %s of type float.",
    2654             :                         pszValue, pszKey, pszErrorMessageOptionType);
    2655           2 :                     bRet = false;
    2656             :                 }
    2657             :                 else
    2658             :                 {
    2659         774 :                     if (pszMin && dfVal < CPLAtof(pszMin))
    2660             :                     {
    2661           3 :                         CPLError(CE_Warning, CPLE_NotSupported,
    2662             :                                  "'%s' is an unexpected value for %s %s that "
    2663             :                                  "should be >= %s.",
    2664             :                                  pszValue, pszKey, pszErrorMessageOptionType,
    2665             :                                  pszMin);
    2666           3 :                         bRet = false;
    2667             :                     }
    2668         774 :                     if (pszMax && dfVal > CPLAtof(pszMax))
    2669             :                     {
    2670           0 :                         CPLError(CE_Warning, CPLE_NotSupported,
    2671             :                                  "'%s' is an unexpected value for %s %s that "
    2672             :                                  "should be <= %s.",
    2673             :                                  pszValue, pszKey, pszErrorMessageOptionType,
    2674             :                                  pszMax);
    2675           0 :                         bRet = false;
    2676             :                     }
    2677             :                 }
    2678             :             }
    2679       19245 :             else if (EQUAL(pszType, "BOOLEAN"))
    2680             :             {
    2681        4608 :                 if (!(EQUAL(pszValue, "ON") || EQUAL(pszValue, "TRUE") ||
    2682        4538 :                       EQUAL(pszValue, "YES") || EQUAL(pszValue, "OFF") ||
    2683         833 :                       EQUAL(pszValue, "FALSE") || EQUAL(pszValue, "NO")))
    2684             :                 {
    2685           0 :                     CPLError(CE_Warning, CPLE_NotSupported,
    2686             :                              "'%s' is an unexpected value for %s %s of type "
    2687             :                              "boolean.",
    2688             :                              pszValue, pszKey, pszErrorMessageOptionType);
    2689           0 :                     bRet = false;
    2690             :                 }
    2691             :             }
    2692       14637 :             else if (EQUAL(pszType, "STRING-SELECT"))
    2693             :             {
    2694        7498 :                 bool bMatchFound = false;
    2695        7498 :                 bool bOtherValuesElementFound = false;
    2696        7498 :                 CPLXMLNode *psStringSelect = psChildNode->psChild;
    2697       46165 :                 while (psStringSelect)
    2698             :                 {
    2699       46124 :                     if (psStringSelect->eType == CXT_Element &&
    2700       22251 :                         EQUAL(psStringSelect->pszValue, "Value"))
    2701             :                     {
    2702       22251 :                         CPLXMLNode *psOptionNode = psStringSelect->psChild;
    2703       37672 :                         while (psOptionNode)
    2704             :                         {
    2705       22878 :                             if (psOptionNode->eType == CXT_Text &&
    2706       22132 :                                 EQUAL(psOptionNode->pszValue, pszValue))
    2707             :                             {
    2708        7338 :                                 bMatchFound = true;
    2709        7338 :                                 break;
    2710             :                             }
    2711       15540 :                             if (psOptionNode->eType == CXT_Attribute &&
    2712         746 :                                 (EQUAL(psOptionNode->pszValue, "alias") ||
    2713          15 :                                  EQUAL(psOptionNode->pszValue,
    2714         731 :                                        "deprecated_alias")) &&
    2715         731 :                                 EQUAL(psOptionNode->psChild->pszValue,
    2716             :                                       pszValue))
    2717             :                             {
    2718         119 :                                 bMatchFound = true;
    2719         119 :                                 break;
    2720             :                             }
    2721       15421 :                             psOptionNode = psOptionNode->psNext;
    2722             :                         }
    2723       22251 :                         if (bMatchFound)
    2724       22251 :                             break;
    2725             :                     }
    2726       23873 :                     else if (psStringSelect->eType == CXT_Element &&
    2727           0 :                              EQUAL(psStringSelect->pszValue, "OtherValues"))
    2728             :                     {
    2729           0 :                         bOtherValuesElementFound = true;
    2730             :                     }
    2731       38667 :                     psStringSelect = psStringSelect->psNext;
    2732             :                 }
    2733        7498 :                 if (!bMatchFound && !bOtherValuesElementFound)
    2734             :                 {
    2735          41 :                     CPLError(CE_Warning, CPLE_NotSupported,
    2736             :                              "'%s' is an unexpected value for %s %s of type "
    2737             :                              "string-select.",
    2738             :                              pszValue, pszKey, pszErrorMessageOptionType);
    2739          41 :                     bRet = false;
    2740             :                 }
    2741             :             }
    2742        7139 :             else if (EQUAL(pszType, "STRING"))
    2743             :             {
    2744             :                 const char *pszMaxSize =
    2745        7139 :                     CPLGetXMLValue(psChildNode, "maxsize", nullptr);
    2746        7139 :                 if (pszMaxSize != nullptr)
    2747             :                 {
    2748          30 :                     if (static_cast<int>(strlen(pszValue)) > atoi(pszMaxSize))
    2749             :                     {
    2750           1 :                         CPLError(CE_Warning, CPLE_NotSupported,
    2751             :                                  "'%s' is of size %d, whereas maximum size for "
    2752             :                                  "%s %s is %d.",
    2753           1 :                                  pszValue, static_cast<int>(strlen(pszValue)),
    2754             :                                  pszKey, pszErrorMessageOptionType,
    2755             :                                  atoi(pszMaxSize));
    2756           1 :                         bRet = false;
    2757             :                     }
    2758             :                 }
    2759             :             }
    2760             :             else
    2761             :             {
    2762             :                 /* Driver error */
    2763           0 :                 CPLError(CE_Warning, CPLE_NotSupported,
    2764             :                          "%s : type '%s' for %s %s is not recognized.",
    2765             :                          pszErrorMessageContainerName, pszType, pszKey,
    2766             :                          pszErrorMessageOptionType);
    2767             :             }
    2768             :         }
    2769             :         else
    2770             :         {
    2771             :             /* Driver error */
    2772           0 :             CPLError(CE_Warning, CPLE_NotSupported, "%s : no type for %s %s.",
    2773             :                      pszErrorMessageContainerName, pszKey,
    2774             :                      pszErrorMessageOptionType);
    2775             :         }
    2776       28878 :         CPLFree(pszKey);
    2777       28878 :         ++papszOptionsToValidate;
    2778             :     }
    2779             : 
    2780       18214 :     CPLDestroyXMLNode(psNode);
    2781       18214 :     return bRet ? TRUE : FALSE;
    2782             : }
    2783             : 
    2784             : /************************************************************************/
    2785             : /*                         GDALIdentifyDriver()                         */
    2786             : /************************************************************************/
    2787             : 
    2788             : /**
    2789             :  * \brief Identify the driver that can open a dataset.
    2790             :  *
    2791             :  * This function will try to identify the driver that can open the passed file
    2792             :  * name by invoking the Identify method of each registered GDALDriver in turn.
    2793             :  * The first driver that successfully identifies the file name will be returned.
    2794             :  * If all drivers fail then NULL is returned.
    2795             :  *
    2796             :  * In order to reduce the need for such searches to touch the operating system
    2797             :  * file system machinery, it is possible to give an optional list of files.
    2798             :  * This is the list of all files at the same level in the file system as the
    2799             :  * target file, including the target file. The filenames will not include any
    2800             :  * path components, and are essentially just the output of VSIReadDir() on the
    2801             :  * parent directory. If the target object does not have filesystem semantics
    2802             :  * then the file list should be NULL.
    2803             :  *
    2804             :  * @param pszFilename the name of the file to access.  In the case of
    2805             :  * exotic drivers this may not refer to a physical file, but instead contain
    2806             :  * information for the driver on how to access a dataset.
    2807             :  *
    2808             :  * @param papszFileList an array of strings, whose last element is the NULL
    2809             :  * pointer.  These strings are filenames that are auxiliary to the main
    2810             :  * filename. The passed value may be NULL.
    2811             :  *
    2812             :  * @return A GDALDriverH handle or NULL on failure.  For C++ applications
    2813             :  * this handle can be cast to a GDALDriver *.
    2814             :  */
    2815             : 
    2816       26684 : GDALDriverH CPL_STDCALL GDALIdentifyDriver(const char *pszFilename,
    2817             :                                            CSLConstList papszFileList)
    2818             : 
    2819             : {
    2820       26684 :     return GDALIdentifyDriverEx(pszFilename, 0, nullptr, papszFileList);
    2821             : }
    2822             : 
    2823             : /************************************************************************/
    2824             : /*                        GDALIdentifyDriverEx()                        */
    2825             : /************************************************************************/
    2826             : 
    2827             : /**
    2828             :  * \brief Identify the driver that can open a dataset.
    2829             :  *
    2830             :  * This function will try to identify the driver that can open the passed file
    2831             :  * name by invoking the Identify method of each registered GDALDriver in turn.
    2832             :  * The first driver that successfully identifies the file name will be returned.
    2833             :  * If all drivers fail then NULL is returned.
    2834             :  *
    2835             :  * In order to reduce the need for such searches to touch the operating system
    2836             :  * file system machinery, it is possible to give an optional list of files.
    2837             :  * This is the list of all files at the same level in the file system as the
    2838             :  * target file, including the target file. The filenames will not include any
    2839             :  * path components, and are essentially just the output of VSIReadDir() on the
    2840             :  * parent directory. If the target object does not have filesystem semantics
    2841             :  * then the file list should be NULL.
    2842             :  *
    2843             :  * @param pszFilename the name of the file to access.  In the case of
    2844             :  * exotic drivers this may not refer to a physical file, but instead contain
    2845             :  * information for the driver on how to access a dataset.
    2846             :  *
    2847             :  * @param nIdentifyFlags a combination of GDAL_OF_RASTER for raster drivers
    2848             :  * or GDAL_OF_VECTOR for vector drivers. If none of the value is specified,
    2849             :  * both kinds are implied.
    2850             :  *
    2851             :  * @param papszAllowedDrivers NULL to consider all candidate drivers, or a NULL
    2852             :  * terminated list of strings with the driver short names that must be
    2853             :  * considered.
    2854             :  *
    2855             :  * @param papszFileList an array of strings, whose last element is the NULL
    2856             :  * pointer.  These strings are filenames that are auxiliary to the main
    2857             :  * filename. The passed value may be NULL.
    2858             :  *
    2859             :  * @return A GDALDriverH handle or NULL on failure.  For C++ applications
    2860             :  * this handle can be cast to a GDALDriver *.
    2861             :  */
    2862             : 
    2863       26774 : GDALDriverH CPL_STDCALL GDALIdentifyDriverEx(
    2864             :     const char *pszFilename, unsigned int nIdentifyFlags,
    2865             :     const char *const *papszAllowedDrivers, const char *const *papszFileList)
    2866             : {
    2867       26774 :     GDALDriverManager *poDM = GetGDALDriverManager();
    2868       26774 :     CPLAssert(nullptr != poDM);
    2869             : 
    2870             :     // If no driver kind is specified, assume all are to be probed.
    2871       26774 :     if ((nIdentifyFlags & GDAL_OF_KIND_MASK) == 0)
    2872       26731 :         nIdentifyFlags |= GDAL_OF_KIND_MASK & ~GDAL_OF_MULTIDIM_RASTER;
    2873             : 
    2874       53548 :     GDALOpenInfo oOpenInfo(pszFilename, nIdentifyFlags, papszFileList);
    2875       26774 :     oOpenInfo.papszAllowedDrivers = papszAllowedDrivers;
    2876             : 
    2877       53548 :     CPLErrorStateBackuper oBackuper;
    2878       26774 :     CPLErrorSetState(CE_None, CPLE_AppDefined, "");
    2879             : 
    2880       26774 :     const int nDriverCount = poDM->GetDriverCount();
    2881             : 
    2882             :     // First pass: only use drivers that have a pfnIdentify implementation.
    2883       53548 :     std::vector<GDALDriver *> apoSecondPassDrivers;
    2884     5978270 :     for (int iDriver = 0; iDriver < nDriverCount; ++iDriver)
    2885             :     {
    2886     5952790 :         GDALDriver *poDriver = poDM->GetDriver(iDriver);
    2887     5960300 :         if (papszAllowedDrivers != nullptr &&
    2888        7510 :             CSLFindString(papszAllowedDrivers,
    2889             :                           GDALGetDriverShortName(poDriver)) == -1)
    2890             :         {
    2891     1146270 :             continue;
    2892             :         }
    2893             : 
    2894     5946610 :         VALIDATE_POINTER1(poDriver, "GDALIdentifyDriver", nullptr);
    2895             : 
    2896     5945320 :         if (poDriver->pfnIdentify == nullptr &&
    2897     1134890 :             poDriver->pfnIdentifyEx == nullptr)
    2898             :         {
    2899     1134890 :             continue;
    2900             :         }
    2901             : 
    2902     4810480 :         if (papszAllowedDrivers != nullptr &&
    2903          44 :             CSLFindString(papszAllowedDrivers,
    2904             :                           GDALGetDriverShortName(poDriver)) == -1)
    2905           0 :             continue;
    2906    14426400 :         if ((nIdentifyFlags & GDAL_OF_RASTER) != 0 &&
    2907     4810950 :             (nIdentifyFlags & GDAL_OF_VECTOR) == 0 &&
    2908         517 :             poDriver->GetMetadataItem(GDAL_DCAP_RASTER) == nullptr)
    2909         145 :             continue;
    2910    14434300 :         if ((nIdentifyFlags & GDAL_OF_VECTOR) != 0 &&
    2911     4815290 :             (nIdentifyFlags & GDAL_OF_RASTER) == 0 &&
    2912        5005 :             poDriver->GetMetadataItem(GDAL_DCAP_VECTOR) == nullptr)
    2913        3765 :             continue;
    2914             : 
    2915     4806520 :         if (poDriver->pfnIdentifyEx)
    2916             :         {
    2917           0 :             if (poDriver->pfnIdentifyEx(poDriver, &oOpenInfo) > 0)
    2918           0 :                 return poDriver;
    2919             :         }
    2920             :         else
    2921             :         {
    2922     4806520 :             const int nIdentifyRes = poDriver->pfnIdentify(&oOpenInfo);
    2923     4806520 :             if (nIdentifyRes > 0)
    2924        1291 :                 return poDriver;
    2925     4831860 :             if (nIdentifyRes < 0 &&
    2926       26633 :                 poDriver->GetMetadataItem("IS_NON_LOADED_PLUGIN"))
    2927             :             {
    2928             :                 // Not loaded plugin
    2929          34 :                 apoSecondPassDrivers.push_back(poDriver);
    2930             :             }
    2931             :         }
    2932             :     }
    2933             : 
    2934             :     // second pass: try loading plugin drivers
    2935       25514 :     for (auto poDriver : apoSecondPassDrivers)
    2936             :     {
    2937             :         // Force plugin driver loading
    2938          32 :         poDriver->GetMetadata();
    2939          32 :         if (poDriver->pfnIdentify(&oOpenInfo) > 0)
    2940           1 :             return poDriver;
    2941             :     }
    2942             : 
    2943             :     // third pass: slow method.
    2944     5845990 :     for (int iDriver = 0; iDriver < nDriverCount; ++iDriver)
    2945             :     {
    2946     5820740 :         GDALDriver *poDriver = poDM->GetDriver(iDriver);
    2947     5824640 :         if (papszAllowedDrivers != nullptr &&
    2948        3909 :             CSLFindString(papszAllowedDrivers,
    2949             :                           GDALGetDriverShortName(poDriver)) == -1)
    2950             :         {
    2951        3892 :             continue;
    2952             :         }
    2953             : 
    2954     5816840 :         VALIDATE_POINTER1(poDriver, "GDALIdentifyDriver", nullptr);
    2955             : 
    2956    17449100 :         if ((nIdentifyFlags & GDAL_OF_RASTER) != 0 &&
    2957     5817300 :             (nIdentifyFlags & GDAL_OF_VECTOR) == 0 &&
    2958         458 :             poDriver->GetMetadataItem(GDAL_DCAP_RASTER) == nullptr)
    2959         143 :             continue;
    2960    17450800 :         if ((nIdentifyFlags & GDAL_OF_VECTOR) != 0 &&
    2961     5818300 :             (nIdentifyFlags & GDAL_OF_RASTER) == 0 &&
    2962        1605 :             poDriver->GetMetadataItem(GDAL_DCAP_VECTOR) == nullptr)
    2963         967 :             continue;
    2964             : 
    2965     5815730 :         if (poDriver->pfnIdentifyEx != nullptr)
    2966             :         {
    2967           0 :             if (poDriver->pfnIdentifyEx(poDriver, &oOpenInfo) == 0)
    2968           0 :                 continue;
    2969             :         }
    2970     5815730 :         else if (poDriver->pfnIdentify != nullptr)
    2971             :         {
    2972     4704810 :             if (poDriver->pfnIdentify(&oOpenInfo) == 0)
    2973     4678750 :                 continue;
    2974             :         }
    2975             : 
    2976             :         GDALDataset *poDS;
    2977     1136980 :         if (poDriver->pfnOpen != nullptr)
    2978             :         {
    2979     1086270 :             poDS = poDriver->pfnOpen(&oOpenInfo);
    2980     1086270 :             if (poDS != nullptr)
    2981             :             {
    2982          87 :                 delete poDS;
    2983          87 :                 return GDALDriver::ToHandle(poDriver);
    2984             :             }
    2985             : 
    2986     1086180 :             if (CPLGetLastErrorType() != CE_None)
    2987         136 :                 return nullptr;
    2988             :         }
    2989       50711 :         else if (poDriver->pfnOpenWithDriverArg != nullptr)
    2990             :         {
    2991           0 :             poDS = poDriver->pfnOpenWithDriverArg(poDriver, &oOpenInfo);
    2992           0 :             if (poDS != nullptr)
    2993             :             {
    2994           0 :                 delete poDS;
    2995           0 :                 return GDALDriver::ToHandle(poDriver);
    2996             :             }
    2997             : 
    2998           0 :             if (CPLGetLastErrorType() != CE_None)
    2999           0 :                 return nullptr;
    3000             :         }
    3001             :     }
    3002             : 
    3003       25259 :     return nullptr;
    3004             : }
    3005             : 
    3006             : /************************************************************************/
    3007             : /*                          GetMetadataItem()                           */
    3008             : /************************************************************************/
    3009             : 
    3010    13556900 : const char *GDALDriver::GetMetadataItem(const char *pszName,
    3011             :                                         const char *pszDomain)
    3012             : {
    3013    13556900 :     if (pszDomain == nullptr || pszDomain[0] == '\0')
    3014             :     {
    3015    13556700 :         if (EQUAL(pszName, GDAL_DMD_OVERVIEW_CREATIONOPTIONLIST))
    3016             :         {
    3017        2291 :             const char *pszVal = GDALMajorObject::GetMetadataItem(pszName, "");
    3018        2291 :             if (pszVal)
    3019        2064 :                 return pszVal;
    3020         227 :             if (GetMetadataItem(GDAL_DCAP_RASTER))
    3021             :             {
    3022         155 :                 auto poDM = GetGDALDriverManager();
    3023         155 :                 auto poGTiffDrv = poDM->GetDriverByName("GTiff");
    3024         155 :                 if (poGTiffDrv)
    3025             :                 {
    3026             :                     const char *pszXML =
    3027         155 :                         poGTiffDrv->GetMetadataItem(pszName, "");
    3028         155 :                     if (pszXML)
    3029             :                     {
    3030         310 :                         CPLString osXML(pszXML);
    3031         155 :                         osXML.replaceAll("<Value>INTERNAL</Value>", "");
    3032         155 :                         return CPLSPrintf("%s", osXML.c_str());
    3033             :                     }
    3034             :                 }
    3035             :             }
    3036             :         }
    3037             :     }
    3038    13554700 :     return GDALMajorObject::GetMetadataItem(pszName, pszDomain);
    3039             : }
    3040             : 
    3041             : /************************************************************************/
    3042             : /*                          SetMetadataItem()                           */
    3043             : /************************************************************************/
    3044             : 
    3045     4803360 : CPLErr GDALDriver::SetMetadataItem(const char *pszName, const char *pszValue,
    3046             :                                    const char *pszDomain)
    3047             : 
    3048             : {
    3049     4803360 :     if (pszDomain == nullptr || pszDomain[0] == '\0')
    3050             :     {
    3051             :         /* Automatically sets GDAL_DMD_EXTENSIONS from GDAL_DMD_EXTENSION */
    3052     5007580 :         if (EQUAL(pszName, GDAL_DMD_EXTENSION) &&
    3053      209845 :             GDALMajorObject::GetMetadataItem(GDAL_DMD_EXTENSIONS) == nullptr)
    3054             :         {
    3055      209845 :             GDALMajorObject::SetMetadataItem(GDAL_DMD_EXTENSIONS, pszValue);
    3056             :         }
    3057             :         /* and vice-versa if there is a single extension in GDAL_DMD_EXTENSIONS */
    3058     9259970 :         else if (EQUAL(pszName, GDAL_DMD_EXTENSIONS) &&
    3059     4597250 :                  strchr(pszValue, ' ') == nullptr &&
    3060        9357 :                  GDALMajorObject::GetMetadataItem(GDAL_DMD_EXTENSION) ==
    3061             :                      nullptr)
    3062             :         {
    3063        9357 :             GDALMajorObject::SetMetadataItem(GDAL_DMD_EXTENSION, pszValue);
    3064             :         }
    3065             :     }
    3066     4803360 :     return GDALMajorObject::SetMetadataItem(pszName, pszValue, pszDomain);
    3067             : }
    3068             : 
    3069             : /************************************************************************/
    3070             : /*                        InstantiateAlgorithm()                        */
    3071             : /************************************************************************/
    3072             : 
    3073             : //! @cond Doxygen_Suppress
    3074             : 
    3075             : GDALAlgorithm *
    3076        1261 : GDALDriver::InstantiateAlgorithm(const std::vector<std::string> &aosPath)
    3077             : {
    3078        1261 :     pfnInstantiateAlgorithm = GetInstantiateAlgorithmCallback();
    3079        1261 :     if (pfnInstantiateAlgorithm)
    3080        1261 :         return pfnInstantiateAlgorithm(aosPath);
    3081           0 :     return nullptr;
    3082             : }
    3083             : 
    3084             : /************************************************************************/
    3085             : /*                          DeclareAlgorithm()                          */
    3086             : /************************************************************************/
    3087             : 
    3088       16945 : void GDALDriver::DeclareAlgorithm(const std::vector<std::string> &aosPath)
    3089             : {
    3090       33890 :     const std::string osDriverName = GetDescription();
    3091       16945 :     auto &singleton = GDALGlobalAlgorithmRegistry::GetSingleton();
    3092             : 
    3093       33890 :     if (!singleton.HasDeclaredSubAlgorithm({"driver"}))
    3094             :     {
    3095        3338 :         singleton.DeclareAlgorithm(
    3096             :             {"driver"},
    3097         155 :             []() -> std::unique_ptr<GDALAlgorithm>
    3098             :             {
    3099         310 :                 return std::make_unique<GDALContainerAlgorithm>(
    3100         155 :                     "driver", "Command for driver specific operations.");
    3101        1669 :             });
    3102             :     }
    3103             : 
    3104             :     std::vector<std::string> path = {"driver",
    3105      101670 :                                      CPLString(osDriverName).tolower()};
    3106       16945 :     if (!singleton.HasDeclaredSubAlgorithm(path))
    3107             :     {
    3108        1519 :         auto lambda = [osDriverName]() -> std::unique_ptr<GDALAlgorithm>
    3109             :         {
    3110             :             auto poDriver =
    3111        1519 :                 GetGDALDriverManager()->GetDriverByName(osDriverName.c_str());
    3112        1519 :             if (poDriver)
    3113             :             {
    3114             :                 const char *pszHelpTopic =
    3115        1519 :                     poDriver->GetMetadataItem(GDAL_DMD_HELPTOPIC);
    3116        3038 :                 return std::make_unique<GDALContainerAlgorithm>(
    3117        3038 :                     CPLString(osDriverName).tolower(),
    3118        3038 :                     std::string("Command for ")
    3119        1519 :                         .append(osDriverName)
    3120             :                         .append(" driver specific operations."),
    3121        3038 :                     pszHelpTopic ? std::string("/").append(pszHelpTopic)
    3122        1519 :                                  : std::string());
    3123             :             }
    3124           0 :             return nullptr;
    3125       13352 :         };
    3126       13352 :         singleton.DeclareAlgorithm(path, std::move(lambda));
    3127             :     }
    3128             : 
    3129       16945 :     path.insert(path.end(), aosPath.begin(), aosPath.end());
    3130             : 
    3131        1261 :     auto lambda = [osDriverName, aosPath]() -> std::unique_ptr<GDALAlgorithm>
    3132             :     {
    3133             :         auto poDriver =
    3134        1261 :             GetGDALDriverManager()->GetDriverByName(osDriverName.c_str());
    3135        1261 :         if (poDriver)
    3136             :             return std::unique_ptr<GDALAlgorithm>(
    3137        1261 :                 poDriver->InstantiateAlgorithm(aosPath));
    3138           0 :         return nullptr;
    3139       33890 :     };
    3140             : 
    3141       16945 :     singleton.DeclareAlgorithm(path, std::move(lambda));
    3142             : 
    3143       16945 :     CPL_IGNORE_RET_VAL(osDriverName);
    3144       16945 : }
    3145             : 
    3146             : //! @endcond
    3147             : 
    3148             : /************************************************************************/
    3149             : /*                     DoesDriverHandleExtension()                      */
    3150             : /************************************************************************/
    3151             : 
    3152      202935 : static bool DoesDriverHandleExtension(GDALDriverH hDriver, const char *pszExt)
    3153             : {
    3154      202935 :     bool bRet = false;
    3155             :     const char *pszDriverExtensions =
    3156      202935 :         GDALGetMetadataItem(hDriver, GDAL_DMD_EXTENSIONS, nullptr);
    3157      202935 :     if (pszDriverExtensions)
    3158             :     {
    3159      339818 :         const CPLStringList aosTokens(CSLTokenizeString(pszDriverExtensions));
    3160      169909 :         const int nTokens = aosTokens.size();
    3161      381683 :         for (int j = 0; j < nTokens; ++j)
    3162             :         {
    3163      216551 :             if (EQUAL(pszExt, aosTokens[j]))
    3164             :             {
    3165        4777 :                 bRet = true;
    3166        4777 :                 break;
    3167             :             }
    3168             :         }
    3169             :     }
    3170      202935 :     return bRet;
    3171             : }
    3172             : 
    3173             : /************************************************************************/
    3174             : /*                      IsOnlyExpectedGDBDrivers()                      */
    3175             : /************************************************************************/
    3176             : 
    3177           1 : static bool IsOnlyExpectedGDBDrivers(const CPLStringList &aosDriverNames)
    3178             : {
    3179           3 :     for (const char *pszDrvName : aosDriverNames)
    3180             :     {
    3181           2 :         if (!EQUAL(pszDrvName, "OpenFileGDB") &&
    3182           1 :             !EQUAL(pszDrvName, "FileGDB") && !EQUAL(pszDrvName, "GPSBabel"))
    3183             :         {
    3184           0 :             return false;
    3185             :         }
    3186             :     }
    3187           1 :     return true;
    3188             : }
    3189             : 
    3190             : /************************************************************************/
    3191             : /*                 GDALGetOutputDriversForDatasetName()                 */
    3192             : /************************************************************************/
    3193             : 
    3194             : /** Return a list of driver short names that are likely candidates for the
    3195             :  * provided output file name.
    3196             :  *
    3197             :  * @param pszDestDataset Output dataset name (might not exist).
    3198             :  * @param nDatasetTypeFlag GDAL_OF_RASTER, GDAL_OF_VECTOR, GDAL_OF_MULTIDIM_RASTER
    3199             :  *                         or a binary-or'ed combination of them
    3200             :  * @param bSingleMatch Whether a single match is desired, that is to say the
    3201             :  *                     returned list will contain at most one item, which will
    3202             :  *                     be the first driver in the order they are registered to
    3203             :  *                     match the output dataset name. Note that in this mode, if
    3204             :  *                     nDatasetTypeFlag==GDAL_OF_RASTER and pszDestDataset has
    3205             :  *                     no extension, GTiff will be selected.
    3206             :  * @param bEmitWarning Whether a warning should be emitted when bSingleMatch is
    3207             :  *                     true and there are more than 2 candidates.
    3208             :  * @return NULL terminated list of driver short names.
    3209             :  * To be freed with CSLDestroy()
    3210             :  * @since 3.9
    3211             :  */
    3212        2837 : char **GDALGetOutputDriversForDatasetName(const char *pszDestDataset,
    3213             :                                           int nDatasetTypeFlag,
    3214             :                                           bool bSingleMatch, bool bEmitWarning)
    3215             : {
    3216        5674 :     CPLStringList aosDriverNames;
    3217        5674 :     CPLStringList aosMissingDriverNames;
    3218             : 
    3219        5674 :     std::string osExt = CPLGetExtensionSafe(pszDestDataset);
    3220        2837 :     if (EQUAL(osExt.c_str(), "zip"))
    3221             :     {
    3222           2 :         const CPLString osLower(CPLString(pszDestDataset).tolower());
    3223           1 :         if (osLower.endsWith(".shp.zip"))
    3224             :         {
    3225           1 :             osExt = "shp.zip";
    3226             :         }
    3227           0 :         else if (osLower.endsWith(".gpkg.zip"))
    3228             :         {
    3229           0 :             osExt = "gpkg.zip";
    3230             :         }
    3231             :     }
    3232        2836 :     else if (EQUAL(osExt.c_str(), "json"))
    3233             :     {
    3234           1 :         const CPLString osLower(CPLString(pszDestDataset).tolower());
    3235           1 :         if (osLower.endsWith(".gdalg.json"))
    3236           0 :             return nullptr;
    3237             :     }
    3238             : 
    3239        2837 :     auto poDM = GetGDALDriverManager();
    3240        2837 :     const int nDriverCount = poDM->GetDriverCount(true);
    3241        2837 :     GDALDriver *poMissingPluginDriver = nullptr;
    3242        5674 :     std::string osMatchingPrefix;
    3243      654939 :     for (int i = 0; i < nDriverCount; i++)
    3244             :     {
    3245      652102 :         GDALDriver *poDriver = poDM->GetDriver(i, true);
    3246      652102 :         bool bOk = false;
    3247      652102 :         if ((poDriver->GetMetadataItem(GDAL_DCAP_CREATE) != nullptr ||
    3248      402449 :              poDriver->GetMetadataItem(GDAL_DCAP_CREATECOPY) != nullptr ||
    3249     1304200 :              poDriver->GetMetadataItem(GDAL_DCAP_UPDATE) != nullptr) &&
    3250      334763 :             (((nDatasetTypeFlag & GDAL_OF_RASTER) &&
    3251      262431 :               poDriver->GetMetadataItem(GDAL_DCAP_RASTER) != nullptr) ||
    3252      163516 :              ((nDatasetTypeFlag & GDAL_OF_VECTOR) &&
    3253       71742 :               poDriver->GetMetadataItem(GDAL_DCAP_VECTOR) != nullptr) ||
    3254      129470 :              ((nDatasetTypeFlag & GDAL_OF_MULTIDIM_RASTER) &&
    3255         590 :               poDriver->GetMetadataItem(GDAL_DCAP_MULTIDIM_RASTER) != nullptr)))
    3256             :         {
    3257      205343 :             bOk = true;
    3258             :         }
    3259      448993 :         else if (poDriver->GetMetadataItem(GDAL_DCAP_VECTOR_TRANSLATE_FROM) &&
    3260        2234 :                  (nDatasetTypeFlag & GDAL_OF_VECTOR) != 0)
    3261             :         {
    3262           0 :             bOk = true;
    3263             :         }
    3264      652102 :         if (bOk)
    3265             :         {
    3266      408278 :             if (!osExt.empty() &&
    3267      202935 :                 DoesDriverHandleExtension(GDALDriver::ToHandle(poDriver),
    3268             :                                           osExt.c_str()))
    3269             :             {
    3270        4777 :                 if (poDriver->GetMetadataItem("MISSING_PLUGIN_FILENAME"))
    3271             :                 {
    3272           0 :                     poMissingPluginDriver = poDriver;
    3273           0 :                     aosMissingDriverNames.AddString(poDriver->GetDescription());
    3274             :                 }
    3275             :                 else
    3276        4777 :                     aosDriverNames.AddString(poDriver->GetDescription());
    3277             :             }
    3278             :             else
    3279             :             {
    3280             :                 const char *pszPrefix =
    3281      200566 :                     poDriver->GetMetadataItem(GDAL_DMD_CONNECTION_PREFIX);
    3282      200566 :                 if (pszPrefix && STARTS_WITH_CI(pszDestDataset, pszPrefix))
    3283             :                 {
    3284           9 :                     if (poDriver->GetMetadataItem("MISSING_PLUGIN_FILENAME"))
    3285             :                     {
    3286           0 :                         osMatchingPrefix = pszPrefix;
    3287           0 :                         poMissingPluginDriver = poDriver;
    3288             :                         aosMissingDriverNames.AddString(
    3289           0 :                             poDriver->GetDescription());
    3290             :                     }
    3291             :                     else
    3292           9 :                         aosDriverNames.AddString(poDriver->GetDescription());
    3293             :                 }
    3294             :             }
    3295             :         }
    3296             :     }
    3297             : 
    3298             :     // GMT is registered before netCDF for opening reasons, but we want
    3299             :     // netCDF to be used by default for output.
    3300        2844 :     if (EQUAL(osExt.c_str(), "nc") && aosDriverNames.size() == 2 &&
    3301        2844 :         EQUAL(aosDriverNames[0], "GMT") && EQUAL(aosDriverNames[1], "netCDF"))
    3302             :     {
    3303           0 :         aosDriverNames.Clear();
    3304           0 :         aosDriverNames.AddString("netCDF");
    3305           0 :         aosDriverNames.AddString("GMT");
    3306             :     }
    3307             : 
    3308        2837 :     if (bSingleMatch)
    3309             :     {
    3310        2765 :         if (nDatasetTypeFlag == GDAL_OF_RASTER)
    3311             :         {
    3312        2224 :             if (aosDriverNames.empty())
    3313             :             {
    3314          13 :                 if (osExt.empty())
    3315             :                 {
    3316           8 :                     aosDriverNames.AddString("GTiff");
    3317             :                 }
    3318             :             }
    3319        2211 :             else if (aosDriverNames.size() >= 2)
    3320             :             {
    3321        3975 :                 if (bEmitWarning && !(EQUAL(aosDriverNames[0], "GTiff") &&
    3322        1986 :                                       EQUAL(aosDriverNames[1], "COG")))
    3323             :                 {
    3324           3 :                     CPLError(CE_Warning, CPLE_AppDefined,
    3325             :                              "Several drivers matching %s extension. Using %s",
    3326             :                              osExt.c_str(), aosDriverNames[0]);
    3327             :                 }
    3328        3978 :                 const std::string osDrvName = aosDriverNames[0];
    3329        1989 :                 aosDriverNames.Clear();
    3330        1989 :                 aosDriverNames.AddString(osDrvName.c_str());
    3331             :             }
    3332             :         }
    3333         542 :         else if (EQUAL(osExt.c_str(), "gdb") &&
    3334           1 :                  IsOnlyExpectedGDBDrivers(aosDriverNames))
    3335             :         {
    3336             :             // Do not warn about that case given that FileGDB write support
    3337             :             // forwards to OpenFileGDB one. And also consider GPSBabel as too
    3338             :             // marginal to deserve the warning.
    3339           1 :             aosDriverNames.Clear();
    3340           1 :             aosDriverNames.AddString("OpenFileGDB");
    3341             :         }
    3342         540 :         else if (aosDriverNames.size() >= 2)
    3343             :         {
    3344           0 :             if (bEmitWarning)
    3345             :             {
    3346           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    3347             :                          "Several drivers matching %s %s. Using %s",
    3348           0 :                          osMatchingPrefix.empty() ? osExt.c_str()
    3349           0 :                                                   : osMatchingPrefix.c_str(),
    3350           0 :                          osMatchingPrefix.empty() ? "extension" : "prefix",
    3351             :                          aosDriverNames[0]);
    3352             :             }
    3353           0 :             const std::string osDrvName = aosDriverNames[0];
    3354           0 :             aosDriverNames.Clear();
    3355           0 :             aosDriverNames.AddString(osDrvName.c_str());
    3356             :         }
    3357             :     }
    3358             : 
    3359        2871 :     if (aosDriverNames.empty() && bEmitWarning &&
    3360        2871 :         aosMissingDriverNames.size() == 1 && poMissingPluginDriver)
    3361             :     {
    3362           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    3363             :                  "No installed driver matching %s %s, but %s driver is "
    3364             :                  "known. However plugin %s",
    3365           0 :                  osMatchingPrefix.empty() ? osExt.c_str()
    3366           0 :                                           : osMatchingPrefix.c_str(),
    3367           0 :                  osMatchingPrefix.empty() ? "extension" : "prefix",
    3368           0 :                  poMissingPluginDriver->GetDescription(),
    3369           0 :                  GDALGetMessageAboutMissingPluginDriver(poMissingPluginDriver)
    3370             :                      .c_str());
    3371             :     }
    3372        2870 :     else if (aosDriverNames.empty() && bEmitWarning &&
    3373          33 :              aosMissingDriverNames.empty())
    3374             :     {
    3375         911 :         for (const auto &sConnectionPrefix : asKnownConnectionPrefixes)
    3376             :         {
    3377         879 :             if (STARTS_WITH_CI(pszDestDataset, sConnectionPrefix.pszPrefix))
    3378             :             {
    3379           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
    3380             :                          "Filename %s starts with the connection prefix of "
    3381             :                          "driver %s, which is not enabled in this GDAL build. "
    3382             :                          "If that filename is really intended, explicitly "
    3383             :                          "specify its output format.",
    3384           1 :                          pszDestDataset, sConnectionPrefix.pszDriverName);
    3385           1 :                 break;
    3386             :             }
    3387             :         }
    3388             :     }
    3389             : 
    3390        2837 :     return aosDriverNames.StealList();
    3391             : }
    3392             : 
    3393             : /************************************************************************/
    3394             : /*               GDALGetMessageAboutMissingPluginDriver()               */
    3395             : /************************************************************************/
    3396             : 
    3397             : std::string
    3398           0 : GDALGetMessageAboutMissingPluginDriver(GDALDriver *poMissingPluginDriver)
    3399             : {
    3400             :     std::string osMsg =
    3401           0 :         poMissingPluginDriver->GetMetadataItem("MISSING_PLUGIN_FILENAME");
    3402             :     osMsg += " is not available in your "
    3403           0 :              "installation.";
    3404           0 :     if (const char *pszInstallationMsg = poMissingPluginDriver->GetMetadataItem(
    3405           0 :             GDAL_DMD_PLUGIN_INSTALLATION_MESSAGE))
    3406             :     {
    3407           0 :         osMsg += " ";
    3408           0 :         osMsg += pszInstallationMsg;
    3409             :     }
    3410             : 
    3411             :     VSIStatBuf sStat;
    3412           0 :     if (const char *pszGDALDriverPath =
    3413           0 :             CPLGetConfigOption("GDAL_DRIVER_PATH", nullptr))
    3414             :     {
    3415           0 :         if (VSIStat(pszGDALDriverPath, &sStat) != 0)
    3416             :         {
    3417           0 :             if (osMsg.back() != '.')
    3418           0 :                 osMsg += ".";
    3419           0 :             osMsg += " Directory '";
    3420           0 :             osMsg += pszGDALDriverPath;
    3421           0 :             osMsg += "' pointed by GDAL_DRIVER_PATH does not exist.";
    3422             :         }
    3423             :     }
    3424             :     else
    3425             :     {
    3426           0 :         if (osMsg.back() != '.')
    3427           0 :             osMsg += ".";
    3428             : #ifdef INSTALL_PLUGIN_FULL_DIR
    3429             :         if (VSIStat(INSTALL_PLUGIN_FULL_DIR, &sStat) != 0)
    3430             :         {
    3431             :             osMsg += " Directory '";
    3432             :             osMsg += INSTALL_PLUGIN_FULL_DIR;
    3433             :             osMsg += "' hardcoded in the GDAL library does not "
    3434             :                      "exist and the GDAL_DRIVER_PATH "
    3435             :                      "configuration option is not set.";
    3436             :         }
    3437             :         else
    3438             : #endif
    3439             :         {
    3440             :             osMsg += " The GDAL_DRIVER_PATH configuration "
    3441           0 :                      "option is not set.";
    3442             :         }
    3443             :     }
    3444           0 :     return osMsg;
    3445             : }
    3446             : 
    3447             : /************************************************************************/
    3448             : /*                       GDALClearMemoryCaches()                        */
    3449             : /************************************************************************/
    3450             : 
    3451             : /**
    3452             :  * \brief Clear all GDAL-controlled in-memory caches.
    3453             :  *
    3454             :  * Iterates registered drivers and calls their pfnClearCaches callback if set,
    3455             :  * then calls VSICurlClearCache() to clear /vsicurl/ and related caches.
    3456             :  *
    3457             :  * Note that neither the global raster block cache or caches specific to open
    3458             :  * dataset objects are not cleared by this function (in its current implementation).
    3459             :  *
    3460             :  * Useful when remote datasets may have changed during the lifetime of a
    3461             :  * process.
    3462             :  *
    3463             :  * @since GDAL 3.13
    3464             :  */
    3465           4 : void GDALClearMemoryCaches()
    3466             : {
    3467           4 :     auto *poDM = GetGDALDriverManager();
    3468           4 :     if (poDM)
    3469             :     {
    3470         924 :         for (int i = 0; i < poDM->GetDriverCount(); i++)
    3471             :         {
    3472         920 :             auto *poDriver = poDM->GetDriver(i);
    3473         920 :             if (poDriver && poDriver->pfnClearCaches)
    3474           4 :                 poDriver->pfnClearCaches(poDriver);
    3475             :         }
    3476             :     }
    3477           4 :     VSICurlClearCache();
    3478           4 : }

Generated by: LCOV version 1.14