000001  /*
000002  ** 2005 November 29
000003  **
000004  ** The author disclaims copyright to this source code.  In place of
000005  ** a legal notice, here is a blessing:
000006  **
000007  **    May you do good and not evil.
000008  **    May you find forgiveness for yourself and forgive others.
000009  **    May you share freely, never taking more than you give.
000010  **
000011  ******************************************************************************
000012  **
000013  ** This file contains OS interface code that is common to all
000014  ** architectures.
000015  */
000016  #include "sqliteInt.h"
000017  
000018  /*
000019  ** If we compile with the SQLITE_TEST macro set, then the following block
000020  ** of code will give us the ability to simulate a disk I/O error.  This
000021  ** is used for testing the I/O recovery logic.
000022  */
000023  #if defined(SQLITE_TEST)
000024  int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
000025  int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
000026  int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
000027  int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
000028  int sqlite3_io_error_benign = 0;         /* True if errors are benign */
000029  int sqlite3_diskfull_pending = 0;
000030  int sqlite3_diskfull = 0;
000031  #endif /* defined(SQLITE_TEST) */
000032  
000033  /*
000034  ** When testing, also keep a count of the number of open files.
000035  */
000036  #if defined(SQLITE_TEST)
000037  int sqlite3_open_file_count = 0;
000038  #endif /* defined(SQLITE_TEST) */
000039  
000040  /*
000041  ** The default SQLite sqlite3_vfs implementations do not allocate
000042  ** memory (actually, os_unix.c allocates a small amount of memory
000043  ** from within OsOpen()), but some third-party implementations may.
000044  ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
000045  ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
000046  **
000047  ** The following functions are instrumented for malloc() failure
000048  ** testing:
000049  **
000050  **     sqlite3OsRead()
000051  **     sqlite3OsWrite()
000052  **     sqlite3OsSync()
000053  **     sqlite3OsFileSize()
000054  **     sqlite3OsLock()
000055  **     sqlite3OsCheckReservedLock()
000056  **     sqlite3OsFileControl()
000057  **     sqlite3OsShmMap()
000058  **     sqlite3OsOpen()
000059  **     sqlite3OsDelete()
000060  **     sqlite3OsAccess()
000061  **     sqlite3OsFullPathname()
000062  **
000063  */
000064  #if defined(SQLITE_TEST)
000065  int sqlite3_memdebug_vfs_oom_test = 1;
000066    #define DO_OS_MALLOC_TEST(x)                                       \
000067    if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3JournalIsInMemory(x))) { \
000068      void *pTstAlloc = sqlite3Malloc(10);                             \
000069      if (!pTstAlloc) return SQLITE_IOERR_NOMEM_BKPT;                  \
000070      sqlite3_free(pTstAlloc);                                         \
000071    }
000072  #else
000073    #define DO_OS_MALLOC_TEST(x)
000074  #endif
000075  
000076  /*
000077  ** The following routines are convenience wrappers around methods
000078  ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
000079  ** of this would be completely automatic if SQLite were coded using
000080  ** C++ instead of plain old C.
000081  */
000082  void sqlite3OsClose(sqlite3_file *pId){
000083    if( pId->pMethods ){
000084      pId->pMethods->xClose(pId);
000085      pId->pMethods = 0;
000086    }
000087  }
000088  int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
000089    DO_OS_MALLOC_TEST(id);
000090    return id->pMethods->xRead(id, pBuf, amt, offset);
000091  }
000092  int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
000093    DO_OS_MALLOC_TEST(id);
000094    return id->pMethods->xWrite(id, pBuf, amt, offset);
000095  }
000096  int sqlite3OsTruncate(sqlite3_file *id, i64 size){
000097    return id->pMethods->xTruncate(id, size);
000098  }
000099  int sqlite3OsSync(sqlite3_file *id, int flags){
000100    DO_OS_MALLOC_TEST(id);
000101    return flags ? id->pMethods->xSync(id, flags) : SQLITE_OK;
000102  }
000103  int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
000104    DO_OS_MALLOC_TEST(id);
000105    return id->pMethods->xFileSize(id, pSize);
000106  }
000107  int sqlite3OsLock(sqlite3_file *id, int lockType){
000108    DO_OS_MALLOC_TEST(id);
000109    assert( lockType>=SQLITE_LOCK_SHARED && lockType<=SQLITE_LOCK_EXCLUSIVE );
000110    return id->pMethods->xLock(id, lockType);
000111  }
000112  int sqlite3OsUnlock(sqlite3_file *id, int lockType){
000113    assert( lockType==SQLITE_LOCK_NONE || lockType==SQLITE_LOCK_SHARED );
000114    return id->pMethods->xUnlock(id, lockType);
000115  }
000116  int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
000117    DO_OS_MALLOC_TEST(id);
000118    return id->pMethods->xCheckReservedLock(id, pResOut);
000119  }
000120  
000121  /*
000122  ** Use sqlite3OsFileControl() when we are doing something that might fail
000123  ** and we need to know about the failures.  Use sqlite3OsFileControlHint()
000124  ** when simply tossing information over the wall to the VFS and we do not
000125  ** really care if the VFS receives and understands the information since it
000126  ** is only a hint and can be safely ignored.  The sqlite3OsFileControlHint()
000127  ** routine has no return value since the return value would be meaningless.
000128  */
000129  int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
000130    if( id->pMethods==0 ) return SQLITE_NOTFOUND;
000131  #ifdef SQLITE_TEST
000132    if( op!=SQLITE_FCNTL_COMMIT_PHASETWO
000133     && op!=SQLITE_FCNTL_LOCK_TIMEOUT
000134     && op!=SQLITE_FCNTL_CKPT_DONE
000135     && op!=SQLITE_FCNTL_CKPT_START
000136    ){
000137      /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
000138      ** is using a regular VFS, it is called after the corresponding
000139      ** transaction has been committed. Injecting a fault at this point
000140      ** confuses the test scripts - the COMMIT command returns SQLITE_NOMEM
000141      ** but the transaction is committed anyway.
000142      **
000143      ** The core must call OsFileControl() though, not OsFileControlHint(),
000144      ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
000145      ** means the commit really has failed and an error should be returned
000146      ** to the user.
000147      **
000148      ** The CKPT_DONE and CKPT_START file-controls are write-only signals
000149      ** to the cksumvfs.  Their return code is meaningless and is ignored
000150      ** by the SQLite core, so there is no point in simulating OOMs for them.
000151      */
000152      DO_OS_MALLOC_TEST(id);
000153    }
000154  #endif
000155    return id->pMethods->xFileControl(id, op, pArg);
000156  }
000157  void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
000158    if( id->pMethods ) (void)id->pMethods->xFileControl(id, op, pArg);
000159  }
000160  
000161  int sqlite3OsSectorSize(sqlite3_file *id){
000162    int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
000163    return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
000164  }
000165  int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
000166    if( NEVER(id->pMethods==0) ) return 0;
000167    return id->pMethods->xDeviceCharacteristics(id);
000168  }
000169  #ifndef SQLITE_OMIT_WAL
000170  int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
000171    return id->pMethods->xShmLock(id, offset, n, flags);
000172  }
000173  void sqlite3OsShmBarrier(sqlite3_file *id){
000174    id->pMethods->xShmBarrier(id);
000175  }
000176  int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
000177    return id->pMethods->xShmUnmap(id, deleteFlag);
000178  }
000179  int sqlite3OsShmMap(
000180    sqlite3_file *id,               /* Database file handle */
000181    int iPage,
000182    int pgsz,
000183    int bExtend,                    /* True to extend file if necessary */
000184    void volatile **pp              /* OUT: Pointer to mapping */
000185  ){
000186    DO_OS_MALLOC_TEST(id);
000187    return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
000188  }
000189  #endif /* SQLITE_OMIT_WAL */
000190  
000191  #if SQLITE_MAX_MMAP_SIZE>0
000192  /* The real implementation of xFetch and xUnfetch */
000193  int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
000194    DO_OS_MALLOC_TEST(id);
000195    return id->pMethods->xFetch(id, iOff, iAmt, pp);
000196  }
000197  int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
000198    return id->pMethods->xUnfetch(id, iOff, p);
000199  }
000200  #else
000201  /* No-op stubs to use when memory-mapped I/O is disabled */
000202  int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
000203    *pp = 0;
000204    return SQLITE_OK;
000205  }
000206  int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
000207    return SQLITE_OK;
000208  }
000209  #endif
000210  
000211  /*
000212  ** The next group of routines are convenience wrappers around the
000213  ** VFS methods.
000214  */
000215  int sqlite3OsOpen(
000216    sqlite3_vfs *pVfs,
000217    const char *zPath,
000218    sqlite3_file *pFile,
000219    int flags,
000220    int *pFlagsOut
000221  ){
000222    int rc;
000223    DO_OS_MALLOC_TEST(0);
000224    /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
000225    ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
000226    ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
000227    ** reaching the VFS. */
000228    assert( zPath || (flags & SQLITE_OPEN_EXCLUSIVE) );
000229    rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x1087f7f, pFlagsOut);
000230    assert( rc==SQLITE_OK || pFile->pMethods==0 );
000231    return rc;
000232  }
000233  int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
000234    DO_OS_MALLOC_TEST(0);
000235    assert( dirSync==0 || dirSync==1 );
000236    return pVfs->xDelete!=0 ? pVfs->xDelete(pVfs, zPath, dirSync) : SQLITE_OK;
000237  }
000238  int sqlite3OsAccess(
000239    sqlite3_vfs *pVfs,
000240    const char *zPath,
000241    int flags,
000242    int *pResOut
000243  ){
000244    DO_OS_MALLOC_TEST(0);
000245    return pVfs->xAccess(pVfs, zPath, flags, pResOut);
000246  }
000247  int sqlite3OsFullPathname(
000248    sqlite3_vfs *pVfs,
000249    const char *zPath,
000250    int nPathOut,
000251    char *zPathOut
000252  ){
000253    DO_OS_MALLOC_TEST(0);
000254    zPathOut[0] = 0;
000255    return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
000256  }
000257  #ifndef SQLITE_OMIT_LOAD_EXTENSION
000258  void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
000259    assert( zPath!=0 );
000260    assert( strlen(zPath)<=SQLITE_MAX_PATHLEN );  /* tag-20210611-1 */
000261    return pVfs->xDlOpen(pVfs, zPath);
000262  }
000263  void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
000264    pVfs->xDlError(pVfs, nByte, zBufOut);
000265  }
000266  void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
000267    return pVfs->xDlSym(pVfs, pHdle, zSym);
000268  }
000269  void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
000270    pVfs->xDlClose(pVfs, pHandle);
000271  }
000272  #endif /* SQLITE_OMIT_LOAD_EXTENSION */
000273  int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
000274    if( sqlite3Config.iPrngSeed ){
000275      memset(zBufOut, 0, nByte);
000276      if( ALWAYS(nByte>(signed)sizeof(unsigned)) ) nByte = sizeof(unsigned int);
000277      memcpy(zBufOut, &sqlite3Config.iPrngSeed, nByte);
000278      return SQLITE_OK;
000279    }else{
000280      return pVfs->xRandomness(pVfs, nByte, zBufOut);
000281    }
000282  
000283  }
000284  int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
000285    return pVfs->xSleep(pVfs, nMicro);
000286  }
000287  int sqlite3OsGetLastError(sqlite3_vfs *pVfs){
000288    return pVfs->xGetLastError ? pVfs->xGetLastError(pVfs, 0, 0) : 0;
000289  }
000290  int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
000291    int rc;
000292    /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
000293    ** method to get the current date and time if that method is available
000294    ** (if iVersion is 2 or greater and the function pointer is not NULL) and
000295    ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
000296    ** unavailable.
000297    */
000298    if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
000299      rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
000300    }else{
000301      double r;
000302      rc = pVfs->xCurrentTime(pVfs, &r);
000303      *pTimeOut = (sqlite3_int64)(r*86400000.0);
000304    }
000305    return rc;
000306  }
000307  
000308  int sqlite3OsOpenMalloc(
000309    sqlite3_vfs *pVfs,
000310    const char *zFile,
000311    sqlite3_file **ppFile,
000312    int flags,
000313    int *pOutFlags
000314  ){
000315    int rc;
000316    sqlite3_file *pFile;
000317    pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
000318    if( pFile ){
000319      rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
000320      if( rc!=SQLITE_OK ){
000321        sqlite3_free(pFile);
000322        *ppFile = 0;
000323      }else{
000324        *ppFile = pFile;
000325      }
000326    }else{
000327      *ppFile = 0;
000328      rc = SQLITE_NOMEM_BKPT;
000329    }
000330    assert( *ppFile!=0 || rc!=SQLITE_OK );
000331    return rc;
000332  }
000333  void sqlite3OsCloseFree(sqlite3_file *pFile){
000334    assert( pFile );
000335    sqlite3OsClose(pFile);
000336    sqlite3_free(pFile);
000337  }
000338  
000339  /*
000340  ** This function is a wrapper around the OS specific implementation of
000341  ** sqlite3_os_init(). The purpose of the wrapper is to provide the
000342  ** ability to simulate a malloc failure, so that the handling of an
000343  ** error in sqlite3_os_init() by the upper layers can be tested.
000344  */
000345  int sqlite3OsInit(void){
000346    void *p = sqlite3_malloc(10);
000347    if( p==0 ) return SQLITE_NOMEM_BKPT;
000348    sqlite3_free(p);
000349    return sqlite3_os_init();
000350  }
000351  
000352  /*
000353  ** The list of all registered VFS implementations.
000354  */
000355  static sqlite3_vfs * SQLITE_WSD vfsList = 0;
000356  #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
000357  
000358  /*
000359  ** Locate a VFS by name.  If no name is given, simply return the
000360  ** first VFS on the list.
000361  */
000362  sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
000363    sqlite3_vfs *pVfs = 0;
000364  #if SQLITE_THREADSAFE
000365    sqlite3_mutex *mutex;
000366  #endif
000367  #ifndef SQLITE_OMIT_AUTOINIT
000368    int rc = sqlite3_initialize();
000369    if( rc ) return 0;
000370  #endif
000371  #if SQLITE_THREADSAFE
000372    mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);
000373  #endif
000374    sqlite3_mutex_enter(mutex);
000375    for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
000376      if( zVfs==0 ) break;
000377      if( strcmp(zVfs, pVfs->zName)==0 ) break;
000378    }
000379    sqlite3_mutex_leave(mutex);
000380    return pVfs;
000381  }
000382  
000383  /*
000384  ** Unlink a VFS from the linked list
000385  */
000386  static void vfsUnlink(sqlite3_vfs *pVfs){
000387    assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN)) );
000388    if( pVfs==0 ){
000389      /* No-op */
000390    }else if( vfsList==pVfs ){
000391      vfsList = pVfs->pNext;
000392    }else if( vfsList ){
000393      sqlite3_vfs *p = vfsList;
000394      while( p->pNext && p->pNext!=pVfs ){
000395        p = p->pNext;
000396      }
000397      if( p->pNext==pVfs ){
000398        p->pNext = pVfs->pNext;
000399      }
000400    }
000401  }
000402  
000403  /*
000404  ** Register a VFS with the system.  It is harmless to register the same
000405  ** VFS multiple times.  The new VFS becomes the default if makeDflt is
000406  ** true.
000407  */
000408  int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
000409    MUTEX_LOGIC(sqlite3_mutex *mutex;)
000410  #ifndef SQLITE_OMIT_AUTOINIT
000411    int rc = sqlite3_initialize();
000412    if( rc ) return rc;
000413  #endif
000414  #ifdef SQLITE_ENABLE_API_ARMOR
000415    if( pVfs==0 ) return SQLITE_MISUSE_BKPT;
000416  #endif
000417  
000418    MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )
000419    sqlite3_mutex_enter(mutex);
000420    vfsUnlink(pVfs);
000421    if( makeDflt || vfsList==0 ){
000422      pVfs->pNext = vfsList;
000423      vfsList = pVfs;
000424    }else{
000425      pVfs->pNext = vfsList->pNext;
000426      vfsList->pNext = pVfs;
000427    }
000428    assert(vfsList);
000429    sqlite3_mutex_leave(mutex);
000430    return SQLITE_OK;
000431  }
000432  
000433  /*
000434  ** Unregister a VFS so that it is no longer accessible.
000435  */
000436  int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
000437    MUTEX_LOGIC(sqlite3_mutex *mutex;)
000438  #ifndef SQLITE_OMIT_AUTOINIT
000439    int rc = sqlite3_initialize();
000440    if( rc ) return rc;
000441  #endif
000442    MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )
000443    sqlite3_mutex_enter(mutex);
000444    vfsUnlink(pVfs);
000445    sqlite3_mutex_leave(mutex);
000446    return SQLITE_OK;
000447  }