LCOV - code coverage report
Current view: top level - port - cpl_conv.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 740 956 77.4 %
Date: 2025-01-18 12:42:00 Functions: 69 79 87.3 %

          Line data    Source code
       1             : /******************************************************************************
       2             :  *
       3             :  * Project:  CPL - Common Portability Library
       4             :  * Purpose:  Convenience functions.
       5             :  * Author:   Frank Warmerdam, warmerdam@pobox.com
       6             :  *
       7             :  ******************************************************************************
       8             :  * Copyright (c) 1998, 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_config.h"
      15             : 
      16             : #ifdef HAVE_USELOCALE
      17             : // For uselocale, define _XOPEN_SOURCE = 700
      18             : // but on Solaris, we don't have uselocale and we cannot have
      19             : // std=c++11 with _XOPEN_SOURCE != 600
      20             : #if defined(__sun__) && __cplusplus >= 201103L
      21             : #if _XOPEN_SOURCE != 600
      22             : #ifdef _XOPEN_SOURCE
      23             : #undef _XOPEN_SOURCE
      24             : #endif
      25             : #define _XOPEN_SOURCE 600
      26             : #endif
      27             : #else
      28             : #ifdef _XOPEN_SOURCE
      29             : #undef _XOPEN_SOURCE
      30             : #endif
      31             : #define _XOPEN_SOURCE 700
      32             : #endif
      33             : #endif
      34             : 
      35             : // For atoll (at least for NetBSD)
      36             : #ifndef _ISOC99_SOURCE
      37             : #define _ISOC99_SOURCE
      38             : #endif
      39             : 
      40             : #ifdef MSVC_USE_VLD
      41             : #include <vld.h>
      42             : #endif
      43             : 
      44             : #include "cpl_conv.h"
      45             : 
      46             : #include <algorithm>
      47             : #include <cctype>
      48             : #include <cerrno>
      49             : #include <climits>
      50             : #include <clocale>
      51             : #include <cmath>
      52             : #include <cstdlib>
      53             : #include <cstring>
      54             : #include <ctime>
      55             : #if HAVE_FCNTL_H
      56             : #include <fcntl.h>
      57             : #endif
      58             : #include <mutex>
      59             : #include <set>
      60             : 
      61             : #if HAVE_UNISTD_H
      62             : #include <unistd.h>
      63             : #endif
      64             : #if HAVE_XLOCALE_H
      65             : #include <xlocale.h>  // for LC_NUMERIC_MASK on MacOS
      66             : #endif
      67             : 
      68             : #ifdef _WIN32
      69             : #include <io.h>  // _isatty
      70             : #else
      71             : #include <unistd.h>  // isatty
      72             : #endif
      73             : 
      74             : #include <string>
      75             : 
      76             : #if __cplusplus >= 202002L
      77             : #include <bit>  // For std::endian
      78             : #endif
      79             : 
      80             : #include "cpl_config.h"
      81             : #include "cpl_multiproc.h"
      82             : #include "cpl_string.h"
      83             : #include "cpl_vsi.h"
      84             : #include "cpl_vsil_curl_priv.h"
      85             : #include "cpl_known_config_options.h"
      86             : 
      87             : #ifdef DEBUG
      88             : #define OGRAPISPY_ENABLED
      89             : #endif
      90             : #ifdef OGRAPISPY_ENABLED
      91             : // Keep in sync with ograpispy.cpp
      92             : void OGRAPISPYCPLSetConfigOption(const char *, const char *);
      93             : void OGRAPISPYCPLSetThreadLocalConfigOption(const char *, const char *);
      94             : #endif
      95             : 
      96             : // Uncomment to get list of options that have been fetched and set.
      97             : // #define DEBUG_CONFIG_OPTIONS
      98             : 
      99             : static CPLMutex *hConfigMutex = nullptr;
     100             : static volatile char **g_papszConfigOptions = nullptr;
     101             : static bool gbIgnoreEnvVariables =
     102             :     false;  // if true, only take into account configuration options set through
     103             :             // configuration file or
     104             :             // CPLSetConfigOption()/CPLSetThreadLocalConfigOption()
     105             : 
     106             : static std::vector<std::pair<CPLSetConfigOptionSubscriber, void *>>
     107             :     gSetConfigOptionSubscribers{};
     108             : 
     109             : // Used by CPLOpenShared() and friends.
     110             : static CPLMutex *hSharedFileMutex = nullptr;
     111             : static int nSharedFileCount = 0;
     112             : static CPLSharedFileInfo *pasSharedFileList = nullptr;
     113             : 
     114             : // Used by CPLsetlocale().
     115             : static CPLMutex *hSetLocaleMutex = nullptr;
     116             : 
     117             : // Note: ideally this should be added in CPLSharedFileInfo*
     118             : // but CPLSharedFileInfo is exposed in the API, hence that trick
     119             : // to hide this detail.
     120             : typedef struct
     121             : {
     122             :     GIntBig nPID;  // pid of opening thread.
     123             : } CPLSharedFileInfoExtra;
     124             : 
     125             : static volatile CPLSharedFileInfoExtra *pasSharedFileListExtra = nullptr;
     126             : 
     127             : /************************************************************************/
     128             : /*                             CPLCalloc()                              */
     129             : /************************************************************************/
     130             : 
     131             : /**
     132             :  * Safe version of calloc().
     133             :  *
     134             :  * This function is like the C library calloc(), but raises a CE_Fatal
     135             :  * error with CPLError() if it fails to allocate the desired memory.  It
     136             :  * should be used for small memory allocations that are unlikely to fail
     137             :  * and for which the application is unwilling to test for out of memory
     138             :  * conditions.  It uses VSICalloc() to get the memory, so any hooking of
     139             :  * VSICalloc() will apply to CPLCalloc() as well.  CPLFree() or VSIFree()
     140             :  * can be used free memory allocated by CPLCalloc().
     141             :  *
     142             :  * @param nCount number of objects to allocate.
     143             :  * @param nSize size (in bytes) of object to allocate.
     144             :  * @return pointer to newly allocated memory, only NULL if nSize * nCount is
     145             :  * NULL.
     146             :  */
     147             : 
     148     3223770 : void *CPLCalloc(size_t nCount, size_t nSize)
     149             : 
     150             : {
     151     3223770 :     if (nSize * nCount == 0)
     152        9138 :         return nullptr;
     153             : 
     154     3214630 :     void *pReturn = CPLMalloc(nCount * nSize);
     155     3214620 :     memset(pReturn, 0, nCount * nSize);
     156     3214620 :     return pReturn;
     157             : }
     158             : 
     159             : /************************************************************************/
     160             : /*                             CPLMalloc()                              */
     161             : /************************************************************************/
     162             : 
     163             : /**
     164             :  * Safe version of malloc().
     165             :  *
     166             :  * This function is like the C library malloc(), but raises a CE_Fatal
     167             :  * error with CPLError() if it fails to allocate the desired memory.  It
     168             :  * should be used for small memory allocations that are unlikely to fail
     169             :  * and for which the application is unwilling to test for out of memory
     170             :  * conditions.  It uses VSIMalloc() to get the memory, so any hooking of
     171             :  * VSIMalloc() will apply to CPLMalloc() as well.  CPLFree() or VSIFree()
     172             :  * can be used free memory allocated by CPLMalloc().
     173             :  *
     174             :  * @param nSize size (in bytes) of memory block to allocate.
     175             :  * @return pointer to newly allocated memory, only NULL if nSize is zero.
     176             :  */
     177             : 
     178    18974500 : void *CPLMalloc(size_t nSize)
     179             : 
     180             : {
     181    18974500 :     if (nSize == 0)
     182        5657 :         return nullptr;
     183             : 
     184    18968900 :     if ((nSize >> (8 * sizeof(nSize) - 1)) != 0)
     185             :     {
     186             :         // coverity[dead_error_begin]
     187           0 :         CPLError(CE_Failure, CPLE_AppDefined,
     188             :                  "CPLMalloc(%ld): Silly size requested.",
     189             :                  static_cast<long>(nSize));
     190           0 :         return nullptr;
     191             :     }
     192             : 
     193    18968900 :     void *pReturn = VSIMalloc(nSize);
     194    18969000 :     if (pReturn == nullptr)
     195             :     {
     196           0 :         if (nSize < 2000)
     197             :         {
     198           0 :             CPLEmergencyError("CPLMalloc(): Out of memory allocating a small "
     199             :                               "number of bytes.");
     200             :         }
     201             : 
     202           0 :         CPLError(CE_Fatal, CPLE_OutOfMemory,
     203             :                  "CPLMalloc(): Out of memory allocating %ld bytes.",
     204             :                  static_cast<long>(nSize));
     205             :     }
     206             : 
     207    18969000 :     return pReturn;
     208             : }
     209             : 
     210             : /************************************************************************/
     211             : /*                             CPLRealloc()                             */
     212             : /************************************************************************/
     213             : 
     214             : /**
     215             :  * Safe version of realloc().
     216             :  *
     217             :  * This function is like the C library realloc(), but raises a CE_Fatal
     218             :  * error with CPLError() if it fails to allocate the desired memory.  It
     219             :  * should be used for small memory allocations that are unlikely to fail
     220             :  * and for which the application is unwilling to test for out of memory
     221             :  * conditions.  It uses VSIRealloc() to get the memory, so any hooking of
     222             :  * VSIRealloc() will apply to CPLRealloc() as well.  CPLFree() or VSIFree()
     223             :  * can be used free memory allocated by CPLRealloc().
     224             :  *
     225             :  * It is also safe to pass NULL in as the existing memory block for
     226             :  * CPLRealloc(), in which case it uses VSIMalloc() to allocate a new block.
     227             :  *
     228             :  * @param pData existing memory block which should be copied to the new block.
     229             :  * @param nNewSize new size (in bytes) of memory block to allocate.
     230             :  * @return pointer to allocated memory, only NULL if nNewSize is zero.
     231             :  */
     232             : 
     233     1835160 : void *CPLRealloc(void *pData, size_t nNewSize)
     234             : 
     235             : {
     236     1835160 :     if (nNewSize == 0)
     237             :     {
     238          45 :         VSIFree(pData);
     239          45 :         return nullptr;
     240             :     }
     241             : 
     242     1835110 :     if ((nNewSize >> (8 * sizeof(nNewSize) - 1)) != 0)
     243             :     {
     244             :         // coverity[dead_error_begin]
     245           0 :         CPLError(CE_Failure, CPLE_AppDefined,
     246             :                  "CPLRealloc(%ld): Silly size requested.",
     247             :                  static_cast<long>(nNewSize));
     248           0 :         return nullptr;
     249             :     }
     250             : 
     251     1835110 :     void *pReturn = nullptr;
     252             : 
     253     1835110 :     if (pData == nullptr)
     254      857514 :         pReturn = VSIMalloc(nNewSize);
     255             :     else
     256      977600 :         pReturn = VSIRealloc(pData, nNewSize);
     257             : 
     258     1834850 :     if (pReturn == nullptr)
     259             :     {
     260           0 :         if (nNewSize < 2000)
     261             :         {
     262           0 :             char szSmallMsg[80] = {};
     263             : 
     264           0 :             snprintf(szSmallMsg, sizeof(szSmallMsg),
     265             :                      "CPLRealloc(): Out of memory allocating %ld bytes.",
     266             :                      static_cast<long>(nNewSize));
     267           0 :             CPLEmergencyError(szSmallMsg);
     268             :         }
     269             :         else
     270             :         {
     271           0 :             CPLError(CE_Fatal, CPLE_OutOfMemory,
     272             :                      "CPLRealloc(): Out of memory allocating %ld bytes.",
     273             :                      static_cast<long>(nNewSize));
     274             :         }
     275             :     }
     276             : 
     277     1835100 :     return pReturn;
     278             : }
     279             : 
     280             : /************************************************************************/
     281             : /*                             CPLStrdup()                              */
     282             : /************************************************************************/
     283             : 
     284             : /**
     285             :  * Safe version of strdup() function.
     286             :  *
     287             :  * This function is similar to the C library strdup() function, but if
     288             :  * the memory allocation fails it will issue a CE_Fatal error with
     289             :  * CPLError() instead of returning NULL. Memory
     290             :  * allocated with CPLStrdup() can be freed with CPLFree() or VSIFree().
     291             :  *
     292             :  * It is also safe to pass a NULL string into CPLStrdup().  CPLStrdup()
     293             :  * will allocate and return a zero length string (as opposed to a NULL
     294             :  * string).
     295             :  *
     296             :  * @param pszString input string to be duplicated.  May be NULL.
     297             :  * @return pointer to a newly allocated copy of the string.  Free with
     298             :  * CPLFree() or VSIFree().
     299             :  */
     300             : 
     301     7404810 : char *CPLStrdup(const char *pszString)
     302             : 
     303             : {
     304     7404810 :     if (pszString == nullptr)
     305      985639 :         pszString = "";
     306             : 
     307     7404810 :     const size_t nLen = strlen(pszString);
     308     7404810 :     char *pszReturn = static_cast<char *>(CPLMalloc(nLen + 1));
     309     7404780 :     memcpy(pszReturn, pszString, nLen + 1);
     310     7404780 :     return (pszReturn);
     311             : }
     312             : 
     313             : /************************************************************************/
     314             : /*                             CPLStrlwr()                              */
     315             : /************************************************************************/
     316             : 
     317             : /**
     318             :  * Convert each characters of the string to lower case.
     319             :  *
     320             :  * For example, "ABcdE" will be converted to "abcde".
     321             :  * Starting with GDAL 3.9, this function is no longer locale dependent.
     322             :  *
     323             :  * @param pszString input string to be converted.
     324             :  * @return pointer to the same string, pszString.
     325             :  */
     326             : 
     327          32 : char *CPLStrlwr(char *pszString)
     328             : 
     329             : {
     330          32 :     if (pszString == nullptr)
     331           0 :         return nullptr;
     332             : 
     333          32 :     char *pszTemp = pszString;
     334             : 
     335         140 :     while (*pszTemp)
     336             :     {
     337         108 :         *pszTemp =
     338         108 :             static_cast<char>(CPLTolower(static_cast<unsigned char>(*pszTemp)));
     339         108 :         pszTemp++;
     340             :     }
     341             : 
     342          32 :     return pszString;
     343             : }
     344             : 
     345             : /************************************************************************/
     346             : /*                              CPLFGets()                              */
     347             : /*                                                                      */
     348             : /*      Note: LF = \n = ASCII 10                                        */
     349             : /*            CR = \r = ASCII 13                                        */
     350             : /************************************************************************/
     351             : 
     352             : // ASCII characters.
     353             : constexpr char knLF = 10;
     354             : constexpr char knCR = 13;
     355             : 
     356             : /**
     357             :  * Reads in at most one less than nBufferSize characters from the fp
     358             :  * stream and stores them into the buffer pointed to by pszBuffer.
     359             :  * Reading stops after an EOF or a newline. If a newline is read, it
     360             :  * is _not_ stored into the buffer. A '\\0' is stored after the last
     361             :  * character in the buffer. All three types of newline terminators
     362             :  * recognized by the CPLFGets(): single '\\r' and '\\n' and '\\r\\n'
     363             :  * combination.
     364             :  *
     365             :  * @param pszBuffer pointer to the targeting character buffer.
     366             :  * @param nBufferSize maximum size of the string to read (not including
     367             :  * terminating '\\0').
     368             :  * @param fp file pointer to read from.
     369             :  * @return pointer to the pszBuffer containing a string read
     370             :  * from the file or NULL if the error or end of file was encountered.
     371             :  */
     372             : 
     373           0 : char *CPLFGets(char *pszBuffer, int nBufferSize, FILE *fp)
     374             : 
     375             : {
     376           0 :     if (nBufferSize == 0 || pszBuffer == nullptr || fp == nullptr)
     377           0 :         return nullptr;
     378             : 
     379             :     /* -------------------------------------------------------------------- */
     380             :     /*      Let the OS level call read what it things is one line.  This    */
     381             :     /*      will include the newline.  On windows, if the file happens      */
     382             :     /*      to be in text mode, the CRLF will have been converted to        */
     383             :     /*      just the newline (LF).  If it is in binary mode it may well     */
     384             :     /*      have both.                                                      */
     385             :     /* -------------------------------------------------------------------- */
     386           0 :     const long nOriginalOffset = VSIFTell(fp);
     387           0 :     if (VSIFGets(pszBuffer, nBufferSize, fp) == nullptr)
     388           0 :         return nullptr;
     389             : 
     390           0 :     int nActuallyRead = static_cast<int>(strlen(pszBuffer));
     391           0 :     if (nActuallyRead == 0)
     392           0 :         return nullptr;
     393             : 
     394             :     /* -------------------------------------------------------------------- */
     395             :     /*      If we found \r and out buffer is full, it is possible there     */
     396             :     /*      is also a pending \n.  Check for it.                            */
     397             :     /* -------------------------------------------------------------------- */
     398           0 :     if (nBufferSize == nActuallyRead + 1 &&
     399           0 :         pszBuffer[nActuallyRead - 1] == knCR)
     400             :     {
     401           0 :         const int chCheck = fgetc(fp);
     402           0 :         if (chCheck != knLF)
     403             :         {
     404             :             // unget the character.
     405           0 :             if (VSIFSeek(fp, nOriginalOffset + nActuallyRead, SEEK_SET) == -1)
     406             :             {
     407           0 :                 CPLError(CE_Failure, CPLE_FileIO,
     408             :                          "Unable to unget a character");
     409             :             }
     410             :         }
     411             :     }
     412             : 
     413             :     /* -------------------------------------------------------------------- */
     414             :     /*      Trim off \n, \r or \r\n if it appears at the end.  We don't     */
     415             :     /*      need to do any "seeking" since we want the newline eaten.       */
     416             :     /* -------------------------------------------------------------------- */
     417           0 :     if (nActuallyRead > 1 && pszBuffer[nActuallyRead - 1] == knLF &&
     418           0 :         pszBuffer[nActuallyRead - 2] == knCR)
     419             :     {
     420           0 :         pszBuffer[nActuallyRead - 2] = '\0';
     421             :     }
     422           0 :     else if (pszBuffer[nActuallyRead - 1] == knLF ||
     423           0 :              pszBuffer[nActuallyRead - 1] == knCR)
     424             :     {
     425           0 :         pszBuffer[nActuallyRead - 1] = '\0';
     426             :     }
     427             : 
     428             :     /* -------------------------------------------------------------------- */
     429             :     /*      Search within the string for a \r (MacOS convention             */
     430             :     /*      apparently), and if we find it we need to trim the string,      */
     431             :     /*      and seek back.                                                  */
     432             :     /* -------------------------------------------------------------------- */
     433           0 :     char *pszExtraNewline = strchr(pszBuffer, knCR);
     434             : 
     435           0 :     if (pszExtraNewline != nullptr)
     436             :     {
     437           0 :         nActuallyRead = static_cast<int>(pszExtraNewline - pszBuffer + 1);
     438             : 
     439           0 :         *pszExtraNewline = '\0';
     440           0 :         if (VSIFSeek(fp, nOriginalOffset + nActuallyRead - 1, SEEK_SET) != 0)
     441           0 :             return nullptr;
     442             : 
     443             :         // This hackery is necessary to try and find our correct
     444             :         // spot on win32 systems with text mode line translation going
     445             :         // on.  Sometimes the fseek back overshoots, but it doesn't
     446             :         // "realize it" till a character has been read. Try to read till
     447             :         // we get to the right spot and get our CR.
     448           0 :         int chCheck = fgetc(fp);
     449           0 :         while ((chCheck != knCR && chCheck != EOF) ||
     450           0 :                VSIFTell(fp) < nOriginalOffset + nActuallyRead)
     451             :         {
     452             :             static bool bWarned = false;
     453             : 
     454           0 :             if (!bWarned)
     455             :             {
     456           0 :                 bWarned = true;
     457           0 :                 CPLDebug("CPL",
     458             :                          "CPLFGets() correcting for DOS text mode translation "
     459             :                          "seek problem.");
     460             :             }
     461           0 :             chCheck = fgetc(fp);
     462             :         }
     463             :     }
     464             : 
     465           0 :     return pszBuffer;
     466             : }
     467             : 
     468             : /************************************************************************/
     469             : /*                         CPLReadLineBuffer()                          */
     470             : /*                                                                      */
     471             : /*      Fetch readline buffer, and ensure it is the desired size,       */
     472             : /*      reallocating if needed.  Manages TLS (thread local storage)     */
     473             : /*      issues for the buffer.                                          */
     474             : /*      We use a special trick to track the actual size of the buffer   */
     475             : /*      The first 4 bytes are reserved to store it as a int, hence the  */
     476             : /*      -4 / +4 hacks with the size and pointer.                        */
     477             : /************************************************************************/
     478     2389390 : static char *CPLReadLineBuffer(int nRequiredSize)
     479             : 
     480             : {
     481             : 
     482             :     /* -------------------------------------------------------------------- */
     483             :     /*      A required size of -1 means the buffer should be freed.         */
     484             :     /* -------------------------------------------------------------------- */
     485     2389390 :     if (nRequiredSize == -1)
     486             :     {
     487        2336 :         int bMemoryError = FALSE;
     488        2336 :         void *pRet = CPLGetTLSEx(CTLS_RLBUFFERINFO, &bMemoryError);
     489        2336 :         if (pRet != nullptr)
     490             :         {
     491        2084 :             CPLFree(pRet);
     492        2084 :             CPLSetTLS(CTLS_RLBUFFERINFO, nullptr, FALSE);
     493             :         }
     494        2336 :         return nullptr;
     495             :     }
     496             : 
     497             :     /* -------------------------------------------------------------------- */
     498             :     /*      If the buffer doesn't exist yet, create it.                     */
     499             :     /* -------------------------------------------------------------------- */
     500     2387060 :     int bMemoryError = FALSE;
     501             :     GUInt32 *pnAlloc =
     502     2387060 :         static_cast<GUInt32 *>(CPLGetTLSEx(CTLS_RLBUFFERINFO, &bMemoryError));
     503     2387060 :     if (bMemoryError)
     504           0 :         return nullptr;
     505             : 
     506     2387060 :     if (pnAlloc == nullptr)
     507             :     {
     508        3337 :         pnAlloc = static_cast<GUInt32 *>(VSI_MALLOC_VERBOSE(200));
     509        3337 :         if (pnAlloc == nullptr)
     510           0 :             return nullptr;
     511        3337 :         *pnAlloc = 196;
     512        3337 :         CPLSetTLS(CTLS_RLBUFFERINFO, pnAlloc, TRUE);
     513             :     }
     514             : 
     515             :     /* -------------------------------------------------------------------- */
     516             :     /*      If it is too small, grow it bigger.                             */
     517             :     /* -------------------------------------------------------------------- */
     518     2387060 :     if (static_cast<int>(*pnAlloc) - 1 < nRequiredSize)
     519             :     {
     520         681 :         const int nNewSize = nRequiredSize + 4 + 500;
     521         681 :         if (nNewSize <= 0)
     522             :         {
     523           0 :             VSIFree(pnAlloc);
     524           0 :             CPLSetTLS(CTLS_RLBUFFERINFO, nullptr, FALSE);
     525           0 :             CPLError(CE_Failure, CPLE_OutOfMemory,
     526             :                      "CPLReadLineBuffer(): Trying to allocate more than "
     527             :                      "2 GB.");
     528           0 :             return nullptr;
     529             :         }
     530             : 
     531             :         GUInt32 *pnAllocNew =
     532         681 :             static_cast<GUInt32 *>(VSI_REALLOC_VERBOSE(pnAlloc, nNewSize));
     533         681 :         if (pnAllocNew == nullptr)
     534             :         {
     535           0 :             VSIFree(pnAlloc);
     536           0 :             CPLSetTLS(CTLS_RLBUFFERINFO, nullptr, FALSE);
     537           0 :             return nullptr;
     538             :         }
     539         681 :         pnAlloc = pnAllocNew;
     540             : 
     541         681 :         *pnAlloc = nNewSize - 4;
     542         681 :         CPLSetTLS(CTLS_RLBUFFERINFO, pnAlloc, TRUE);
     543             :     }
     544             : 
     545     2387060 :     return reinterpret_cast<char *>(pnAlloc + 1);
     546             : }
     547             : 
     548             : /************************************************************************/
     549             : /*                            CPLReadLine()                             */
     550             : /************************************************************************/
     551             : 
     552             : /**
     553             :  * Simplified line reading from text file.
     554             :  *
     555             :  * Read a line of text from the given file handle, taking care
     556             :  * to capture CR and/or LF and strip off ... equivalent of
     557             :  * DKReadLine().  Pointer to an internal buffer is returned.
     558             :  * The application shouldn't free it, or depend on its value
     559             :  * past the next call to CPLReadLine().
     560             :  *
     561             :  * Note that CPLReadLine() uses VSIFGets(), so any hooking of VSI file
     562             :  * services should apply to CPLReadLine() as well.
     563             :  *
     564             :  * CPLReadLine() maintains an internal buffer, which will appear as a
     565             :  * single block memory leak in some circumstances.  CPLReadLine() may
     566             :  * be called with a NULL FILE * at any time to free this working buffer.
     567             :  *
     568             :  * @param fp file pointer opened with VSIFOpen().
     569             :  *
     570             :  * @return pointer to an internal buffer containing a line of text read
     571             :  * from the file or NULL if the end of file was encountered.
     572             :  */
     573             : 
     574           6 : const char *CPLReadLine(FILE *fp)
     575             : 
     576             : {
     577             :     /* -------------------------------------------------------------------- */
     578             :     /*      Cleanup case.                                                   */
     579             :     /* -------------------------------------------------------------------- */
     580           6 :     if (fp == nullptr)
     581             :     {
     582           6 :         CPLReadLineBuffer(-1);
     583           6 :         return nullptr;
     584             :     }
     585             : 
     586             :     /* -------------------------------------------------------------------- */
     587             :     /*      Loop reading chunks of the line till we get to the end of       */
     588             :     /*      the line.                                                       */
     589             :     /* -------------------------------------------------------------------- */
     590           0 :     size_t nBytesReadThisTime = 0;
     591           0 :     char *pszRLBuffer = nullptr;
     592           0 :     size_t nReadSoFar = 0;
     593             : 
     594           0 :     do
     595             :     {
     596             :         /* --------------------------------------------------------------------
     597             :          */
     598             :         /*      Grow the working buffer if we have it nearly full.  Fail out */
     599             :         /*      of read line if we can't reallocate it big enough (for */
     600             :         /*      instance for a _very large_ file with no newlines). */
     601             :         /* --------------------------------------------------------------------
     602             :          */
     603           0 :         if (nReadSoFar > 100 * 1024 * 1024)
     604             :             // It is dubious that we need to read a line longer than 100 MB.
     605           0 :             return nullptr;
     606           0 :         pszRLBuffer = CPLReadLineBuffer(static_cast<int>(nReadSoFar) + 129);
     607           0 :         if (pszRLBuffer == nullptr)
     608           0 :             return nullptr;
     609             : 
     610             :         /* --------------------------------------------------------------------
     611             :          */
     612             :         /*      Do the actual read. */
     613             :         /* --------------------------------------------------------------------
     614             :          */
     615           0 :         if (CPLFGets(pszRLBuffer + nReadSoFar, 128, fp) == nullptr &&
     616             :             nReadSoFar == 0)
     617           0 :             return nullptr;
     618             : 
     619           0 :         nBytesReadThisTime = strlen(pszRLBuffer + nReadSoFar);
     620           0 :         nReadSoFar += nBytesReadThisTime;
     621           0 :     } while (nBytesReadThisTime >= 127 && pszRLBuffer[nReadSoFar - 1] != knCR &&
     622           0 :              pszRLBuffer[nReadSoFar - 1] != knLF);
     623             : 
     624           0 :     return pszRLBuffer;
     625             : }
     626             : 
     627             : /************************************************************************/
     628             : /*                            CPLReadLineL()                            */
     629             : /************************************************************************/
     630             : 
     631             : /**
     632             :  * Simplified line reading from text file.
     633             :  *
     634             :  * Similar to CPLReadLine(), but reading from a large file API handle.
     635             :  *
     636             :  * @param fp file pointer opened with VSIFOpenL().
     637             :  *
     638             :  * @return pointer to an internal buffer containing a line of text read
     639             :  * from the file or NULL if the end of file was encountered.
     640             :  */
     641             : 
     642      194581 : const char *CPLReadLineL(VSILFILE *fp)
     643             : {
     644      194581 :     return CPLReadLine2L(fp, -1, nullptr);
     645             : }
     646             : 
     647             : /************************************************************************/
     648             : /*                           CPLReadLine2L()                            */
     649             : /************************************************************************/
     650             : 
     651             : /**
     652             :  * Simplified line reading from text file.
     653             :  *
     654             :  * Similar to CPLReadLine(), but reading from a large file API handle.
     655             :  *
     656             :  * @param fp file pointer opened with VSIFOpenL().
     657             :  * @param nMaxCars  maximum number of characters allowed, or -1 for no limit.
     658             :  * @param papszOptions NULL-terminated array of options. Unused for now.
     659             : 
     660             :  * @return pointer to an internal buffer containing a line of text read
     661             :  * from the file or NULL if the end of file was encountered or the maximum
     662             :  * number of characters allowed reached.
     663             :  *
     664             :  * @since GDAL 1.7.0
     665             :  */
     666             : 
     667     1282120 : const char *CPLReadLine2L(VSILFILE *fp, int nMaxCars,
     668             :                           CPL_UNUSED CSLConstList papszOptions)
     669             : 
     670             : {
     671             :     int nBufLength;
     672     2564240 :     return CPLReadLine3L(fp, nMaxCars, &nBufLength, papszOptions);
     673             : }
     674             : 
     675             : /************************************************************************/
     676             : /*                           CPLReadLine3L()                            */
     677             : /************************************************************************/
     678             : 
     679             : /**
     680             :  * Simplified line reading from text file.
     681             :  *
     682             :  * Similar to CPLReadLine(), but reading from a large file API handle.
     683             :  *
     684             :  * @param fp file pointer opened with VSIFOpenL().
     685             :  * @param nMaxCars  maximum number of characters allowed, or -1 for no limit.
     686             :  * @param papszOptions NULL-terminated array of options. Unused for now.
     687             :  * @param[out] pnBufLength size of output string (must be non-NULL)
     688             : 
     689             :  * @return pointer to an internal buffer containing a line of text read
     690             :  * from the file or NULL if the end of file was encountered or the maximum
     691             :  * number of characters allowed reached.
     692             :  *
     693             :  * @since GDAL 2.3.0
     694             :  */
     695     1345040 : const char *CPLReadLine3L(VSILFILE *fp, int nMaxCars, int *pnBufLength,
     696             :                           CPL_UNUSED CSLConstList papszOptions)
     697             : {
     698             :     /* -------------------------------------------------------------------- */
     699             :     /*      Cleanup case.                                                   */
     700             :     /* -------------------------------------------------------------------- */
     701     1345040 :     if (fp == nullptr)
     702             :     {
     703        2330 :         CPLReadLineBuffer(-1);
     704        2330 :         return nullptr;
     705             :     }
     706             : 
     707             :     /* -------------------------------------------------------------------- */
     708             :     /*      Loop reading chunks of the line till we get to the end of       */
     709             :     /*      the line.                                                       */
     710             :     /* -------------------------------------------------------------------- */
     711     1342710 :     char *pszRLBuffer = nullptr;
     712     1342710 :     const size_t nChunkSize = 40;
     713     1342710 :     char szChunk[nChunkSize] = {};
     714     1342710 :     size_t nChunkBytesRead = 0;
     715     1342710 :     size_t nChunkBytesConsumed = 0;
     716             : 
     717     1342710 :     *pnBufLength = 0;
     718     1342710 :     szChunk[0] = 0;
     719             : 
     720             :     while (true)
     721             :     {
     722             :         /* --------------------------------------------------------------------
     723             :          */
     724             :         /*      Read a chunk from the input file. */
     725             :         /* --------------------------------------------------------------------
     726             :          */
     727     2387060 :         if (*pnBufLength > INT_MAX - static_cast<int>(nChunkSize) - 1)
     728             :         {
     729           0 :             CPLError(CE_Failure, CPLE_AppDefined,
     730             :                      "Too big line : more than 2 billion characters!.");
     731           0 :             CPLReadLineBuffer(-1);
     732           0 :             return nullptr;
     733             :         }
     734             : 
     735             :         pszRLBuffer =
     736     2387060 :             CPLReadLineBuffer(static_cast<int>(*pnBufLength + nChunkSize + 1));
     737     2387060 :         if (pszRLBuffer == nullptr)
     738           0 :             return nullptr;
     739             : 
     740     2387060 :         if (nChunkBytesRead == nChunkBytesConsumed + 1)
     741             :         {
     742             : 
     743             :             // case where one character is left over from last read.
     744     1044350 :             szChunk[0] = szChunk[nChunkBytesConsumed];
     745             : 
     746     1044350 :             nChunkBytesConsumed = 0;
     747     1044350 :             nChunkBytesRead = VSIFReadL(szChunk + 1, 1, nChunkSize - 1, fp) + 1;
     748             :         }
     749             :         else
     750             :         {
     751     1342710 :             nChunkBytesConsumed = 0;
     752             : 
     753             :             // fresh read.
     754     1342710 :             nChunkBytesRead = VSIFReadL(szChunk, 1, nChunkSize, fp);
     755     1342710 :             if (nChunkBytesRead == 0)
     756             :             {
     757       11103 :                 if (*pnBufLength == 0)
     758       11103 :                     return nullptr;
     759             : 
     760           0 :                 break;
     761             :             }
     762             :         }
     763             : 
     764             :         /* --------------------------------------------------------------------
     765             :          */
     766             :         /*      copy over characters watching for end-of-line. */
     767             :         /* --------------------------------------------------------------------
     768             :          */
     769     2375950 :         bool bBreak = false;
     770    62527800 :         while (nChunkBytesConsumed < nChunkBytesRead - 1 && !bBreak)
     771             :         {
     772    60151800 :             if ((szChunk[nChunkBytesConsumed] == knCR &&
     773      172272 :                  szChunk[nChunkBytesConsumed + 1] == knLF) ||
     774    59979900 :                 (szChunk[nChunkBytesConsumed] == knLF &&
     775     1147800 :                  szChunk[nChunkBytesConsumed + 1] == knCR))
     776             :             {
     777      171995 :                 nChunkBytesConsumed += 2;
     778      171995 :                 bBreak = true;
     779             :             }
     780    59979900 :             else if (szChunk[nChunkBytesConsumed] == knLF ||
     781    58832100 :                      szChunk[nChunkBytesConsumed] == knCR)
     782             :             {
     783     1148070 :                 nChunkBytesConsumed += 1;
     784     1148070 :                 bBreak = true;
     785             :             }
     786             :             else
     787             :             {
     788    58831800 :                 pszRLBuffer[(*pnBufLength)++] = szChunk[nChunkBytesConsumed++];
     789    58831800 :                 if (nMaxCars >= 0 && *pnBufLength == nMaxCars)
     790             :                 {
     791           0 :                     CPLError(CE_Failure, CPLE_AppDefined,
     792             :                              "Maximum number of characters allowed reached.");
     793           0 :                     return nullptr;
     794             :                 }
     795             :             }
     796             :         }
     797             : 
     798     2375950 :         if (bBreak)
     799     1320070 :             break;
     800             : 
     801             :         /* --------------------------------------------------------------------
     802             :          */
     803             :         /*      If there is a remaining character and it is not a newline */
     804             :         /*      consume it.  If it is a newline, but we are clearly at the */
     805             :         /*      end of the file then consume it. */
     806             :         /* --------------------------------------------------------------------
     807             :          */
     808     1055890 :         if (nChunkBytesConsumed == nChunkBytesRead - 1 &&
     809             :             nChunkBytesRead < nChunkSize)
     810             :         {
     811       11539 :             if (szChunk[nChunkBytesConsumed] == knLF ||
     812        1674 :                 szChunk[nChunkBytesConsumed] == knCR)
     813             :             {
     814        9865 :                 nChunkBytesConsumed++;
     815        9865 :                 break;
     816             :             }
     817             : 
     818        1674 :             pszRLBuffer[(*pnBufLength)++] = szChunk[nChunkBytesConsumed++];
     819        1674 :             break;
     820             :         }
     821     1044350 :     }
     822             : 
     823             :     /* -------------------------------------------------------------------- */
     824             :     /*      If we have left over bytes after breaking out, seek back to     */
     825             :     /*      ensure they remain to be read next time.                        */
     826             :     /* -------------------------------------------------------------------- */
     827     1331610 :     if (nChunkBytesConsumed < nChunkBytesRead)
     828             :     {
     829     1314560 :         const size_t nBytesToPush = nChunkBytesRead - nChunkBytesConsumed;
     830             : 
     831     1314560 :         if (VSIFSeekL(fp, VSIFTellL(fp) - nBytesToPush, SEEK_SET) != 0)
     832           0 :             return nullptr;
     833             :     }
     834             : 
     835     1331610 :     pszRLBuffer[*pnBufLength] = '\0';
     836             : 
     837     1331610 :     return pszRLBuffer;
     838             : }
     839             : 
     840             : /************************************************************************/
     841             : /*                            CPLScanString()                           */
     842             : /************************************************************************/
     843             : 
     844             : /**
     845             :  * Scan up to a maximum number of characters from a given string,
     846             :  * allocate a buffer for a new string and fill it with scanned characters.
     847             :  *
     848             :  * @param pszString String containing characters to be scanned. It may be
     849             :  * terminated with a null character.
     850             :  *
     851             :  * @param nMaxLength The maximum number of character to read. Less
     852             :  * characters will be read if a null character is encountered.
     853             :  *
     854             :  * @param bTrimSpaces If TRUE, trim ending spaces from the input string.
     855             :  * Character considered as empty using isspace(3) function.
     856             :  *
     857             :  * @param bNormalize If TRUE, replace ':' symbol with the '_'. It is needed if
     858             :  * resulting string will be used in CPL dictionaries.
     859             :  *
     860             :  * @return Pointer to the resulting string buffer. Caller responsible to free
     861             :  * this buffer with CPLFree().
     862             :  */
     863             : 
     864        5107 : char *CPLScanString(const char *pszString, int nMaxLength, int bTrimSpaces,
     865             :                     int bNormalize)
     866             : {
     867        5107 :     if (!pszString)
     868           0 :         return nullptr;
     869             : 
     870        5107 :     if (!nMaxLength)
     871           2 :         return CPLStrdup("");
     872             : 
     873        5105 :     char *pszBuffer = static_cast<char *>(CPLMalloc(nMaxLength + 1));
     874        5105 :     if (!pszBuffer)
     875           0 :         return nullptr;
     876             : 
     877        5105 :     strncpy(pszBuffer, pszString, nMaxLength);
     878        5105 :     pszBuffer[nMaxLength] = '\0';
     879             : 
     880        5105 :     if (bTrimSpaces)
     881             :     {
     882        5102 :         size_t i = strlen(pszBuffer);
     883        6226 :         while (i > 0)
     884             :         {
     885        6192 :             i--;
     886        6192 :             if (!isspace(static_cast<unsigned char>(pszBuffer[i])))
     887        5068 :                 break;
     888        1124 :             pszBuffer[i] = '\0';
     889             :         }
     890             :     }
     891             : 
     892        5105 :     if (bNormalize)
     893             :     {
     894        4984 :         size_t i = strlen(pszBuffer);
     895       38121 :         while (i > 0)
     896             :         {
     897       33137 :             i--;
     898       33137 :             if (pszBuffer[i] == ':')
     899           0 :                 pszBuffer[i] = '_';
     900             :         }
     901             :     }
     902             : 
     903        5105 :     return pszBuffer;
     904             : }
     905             : 
     906             : /************************************************************************/
     907             : /*                             CPLScanLong()                            */
     908             : /************************************************************************/
     909             : 
     910             : /**
     911             :  * Scan up to a maximum number of characters from a string and convert
     912             :  * the result to a long.
     913             :  *
     914             :  * @param pszString String containing characters to be scanned. It may be
     915             :  * terminated with a null character.
     916             :  *
     917             :  * @param nMaxLength The maximum number of character to consider as part
     918             :  * of the number. Less characters will be considered if a null character
     919             :  * is encountered.
     920             :  *
     921             :  * @return Long value, converted from its ASCII form.
     922             :  */
     923             : 
     924        1358 : long CPLScanLong(const char *pszString, int nMaxLength)
     925             : {
     926        1358 :     CPLAssert(nMaxLength >= 0);
     927        1358 :     if (pszString == nullptr)
     928           0 :         return 0;
     929        1358 :     const size_t nLength = CPLStrnlen(pszString, nMaxLength);
     930        2715 :     const std::string osValue(pszString, nLength);
     931        1358 :     return atol(osValue.c_str());
     932             : }
     933             : 
     934             : /************************************************************************/
     935             : /*                            CPLScanULong()                            */
     936             : /************************************************************************/
     937             : 
     938             : /**
     939             :  * Scan up to a maximum number of characters from a string and convert
     940             :  * the result to a unsigned long.
     941             :  *
     942             :  * @param pszString String containing characters to be scanned. It may be
     943             :  * terminated with a null character.
     944             :  *
     945             :  * @param nMaxLength The maximum number of character to consider as part
     946             :  * of the number. Less characters will be considered if a null character
     947             :  * is encountered.
     948             :  *
     949             :  * @return Unsigned long value, converted from its ASCII form.
     950             :  */
     951             : 
     952           0 : unsigned long CPLScanULong(const char *pszString, int nMaxLength)
     953             : {
     954           0 :     CPLAssert(nMaxLength >= 0);
     955           0 :     if (pszString == nullptr)
     956           0 :         return 0;
     957           0 :     const size_t nLength = CPLStrnlen(pszString, nMaxLength);
     958           0 :     const std::string osValue(pszString, nLength);
     959           0 :     return strtoul(osValue.c_str(), nullptr, 10);
     960             : }
     961             : 
     962             : /************************************************************************/
     963             : /*                           CPLScanUIntBig()                           */
     964             : /************************************************************************/
     965             : 
     966             : /**
     967             :  * Extract big integer from string.
     968             :  *
     969             :  * Scan up to a maximum number of characters from a string and convert
     970             :  * the result to a GUIntBig.
     971             :  *
     972             :  * @param pszString String containing characters to be scanned. It may be
     973             :  * terminated with a null character.
     974             :  *
     975             :  * @param nMaxLength The maximum number of character to consider as part
     976             :  * of the number. Less characters will be considered if a null character
     977             :  * is encountered.
     978             :  *
     979             :  * @return GUIntBig value, converted from its ASCII form.
     980             :  */
     981             : 
     982       20602 : GUIntBig CPLScanUIntBig(const char *pszString, int nMaxLength)
     983             : {
     984       20602 :     CPLAssert(nMaxLength >= 0);
     985       20602 :     if (pszString == nullptr)
     986           0 :         return 0;
     987       20602 :     const size_t nLength = CPLStrnlen(pszString, nMaxLength);
     988       41204 :     const std::string osValue(pszString, nLength);
     989             : 
     990             :     /* -------------------------------------------------------------------- */
     991             :     /*      Fetch out the result                                            */
     992             :     /* -------------------------------------------------------------------- */
     993       20602 :     return strtoull(osValue.c_str(), nullptr, 10);
     994             : }
     995             : 
     996             : /************************************************************************/
     997             : /*                           CPLAtoGIntBig()                            */
     998             : /************************************************************************/
     999             : 
    1000             : /**
    1001             :  * Convert a string to a 64 bit signed integer.
    1002             :  *
    1003             :  * @param pszString String containing 64 bit signed integer.
    1004             :  * @return 64 bit signed integer.
    1005             :  * @since GDAL 2.0
    1006             :  */
    1007             : 
    1008      105313 : GIntBig CPLAtoGIntBig(const char *pszString)
    1009             : {
    1010      105313 :     return atoll(pszString);
    1011             : }
    1012             : 
    1013             : #if defined(__MINGW32__) || defined(__sun__)
    1014             : 
    1015             : // mingw atoll() doesn't return ERANGE in case of overflow
    1016             : static int CPLAtoGIntBigExHasOverflow(const char *pszString, GIntBig nVal)
    1017             : {
    1018             :     if (strlen(pszString) <= 18)
    1019             :         return FALSE;
    1020             :     while (*pszString == ' ')
    1021             :         pszString++;
    1022             :     if (*pszString == '+')
    1023             :         pszString++;
    1024             :     char szBuffer[32] = {};
    1025             : /* x86_64-w64-mingw32-g++ (GCC) 4.8.2 annoyingly warns */
    1026             : #ifdef HAVE_GCC_DIAGNOSTIC_PUSH
    1027             : #pragma GCC diagnostic push
    1028             : #pragma GCC diagnostic ignored "-Wformat"
    1029             : #endif
    1030             :     snprintf(szBuffer, sizeof(szBuffer), CPL_FRMT_GIB, nVal);
    1031             : #ifdef HAVE_GCC_DIAGNOSTIC_PUSH
    1032             : #pragma GCC diagnostic pop
    1033             : #endif
    1034             :     return strcmp(szBuffer, pszString) != 0;
    1035             : }
    1036             : 
    1037             : #endif
    1038             : 
    1039             : /************************************************************************/
    1040             : /*                          CPLAtoGIntBigEx()                           */
    1041             : /************************************************************************/
    1042             : 
    1043             : /**
    1044             :  * Convert a string to a 64 bit signed integer.
    1045             :  *
    1046             :  * @param pszString String containing 64 bit signed integer.
    1047             :  * @param bWarn Issue a warning if an overflow occurs during conversion
    1048             :  * @param pbOverflow Pointer to an integer to store if an overflow occurred, or
    1049             :  *        NULL
    1050             :  * @return 64 bit signed integer.
    1051             :  * @since GDAL 2.0
    1052             :  */
    1053             : 
    1054      100064 : GIntBig CPLAtoGIntBigEx(const char *pszString, int bWarn, int *pbOverflow)
    1055             : {
    1056      100064 :     errno = 0;
    1057      100064 :     GIntBig nVal = strtoll(pszString, nullptr, 10);
    1058      100064 :     if (errno == ERANGE
    1059             : #if defined(__MINGW32__) || defined(__sun__)
    1060             :         || CPLAtoGIntBigExHasOverflow(pszString, nVal)
    1061             : #endif
    1062             :     )
    1063             :     {
    1064           4 :         if (pbOverflow)
    1065           2 :             *pbOverflow = TRUE;
    1066           4 :         if (bWarn)
    1067             :         {
    1068           2 :             CPLError(CE_Warning, CPLE_AppDefined,
    1069             :                      "64 bit integer overflow when converting %s", pszString);
    1070             :         }
    1071           4 :         while (*pszString == ' ')
    1072           0 :             pszString++;
    1073           4 :         return (*pszString == '-') ? GINTBIG_MIN : GINTBIG_MAX;
    1074             :     }
    1075      100060 :     else if (pbOverflow)
    1076             :     {
    1077        3874 :         *pbOverflow = FALSE;
    1078             :     }
    1079      100060 :     return nVal;
    1080             : }
    1081             : 
    1082             : /************************************************************************/
    1083             : /*                           CPLScanPointer()                           */
    1084             : /************************************************************************/
    1085             : 
    1086             : /**
    1087             :  * Extract pointer from string.
    1088             :  *
    1089             :  * Scan up to a maximum number of characters from a string and convert
    1090             :  * the result to a pointer.
    1091             :  *
    1092             :  * @param pszString String containing characters to be scanned. It may be
    1093             :  * terminated with a null character.
    1094             :  *
    1095             :  * @param nMaxLength The maximum number of character to consider as part
    1096             :  * of the number. Less characters will be considered if a null character
    1097             :  * is encountered.
    1098             :  *
    1099             :  * @return pointer value, converted from its ASCII form.
    1100             :  */
    1101             : 
    1102         957 : void *CPLScanPointer(const char *pszString, int nMaxLength)
    1103             : {
    1104         957 :     char szTemp[128] = {};
    1105             : 
    1106             :     /* -------------------------------------------------------------------- */
    1107             :     /*      Compute string into local buffer, and terminate it.             */
    1108             :     /* -------------------------------------------------------------------- */
    1109         957 :     if (nMaxLength > static_cast<int>(sizeof(szTemp)) - 1)
    1110           0 :         nMaxLength = sizeof(szTemp) - 1;
    1111             : 
    1112         957 :     strncpy(szTemp, pszString, nMaxLength);
    1113         957 :     szTemp[nMaxLength] = '\0';
    1114             : 
    1115             :     /* -------------------------------------------------------------------- */
    1116             :     /*      On MSVC we have to scanf pointer values without the 0x          */
    1117             :     /*      prefix.                                                         */
    1118             :     /* -------------------------------------------------------------------- */
    1119         957 :     if (STARTS_WITH_CI(szTemp, "0x"))
    1120             :     {
    1121         957 :         void *pResult = nullptr;
    1122             : 
    1123             : #if defined(__MSVCRT__) || (defined(_WIN32) && defined(_MSC_VER))
    1124             :         // cppcheck-suppress invalidscanf
    1125             :         sscanf(szTemp + 2, "%p", &pResult);
    1126             : #else
    1127             :         // cppcheck-suppress invalidscanf
    1128         957 :         sscanf(szTemp, "%p", &pResult);
    1129             : 
    1130             :         // Solaris actually behaves like MSVCRT.
    1131         957 :         if (pResult == nullptr)
    1132             :         {
    1133             :             // cppcheck-suppress invalidscanf
    1134           0 :             sscanf(szTemp + 2, "%p", &pResult);
    1135             :         }
    1136             : #endif
    1137         957 :         return pResult;
    1138             :     }
    1139             : 
    1140             : #if SIZEOF_VOIDP == 8
    1141           0 :     return reinterpret_cast<void *>(CPLScanUIntBig(szTemp, nMaxLength));
    1142             : #else
    1143             :     return reinterpret_cast<void *>(CPLScanULong(szTemp, nMaxLength));
    1144             : #endif
    1145             : }
    1146             : 
    1147             : /************************************************************************/
    1148             : /*                             CPLScanDouble()                          */
    1149             : /************************************************************************/
    1150             : 
    1151             : /**
    1152             :  * Extract double from string.
    1153             :  *
    1154             :  * Scan up to a maximum number of characters from a string and convert the
    1155             :  * result to a double. This function uses CPLAtof() to convert string to
    1156             :  * double value, so it uses a comma as a decimal delimiter.
    1157             :  *
    1158             :  * @param pszString String containing characters to be scanned. It may be
    1159             :  * terminated with a null character.
    1160             :  *
    1161             :  * @param nMaxLength The maximum number of character to consider as part
    1162             :  * of the number. Less characters will be considered if a null character
    1163             :  * is encountered.
    1164             :  *
    1165             :  * @return Double value, converted from its ASCII form.
    1166             :  */
    1167             : 
    1168         317 : double CPLScanDouble(const char *pszString, int nMaxLength)
    1169             : {
    1170         317 :     char szValue[32] = {};
    1171         317 :     char *pszValue = nullptr;
    1172             : 
    1173         317 :     if (nMaxLength + 1 < static_cast<int>(sizeof(szValue)))
    1174         317 :         pszValue = szValue;
    1175             :     else
    1176           0 :         pszValue = static_cast<char *>(CPLMalloc(nMaxLength + 1));
    1177             : 
    1178             :     /* -------------------------------------------------------------------- */
    1179             :     /*      Compute string into local buffer, and terminate it.             */
    1180             :     /* -------------------------------------------------------------------- */
    1181         317 :     strncpy(pszValue, pszString, nMaxLength);
    1182         317 :     pszValue[nMaxLength] = '\0';
    1183             : 
    1184             :     /* -------------------------------------------------------------------- */
    1185             :     /*      Make a pass through converting 'D's to 'E's.                    */
    1186             :     /* -------------------------------------------------------------------- */
    1187        6436 :     for (int i = 0; i < nMaxLength; i++)
    1188        6119 :         if (pszValue[i] == 'd' || pszValue[i] == 'D')
    1189          45 :             pszValue[i] = 'E';
    1190             : 
    1191             :     /* -------------------------------------------------------------------- */
    1192             :     /*      The conversion itself.                                          */
    1193             :     /* -------------------------------------------------------------------- */
    1194         317 :     const double dfValue = CPLAtof(pszValue);
    1195             : 
    1196         317 :     if (pszValue != szValue)
    1197           0 :         CPLFree(pszValue);
    1198         317 :     return dfValue;
    1199             : }
    1200             : 
    1201             : /************************************************************************/
    1202             : /*                      CPLPrintString()                                */
    1203             : /************************************************************************/
    1204             : 
    1205             : /**
    1206             :  * Copy the string pointed to by pszSrc, NOT including the terminating
    1207             :  * `\\0' character, to the array pointed to by pszDest.
    1208             :  *
    1209             :  * @param pszDest Pointer to the destination string buffer. Should be
    1210             :  * large enough to hold the resulting string.
    1211             :  *
    1212             :  * @param pszSrc Pointer to the source buffer.
    1213             :  *
    1214             :  * @param nMaxLen Maximum length of the resulting string. If string length
    1215             :  * is greater than nMaxLen, it will be truncated.
    1216             :  *
    1217             :  * @return Number of characters printed.
    1218             :  */
    1219             : 
    1220        9321 : int CPLPrintString(char *pszDest, const char *pszSrc, int nMaxLen)
    1221             : {
    1222        9321 :     if (!pszDest)
    1223           0 :         return 0;
    1224             : 
    1225        9321 :     if (!pszSrc)
    1226             :     {
    1227           0 :         *pszDest = '\0';
    1228           0 :         return 1;
    1229             :     }
    1230             : 
    1231        9321 :     int nChars = 0;
    1232        9321 :     char *pszTemp = pszDest;
    1233             : 
    1234      137552 :     while (nChars < nMaxLen && *pszSrc)
    1235             :     {
    1236      128231 :         *pszTemp++ = *pszSrc++;
    1237      128231 :         nChars++;
    1238             :     }
    1239             : 
    1240        9321 :     return nChars;
    1241             : }
    1242             : 
    1243             : /************************************************************************/
    1244             : /*                         CPLPrintStringFill()                         */
    1245             : /************************************************************************/
    1246             : 
    1247             : /**
    1248             :  * Copy the string pointed to by pszSrc, NOT including the terminating
    1249             :  * `\\0' character, to the array pointed to by pszDest. Remainder of the
    1250             :  * destination string will be filled with space characters. This is only
    1251             :  * difference from the PrintString().
    1252             :  *
    1253             :  * @param pszDest Pointer to the destination string buffer. Should be
    1254             :  * large enough to hold the resulting string.
    1255             :  *
    1256             :  * @param pszSrc Pointer to the source buffer.
    1257             :  *
    1258             :  * @param nMaxLen Maximum length of the resulting string. If string length
    1259             :  * is greater than nMaxLen, it will be truncated.
    1260             :  *
    1261             :  * @return Number of characters printed.
    1262             :  */
    1263             : 
    1264         203 : int CPLPrintStringFill(char *pszDest, const char *pszSrc, int nMaxLen)
    1265             : {
    1266         203 :     if (!pszDest)
    1267           0 :         return 0;
    1268             : 
    1269         203 :     if (!pszSrc)
    1270             :     {
    1271           0 :         memset(pszDest, ' ', nMaxLen);
    1272           0 :         return nMaxLen;
    1273             :     }
    1274             : 
    1275         203 :     char *pszTemp = pszDest;
    1276        1219 :     while (nMaxLen && *pszSrc)
    1277             :     {
    1278        1016 :         *pszTemp++ = *pszSrc++;
    1279        1016 :         nMaxLen--;
    1280             :     }
    1281             : 
    1282         203 :     if (nMaxLen)
    1283          69 :         memset(pszTemp, ' ', nMaxLen);
    1284             : 
    1285         203 :     return nMaxLen;
    1286             : }
    1287             : 
    1288             : /************************************************************************/
    1289             : /*                          CPLPrintInt32()                             */
    1290             : /************************************************************************/
    1291             : 
    1292             : /**
    1293             :  * Print GInt32 value into specified string buffer. This string will not
    1294             :  * be NULL-terminated.
    1295             :  *
    1296             :  * @param pszBuffer Pointer to the destination string buffer. Should be
    1297             :  * large enough to hold the resulting string. Note, that the string will
    1298             :  * not be NULL-terminated, so user should do this himself, if needed.
    1299             :  *
    1300             :  * @param iValue Numerical value to print.
    1301             :  *
    1302             :  * @param nMaxLen Maximum length of the resulting string. If string length
    1303             :  * is greater than nMaxLen, it will be truncated.
    1304             :  *
    1305             :  * @return Number of characters printed.
    1306             :  */
    1307             : 
    1308           9 : int CPLPrintInt32(char *pszBuffer, GInt32 iValue, int nMaxLen)
    1309             : {
    1310           9 :     if (!pszBuffer)
    1311           0 :         return 0;
    1312             : 
    1313           9 :     if (nMaxLen >= 64)
    1314           0 :         nMaxLen = 63;
    1315             : 
    1316           9 :     char szTemp[64] = {};
    1317             : 
    1318             : #if UINT_MAX == 65535
    1319             :     snprintf(szTemp, sizeof(szTemp), "%*ld", nMaxLen, iValue);
    1320             : #else
    1321           9 :     snprintf(szTemp, sizeof(szTemp), "%*d", nMaxLen, iValue);
    1322             : #endif
    1323             : 
    1324           9 :     return CPLPrintString(pszBuffer, szTemp, nMaxLen);
    1325             : }
    1326             : 
    1327             : /************************************************************************/
    1328             : /*                          CPLPrintUIntBig()                           */
    1329             : /************************************************************************/
    1330             : 
    1331             : /**
    1332             :  * Print GUIntBig value into specified string buffer. This string will not
    1333             :  * be NULL-terminated.
    1334             :  *
    1335             :  * @param pszBuffer Pointer to the destination string buffer. Should be
    1336             :  * large enough to hold the resulting string. Note, that the string will
    1337             :  * not be NULL-terminated, so user should do this himself, if needed.
    1338             :  *
    1339             :  * @param iValue Numerical value to print.
    1340             :  *
    1341             :  * @param nMaxLen Maximum length of the resulting string. If string length
    1342             :  * is greater than nMaxLen, it will be truncated.
    1343             :  *
    1344             :  * @return Number of characters printed.
    1345             :  */
    1346             : 
    1347          26 : int CPLPrintUIntBig(char *pszBuffer, GUIntBig iValue, int nMaxLen)
    1348             : {
    1349          26 :     if (!pszBuffer)
    1350           0 :         return 0;
    1351             : 
    1352          26 :     if (nMaxLen >= 64)
    1353           0 :         nMaxLen = 63;
    1354             : 
    1355          26 :     char szTemp[64] = {};
    1356             : 
    1357             : #if defined(__MSVCRT__) || (defined(_WIN32) && defined(_MSC_VER))
    1358             : /* x86_64-w64-mingw32-g++ (GCC) 4.8.2 annoyingly warns */
    1359             : #ifdef HAVE_GCC_DIAGNOSTIC_PUSH
    1360             : #pragma GCC diagnostic push
    1361             : #pragma GCC diagnostic ignored "-Wformat"
    1362             : #pragma GCC diagnostic ignored "-Wformat-extra-args"
    1363             : #endif
    1364             :     snprintf(szTemp, sizeof(szTemp), "%*I64u", nMaxLen, iValue);
    1365             : #ifdef HAVE_GCC_DIAGNOSTIC_PUSH
    1366             : #pragma GCC diagnostic pop
    1367             : #endif
    1368             : #else
    1369          26 :     snprintf(szTemp, sizeof(szTemp), "%*llu", nMaxLen, iValue);
    1370             : #endif
    1371             : 
    1372          26 :     return CPLPrintString(pszBuffer, szTemp, nMaxLen);
    1373             : }
    1374             : 
    1375             : /************************************************************************/
    1376             : /*                          CPLPrintPointer()                           */
    1377             : /************************************************************************/
    1378             : 
    1379             : /**
    1380             :  * Print pointer value into specified string buffer. This string will not
    1381             :  * be NULL-terminated.
    1382             :  *
    1383             :  * @param pszBuffer Pointer to the destination string buffer. Should be
    1384             :  * large enough to hold the resulting string. Note, that the string will
    1385             :  * not be NULL-terminated, so user should do this himself, if needed.
    1386             :  *
    1387             :  * @param pValue Pointer to ASCII encode.
    1388             :  *
    1389             :  * @param nMaxLen Maximum length of the resulting string. If string length
    1390             :  * is greater than nMaxLen, it will be truncated.
    1391             :  *
    1392             :  * @return Number of characters printed.
    1393             :  */
    1394             : 
    1395        9251 : int CPLPrintPointer(char *pszBuffer, void *pValue, int nMaxLen)
    1396             : {
    1397        9251 :     if (!pszBuffer)
    1398           0 :         return 0;
    1399             : 
    1400        9251 :     if (nMaxLen >= 64)
    1401        8286 :         nMaxLen = 63;
    1402             : 
    1403        9251 :     char szTemp[64] = {};
    1404             : 
    1405        9251 :     snprintf(szTemp, sizeof(szTemp), "%p", pValue);
    1406             : 
    1407             :     // On windows, and possibly some other platforms the sprintf("%p")
    1408             :     // does not prefix things with 0x so it is hard to know later if the
    1409             :     // value is hex encoded.  Fix this up here.
    1410             : 
    1411        9251 :     if (!STARTS_WITH_CI(szTemp, "0x"))
    1412           0 :         snprintf(szTemp, sizeof(szTemp), "0x%p", pValue);
    1413             : 
    1414        9251 :     return CPLPrintString(pszBuffer, szTemp, nMaxLen);
    1415             : }
    1416             : 
    1417             : /************************************************************************/
    1418             : /*                          CPLPrintDouble()                            */
    1419             : /************************************************************************/
    1420             : 
    1421             : /**
    1422             :  * Print double value into specified string buffer. Exponential character
    1423             :  * flag 'E' (or 'e') will be replaced with 'D', as in Fortran. Resulting
    1424             :  * string will not to be NULL-terminated.
    1425             :  *
    1426             :  * @param pszBuffer Pointer to the destination string buffer. Should be
    1427             :  * large enough to hold the resulting string. Note, that the string will
    1428             :  * not be NULL-terminated, so user should do this himself, if needed.
    1429             :  *
    1430             :  * @param pszFormat Format specifier (for example, "%16.9E").
    1431             :  *
    1432             :  * @param dfValue Numerical value to print.
    1433             :  *
    1434             :  * @param pszLocale Unused.
    1435             :  *
    1436             :  * @return Number of characters printed.
    1437             :  */
    1438             : 
    1439           0 : int CPLPrintDouble(char *pszBuffer, const char *pszFormat, double dfValue,
    1440             :                    CPL_UNUSED const char *pszLocale)
    1441             : {
    1442           0 :     if (!pszBuffer)
    1443           0 :         return 0;
    1444             : 
    1445           0 :     const int knDoubleBufferSize = 64;
    1446           0 :     char szTemp[knDoubleBufferSize] = {};
    1447             : 
    1448           0 :     CPLsnprintf(szTemp, knDoubleBufferSize, pszFormat, dfValue);
    1449           0 :     szTemp[knDoubleBufferSize - 1] = '\0';
    1450             : 
    1451           0 :     for (int i = 0; szTemp[i] != '\0'; i++)
    1452             :     {
    1453           0 :         if (szTemp[i] == 'E' || szTemp[i] == 'e')
    1454           0 :             szTemp[i] = 'D';
    1455             :     }
    1456             : 
    1457           0 :     return CPLPrintString(pszBuffer, szTemp, 64);
    1458             : }
    1459             : 
    1460             : /************************************************************************/
    1461             : /*                            CPLPrintTime()                            */
    1462             : /************************************************************************/
    1463             : 
    1464             : /**
    1465             :  * Print specified time value accordingly to the format options and
    1466             :  * specified locale name. This function does following:
    1467             :  *
    1468             :  *  - if locale parameter is not NULL, the current locale setting will be
    1469             :  *  stored and replaced with the specified one;
    1470             :  *  - format time value with the strftime(3) function;
    1471             :  *  - restore back current locale, if was saved.
    1472             :  *
    1473             :  * @param pszBuffer Pointer to the destination string buffer. Should be
    1474             :  * large enough to hold the resulting string. Note, that the string will
    1475             :  * not be NULL-terminated, so user should do this himself, if needed.
    1476             :  *
    1477             :  * @param nMaxLen Maximum length of the resulting string. If string length is
    1478             :  * greater than nMaxLen, it will be truncated.
    1479             :  *
    1480             :  * @param pszFormat Controls the output format. Options are the same as
    1481             :  * for strftime(3) function.
    1482             :  *
    1483             :  * @param poBrokenTime Pointer to the broken-down time structure. May be
    1484             :  * requested with the VSIGMTime() and VSILocalTime() functions.
    1485             :  *
    1486             :  * @param pszLocale Pointer to a character string containing locale name
    1487             :  * ("C", "POSIX", "us_US", "ru_RU.KOI8-R" etc.). If NULL we will not
    1488             :  * manipulate with locale settings and current process locale will be used for
    1489             :  * printing. Be aware that it may be unsuitable to use current locale for
    1490             :  * printing time, because all names will be printed in your native language,
    1491             :  * as well as time format settings also may be adjusted differently from the
    1492             :  * C/POSIX defaults. To solve these problems this option was introduced.
    1493             :  *
    1494             :  * @return Number of characters printed.
    1495             :  */
    1496             : 
    1497          31 : int CPLPrintTime(char *pszBuffer, int nMaxLen, const char *pszFormat,
    1498             :                  const struct tm *poBrokenTime, const char *pszLocale)
    1499             : {
    1500             :     char *pszTemp =
    1501          31 :         static_cast<char *>(CPLMalloc((nMaxLen + 1) * sizeof(char)));
    1502             : 
    1503          31 :     if (pszLocale && EQUAL(pszLocale, "C") &&
    1504          31 :         strcmp(pszFormat, "%a, %d %b %Y %H:%M:%S GMT") == 0)
    1505             :     {
    1506             :         // Particular case when formatting RFC822 datetime, to avoid locale
    1507             :         // change
    1508             :         static const char *const aszMonthStr[] = {"Jan", "Feb", "Mar", "Apr",
    1509             :                                                   "May", "Jun", "Jul", "Aug",
    1510             :                                                   "Sep", "Oct", "Nov", "Dec"};
    1511             :         static const char *const aszDayOfWeek[] = {"Sun", "Mon", "Tue", "Wed",
    1512             :                                                    "Thu", "Fri", "Sat"};
    1513          62 :         snprintf(pszTemp, nMaxLen + 1, "%s, %02d %s %04d %02d:%02d:%02d GMT",
    1514          31 :                  aszDayOfWeek[std::max(0, std::min(6, poBrokenTime->tm_wday))],
    1515          31 :                  poBrokenTime->tm_mday,
    1516          31 :                  aszMonthStr[std::max(0, std::min(11, poBrokenTime->tm_mon))],
    1517          31 :                  poBrokenTime->tm_year + 1900, poBrokenTime->tm_hour,
    1518          62 :                  poBrokenTime->tm_min, poBrokenTime->tm_sec);
    1519             :     }
    1520             :     else
    1521             :     {
    1522             : #if defined(HAVE_LOCALE_H) && defined(HAVE_SETLOCALE)
    1523             :         char *pszCurLocale = NULL;
    1524             : 
    1525             :         if (pszLocale || EQUAL(pszLocale, ""))
    1526             :         {
    1527             :             // Save the current locale.
    1528             :             pszCurLocale = CPLsetlocale(LC_ALL, NULL);
    1529             :             // Set locale to the specified value.
    1530             :             CPLsetlocale(LC_ALL, pszLocale);
    1531             :         }
    1532             : #else
    1533             :         (void)pszLocale;
    1534             : #endif
    1535             : 
    1536           0 :         if (!strftime(pszTemp, nMaxLen + 1, pszFormat, poBrokenTime))
    1537           0 :             memset(pszTemp, 0, nMaxLen + 1);
    1538             : 
    1539             : #if defined(HAVE_LOCALE_H) && defined(HAVE_SETLOCALE)
    1540             :         // Restore stored locale back.
    1541             :         if (pszCurLocale)
    1542             :             CPLsetlocale(LC_ALL, pszCurLocale);
    1543             : #endif
    1544             :     }
    1545             : 
    1546          31 :     const int nChars = CPLPrintString(pszBuffer, pszTemp, nMaxLen);
    1547             : 
    1548          31 :     CPLFree(pszTemp);
    1549             : 
    1550          31 :     return nChars;
    1551             : }
    1552             : 
    1553             : /************************************************************************/
    1554             : /*                       CPLVerifyConfiguration()                       */
    1555             : /************************************************************************/
    1556             : 
    1557           0 : void CPLVerifyConfiguration()
    1558             : 
    1559             : {
    1560             :     /* -------------------------------------------------------------------- */
    1561             :     /*      Verify data types.                                              */
    1562             :     /* -------------------------------------------------------------------- */
    1563             :     static_assert(sizeof(short) == 2);   // We unfortunately rely on this
    1564             :     static_assert(sizeof(int) == 4);     // We unfortunately rely on this
    1565             :     static_assert(sizeof(float) == 4);   // We unfortunately rely on this
    1566             :     static_assert(sizeof(double) == 8);  // We unfortunately rely on this
    1567             :     static_assert(sizeof(GInt64) == 8);
    1568             :     static_assert(sizeof(GInt32) == 4);
    1569             :     static_assert(sizeof(GInt16) == 2);
    1570             :     static_assert(sizeof(GByte) == 1);
    1571             : 
    1572             :     /* -------------------------------------------------------------------- */
    1573             :     /*      Verify byte order                                               */
    1574             :     /* -------------------------------------------------------------------- */
    1575             : #ifdef CPL_LSB
    1576             : #if __cplusplus >= 202002L
    1577             :     static_assert(std::endian::native == std::endian::little);
    1578             : #elif defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__)
    1579             :     static_assert(__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__);
    1580             : #endif
    1581             : #elif defined(CPL_MSB)
    1582             : #if __cplusplus >= 202002L
    1583             :     static_assert(std::endian::native == std::endian::big);
    1584             : #elif defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__)
    1585             :     static_assert(__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__);
    1586             : #endif
    1587             : #else
    1588             : #error "CPL_LSB or CPL_MSB must be defined"
    1589             : #endif
    1590           0 : }
    1591             : 
    1592             : #ifdef DEBUG_CONFIG_OPTIONS
    1593             : 
    1594             : static CPLMutex *hRegisterConfigurationOptionMutex = nullptr;
    1595             : static std::set<CPLString> *paoGetKeys = nullptr;
    1596             : static std::set<CPLString> *paoSetKeys = nullptr;
    1597             : 
    1598             : /************************************************************************/
    1599             : /*                      CPLShowAccessedOptions()                        */
    1600             : /************************************************************************/
    1601             : 
    1602             : static void CPLShowAccessedOptions()
    1603             : {
    1604             :     std::set<CPLString>::iterator aoIter;
    1605             : 
    1606             :     printf("Configuration options accessed in reading : "); /*ok*/
    1607             :     aoIter = paoGetKeys->begin();
    1608             :     while (aoIter != paoGetKeys->end())
    1609             :     {
    1610             :         printf("%s, ", (*aoIter).c_str()); /*ok*/
    1611             :         ++aoIter;
    1612             :     }
    1613             :     printf("\n"); /*ok*/
    1614             : 
    1615             :     printf("Configuration options accessed in writing : "); /*ok*/
    1616             :     aoIter = paoSetKeys->begin();
    1617             :     while (aoIter != paoSetKeys->end())
    1618             :     {
    1619             :         printf("%s, ", (*aoIter).c_str()); /*ok*/
    1620             :         ++aoIter;
    1621             :     }
    1622             :     printf("\n"); /*ok*/
    1623             : 
    1624             :     delete paoGetKeys;
    1625             :     delete paoSetKeys;
    1626             :     paoGetKeys = nullptr;
    1627             :     paoSetKeys = nullptr;
    1628             : }
    1629             : 
    1630             : /************************************************************************/
    1631             : /*                       CPLAccessConfigOption()                        */
    1632             : /************************************************************************/
    1633             : 
    1634             : static void CPLAccessConfigOption(const char *pszKey, bool bGet)
    1635             : {
    1636             :     CPLMutexHolderD(&hRegisterConfigurationOptionMutex);
    1637             :     if (paoGetKeys == nullptr)
    1638             :     {
    1639             :         paoGetKeys = new std::set<CPLString>;
    1640             :         paoSetKeys = new std::set<CPLString>;
    1641             :         atexit(CPLShowAccessedOptions);
    1642             :     }
    1643             :     if (bGet)
    1644             :         paoGetKeys->insert(pszKey);
    1645             :     else
    1646             :         paoSetKeys->insert(pszKey);
    1647             : }
    1648             : #endif
    1649             : 
    1650             : /************************************************************************/
    1651             : /*                         CPLGetConfigOption()                         */
    1652             : /************************************************************************/
    1653             : 
    1654             : /**
    1655             :  * Get the value of a configuration option.
    1656             :  *
    1657             :  * The value is the value of a (key, value) option set with
    1658             :  * CPLSetConfigOption(), or CPLSetThreadLocalConfigOption() of the same
    1659             :  * thread. If the given option was no defined with
    1660             :  * CPLSetConfigOption(), it tries to find it in environment variables.
    1661             :  *
    1662             :  * Note: the string returned by CPLGetConfigOption() might be short-lived, and
    1663             :  * in particular it will become invalid after a call to CPLSetConfigOption()
    1664             :  * with the same key.
    1665             :  *
    1666             :  * To override temporary a potentially existing option with a new value, you
    1667             :  * can use the following snippet :
    1668             :  * \code{.cpp}
    1669             :  *     // backup old value
    1670             :  *     const char* pszOldValTmp = CPLGetConfigOption(pszKey, NULL);
    1671             :  *     char* pszOldVal = pszOldValTmp ? CPLStrdup(pszOldValTmp) : NULL;
    1672             :  *     // override with new value
    1673             :  *     CPLSetConfigOption(pszKey, pszNewVal);
    1674             :  *     // do something useful
    1675             :  *     // restore old value
    1676             :  *     CPLSetConfigOption(pszKey, pszOldVal);
    1677             :  *     CPLFree(pszOldVal);
    1678             :  * \endcode
    1679             :  *
    1680             :  * @param pszKey the key of the option to retrieve
    1681             :  * @param pszDefault a default value if the key does not match existing defined
    1682             :  *     options (may be NULL)
    1683             :  * @return the value associated to the key, or the default value if not found
    1684             :  *
    1685             :  * @see CPLSetConfigOption(), https://gdal.org/user/configoptions.html
    1686             :  */
    1687     4832450 : const char *CPL_STDCALL CPLGetConfigOption(const char *pszKey,
    1688             :                                            const char *pszDefault)
    1689             : 
    1690             : {
    1691     4832450 :     const char *pszResult = CPLGetThreadLocalConfigOption(pszKey, nullptr);
    1692             : 
    1693     4831970 :     if (pszResult == nullptr)
    1694             :     {
    1695     4794600 :         pszResult = CPLGetGlobalConfigOption(pszKey, nullptr);
    1696             :     }
    1697             : 
    1698     4833560 :     if (gbIgnoreEnvVariables)
    1699             :     {
    1700           6 :         const char *pszEnvVar = getenv(pszKey);
    1701           6 :         if (pszEnvVar != nullptr)
    1702             :         {
    1703           1 :             CPLDebug("CPL",
    1704             :                      "Ignoring environment variable %s=%s because of "
    1705             :                      "ignore-env-vars=yes setting in configuration file",
    1706             :                      pszKey, pszEnvVar);
    1707             :         }
    1708             :     }
    1709     4833550 :     else if (pszResult == nullptr)
    1710             :     {
    1711     4788510 :         pszResult = getenv(pszKey);
    1712             :     }
    1713             : 
    1714     4833540 :     if (pszResult == nullptr)
    1715     4779500 :         return pszDefault;
    1716             : 
    1717       54041 :     return pszResult;
    1718             : }
    1719             : 
    1720             : /************************************************************************/
    1721             : /*                         CPLGetConfigOptions()                        */
    1722             : /************************************************************************/
    1723             : 
    1724             : /**
    1725             :  * Return the list of configuration options as KEY=VALUE pairs.
    1726             :  *
    1727             :  * The list is the one set through the CPLSetConfigOption() API.
    1728             :  *
    1729             :  * Options that through environment variables or with
    1730             :  * CPLSetThreadLocalConfigOption() will *not* be listed.
    1731             :  *
    1732             :  * @return a copy of the list, to be freed with CSLDestroy().
    1733             :  * @since GDAL 2.2
    1734             :  */
    1735           7 : char **CPLGetConfigOptions(void)
    1736             : {
    1737          14 :     CPLMutexHolderD(&hConfigMutex);
    1738          14 :     return CSLDuplicate(const_cast<char **>(g_papszConfigOptions));
    1739             : }
    1740             : 
    1741             : /************************************************************************/
    1742             : /*                         CPLSetConfigOptions()                        */
    1743             : /************************************************************************/
    1744             : 
    1745             : /**
    1746             :  * Replace the full list of configuration options with the passed list of
    1747             :  * KEY=VALUE pairs.
    1748             :  *
    1749             :  * This has the same effect of clearing the existing list, and setting
    1750             :  * individually each pair with the CPLSetConfigOption() API.
    1751             :  *
    1752             :  * This does not affect options set through environment variables or with
    1753             :  * CPLSetThreadLocalConfigOption().
    1754             :  *
    1755             :  * The passed list is copied by the function.
    1756             :  *
    1757             :  * @param papszConfigOptions the new list (or NULL).
    1758             :  *
    1759             :  * @since GDAL 2.2
    1760             :  */
    1761          88 : void CPLSetConfigOptions(const char *const *papszConfigOptions)
    1762             : {
    1763          88 :     CPLMutexHolderD(&hConfigMutex);
    1764          88 :     CSLDestroy(const_cast<char **>(g_papszConfigOptions));
    1765          88 :     g_papszConfigOptions = const_cast<volatile char **>(
    1766          88 :         CSLDuplicate(const_cast<char **>(papszConfigOptions)));
    1767          88 : }
    1768             : 
    1769             : /************************************************************************/
    1770             : /*                   CPLGetThreadLocalConfigOption()                    */
    1771             : /************************************************************************/
    1772             : 
    1773             : /** Same as CPLGetConfigOption() but only with options set with
    1774             :  * CPLSetThreadLocalConfigOption() */
    1775     4858380 : const char *CPL_STDCALL CPLGetThreadLocalConfigOption(const char *pszKey,
    1776             :                                                       const char *pszDefault)
    1777             : 
    1778             : {
    1779             : #ifdef DEBUG_CONFIG_OPTIONS
    1780             :     CPLAccessConfigOption(pszKey, TRUE);
    1781             : #endif
    1782             : 
    1783     4858380 :     const char *pszResult = nullptr;
    1784             : 
    1785     4858380 :     int bMemoryError = FALSE;
    1786             :     char **papszTLConfigOptions = reinterpret_cast<char **>(
    1787     4858380 :         CPLGetTLSEx(CTLS_CONFIGOPTIONS, &bMemoryError));
    1788     4857790 :     if (papszTLConfigOptions != nullptr)
    1789     4461140 :         pszResult = CSLFetchNameValue(papszTLConfigOptions, pszKey);
    1790             : 
    1791     4858060 :     if (pszResult == nullptr)
    1792     4820120 :         return pszDefault;
    1793             : 
    1794       37938 :     return pszResult;
    1795             : }
    1796             : 
    1797             : /************************************************************************/
    1798             : /*                   CPLGetGlobalConfigOption()                         */
    1799             : /************************************************************************/
    1800             : 
    1801             : /** Same as CPLGetConfigOption() but excludes environment variables and
    1802             :  *  options set with CPLSetThreadLocalConfigOption().
    1803             :  *  This function should generally not be used by applications, which should
    1804             :  *  use CPLGetConfigOption() instead.
    1805             :  *  @since 3.8 */
    1806     4796970 : const char *CPL_STDCALL CPLGetGlobalConfigOption(const char *pszKey,
    1807             :                                                  const char *pszDefault)
    1808             : {
    1809             : #ifdef DEBUG_CONFIG_OPTIONS
    1810             :     CPLAccessConfigOption(pszKey, TRUE);
    1811             : #endif
    1812             : 
    1813     9595080 :     CPLMutexHolderD(&hConfigMutex);
    1814             : 
    1815             :     const char *pszResult =
    1816     4798110 :         CSLFetchNameValue(const_cast<char **>(g_papszConfigOptions), pszKey);
    1817             : 
    1818     4798110 :     if (pszResult == nullptr)
    1819     4790240 :         return pszDefault;
    1820             : 
    1821        7875 :     return pszResult;
    1822             : }
    1823             : 
    1824             : /************************************************************************/
    1825             : /*                    CPLSubscribeToSetConfigOption()                   */
    1826             : /************************************************************************/
    1827             : 
    1828             : /**
    1829             :  * Install a callback that will be notified of calls to CPLSetConfigOption()/
    1830             :  * CPLSetThreadLocalConfigOption()
    1831             :  *
    1832             :  * @param pfnCallback Callback. Must not be NULL
    1833             :  * @param pUserData Callback user data. May be NULL.
    1834             :  * @return subscriber ID that can be used with CPLUnsubscribeToSetConfigOption()
    1835             :  * @since GDAL 3.7
    1836             :  */
    1837             : 
    1838        1205 : int CPLSubscribeToSetConfigOption(CPLSetConfigOptionSubscriber pfnCallback,
    1839             :                                   void *pUserData)
    1840             : {
    1841        2410 :     CPLMutexHolderD(&hConfigMutex);
    1842        1210 :     for (int nId = 0;
    1843        1210 :          nId < static_cast<int>(gSetConfigOptionSubscribers.size()); ++nId)
    1844             :     {
    1845           6 :         if (!gSetConfigOptionSubscribers[nId].first)
    1846             :         {
    1847           1 :             gSetConfigOptionSubscribers[nId].first = pfnCallback;
    1848           1 :             gSetConfigOptionSubscribers[nId].second = pUserData;
    1849           1 :             return nId;
    1850             :         }
    1851             :     }
    1852        1204 :     int nId = static_cast<int>(gSetConfigOptionSubscribers.size());
    1853        1204 :     gSetConfigOptionSubscribers.push_back(
    1854        1204 :         std::pair<CPLSetConfigOptionSubscriber, void *>(pfnCallback,
    1855             :                                                         pUserData));
    1856        1204 :     return nId;
    1857             : }
    1858             : 
    1859             : /************************************************************************/
    1860             : /*                  CPLUnsubscribeToSetConfigOption()                   */
    1861             : /************************************************************************/
    1862             : 
    1863             : /**
    1864             :  * Remove a subscriber installed with CPLSubscribeToSetConfigOption()
    1865             :  *
    1866             :  * @param nId Subscriber id returned by CPLSubscribeToSetConfigOption()
    1867             :  * @since GDAL 3.7
    1868             :  */
    1869             : 
    1870           4 : void CPLUnsubscribeToSetConfigOption(int nId)
    1871             : {
    1872           8 :     CPLMutexHolderD(&hConfigMutex);
    1873           4 :     if (nId == static_cast<int>(gSetConfigOptionSubscribers.size()) - 1)
    1874             :     {
    1875           3 :         gSetConfigOptionSubscribers.resize(gSetConfigOptionSubscribers.size() -
    1876             :                                            1);
    1877             :     }
    1878           2 :     else if (nId >= 0 &&
    1879           1 :              nId < static_cast<int>(gSetConfigOptionSubscribers.size()))
    1880             :     {
    1881           1 :         gSetConfigOptionSubscribers[nId].first = nullptr;
    1882             :     }
    1883           4 : }
    1884             : 
    1885             : /************************************************************************/
    1886             : /*                  NotifyOtherComponentsConfigOptionChanged()          */
    1887             : /************************************************************************/
    1888             : 
    1889       61960 : static void NotifyOtherComponentsConfigOptionChanged(const char *pszKey,
    1890             :                                                      const char *pszValue,
    1891             :                                                      bool bThreadLocal)
    1892             : {
    1893             :     // Hack
    1894       61960 :     if (STARTS_WITH_CI(pszKey, "AWS_"))
    1895        2352 :         VSICurlAuthParametersChanged();
    1896             : 
    1897       61960 :     if (!gSetConfigOptionSubscribers.empty())
    1898             :     {
    1899      122360 :         for (const auto &iter : gSetConfigOptionSubscribers)
    1900             :         {
    1901       61392 :             if (iter.first)
    1902       61491 :                 iter.first(pszKey, pszValue, bThreadLocal, iter.second);
    1903             :         }
    1904             :     }
    1905       61660 : }
    1906             : 
    1907             : /************************************************************************/
    1908             : /*                       CPLIsDebugEnabled()                            */
    1909             : /************************************************************************/
    1910             : 
    1911             : static int gnDebug = -1;
    1912             : 
    1913             : /** Returns whether CPL_DEBUG is enabled.
    1914             :  *
    1915             :  * @since 3.11
    1916             :  */
    1917       67281 : bool CPLIsDebugEnabled()
    1918             : {
    1919       67281 :     if (gnDebug < 0)
    1920             :     {
    1921             :         // Check that apszKnownConfigOptions is correctly sorted with
    1922             :         // STRCASECMP() criterion.
    1923      477609 :         for (size_t i = 1; i < CPL_ARRAYSIZE(apszKnownConfigOptions); ++i)
    1924             :         {
    1925      477158 :             if (STRCASECMP(apszKnownConfigOptions[i - 1],
    1926             :                            apszKnownConfigOptions[i]) >= 0)
    1927             :             {
    1928           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    1929             :                          "ERROR: apszKnownConfigOptions[] isn't correctly "
    1930             :                          "sorted: %s >= %s",
    1931           0 :                          apszKnownConfigOptions[i - 1],
    1932           0 :                          apszKnownConfigOptions[i]);
    1933             :             }
    1934             :         }
    1935         451 :         gnDebug = CPLTestBool(CPLGetConfigOption("CPL_DEBUG", "OFF"));
    1936             :     }
    1937             : 
    1938       67255 :     return gnDebug != 0;
    1939             : }
    1940             : 
    1941             : /************************************************************************/
    1942             : /*                       CPLDeclareKnownConfigOption()                  */
    1943             : /************************************************************************/
    1944             : 
    1945             : static std::mutex goMutexDeclaredKnownConfigOptions;
    1946             : static std::set<CPLString> goSetKnownConfigOptions;
    1947             : 
    1948             : /** Declare that the specified configuration option is known.
    1949             :  *
    1950             :  * This is useful to avoid a warning to be emitted on unknown configuration
    1951             :  * options when CPL_DEBUG is enabled.
    1952             :  *
    1953             :  * @param pszKey Name of the configuration option to declare.
    1954             :  * @param pszDefinition Unused for now. Must be set to nullptr.
    1955             :  * @since 3.11
    1956             :  */
    1957           1 : void CPLDeclareKnownConfigOption(const char *pszKey,
    1958             :                                  [[maybe_unused]] const char *pszDefinition)
    1959             : {
    1960           1 :     std::lock_guard oLock(goMutexDeclaredKnownConfigOptions);
    1961           1 :     goSetKnownConfigOptions.insert(CPLString(pszKey).toupper());
    1962           1 : }
    1963             : 
    1964             : /************************************************************************/
    1965             : /*                       CPLGetKnownConfigOptions()                     */
    1966             : /************************************************************************/
    1967             : 
    1968             : /** Return the list of known configuration options.
    1969             :  *
    1970             :  * Must be freed with CSLDestroy().
    1971             :  * @since 3.11
    1972             :  */
    1973           3 : char **CPLGetKnownConfigOptions()
    1974             : {
    1975           6 :     std::lock_guard oLock(goMutexDeclaredKnownConfigOptions);
    1976           6 :     CPLStringList aosList;
    1977        3180 :     for (const char *pszKey : apszKnownConfigOptions)
    1978        3177 :         aosList.AddString(pszKey);
    1979           4 :     for (const auto &osKey : goSetKnownConfigOptions)
    1980           1 :         aosList.AddString(osKey);
    1981           6 :     return aosList.StealList();
    1982             : }
    1983             : 
    1984             : /************************************************************************/
    1985             : /*           CPLSetConfigOptionDetectUnknownConfigOption()              */
    1986             : /************************************************************************/
    1987             : 
    1988       62018 : static void CPLSetConfigOptionDetectUnknownConfigOption(const char *pszKey,
    1989             :                                                         const char *pszValue)
    1990             : {
    1991       62018 :     if (EQUAL(pszKey, "CPL_DEBUG"))
    1992             :     {
    1993         100 :         gnDebug = pszValue ? CPLTestBool(pszValue) : false;
    1994             :     }
    1995       61918 :     else if (CPLIsDebugEnabled())
    1996             :     {
    1997          89 :         if (!std::binary_search(std::begin(apszKnownConfigOptions),
    1998             :                                 std::end(apszKnownConfigOptions), pszKey,
    1999         983 :                                 [](const char *a, const char *b)
    2000         983 :                                 { return STRCASECMP(a, b) < 0; }))
    2001             :         {
    2002             :             bool bFound;
    2003             :             {
    2004           4 :                 std::lock_guard oLock(goMutexDeclaredKnownConfigOptions);
    2005           8 :                 bFound = cpl::contains(goSetKnownConfigOptions,
    2006           4 :                                        CPLString(pszKey).toupper());
    2007             :             }
    2008           4 :             if (!bFound)
    2009             :             {
    2010           2 :                 const char *pszOldValue = CPLGetConfigOption(pszKey, nullptr);
    2011           2 :                 if (!((!pszValue && !pszOldValue) ||
    2012           1 :                       (pszValue && pszOldValue &&
    2013           0 :                        EQUAL(pszValue, pszOldValue))))
    2014             :                 {
    2015           2 :                     CPLError(CE_Warning, CPLE_AppDefined,
    2016             :                              "Unknown configuration option '%s'.", pszKey);
    2017             :                 }
    2018             :             }
    2019             :         }
    2020             :     }
    2021       61877 : }
    2022             : 
    2023             : /************************************************************************/
    2024             : /*                         CPLSetConfigOption()                         */
    2025             : /************************************************************************/
    2026             : 
    2027             : /**
    2028             :  * Set a configuration option for GDAL/OGR use.
    2029             :  *
    2030             :  * Those options are defined as a (key, value) couple. The value corresponding
    2031             :  * to a key can be got later with the CPLGetConfigOption() method.
    2032             :  *
    2033             :  * This mechanism is similar to environment variables, but options set with
    2034             :  * CPLSetConfigOption() overrides, for CPLGetConfigOption() point of view,
    2035             :  * values defined in the environment.
    2036             :  *
    2037             :  * If CPLSetConfigOption() is called several times with the same key, the
    2038             :  * value provided during the last call will be used.
    2039             :  *
    2040             :  * Options can also be passed on the command line of most GDAL utilities
    2041             :  * with '--config KEY VALUE' (or '--config KEY=VALUE' since GDAL 3.10).
    2042             :  * For example, ogrinfo --config CPL_DEBUG ON ~/data/test/point.shp
    2043             :  *
    2044             :  * This function can also be used to clear a setting by passing NULL as the
    2045             :  * value (note: passing NULL will not unset an existing environment variable;
    2046             :  * it will just unset a value previously set by CPLSetConfigOption()).
    2047             :  *
    2048             :  * Starting with GDAL 3.11, if CPL_DEBUG is enabled prior to this call, and
    2049             :  * CPLSetConfigOption() is called with a key that is neither a known
    2050             :  * configuration option of GDAL itself, or one that has been declared with
    2051             :  * CPLDeclareKnownConfigOption(), a warning will be emitted.
    2052             :  *
    2053             :  * @param pszKey the key of the option
    2054             :  * @param pszValue the value of the option, or NULL to clear a setting.
    2055             :  *
    2056             :  * @see https://gdal.org/user/configoptions.html
    2057             :  */
    2058        4758 : void CPL_STDCALL CPLSetConfigOption(const char *pszKey, const char *pszValue)
    2059             : 
    2060             : {
    2061             : #ifdef DEBUG_CONFIG_OPTIONS
    2062             :     CPLAccessConfigOption(pszKey, FALSE);
    2063             : #endif
    2064        9516 :     CPLMutexHolderD(&hConfigMutex);
    2065             : 
    2066             : #ifdef OGRAPISPY_ENABLED
    2067        4758 :     OGRAPISPYCPLSetConfigOption(pszKey, pszValue);
    2068             : #endif
    2069             : 
    2070        4758 :     CPLSetConfigOptionDetectUnknownConfigOption(pszKey, pszValue);
    2071             : 
    2072        4758 :     g_papszConfigOptions = const_cast<volatile char **>(CSLSetNameValue(
    2073             :         const_cast<char **>(g_papszConfigOptions), pszKey, pszValue));
    2074             : 
    2075        4758 :     NotifyOtherComponentsConfigOptionChanged(pszKey, pszValue,
    2076             :                                              /*bTheadLocal=*/false);
    2077        4758 : }
    2078             : 
    2079             : /************************************************************************/
    2080             : /*                   CPLSetThreadLocalTLSFreeFunc()                     */
    2081             : /************************************************************************/
    2082             : 
    2083             : /* non-stdcall wrapper function for CSLDestroy() (#5590) */
    2084           6 : static void CPLSetThreadLocalTLSFreeFunc(void *pData)
    2085             : {
    2086           6 :     CSLDestroy(reinterpret_cast<char **>(pData));
    2087           6 : }
    2088             : 
    2089             : /************************************************************************/
    2090             : /*                   CPLSetThreadLocalConfigOption()                    */
    2091             : /************************************************************************/
    2092             : 
    2093             : /**
    2094             :  * Set a configuration option for GDAL/OGR use.
    2095             :  *
    2096             :  * Those options are defined as a (key, value) couple. The value corresponding
    2097             :  * to a key can be got later with the CPLGetConfigOption() method.
    2098             :  *
    2099             :  * This function sets the configuration option that only applies in the
    2100             :  * current thread, as opposed to CPLSetConfigOption() which sets an option
    2101             :  * that applies on all threads. CPLSetThreadLocalConfigOption() will override
    2102             :  * the effect of CPLSetConfigOption) for the current thread.
    2103             :  *
    2104             :  * This function can also be used to clear a setting by passing NULL as the
    2105             :  * value (note: passing NULL will not unset an existing environment variable or
    2106             :  * a value set through CPLSetConfigOption();
    2107             :  * it will just unset a value previously set by
    2108             :  * CPLSetThreadLocalConfigOption()).
    2109             :  *
    2110             :  * @param pszKey the key of the option
    2111             :  * @param pszValue the value of the option, or NULL to clear a setting.
    2112             :  */
    2113             : 
    2114       57327 : void CPL_STDCALL CPLSetThreadLocalConfigOption(const char *pszKey,
    2115             :                                                const char *pszValue)
    2116             : 
    2117             : {
    2118             : #ifdef DEBUG_CONFIG_OPTIONS
    2119             :     CPLAccessConfigOption(pszKey, FALSE);
    2120             : #endif
    2121             : 
    2122             : #ifdef OGRAPISPY_ENABLED
    2123       57327 :     OGRAPISPYCPLSetThreadLocalConfigOption(pszKey, pszValue);
    2124             : #endif
    2125             : 
    2126       57207 :     int bMemoryError = FALSE;
    2127             :     char **papszTLConfigOptions = reinterpret_cast<char **>(
    2128       57207 :         CPLGetTLSEx(CTLS_CONFIGOPTIONS, &bMemoryError));
    2129       57218 :     if (bMemoryError)
    2130           0 :         return;
    2131             : 
    2132       57218 :     CPLSetConfigOptionDetectUnknownConfigOption(pszKey, pszValue);
    2133             : 
    2134             :     papszTLConfigOptions =
    2135       57065 :         CSLSetNameValue(papszTLConfigOptions, pszKey, pszValue);
    2136             : 
    2137       57157 :     CPLSetTLSWithFreeFunc(CTLS_CONFIGOPTIONS, papszTLConfigOptions,
    2138             :                           CPLSetThreadLocalTLSFreeFunc);
    2139             : 
    2140       57014 :     NotifyOtherComponentsConfigOptionChanged(pszKey, pszValue,
    2141             :                                              /*bTheadLocal=*/true);
    2142             : }
    2143             : 
    2144             : /************************************************************************/
    2145             : /*                   CPLGetThreadLocalConfigOptions()                   */
    2146             : /************************************************************************/
    2147             : 
    2148             : /**
    2149             :  * Return the list of thread local configuration options as KEY=VALUE pairs.
    2150             :  *
    2151             :  * Options that through environment variables or with
    2152             :  * CPLSetConfigOption() will *not* be listed.
    2153             :  *
    2154             :  * @return a copy of the list, to be freed with CSLDestroy().
    2155             :  * @since GDAL 2.2
    2156             :  */
    2157      737591 : char **CPLGetThreadLocalConfigOptions(void)
    2158             : {
    2159      737591 :     int bMemoryError = FALSE;
    2160             :     char **papszTLConfigOptions = reinterpret_cast<char **>(
    2161      737591 :         CPLGetTLSEx(CTLS_CONFIGOPTIONS, &bMemoryError));
    2162      730274 :     if (bMemoryError)
    2163           0 :         return nullptr;
    2164      730274 :     return CSLDuplicate(papszTLConfigOptions);
    2165             : }
    2166             : 
    2167             : /************************************************************************/
    2168             : /*                   CPLSetThreadLocalConfigOptions()                   */
    2169             : /************************************************************************/
    2170             : 
    2171             : /**
    2172             :  * Replace the full list of thread local configuration options with the
    2173             :  * passed list of KEY=VALUE pairs.
    2174             :  *
    2175             :  * This has the same effect of clearing the existing list, and setting
    2176             :  * individually each pair with the CPLSetThreadLocalConfigOption() API.
    2177             :  *
    2178             :  * This does not affect options set through environment variables or with
    2179             :  * CPLSetConfigOption().
    2180             :  *
    2181             :  * The passed list is copied by the function.
    2182             :  *
    2183             :  * @param papszConfigOptions the new list (or NULL).
    2184             :  *
    2185             :  * @since GDAL 2.2
    2186             :  */
    2187     1480750 : void CPLSetThreadLocalConfigOptions(const char *const *papszConfigOptions)
    2188             : {
    2189     1480750 :     int bMemoryError = FALSE;
    2190             :     char **papszTLConfigOptions = reinterpret_cast<char **>(
    2191     1480750 :         CPLGetTLSEx(CTLS_CONFIGOPTIONS, &bMemoryError));
    2192     1457530 :     if (bMemoryError)
    2193           0 :         return;
    2194     1457530 :     CSLDestroy(papszTLConfigOptions);
    2195             :     papszTLConfigOptions =
    2196     1458840 :         CSLDuplicate(const_cast<char **>(papszConfigOptions));
    2197     1466620 :     CPLSetTLSWithFreeFunc(CTLS_CONFIGOPTIONS, papszTLConfigOptions,
    2198             :                           CPLSetThreadLocalTLSFreeFunc);
    2199             : }
    2200             : 
    2201             : /************************************************************************/
    2202             : /*                           CPLFreeConfig()                            */
    2203             : /************************************************************************/
    2204             : 
    2205        1381 : void CPL_STDCALL CPLFreeConfig()
    2206             : 
    2207             : {
    2208             :     {
    2209        2762 :         CPLMutexHolderD(&hConfigMutex);
    2210             : 
    2211        1381 :         CSLDestroy(const_cast<char **>(g_papszConfigOptions));
    2212        1381 :         g_papszConfigOptions = nullptr;
    2213             : 
    2214        1381 :         int bMemoryError = FALSE;
    2215             :         char **papszTLConfigOptions = reinterpret_cast<char **>(
    2216        1381 :             CPLGetTLSEx(CTLS_CONFIGOPTIONS, &bMemoryError));
    2217        1381 :         if (papszTLConfigOptions != nullptr)
    2218             :         {
    2219         221 :             CSLDestroy(papszTLConfigOptions);
    2220         221 :             CPLSetTLS(CTLS_CONFIGOPTIONS, nullptr, FALSE);
    2221             :         }
    2222             :     }
    2223        1381 :     CPLDestroyMutex(hConfigMutex);
    2224        1381 :     hConfigMutex = nullptr;
    2225        1381 : }
    2226             : 
    2227             : /************************************************************************/
    2228             : /*                    CPLLoadConfigOptionsFromFile()                    */
    2229             : /************************************************************************/
    2230             : 
    2231             : /** Load configuration from a given configuration file.
    2232             : 
    2233             : A configuration file is a text file in a .ini style format, that lists
    2234             : configuration options and their values.
    2235             : Lines starting with # are comment lines.
    2236             : 
    2237             : Example:
    2238             : \verbatim
    2239             : [configoptions]
    2240             : # set BAR as the value of configuration option FOO
    2241             : FOO=BAR
    2242             : \endverbatim
    2243             : 
    2244             : Starting with GDAL 3.5, a configuration file can also contain credentials
    2245             : (or more generally options related to a virtual file system) for a given path
    2246             : prefix, that can also be set with VSISetPathSpecificOption(). Credentials should
    2247             : be put under a [credentials] section, and for each path prefix, under a relative
    2248             : subsection whose name starts with "[." (e.g. "[.some_arbitrary_name]"), and
    2249             : whose first key is "path".
    2250             : 
    2251             : Example:
    2252             : \verbatim
    2253             : [credentials]
    2254             : 
    2255             : [.private_bucket]
    2256             : path=/vsis3/my_private_bucket
    2257             : AWS_SECRET_ACCESS_KEY=...
    2258             : AWS_ACCESS_KEY_ID=...
    2259             : 
    2260             : [.sentinel_s2_l1c]
    2261             : path=/vsis3/sentinel-s2-l1c
    2262             : AWS_REQUEST_PAYER=requester
    2263             : \endverbatim
    2264             : 
    2265             : Starting with GDAL 3.6, a leading [directives] section might be added with
    2266             : a "ignore-env-vars=yes" setting to indicate that, starting with that point,
    2267             : all environment variables should be ignored, and only configuration options
    2268             : defined in the [configoptions] sections or through the CPLSetConfigOption() /
    2269             : CPLSetThreadLocalConfigOption() functions should be taken into account.
    2270             : 
    2271             : This function is typically called by CPLLoadConfigOptionsFromPredefinedFiles()
    2272             : 
    2273             : @param pszFilename File where to load configuration from.
    2274             : @param bOverrideEnvVars Whether configuration options from the configuration
    2275             :                         file should override environment variables.
    2276             : @since GDAL 3.3
    2277             :  */
    2278        2776 : void CPLLoadConfigOptionsFromFile(const char *pszFilename, int bOverrideEnvVars)
    2279             : {
    2280        2776 :     VSILFILE *fp = VSIFOpenL(pszFilename, "rb");
    2281        2776 :     if (fp == nullptr)
    2282        2767 :         return;
    2283           9 :     CPLDebug("CPL", "Loading configuration from %s", pszFilename);
    2284             :     const char *pszLine;
    2285             :     enum class Section
    2286             :     {
    2287             :         NONE,
    2288             :         GENERAL,
    2289             :         CONFIG_OPTIONS,
    2290             :         CREDENTIALS,
    2291             :     };
    2292           9 :     Section eCurrentSection = Section::NONE;
    2293           9 :     bool bInSubsection = false;
    2294          18 :     std::string osPath;
    2295           9 :     int nSectionCounter = 0;
    2296             : 
    2297          56 :     const auto IsSpaceOnly = [](const char *pszStr)
    2298             :     {
    2299          56 :         for (; *pszStr; ++pszStr)
    2300             :         {
    2301          47 :             if (!isspace(static_cast<unsigned char>(*pszStr)))
    2302          41 :                 return false;
    2303             :         }
    2304           9 :         return true;
    2305             :     };
    2306             : 
    2307          59 :     while ((pszLine = CPLReadLine2L(fp, -1, nullptr)) != nullptr)
    2308             :     {
    2309          50 :         if (IsSpaceOnly(pszLine))
    2310             :         {
    2311             :             // Blank line
    2312             :         }
    2313          41 :         else if (pszLine[0] == '#')
    2314             :         {
    2315             :             // Comment line
    2316             :         }
    2317          35 :         else if (strcmp(pszLine, "[configoptions]") == 0)
    2318             :         {
    2319           6 :             nSectionCounter++;
    2320           6 :             eCurrentSection = Section::CONFIG_OPTIONS;
    2321             :         }
    2322          29 :         else if (strcmp(pszLine, "[credentials]") == 0)
    2323             :         {
    2324           4 :             nSectionCounter++;
    2325           4 :             eCurrentSection = Section::CREDENTIALS;
    2326           4 :             bInSubsection = false;
    2327           4 :             osPath.clear();
    2328             :         }
    2329          25 :         else if (strcmp(pszLine, "[directives]") == 0)
    2330             :         {
    2331           2 :             nSectionCounter++;
    2332           2 :             if (nSectionCounter != 1)
    2333             :             {
    2334           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    2335             :                          "The [directives] section should be the first one in "
    2336             :                          "the file, otherwise some its settings might not be "
    2337             :                          "used correctly.");
    2338             :             }
    2339           2 :             eCurrentSection = Section::GENERAL;
    2340             :         }
    2341          23 :         else if (eCurrentSection == Section::GENERAL)
    2342             :         {
    2343           2 :             char *pszKey = nullptr;
    2344           2 :             const char *pszValue = CPLParseNameValue(pszLine, &pszKey);
    2345           2 :             if (pszKey && pszValue)
    2346             :             {
    2347           2 :                 if (strcmp(pszKey, "ignore-env-vars") == 0)
    2348             :                 {
    2349           2 :                     gbIgnoreEnvVariables = CPLTestBool(pszValue);
    2350             :                 }
    2351             :                 else
    2352             :                 {
    2353           0 :                     CPLError(CE_Warning, CPLE_AppDefined,
    2354             :                              "Ignoring %s line in [directives] section",
    2355             :                              pszLine);
    2356             :                 }
    2357             :             }
    2358           2 :             CPLFree(pszKey);
    2359             :         }
    2360          21 :         else if (eCurrentSection == Section::CREDENTIALS)
    2361             :         {
    2362          15 :             if (strncmp(pszLine, "[.", 2) == 0)
    2363             :             {
    2364           4 :                 bInSubsection = true;
    2365           4 :                 osPath.clear();
    2366             :             }
    2367          11 :             else if (bInSubsection)
    2368             :             {
    2369          10 :                 char *pszKey = nullptr;
    2370          10 :                 const char *pszValue = CPLParseNameValue(pszLine, &pszKey);
    2371          10 :                 if (pszKey && pszValue)
    2372             :                 {
    2373          10 :                     if (strcmp(pszKey, "path") == 0)
    2374             :                     {
    2375           4 :                         if (!osPath.empty())
    2376             :                         {
    2377           1 :                             CPLError(
    2378             :                                 CE_Warning, CPLE_AppDefined,
    2379             :                                 "Duplicated 'path' key in the same subsection. "
    2380             :                                 "Ignoring %s=%s",
    2381             :                                 pszKey, pszValue);
    2382             :                         }
    2383             :                         else
    2384             :                         {
    2385           3 :                             osPath = pszValue;
    2386             :                         }
    2387             :                     }
    2388           6 :                     else if (osPath.empty())
    2389             :                     {
    2390           1 :                         CPLError(CE_Warning, CPLE_AppDefined,
    2391             :                                  "First entry in a credentials subsection "
    2392             :                                  "should be 'path'.");
    2393             :                     }
    2394             :                     else
    2395             :                     {
    2396           5 :                         VSISetPathSpecificOption(osPath.c_str(), pszKey,
    2397             :                                                  pszValue);
    2398             :                     }
    2399             :                 }
    2400          10 :                 CPLFree(pszKey);
    2401             :             }
    2402           1 :             else if (pszLine[0] == '[')
    2403             :             {
    2404           0 :                 eCurrentSection = Section::NONE;
    2405             :             }
    2406             :             else
    2407             :             {
    2408           1 :                 CPLError(CE_Warning, CPLE_AppDefined,
    2409             :                          "Ignoring content in [credential] section that is not "
    2410             :                          "in a [.xxxxx] subsection");
    2411             :             }
    2412             :         }
    2413           6 :         else if (pszLine[0] == '[')
    2414             :         {
    2415           0 :             eCurrentSection = Section::NONE;
    2416             :         }
    2417           6 :         else if (eCurrentSection == Section::CONFIG_OPTIONS)
    2418             :         {
    2419           6 :             char *pszKey = nullptr;
    2420           6 :             const char *pszValue = CPLParseNameValue(pszLine, &pszKey);
    2421           6 :             if (pszKey && pszValue)
    2422             :             {
    2423          11 :                 if (bOverrideEnvVars || gbIgnoreEnvVariables ||
    2424           5 :                     getenv(pszKey) == nullptr)
    2425             :                 {
    2426           5 :                     CPLDebugOnly("CPL", "Setting configuration option %s=%s",
    2427             :                                  pszKey, pszValue);
    2428           5 :                     CPLSetConfigOption(pszKey, pszValue);
    2429             :                 }
    2430             :                 else
    2431             :                 {
    2432           1 :                     CPLDebug("CPL",
    2433             :                              "Ignoring configuration option %s=%s from "
    2434             :                              "configuration file as it is already set "
    2435             :                              "as an environment variable",
    2436             :                              pszKey, pszValue);
    2437             :                 }
    2438             :             }
    2439           6 :             CPLFree(pszKey);
    2440             :         }
    2441             :     }
    2442           9 :     VSIFCloseL(fp);
    2443             : }
    2444             : 
    2445             : /************************************************************************/
    2446             : /*                CPLLoadConfigOptionsFromPredefinedFiles()             */
    2447             : /************************************************************************/
    2448             : 
    2449             : /** Load configuration from a set of predefined files.
    2450             :  *
    2451             :  * If the environment variable (or configuration option) GDAL_CONFIG_FILE is
    2452             :  * set, then CPLLoadConfigOptionsFromFile() will be called with the value of
    2453             :  * this configuration option as the file location.
    2454             :  *
    2455             :  * Otherwise, for Unix builds, CPLLoadConfigOptionsFromFile() will be called
    2456             :  * with ${sysconfdir}/gdal/gdalrc first where ${sysconfdir} evaluates
    2457             :  * to ${prefix}/etc, unless the --sysconfdir switch of configure has been
    2458             :  * invoked.
    2459             :  *
    2460             :  * Then CPLLoadConfigOptionsFromFile() will be called with $(HOME)/.gdal/gdalrc
    2461             :  * on Unix builds (potentially overriding what was loaded with the sysconfdir)
    2462             :  * or $(USERPROFILE)/.gdal/gdalrc on Windows builds.
    2463             :  *
    2464             :  * CPLLoadConfigOptionsFromFile() will be called with bOverrideEnvVars = false,
    2465             :  * that is the value of environment variables previously set will be used
    2466             :  * instead of the value set in the configuration files (unless the configuration
    2467             :  * file contains a leading [directives] section with a "ignore-env-vars=yes"
    2468             :  * setting).
    2469             :  *
    2470             :  * This function is automatically called by GDALDriverManager() constructor
    2471             :  *
    2472             :  * @since GDAL 3.3
    2473             :  */
    2474        1385 : void CPLLoadConfigOptionsFromPredefinedFiles()
    2475             : {
    2476        1385 :     const char *pszFile = CPLGetConfigOption("GDAL_CONFIG_FILE", nullptr);
    2477        1385 :     if (pszFile != nullptr)
    2478             :     {
    2479           2 :         CPLLoadConfigOptionsFromFile(pszFile, false);
    2480             :     }
    2481             :     else
    2482             :     {
    2483             : #ifdef SYSCONFDIR
    2484        1383 :         CPLLoadConfigOptionsFromFile(
    2485        2766 :             CPLFormFilenameSafe(
    2486        2766 :                 CPLFormFilenameSafe(SYSCONFDIR, "gdal", nullptr).c_str(),
    2487             :                 "gdalrc", nullptr)
    2488             :                 .c_str(),
    2489             :             false);
    2490             : #endif
    2491             : 
    2492             : #ifdef _WIN32
    2493             :         const char *pszHome = CPLGetConfigOption("USERPROFILE", nullptr);
    2494             : #else
    2495        1383 :         const char *pszHome = CPLGetConfigOption("HOME", nullptr);
    2496             : #endif
    2497        1383 :         if (pszHome != nullptr)
    2498             :         {
    2499        1383 :             CPLLoadConfigOptionsFromFile(
    2500        2766 :                 CPLFormFilenameSafe(
    2501        2766 :                     CPLFormFilenameSafe(pszHome, ".gdal", nullptr).c_str(),
    2502             :                     "gdalrc", nullptr)
    2503             :                     .c_str(),
    2504             :                 false);
    2505             :         }
    2506             :     }
    2507        1385 : }
    2508             : 
    2509             : /************************************************************************/
    2510             : /*                              CPLStat()                               */
    2511             : /************************************************************************/
    2512             : 
    2513             : /** Same as VSIStat() except it works on "C:" as if it were "C:\". */
    2514             : 
    2515          66 : int CPLStat(const char *pszPath, VSIStatBuf *psStatBuf)
    2516             : 
    2517             : {
    2518          66 :     if (strlen(pszPath) == 2 && pszPath[1] == ':')
    2519             :     {
    2520           0 :         char szAltPath[4] = {pszPath[0], pszPath[1], '\\', '\0'};
    2521           0 :         return VSIStat(szAltPath, psStatBuf);
    2522             :     }
    2523             : 
    2524          66 :     return VSIStat(pszPath, psStatBuf);
    2525             : }
    2526             : 
    2527             : /************************************************************************/
    2528             : /*                            proj_strtod()                             */
    2529             : /************************************************************************/
    2530          20 : static double proj_strtod(char *nptr, char **endptr)
    2531             : 
    2532             : {
    2533          20 :     char c = '\0';
    2534          20 :     char *cp = nptr;
    2535             : 
    2536             :     // Scan for characters which cause problems with VC++ strtod().
    2537          92 :     while ((c = *cp) != '\0')
    2538             :     {
    2539          78 :         if (c == 'd' || c == 'D')
    2540             :         {
    2541             :             // Found one, so NUL it out, call strtod(),
    2542             :             // then restore it and return.
    2543           6 :             *cp = '\0';
    2544           6 :             const double result = CPLStrtod(nptr, endptr);
    2545           6 :             *cp = c;
    2546           6 :             return result;
    2547             :         }
    2548          72 :         ++cp;
    2549             :     }
    2550             : 
    2551             :     // No offending characters, just handle normally.
    2552             : 
    2553          14 :     return CPLStrtod(nptr, endptr);
    2554             : }
    2555             : 
    2556             : /************************************************************************/
    2557             : /*                            CPLDMSToDec()                             */
    2558             : /************************************************************************/
    2559             : 
    2560             : static const char *sym = "NnEeSsWw";
    2561             : constexpr double vm[] = {1.0, 0.0166666666667, 0.00027777778};
    2562             : 
    2563             : /** CPLDMSToDec */
    2564           8 : double CPLDMSToDec(const char *is)
    2565             : 
    2566             : {
    2567             :     // Copy string into work space.
    2568           8 :     while (isspace(static_cast<unsigned char>(*is)))
    2569           0 :         ++is;
    2570             : 
    2571           8 :     const char *p = is;
    2572           8 :     char work[64] = {};
    2573           8 :     char *s = work;
    2574           8 :     int n = sizeof(work);
    2575          68 :     for (; isgraph(*p) && --n;)
    2576          60 :         *s++ = *p++;
    2577           8 :     *s = '\0';
    2578             :     // It is possible that a really odd input (like lots of leading
    2579             :     // zeros) could be truncated in copying into work.  But...
    2580           8 :     s = work;
    2581           8 :     int sign = *s;
    2582             : 
    2583           8 :     if (sign == '+' || sign == '-')
    2584           0 :         s++;
    2585             :     else
    2586           8 :         sign = '+';
    2587             : 
    2588           8 :     int nl = 0;
    2589           8 :     double v = 0.0;
    2590          28 :     for (; nl < 3; nl = n + 1)
    2591             :     {
    2592          20 :         if (!(isdigit(static_cast<unsigned char>(*s)) || *s == '.'))
    2593           0 :             break;
    2594          20 :         const double tv = proj_strtod(s, &s);
    2595          20 :         if (tv == HUGE_VAL)
    2596           0 :             return tv;
    2597          20 :         switch (*s)
    2598             :         {
    2599           6 :             case 'D':
    2600             :             case 'd':
    2601           6 :                 n = 0;
    2602           6 :                 break;
    2603           6 :             case '\'':
    2604           6 :                 n = 1;
    2605           6 :                 break;
    2606           6 :             case '"':
    2607           6 :                 n = 2;
    2608           6 :                 break;
    2609           0 :             case 'r':
    2610             :             case 'R':
    2611           0 :                 if (nl)
    2612             :                 {
    2613           0 :                     return 0.0;
    2614             :                 }
    2615           0 :                 ++s;
    2616           0 :                 v = tv;
    2617           0 :                 goto skip;
    2618           2 :             default:
    2619           2 :                 v += tv * vm[nl];
    2620           2 :             skip:
    2621           2 :                 n = 4;
    2622           2 :                 continue;
    2623             :         }
    2624          18 :         if (n < nl)
    2625             :         {
    2626           0 :             return 0.0;
    2627             :         }
    2628          18 :         v += tv * vm[n];
    2629          18 :         ++s;
    2630             :     }
    2631             :     // Postfix sign.
    2632           8 :     if (*s && ((p = strchr(sym, *s))) != nullptr)
    2633             :     {
    2634           2 :         sign = (p - sym) >= 4 ? '-' : '+';
    2635           2 :         ++s;
    2636             :     }
    2637           8 :     if (sign == '-')
    2638           1 :         v = -v;
    2639             : 
    2640           8 :     return v;
    2641             : }
    2642             : 
    2643             : /************************************************************************/
    2644             : /*                            CPLDecToDMS()                             */
    2645             : /************************************************************************/
    2646             : 
    2647             : /** Translate a decimal degrees value to a DMS string with hemisphere. */
    2648             : 
    2649         550 : const char *CPLDecToDMS(double dfAngle, const char *pszAxis, int nPrecision)
    2650             : 
    2651             : {
    2652         550 :     VALIDATE_POINTER1(pszAxis, "CPLDecToDMS", "");
    2653             : 
    2654         550 :     if (std::isnan(dfAngle))
    2655           0 :         return "Invalid angle";
    2656             : 
    2657         550 :     const double dfEpsilon = (0.5 / 3600.0) * pow(0.1, nPrecision);
    2658         550 :     const double dfABSAngle = std::abs(dfAngle) + dfEpsilon;
    2659         550 :     if (dfABSAngle > 361.0)
    2660             :     {
    2661           0 :         return "Invalid angle";
    2662             :     }
    2663             : 
    2664         550 :     const int nDegrees = static_cast<int>(dfABSAngle);
    2665         550 :     const int nMinutes = static_cast<int>((dfABSAngle - nDegrees) * 60);
    2666         550 :     double dfSeconds = dfABSAngle * 3600 - nDegrees * 3600 - nMinutes * 60;
    2667             : 
    2668         550 :     if (dfSeconds > dfEpsilon * 3600.0)
    2669         544 :         dfSeconds -= dfEpsilon * 3600.0;
    2670             : 
    2671         550 :     const char *pszHemisphere = nullptr;
    2672         550 :     if (EQUAL(pszAxis, "Long") && dfAngle < 0.0)
    2673         238 :         pszHemisphere = "W";
    2674         312 :     else if (EQUAL(pszAxis, "Long"))
    2675          37 :         pszHemisphere = "E";
    2676         275 :     else if (dfAngle < 0.0)
    2677          22 :         pszHemisphere = "S";
    2678             :     else
    2679         253 :         pszHemisphere = "N";
    2680             : 
    2681         550 :     char szFormat[30] = {};
    2682         550 :     CPLsnprintf(szFormat, sizeof(szFormat), "%%3dd%%2d\'%%%d.%df\"%s",
    2683             :                 nPrecision + 3, nPrecision, pszHemisphere);
    2684             : 
    2685             :     static CPL_THREADLOCAL char szBuffer[50] = {};
    2686         550 :     CPLsnprintf(szBuffer, sizeof(szBuffer), szFormat, nDegrees, nMinutes,
    2687             :                 dfSeconds);
    2688             : 
    2689         550 :     return szBuffer;
    2690             : }
    2691             : 
    2692             : /************************************************************************/
    2693             : /*                         CPLPackedDMSToDec()                          */
    2694             : /************************************************************************/
    2695             : 
    2696             : /**
    2697             :  * Convert a packed DMS value (DDDMMMSSS.SS) into decimal degrees.
    2698             :  *
    2699             :  * This function converts a packed DMS angle to seconds. The standard
    2700             :  * packed DMS format is:
    2701             :  *
    2702             :  *  degrees * 1000000 + minutes * 1000 + seconds
    2703             :  *
    2704             :  * Example:     angle = 120025045.25 yields
    2705             :  *              deg = 120
    2706             :  *              min = 25
    2707             :  *              sec = 45.25
    2708             :  *
    2709             :  * The algorithm used for the conversion is as follows:
    2710             :  *
    2711             :  * 1.  The absolute value of the angle is used.
    2712             :  *
    2713             :  * 2.  The degrees are separated out:
    2714             :  *     deg = angle/1000000                    (fractional portion truncated)
    2715             :  *
    2716             :  * 3.  The minutes are separated out:
    2717             :  *     min = (angle - deg * 1000000) / 1000   (fractional portion truncated)
    2718             :  *
    2719             :  * 4.  The seconds are then computed:
    2720             :  *     sec = angle - deg * 1000000 - min * 1000
    2721             :  *
    2722             :  * 5.  The total angle in seconds is computed:
    2723             :  *     sec = deg * 3600.0 + min * 60.0 + sec
    2724             :  *
    2725             :  * 6.  The sign of sec is set to that of the input angle.
    2726             :  *
    2727             :  * Packed DMS values used by the USGS GCTP package and probably by other
    2728             :  * software.
    2729             :  *
    2730             :  * NOTE: This code does not validate input value. If you give the wrong
    2731             :  * value, you will get the wrong result.
    2732             :  *
    2733             :  * @param dfPacked Angle in packed DMS format.
    2734             :  *
    2735             :  * @return Angle in decimal degrees.
    2736             :  *
    2737             :  */
    2738             : 
    2739          34 : double CPLPackedDMSToDec(double dfPacked)
    2740             : {
    2741          34 :     const double dfSign = dfPacked < 0.0 ? -1 : 1;
    2742             : 
    2743          34 :     double dfSeconds = std::abs(dfPacked);
    2744          34 :     double dfDegrees = floor(dfSeconds / 1000000.0);
    2745          34 :     dfSeconds -= dfDegrees * 1000000.0;
    2746          34 :     const double dfMinutes = floor(dfSeconds / 1000.0);
    2747          34 :     dfSeconds -= dfMinutes * 1000.0;
    2748          34 :     dfSeconds = dfSign * (dfDegrees * 3600.0 + dfMinutes * 60.0 + dfSeconds);
    2749          34 :     dfDegrees = dfSeconds / 3600.0;
    2750             : 
    2751          34 :     return dfDegrees;
    2752             : }
    2753             : 
    2754             : /************************************************************************/
    2755             : /*                         CPLDecToPackedDMS()                          */
    2756             : /************************************************************************/
    2757             : /**
    2758             :  * Convert decimal degrees into packed DMS value (DDDMMMSSS.SS).
    2759             :  *
    2760             :  * This function converts a value, specified in decimal degrees into
    2761             :  * packed DMS angle. The standard packed DMS format is:
    2762             :  *
    2763             :  *  degrees * 1000000 + minutes * 1000 + seconds
    2764             :  *
    2765             :  * See also CPLPackedDMSToDec().
    2766             :  *
    2767             :  * @param dfDec Angle in decimal degrees.
    2768             :  *
    2769             :  * @return Angle in packed DMS format.
    2770             :  *
    2771             :  */
    2772             : 
    2773           8 : double CPLDecToPackedDMS(double dfDec)
    2774             : {
    2775           8 :     const double dfSign = dfDec < 0.0 ? -1 : 1;
    2776             : 
    2777           8 :     dfDec = std::abs(dfDec);
    2778           8 :     const double dfDegrees = floor(dfDec);
    2779           8 :     const double dfMinutes = floor((dfDec - dfDegrees) * 60.0);
    2780           8 :     const double dfSeconds = (dfDec - dfDegrees) * 3600.0 - dfMinutes * 60.0;
    2781             : 
    2782           8 :     return dfSign * (dfDegrees * 1000000.0 + dfMinutes * 1000.0 + dfSeconds);
    2783             : }
    2784             : 
    2785             : /************************************************************************/
    2786             : /*                         CPLStringToComplex()                         */
    2787             : /************************************************************************/
    2788             : 
    2789             : /** Fetch the real and imaginary part of a serialized complex number */
    2790        2167 : void CPL_DLL CPLStringToComplex(const char *pszString, double *pdfReal,
    2791             :                                 double *pdfImag)
    2792             : 
    2793             : {
    2794        2167 :     while (*pszString == ' ')
    2795           0 :         pszString++;
    2796             : 
    2797        2167 :     *pdfReal = CPLAtof(pszString);
    2798        2167 :     *pdfImag = 0.0;
    2799             : 
    2800        2167 :     int iPlus = -1;
    2801        2167 :     int iImagEnd = -1;
    2802             : 
    2803        4584 :     for (int i = 0; i < 100 && pszString[i] != '\0' && pszString[i] != ' '; i++)
    2804             :     {
    2805        2417 :         if (pszString[i] == '+' && i > 0)
    2806           0 :             iPlus = i;
    2807        2417 :         if (pszString[i] == '-' && i > 0)
    2808           0 :             iPlus = i;
    2809        2417 :         if (pszString[i] == 'i')
    2810           2 :             iImagEnd = i;
    2811             :     }
    2812             : 
    2813        2167 :     if (iPlus > -1 && iImagEnd > -1 && iPlus < iImagEnd)
    2814             :     {
    2815           0 :         *pdfImag = CPLAtof(pszString + iPlus);
    2816             :     }
    2817             : 
    2818        2167 :     return;
    2819             : }
    2820             : 
    2821             : /************************************************************************/
    2822             : /*                           CPLOpenShared()                            */
    2823             : /************************************************************************/
    2824             : 
    2825             : /**
    2826             :  * Open a shared file handle.
    2827             :  *
    2828             :  * Some operating systems have limits on the number of file handles that can
    2829             :  * be open at one time.  This function attempts to maintain a registry of
    2830             :  * already open file handles, and reuse existing ones if the same file
    2831             :  * is requested by another part of the application.
    2832             :  *
    2833             :  * Note that access is only shared for access types "r", "rb", "r+" and
    2834             :  * "rb+".  All others will just result in direct VSIOpen() calls.  Keep in
    2835             :  * mind that a file is only reused if the file name is exactly the same.
    2836             :  * Different names referring to the same file will result in different
    2837             :  * handles.
    2838             :  *
    2839             :  * The VSIFOpen() or VSIFOpenL() function is used to actually open the file,
    2840             :  * when an existing file handle can't be shared.
    2841             :  *
    2842             :  * @param pszFilename the name of the file to open.
    2843             :  * @param pszAccess the normal fopen()/VSIFOpen() style access string.
    2844             :  * @param bLargeIn If TRUE VSIFOpenL() (for large files) will be used instead of
    2845             :  * VSIFOpen().
    2846             :  *
    2847             :  * @return a file handle or NULL if opening fails.
    2848             :  */
    2849             : 
    2850          35 : FILE *CPLOpenShared(const char *pszFilename, const char *pszAccess,
    2851             :                     int bLargeIn)
    2852             : 
    2853             : {
    2854          35 :     const bool bLarge = CPL_TO_BOOL(bLargeIn);
    2855          70 :     CPLMutexHolderD(&hSharedFileMutex);
    2856          35 :     const GIntBig nPID = CPLGetPID();
    2857             : 
    2858             :     /* -------------------------------------------------------------------- */
    2859             :     /*      Is there an existing file we can use?                           */
    2860             :     /* -------------------------------------------------------------------- */
    2861          35 :     const bool bReuse = EQUAL(pszAccess, "rb") || EQUAL(pszAccess, "rb+");
    2862             : 
    2863          39 :     for (int i = 0; bReuse && i < nSharedFileCount; i++)
    2864             :     {
    2865          20 :         if (strcmp(pasSharedFileList[i].pszFilename, pszFilename) == 0 &&
    2866           4 :             !bLarge == !pasSharedFileList[i].bLarge &&
    2867          16 :             EQUAL(pasSharedFileList[i].pszAccess, pszAccess) &&
    2868           4 :             nPID == pasSharedFileListExtra[i].nPID)
    2869             :         {
    2870           4 :             pasSharedFileList[i].nRefCount++;
    2871           4 :             return pasSharedFileList[i].fp;
    2872             :         }
    2873             :     }
    2874             : 
    2875             :     /* -------------------------------------------------------------------- */
    2876             :     /*      Open the file.                                                  */
    2877             :     /* -------------------------------------------------------------------- */
    2878             :     FILE *fp = bLarge
    2879          31 :                    ? reinterpret_cast<FILE *>(VSIFOpenL(pszFilename, pszAccess))
    2880           0 :                    : VSIFOpen(pszFilename, pszAccess);
    2881             : 
    2882          31 :     if (fp == nullptr)
    2883           8 :         return nullptr;
    2884             : 
    2885             :     /* -------------------------------------------------------------------- */
    2886             :     /*      Add an entry to the list.                                       */
    2887             :     /* -------------------------------------------------------------------- */
    2888          23 :     nSharedFileCount++;
    2889             : 
    2890          23 :     pasSharedFileList = static_cast<CPLSharedFileInfo *>(
    2891          46 :         CPLRealloc(const_cast<CPLSharedFileInfo *>(pasSharedFileList),
    2892          23 :                    sizeof(CPLSharedFileInfo) * nSharedFileCount));
    2893          23 :     pasSharedFileListExtra = static_cast<CPLSharedFileInfoExtra *>(
    2894          46 :         CPLRealloc(const_cast<CPLSharedFileInfoExtra *>(pasSharedFileListExtra),
    2895          23 :                    sizeof(CPLSharedFileInfoExtra) * nSharedFileCount));
    2896             : 
    2897          23 :     pasSharedFileList[nSharedFileCount - 1].fp = fp;
    2898          23 :     pasSharedFileList[nSharedFileCount - 1].nRefCount = 1;
    2899          23 :     pasSharedFileList[nSharedFileCount - 1].bLarge = bLarge;
    2900          46 :     pasSharedFileList[nSharedFileCount - 1].pszFilename =
    2901          23 :         CPLStrdup(pszFilename);
    2902          23 :     pasSharedFileList[nSharedFileCount - 1].pszAccess = CPLStrdup(pszAccess);
    2903          23 :     pasSharedFileListExtra[nSharedFileCount - 1].nPID = nPID;
    2904             : 
    2905          23 :     return fp;
    2906             : }
    2907             : 
    2908             : /************************************************************************/
    2909             : /*                           CPLCloseShared()                           */
    2910             : /************************************************************************/
    2911             : 
    2912             : /**
    2913             :  * Close shared file.
    2914             :  *
    2915             :  * Dereferences the indicated file handle, and closes it if the reference
    2916             :  * count has dropped to zero.  A CPLError() is issued if the file is not
    2917             :  * in the shared file list.
    2918             :  *
    2919             :  * @param fp file handle from CPLOpenShared() to deaccess.
    2920             :  */
    2921             : 
    2922          27 : void CPLCloseShared(FILE *fp)
    2923             : 
    2924             : {
    2925          27 :     CPLMutexHolderD(&hSharedFileMutex);
    2926             : 
    2927             :     /* -------------------------------------------------------------------- */
    2928             :     /*      Search for matching information.                                */
    2929             :     /* -------------------------------------------------------------------- */
    2930          27 :     int i = 0;
    2931          29 :     for (; i < nSharedFileCount && fp != pasSharedFileList[i].fp; i++)
    2932             :     {
    2933             :     }
    2934             : 
    2935          27 :     if (i == nSharedFileCount)
    2936             :     {
    2937           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    2938             :                  "Unable to find file handle %p in CPLCloseShared().", fp);
    2939           0 :         return;
    2940             :     }
    2941             : 
    2942             :     /* -------------------------------------------------------------------- */
    2943             :     /*      Dereference and return if there are still some references.      */
    2944             :     /* -------------------------------------------------------------------- */
    2945          27 :     if (--pasSharedFileList[i].nRefCount > 0)
    2946           4 :         return;
    2947             : 
    2948             :     /* -------------------------------------------------------------------- */
    2949             :     /*      Close the file, and remove the information.                     */
    2950             :     /* -------------------------------------------------------------------- */
    2951          23 :     if (pasSharedFileList[i].bLarge)
    2952             :     {
    2953          23 :         if (VSIFCloseL(reinterpret_cast<VSILFILE *>(pasSharedFileList[i].fp)) !=
    2954             :             0)
    2955             :         {
    2956           0 :             CPLError(CE_Failure, CPLE_FileIO, "Error while closing %s",
    2957           0 :                      pasSharedFileList[i].pszFilename);
    2958             :         }
    2959             :     }
    2960             :     else
    2961             :     {
    2962           0 :         VSIFClose(pasSharedFileList[i].fp);
    2963             :     }
    2964             : 
    2965          23 :     CPLFree(pasSharedFileList[i].pszFilename);
    2966          23 :     CPLFree(pasSharedFileList[i].pszAccess);
    2967             : 
    2968          23 :     nSharedFileCount--;
    2969          23 :     memmove(
    2970          23 :         const_cast<CPLSharedFileInfo *>(pasSharedFileList + i),
    2971          23 :         const_cast<CPLSharedFileInfo *>(pasSharedFileList + nSharedFileCount),
    2972             :         sizeof(CPLSharedFileInfo));
    2973          23 :     memmove(const_cast<CPLSharedFileInfoExtra *>(pasSharedFileListExtra + i),
    2974          23 :             const_cast<CPLSharedFileInfoExtra *>(pasSharedFileListExtra +
    2975          23 :                                                  nSharedFileCount),
    2976             :             sizeof(CPLSharedFileInfoExtra));
    2977             : 
    2978          23 :     if (nSharedFileCount == 0)
    2979             :     {
    2980          20 :         CPLFree(const_cast<CPLSharedFileInfo *>(pasSharedFileList));
    2981          20 :         pasSharedFileList = nullptr;
    2982          20 :         CPLFree(const_cast<CPLSharedFileInfoExtra *>(pasSharedFileListExtra));
    2983          20 :         pasSharedFileListExtra = nullptr;
    2984             :     }
    2985             : }
    2986             : 
    2987             : /************************************************************************/
    2988             : /*                   CPLCleanupSharedFileMutex()                        */
    2989             : /************************************************************************/
    2990             : 
    2991         941 : void CPLCleanupSharedFileMutex()
    2992             : {
    2993         941 :     if (hSharedFileMutex != nullptr)
    2994             :     {
    2995           0 :         CPLDestroyMutex(hSharedFileMutex);
    2996           0 :         hSharedFileMutex = nullptr;
    2997             :     }
    2998         941 : }
    2999             : 
    3000             : /************************************************************************/
    3001             : /*                          CPLGetSharedList()                          */
    3002             : /************************************************************************/
    3003             : 
    3004             : /**
    3005             :  * Fetch list of open shared files.
    3006             :  *
    3007             :  * @param pnCount place to put the count of entries.
    3008             :  *
    3009             :  * @return the pointer to the first in the array of shared file info
    3010             :  * structures.
    3011             :  */
    3012             : 
    3013           0 : CPLSharedFileInfo *CPLGetSharedList(int *pnCount)
    3014             : 
    3015             : {
    3016           0 :     if (pnCount != nullptr)
    3017           0 :         *pnCount = nSharedFileCount;
    3018             : 
    3019           0 :     return const_cast<CPLSharedFileInfo *>(pasSharedFileList);
    3020             : }
    3021             : 
    3022             : /************************************************************************/
    3023             : /*                         CPLDumpSharedList()                          */
    3024             : /************************************************************************/
    3025             : 
    3026             : /**
    3027             :  * Report open shared files.
    3028             :  *
    3029             :  * Dumps all open shared files to the indicated file handle.  If the
    3030             :  * file handle is NULL information is sent via the CPLDebug() call.
    3031             :  *
    3032             :  * @param fp File handle to write to.
    3033             :  */
    3034             : 
    3035         103 : void CPLDumpSharedList(FILE *fp)
    3036             : 
    3037             : {
    3038         103 :     if (nSharedFileCount > 0)
    3039             :     {
    3040           0 :         if (fp == nullptr)
    3041           0 :             CPLDebug("CPL", "%d Shared files open.", nSharedFileCount);
    3042             :         else
    3043           0 :             fprintf(fp, "%d Shared files open.", nSharedFileCount);
    3044             :     }
    3045             : 
    3046         103 :     for (int i = 0; i < nSharedFileCount; i++)
    3047             :     {
    3048           0 :         if (fp == nullptr)
    3049           0 :             CPLDebug("CPL", "%2d %d %4s %s", pasSharedFileList[i].nRefCount,
    3050           0 :                      pasSharedFileList[i].bLarge,
    3051           0 :                      pasSharedFileList[i].pszAccess,
    3052           0 :                      pasSharedFileList[i].pszFilename);
    3053             :         else
    3054           0 :             fprintf(fp, "%2d %d %4s %s", pasSharedFileList[i].nRefCount,
    3055           0 :                     pasSharedFileList[i].bLarge, pasSharedFileList[i].pszAccess,
    3056           0 :                     pasSharedFileList[i].pszFilename);
    3057             :     }
    3058         103 : }
    3059             : 
    3060             : /************************************************************************/
    3061             : /*                           CPLUnlinkTree()                            */
    3062             : /************************************************************************/
    3063             : 
    3064             : /** Recursively unlink a directory.
    3065             :  *
    3066             :  * @return 0 on successful completion, -1 if function fails.
    3067             :  */
    3068             : 
    3069          52 : int CPLUnlinkTree(const char *pszPath)
    3070             : 
    3071             : {
    3072             :     /* -------------------------------------------------------------------- */
    3073             :     /*      First, ensure there is such a file.                             */
    3074             :     /* -------------------------------------------------------------------- */
    3075             :     VSIStatBufL sStatBuf;
    3076             : 
    3077          52 :     if (VSIStatL(pszPath, &sStatBuf) != 0)
    3078             :     {
    3079           2 :         CPLError(CE_Failure, CPLE_AppDefined,
    3080             :                  "It seems no file system object called '%s' exists.", pszPath);
    3081             : 
    3082           2 :         return -1;
    3083             :     }
    3084             : 
    3085             :     /* -------------------------------------------------------------------- */
    3086             :     /*      If it is a simple file, just delete it.                         */
    3087             :     /* -------------------------------------------------------------------- */
    3088          50 :     if (VSI_ISREG(sStatBuf.st_mode))
    3089             :     {
    3090          34 :         if (VSIUnlink(pszPath) != 0)
    3091             :         {
    3092           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Failed to unlink %s.",
    3093             :                      pszPath);
    3094             : 
    3095           0 :             return -1;
    3096             :         }
    3097             : 
    3098          34 :         return 0;
    3099             :     }
    3100             : 
    3101             :     /* -------------------------------------------------------------------- */
    3102             :     /*      If it is a directory recurse then unlink the directory.         */
    3103             :     /* -------------------------------------------------------------------- */
    3104          16 :     else if (VSI_ISDIR(sStatBuf.st_mode))
    3105             :     {
    3106          16 :         char **papszItems = VSIReadDir(pszPath);
    3107             : 
    3108          32 :         for (int i = 0; papszItems != nullptr && papszItems[i] != nullptr; i++)
    3109             :         {
    3110          16 :             if (papszItems[i][0] == '\0' || EQUAL(papszItems[i], ".") ||
    3111          16 :                 EQUAL(papszItems[i], ".."))
    3112           0 :                 continue;
    3113             : 
    3114             :             const std::string osSubPath =
    3115          16 :                 CPLFormFilenameSafe(pszPath, papszItems[i], nullptr);
    3116             : 
    3117          16 :             const int nErr = CPLUnlinkTree(osSubPath.c_str());
    3118             : 
    3119          16 :             if (nErr != 0)
    3120             :             {
    3121           0 :                 CSLDestroy(papszItems);
    3122           0 :                 return nErr;
    3123             :             }
    3124             :         }
    3125             : 
    3126          16 :         CSLDestroy(papszItems);
    3127             : 
    3128          16 :         if (VSIRmdir(pszPath) != 0)
    3129             :         {
    3130           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Failed to unlink %s.",
    3131             :                      pszPath);
    3132             : 
    3133           0 :             return -1;
    3134             :         }
    3135             : 
    3136          16 :         return 0;
    3137             :     }
    3138             : 
    3139             :     /* -------------------------------------------------------------------- */
    3140             :     /*      otherwise report an error.                                      */
    3141             :     /* -------------------------------------------------------------------- */
    3142           0 :     CPLError(CE_Failure, CPLE_AppDefined,
    3143             :              "Failed to unlink %s.\nUnrecognised filesystem object.", pszPath);
    3144           0 :     return 1000;
    3145             : }
    3146             : 
    3147             : /************************************************************************/
    3148             : /*                            CPLCopyFile()                             */
    3149             : /************************************************************************/
    3150             : 
    3151             : /** Copy a file */
    3152        2211 : int CPLCopyFile(const char *pszNewPath, const char *pszOldPath)
    3153             : 
    3154             : {
    3155        2211 :     return VSICopyFile(pszOldPath, pszNewPath, nullptr,
    3156             :                        static_cast<vsi_l_offset>(-1), nullptr, nullptr,
    3157        2211 :                        nullptr);
    3158             : }
    3159             : 
    3160             : /************************************************************************/
    3161             : /*                            CPLCopyTree()                             */
    3162             : /************************************************************************/
    3163             : 
    3164             : /** Recursively copy a tree */
    3165           4 : int CPLCopyTree(const char *pszNewPath, const char *pszOldPath)
    3166             : 
    3167             : {
    3168             :     VSIStatBufL sStatBuf;
    3169           4 :     if (VSIStatL(pszNewPath, &sStatBuf) == 0)
    3170             :     {
    3171           1 :         CPLError(
    3172             :             CE_Failure, CPLE_AppDefined,
    3173             :             "It seems that a file system object called '%s' already exists.",
    3174             :             pszNewPath);
    3175             : 
    3176           1 :         return -1;
    3177             :     }
    3178             : 
    3179           3 :     if (VSIStatL(pszOldPath, &sStatBuf) != 0)
    3180             :     {
    3181           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    3182             :                  "It seems no file system object called '%s' exists.",
    3183             :                  pszOldPath);
    3184             : 
    3185           1 :         return -1;
    3186             :     }
    3187             : 
    3188           2 :     if (VSI_ISDIR(sStatBuf.st_mode))
    3189             :     {
    3190           1 :         if (VSIMkdir(pszNewPath, 0755) != 0)
    3191             :         {
    3192           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    3193             :                      "Cannot create directory '%s'.", pszNewPath);
    3194             : 
    3195           0 :             return -1;
    3196             :         }
    3197             : 
    3198           1 :         char **papszItems = VSIReadDir(pszOldPath);
    3199             : 
    3200           4 :         for (int i = 0; papszItems != nullptr && papszItems[i] != nullptr; i++)
    3201             :         {
    3202           3 :             if (EQUAL(papszItems[i], ".") || EQUAL(papszItems[i], ".."))
    3203           2 :                 continue;
    3204             : 
    3205             :             const std::string osNewSubPath =
    3206           1 :                 CPLFormFilenameSafe(pszNewPath, papszItems[i], nullptr);
    3207             :             const std::string osOldSubPath =
    3208           1 :                 CPLFormFilenameSafe(pszOldPath, papszItems[i], nullptr);
    3209             : 
    3210             :             const int nErr =
    3211           1 :                 CPLCopyTree(osNewSubPath.c_str(), osOldSubPath.c_str());
    3212             : 
    3213           1 :             if (nErr != 0)
    3214             :             {
    3215           0 :                 CSLDestroy(papszItems);
    3216           0 :                 return nErr;
    3217             :             }
    3218             :         }
    3219           1 :         CSLDestroy(papszItems);
    3220             : 
    3221           1 :         return 0;
    3222             :     }
    3223           1 :     else if (VSI_ISREG(sStatBuf.st_mode))
    3224             :     {
    3225           1 :         return CPLCopyFile(pszNewPath, pszOldPath);
    3226             :     }
    3227             :     else
    3228             :     {
    3229           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    3230             :                  "Unrecognized filesystem object : '%s'.", pszOldPath);
    3231           0 :         return -1;
    3232             :     }
    3233             : }
    3234             : 
    3235             : /************************************************************************/
    3236             : /*                            CPLMoveFile()                             */
    3237             : /************************************************************************/
    3238             : 
    3239             : /** Move a file */
    3240         184 : int CPLMoveFile(const char *pszNewPath, const char *pszOldPath)
    3241             : 
    3242             : {
    3243         184 :     if (VSIRename(pszOldPath, pszNewPath) == 0)
    3244         181 :         return 0;
    3245             : 
    3246           3 :     const int nRet = CPLCopyFile(pszNewPath, pszOldPath);
    3247             : 
    3248           3 :     if (nRet == 0)
    3249           3 :         VSIUnlink(pszOldPath);
    3250           3 :     return nRet;
    3251             : }
    3252             : 
    3253             : /************************************************************************/
    3254             : /*                             CPLSymlink()                             */
    3255             : /************************************************************************/
    3256             : 
    3257             : /** Create a symbolic link */
    3258             : #ifdef _WIN32
    3259             : int CPLSymlink(const char *, const char *, CSLConstList)
    3260             : {
    3261             :     return -1;
    3262             : }
    3263             : #else
    3264           0 : int CPLSymlink(const char *pszOldPath, const char *pszNewPath,
    3265             :                CSLConstList /* papszOptions */)
    3266             : {
    3267           0 :     return symlink(pszOldPath, pszNewPath);
    3268             : }
    3269             : #endif
    3270             : 
    3271             : /************************************************************************/
    3272             : /* ==================================================================== */
    3273             : /*                              CPLLocaleC                              */
    3274             : /* ==================================================================== */
    3275             : /************************************************************************/
    3276             : 
    3277             : //! @cond Doxygen_Suppress
    3278             : /************************************************************************/
    3279             : /*                             CPLLocaleC()                             */
    3280             : /************************************************************************/
    3281             : 
    3282         127 : CPLLocaleC::CPLLocaleC() : pszOldLocale(nullptr)
    3283             : {
    3284         127 :     if (CPLTestBool(CPLGetConfigOption("GDAL_DISABLE_CPLLOCALEC", "NO")))
    3285           0 :         return;
    3286             : 
    3287         127 :     pszOldLocale = CPLStrdup(CPLsetlocale(LC_NUMERIC, nullptr));
    3288         127 :     if (EQUAL(pszOldLocale, "C") || EQUAL(pszOldLocale, "POSIX") ||
    3289           0 :         CPLsetlocale(LC_NUMERIC, "C") == nullptr)
    3290             :     {
    3291         127 :         CPLFree(pszOldLocale);
    3292         127 :         pszOldLocale = nullptr;
    3293             :     }
    3294             : }
    3295             : 
    3296             : /************************************************************************/
    3297             : /*                            ~CPLLocaleC()                             */
    3298             : /************************************************************************/
    3299             : 
    3300           0 : CPLLocaleC::~CPLLocaleC()
    3301             : 
    3302             : {
    3303         127 :     if (pszOldLocale == nullptr)
    3304         127 :         return;
    3305             : 
    3306           0 :     CPLsetlocale(LC_NUMERIC, pszOldLocale);
    3307           0 :     CPLFree(pszOldLocale);
    3308         127 : }
    3309             : 
    3310             : /************************************************************************/
    3311             : /*                        CPLThreadLocaleCPrivate                       */
    3312             : /************************************************************************/
    3313             : 
    3314             : #ifdef HAVE_USELOCALE
    3315             : 
    3316             : class CPLThreadLocaleCPrivate
    3317             : {
    3318             :     locale_t nNewLocale;
    3319             :     locale_t nOldLocale;
    3320             : 
    3321             :     CPL_DISALLOW_COPY_ASSIGN(CPLThreadLocaleCPrivate)
    3322             : 
    3323             :   public:
    3324             :     CPLThreadLocaleCPrivate();
    3325             :     ~CPLThreadLocaleCPrivate();
    3326             : };
    3327             : 
    3328           0 : CPLThreadLocaleCPrivate::CPLThreadLocaleCPrivate()
    3329           0 :     : nNewLocale(newlocale(LC_NUMERIC_MASK, "C", nullptr)),
    3330           0 :       nOldLocale(uselocale(nNewLocale))
    3331             : {
    3332           0 : }
    3333             : 
    3334           0 : CPLThreadLocaleCPrivate::~CPLThreadLocaleCPrivate()
    3335             : {
    3336           0 :     uselocale(nOldLocale);
    3337           0 :     freelocale(nNewLocale);
    3338           0 : }
    3339             : 
    3340             : #elif defined(_MSC_VER)
    3341             : 
    3342             : class CPLThreadLocaleCPrivate
    3343             : {
    3344             :     int nOldValConfigThreadLocale;
    3345             :     char *pszOldLocale;
    3346             : 
    3347             :     CPL_DISALLOW_COPY_ASSIGN(CPLThreadLocaleCPrivate)
    3348             : 
    3349             :   public:
    3350             :     CPLThreadLocaleCPrivate();
    3351             :     ~CPLThreadLocaleCPrivate();
    3352             : };
    3353             : 
    3354             : CPLThreadLocaleCPrivate::CPLThreadLocaleCPrivate()
    3355             : {
    3356             :     nOldValConfigThreadLocale = _configthreadlocale(_ENABLE_PER_THREAD_LOCALE);
    3357             :     pszOldLocale = setlocale(LC_NUMERIC, "C");
    3358             :     if (pszOldLocale)
    3359             :         pszOldLocale = CPLStrdup(pszOldLocale);
    3360             : }
    3361             : 
    3362             : CPLThreadLocaleCPrivate::~CPLThreadLocaleCPrivate()
    3363             : {
    3364             :     if (pszOldLocale != nullptr)
    3365             :     {
    3366             :         setlocale(LC_NUMERIC, pszOldLocale);
    3367             :         CPLFree(pszOldLocale);
    3368             :     }
    3369             :     _configthreadlocale(nOldValConfigThreadLocale);
    3370             : }
    3371             : 
    3372             : #else
    3373             : 
    3374             : class CPLThreadLocaleCPrivate
    3375             : {
    3376             :     char *pszOldLocale;
    3377             : 
    3378             :     CPL_DISALLOW_COPY_ASSIGN(CPLThreadLocaleCPrivate)
    3379             : 
    3380             :   public:
    3381             :     CPLThreadLocaleCPrivate();
    3382             :     ~CPLThreadLocaleCPrivate();
    3383             : };
    3384             : 
    3385             : CPLThreadLocaleCPrivate::CPLThreadLocaleCPrivate()
    3386             :     : pszOldLocale(CPLStrdup(CPLsetlocale(LC_NUMERIC, nullptr)))
    3387             : {
    3388             :     if (EQUAL(pszOldLocale, "C") || EQUAL(pszOldLocale, "POSIX") ||
    3389             :         CPLsetlocale(LC_NUMERIC, "C") == nullptr)
    3390             :     {
    3391             :         CPLFree(pszOldLocale);
    3392             :         pszOldLocale = nullptr;
    3393             :     }
    3394             : }
    3395             : 
    3396             : CPLThreadLocaleCPrivate::~CPLThreadLocaleCPrivate()
    3397             : {
    3398             :     if (pszOldLocale != nullptr)
    3399             :     {
    3400             :         CPLsetlocale(LC_NUMERIC, pszOldLocale);
    3401             :         CPLFree(pszOldLocale);
    3402             :     }
    3403             : }
    3404             : 
    3405             : #endif
    3406             : 
    3407             : /************************************************************************/
    3408             : /*                        CPLThreadLocaleC()                            */
    3409             : /************************************************************************/
    3410             : 
    3411           0 : CPLThreadLocaleC::CPLThreadLocaleC() : m_private(new CPLThreadLocaleCPrivate)
    3412             : {
    3413           0 : }
    3414             : 
    3415             : /************************************************************************/
    3416             : /*                       ~CPLThreadLocaleC()                            */
    3417             : /************************************************************************/
    3418             : 
    3419           0 : CPLThreadLocaleC::~CPLThreadLocaleC()
    3420             : 
    3421             : {
    3422           0 :     delete m_private;
    3423           0 : }
    3424             : 
    3425             : //! @endcond
    3426             : 
    3427             : /************************************************************************/
    3428             : /*                          CPLsetlocale()                              */
    3429             : /************************************************************************/
    3430             : 
    3431             : /**
    3432             :  * Prevents parallel executions of setlocale().
    3433             :  *
    3434             :  * Calling setlocale() concurrently from two or more threads is a
    3435             :  * potential data race. A mutex is used to provide a critical region so
    3436             :  * that only one thread at a time can be executing setlocale().
    3437             :  *
    3438             :  * The return should not be freed, and copied quickly as it may be invalidated
    3439             :  * by a following next call to CPLsetlocale().
    3440             :  *
    3441             :  * @param category See your compiler's documentation on setlocale.
    3442             :  * @param locale See your compiler's documentation on setlocale.
    3443             :  *
    3444             :  * @return See your compiler's documentation on setlocale.
    3445             :  */
    3446         129 : char *CPLsetlocale(int category, const char *locale)
    3447             : {
    3448         258 :     CPLMutexHolder oHolder(&hSetLocaleMutex);
    3449         129 :     char *pszRet = setlocale(category, locale);
    3450         129 :     if (pszRet == nullptr)
    3451           0 :         return pszRet;
    3452             : 
    3453             :     // Make it thread-locale storage.
    3454         129 :     return const_cast<char *>(CPLSPrintf("%s", pszRet));
    3455             : }
    3456             : 
    3457             : /************************************************************************/
    3458             : /*                       CPLCleanupSetlocaleMutex()                     */
    3459             : /************************************************************************/
    3460             : 
    3461         941 : void CPLCleanupSetlocaleMutex(void)
    3462             : {
    3463         941 :     if (hSetLocaleMutex != nullptr)
    3464           5 :         CPLDestroyMutex(hSetLocaleMutex);
    3465         941 :     hSetLocaleMutex = nullptr;
    3466         941 : }
    3467             : 
    3468             : /************************************************************************/
    3469             : /*                            IsPowerOfTwo()                            */
    3470             : /************************************************************************/
    3471             : 
    3472         134 : int CPLIsPowerOfTwo(unsigned int i)
    3473             : {
    3474         134 :     if (i == 0)
    3475           0 :         return FALSE;
    3476         134 :     return (i & (i - 1)) == 0 ? TRUE : FALSE;
    3477             : }
    3478             : 
    3479             : /************************************************************************/
    3480             : /*                          CPLCheckForFile()                           */
    3481             : /************************************************************************/
    3482             : 
    3483             : /**
    3484             :  * Check for file existence.
    3485             :  *
    3486             :  * The function checks if a named file exists in the filesystem, hopefully
    3487             :  * in an efficient fashion if a sibling file list is available.   It exists
    3488             :  * primarily to do faster file checking for functions like GDAL open methods
    3489             :  * that get a list of files from the target directory.
    3490             :  *
    3491             :  * If the sibling file list exists (is not NULL) it is assumed to be a list
    3492             :  * of files in the same directory as the target file, and it will be checked
    3493             :  * (case insensitively) for a match.  If a match is found, pszFilename is
    3494             :  * updated with the correct case and TRUE is returned.
    3495             :  *
    3496             :  * If papszSiblingFiles is NULL, a VSIStatL() is used to test for the files
    3497             :  * existence, and no case insensitive testing is done.
    3498             :  *
    3499             :  * @param pszFilename name of file to check for - filename case updated in
    3500             :  * some cases.
    3501             :  * @param papszSiblingFiles a list of files in the same directory as
    3502             :  * pszFilename if available, or NULL. This list should have no path components.
    3503             :  *
    3504             :  * @return TRUE if a match is found, or FALSE if not.
    3505             :  */
    3506             : 
    3507      158024 : int CPLCheckForFile(char *pszFilename, char **papszSiblingFiles)
    3508             : 
    3509             : {
    3510             :     /* -------------------------------------------------------------------- */
    3511             :     /*      Fallback case if we don't have a sibling file list.             */
    3512             :     /* -------------------------------------------------------------------- */
    3513      158024 :     if (papszSiblingFiles == nullptr)
    3514             :     {
    3515             :         VSIStatBufL sStatBuf;
    3516             : 
    3517       10820 :         return VSIStatExL(pszFilename, &sStatBuf, VSI_STAT_EXISTS_FLAG) == 0;
    3518             :     }
    3519             : 
    3520             :     /* -------------------------------------------------------------------- */
    3521             :     /*      We have sibling files, compare the non-path filename portion    */
    3522             :     /*      of pszFilename too all entries.                                 */
    3523             :     /* -------------------------------------------------------------------- */
    3524      294408 :     const CPLString osFileOnly = CPLGetFilename(pszFilename);
    3525             : 
    3526    13843100 :     for (int i = 0; papszSiblingFiles[i] != nullptr; i++)
    3527             :     {
    3528    13696100 :         if (EQUAL(papszSiblingFiles[i], osFileOnly))
    3529             :         {
    3530         314 :             strcpy(pszFilename + strlen(pszFilename) - osFileOnly.size(),
    3531         157 :                    papszSiblingFiles[i]);
    3532         157 :             return TRUE;
    3533             :         }
    3534             :     }
    3535             : 
    3536      147047 :     return FALSE;
    3537             : }
    3538             : 
    3539             : /************************************************************************/
    3540             : /*      Stub implementation of zip services if we don't have libz.      */
    3541             : /************************************************************************/
    3542             : 
    3543             : #if !defined(HAVE_LIBZ)
    3544             : 
    3545             : void *CPLCreateZip(const char *, char **)
    3546             : 
    3547             : {
    3548             :     CPLError(CE_Failure, CPLE_NotSupported,
    3549             :              "This GDAL/OGR build does not include zlib and zip services.");
    3550             :     return nullptr;
    3551             : }
    3552             : 
    3553             : CPLErr CPLCreateFileInZip(void *, const char *, char **)
    3554             : {
    3555             :     return CE_Failure;
    3556             : }
    3557             : 
    3558             : CPLErr CPLWriteFileInZip(void *, const void *, int)
    3559             : {
    3560             :     return CE_Failure;
    3561             : }
    3562             : 
    3563             : CPLErr CPLCloseFileInZip(void *)
    3564             : {
    3565             :     return CE_Failure;
    3566             : }
    3567             : 
    3568             : CPLErr CPLCloseZip(void *)
    3569             : {
    3570             :     return CE_Failure;
    3571             : }
    3572             : 
    3573             : void *CPLZLibDeflate(const void *, size_t, int, void *, size_t,
    3574             :                      size_t *pnOutBytes)
    3575             : {
    3576             :     if (pnOutBytes != nullptr)
    3577             :         *pnOutBytes = 0;
    3578             :     return nullptr;
    3579             : }
    3580             : 
    3581             : void *CPLZLibInflate(const void *, size_t, void *, size_t, size_t *pnOutBytes)
    3582             : {
    3583             :     if (pnOutBytes != nullptr)
    3584             :         *pnOutBytes = 0;
    3585             :     return nullptr;
    3586             : }
    3587             : 
    3588             : #endif /* !defined(HAVE_LIBZ) */
    3589             : 
    3590             : /************************************************************************/
    3591             : /* ==================================================================== */
    3592             : /*                          CPLConfigOptionSetter                       */
    3593             : /* ==================================================================== */
    3594             : /************************************************************************/
    3595             : 
    3596             : //! @cond Doxygen_Suppress
    3597             : /************************************************************************/
    3598             : /*                         CPLConfigOptionSetter()                      */
    3599             : /************************************************************************/
    3600             : 
    3601       23460 : CPLConfigOptionSetter::CPLConfigOptionSetter(const char *pszKey,
    3602             :                                              const char *pszValue,
    3603       23460 :                                              bool bSetOnlyIfUndefined)
    3604       23460 :     : m_pszKey(CPLStrdup(pszKey)), m_pszOldValue(nullptr),
    3605       23428 :       m_bRestoreOldValue(false)
    3606             : {
    3607       23428 :     const char *pszOldValue = CPLGetThreadLocalConfigOption(pszKey, nullptr);
    3608       37210 :     if ((bSetOnlyIfUndefined &&
    3609       33149 :          CPLGetConfigOption(pszKey, nullptr) == nullptr) ||
    3610        9712 :         !bSetOnlyIfUndefined)
    3611             :     {
    3612       23449 :         m_bRestoreOldValue = true;
    3613       23449 :         if (pszOldValue)
    3614         644 :             m_pszOldValue = CPLStrdup(pszOldValue);
    3615       23449 :         CPLSetThreadLocalConfigOption(pszKey, pszValue);
    3616             :     }
    3617       23286 : }
    3618             : 
    3619             : /************************************************************************/
    3620             : /*                        ~CPLConfigOptionSetter()                      */
    3621             : /************************************************************************/
    3622             : 
    3623       46776 : CPLConfigOptionSetter::~CPLConfigOptionSetter()
    3624             : {
    3625       23462 :     if (m_bRestoreOldValue)
    3626             :     {
    3627       23453 :         CPLSetThreadLocalConfigOption(m_pszKey, m_pszOldValue);
    3628       23227 :         CPLFree(m_pszOldValue);
    3629             :     }
    3630       23194 :     CPLFree(m_pszKey);
    3631       23314 : }
    3632             : 
    3633             : //! @endcond
    3634             : 
    3635             : /************************************************************************/
    3636             : /*                          CPLIsInteractive()                          */
    3637             : /************************************************************************/
    3638             : 
    3639             : /** Returns whether the provided file refers to a terminal.
    3640             :  *
    3641             :  * This function is a wrapper of the ``isatty()`` POSIX function.
    3642             :  *
    3643             :  * @param f File to test. Typically stdin, stdout or stderr
    3644             :  * @return true if it is an open file referring to a terminal.
    3645             :  * @since GDAL 3.11
    3646             :  */
    3647         642 : bool CPLIsInteractive(FILE *f)
    3648             : {
    3649             : #ifndef _WIN32
    3650         642 :     return isatty(static_cast<int>(fileno(f)));
    3651             : #else
    3652             :     return _isatty(_fileno(f));
    3653             : #endif
    3654             : }

Generated by: LCOV version 1.14