Home | History | Annotate | Download | only in src
      1 /*
      2 ** 2004 May 22
      3 **
      4 ** The author disclaims copyright to this source code.  In place of
      5 ** a legal notice, here is a blessing:
      6 **
      7 **    May you do good and not evil.
      8 **    May you find forgiveness for yourself and forgive others.
      9 **    May you share freely, never taking more than you give.
     10 **
     11 ******************************************************************************
     12 **
     13 ** This file contains the VFS implementation for unix-like operating systems
     14 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
     15 **
     16 ** There are actually several different VFS implementations in this file.
     17 ** The differences are in the way that file locking is done.  The default
     18 ** implementation uses Posix Advisory Locks.  Alternative implementations
     19 ** use flock(), dot-files, various proprietary locking schemas, or simply
     20 ** skip locking all together.
     21 **
     22 ** This source file is organized into divisions where the logic for various
     23 ** subfunctions is contained within the appropriate division.  PLEASE
     24 ** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
     25 ** in the correct division and should be clearly labeled.
     26 **
     27 ** The layout of divisions is as follows:
     28 **
     29 **   *  General-purpose declarations and utility functions.
     30 **   *  Unique file ID logic used by VxWorks.
     31 **   *  Various locking primitive implementations (all except proxy locking):
     32 **      + for Posix Advisory Locks
     33 **      + for no-op locks
     34 **      + for dot-file locks
     35 **      + for flock() locking
     36 **      + for named semaphore locks (VxWorks only)
     37 **      + for AFP filesystem locks (MacOSX only)
     38 **   *  sqlite3_file methods not associated with locking.
     39 **   *  Definitions of sqlite3_io_methods objects for all locking
     40 **      methods plus "finder" functions for each locking method.
     41 **   *  sqlite3_vfs method implementations.
     42 **   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
     43 **   *  Definitions of sqlite3_vfs objects for all locking methods
     44 **      plus implementations of sqlite3_os_init() and sqlite3_os_end().
     45 */
     46 #include "sqliteInt.h"
     47 #if SQLITE_OS_UNIX              /* This file is used on unix only */
     48 
     49 /*
     50 ** There are various methods for file locking used for concurrency
     51 ** control:
     52 **
     53 **   1. POSIX locking (the default),
     54 **   2. No locking,
     55 **   3. Dot-file locking,
     56 **   4. flock() locking,
     57 **   5. AFP locking (OSX only),
     58 **   6. Named POSIX semaphores (VXWorks only),
     59 **   7. proxy locking. (OSX only)
     60 **
     61 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
     62 ** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
     63 ** selection of the appropriate locking style based on the filesystem
     64 ** where the database is located.
     65 */
     66 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
     67 #  if defined(__APPLE__)
     68 #    define SQLITE_ENABLE_LOCKING_STYLE 1
     69 #  else
     70 #    define SQLITE_ENABLE_LOCKING_STYLE 0
     71 #  endif
     72 #endif
     73 
     74 /*
     75 ** Define the OS_VXWORKS pre-processor macro to 1 if building on
     76 ** vxworks, or 0 otherwise.
     77 */
     78 #ifndef OS_VXWORKS
     79 #  if defined(__RTP__) || defined(_WRS_KERNEL)
     80 #    define OS_VXWORKS 1
     81 #  else
     82 #    define OS_VXWORKS 0
     83 #  endif
     84 #endif
     85 
     86 /*
     87 ** These #defines should enable >2GB file support on Posix if the
     88 ** underlying operating system supports it.  If the OS lacks
     89 ** large file support, these should be no-ops.
     90 **
     91 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
     92 ** on the compiler command line.  This is necessary if you are compiling
     93 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
     94 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
     95 ** without this option, LFS is enable.  But LFS does not exist in the kernel
     96 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
     97 ** portability you should omit LFS.
     98 **
     99 ** The previous paragraph was written in 2005.  (This paragraph is written
    100 ** on 2008-11-28.) These days, all Linux kernels support large files, so
    101 ** you should probably leave LFS enabled.  But some embedded platforms might
    102 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
    103 */
    104 #ifndef SQLITE_DISABLE_LFS
    105 # define _LARGE_FILE       1
    106 # ifndef _FILE_OFFSET_BITS
    107 #   define _FILE_OFFSET_BITS 64
    108 # endif
    109 # define _LARGEFILE_SOURCE 1
    110 #endif
    111 
    112 /*
    113 ** standard include files.
    114 */
    115 #include <sys/types.h>
    116 #include <sys/stat.h>
    117 #include <fcntl.h>
    118 #include <unistd.h>
    119 #include <time.h>
    120 #include <sys/time.h>
    121 #include <errno.h>
    122 #ifndef SQLITE_OMIT_WAL
    123 #include <sys/mman.h>
    124 #endif
    125 
    126 #if SQLITE_ENABLE_LOCKING_STYLE
    127 # include <sys/ioctl.h>
    128 # if OS_VXWORKS
    129 #  include <semaphore.h>
    130 #  include <limits.h>
    131 # else
    132 #  include <sys/file.h>
    133 #  include <sys/param.h>
    134 # endif
    135 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
    136 
    137 #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
    138 # include <sys/mount.h>
    139 #endif
    140 
    141 /*
    142 ** Allowed values of unixFile.fsFlags
    143 */
    144 #define SQLITE_FSFLAGS_IS_MSDOS     0x1
    145 
    146 /*
    147 ** If we are to be thread-safe, include the pthreads header and define
    148 ** the SQLITE_UNIX_THREADS macro.
    149 */
    150 #if SQLITE_THREADSAFE
    151 # include <pthread.h>
    152 # define SQLITE_UNIX_THREADS 1
    153 #endif
    154 
    155 /*
    156 ** Default permissions when creating a new file
    157 */
    158 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
    159 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
    160 #endif
    161 
    162 /*
    163  ** Default permissions when creating auto proxy dir
    164  */
    165 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
    166 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
    167 #endif
    168 
    169 /*
    170 ** Maximum supported path-length.
    171 */
    172 #define MAX_PATHNAME 512
    173 
    174 /*
    175 ** Only set the lastErrno if the error code is a real error and not
    176 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
    177 */
    178 #define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
    179 
    180 /* Forward references */
    181 typedef struct unixShm unixShm;               /* Connection shared memory */
    182 typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
    183 typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
    184 typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
    185 
    186 /*
    187 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
    188 ** cannot be closed immediately. In these cases, instances of the following
    189 ** structure are used to store the file descriptor while waiting for an
    190 ** opportunity to either close or reuse it.
    191 */
    192 struct UnixUnusedFd {
    193   int fd;                   /* File descriptor to close */
    194   int flags;                /* Flags this file descriptor was opened with */
    195   UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
    196 };
    197 
    198 /*
    199 ** The unixFile structure is subclass of sqlite3_file specific to the unix
    200 ** VFS implementations.
    201 */
    202 typedef struct unixFile unixFile;
    203 struct unixFile {
    204   sqlite3_io_methods const *pMethod;  /* Always the first entry */
    205   unixInodeInfo *pInode;              /* Info about locks on this inode */
    206   int h;                              /* The file descriptor */
    207   unsigned char eFileLock;            /* The type of lock held on this fd */
    208   unsigned char ctrlFlags;            /* Behavioral bits.  UNIXFILE_* flags */
    209   int lastErrno;                      /* The unix errno from last I/O error */
    210   void *lockingContext;               /* Locking style specific state */
    211   UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
    212   const char *zPath;                  /* Name of the file */
    213   unixShm *pShm;                      /* Shared memory segment information */
    214   int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
    215 #if SQLITE_ENABLE_LOCKING_STYLE
    216   int openFlags;                      /* The flags specified at open() */
    217 #endif
    218 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
    219   unsigned fsFlags;                   /* cached details from statfs() */
    220 #endif
    221 #if OS_VXWORKS
    222   int isDelete;                       /* Delete on close if true */
    223   struct vxworksFileId *pId;          /* Unique file ID */
    224 #endif
    225 #ifndef NDEBUG
    226   /* The next group of variables are used to track whether or not the
    227   ** transaction counter in bytes 24-27 of database files are updated
    228   ** whenever any part of the database changes.  An assertion fault will
    229   ** occur if a file is updated without also updating the transaction
    230   ** counter.  This test is made to avoid new problems similar to the
    231   ** one described by ticket #3584.
    232   */
    233   unsigned char transCntrChng;   /* True if the transaction counter changed */
    234   unsigned char dbUpdate;        /* True if any part of database file changed */
    235   unsigned char inNormalWrite;   /* True if in a normal write operation */
    236 #endif
    237 #ifdef SQLITE_TEST
    238   /* In test mode, increase the size of this structure a bit so that
    239   ** it is larger than the struct CrashFile defined in test6.c.
    240   */
    241   char aPadding[32];
    242 #endif
    243 };
    244 
    245 /*
    246 ** Allowed values for the unixFile.ctrlFlags bitmask:
    247 */
    248 #define UNIXFILE_EXCL   0x01     /* Connections from one process only */
    249 #define UNIXFILE_RDONLY 0x02     /* Connection is read only */
    250 #define UNIXFILE_DIRSYNC 0x04    /* Directory sync needed */
    251 
    252 /*
    253 ** Include code that is common to all os_*.c files
    254 */
    255 #include "os_common.h"
    256 
    257 /*
    258 ** Define various macros that are missing from some systems.
    259 */
    260 #ifndef O_LARGEFILE
    261 # define O_LARGEFILE 0
    262 #endif
    263 #ifdef SQLITE_DISABLE_LFS
    264 # undef O_LARGEFILE
    265 # define O_LARGEFILE 0
    266 #endif
    267 #ifndef O_NOFOLLOW
    268 # define O_NOFOLLOW 0
    269 #endif
    270 #ifndef O_BINARY
    271 # define O_BINARY 0
    272 #endif
    273 
    274 /*
    275 ** The threadid macro resolves to the thread-id or to 0.  Used for
    276 ** testing and debugging only.
    277 */
    278 #if SQLITE_THREADSAFE
    279 #define threadid pthread_self()
    280 #else
    281 #define threadid 0
    282 #endif
    283 
    284 /* Forward reference */
    285 static int openDirectory(const char*, int*);
    286 
    287 /*
    288 ** Many system calls are accessed through pointer-to-functions so that
    289 ** they may be overridden at runtime to facilitate fault injection during
    290 ** testing and sandboxing.  The following array holds the names and pointers
    291 ** to all overrideable system calls.
    292 */
    293 static struct unix_syscall {
    294   const char *zName;            /* Name of the sytem call */
    295   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
    296   sqlite3_syscall_ptr pDefault; /* Default value */
    297 } aSyscall[] = {
    298   { "open",         (sqlite3_syscall_ptr)open,       0  },
    299 #define osOpen      ((int(*)(const char*,int,...))aSyscall[0].pCurrent)
    300 
    301   { "close",        (sqlite3_syscall_ptr)close,      0  },
    302 #define osClose     ((int(*)(int))aSyscall[1].pCurrent)
    303 
    304   { "access",       (sqlite3_syscall_ptr)access,     0  },
    305 #define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)
    306 
    307   { "getcwd",       (sqlite3_syscall_ptr)getcwd,     0  },
    308 #define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
    309 
    310   { "stat",         (sqlite3_syscall_ptr)stat,       0  },
    311 #define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
    312 
    313 /*
    314 ** The DJGPP compiler environment looks mostly like Unix, but it
    315 ** lacks the fcntl() system call.  So redefine fcntl() to be something
    316 ** that always succeeds.  This means that locking does not occur under
    317 ** DJGPP.  But it is DOS - what did you expect?
    318 */
    319 #ifdef __DJGPP__
    320   { "fstat",        0,                 0  },
    321 #define osFstat(a,b,c)    0
    322 #else
    323   { "fstat",        (sqlite3_syscall_ptr)fstat,      0  },
    324 #define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
    325 #endif
    326 
    327   { "ftruncate",    (sqlite3_syscall_ptr)ftruncate,  0  },
    328 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
    329 
    330   { "fcntl",        (sqlite3_syscall_ptr)fcntl,      0  },
    331 #define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)
    332 
    333   { "read",         (sqlite3_syscall_ptr)read,       0  },
    334 #define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
    335 
    336 #if defined(USE_PREAD) || defined(SQLITE_ENABLE_LOCKING_STYLE)
    337   { "pread",        (sqlite3_syscall_ptr)pread,      0  },
    338 #else
    339   { "pread",        (sqlite3_syscall_ptr)0,          0  },
    340 #endif
    341 #define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
    342 
    343 #if defined(USE_PREAD64)
    344   { "pread64",      (sqlite3_syscall_ptr)pread64,    0  },
    345 #else
    346   { "pread64",      (sqlite3_syscall_ptr)0,          0  },
    347 #endif
    348 #define osPread64   ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
    349 
    350   { "write",        (sqlite3_syscall_ptr)write,      0  },
    351 #define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
    352 
    353 #if defined(USE_PREAD) || defined(SQLITE_ENABLE_LOCKING_STYLE)
    354   { "pwrite",       (sqlite3_syscall_ptr)pwrite,     0  },
    355 #else
    356   { "pwrite",       (sqlite3_syscall_ptr)0,          0  },
    357 #endif
    358 #define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\
    359                     aSyscall[12].pCurrent)
    360 
    361 #if defined(USE_PREAD64)
    362   { "pwrite64",     (sqlite3_syscall_ptr)pwrite64,   0  },
    363 #else
    364   { "pwrite64",     (sqlite3_syscall_ptr)0,          0  },
    365 #endif
    366 #define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off_t))\
    367                     aSyscall[13].pCurrent)
    368 
    369 #if SQLITE_ENABLE_LOCKING_STYLE
    370   { "fchmod",       (sqlite3_syscall_ptr)fchmod,     0  },
    371 #else
    372   { "fchmod",       (sqlite3_syscall_ptr)0,          0  },
    373 #endif
    374 #define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)
    375 
    376 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
    377   { "fallocate",    (sqlite3_syscall_ptr)posix_fallocate,  0 },
    378 #else
    379   { "fallocate",    (sqlite3_syscall_ptr)0,                0 },
    380 #endif
    381 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
    382 
    383   { "unlink",       (sqlite3_syscall_ptr)unlink,           0 },
    384 #define osUnlink    ((int(*)(const char*))aSyscall[16].pCurrent)
    385 
    386   { "openDirectory",    (sqlite3_syscall_ptr)openDirectory,      0 },
    387 #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
    388 
    389 }; /* End of the overrideable system calls */
    390 
    391 /*
    392 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
    393 ** "unix" VFSes.  Return SQLITE_OK opon successfully updating the
    394 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
    395 ** system call named zName.
    396 */
    397 static int unixSetSystemCall(
    398   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
    399   const char *zName,            /* Name of system call to override */
    400   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
    401 ){
    402   unsigned int i;
    403   int rc = SQLITE_NOTFOUND;
    404 
    405   UNUSED_PARAMETER(pNotUsed);
    406   if( zName==0 ){
    407     /* If no zName is given, restore all system calls to their default
    408     ** settings and return NULL
    409     */
    410     rc = SQLITE_OK;
    411     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
    412       if( aSyscall[i].pDefault ){
    413         aSyscall[i].pCurrent = aSyscall[i].pDefault;
    414       }
    415     }
    416   }else{
    417     /* If zName is specified, operate on only the one system call
    418     ** specified.
    419     */
    420     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
    421       if( strcmp(zName, aSyscall[i].zName)==0 ){
    422         if( aSyscall[i].pDefault==0 ){
    423           aSyscall[i].pDefault = aSyscall[i].pCurrent;
    424         }
    425         rc = SQLITE_OK;
    426         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
    427         aSyscall[i].pCurrent = pNewFunc;
    428         break;
    429       }
    430     }
    431   }
    432   return rc;
    433 }
    434 
    435 /*
    436 ** Return the value of a system call.  Return NULL if zName is not a
    437 ** recognized system call name.  NULL is also returned if the system call
    438 ** is currently undefined.
    439 */
    440 static sqlite3_syscall_ptr unixGetSystemCall(
    441   sqlite3_vfs *pNotUsed,
    442   const char *zName
    443 ){
    444   unsigned int i;
    445 
    446   UNUSED_PARAMETER(pNotUsed);
    447   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
    448     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
    449   }
    450   return 0;
    451 }
    452 
    453 /*
    454 ** Return the name of the first system call after zName.  If zName==NULL
    455 ** then return the name of the first system call.  Return NULL if zName
    456 ** is the last system call or if zName is not the name of a valid
    457 ** system call.
    458 */
    459 static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
    460   int i = -1;
    461 
    462   UNUSED_PARAMETER(p);
    463   if( zName ){
    464     for(i=0; i<ArraySize(aSyscall)-1; i++){
    465       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
    466     }
    467   }
    468   for(i++; i<ArraySize(aSyscall); i++){
    469     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
    470   }
    471   return 0;
    472 }
    473 
    474 /*
    475 ** Retry open() calls that fail due to EINTR
    476 */
    477 static int robust_open(const char *z, int f, int m){
    478   int rc;
    479   do{ rc = osOpen(z,f,m); }while( rc<0 && errno==EINTR );
    480   return rc;
    481 }
    482 
    483 /*
    484 ** Helper functions to obtain and relinquish the global mutex. The
    485 ** global mutex is used to protect the unixInodeInfo and
    486 ** vxworksFileId objects used by this file, all of which may be
    487 ** shared by multiple threads.
    488 **
    489 ** Function unixMutexHeld() is used to assert() that the global mutex
    490 ** is held when required. This function is only used as part of assert()
    491 ** statements. e.g.
    492 **
    493 **   unixEnterMutex()
    494 **     assert( unixMutexHeld() );
    495 **   unixEnterLeave()
    496 */
    497 static void unixEnterMutex(void){
    498   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
    499 }
    500 static void unixLeaveMutex(void){
    501   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
    502 }
    503 #ifdef SQLITE_DEBUG
    504 static int unixMutexHeld(void) {
    505   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
    506 }
    507 #endif
    508 
    509 
    510 #ifdef SQLITE_DEBUG
    511 /*
    512 ** Helper function for printing out trace information from debugging
    513 ** binaries. This returns the string represetation of the supplied
    514 ** integer lock-type.
    515 */
    516 static const char *azFileLock(int eFileLock){
    517   switch( eFileLock ){
    518     case NO_LOCK: return "NONE";
    519     case SHARED_LOCK: return "SHARED";
    520     case RESERVED_LOCK: return "RESERVED";
    521     case PENDING_LOCK: return "PENDING";
    522     case EXCLUSIVE_LOCK: return "EXCLUSIVE";
    523   }
    524   return "ERROR";
    525 }
    526 #endif
    527 
    528 #ifdef SQLITE_LOCK_TRACE
    529 /*
    530 ** Print out information about all locking operations.
    531 **
    532 ** This routine is used for troubleshooting locks on multithreaded
    533 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
    534 ** command-line option on the compiler.  This code is normally
    535 ** turned off.
    536 */
    537 static int lockTrace(int fd, int op, struct flock *p){
    538   char *zOpName, *zType;
    539   int s;
    540   int savedErrno;
    541   if( op==F_GETLK ){
    542     zOpName = "GETLK";
    543   }else if( op==F_SETLK ){
    544     zOpName = "SETLK";
    545   }else{
    546     s = osFcntl(fd, op, p);
    547     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
    548     return s;
    549   }
    550   if( p->l_type==F_RDLCK ){
    551     zType = "RDLCK";
    552   }else if( p->l_type==F_WRLCK ){
    553     zType = "WRLCK";
    554   }else if( p->l_type==F_UNLCK ){
    555     zType = "UNLCK";
    556   }else{
    557     assert( 0 );
    558   }
    559   assert( p->l_whence==SEEK_SET );
    560   s = osFcntl(fd, op, p);
    561   savedErrno = errno;
    562   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
    563      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
    564      (int)p->l_pid, s);
    565   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
    566     struct flock l2;
    567     l2 = *p;
    568     osFcntl(fd, F_GETLK, &l2);
    569     if( l2.l_type==F_RDLCK ){
    570       zType = "RDLCK";
    571     }else if( l2.l_type==F_WRLCK ){
    572       zType = "WRLCK";
    573     }else if( l2.l_type==F_UNLCK ){
    574       zType = "UNLCK";
    575     }else{
    576       assert( 0 );
    577     }
    578     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
    579        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
    580   }
    581   errno = savedErrno;
    582   return s;
    583 }
    584 #undef osFcntl
    585 #define osFcntl lockTrace
    586 #endif /* SQLITE_LOCK_TRACE */
    587 
    588 /*
    589 ** Retry ftruncate() calls that fail due to EINTR
    590 */
    591 static int robust_ftruncate(int h, sqlite3_int64 sz){
    592   int rc;
    593   do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
    594   return rc;
    595 }
    596 
    597 /*
    598 ** This routine translates a standard POSIX errno code into something
    599 ** useful to the clients of the sqlite3 functions.  Specifically, it is
    600 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
    601 ** and a variety of "please close the file descriptor NOW" errors into
    602 ** SQLITE_IOERR
    603 **
    604 ** Errors during initialization of locks, or file system support for locks,
    605 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
    606 */
    607 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
    608   switch (posixError) {
    609 #if 0
    610   /* At one point this code was not commented out. In theory, this branch
    611   ** should never be hit, as this function should only be called after
    612   ** a locking-related function (i.e. fcntl()) has returned non-zero with
    613   ** the value of errno as the first argument. Since a system call has failed,
    614   ** errno should be non-zero.
    615   **
    616   ** Despite this, if errno really is zero, we still don't want to return
    617   ** SQLITE_OK. The system call failed, and *some* SQLite error should be
    618   ** propagated back to the caller. Commenting this branch out means errno==0
    619   ** will be handled by the "default:" case below.
    620   */
    621   case 0:
    622     return SQLITE_OK;
    623 #endif
    624 
    625   case EAGAIN:
    626   case ETIMEDOUT:
    627   case EBUSY:
    628   case EINTR:
    629   case ENOLCK:
    630     /* random NFS retry error, unless during file system support
    631      * introspection, in which it actually means what it says */
    632     return SQLITE_BUSY;
    633 
    634   case EACCES:
    635     /* EACCES is like EAGAIN during locking operations, but not any other time*/
    636     if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
    637 	(sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
    638 	(sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
    639 	(sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
    640       return SQLITE_BUSY;
    641     }
    642     /* else fall through */
    643   case EPERM:
    644     return SQLITE_PERM;
    645 
    646   /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
    647   ** this module never makes such a call. And the code in SQLite itself
    648   ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
    649   ** this case is also commented out. If the system does set errno to EDEADLK,
    650   ** the default SQLITE_IOERR_XXX code will be returned. */
    651 #if 0
    652   case EDEADLK:
    653     return SQLITE_IOERR_BLOCKED;
    654 #endif
    655 
    656 #if EOPNOTSUPP!=ENOTSUP
    657   case EOPNOTSUPP:
    658     /* something went terribly awry, unless during file system support
    659      * introspection, in which it actually means what it says */
    660 #endif
    661 #ifdef ENOTSUP
    662   case ENOTSUP:
    663     /* invalid fd, unless during file system support introspection, in which
    664      * it actually means what it says */
    665 #endif
    666   case EIO:
    667   case EBADF:
    668   case EINVAL:
    669   case ENOTCONN:
    670   case ENODEV:
    671   case ENXIO:
    672   case ENOENT:
    673   case ESTALE:
    674   case ENOSYS:
    675     /* these should force the client to close the file and reconnect */
    676 
    677   default:
    678     return sqliteIOErr;
    679   }
    680 }
    681 
    682 
    683 
    684 /******************************************************************************
    685 ****************** Begin Unique File ID Utility Used By VxWorks ***************
    686 **
    687 ** On most versions of unix, we can get a unique ID for a file by concatenating
    688 ** the device number and the inode number.  But this does not work on VxWorks.
    689 ** On VxWorks, a unique file id must be based on the canonical filename.
    690 **
    691 ** A pointer to an instance of the following structure can be used as a
    692 ** unique file ID in VxWorks.  Each instance of this structure contains
    693 ** a copy of the canonical filename.  There is also a reference count.
    694 ** The structure is reclaimed when the number of pointers to it drops to
    695 ** zero.
    696 **
    697 ** There are never very many files open at one time and lookups are not
    698 ** a performance-critical path, so it is sufficient to put these
    699 ** structures on a linked list.
    700 */
    701 struct vxworksFileId {
    702   struct vxworksFileId *pNext;  /* Next in a list of them all */
    703   int nRef;                     /* Number of references to this one */
    704   int nName;                    /* Length of the zCanonicalName[] string */
    705   char *zCanonicalName;         /* Canonical filename */
    706 };
    707 
    708 #if OS_VXWORKS
    709 /*
    710 ** All unique filenames are held on a linked list headed by this
    711 ** variable:
    712 */
    713 static struct vxworksFileId *vxworksFileList = 0;
    714 
    715 /*
    716 ** Simplify a filename into its canonical form
    717 ** by making the following changes:
    718 **
    719 **  * removing any trailing and duplicate /
    720 **  * convert /./ into just /
    721 **  * convert /A/../ where A is any simple name into just /
    722 **
    723 ** Changes are made in-place.  Return the new name length.
    724 **
    725 ** The original filename is in z[0..n-1].  Return the number of
    726 ** characters in the simplified name.
    727 */
    728 static int vxworksSimplifyName(char *z, int n){
    729   int i, j;
    730   while( n>1 && z[n-1]=='/' ){ n--; }
    731   for(i=j=0; i<n; i++){
    732     if( z[i]=='/' ){
    733       if( z[i+1]=='/' ) continue;
    734       if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
    735         i += 1;
    736         continue;
    737       }
    738       if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
    739         while( j>0 && z[j-1]!='/' ){ j--; }
    740         if( j>0 ){ j--; }
    741         i += 2;
    742         continue;
    743       }
    744     }
    745     z[j++] = z[i];
    746   }
    747   z[j] = 0;
    748   return j;
    749 }
    750 
    751 /*
    752 ** Find a unique file ID for the given absolute pathname.  Return
    753 ** a pointer to the vxworksFileId object.  This pointer is the unique
    754 ** file ID.
    755 **
    756 ** The nRef field of the vxworksFileId object is incremented before
    757 ** the object is returned.  A new vxworksFileId object is created
    758 ** and added to the global list if necessary.
    759 **
    760 ** If a memory allocation error occurs, return NULL.
    761 */
    762 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
    763   struct vxworksFileId *pNew;         /* search key and new file ID */
    764   struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
    765   int n;                              /* Length of zAbsoluteName string */
    766 
    767   assert( zAbsoluteName[0]=='/' );
    768   n = (int)strlen(zAbsoluteName);
    769   pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
    770   if( pNew==0 ) return 0;
    771   pNew->zCanonicalName = (char*)&pNew[1];
    772   memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
    773   n = vxworksSimplifyName(pNew->zCanonicalName, n);
    774 
    775   /* Search for an existing entry that matching the canonical name.
    776   ** If found, increment the reference count and return a pointer to
    777   ** the existing file ID.
    778   */
    779   unixEnterMutex();
    780   for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
    781     if( pCandidate->nName==n
    782      && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
    783     ){
    784        sqlite3_free(pNew);
    785        pCandidate->nRef++;
    786        unixLeaveMutex();
    787        return pCandidate;
    788     }
    789   }
    790 
    791   /* No match was found.  We will make a new file ID */
    792   pNew->nRef = 1;
    793   pNew->nName = n;
    794   pNew->pNext = vxworksFileList;
    795   vxworksFileList = pNew;
    796   unixLeaveMutex();
    797   return pNew;
    798 }
    799 
    800 /*
    801 ** Decrement the reference count on a vxworksFileId object.  Free
    802 ** the object when the reference count reaches zero.
    803 */
    804 static void vxworksReleaseFileId(struct vxworksFileId *pId){
    805   unixEnterMutex();
    806   assert( pId->nRef>0 );
    807   pId->nRef--;
    808   if( pId->nRef==0 ){
    809     struct vxworksFileId **pp;
    810     for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
    811     assert( *pp==pId );
    812     *pp = pId->pNext;
    813     sqlite3_free(pId);
    814   }
    815   unixLeaveMutex();
    816 }
    817 #endif /* OS_VXWORKS */
    818 /*************** End of Unique File ID Utility Used By VxWorks ****************
    819 ******************************************************************************/
    820 
    821 
    822 /******************************************************************************
    823 *************************** Posix Advisory Locking ****************************
    824 **
    825 ** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
    826 ** section 6.5.2.2 lines 483 through 490 specify that when a process
    827 ** sets or clears a lock, that operation overrides any prior locks set
    828 ** by the same process.  It does not explicitly say so, but this implies
    829 ** that it overrides locks set by the same process using a different
    830 ** file descriptor.  Consider this test case:
    831 **
    832 **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
    833 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
    834 **
    835 ** Suppose ./file1 and ./file2 are really the same file (because
    836 ** one is a hard or symbolic link to the other) then if you set
    837 ** an exclusive lock on fd1, then try to get an exclusive lock
    838 ** on fd2, it works.  I would have expected the second lock to
    839 ** fail since there was already a lock on the file due to fd1.
    840 ** But not so.  Since both locks came from the same process, the
    841 ** second overrides the first, even though they were on different
    842 ** file descriptors opened on different file names.
    843 **
    844 ** This means that we cannot use POSIX locks to synchronize file access
    845 ** among competing threads of the same process.  POSIX locks will work fine
    846 ** to synchronize access for threads in separate processes, but not
    847 ** threads within the same process.
    848 **
    849 ** To work around the problem, SQLite has to manage file locks internally
    850 ** on its own.  Whenever a new database is opened, we have to find the
    851 ** specific inode of the database file (the inode is determined by the
    852 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
    853 ** and check for locks already existing on that inode.  When locks are
    854 ** created or removed, we have to look at our own internal record of the
    855 ** locks to see if another thread has previously set a lock on that same
    856 ** inode.
    857 **
    858 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
    859 ** For VxWorks, we have to use the alternative unique ID system based on
    860 ** canonical filename and implemented in the previous division.)
    861 **
    862 ** The sqlite3_file structure for POSIX is no longer just an integer file
    863 ** descriptor.  It is now a structure that holds the integer file
    864 ** descriptor and a pointer to a structure that describes the internal
    865 ** locks on the corresponding inode.  There is one locking structure
    866 ** per inode, so if the same inode is opened twice, both unixFile structures
    867 ** point to the same locking structure.  The locking structure keeps
    868 ** a reference count (so we will know when to delete it) and a "cnt"
    869 ** field that tells us its internal lock status.  cnt==0 means the
    870 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
    871 ** cnt>0 means there are cnt shared locks on the file.
    872 **
    873 ** Any attempt to lock or unlock a file first checks the locking
    874 ** structure.  The fcntl() system call is only invoked to set a
    875 ** POSIX lock if the internal lock structure transitions between
    876 ** a locked and an unlocked state.
    877 **
    878 ** But wait:  there are yet more problems with POSIX advisory locks.
    879 **
    880 ** If you close a file descriptor that points to a file that has locks,
    881 ** all locks on that file that are owned by the current process are
    882 ** released.  To work around this problem, each unixInodeInfo object
    883 ** maintains a count of the number of pending locks on tha inode.
    884 ** When an attempt is made to close an unixFile, if there are
    885 ** other unixFile open on the same inode that are holding locks, the call
    886 ** to close() the file descriptor is deferred until all of the locks clear.
    887 ** The unixInodeInfo structure keeps a list of file descriptors that need to
    888 ** be closed and that list is walked (and cleared) when the last lock
    889 ** clears.
    890 **
    891 ** Yet another problem:  LinuxThreads do not play well with posix locks.
    892 **
    893 ** Many older versions of linux use the LinuxThreads library which is
    894 ** not posix compliant.  Under LinuxThreads, a lock created by thread
    895 ** A cannot be modified or overridden by a different thread B.
    896 ** Only thread A can modify the lock.  Locking behavior is correct
    897 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
    898 ** on linux - with NPTL a lock created by thread A can override locks
    899 ** in thread B.  But there is no way to know at compile-time which
    900 ** threading library is being used.  So there is no way to know at
    901 ** compile-time whether or not thread A can override locks on thread B.
    902 ** One has to do a run-time check to discover the behavior of the
    903 ** current process.
    904 **
    905 ** SQLite used to support LinuxThreads.  But support for LinuxThreads
    906 ** was dropped beginning with version 3.7.0.  SQLite will still work with
    907 ** LinuxThreads provided that (1) there is no more than one connection
    908 ** per database file in the same process and (2) database connections
    909 ** do not move across threads.
    910 */
    911 
    912 /*
    913 ** An instance of the following structure serves as the key used
    914 ** to locate a particular unixInodeInfo object.
    915 */
    916 struct unixFileId {
    917   dev_t dev;                  /* Device number */
    918 #if OS_VXWORKS
    919   struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
    920 #else
    921   ino_t ino;                  /* Inode number */
    922 #endif
    923 };
    924 
    925 /*
    926 ** An instance of the following structure is allocated for each open
    927 ** inode.  Or, on LinuxThreads, there is one of these structures for
    928 ** each inode opened by each thread.
    929 **
    930 ** A single inode can have multiple file descriptors, so each unixFile
    931 ** structure contains a pointer to an instance of this object and this
    932 ** object keeps a count of the number of unixFile pointing to it.
    933 */
    934 struct unixInodeInfo {
    935   struct unixFileId fileId;       /* The lookup key */
    936   int nShared;                    /* Number of SHARED locks held */
    937   unsigned char eFileLock;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
    938   unsigned char bProcessLock;     /* An exclusive process lock is held */
    939   int nRef;                       /* Number of pointers to this structure */
    940   unixShmNode *pShmNode;          /* Shared memory associated with this inode */
    941   int nLock;                      /* Number of outstanding file locks */
    942   UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
    943   unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
    944   unixInodeInfo *pPrev;           /*    .... doubly linked */
    945 #if defined(SQLITE_ENABLE_LOCKING_STYLE)
    946   unsigned long long sharedByte;  /* for AFP simulated shared lock */
    947 #endif
    948 #if OS_VXWORKS
    949   sem_t *pSem;                    /* Named POSIX semaphore */
    950   char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
    951 #endif
    952 };
    953 
    954 /*
    955 ** A lists of all unixInodeInfo objects.
    956 */
    957 static unixInodeInfo *inodeList = 0;
    958 
    959 /*
    960 **
    961 ** This function - unixLogError_x(), is only ever called via the macro
    962 ** unixLogError().
    963 **
    964 ** It is invoked after an error occurs in an OS function and errno has been
    965 ** set. It logs a message using sqlite3_log() containing the current value of
    966 ** errno and, if possible, the human-readable equivalent from strerror() or
    967 ** strerror_r().
    968 **
    969 ** The first argument passed to the macro should be the error code that
    970 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
    971 ** The two subsequent arguments should be the name of the OS function that
    972 ** failed (e.g. "unlink", "open") and the the associated file-system path,
    973 ** if any.
    974 */
    975 #define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)
    976 static int unixLogErrorAtLine(
    977   int errcode,                    /* SQLite error code */
    978   const char *zFunc,              /* Name of OS function that failed */
    979   const char *zPath,              /* File path associated with error */
    980   int iLine                       /* Source line number where error occurred */
    981 ){
    982   char *zErr;                     /* Message from strerror() or equivalent */
    983   int iErrno = errno;             /* Saved syscall error number */
    984 
    985   /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
    986   ** the strerror() function to obtain the human-readable error message
    987   ** equivalent to errno. Otherwise, use strerror_r().
    988   */
    989 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
    990   char aErr[80];
    991   memset(aErr, 0, sizeof(aErr));
    992   zErr = aErr;
    993 
    994   /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
    995   ** assume that the system provides the the GNU version of strerror_r() that
    996   ** returns a pointer to a buffer containing the error message. That pointer
    997   ** may point to aErr[], or it may point to some static storage somewhere.
    998   ** Otherwise, assume that the system provides the POSIX version of
    999   ** strerror_r(), which always writes an error message into aErr[].
   1000   **
   1001   ** If the code incorrectly assumes that it is the POSIX version that is
   1002   ** available, the error message will often be an empty string. Not a
   1003   ** huge problem. Incorrectly concluding that the GNU version is available
   1004   ** could lead to a segfault though.
   1005   */
   1006 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
   1007   zErr =
   1008 # endif
   1009   strerror_r(iErrno, aErr, sizeof(aErr)-1);
   1010 
   1011 #elif SQLITE_THREADSAFE
   1012   /* This is a threadsafe build, but strerror_r() is not available. */
   1013   zErr = "";
   1014 #else
   1015   /* Non-threadsafe build, use strerror(). */
   1016   zErr = strerror(iErrno);
   1017 #endif
   1018 
   1019   assert( errcode!=SQLITE_OK );
   1020   if( zPath==0 ) zPath = "";
   1021   sqlite3_log(errcode,
   1022       "os_unix.c:%d: (%d) %s(%s) - %s",
   1023       iLine, iErrno, zFunc, zPath, zErr
   1024   );
   1025 
   1026   return errcode;
   1027 }
   1028 
   1029 /*
   1030 ** Close a file descriptor.
   1031 **
   1032 ** We assume that close() almost always works, since it is only in a
   1033 ** very sick application or on a very sick platform that it might fail.
   1034 ** If it does fail, simply leak the file descriptor, but do log the
   1035 ** error.
   1036 **
   1037 ** Note that it is not safe to retry close() after EINTR since the
   1038 ** file descriptor might have already been reused by another thread.
   1039 ** So we don't even try to recover from an EINTR.  Just log the error
   1040 ** and move on.
   1041 */
   1042 static void robust_close(unixFile *pFile, int h, int lineno){
   1043   if( osClose(h) ){
   1044     unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
   1045                        pFile ? pFile->zPath : 0, lineno);
   1046   }
   1047 }
   1048 
   1049 /*
   1050 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
   1051 */
   1052 static void closePendingFds(unixFile *pFile){
   1053   unixInodeInfo *pInode = pFile->pInode;
   1054   UnixUnusedFd *p;
   1055   UnixUnusedFd *pNext;
   1056   for(p=pInode->pUnused; p; p=pNext){
   1057     pNext = p->pNext;
   1058     robust_close(pFile, p->fd, __LINE__);
   1059     sqlite3_free(p);
   1060   }
   1061   pInode->pUnused = 0;
   1062 }
   1063 
   1064 /*
   1065 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
   1066 **
   1067 ** The mutex entered using the unixEnterMutex() function must be held
   1068 ** when this function is called.
   1069 */
   1070 static void releaseInodeInfo(unixFile *pFile){
   1071   unixInodeInfo *pInode = pFile->pInode;
   1072   assert( unixMutexHeld() );
   1073   if( ALWAYS(pInode) ){
   1074     pInode->nRef--;
   1075     if( pInode->nRef==0 ){
   1076       assert( pInode->pShmNode==0 );
   1077       closePendingFds(pFile);
   1078       if( pInode->pPrev ){
   1079         assert( pInode->pPrev->pNext==pInode );
   1080         pInode->pPrev->pNext = pInode->pNext;
   1081       }else{
   1082         assert( inodeList==pInode );
   1083         inodeList = pInode->pNext;
   1084       }
   1085       if( pInode->pNext ){
   1086         assert( pInode->pNext->pPrev==pInode );
   1087         pInode->pNext->pPrev = pInode->pPrev;
   1088       }
   1089       sqlite3_free(pInode);
   1090     }
   1091   }
   1092 }
   1093 
   1094 /*
   1095 ** Given a file descriptor, locate the unixInodeInfo object that
   1096 ** describes that file descriptor.  Create a new one if necessary.  The
   1097 ** return value might be uninitialized if an error occurs.
   1098 **
   1099 ** The mutex entered using the unixEnterMutex() function must be held
   1100 ** when this function is called.
   1101 **
   1102 ** Return an appropriate error code.
   1103 */
   1104 static int findInodeInfo(
   1105   unixFile *pFile,               /* Unix file with file desc used in the key */
   1106   unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
   1107 ){
   1108   int rc;                        /* System call return code */
   1109   int fd;                        /* The file descriptor for pFile */
   1110   struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
   1111   struct stat statbuf;           /* Low-level file information */
   1112   unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
   1113 
   1114   assert( unixMutexHeld() );
   1115 
   1116   /* Get low-level information about the file that we can used to
   1117   ** create a unique name for the file.
   1118   */
   1119   fd = pFile->h;
   1120   rc = osFstat(fd, &statbuf);
   1121   if( rc!=0 ){
   1122     pFile->lastErrno = errno;
   1123 #ifdef EOVERFLOW
   1124     if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
   1125 #endif
   1126     return SQLITE_IOERR;
   1127   }
   1128 
   1129 #ifdef __APPLE__
   1130   /* On OS X on an msdos filesystem, the inode number is reported
   1131   ** incorrectly for zero-size files.  See ticket #3260.  To work
   1132   ** around this problem (we consider it a bug in OS X, not SQLite)
   1133   ** we always increase the file size to 1 by writing a single byte
   1134   ** prior to accessing the inode number.  The one byte written is
   1135   ** an ASCII 'S' character which also happens to be the first byte
   1136   ** in the header of every SQLite database.  In this way, if there
   1137   ** is a race condition such that another thread has already populated
   1138   ** the first page of the database, no damage is done.
   1139   */
   1140   if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
   1141     do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
   1142     if( rc!=1 ){
   1143       pFile->lastErrno = errno;
   1144       return SQLITE_IOERR;
   1145     }
   1146     rc = osFstat(fd, &statbuf);
   1147     if( rc!=0 ){
   1148       pFile->lastErrno = errno;
   1149       return SQLITE_IOERR;
   1150     }
   1151   }
   1152 #endif
   1153 
   1154   memset(&fileId, 0, sizeof(fileId));
   1155   fileId.dev = statbuf.st_dev;
   1156 #if OS_VXWORKS
   1157   fileId.pId = pFile->pId;
   1158 #else
   1159   fileId.ino = statbuf.st_ino;
   1160 #endif
   1161   pInode = inodeList;
   1162   while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
   1163     pInode = pInode->pNext;
   1164   }
   1165   if( pInode==0 ){
   1166     pInode = sqlite3_malloc( sizeof(*pInode) );
   1167     if( pInode==0 ){
   1168       return SQLITE_NOMEM;
   1169     }
   1170     memset(pInode, 0, sizeof(*pInode));
   1171     memcpy(&pInode->fileId, &fileId, sizeof(fileId));
   1172     pInode->nRef = 1;
   1173     pInode->pNext = inodeList;
   1174     pInode->pPrev = 0;
   1175     if( inodeList ) inodeList->pPrev = pInode;
   1176     inodeList = pInode;
   1177   }else{
   1178     pInode->nRef++;
   1179   }
   1180   *ppInode = pInode;
   1181   return SQLITE_OK;
   1182 }
   1183 
   1184 
   1185 /*
   1186 ** This routine checks if there is a RESERVED lock held on the specified
   1187 ** file by this or any other process. If such a lock is held, set *pResOut
   1188 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   1189 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   1190 */
   1191 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
   1192   int rc = SQLITE_OK;
   1193   int reserved = 0;
   1194   unixFile *pFile = (unixFile*)id;
   1195 
   1196   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   1197 
   1198   assert( pFile );
   1199   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
   1200 
   1201   /* Check if a thread in this process holds such a lock */
   1202   if( pFile->pInode->eFileLock>SHARED_LOCK ){
   1203     reserved = 1;
   1204   }
   1205 
   1206   /* Otherwise see if some other process holds it.
   1207   */
   1208 #ifndef __DJGPP__
   1209   if( !reserved && !pFile->pInode->bProcessLock ){
   1210     struct flock lock;
   1211     lock.l_whence = SEEK_SET;
   1212     lock.l_start = RESERVED_BYTE;
   1213     lock.l_len = 1;
   1214     lock.l_type = F_WRLCK;
   1215     if( osFcntl(pFile->h, F_GETLK, &lock) ){
   1216       rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
   1217       pFile->lastErrno = errno;
   1218     } else if( lock.l_type!=F_UNLCK ){
   1219       reserved = 1;
   1220     }
   1221   }
   1222 #endif
   1223 
   1224   unixLeaveMutex();
   1225   OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
   1226 
   1227   *pResOut = reserved;
   1228   return rc;
   1229 }
   1230 
   1231 /*
   1232 ** Attempt to set a system-lock on the file pFile.  The lock is
   1233 ** described by pLock.
   1234 **
   1235 ** If the pFile was opened read/write from unix-excl, then the only lock
   1236 ** ever obtained is an exclusive lock, and it is obtained exactly once
   1237 ** the first time any lock is attempted.  All subsequent system locking
   1238 ** operations become no-ops.  Locking operations still happen internally,
   1239 ** in order to coordinate access between separate database connections
   1240 ** within this process, but all of that is handled in memory and the
   1241 ** operating system does not participate.
   1242 **
   1243 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
   1244 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
   1245 ** and is read-only.
   1246 **
   1247 ** Zero is returned if the call completes successfully, or -1 if a call
   1248 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
   1249 */
   1250 static int unixFileLock(unixFile *pFile, struct flock *pLock){
   1251   int rc;
   1252   unixInodeInfo *pInode = pFile->pInode;
   1253   assert( unixMutexHeld() );
   1254   assert( pInode!=0 );
   1255   if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
   1256    && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
   1257   ){
   1258     if( pInode->bProcessLock==0 ){
   1259       struct flock lock;
   1260       assert( pInode->nLock==0 );
   1261       lock.l_whence = SEEK_SET;
   1262       lock.l_start = SHARED_FIRST;
   1263       lock.l_len = SHARED_SIZE;
   1264       lock.l_type = F_WRLCK;
   1265       rc = osFcntl(pFile->h, F_SETLK, &lock);
   1266       if( rc<0 ) return rc;
   1267       pInode->bProcessLock = 1;
   1268       pInode->nLock++;
   1269     }else{
   1270       rc = 0;
   1271     }
   1272   }else{
   1273     rc = osFcntl(pFile->h, F_SETLK, pLock);
   1274   }
   1275   return rc;
   1276 }
   1277 
   1278 /*
   1279 ** Lock the file with the lock specified by parameter eFileLock - one
   1280 ** of the following:
   1281 **
   1282 **     (1) SHARED_LOCK
   1283 **     (2) RESERVED_LOCK
   1284 **     (3) PENDING_LOCK
   1285 **     (4) EXCLUSIVE_LOCK
   1286 **
   1287 ** Sometimes when requesting one lock state, additional lock states
   1288 ** are inserted in between.  The locking might fail on one of the later
   1289 ** transitions leaving the lock state different from what it started but
   1290 ** still short of its goal.  The following chart shows the allowed
   1291 ** transitions and the inserted intermediate states:
   1292 **
   1293 **    UNLOCKED -> SHARED
   1294 **    SHARED -> RESERVED
   1295 **    SHARED -> (PENDING) -> EXCLUSIVE
   1296 **    RESERVED -> (PENDING) -> EXCLUSIVE
   1297 **    PENDING -> EXCLUSIVE
   1298 **
   1299 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   1300 ** routine to lower a locking level.
   1301 */
   1302 static int unixLock(sqlite3_file *id, int eFileLock){
   1303   /* The following describes the implementation of the various locks and
   1304   ** lock transitions in terms of the POSIX advisory shared and exclusive
   1305   ** lock primitives (called read-locks and write-locks below, to avoid
   1306   ** confusion with SQLite lock names). The algorithms are complicated
   1307   ** slightly in order to be compatible with windows systems simultaneously
   1308   ** accessing the same database file, in case that is ever required.
   1309   **
   1310   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
   1311   ** byte', each single bytes at well known offsets, and the 'shared byte
   1312   ** range', a range of 510 bytes at a well known offset.
   1313   **
   1314   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
   1315   ** byte'.  If this is successful, a random byte from the 'shared byte
   1316   ** range' is read-locked and the lock on the 'pending byte' released.
   1317   **
   1318   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
   1319   ** A RESERVED lock is implemented by grabbing a write-lock on the
   1320   ** 'reserved byte'.
   1321   **
   1322   ** A process may only obtain a PENDING lock after it has obtained a
   1323   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
   1324   ** on the 'pending byte'. This ensures that no new SHARED locks can be
   1325   ** obtained, but existing SHARED locks are allowed to persist. A process
   1326   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
   1327   ** This property is used by the algorithm for rolling back a journal file
   1328   ** after a crash.
   1329   **
   1330   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
   1331   ** implemented by obtaining a write-lock on the entire 'shared byte
   1332   ** range'. Since all other locks require a read-lock on one of the bytes
   1333   ** within this range, this ensures that no other locks are held on the
   1334   ** database.
   1335   **
   1336   ** The reason a single byte cannot be used instead of the 'shared byte
   1337   ** range' is that some versions of windows do not support read-locks. By
   1338   ** locking a random byte from a range, concurrent SHARED locks may exist
   1339   ** even if the locking primitive used is always a write-lock.
   1340   */
   1341   int rc = SQLITE_OK;
   1342   unixFile *pFile = (unixFile*)id;
   1343   unixInodeInfo *pInode = pFile->pInode;
   1344   struct flock lock;
   1345   int tErrno = 0;
   1346 
   1347   assert( pFile );
   1348   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
   1349       azFileLock(eFileLock), azFileLock(pFile->eFileLock),
   1350       azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
   1351 
   1352   /* If there is already a lock of this type or more restrictive on the
   1353   ** unixFile, do nothing. Don't use the end_lock: exit path, as
   1354   ** unixEnterMutex() hasn't been called yet.
   1355   */
   1356   if( pFile->eFileLock>=eFileLock ){
   1357     OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
   1358             azFileLock(eFileLock)));
   1359     return SQLITE_OK;
   1360   }
   1361 
   1362   /* Make sure the locking sequence is correct.
   1363   **  (1) We never move from unlocked to anything higher than shared lock.
   1364   **  (2) SQLite never explicitly requests a pendig lock.
   1365   **  (3) A shared lock is always held when a reserve lock is requested.
   1366   */
   1367   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
   1368   assert( eFileLock!=PENDING_LOCK );
   1369   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
   1370 
   1371   /* This mutex is needed because pFile->pInode is shared across threads
   1372   */
   1373   unixEnterMutex();
   1374   pInode = pFile->pInode;
   1375 
   1376   /* If some thread using this PID has a lock via a different unixFile*
   1377   ** handle that precludes the requested lock, return BUSY.
   1378   */
   1379   if( (pFile->eFileLock!=pInode->eFileLock &&
   1380           (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
   1381   ){
   1382     rc = SQLITE_BUSY;
   1383     goto end_lock;
   1384   }
   1385 
   1386   /* If a SHARED lock is requested, and some thread using this PID already
   1387   ** has a SHARED or RESERVED lock, then increment reference counts and
   1388   ** return SQLITE_OK.
   1389   */
   1390   if( eFileLock==SHARED_LOCK &&
   1391       (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
   1392     assert( eFileLock==SHARED_LOCK );
   1393     assert( pFile->eFileLock==0 );
   1394     assert( pInode->nShared>0 );
   1395     pFile->eFileLock = SHARED_LOCK;
   1396     pInode->nShared++;
   1397     pInode->nLock++;
   1398     goto end_lock;
   1399   }
   1400 
   1401 
   1402   /* A PENDING lock is needed before acquiring a SHARED lock and before
   1403   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
   1404   ** be released.
   1405   */
   1406   lock.l_len = 1L;
   1407   lock.l_whence = SEEK_SET;
   1408   if( eFileLock==SHARED_LOCK
   1409       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
   1410   ){
   1411     lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
   1412     lock.l_start = PENDING_BYTE;
   1413     if( unixFileLock(pFile, &lock) ){
   1414       tErrno = errno;
   1415       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   1416       if( rc!=SQLITE_BUSY ){
   1417         pFile->lastErrno = tErrno;
   1418       }
   1419       goto end_lock;
   1420     }
   1421   }
   1422 
   1423 
   1424   /* If control gets to this point, then actually go ahead and make
   1425   ** operating system calls for the specified lock.
   1426   */
   1427   if( eFileLock==SHARED_LOCK ){
   1428     assert( pInode->nShared==0 );
   1429     assert( pInode->eFileLock==0 );
   1430     assert( rc==SQLITE_OK );
   1431 
   1432     /* Now get the read-lock */
   1433     lock.l_start = SHARED_FIRST;
   1434     lock.l_len = SHARED_SIZE;
   1435     if( unixFileLock(pFile, &lock) ){
   1436       tErrno = errno;
   1437       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   1438     }
   1439 
   1440     /* Drop the temporary PENDING lock */
   1441     lock.l_start = PENDING_BYTE;
   1442     lock.l_len = 1L;
   1443     lock.l_type = F_UNLCK;
   1444     if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
   1445       /* This could happen with a network mount */
   1446       tErrno = errno;
   1447       rc = SQLITE_IOERR_UNLOCK;
   1448     }
   1449 
   1450     if( rc ){
   1451       if( rc!=SQLITE_BUSY ){
   1452         pFile->lastErrno = tErrno;
   1453       }
   1454       goto end_lock;
   1455     }else{
   1456       pFile->eFileLock = SHARED_LOCK;
   1457       pInode->nLock++;
   1458       pInode->nShared = 1;
   1459     }
   1460   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
   1461     /* We are trying for an exclusive lock but another thread in this
   1462     ** same process is still holding a shared lock. */
   1463     rc = SQLITE_BUSY;
   1464   }else{
   1465     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
   1466     ** assumed that there is a SHARED or greater lock on the file
   1467     ** already.
   1468     */
   1469     assert( 0!=pFile->eFileLock );
   1470     lock.l_type = F_WRLCK;
   1471 
   1472     assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
   1473     if( eFileLock==RESERVED_LOCK ){
   1474       lock.l_start = RESERVED_BYTE;
   1475       lock.l_len = 1L;
   1476     }else{
   1477       lock.l_start = SHARED_FIRST;
   1478       lock.l_len = SHARED_SIZE;
   1479     }
   1480 
   1481     if( unixFileLock(pFile, &lock) ){
   1482       tErrno = errno;
   1483       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   1484       if( rc!=SQLITE_BUSY ){
   1485         pFile->lastErrno = tErrno;
   1486       }
   1487     }
   1488   }
   1489 
   1490 
   1491 #ifndef NDEBUG
   1492   /* Set up the transaction-counter change checking flags when
   1493   ** transitioning from a SHARED to a RESERVED lock.  The change
   1494   ** from SHARED to RESERVED marks the beginning of a normal
   1495   ** write operation (not a hot journal rollback).
   1496   */
   1497   if( rc==SQLITE_OK
   1498    && pFile->eFileLock<=SHARED_LOCK
   1499    && eFileLock==RESERVED_LOCK
   1500   ){
   1501     pFile->transCntrChng = 0;
   1502     pFile->dbUpdate = 0;
   1503     pFile->inNormalWrite = 1;
   1504   }
   1505 #endif
   1506 
   1507 
   1508   if( rc==SQLITE_OK ){
   1509     pFile->eFileLock = eFileLock;
   1510     pInode->eFileLock = eFileLock;
   1511   }else if( eFileLock==EXCLUSIVE_LOCK ){
   1512     pFile->eFileLock = PENDING_LOCK;
   1513     pInode->eFileLock = PENDING_LOCK;
   1514   }
   1515 
   1516 end_lock:
   1517   unixLeaveMutex();
   1518   OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
   1519       rc==SQLITE_OK ? "ok" : "failed"));
   1520   return rc;
   1521 }
   1522 
   1523 /*
   1524 ** Add the file descriptor used by file handle pFile to the corresponding
   1525 ** pUnused list.
   1526 */
   1527 static void setPendingFd(unixFile *pFile){
   1528   unixInodeInfo *pInode = pFile->pInode;
   1529   UnixUnusedFd *p = pFile->pUnused;
   1530   p->pNext = pInode->pUnused;
   1531   pInode->pUnused = p;
   1532   pFile->h = -1;
   1533   pFile->pUnused = 0;
   1534 }
   1535 
   1536 /*
   1537 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   1538 ** must be either NO_LOCK or SHARED_LOCK.
   1539 **
   1540 ** If the locking level of the file descriptor is already at or below
   1541 ** the requested locking level, this routine is a no-op.
   1542 **
   1543 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
   1544 ** the byte range is divided into 2 parts and the first part is unlocked then
   1545 ** set to a read lock, then the other part is simply unlocked.  This works
   1546 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
   1547 ** remove the write lock on a region when a read lock is set.
   1548 */
   1549 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
   1550   unixFile *pFile = (unixFile*)id;
   1551   unixInodeInfo *pInode;
   1552   struct flock lock;
   1553   int rc = SQLITE_OK;
   1554   int h;
   1555 
   1556   assert( pFile );
   1557   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
   1558       pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
   1559       getpid()));
   1560 
   1561   assert( eFileLock<=SHARED_LOCK );
   1562   if( pFile->eFileLock<=eFileLock ){
   1563     return SQLITE_OK;
   1564   }
   1565   unixEnterMutex();
   1566   h = pFile->h;
   1567   pInode = pFile->pInode;
   1568   assert( pInode->nShared!=0 );
   1569   if( pFile->eFileLock>SHARED_LOCK ){
   1570     assert( pInode->eFileLock==pFile->eFileLock );
   1571     SimulateIOErrorBenign(1);
   1572     SimulateIOError( h=(-1) )
   1573     SimulateIOErrorBenign(0);
   1574 
   1575 #ifndef NDEBUG
   1576     /* When reducing a lock such that other processes can start
   1577     ** reading the database file again, make sure that the
   1578     ** transaction counter was updated if any part of the database
   1579     ** file changed.  If the transaction counter is not updated,
   1580     ** other connections to the same file might not realize that
   1581     ** the file has changed and hence might not know to flush their
   1582     ** cache.  The use of a stale cache can lead to database corruption.
   1583     */
   1584 #if 0
   1585     assert( pFile->inNormalWrite==0
   1586          || pFile->dbUpdate==0
   1587          || pFile->transCntrChng==1 );
   1588 #endif
   1589     pFile->inNormalWrite = 0;
   1590 #endif
   1591 
   1592     /* downgrading to a shared lock on NFS involves clearing the write lock
   1593     ** before establishing the readlock - to avoid a race condition we downgrade
   1594     ** the lock in 2 blocks, so that part of the range will be covered by a
   1595     ** write lock until the rest is covered by a read lock:
   1596     **  1:   [WWWWW]
   1597     **  2:   [....W]
   1598     **  3:   [RRRRW]
   1599     **  4:   [RRRR.]
   1600     */
   1601     if( eFileLock==SHARED_LOCK ){
   1602 
   1603 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
   1604       (void)handleNFSUnlock;
   1605       assert( handleNFSUnlock==0 );
   1606 #endif
   1607 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   1608       if( handleNFSUnlock ){
   1609         int tErrno;               /* Error code from system call errors */
   1610         off_t divSize = SHARED_SIZE - 1;
   1611 
   1612         lock.l_type = F_UNLCK;
   1613         lock.l_whence = SEEK_SET;
   1614         lock.l_start = SHARED_FIRST;
   1615         lock.l_len = divSize;
   1616         if( unixFileLock(pFile, &lock)==(-1) ){
   1617           tErrno = errno;
   1618           rc = SQLITE_IOERR_UNLOCK;
   1619           if( IS_LOCK_ERROR(rc) ){
   1620             pFile->lastErrno = tErrno;
   1621           }
   1622           goto end_unlock;
   1623         }
   1624         lock.l_type = F_RDLCK;
   1625         lock.l_whence = SEEK_SET;
   1626         lock.l_start = SHARED_FIRST;
   1627         lock.l_len = divSize;
   1628         if( unixFileLock(pFile, &lock)==(-1) ){
   1629           tErrno = errno;
   1630           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
   1631           if( IS_LOCK_ERROR(rc) ){
   1632             pFile->lastErrno = tErrno;
   1633           }
   1634           goto end_unlock;
   1635         }
   1636         lock.l_type = F_UNLCK;
   1637         lock.l_whence = SEEK_SET;
   1638         lock.l_start = SHARED_FIRST+divSize;
   1639         lock.l_len = SHARED_SIZE-divSize;
   1640         if( unixFileLock(pFile, &lock)==(-1) ){
   1641           tErrno = errno;
   1642           rc = SQLITE_IOERR_UNLOCK;
   1643           if( IS_LOCK_ERROR(rc) ){
   1644             pFile->lastErrno = tErrno;
   1645           }
   1646           goto end_unlock;
   1647         }
   1648       }else
   1649 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
   1650       {
   1651         lock.l_type = F_RDLCK;
   1652         lock.l_whence = SEEK_SET;
   1653         lock.l_start = SHARED_FIRST;
   1654         lock.l_len = SHARED_SIZE;
   1655         if( unixFileLock(pFile, &lock) ){
   1656           /* In theory, the call to unixFileLock() cannot fail because another
   1657           ** process is holding an incompatible lock. If it does, this
   1658           ** indicates that the other process is not following the locking
   1659           ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
   1660           ** SQLITE_BUSY would confuse the upper layer (in practice it causes
   1661           ** an assert to fail). */
   1662           rc = SQLITE_IOERR_RDLOCK;
   1663           pFile->lastErrno = errno;
   1664           goto end_unlock;
   1665         }
   1666       }
   1667     }
   1668     lock.l_type = F_UNLCK;
   1669     lock.l_whence = SEEK_SET;
   1670     lock.l_start = PENDING_BYTE;
   1671     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
   1672     if( unixFileLock(pFile, &lock)==0 ){
   1673       pInode->eFileLock = SHARED_LOCK;
   1674     }else{
   1675       rc = SQLITE_IOERR_UNLOCK;
   1676       pFile->lastErrno = errno;
   1677       goto end_unlock;
   1678     }
   1679   }
   1680   if( eFileLock==NO_LOCK ){
   1681     /* Decrement the shared lock counter.  Release the lock using an
   1682     ** OS call only when all threads in this same process have released
   1683     ** the lock.
   1684     */
   1685     pInode->nShared--;
   1686     if( pInode->nShared==0 ){
   1687       lock.l_type = F_UNLCK;
   1688       lock.l_whence = SEEK_SET;
   1689       lock.l_start = lock.l_len = 0L;
   1690       SimulateIOErrorBenign(1);
   1691       SimulateIOError( h=(-1) )
   1692       SimulateIOErrorBenign(0);
   1693       if( unixFileLock(pFile, &lock)==0 ){
   1694         pInode->eFileLock = NO_LOCK;
   1695       }else{
   1696         rc = SQLITE_IOERR_UNLOCK;
   1697 	pFile->lastErrno = errno;
   1698         pInode->eFileLock = NO_LOCK;
   1699         pFile->eFileLock = NO_LOCK;
   1700       }
   1701     }
   1702 
   1703     /* Decrement the count of locks against this same file.  When the
   1704     ** count reaches zero, close any other file descriptors whose close
   1705     ** was deferred because of outstanding locks.
   1706     */
   1707     pInode->nLock--;
   1708     assert( pInode->nLock>=0 );
   1709     if( pInode->nLock==0 ){
   1710       closePendingFds(pFile);
   1711     }
   1712   }
   1713 
   1714 end_unlock:
   1715   unixLeaveMutex();
   1716   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
   1717   return rc;
   1718 }
   1719 
   1720 /*
   1721 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   1722 ** must be either NO_LOCK or SHARED_LOCK.
   1723 **
   1724 ** If the locking level of the file descriptor is already at or below
   1725 ** the requested locking level, this routine is a no-op.
   1726 */
   1727 static int unixUnlock(sqlite3_file *id, int eFileLock){
   1728   return posixUnlock(id, eFileLock, 0);
   1729 }
   1730 
   1731 /*
   1732 ** This function performs the parts of the "close file" operation
   1733 ** common to all locking schemes. It closes the directory and file
   1734 ** handles, if they are valid, and sets all fields of the unixFile
   1735 ** structure to 0.
   1736 **
   1737 ** It is *not* necessary to hold the mutex when this routine is called,
   1738 ** even on VxWorks.  A mutex will be acquired on VxWorks by the
   1739 ** vxworksReleaseFileId() routine.
   1740 */
   1741 static int closeUnixFile(sqlite3_file *id){
   1742   unixFile *pFile = (unixFile*)id;
   1743   if( pFile->h>=0 ){
   1744     robust_close(pFile, pFile->h, __LINE__);
   1745     pFile->h = -1;
   1746   }
   1747 #if OS_VXWORKS
   1748   if( pFile->pId ){
   1749     if( pFile->isDelete ){
   1750       osUnlink(pFile->pId->zCanonicalName);
   1751     }
   1752     vxworksReleaseFileId(pFile->pId);
   1753     pFile->pId = 0;
   1754   }
   1755 #endif
   1756   OSTRACE(("CLOSE   %-3d\n", pFile->h));
   1757   OpenCounter(-1);
   1758   sqlite3_free(pFile->pUnused);
   1759   memset(pFile, 0, sizeof(unixFile));
   1760   return SQLITE_OK;
   1761 }
   1762 
   1763 /*
   1764 ** Close a file.
   1765 */
   1766 static int unixClose(sqlite3_file *id){
   1767   int rc = SQLITE_OK;
   1768   unixFile *pFile = (unixFile *)id;
   1769   unixUnlock(id, NO_LOCK);
   1770   unixEnterMutex();
   1771 
   1772   /* unixFile.pInode is always valid here. Otherwise, a different close
   1773   ** routine (e.g. nolockClose()) would be called instead.
   1774   */
   1775   assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
   1776   if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
   1777     /* If there are outstanding locks, do not actually close the file just
   1778     ** yet because that would clear those locks.  Instead, add the file
   1779     ** descriptor to pInode->pUnused list.  It will be automatically closed
   1780     ** when the last lock is cleared.
   1781     */
   1782     setPendingFd(pFile);
   1783   }
   1784   releaseInodeInfo(pFile);
   1785   rc = closeUnixFile(id);
   1786   unixLeaveMutex();
   1787   return rc;
   1788 }
   1789 
   1790 /************** End of the posix advisory lock implementation *****************
   1791 ******************************************************************************/
   1792 
   1793 /******************************************************************************
   1794 ****************************** No-op Locking **********************************
   1795 **
   1796 ** Of the various locking implementations available, this is by far the
   1797 ** simplest:  locking is ignored.  No attempt is made to lock the database
   1798 ** file for reading or writing.
   1799 **
   1800 ** This locking mode is appropriate for use on read-only databases
   1801 ** (ex: databases that are burned into CD-ROM, for example.)  It can
   1802 ** also be used if the application employs some external mechanism to
   1803 ** prevent simultaneous access of the same database by two or more
   1804 ** database connections.  But there is a serious risk of database
   1805 ** corruption if this locking mode is used in situations where multiple
   1806 ** database connections are accessing the same database file at the same
   1807 ** time and one or more of those connections are writing.
   1808 */
   1809 
   1810 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
   1811   UNUSED_PARAMETER(NotUsed);
   1812   *pResOut = 0;
   1813   return SQLITE_OK;
   1814 }
   1815 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
   1816   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   1817   return SQLITE_OK;
   1818 }
   1819 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
   1820   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   1821   return SQLITE_OK;
   1822 }
   1823 
   1824 /*
   1825 ** Close the file.
   1826 */
   1827 static int nolockClose(sqlite3_file *id) {
   1828   return closeUnixFile(id);
   1829 }
   1830 
   1831 /******************* End of the no-op lock implementation *********************
   1832 ******************************************************************************/
   1833 
   1834 /******************************************************************************
   1835 ************************* Begin dot-file Locking ******************************
   1836 **
   1837 ** The dotfile locking implementation uses the existance of separate lock
   1838 ** files in order to control access to the database.  This works on just
   1839 ** about every filesystem imaginable.  But there are serious downsides:
   1840 **
   1841 **    (1)  There is zero concurrency.  A single reader blocks all other
   1842 **         connections from reading or writing the database.
   1843 **
   1844 **    (2)  An application crash or power loss can leave stale lock files
   1845 **         sitting around that need to be cleared manually.
   1846 **
   1847 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
   1848 ** other locking strategy is available.
   1849 **
   1850 ** Dotfile locking works by creating a file in the same directory as the
   1851 ** database and with the same name but with a ".lock" extension added.
   1852 ** The existance of a lock file implies an EXCLUSIVE lock.  All other lock
   1853 ** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
   1854 */
   1855 
   1856 /*
   1857 ** The file suffix added to the data base filename in order to create the
   1858 ** lock file.
   1859 */
   1860 #define DOTLOCK_SUFFIX ".lock"
   1861 
   1862 /*
   1863 ** This routine checks if there is a RESERVED lock held on the specified
   1864 ** file by this or any other process. If such a lock is held, set *pResOut
   1865 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   1866 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   1867 **
   1868 ** In dotfile locking, either a lock exists or it does not.  So in this
   1869 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
   1870 ** is held on the file and false if the file is unlocked.
   1871 */
   1872 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
   1873   int rc = SQLITE_OK;
   1874   int reserved = 0;
   1875   unixFile *pFile = (unixFile*)id;
   1876 
   1877   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   1878 
   1879   assert( pFile );
   1880 
   1881   /* Check if a thread in this process holds such a lock */
   1882   if( pFile->eFileLock>SHARED_LOCK ){
   1883     /* Either this connection or some other connection in the same process
   1884     ** holds a lock on the file.  No need to check further. */
   1885     reserved = 1;
   1886   }else{
   1887     /* The lock is held if and only if the lockfile exists */
   1888     const char *zLockFile = (const char*)pFile->lockingContext;
   1889     reserved = osAccess(zLockFile, 0)==0;
   1890   }
   1891   OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
   1892   *pResOut = reserved;
   1893   return rc;
   1894 }
   1895 
   1896 /*
   1897 ** Lock the file with the lock specified by parameter eFileLock - one
   1898 ** of the following:
   1899 **
   1900 **     (1) SHARED_LOCK
   1901 **     (2) RESERVED_LOCK
   1902 **     (3) PENDING_LOCK
   1903 **     (4) EXCLUSIVE_LOCK
   1904 **
   1905 ** Sometimes when requesting one lock state, additional lock states
   1906 ** are inserted in between.  The locking might fail on one of the later
   1907 ** transitions leaving the lock state different from what it started but
   1908 ** still short of its goal.  The following chart shows the allowed
   1909 ** transitions and the inserted intermediate states:
   1910 **
   1911 **    UNLOCKED -> SHARED
   1912 **    SHARED -> RESERVED
   1913 **    SHARED -> (PENDING) -> EXCLUSIVE
   1914 **    RESERVED -> (PENDING) -> EXCLUSIVE
   1915 **    PENDING -> EXCLUSIVE
   1916 **
   1917 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   1918 ** routine to lower a locking level.
   1919 **
   1920 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
   1921 ** But we track the other locking levels internally.
   1922 */
   1923 static int dotlockLock(sqlite3_file *id, int eFileLock) {
   1924   unixFile *pFile = (unixFile*)id;
   1925   int fd;
   1926   char *zLockFile = (char *)pFile->lockingContext;
   1927   int rc = SQLITE_OK;
   1928 
   1929 
   1930   /* If we have any lock, then the lock file already exists.  All we have
   1931   ** to do is adjust our internal record of the lock level.
   1932   */
   1933   if( pFile->eFileLock > NO_LOCK ){
   1934     pFile->eFileLock = eFileLock;
   1935 #if !OS_VXWORKS
   1936     /* Always update the timestamp on the old file */
   1937     utimes(zLockFile, NULL);
   1938 #endif
   1939     return SQLITE_OK;
   1940   }
   1941 
   1942   /* grab an exclusive lock */
   1943   fd = robust_open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
   1944   if( fd<0 ){
   1945     /* failed to open/create the file, someone else may have stolen the lock */
   1946     int tErrno = errno;
   1947     if( EEXIST == tErrno ){
   1948       rc = SQLITE_BUSY;
   1949     } else {
   1950       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   1951       if( IS_LOCK_ERROR(rc) ){
   1952         pFile->lastErrno = tErrno;
   1953       }
   1954     }
   1955     return rc;
   1956   }
   1957   robust_close(pFile, fd, __LINE__);
   1958 
   1959   /* got it, set the type and return ok */
   1960   pFile->eFileLock = eFileLock;
   1961   return rc;
   1962 }
   1963 
   1964 /*
   1965 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   1966 ** must be either NO_LOCK or SHARED_LOCK.
   1967 **
   1968 ** If the locking level of the file descriptor is already at or below
   1969 ** the requested locking level, this routine is a no-op.
   1970 **
   1971 ** When the locking level reaches NO_LOCK, delete the lock file.
   1972 */
   1973 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
   1974   unixFile *pFile = (unixFile*)id;
   1975   char *zLockFile = (char *)pFile->lockingContext;
   1976 
   1977   assert( pFile );
   1978   OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
   1979 	   pFile->eFileLock, getpid()));
   1980   assert( eFileLock<=SHARED_LOCK );
   1981 
   1982   /* no-op if possible */
   1983   if( pFile->eFileLock==eFileLock ){
   1984     return SQLITE_OK;
   1985   }
   1986 
   1987   /* To downgrade to shared, simply update our internal notion of the
   1988   ** lock state.  No need to mess with the file on disk.
   1989   */
   1990   if( eFileLock==SHARED_LOCK ){
   1991     pFile->eFileLock = SHARED_LOCK;
   1992     return SQLITE_OK;
   1993   }
   1994 
   1995   /* To fully unlock the database, delete the lock file */
   1996   assert( eFileLock==NO_LOCK );
   1997   if( osUnlink(zLockFile) ){
   1998     int rc = 0;
   1999     int tErrno = errno;
   2000     if( ENOENT != tErrno ){
   2001       rc = SQLITE_IOERR_UNLOCK;
   2002     }
   2003     if( IS_LOCK_ERROR(rc) ){
   2004       pFile->lastErrno = tErrno;
   2005     }
   2006     return rc;
   2007   }
   2008   pFile->eFileLock = NO_LOCK;
   2009   return SQLITE_OK;
   2010 }
   2011 
   2012 /*
   2013 ** Close a file.  Make sure the lock has been released before closing.
   2014 */
   2015 static int dotlockClose(sqlite3_file *id) {
   2016   int rc;
   2017   if( id ){
   2018     unixFile *pFile = (unixFile*)id;
   2019     dotlockUnlock(id, NO_LOCK);
   2020     sqlite3_free(pFile->lockingContext);
   2021   }
   2022   rc = closeUnixFile(id);
   2023   return rc;
   2024 }
   2025 /****************** End of the dot-file lock implementation *******************
   2026 ******************************************************************************/
   2027 
   2028 /******************************************************************************
   2029 ************************** Begin flock Locking ********************************
   2030 **
   2031 ** Use the flock() system call to do file locking.
   2032 **
   2033 ** flock() locking is like dot-file locking in that the various
   2034 ** fine-grain locking levels supported by SQLite are collapsed into
   2035 ** a single exclusive lock.  In other words, SHARED, RESERVED, and
   2036 ** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
   2037 ** still works when you do this, but concurrency is reduced since
   2038 ** only a single process can be reading the database at a time.
   2039 **
   2040 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
   2041 ** compiling for VXWORKS.
   2042 */
   2043 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
   2044 
   2045 /*
   2046 ** Retry flock() calls that fail with EINTR
   2047 */
   2048 #ifdef EINTR
   2049 static int robust_flock(int fd, int op){
   2050   int rc;
   2051   do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
   2052   return rc;
   2053 }
   2054 #else
   2055 # define robust_flock(a,b) flock(a,b)
   2056 #endif
   2057 
   2058 
   2059 /*
   2060 ** This routine checks if there is a RESERVED lock held on the specified
   2061 ** file by this or any other process. If such a lock is held, set *pResOut
   2062 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   2063 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   2064 */
   2065 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
   2066   int rc = SQLITE_OK;
   2067   int reserved = 0;
   2068   unixFile *pFile = (unixFile*)id;
   2069 
   2070   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   2071 
   2072   assert( pFile );
   2073 
   2074   /* Check if a thread in this process holds such a lock */
   2075   if( pFile->eFileLock>SHARED_LOCK ){
   2076     reserved = 1;
   2077   }
   2078 
   2079   /* Otherwise see if some other process holds it. */
   2080   if( !reserved ){
   2081     /* attempt to get the lock */
   2082     int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
   2083     if( !lrc ){
   2084       /* got the lock, unlock it */
   2085       lrc = robust_flock(pFile->h, LOCK_UN);
   2086       if ( lrc ) {
   2087         int tErrno = errno;
   2088         /* unlock failed with an error */
   2089         lrc = SQLITE_IOERR_UNLOCK;
   2090         if( IS_LOCK_ERROR(lrc) ){
   2091           pFile->lastErrno = tErrno;
   2092           rc = lrc;
   2093         }
   2094       }
   2095     } else {
   2096       int tErrno = errno;
   2097       reserved = 1;
   2098       /* someone else might have it reserved */
   2099       lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   2100       if( IS_LOCK_ERROR(lrc) ){
   2101         pFile->lastErrno = tErrno;
   2102         rc = lrc;
   2103       }
   2104     }
   2105   }
   2106   OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
   2107 
   2108 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
   2109   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
   2110     rc = SQLITE_OK;
   2111     reserved=1;
   2112   }
   2113 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
   2114   *pResOut = reserved;
   2115   return rc;
   2116 }
   2117 
   2118 /*
   2119 ** Lock the file with the lock specified by parameter eFileLock - one
   2120 ** of the following:
   2121 **
   2122 **     (1) SHARED_LOCK
   2123 **     (2) RESERVED_LOCK
   2124 **     (3) PENDING_LOCK
   2125 **     (4) EXCLUSIVE_LOCK
   2126 **
   2127 ** Sometimes when requesting one lock state, additional lock states
   2128 ** are inserted in between.  The locking might fail on one of the later
   2129 ** transitions leaving the lock state different from what it started but
   2130 ** still short of its goal.  The following chart shows the allowed
   2131 ** transitions and the inserted intermediate states:
   2132 **
   2133 **    UNLOCKED -> SHARED
   2134 **    SHARED -> RESERVED
   2135 **    SHARED -> (PENDING) -> EXCLUSIVE
   2136 **    RESERVED -> (PENDING) -> EXCLUSIVE
   2137 **    PENDING -> EXCLUSIVE
   2138 **
   2139 ** flock() only really support EXCLUSIVE locks.  We track intermediate
   2140 ** lock states in the sqlite3_file structure, but all locks SHARED or
   2141 ** above are really EXCLUSIVE locks and exclude all other processes from
   2142 ** access the file.
   2143 **
   2144 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   2145 ** routine to lower a locking level.
   2146 */
   2147 static int flockLock(sqlite3_file *id, int eFileLock) {
   2148   int rc = SQLITE_OK;
   2149   unixFile *pFile = (unixFile*)id;
   2150 
   2151   assert( pFile );
   2152 
   2153   /* if we already have a lock, it is exclusive.
   2154   ** Just adjust level and punt on outta here. */
   2155   if (pFile->eFileLock > NO_LOCK) {
   2156     pFile->eFileLock = eFileLock;
   2157     return SQLITE_OK;
   2158   }
   2159 
   2160   /* grab an exclusive lock */
   2161 
   2162   if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
   2163     int tErrno = errno;
   2164     /* didn't get, must be busy */
   2165     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   2166     if( IS_LOCK_ERROR(rc) ){
   2167       pFile->lastErrno = tErrno;
   2168     }
   2169   } else {
   2170     /* got it, set the type and return ok */
   2171     pFile->eFileLock = eFileLock;
   2172   }
   2173   OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
   2174            rc==SQLITE_OK ? "ok" : "failed"));
   2175 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
   2176   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
   2177     rc = SQLITE_BUSY;
   2178   }
   2179 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
   2180   return rc;
   2181 }
   2182 
   2183 
   2184 /*
   2185 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   2186 ** must be either NO_LOCK or SHARED_LOCK.
   2187 **
   2188 ** If the locking level of the file descriptor is already at or below
   2189 ** the requested locking level, this routine is a no-op.
   2190 */
   2191 static int flockUnlock(sqlite3_file *id, int eFileLock) {
   2192   unixFile *pFile = (unixFile*)id;
   2193 
   2194   assert( pFile );
   2195   OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
   2196            pFile->eFileLock, getpid()));
   2197   assert( eFileLock<=SHARED_LOCK );
   2198 
   2199   /* no-op if possible */
   2200   if( pFile->eFileLock==eFileLock ){
   2201     return SQLITE_OK;
   2202   }
   2203 
   2204   /* shared can just be set because we always have an exclusive */
   2205   if (eFileLock==SHARED_LOCK) {
   2206     pFile->eFileLock = eFileLock;
   2207     return SQLITE_OK;
   2208   }
   2209 
   2210   /* no, really, unlock. */
   2211   if( robust_flock(pFile->h, LOCK_UN) ){
   2212 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
   2213     return SQLITE_OK;
   2214 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
   2215     return SQLITE_IOERR_UNLOCK;
   2216   }else{
   2217     pFile->eFileLock = NO_LOCK;
   2218     return SQLITE_OK;
   2219   }
   2220 }
   2221 
   2222 /*
   2223 ** Close a file.
   2224 */
   2225 static int flockClose(sqlite3_file *id) {
   2226   if( id ){
   2227     flockUnlock(id, NO_LOCK);
   2228   }
   2229   return closeUnixFile(id);
   2230 }
   2231 
   2232 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
   2233 
   2234 /******************* End of the flock lock implementation *********************
   2235 ******************************************************************************/
   2236 
   2237 /******************************************************************************
   2238 ************************ Begin Named Semaphore Locking ************************
   2239 **
   2240 ** Named semaphore locking is only supported on VxWorks.
   2241 **
   2242 ** Semaphore locking is like dot-lock and flock in that it really only
   2243 ** supports EXCLUSIVE locking.  Only a single process can read or write
   2244 ** the database file at a time.  This reduces potential concurrency, but
   2245 ** makes the lock implementation much easier.
   2246 */
   2247 #if OS_VXWORKS
   2248 
   2249 /*
   2250 ** This routine checks if there is a RESERVED lock held on the specified
   2251 ** file by this or any other process. If such a lock is held, set *pResOut
   2252 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   2253 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   2254 */
   2255 static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
   2256   int rc = SQLITE_OK;
   2257   int reserved = 0;
   2258   unixFile *pFile = (unixFile*)id;
   2259 
   2260   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   2261 
   2262   assert( pFile );
   2263 
   2264   /* Check if a thread in this process holds such a lock */
   2265   if( pFile->eFileLock>SHARED_LOCK ){
   2266     reserved = 1;
   2267   }
   2268 
   2269   /* Otherwise see if some other process holds it. */
   2270   if( !reserved ){
   2271     sem_t *pSem = pFile->pInode->pSem;
   2272     struct stat statBuf;
   2273 
   2274     if( sem_trywait(pSem)==-1 ){
   2275       int tErrno = errno;
   2276       if( EAGAIN != tErrno ){
   2277         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
   2278         pFile->lastErrno = tErrno;
   2279       } else {
   2280         /* someone else has the lock when we are in NO_LOCK */
   2281         reserved = (pFile->eFileLock < SHARED_LOCK);
   2282       }
   2283     }else{
   2284       /* we could have it if we want it */
   2285       sem_post(pSem);
   2286     }
   2287   }
   2288   OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
   2289 
   2290   *pResOut = reserved;
   2291   return rc;
   2292 }
   2293 
   2294 /*
   2295 ** Lock the file with the lock specified by parameter eFileLock - one
   2296 ** of the following:
   2297 **
   2298 **     (1) SHARED_LOCK
   2299 **     (2) RESERVED_LOCK
   2300 **     (3) PENDING_LOCK
   2301 **     (4) EXCLUSIVE_LOCK
   2302 **
   2303 ** Sometimes when requesting one lock state, additional lock states
   2304 ** are inserted in between.  The locking might fail on one of the later
   2305 ** transitions leaving the lock state different from what it started but
   2306 ** still short of its goal.  The following chart shows the allowed
   2307 ** transitions and the inserted intermediate states:
   2308 **
   2309 **    UNLOCKED -> SHARED
   2310 **    SHARED -> RESERVED
   2311 **    SHARED -> (PENDING) -> EXCLUSIVE
   2312 **    RESERVED -> (PENDING) -> EXCLUSIVE
   2313 **    PENDING -> EXCLUSIVE
   2314 **
   2315 ** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
   2316 ** lock states in the sqlite3_file structure, but all locks SHARED or
   2317 ** above are really EXCLUSIVE locks and exclude all other processes from
   2318 ** access the file.
   2319 **
   2320 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   2321 ** routine to lower a locking level.
   2322 */
   2323 static int semLock(sqlite3_file *id, int eFileLock) {
   2324   unixFile *pFile = (unixFile*)id;
   2325   int fd;
   2326   sem_t *pSem = pFile->pInode->pSem;
   2327   int rc = SQLITE_OK;
   2328 
   2329   /* if we already have a lock, it is exclusive.
   2330   ** Just adjust level and punt on outta here. */
   2331   if (pFile->eFileLock > NO_LOCK) {
   2332     pFile->eFileLock = eFileLock;
   2333     rc = SQLITE_OK;
   2334     goto sem_end_lock;
   2335   }
   2336 
   2337   /* lock semaphore now but bail out when already locked. */
   2338   if( sem_trywait(pSem)==-1 ){
   2339     rc = SQLITE_BUSY;
   2340     goto sem_end_lock;
   2341   }
   2342 
   2343   /* got it, set the type and return ok */
   2344   pFile->eFileLock = eFileLock;
   2345 
   2346  sem_end_lock:
   2347   return rc;
   2348 }
   2349 
   2350 /*
   2351 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   2352 ** must be either NO_LOCK or SHARED_LOCK.
   2353 **
   2354 ** If the locking level of the file descriptor is already at or below
   2355 ** the requested locking level, this routine is a no-op.
   2356 */
   2357 static int semUnlock(sqlite3_file *id, int eFileLock) {
   2358   unixFile *pFile = (unixFile*)id;
   2359   sem_t *pSem = pFile->pInode->pSem;
   2360 
   2361   assert( pFile );
   2362   assert( pSem );
   2363   OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
   2364 	   pFile->eFileLock, getpid()));
   2365   assert( eFileLock<=SHARED_LOCK );
   2366 
   2367   /* no-op if possible */
   2368   if( pFile->eFileLock==eFileLock ){
   2369     return SQLITE_OK;
   2370   }
   2371 
   2372   /* shared can just be set because we always have an exclusive */
   2373   if (eFileLock==SHARED_LOCK) {
   2374     pFile->eFileLock = eFileLock;
   2375     return SQLITE_OK;
   2376   }
   2377 
   2378   /* no, really unlock. */
   2379   if ( sem_post(pSem)==-1 ) {
   2380     int rc, tErrno = errno;
   2381     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
   2382     if( IS_LOCK_ERROR(rc) ){
   2383       pFile->lastErrno = tErrno;
   2384     }
   2385     return rc;
   2386   }
   2387   pFile->eFileLock = NO_LOCK;
   2388   return SQLITE_OK;
   2389 }
   2390 
   2391 /*
   2392  ** Close a file.
   2393  */
   2394 static int semClose(sqlite3_file *id) {
   2395   if( id ){
   2396     unixFile *pFile = (unixFile*)id;
   2397     semUnlock(id, NO_LOCK);
   2398     assert( pFile );
   2399     unixEnterMutex();
   2400     releaseInodeInfo(pFile);
   2401     unixLeaveMutex();
   2402     closeUnixFile(id);
   2403   }
   2404   return SQLITE_OK;
   2405 }
   2406 
   2407 #endif /* OS_VXWORKS */
   2408 /*
   2409 ** Named semaphore locking is only available on VxWorks.
   2410 **
   2411 *************** End of the named semaphore lock implementation ****************
   2412 ******************************************************************************/
   2413 
   2414 
   2415 /******************************************************************************
   2416 *************************** Begin AFP Locking *********************************
   2417 **
   2418 ** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
   2419 ** on Apple Macintosh computers - both OS9 and OSX.
   2420 **
   2421 ** Third-party implementations of AFP are available.  But this code here
   2422 ** only works on OSX.
   2423 */
   2424 
   2425 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   2426 /*
   2427 ** The afpLockingContext structure contains all afp lock specific state
   2428 */
   2429 typedef struct afpLockingContext afpLockingContext;
   2430 struct afpLockingContext {
   2431   int reserved;
   2432   const char *dbPath;             /* Name of the open file */
   2433 };
   2434 
   2435 struct ByteRangeLockPB2
   2436 {
   2437   unsigned long long offset;        /* offset to first byte to lock */
   2438   unsigned long long length;        /* nbr of bytes to lock */
   2439   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
   2440   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
   2441   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
   2442   int fd;                           /* file desc to assoc this lock with */
   2443 };
   2444 
   2445 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
   2446 
   2447 /*
   2448 ** This is a utility for setting or clearing a bit-range lock on an
   2449 ** AFP filesystem.
   2450 **
   2451 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
   2452 */
   2453 static int afpSetLock(
   2454   const char *path,              /* Name of the file to be locked or unlocked */
   2455   unixFile *pFile,               /* Open file descriptor on path */
   2456   unsigned long long offset,     /* First byte to be locked */
   2457   unsigned long long length,     /* Number of bytes to lock */
   2458   int setLockFlag                /* True to set lock.  False to clear lock */
   2459 ){
   2460   struct ByteRangeLockPB2 pb;
   2461   int err;
   2462 
   2463   pb.unLockFlag = setLockFlag ? 0 : 1;
   2464   pb.startEndFlag = 0;
   2465   pb.offset = offset;
   2466   pb.length = length;
   2467   pb.fd = pFile->h;
   2468 
   2469   OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
   2470     (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
   2471     offset, length));
   2472   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
   2473   if ( err==-1 ) {
   2474     int rc;
   2475     int tErrno = errno;
   2476     OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
   2477              path, tErrno, strerror(tErrno)));
   2478 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
   2479     rc = SQLITE_BUSY;
   2480 #else
   2481     rc = sqliteErrorFromPosixError(tErrno,
   2482                     setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
   2483 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
   2484     if( IS_LOCK_ERROR(rc) ){
   2485       pFile->lastErrno = tErrno;
   2486     }
   2487     return rc;
   2488   } else {
   2489     return SQLITE_OK;
   2490   }
   2491 }
   2492 
   2493 /*
   2494 ** This routine checks if there is a RESERVED lock held on the specified
   2495 ** file by this or any other process. If such a lock is held, set *pResOut
   2496 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   2497 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   2498 */
   2499 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
   2500   int rc = SQLITE_OK;
   2501   int reserved = 0;
   2502   unixFile *pFile = (unixFile*)id;
   2503 
   2504   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   2505 
   2506   assert( pFile );
   2507   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
   2508   if( context->reserved ){
   2509     *pResOut = 1;
   2510     return SQLITE_OK;
   2511   }
   2512   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
   2513 
   2514   /* Check if a thread in this process holds such a lock */
   2515   if( pFile->pInode->eFileLock>SHARED_LOCK ){
   2516     reserved = 1;
   2517   }
   2518 
   2519   /* Otherwise see if some other process holds it.
   2520    */
   2521   if( !reserved ){
   2522     /* lock the RESERVED byte */
   2523     int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
   2524     if( SQLITE_OK==lrc ){
   2525       /* if we succeeded in taking the reserved lock, unlock it to restore
   2526       ** the original state */
   2527       lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
   2528     } else {
   2529       /* if we failed to get the lock then someone else must have it */
   2530       reserved = 1;
   2531     }
   2532     if( IS_LOCK_ERROR(lrc) ){
   2533       rc=lrc;
   2534     }
   2535   }
   2536 
   2537   unixLeaveMutex();
   2538   OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
   2539 
   2540   *pResOut = reserved;
   2541   return rc;
   2542 }
   2543 
   2544 /*
   2545 ** Lock the file with the lock specified by parameter eFileLock - one
   2546 ** of the following:
   2547 **
   2548 **     (1) SHARED_LOCK
   2549 **     (2) RESERVED_LOCK
   2550 **     (3) PENDING_LOCK
   2551 **     (4) EXCLUSIVE_LOCK
   2552 **
   2553 ** Sometimes when requesting one lock state, additional lock states
   2554 ** are inserted in between.  The locking might fail on one of the later
   2555 ** transitions leaving the lock state different from what it started but
   2556 ** still short of its goal.  The following chart shows the allowed
   2557 ** transitions and the inserted intermediate states:
   2558 **
   2559 **    UNLOCKED -> SHARED
   2560 **    SHARED -> RESERVED
   2561 **    SHARED -> (PENDING) -> EXCLUSIVE
   2562 **    RESERVED -> (PENDING) -> EXCLUSIVE
   2563 **    PENDING -> EXCLUSIVE
   2564 **
   2565 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   2566 ** routine to lower a locking level.
   2567 */
   2568 static int afpLock(sqlite3_file *id, int eFileLock){
   2569   int rc = SQLITE_OK;
   2570   unixFile *pFile = (unixFile*)id;
   2571   unixInodeInfo *pInode = pFile->pInode;
   2572   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
   2573 
   2574   assert( pFile );
   2575   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
   2576            azFileLock(eFileLock), azFileLock(pFile->eFileLock),
   2577            azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
   2578 
   2579   /* If there is already a lock of this type or more restrictive on the
   2580   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
   2581   ** unixEnterMutex() hasn't been called yet.
   2582   */
   2583   if( pFile->eFileLock>=eFileLock ){
   2584     OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
   2585            azFileLock(eFileLock)));
   2586     return SQLITE_OK;
   2587   }
   2588 
   2589   /* Make sure the locking sequence is correct
   2590   **  (1) We never move from unlocked to anything higher than shared lock.
   2591   **  (2) SQLite never explicitly requests a pendig lock.
   2592   **  (3) A shared lock is always held when a reserve lock is requested.
   2593   */
   2594   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
   2595   assert( eFileLock!=PENDING_LOCK );
   2596   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
   2597 
   2598   /* This mutex is needed because pFile->pInode is shared across threads
   2599   */
   2600   unixEnterMutex();
   2601   pInode = pFile->pInode;
   2602 
   2603   /* If some thread using this PID has a lock via a different unixFile*
   2604   ** handle that precludes the requested lock, return BUSY.
   2605   */
   2606   if( (pFile->eFileLock!=pInode->eFileLock &&
   2607        (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
   2608      ){
   2609     rc = SQLITE_BUSY;
   2610     goto afp_end_lock;
   2611   }
   2612 
   2613   /* If a SHARED lock is requested, and some thread using this PID already
   2614   ** has a SHARED or RESERVED lock, then increment reference counts and
   2615   ** return SQLITE_OK.
   2616   */
   2617   if( eFileLock==SHARED_LOCK &&
   2618      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
   2619     assert( eFileLock==SHARED_LOCK );
   2620     assert( pFile->eFileLock==0 );
   2621     assert( pInode->nShared>0 );
   2622     pFile->eFileLock = SHARED_LOCK;
   2623     pInode->nShared++;
   2624     pInode->nLock++;
   2625     goto afp_end_lock;
   2626   }
   2627 
   2628   /* A PENDING lock is needed before acquiring a SHARED lock and before
   2629   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
   2630   ** be released.
   2631   */
   2632   if( eFileLock==SHARED_LOCK
   2633       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
   2634   ){
   2635     int failed;
   2636     failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
   2637     if (failed) {
   2638       rc = failed;
   2639       goto afp_end_lock;
   2640     }
   2641   }
   2642 
   2643   /* If control gets to this point, then actually go ahead and make
   2644   ** operating system calls for the specified lock.
   2645   */
   2646   if( eFileLock==SHARED_LOCK ){
   2647     int lrc1, lrc2, lrc1Errno;
   2648     long lk, mask;
   2649 
   2650     assert( pInode->nShared==0 );
   2651     assert( pInode->eFileLock==0 );
   2652 
   2653     mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
   2654     /* Now get the read-lock SHARED_LOCK */
   2655     /* note that the quality of the randomness doesn't matter that much */
   2656     lk = random();
   2657     pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
   2658     lrc1 = afpSetLock(context->dbPath, pFile,
   2659           SHARED_FIRST+pInode->sharedByte, 1, 1);
   2660     if( IS_LOCK_ERROR(lrc1) ){
   2661       lrc1Errno = pFile->lastErrno;
   2662     }
   2663     /* Drop the temporary PENDING lock */
   2664     lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
   2665 
   2666     if( IS_LOCK_ERROR(lrc1) ) {
   2667       pFile->lastErrno = lrc1Errno;
   2668       rc = lrc1;
   2669       goto afp_end_lock;
   2670     } else if( IS_LOCK_ERROR(lrc2) ){
   2671       rc = lrc2;
   2672       goto afp_end_lock;
   2673     } else if( lrc1 != SQLITE_OK ) {
   2674       rc = lrc1;
   2675     } else {
   2676       pFile->eFileLock = SHARED_LOCK;
   2677       pInode->nLock++;
   2678       pInode->nShared = 1;
   2679     }
   2680   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
   2681     /* We are trying for an exclusive lock but another thread in this
   2682      ** same process is still holding a shared lock. */
   2683     rc = SQLITE_BUSY;
   2684   }else{
   2685     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
   2686     ** assumed that there is a SHARED or greater lock on the file
   2687     ** already.
   2688     */
   2689     int failed = 0;
   2690     assert( 0!=pFile->eFileLock );
   2691     if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
   2692         /* Acquire a RESERVED lock */
   2693         failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
   2694       if( !failed ){
   2695         context->reserved = 1;
   2696       }
   2697     }
   2698     if (!failed && eFileLock == EXCLUSIVE_LOCK) {
   2699       /* Acquire an EXCLUSIVE lock */
   2700 
   2701       /* Remove the shared lock before trying the range.  we'll need to
   2702       ** reestablish the shared lock if we can't get the  afpUnlock
   2703       */
   2704       if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
   2705                          pInode->sharedByte, 1, 0)) ){
   2706         int failed2 = SQLITE_OK;
   2707         /* now attemmpt to get the exclusive lock range */
   2708         failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
   2709                                SHARED_SIZE, 1);
   2710         if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
   2711                        SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
   2712           /* Can't reestablish the shared lock.  Sqlite can't deal, this is
   2713           ** a critical I/O error
   2714           */
   2715           rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
   2716                SQLITE_IOERR_LOCK;
   2717           goto afp_end_lock;
   2718         }
   2719       }else{
   2720         rc = failed;
   2721       }
   2722     }
   2723     if( failed ){
   2724       rc = failed;
   2725     }
   2726   }
   2727 
   2728   if( rc==SQLITE_OK ){
   2729     pFile->eFileLock = eFileLock;
   2730     pInode->eFileLock = eFileLock;
   2731   }else if( eFileLock==EXCLUSIVE_LOCK ){
   2732     pFile->eFileLock = PENDING_LOCK;
   2733     pInode->eFileLock = PENDING_LOCK;
   2734   }
   2735 
   2736 afp_end_lock:
   2737   unixLeaveMutex();
   2738   OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
   2739          rc==SQLITE_OK ? "ok" : "failed"));
   2740   return rc;
   2741 }
   2742 
   2743 /*
   2744 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   2745 ** must be either NO_LOCK or SHARED_LOCK.
   2746 **
   2747 ** If the locking level of the file descriptor is already at or below
   2748 ** the requested locking level, this routine is a no-op.
   2749 */
   2750 static int afpUnlock(sqlite3_file *id, int eFileLock) {
   2751   int rc = SQLITE_OK;
   2752   unixFile *pFile = (unixFile*)id;
   2753   unixInodeInfo *pInode;
   2754   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
   2755   int skipShared = 0;
   2756 #ifdef SQLITE_TEST
   2757   int h = pFile->h;
   2758 #endif
   2759 
   2760   assert( pFile );
   2761   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
   2762            pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
   2763            getpid()));
   2764 
   2765   assert( eFileLock<=SHARED_LOCK );
   2766   if( pFile->eFileLock<=eFileLock ){
   2767     return SQLITE_OK;
   2768   }
   2769   unixEnterMutex();
   2770   pInode = pFile->pInode;
   2771   assert( pInode->nShared!=0 );
   2772   if( pFile->eFileLock>SHARED_LOCK ){
   2773     assert( pInode->eFileLock==pFile->eFileLock );
   2774     SimulateIOErrorBenign(1);
   2775     SimulateIOError( h=(-1) )
   2776     SimulateIOErrorBenign(0);
   2777 
   2778 #ifndef NDEBUG
   2779     /* When reducing a lock such that other processes can start
   2780     ** reading the database file again, make sure that the
   2781     ** transaction counter was updated if any part of the database
   2782     ** file changed.  If the transaction counter is not updated,
   2783     ** other connections to the same file might not realize that
   2784     ** the file has changed and hence might not know to flush their
   2785     ** cache.  The use of a stale cache can lead to database corruption.
   2786     */
   2787     assert( pFile->inNormalWrite==0
   2788            || pFile->dbUpdate==0
   2789            || pFile->transCntrChng==1 );
   2790     pFile->inNormalWrite = 0;
   2791 #endif
   2792 
   2793     if( pFile->eFileLock==EXCLUSIVE_LOCK ){
   2794       rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
   2795       if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
   2796         /* only re-establish the shared lock if necessary */
   2797         int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
   2798         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
   2799       } else {
   2800         skipShared = 1;
   2801       }
   2802     }
   2803     if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
   2804       rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
   2805     }
   2806     if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
   2807       rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
   2808       if( !rc ){
   2809         context->reserved = 0;
   2810       }
   2811     }
   2812     if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
   2813       pInode->eFileLock = SHARED_LOCK;
   2814     }
   2815   }
   2816   if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
   2817 
   2818     /* Decrement the shared lock counter.  Release the lock using an
   2819     ** OS call only when all threads in this same process have released
   2820     ** the lock.
   2821     */
   2822     unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
   2823     pInode->nShared--;
   2824     if( pInode->nShared==0 ){
   2825       SimulateIOErrorBenign(1);
   2826       SimulateIOError( h=(-1) )
   2827       SimulateIOErrorBenign(0);
   2828       if( !skipShared ){
   2829         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
   2830       }
   2831       if( !rc ){
   2832         pInode->eFileLock = NO_LOCK;
   2833         pFile->eFileLock = NO_LOCK;
   2834       }
   2835     }
   2836     if( rc==SQLITE_OK ){
   2837       pInode->nLock--;
   2838       assert( pInode->nLock>=0 );
   2839       if( pInode->nLock==0 ){
   2840         closePendingFds(pFile);
   2841       }
   2842     }
   2843   }
   2844 
   2845   unixLeaveMutex();
   2846   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
   2847   return rc;
   2848 }
   2849 
   2850 /*
   2851 ** Close a file & cleanup AFP specific locking context
   2852 */
   2853 static int afpClose(sqlite3_file *id) {
   2854   int rc = SQLITE_OK;
   2855   if( id ){
   2856     unixFile *pFile = (unixFile*)id;
   2857     afpUnlock(id, NO_LOCK);
   2858     unixEnterMutex();
   2859     if( pFile->pInode && pFile->pInode->nLock ){
   2860       /* If there are outstanding locks, do not actually close the file just
   2861       ** yet because that would clear those locks.  Instead, add the file
   2862       ** descriptor to pInode->aPending.  It will be automatically closed when
   2863       ** the last lock is cleared.
   2864       */
   2865       setPendingFd(pFile);
   2866     }
   2867     releaseInodeInfo(pFile);
   2868     sqlite3_free(pFile->lockingContext);
   2869     rc = closeUnixFile(id);
   2870     unixLeaveMutex();
   2871   }
   2872   return rc;
   2873 }
   2874 
   2875 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
   2876 /*
   2877 ** The code above is the AFP lock implementation.  The code is specific
   2878 ** to MacOSX and does not work on other unix platforms.  No alternative
   2879 ** is available.  If you don't compile for a mac, then the "unix-afp"
   2880 ** VFS is not available.
   2881 **
   2882 ********************* End of the AFP lock implementation **********************
   2883 ******************************************************************************/
   2884 
   2885 /******************************************************************************
   2886 *************************** Begin NFS Locking ********************************/
   2887 
   2888 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   2889 /*
   2890  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   2891  ** must be either NO_LOCK or SHARED_LOCK.
   2892  **
   2893  ** If the locking level of the file descriptor is already at or below
   2894  ** the requested locking level, this routine is a no-op.
   2895  */
   2896 static int nfsUnlock(sqlite3_file *id, int eFileLock){
   2897   return posixUnlock(id, eFileLock, 1);
   2898 }
   2899 
   2900 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
   2901 /*
   2902 ** The code above is the NFS lock implementation.  The code is specific
   2903 ** to MacOSX and does not work on other unix platforms.  No alternative
   2904 ** is available.
   2905 **
   2906 ********************* End of the NFS lock implementation **********************
   2907 ******************************************************************************/
   2908 
   2909 /******************************************************************************
   2910 **************** Non-locking sqlite3_file methods *****************************
   2911 **
   2912 ** The next division contains implementations for all methods of the
   2913 ** sqlite3_file object other than the locking methods.  The locking
   2914 ** methods were defined in divisions above (one locking method per
   2915 ** division).  Those methods that are common to all locking modes
   2916 ** are gather together into this division.
   2917 */
   2918 
   2919 /*
   2920 ** Seek to the offset passed as the second argument, then read cnt
   2921 ** bytes into pBuf. Return the number of bytes actually read.
   2922 **
   2923 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
   2924 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
   2925 ** one system to another.  Since SQLite does not define USE_PREAD
   2926 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
   2927 ** See tickets #2741 and #2681.
   2928 **
   2929 ** To avoid stomping the errno value on a failed read the lastErrno value
   2930 ** is set before returning.
   2931 */
   2932 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
   2933   int got;
   2934 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
   2935   i64 newOffset;
   2936 #endif
   2937   TIMER_START;
   2938 #if defined(USE_PREAD)
   2939   do{ got = osPread(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
   2940   SimulateIOError( got = -1 );
   2941 #elif defined(USE_PREAD64)
   2942   do{ got = osPread64(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR);
   2943   SimulateIOError( got = -1 );
   2944 #else
   2945   newOffset = lseek(id->h, offset, SEEK_SET);
   2946   SimulateIOError( newOffset-- );
   2947   if( newOffset!=offset ){
   2948     if( newOffset == -1 ){
   2949       ((unixFile*)id)->lastErrno = errno;
   2950     }else{
   2951       ((unixFile*)id)->lastErrno = 0;
   2952     }
   2953     return -1;
   2954   }
   2955   do{ got = osRead(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
   2956 #endif
   2957   TIMER_END;
   2958   if( got<0 ){
   2959     ((unixFile*)id)->lastErrno = errno;
   2960   }
   2961   OSTRACE(("READ    %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
   2962   return got;
   2963 }
   2964 
   2965 /*
   2966 ** Read data from a file into a buffer.  Return SQLITE_OK if all
   2967 ** bytes were read successfully and SQLITE_IOERR if anything goes
   2968 ** wrong.
   2969 */
   2970 static int unixRead(
   2971   sqlite3_file *id,
   2972   void *pBuf,
   2973   int amt,
   2974   sqlite3_int64 offset
   2975 ){
   2976   unixFile *pFile = (unixFile *)id;
   2977   int got;
   2978   assert( id );
   2979 
   2980   /* If this is a database file (not a journal, master-journal or temp
   2981   ** file), the bytes in the locking range should never be read or written. */
   2982 #if 0
   2983   assert( pFile->pUnused==0
   2984        || offset>=PENDING_BYTE+512
   2985        || offset+amt<=PENDING_BYTE
   2986   );
   2987 #endif
   2988 
   2989   got = seekAndRead(pFile, offset, pBuf, amt);
   2990   if( got==amt ){
   2991     return SQLITE_OK;
   2992   }else if( got<0 ){
   2993     /* lastErrno set by seekAndRead */
   2994     return SQLITE_IOERR_READ;
   2995   }else{
   2996     pFile->lastErrno = 0; /* not a system error */
   2997     /* Unread parts of the buffer must be zero-filled */
   2998     memset(&((char*)pBuf)[got], 0, amt-got);
   2999     return SQLITE_IOERR_SHORT_READ;
   3000   }
   3001 }
   3002 
   3003 /*
   3004 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
   3005 ** Return the number of bytes actually read.  Update the offset.
   3006 **
   3007 ** To avoid stomping the errno value on a failed write the lastErrno value
   3008 ** is set before returning.
   3009 */
   3010 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
   3011   int got;
   3012 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
   3013   i64 newOffset;
   3014 #endif
   3015   TIMER_START;
   3016 #if defined(USE_PREAD)
   3017   do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
   3018 #elif defined(USE_PREAD64)
   3019   do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
   3020 #else
   3021   newOffset = lseek(id->h, offset, SEEK_SET);
   3022   SimulateIOError( newOffset-- );
   3023   if( newOffset!=offset ){
   3024     if( newOffset == -1 ){
   3025       ((unixFile*)id)->lastErrno = errno;
   3026     }else{
   3027       ((unixFile*)id)->lastErrno = 0;
   3028     }
   3029     return -1;
   3030   }
   3031   do{ got = osWrite(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
   3032 #endif
   3033   TIMER_END;
   3034   if( got<0 ){
   3035     ((unixFile*)id)->lastErrno = errno;
   3036   }
   3037 
   3038   OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
   3039   return got;
   3040 }
   3041 
   3042 
   3043 /*
   3044 ** Write data from a buffer into a file.  Return SQLITE_OK on success
   3045 ** or some other error code on failure.
   3046 */
   3047 static int unixWrite(
   3048   sqlite3_file *id,
   3049   const void *pBuf,
   3050   int amt,
   3051   sqlite3_int64 offset
   3052 ){
   3053   unixFile *pFile = (unixFile*)id;
   3054   int wrote = 0;
   3055   assert( id );
   3056   assert( amt>0 );
   3057 
   3058   /* If this is a database file (not a journal, master-journal or temp
   3059   ** file), the bytes in the locking range should never be read or written. */
   3060 #if 0
   3061   assert( pFile->pUnused==0
   3062        || offset>=PENDING_BYTE+512
   3063        || offset+amt<=PENDING_BYTE
   3064   );
   3065 #endif
   3066 
   3067 #ifndef NDEBUG
   3068   /* If we are doing a normal write to a database file (as opposed to
   3069   ** doing a hot-journal rollback or a write to some file other than a
   3070   ** normal database file) then record the fact that the database
   3071   ** has changed.  If the transaction counter is modified, record that
   3072   ** fact too.
   3073   */
   3074   if( pFile->inNormalWrite ){
   3075     pFile->dbUpdate = 1;  /* The database has been modified */
   3076     if( offset<=24 && offset+amt>=27 ){
   3077       int rc;
   3078       char oldCntr[4];
   3079       SimulateIOErrorBenign(1);
   3080       rc = seekAndRead(pFile, 24, oldCntr, 4);
   3081       SimulateIOErrorBenign(0);
   3082       if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
   3083         pFile->transCntrChng = 1;  /* The transaction counter has changed */
   3084       }
   3085     }
   3086   }
   3087 #endif
   3088 
   3089   while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
   3090     amt -= wrote;
   3091     offset += wrote;
   3092     pBuf = &((char*)pBuf)[wrote];
   3093   }
   3094   SimulateIOError(( wrote=(-1), amt=1 ));
   3095   SimulateDiskfullError(( wrote=0, amt=1 ));
   3096 
   3097   if( amt>0 ){
   3098     if( wrote<0 ){
   3099       /* lastErrno set by seekAndWrite */
   3100       return SQLITE_IOERR_WRITE;
   3101     }else{
   3102       pFile->lastErrno = 0; /* not a system error */
   3103       return SQLITE_FULL;
   3104     }
   3105   }
   3106 
   3107   return SQLITE_OK;
   3108 }
   3109 
   3110 #ifdef SQLITE_TEST
   3111 /*
   3112 ** Count the number of fullsyncs and normal syncs.  This is used to test
   3113 ** that syncs and fullsyncs are occurring at the right times.
   3114 */
   3115 int sqlite3_sync_count = 0;
   3116 int sqlite3_fullsync_count = 0;
   3117 #endif
   3118 
   3119 /*
   3120 ** We do not trust systems to provide a working fdatasync().  Some do.
   3121 ** Others do no.  To be safe, we will stick with the (slower) fsync().
   3122 ** If you know that your system does support fdatasync() correctly,
   3123 ** then simply compile with -Dfdatasync=fdatasync
   3124 */
   3125 #if !defined(fdatasync) && !defined(__linux__)
   3126 # define fdatasync fsync
   3127 #endif
   3128 
   3129 /*
   3130 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
   3131 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
   3132 ** only available on Mac OS X.  But that could change.
   3133 */
   3134 #ifdef F_FULLFSYNC
   3135 # define HAVE_FULLFSYNC 1
   3136 #else
   3137 # define HAVE_FULLFSYNC 0
   3138 #endif
   3139 
   3140 
   3141 /*
   3142 ** The fsync() system call does not work as advertised on many
   3143 ** unix systems.  The following procedure is an attempt to make
   3144 ** it work better.
   3145 **
   3146 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
   3147 ** for testing when we want to run through the test suite quickly.
   3148 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
   3149 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
   3150 ** or power failure will likely corrupt the database file.
   3151 **
   3152 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
   3153 ** The idea behind dataOnly is that it should only write the file content
   3154 ** to disk, not the inode.  We only set dataOnly if the file size is
   3155 ** unchanged since the file size is part of the inode.  However,
   3156 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
   3157 ** file size has changed.  The only real difference between fdatasync()
   3158 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
   3159 ** inode if the mtime or owner or other inode attributes have changed.
   3160 ** We only care about the file size, not the other file attributes, so
   3161 ** as far as SQLite is concerned, an fdatasync() is always adequate.
   3162 ** So, we always use fdatasync() if it is available, regardless of
   3163 ** the value of the dataOnly flag.
   3164 */
   3165 static int full_fsync(int fd, int fullSync, int dataOnly){
   3166   int rc;
   3167 
   3168   /* The following "ifdef/elif/else/" block has the same structure as
   3169   ** the one below. It is replicated here solely to avoid cluttering
   3170   ** up the real code with the UNUSED_PARAMETER() macros.
   3171   */
   3172 #ifdef SQLITE_NO_SYNC
   3173   UNUSED_PARAMETER(fd);
   3174   UNUSED_PARAMETER(fullSync);
   3175   UNUSED_PARAMETER(dataOnly);
   3176 #elif HAVE_FULLFSYNC
   3177   UNUSED_PARAMETER(dataOnly);
   3178 #else
   3179   UNUSED_PARAMETER(fullSync);
   3180   UNUSED_PARAMETER(dataOnly);
   3181 #endif
   3182 
   3183   /* Record the number of times that we do a normal fsync() and
   3184   ** FULLSYNC.  This is used during testing to verify that this procedure
   3185   ** gets called with the correct arguments.
   3186   */
   3187 #ifdef SQLITE_TEST
   3188   if( fullSync ) sqlite3_fullsync_count++;
   3189   sqlite3_sync_count++;
   3190 #endif
   3191 
   3192   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
   3193   ** no-op
   3194   */
   3195 #ifdef SQLITE_NO_SYNC
   3196   rc = SQLITE_OK;
   3197 #elif HAVE_FULLFSYNC
   3198   if( fullSync ){
   3199     rc = osFcntl(fd, F_FULLFSYNC, 0);
   3200   }else{
   3201     rc = 1;
   3202   }
   3203   /* If the FULLFSYNC failed, fall back to attempting an fsync().
   3204   ** It shouldn't be possible for fullfsync to fail on the local
   3205   ** file system (on OSX), so failure indicates that FULLFSYNC
   3206   ** isn't supported for this file system. So, attempt an fsync
   3207   ** and (for now) ignore the overhead of a superfluous fcntl call.
   3208   ** It'd be better to detect fullfsync support once and avoid
   3209   ** the fcntl call every time sync is called.
   3210   */
   3211   if( rc ) rc = fsync(fd);
   3212 
   3213 #elif defined(__APPLE__)
   3214   /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
   3215   ** so currently we default to the macro that redefines fdatasync to fsync
   3216   */
   3217   rc = fsync(fd);
   3218 #else
   3219   rc = fdatasync(fd);
   3220 #if OS_VXWORKS
   3221   if( rc==-1 && errno==ENOTSUP ){
   3222     rc = fsync(fd);
   3223   }
   3224 #endif /* OS_VXWORKS */
   3225 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
   3226 
   3227   if( OS_VXWORKS && rc!= -1 ){
   3228     rc = 0;
   3229   }
   3230   return rc;
   3231 }
   3232 
   3233 /*
   3234 ** Open a file descriptor to the directory containing file zFilename.
   3235 ** If successful, *pFd is set to the opened file descriptor and
   3236 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
   3237 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
   3238 ** value.
   3239 **
   3240 ** The directory file descriptor is used for only one thing - to
   3241 ** fsync() a directory to make sure file creation and deletion events
   3242 ** are flushed to disk.  Such fsyncs are not needed on newer
   3243 ** journaling filesystems, but are required on older filesystems.
   3244 **
   3245 ** This routine can be overridden using the xSetSysCall interface.
   3246 ** The ability to override this routine was added in support of the
   3247 ** chromium sandbox.  Opening a directory is a security risk (we are
   3248 ** told) so making it overrideable allows the chromium sandbox to
   3249 ** replace this routine with a harmless no-op.  To make this routine
   3250 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
   3251 ** *pFd set to a negative number.
   3252 **
   3253 ** If SQLITE_OK is returned, the caller is responsible for closing
   3254 ** the file descriptor *pFd using close().
   3255 */
   3256 static int openDirectory(const char *zFilename, int *pFd){
   3257   int ii;
   3258   int fd = -1;
   3259   char zDirname[MAX_PATHNAME+1];
   3260 
   3261   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
   3262   for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
   3263   if( ii>0 ){
   3264     zDirname[ii] = '\0';
   3265     fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
   3266     if( fd>=0 ){
   3267 #ifdef FD_CLOEXEC
   3268       osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
   3269 #endif
   3270       OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
   3271     }
   3272   }
   3273   *pFd = fd;
   3274   return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
   3275 }
   3276 
   3277 /*
   3278 ** Make sure all writes to a particular file are committed to disk.
   3279 **
   3280 ** If dataOnly==0 then both the file itself and its metadata (file
   3281 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
   3282 ** file data is synced.
   3283 **
   3284 ** Under Unix, also make sure that the directory entry for the file
   3285 ** has been created by fsync-ing the directory that contains the file.
   3286 ** If we do not do this and we encounter a power failure, the directory
   3287 ** entry for the journal might not exist after we reboot.  The next
   3288 ** SQLite to access the file will not know that the journal exists (because
   3289 ** the directory entry for the journal was never created) and the transaction
   3290 ** will not roll back - possibly leading to database corruption.
   3291 */
   3292 static int unixSync(sqlite3_file *id, int flags){
   3293   int rc;
   3294   unixFile *pFile = (unixFile*)id;
   3295 
   3296   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
   3297   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
   3298 
   3299   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
   3300   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
   3301       || (flags&0x0F)==SQLITE_SYNC_FULL
   3302   );
   3303 
   3304   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
   3305   ** line is to test that doing so does not cause any problems.
   3306   */
   3307   SimulateDiskfullError( return SQLITE_FULL );
   3308 
   3309   assert( pFile );
   3310   OSTRACE(("SYNC    %-3d\n", pFile->h));
   3311   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
   3312   SimulateIOError( rc=1 );
   3313   if( rc ){
   3314     pFile->lastErrno = errno;
   3315     return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
   3316   }
   3317 
   3318   /* Also fsync the directory containing the file if the DIRSYNC flag
   3319   ** is set.  This is a one-time occurrance.  Many systems (examples: AIX)
   3320   ** are unable to fsync a directory, so ignore errors on the fsync.
   3321   */
   3322   if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
   3323     int dirfd;
   3324     OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
   3325             HAVE_FULLFSYNC, isFullsync));
   3326     rc = osOpenDirectory(pFile->zPath, &dirfd);
   3327     if( rc==SQLITE_OK && dirfd>=0 ){
   3328       full_fsync(dirfd, 0, 0);
   3329       robust_close(pFile, dirfd, __LINE__);
   3330     }else if( rc==SQLITE_CANTOPEN ){
   3331       rc = SQLITE_OK;
   3332     }
   3333     pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
   3334   }
   3335   return rc;
   3336 }
   3337 
   3338 /*
   3339 ** Truncate an open file to a specified size
   3340 */
   3341 static int unixTruncate(sqlite3_file *id, i64 nByte){
   3342   unixFile *pFile = (unixFile *)id;
   3343   int rc;
   3344   assert( pFile );
   3345   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
   3346 
   3347   /* If the user has configured a chunk-size for this file, truncate the
   3348   ** file so that it consists of an integer number of chunks (i.e. the
   3349   ** actual file size after the operation may be larger than the requested
   3350   ** size).
   3351   */
   3352   if( pFile->szChunk ){
   3353     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
   3354   }
   3355 
   3356   rc = robust_ftruncate(pFile->h, (off_t)nByte);
   3357   if( rc ){
   3358     pFile->lastErrno = errno;
   3359     return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
   3360   }else{
   3361 #ifndef NDEBUG
   3362     /* If we are doing a normal write to a database file (as opposed to
   3363     ** doing a hot-journal rollback or a write to some file other than a
   3364     ** normal database file) and we truncate the file to zero length,
   3365     ** that effectively updates the change counter.  This might happen
   3366     ** when restoring a database using the backup API from a zero-length
   3367     ** source.
   3368     */
   3369     if( pFile->inNormalWrite && nByte==0 ){
   3370       pFile->transCntrChng = 1;
   3371     }
   3372 #endif
   3373 
   3374     return SQLITE_OK;
   3375   }
   3376 }
   3377 
   3378 /*
   3379 ** Determine the current size of a file in bytes
   3380 */
   3381 static int unixFileSize(sqlite3_file *id, i64 *pSize){
   3382   int rc;
   3383   struct stat buf;
   3384   assert( id );
   3385   rc = osFstat(((unixFile*)id)->h, &buf);
   3386   SimulateIOError( rc=1 );
   3387   if( rc!=0 ){
   3388     ((unixFile*)id)->lastErrno = errno;
   3389     return SQLITE_IOERR_FSTAT;
   3390   }
   3391   *pSize = buf.st_size;
   3392 
   3393   /* When opening a zero-size database, the findInodeInfo() procedure
   3394   ** writes a single byte into that file in order to work around a bug
   3395   ** in the OS-X msdos filesystem.  In order to avoid problems with upper
   3396   ** layers, we need to report this file size as zero even though it is
   3397   ** really 1.   Ticket #3260.
   3398   */
   3399   if( *pSize==1 ) *pSize = 0;
   3400 
   3401 
   3402   return SQLITE_OK;
   3403 }
   3404 
   3405 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   3406 /*
   3407 ** Handler for proxy-locking file-control verbs.  Defined below in the
   3408 ** proxying locking division.
   3409 */
   3410 static int proxyFileControl(sqlite3_file*,int,void*);
   3411 #endif
   3412 
   3413 /*
   3414 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
   3415 ** file-control operation.
   3416 **
   3417 ** If the user has configured a chunk-size for this file, it could be
   3418 ** that the file needs to be extended at this point. Otherwise, the
   3419 ** SQLITE_FCNTL_SIZE_HINT operation is a no-op for Unix.
   3420 */
   3421 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
   3422   if( pFile->szChunk ){
   3423     i64 nSize;                    /* Required file size */
   3424     struct stat buf;              /* Used to hold return values of fstat() */
   3425 
   3426     if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
   3427 
   3428     nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
   3429     if( nSize>(i64)buf.st_size ){
   3430 
   3431 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
   3432       /* The code below is handling the return value of osFallocate()
   3433       ** correctly. posix_fallocate() is defined to "returns zero on success,
   3434       ** or an error number on  failure". See the manpage for details. */
   3435       int err;
   3436       do{
   3437         err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
   3438       }while( err==EINTR );
   3439       if( err ) return SQLITE_IOERR_WRITE;
   3440 #else
   3441       /* If the OS does not have posix_fallocate(), fake it. First use
   3442       ** ftruncate() to set the file size, then write a single byte to
   3443       ** the last byte in each block within the extended region. This
   3444       ** is the same technique used by glibc to implement posix_fallocate()
   3445       ** on systems that do not have a real fallocate() system call.
   3446       */
   3447       int nBlk = buf.st_blksize;  /* File-system block size */
   3448       i64 iWrite;                 /* Next offset to write to */
   3449 
   3450       if( robust_ftruncate(pFile->h, nSize) ){
   3451         pFile->lastErrno = errno;
   3452         return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
   3453       }
   3454       iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
   3455       while( iWrite<nSize ){
   3456         int nWrite = seekAndWrite(pFile, iWrite, "", 1);
   3457         if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
   3458         iWrite += nBlk;
   3459       }
   3460 #endif
   3461     }
   3462   }
   3463 
   3464   return SQLITE_OK;
   3465 }
   3466 
   3467 /*
   3468 ** Information and control of an open file handle.
   3469 */
   3470 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
   3471   switch( op ){
   3472     case SQLITE_FCNTL_LOCKSTATE: {
   3473       *(int*)pArg = ((unixFile*)id)->eFileLock;
   3474       return SQLITE_OK;
   3475     }
   3476     case SQLITE_LAST_ERRNO: {
   3477       *(int*)pArg = ((unixFile*)id)->lastErrno;
   3478       return SQLITE_OK;
   3479     }
   3480     case SQLITE_FCNTL_CHUNK_SIZE: {
   3481       ((unixFile*)id)->szChunk = *(int *)pArg;
   3482       return SQLITE_OK;
   3483     }
   3484     case SQLITE_FCNTL_SIZE_HINT: {
   3485       return fcntlSizeHint((unixFile *)id, *(i64 *)pArg);
   3486     }
   3487 #ifndef NDEBUG
   3488     /* The pager calls this method to signal that it has done
   3489     ** a rollback and that the database is therefore unchanged and
   3490     ** it hence it is OK for the transaction change counter to be
   3491     ** unchanged.
   3492     */
   3493     case SQLITE_FCNTL_DB_UNCHANGED: {
   3494       ((unixFile*)id)->dbUpdate = 0;
   3495       return SQLITE_OK;
   3496     }
   3497 #endif
   3498 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   3499     case SQLITE_SET_LOCKPROXYFILE:
   3500     case SQLITE_GET_LOCKPROXYFILE: {
   3501       return proxyFileControl(id,op,pArg);
   3502     }
   3503 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
   3504     case SQLITE_FCNTL_SYNC_OMITTED: {
   3505       return SQLITE_OK;  /* A no-op */
   3506     }
   3507   }
   3508   return SQLITE_NOTFOUND;
   3509 }
   3510 
   3511 /*
   3512 ** Return the sector size in bytes of the underlying block device for
   3513 ** the specified file. This is almost always 512 bytes, but may be
   3514 ** larger for some devices.
   3515 **
   3516 ** SQLite code assumes this function cannot fail. It also assumes that
   3517 ** if two files are created in the same file-system directory (i.e.
   3518 ** a database and its journal file) that the sector size will be the
   3519 ** same for both.
   3520 */
   3521 static int unixSectorSize(sqlite3_file *NotUsed){
   3522   UNUSED_PARAMETER(NotUsed);
   3523   return SQLITE_DEFAULT_SECTOR_SIZE;
   3524 }
   3525 
   3526 /*
   3527 ** Return the device characteristics for the file. This is always 0 for unix.
   3528 */
   3529 static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
   3530   UNUSED_PARAMETER(NotUsed);
   3531   return 0;
   3532 }
   3533 
   3534 #ifndef SQLITE_OMIT_WAL
   3535 
   3536 
   3537 /*
   3538 ** Object used to represent an shared memory buffer.
   3539 **
   3540 ** When multiple threads all reference the same wal-index, each thread
   3541 ** has its own unixShm object, but they all point to a single instance
   3542 ** of this unixShmNode object.  In other words, each wal-index is opened
   3543 ** only once per process.
   3544 **
   3545 ** Each unixShmNode object is connected to a single unixInodeInfo object.
   3546 ** We could coalesce this object into unixInodeInfo, but that would mean
   3547 ** every open file that does not use shared memory (in other words, most
   3548 ** open files) would have to carry around this extra information.  So
   3549 ** the unixInodeInfo object contains a pointer to this unixShmNode object
   3550 ** and the unixShmNode object is created only when needed.
   3551 **
   3552 ** unixMutexHeld() must be true when creating or destroying
   3553 ** this object or while reading or writing the following fields:
   3554 **
   3555 **      nRef
   3556 **
   3557 ** The following fields are read-only after the object is created:
   3558 **
   3559 **      fid
   3560 **      zFilename
   3561 **
   3562 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
   3563 ** unixMutexHeld() is true when reading or writing any other field
   3564 ** in this structure.
   3565 */
   3566 struct unixShmNode {
   3567   unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
   3568   sqlite3_mutex *mutex;      /* Mutex to access this object */
   3569   char *zFilename;           /* Name of the mmapped file */
   3570   int h;                     /* Open file descriptor */
   3571   int szRegion;              /* Size of shared-memory regions */
   3572   int nRegion;               /* Size of array apRegion */
   3573   char **apRegion;           /* Array of mapped shared-memory regions */
   3574   int nRef;                  /* Number of unixShm objects pointing to this */
   3575   unixShm *pFirst;           /* All unixShm objects pointing to this */
   3576 #ifdef SQLITE_DEBUG
   3577   u8 exclMask;               /* Mask of exclusive locks held */
   3578   u8 sharedMask;             /* Mask of shared locks held */
   3579   u8 nextShmId;              /* Next available unixShm.id value */
   3580 #endif
   3581 };
   3582 
   3583 /*
   3584 ** Structure used internally by this VFS to record the state of an
   3585 ** open shared memory connection.
   3586 **
   3587 ** The following fields are initialized when this object is created and
   3588 ** are read-only thereafter:
   3589 **
   3590 **    unixShm.pFile
   3591 **    unixShm.id
   3592 **
   3593 ** All other fields are read/write.  The unixShm.pFile->mutex must be held
   3594 ** while accessing any read/write fields.
   3595 */
   3596 struct unixShm {
   3597   unixShmNode *pShmNode;     /* The underlying unixShmNode object */
   3598   unixShm *pNext;            /* Next unixShm with the same unixShmNode */
   3599   u8 hasMutex;               /* True if holding the unixShmNode mutex */
   3600   u16 sharedMask;            /* Mask of shared locks held */
   3601   u16 exclMask;              /* Mask of exclusive locks held */
   3602 #ifdef SQLITE_DEBUG
   3603   u8 id;                     /* Id of this connection within its unixShmNode */
   3604 #endif
   3605 };
   3606 
   3607 /*
   3608 ** Constants used for locking
   3609 */
   3610 #define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
   3611 #define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
   3612 
   3613 /*
   3614 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
   3615 **
   3616 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
   3617 ** otherwise.
   3618 */
   3619 static int unixShmSystemLock(
   3620   unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
   3621   int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
   3622   int ofst,              /* First byte of the locking range */
   3623   int n                  /* Number of bytes to lock */
   3624 ){
   3625   struct flock f;       /* The posix advisory locking structure */
   3626   int rc = SQLITE_OK;   /* Result code form fcntl() */
   3627 
   3628   /* Access to the unixShmNode object is serialized by the caller */
   3629   assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
   3630 
   3631   /* Shared locks never span more than one byte */
   3632   assert( n==1 || lockType!=F_RDLCK );
   3633 
   3634   /* Locks are within range */
   3635   assert( n>=1 && n<SQLITE_SHM_NLOCK );
   3636 
   3637   if( pShmNode->h>=0 ){
   3638     /* Initialize the locking parameters */
   3639     memset(&f, 0, sizeof(f));
   3640     f.l_type = lockType;
   3641     f.l_whence = SEEK_SET;
   3642     f.l_start = ofst;
   3643     f.l_len = n;
   3644 
   3645     rc = osFcntl(pShmNode->h, F_SETLK, &f);
   3646     rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
   3647   }
   3648 
   3649   /* Update the global lock state and do debug tracing */
   3650 #ifdef SQLITE_DEBUG
   3651   { u16 mask;
   3652   OSTRACE(("SHM-LOCK "));
   3653   mask = (1<<(ofst+n)) - (1<<ofst);
   3654   if( rc==SQLITE_OK ){
   3655     if( lockType==F_UNLCK ){
   3656       OSTRACE(("unlock %d ok", ofst));
   3657       pShmNode->exclMask &= ~mask;
   3658       pShmNode->sharedMask &= ~mask;
   3659     }else if( lockType==F_RDLCK ){
   3660       OSTRACE(("read-lock %d ok", ofst));
   3661       pShmNode->exclMask &= ~mask;
   3662       pShmNode->sharedMask |= mask;
   3663     }else{
   3664       assert( lockType==F_WRLCK );
   3665       OSTRACE(("write-lock %d ok", ofst));
   3666       pShmNode->exclMask |= mask;
   3667       pShmNode->sharedMask &= ~mask;
   3668     }
   3669   }else{
   3670     if( lockType==F_UNLCK ){
   3671       OSTRACE(("unlock %d failed", ofst));
   3672     }else if( lockType==F_RDLCK ){
   3673       OSTRACE(("read-lock failed"));
   3674     }else{
   3675       assert( lockType==F_WRLCK );
   3676       OSTRACE(("write-lock %d failed", ofst));
   3677     }
   3678   }
   3679   OSTRACE((" - afterwards %03x,%03x\n",
   3680            pShmNode->sharedMask, pShmNode->exclMask));
   3681   }
   3682 #endif
   3683 
   3684   return rc;
   3685 }
   3686 
   3687 
   3688 /*
   3689 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
   3690 **
   3691 ** This is not a VFS shared-memory method; it is a utility function called
   3692 ** by VFS shared-memory methods.
   3693 */
   3694 static void unixShmPurge(unixFile *pFd){
   3695   unixShmNode *p = pFd->pInode->pShmNode;
   3696   assert( unixMutexHeld() );
   3697   if( p && p->nRef==0 ){
   3698     int i;
   3699     assert( p->pInode==pFd->pInode );
   3700     if( p->mutex ) sqlite3_mutex_free(p->mutex);
   3701     for(i=0; i<p->nRegion; i++){
   3702       if( p->h>=0 ){
   3703         munmap(p->apRegion[i], p->szRegion);
   3704       }else{
   3705         sqlite3_free(p->apRegion[i]);
   3706       }
   3707     }
   3708     sqlite3_free(p->apRegion);
   3709     if( p->h>=0 ){
   3710       robust_close(pFd, p->h, __LINE__);
   3711       p->h = -1;
   3712     }
   3713     p->pInode->pShmNode = 0;
   3714     sqlite3_free(p);
   3715   }
   3716 }
   3717 
   3718 /*
   3719 ** Open a shared-memory area associated with open database file pDbFd.
   3720 ** This particular implementation uses mmapped files.
   3721 **
   3722 ** The file used to implement shared-memory is in the same directory
   3723 ** as the open database file and has the same name as the open database
   3724 ** file with the "-shm" suffix added.  For example, if the database file
   3725 ** is "/home/user1/config.db" then the file that is created and mmapped
   3726 ** for shared memory will be called "/home/user1/config.db-shm".
   3727 **
   3728 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
   3729 ** some other tmpfs mount. But if a file in a different directory
   3730 ** from the database file is used, then differing access permissions
   3731 ** or a chroot() might cause two different processes on the same
   3732 ** database to end up using different files for shared memory -
   3733 ** meaning that their memory would not really be shared - resulting
   3734 ** in database corruption.  Nevertheless, this tmpfs file usage
   3735 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
   3736 ** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
   3737 ** option results in an incompatible build of SQLite;  builds of SQLite
   3738 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
   3739 ** same database file at the same time, database corruption will likely
   3740 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
   3741 ** "unsupported" and may go away in a future SQLite release.
   3742 **
   3743 ** When opening a new shared-memory file, if no other instances of that
   3744 ** file are currently open, in this process or in other processes, then
   3745 ** the file must be truncated to zero length or have its header cleared.
   3746 **
   3747 ** If the original database file (pDbFd) is using the "unix-excl" VFS
   3748 ** that means that an exclusive lock is held on the database file and
   3749 ** that no other processes are able to read or write the database.  In
   3750 ** that case, we do not really need shared memory.  No shared memory
   3751 ** file is created.  The shared memory will be simulated with heap memory.
   3752 */
   3753 static int unixOpenSharedMemory(unixFile *pDbFd){
   3754   struct unixShm *p = 0;          /* The connection to be opened */
   3755   struct unixShmNode *pShmNode;   /* The underlying mmapped file */
   3756   int rc;                         /* Result code */
   3757   unixInodeInfo *pInode;          /* The inode of fd */
   3758   char *zShmFilename;             /* Name of the file used for SHM */
   3759   int nShmFilename;               /* Size of the SHM filename in bytes */
   3760 
   3761   /* Allocate space for the new unixShm object. */
   3762   p = sqlite3_malloc( sizeof(*p) );
   3763   if( p==0 ) return SQLITE_NOMEM;
   3764   memset(p, 0, sizeof(*p));
   3765   assert( pDbFd->pShm==0 );
   3766 
   3767   /* Check to see if a unixShmNode object already exists. Reuse an existing
   3768   ** one if present. Create a new one if necessary.
   3769   */
   3770   unixEnterMutex();
   3771   pInode = pDbFd->pInode;
   3772   pShmNode = pInode->pShmNode;
   3773   if( pShmNode==0 ){
   3774     struct stat sStat;                 /* fstat() info for database file */
   3775 
   3776     /* Call fstat() to figure out the permissions on the database file. If
   3777     ** a new *-shm file is created, an attempt will be made to create it
   3778     ** with the same permissions. The actual permissions the file is created
   3779     ** with are subject to the current umask setting.
   3780     */
   3781     if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
   3782       rc = SQLITE_IOERR_FSTAT;
   3783       goto shm_open_err;
   3784     }
   3785 
   3786 #ifdef SQLITE_SHM_DIRECTORY
   3787     nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
   3788 #else
   3789     nShmFilename = 5 + (int)strlen(pDbFd->zPath);
   3790 #endif
   3791     pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
   3792     if( pShmNode==0 ){
   3793       rc = SQLITE_NOMEM;
   3794       goto shm_open_err;
   3795     }
   3796     memset(pShmNode, 0, sizeof(*pShmNode));
   3797     zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
   3798 #ifdef SQLITE_SHM_DIRECTORY
   3799     sqlite3_snprintf(nShmFilename, zShmFilename,
   3800                      SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
   3801                      (u32)sStat.st_ino, (u32)sStat.st_dev);
   3802 #else
   3803     sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
   3804 #endif
   3805     pShmNode->h = -1;
   3806     pDbFd->pInode->pShmNode = pShmNode;
   3807     pShmNode->pInode = pDbFd->pInode;
   3808     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
   3809     if( pShmNode->mutex==0 ){
   3810       rc = SQLITE_NOMEM;
   3811       goto shm_open_err;
   3812     }
   3813 
   3814     if( pInode->bProcessLock==0 ){
   3815       pShmNode->h = robust_open(zShmFilename, O_RDWR|O_CREAT,
   3816                                (sStat.st_mode & 0777));
   3817       if( pShmNode->h<0 ){
   3818         rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
   3819         goto shm_open_err;
   3820       }
   3821 
   3822       /* Check to see if another process is holding the dead-man switch.
   3823       ** If not, truncate the file to zero length.
   3824       */
   3825       rc = SQLITE_OK;
   3826       if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
   3827         if( robust_ftruncate(pShmNode->h, 0) ){
   3828           rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
   3829         }
   3830       }
   3831       if( rc==SQLITE_OK ){
   3832         rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
   3833       }
   3834       if( rc ) goto shm_open_err;
   3835     }
   3836   }
   3837 
   3838   /* Make the new connection a child of the unixShmNode */
   3839   p->pShmNode = pShmNode;
   3840 #ifdef SQLITE_DEBUG
   3841   p->id = pShmNode->nextShmId++;
   3842 #endif
   3843   pShmNode->nRef++;
   3844   pDbFd->pShm = p;
   3845   unixLeaveMutex();
   3846 
   3847   /* The reference count on pShmNode has already been incremented under
   3848   ** the cover of the unixEnterMutex() mutex and the pointer from the
   3849   ** new (struct unixShm) object to the pShmNode has been set. All that is
   3850   ** left to do is to link the new object into the linked list starting
   3851   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
   3852   ** mutex.
   3853   */
   3854   sqlite3_mutex_enter(pShmNode->mutex);
   3855   p->pNext = pShmNode->pFirst;
   3856   pShmNode->pFirst = p;
   3857   sqlite3_mutex_leave(pShmNode->mutex);
   3858   return SQLITE_OK;
   3859 
   3860   /* Jump here on any error */
   3861 shm_open_err:
   3862   unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
   3863   sqlite3_free(p);
   3864   unixLeaveMutex();
   3865   return rc;
   3866 }
   3867 
   3868 /*
   3869 ** This function is called to obtain a pointer to region iRegion of the
   3870 ** shared-memory associated with the database file fd. Shared-memory regions
   3871 ** are numbered starting from zero. Each shared-memory region is szRegion
   3872 ** bytes in size.
   3873 **
   3874 ** If an error occurs, an error code is returned and *pp is set to NULL.
   3875 **
   3876 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
   3877 ** region has not been allocated (by any client, including one running in a
   3878 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
   3879 ** bExtend is non-zero and the requested shared-memory region has not yet
   3880 ** been allocated, it is allocated by this function.
   3881 **
   3882 ** If the shared-memory region has already been allocated or is allocated by
   3883 ** this call as described above, then it is mapped into this processes
   3884 ** address space (if it is not already), *pp is set to point to the mapped
   3885 ** memory and SQLITE_OK returned.
   3886 */
   3887 static int unixShmMap(
   3888   sqlite3_file *fd,               /* Handle open on database file */
   3889   int iRegion,                    /* Region to retrieve */
   3890   int szRegion,                   /* Size of regions */
   3891   int bExtend,                    /* True to extend file if necessary */
   3892   void volatile **pp              /* OUT: Mapped memory */
   3893 ){
   3894   unixFile *pDbFd = (unixFile*)fd;
   3895   unixShm *p;
   3896   unixShmNode *pShmNode;
   3897   int rc = SQLITE_OK;
   3898 
   3899   /* If the shared-memory file has not yet been opened, open it now. */
   3900   if( pDbFd->pShm==0 ){
   3901     rc = unixOpenSharedMemory(pDbFd);
   3902     if( rc!=SQLITE_OK ) return rc;
   3903   }
   3904 
   3905   p = pDbFd->pShm;
   3906   pShmNode = p->pShmNode;
   3907   sqlite3_mutex_enter(pShmNode->mutex);
   3908   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
   3909   assert( pShmNode->pInode==pDbFd->pInode );
   3910   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
   3911   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
   3912 
   3913   if( pShmNode->nRegion<=iRegion ){
   3914     char **apNew;                      /* New apRegion[] array */
   3915     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
   3916     struct stat sStat;                 /* Used by fstat() */
   3917 
   3918     pShmNode->szRegion = szRegion;
   3919 
   3920     if( pShmNode->h>=0 ){
   3921       /* The requested region is not mapped into this processes address space.
   3922       ** Check to see if it has been allocated (i.e. if the wal-index file is
   3923       ** large enough to contain the requested region).
   3924       */
   3925       if( osFstat(pShmNode->h, &sStat) ){
   3926         rc = SQLITE_IOERR_SHMSIZE;
   3927         goto shmpage_out;
   3928       }
   3929 
   3930       if( sStat.st_size<nByte ){
   3931         /* The requested memory region does not exist. If bExtend is set to
   3932         ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
   3933         **
   3934         ** Alternatively, if bExtend is true, use ftruncate() to allocate
   3935         ** the requested memory region.
   3936         */
   3937         if( !bExtend ) goto shmpage_out;
   3938         if( robust_ftruncate(pShmNode->h, nByte) ){
   3939           rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
   3940                             pShmNode->zFilename);
   3941           goto shmpage_out;
   3942         }
   3943       }
   3944     }
   3945 
   3946     /* Map the requested memory region into this processes address space. */
   3947     apNew = (char **)sqlite3_realloc(
   3948         pShmNode->apRegion, (iRegion+1)*sizeof(char *)
   3949     );
   3950     if( !apNew ){
   3951       rc = SQLITE_IOERR_NOMEM;
   3952       goto shmpage_out;
   3953     }
   3954     pShmNode->apRegion = apNew;
   3955     while(pShmNode->nRegion<=iRegion){
   3956       void *pMem;
   3957       if( pShmNode->h>=0 ){
   3958         pMem = mmap(0, szRegion, PROT_READ|PROT_WRITE,
   3959             MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
   3960         );
   3961         if( pMem==MAP_FAILED ){
   3962           rc = SQLITE_IOERR;
   3963           goto shmpage_out;
   3964         }
   3965       }else{
   3966         pMem = sqlite3_malloc(szRegion);
   3967         if( pMem==0 ){
   3968           rc = SQLITE_NOMEM;
   3969           goto shmpage_out;
   3970         }
   3971         memset(pMem, 0, szRegion);
   3972       }
   3973       pShmNode->apRegion[pShmNode->nRegion] = pMem;
   3974       pShmNode->nRegion++;
   3975     }
   3976   }
   3977 
   3978 shmpage_out:
   3979   if( pShmNode->nRegion>iRegion ){
   3980     *pp = pShmNode->apRegion[iRegion];
   3981   }else{
   3982     *pp = 0;
   3983   }
   3984   sqlite3_mutex_leave(pShmNode->mutex);
   3985   return rc;
   3986 }
   3987 
   3988 /*
   3989 ** Change the lock state for a shared-memory segment.
   3990 **
   3991 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
   3992 ** different here than in posix.  In xShmLock(), one can go from unlocked
   3993 ** to shared and back or from unlocked to exclusive and back.  But one may
   3994 ** not go from shared to exclusive or from exclusive to shared.
   3995 */
   3996 static int unixShmLock(
   3997   sqlite3_file *fd,          /* Database file holding the shared memory */
   3998   int ofst,                  /* First lock to acquire or release */
   3999   int n,                     /* Number of locks to acquire or release */
   4000   int flags                  /* What to do with the lock */
   4001 ){
   4002   unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
   4003   unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
   4004   unixShm *pX;                          /* For looping over all siblings */
   4005   unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
   4006   int rc = SQLITE_OK;                   /* Result code */
   4007   u16 mask;                             /* Mask of locks to take or release */
   4008 
   4009   assert( pShmNode==pDbFd->pInode->pShmNode );
   4010   assert( pShmNode->pInode==pDbFd->pInode );
   4011   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
   4012   assert( n>=1 );
   4013   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
   4014        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
   4015        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
   4016        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
   4017   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
   4018   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
   4019   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
   4020 
   4021   mask = (1<<(ofst+n)) - (1<<ofst);
   4022   assert( n>1 || mask==(1<<ofst) );
   4023   sqlite3_mutex_enter(pShmNode->mutex);
   4024   if( flags & SQLITE_SHM_UNLOCK ){
   4025     u16 allMask = 0; /* Mask of locks held by siblings */
   4026 
   4027     /* See if any siblings hold this same lock */
   4028     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   4029       if( pX==p ) continue;
   4030       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
   4031       allMask |= pX->sharedMask;
   4032     }
   4033 
   4034     /* Unlock the system-level locks */
   4035     if( (mask & allMask)==0 ){
   4036       rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
   4037     }else{
   4038       rc = SQLITE_OK;
   4039     }
   4040 
   4041     /* Undo the local locks */
   4042     if( rc==SQLITE_OK ){
   4043       p->exclMask &= ~mask;
   4044       p->sharedMask &= ~mask;
   4045     }
   4046   }else if( flags & SQLITE_SHM_SHARED ){
   4047     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
   4048 
   4049     /* Find out which shared locks are already held by sibling connections.
   4050     ** If any sibling already holds an exclusive lock, go ahead and return
   4051     ** SQLITE_BUSY.
   4052     */
   4053     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   4054       if( (pX->exclMask & mask)!=0 ){
   4055         rc = SQLITE_BUSY;
   4056         break;
   4057       }
   4058       allShared |= pX->sharedMask;
   4059     }
   4060 
   4061     /* Get shared locks at the system level, if necessary */
   4062     if( rc==SQLITE_OK ){
   4063       if( (allShared & mask)==0 ){
   4064         rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
   4065       }else{
   4066         rc = SQLITE_OK;
   4067       }
   4068     }
   4069 
   4070     /* Get the local shared locks */
   4071     if( rc==SQLITE_OK ){
   4072       p->sharedMask |= mask;
   4073     }
   4074   }else{
   4075     /* Make sure no sibling connections hold locks that will block this
   4076     ** lock.  If any do, return SQLITE_BUSY right away.
   4077     */
   4078     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   4079       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
   4080         rc = SQLITE_BUSY;
   4081         break;
   4082       }
   4083     }
   4084 
   4085     /* Get the exclusive locks at the system level.  Then if successful
   4086     ** also mark the local connection as being locked.
   4087     */
   4088     if( rc==SQLITE_OK ){
   4089       rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
   4090       if( rc==SQLITE_OK ){
   4091         assert( (p->sharedMask & mask)==0 );
   4092         p->exclMask |= mask;
   4093       }
   4094     }
   4095   }
   4096   sqlite3_mutex_leave(pShmNode->mutex);
   4097   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
   4098            p->id, getpid(), p->sharedMask, p->exclMask));
   4099   return rc;
   4100 }
   4101 
   4102 /*
   4103 ** Implement a memory barrier or memory fence on shared memory.
   4104 **
   4105 ** All loads and stores begun before the barrier must complete before
   4106 ** any load or store begun after the barrier.
   4107 */
   4108 static void unixShmBarrier(
   4109   sqlite3_file *fd                /* Database file holding the shared memory */
   4110 ){
   4111   UNUSED_PARAMETER(fd);
   4112   unixEnterMutex();
   4113   unixLeaveMutex();
   4114 }
   4115 
   4116 /*
   4117 ** Close a connection to shared-memory.  Delete the underlying
   4118 ** storage if deleteFlag is true.
   4119 **
   4120 ** If there is no shared memory associated with the connection then this
   4121 ** routine is a harmless no-op.
   4122 */
   4123 static int unixShmUnmap(
   4124   sqlite3_file *fd,               /* The underlying database file */
   4125   int deleteFlag                  /* Delete shared-memory if true */
   4126 ){
   4127   unixShm *p;                     /* The connection to be closed */
   4128   unixShmNode *pShmNode;          /* The underlying shared-memory file */
   4129   unixShm **pp;                   /* For looping over sibling connections */
   4130   unixFile *pDbFd;                /* The underlying database file */
   4131 
   4132   pDbFd = (unixFile*)fd;
   4133   p = pDbFd->pShm;
   4134   if( p==0 ) return SQLITE_OK;
   4135   pShmNode = p->pShmNode;
   4136 
   4137   assert( pShmNode==pDbFd->pInode->pShmNode );
   4138   assert( pShmNode->pInode==pDbFd->pInode );
   4139 
   4140   /* Remove connection p from the set of connections associated
   4141   ** with pShmNode */
   4142   sqlite3_mutex_enter(pShmNode->mutex);
   4143   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
   4144   *pp = p->pNext;
   4145 
   4146   /* Free the connection p */
   4147   sqlite3_free(p);
   4148   pDbFd->pShm = 0;
   4149   sqlite3_mutex_leave(pShmNode->mutex);
   4150 
   4151   /* If pShmNode->nRef has reached 0, then close the underlying
   4152   ** shared-memory file, too */
   4153   unixEnterMutex();
   4154   assert( pShmNode->nRef>0 );
   4155   pShmNode->nRef--;
   4156   if( pShmNode->nRef==0 ){
   4157     if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
   4158     unixShmPurge(pDbFd);
   4159   }
   4160   unixLeaveMutex();
   4161 
   4162   return SQLITE_OK;
   4163 }
   4164 
   4165 
   4166 #else
   4167 # define unixShmMap     0
   4168 # define unixShmLock    0
   4169 # define unixShmBarrier 0
   4170 # define unixShmUnmap   0
   4171 #endif /* #ifndef SQLITE_OMIT_WAL */
   4172 
   4173 /*
   4174 ** Here ends the implementation of all sqlite3_file methods.
   4175 **
   4176 ********************** End sqlite3_file Methods *******************************
   4177 ******************************************************************************/
   4178 
   4179 /*
   4180 ** This division contains definitions of sqlite3_io_methods objects that
   4181 ** implement various file locking strategies.  It also contains definitions
   4182 ** of "finder" functions.  A finder-function is used to locate the appropriate
   4183 ** sqlite3_io_methods object for a particular database file.  The pAppData
   4184 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
   4185 ** the correct finder-function for that VFS.
   4186 **
   4187 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
   4188 ** object.  The only interesting finder-function is autolockIoFinder, which
   4189 ** looks at the filesystem type and tries to guess the best locking
   4190 ** strategy from that.
   4191 **
   4192 ** For finder-funtion F, two objects are created:
   4193 **
   4194 **    (1) The real finder-function named "FImpt()".
   4195 **
   4196 **    (2) A constant pointer to this function named just "F".
   4197 **
   4198 **
   4199 ** A pointer to the F pointer is used as the pAppData value for VFS
   4200 ** objects.  We have to do this instead of letting pAppData point
   4201 ** directly at the finder-function since C90 rules prevent a void*
   4202 ** from be cast into a function pointer.
   4203 **
   4204 **
   4205 ** Each instance of this macro generates two objects:
   4206 **
   4207 **   *  A constant sqlite3_io_methods object call METHOD that has locking
   4208 **      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
   4209 **
   4210 **   *  An I/O method finder function called FINDER that returns a pointer
   4211 **      to the METHOD object in the previous bullet.
   4212 */
   4213 #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK)      \
   4214 static const sqlite3_io_methods METHOD = {                                   \
   4215    VERSION,                    /* iVersion */                                \
   4216    CLOSE,                      /* xClose */                                  \
   4217    unixRead,                   /* xRead */                                   \
   4218    unixWrite,                  /* xWrite */                                  \
   4219    unixTruncate,               /* xTruncate */                               \
   4220    unixSync,                   /* xSync */                                   \
   4221    unixFileSize,               /* xFileSize */                               \
   4222    LOCK,                       /* xLock */                                   \
   4223    UNLOCK,                     /* xUnlock */                                 \
   4224    CKLOCK,                     /* xCheckReservedLock */                      \
   4225    unixFileControl,            /* xFileControl */                            \
   4226    unixSectorSize,             /* xSectorSize */                             \
   4227    unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
   4228    unixShmMap,                 /* xShmMap */                                 \
   4229    unixShmLock,                /* xShmLock */                                \
   4230    unixShmBarrier,             /* xShmBarrier */                             \
   4231    unixShmUnmap                /* xShmUnmap */                               \
   4232 };                                                                           \
   4233 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
   4234   UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
   4235   return &METHOD;                                                            \
   4236 }                                                                            \
   4237 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
   4238     = FINDER##Impl;
   4239 
   4240 /*
   4241 ** Here are all of the sqlite3_io_methods objects for each of the
   4242 ** locking strategies.  Functions that return pointers to these methods
   4243 ** are also created.
   4244 */
   4245 IOMETHODS(
   4246   posixIoFinder,            /* Finder function name */
   4247   posixIoMethods,           /* sqlite3_io_methods object name */
   4248   2,                        /* shared memory is enabled */
   4249   unixClose,                /* xClose method */
   4250   unixLock,                 /* xLock method */
   4251   unixUnlock,               /* xUnlock method */
   4252   unixCheckReservedLock     /* xCheckReservedLock method */
   4253 )
   4254 IOMETHODS(
   4255   nolockIoFinder,           /* Finder function name */
   4256   nolockIoMethods,          /* sqlite3_io_methods object name */
   4257   1,                        /* shared memory is disabled */
   4258   nolockClose,              /* xClose method */
   4259   nolockLock,               /* xLock method */
   4260   nolockUnlock,             /* xUnlock method */
   4261   nolockCheckReservedLock   /* xCheckReservedLock method */
   4262 )
   4263 IOMETHODS(
   4264   dotlockIoFinder,          /* Finder function name */
   4265   dotlockIoMethods,         /* sqlite3_io_methods object name */
   4266   1,                        /* shared memory is disabled */
   4267   dotlockClose,             /* xClose method */
   4268   dotlockLock,              /* xLock method */
   4269   dotlockUnlock,            /* xUnlock method */
   4270   dotlockCheckReservedLock  /* xCheckReservedLock method */
   4271 )
   4272 
   4273 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
   4274 IOMETHODS(
   4275   flockIoFinder,            /* Finder function name */
   4276   flockIoMethods,           /* sqlite3_io_methods object name */
   4277   1,                        /* shared memory is disabled */
   4278   flockClose,               /* xClose method */
   4279   flockLock,                /* xLock method */
   4280   flockUnlock,              /* xUnlock method */
   4281   flockCheckReservedLock    /* xCheckReservedLock method */
   4282 )
   4283 #endif
   4284 
   4285 #if OS_VXWORKS
   4286 IOMETHODS(
   4287   semIoFinder,              /* Finder function name */
   4288   semIoMethods,             /* sqlite3_io_methods object name */
   4289   1,                        /* shared memory is disabled */
   4290   semClose,                 /* xClose method */
   4291   semLock,                  /* xLock method */
   4292   semUnlock,                /* xUnlock method */
   4293   semCheckReservedLock      /* xCheckReservedLock method */
   4294 )
   4295 #endif
   4296 
   4297 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   4298 IOMETHODS(
   4299   afpIoFinder,              /* Finder function name */
   4300   afpIoMethods,             /* sqlite3_io_methods object name */
   4301   1,                        /* shared memory is disabled */
   4302   afpClose,                 /* xClose method */
   4303   afpLock,                  /* xLock method */
   4304   afpUnlock,                /* xUnlock method */
   4305   afpCheckReservedLock      /* xCheckReservedLock method */
   4306 )
   4307 #endif
   4308 
   4309 /*
   4310 ** The proxy locking method is a "super-method" in the sense that it
   4311 ** opens secondary file descriptors for the conch and lock files and
   4312 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
   4313 ** secondary files.  For this reason, the division that implements
   4314 ** proxy locking is located much further down in the file.  But we need
   4315 ** to go ahead and define the sqlite3_io_methods and finder function
   4316 ** for proxy locking here.  So we forward declare the I/O methods.
   4317 */
   4318 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   4319 static int proxyClose(sqlite3_file*);
   4320 static int proxyLock(sqlite3_file*, int);
   4321 static int proxyUnlock(sqlite3_file*, int);
   4322 static int proxyCheckReservedLock(sqlite3_file*, int*);
   4323 IOMETHODS(
   4324   proxyIoFinder,            /* Finder function name */
   4325   proxyIoMethods,           /* sqlite3_io_methods object name */
   4326   1,                        /* shared memory is disabled */
   4327   proxyClose,               /* xClose method */
   4328   proxyLock,                /* xLock method */
   4329   proxyUnlock,              /* xUnlock method */
   4330   proxyCheckReservedLock    /* xCheckReservedLock method */
   4331 )
   4332 #endif
   4333 
   4334 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
   4335 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   4336 IOMETHODS(
   4337   nfsIoFinder,               /* Finder function name */
   4338   nfsIoMethods,              /* sqlite3_io_methods object name */
   4339   1,                         /* shared memory is disabled */
   4340   unixClose,                 /* xClose method */
   4341   unixLock,                  /* xLock method */
   4342   nfsUnlock,                 /* xUnlock method */
   4343   unixCheckReservedLock      /* xCheckReservedLock method */
   4344 )
   4345 #endif
   4346 
   4347 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   4348 /*
   4349 ** This "finder" function attempts to determine the best locking strategy
   4350 ** for the database file "filePath".  It then returns the sqlite3_io_methods
   4351 ** object that implements that strategy.
   4352 **
   4353 ** This is for MacOSX only.
   4354 */
   4355 static const sqlite3_io_methods *autolockIoFinderImpl(
   4356   const char *filePath,    /* name of the database file */
   4357   unixFile *pNew           /* open file object for the database file */
   4358 ){
   4359   static const struct Mapping {
   4360     const char *zFilesystem;              /* Filesystem type name */
   4361     const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
   4362   } aMap[] = {
   4363     { "hfs",    &posixIoMethods },
   4364     { "ufs",    &posixIoMethods },
   4365     { "afpfs",  &afpIoMethods },
   4366     { "smbfs",  &afpIoMethods },
   4367     { "webdav", &nolockIoMethods },
   4368     { 0, 0 }
   4369   };
   4370   int i;
   4371   struct statfs fsInfo;
   4372   struct flock lockInfo;
   4373 
   4374   if( !filePath ){
   4375     /* If filePath==NULL that means we are dealing with a transient file
   4376     ** that does not need to be locked. */
   4377     return &nolockIoMethods;
   4378   }
   4379   if( statfs(filePath, &fsInfo) != -1 ){
   4380     if( fsInfo.f_flags & MNT_RDONLY ){
   4381       return &nolockIoMethods;
   4382     }
   4383     for(i=0; aMap[i].zFilesystem; i++){
   4384       if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
   4385         return aMap[i].pMethods;
   4386       }
   4387     }
   4388   }
   4389 
   4390   /* Default case. Handles, amongst others, "nfs".
   4391   ** Test byte-range lock using fcntl(). If the call succeeds,
   4392   ** assume that the file-system supports POSIX style locks.
   4393   */
   4394   lockInfo.l_len = 1;
   4395   lockInfo.l_start = 0;
   4396   lockInfo.l_whence = SEEK_SET;
   4397   lockInfo.l_type = F_RDLCK;
   4398   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
   4399     if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
   4400       return &nfsIoMethods;
   4401     } else {
   4402       return &posixIoMethods;
   4403     }
   4404   }else{
   4405     return &dotlockIoMethods;
   4406   }
   4407 }
   4408 static const sqlite3_io_methods
   4409   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
   4410 
   4411 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
   4412 
   4413 #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
   4414 /*
   4415 ** This "finder" function attempts to determine the best locking strategy
   4416 ** for the database file "filePath".  It then returns the sqlite3_io_methods
   4417 ** object that implements that strategy.
   4418 **
   4419 ** This is for VXWorks only.
   4420 */
   4421 static const sqlite3_io_methods *autolockIoFinderImpl(
   4422   const char *filePath,    /* name of the database file */
   4423   unixFile *pNew           /* the open file object */
   4424 ){
   4425   struct flock lockInfo;
   4426 
   4427   if( !filePath ){
   4428     /* If filePath==NULL that means we are dealing with a transient file
   4429     ** that does not need to be locked. */
   4430     return &nolockIoMethods;
   4431   }
   4432 
   4433   /* Test if fcntl() is supported and use POSIX style locks.
   4434   ** Otherwise fall back to the named semaphore method.
   4435   */
   4436   lockInfo.l_len = 1;
   4437   lockInfo.l_start = 0;
   4438   lockInfo.l_whence = SEEK_SET;
   4439   lockInfo.l_type = F_RDLCK;
   4440   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
   4441     return &posixIoMethods;
   4442   }else{
   4443     return &semIoMethods;
   4444   }
   4445 }
   4446 static const sqlite3_io_methods
   4447   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
   4448 
   4449 #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
   4450 
   4451 /*
   4452 ** An abstract type for a pointer to a IO method finder function:
   4453 */
   4454 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
   4455 
   4456 
   4457 /****************************************************************************
   4458 **************************** sqlite3_vfs methods ****************************
   4459 **
   4460 ** This division contains the implementation of methods on the
   4461 ** sqlite3_vfs object.
   4462 */
   4463 
   4464 /*
   4465 ** Initializes a unixFile structure with zeros.
   4466 */
   4467 void initUnixFile(sqlite3_file* file) {
   4468   memset(file, 0, sizeof(unixFile));
   4469 }
   4470 
   4471 /*
   4472 ** Initialize the contents of the unixFile structure pointed to by pId.
   4473 */
   4474 int fillInUnixFile(
   4475   sqlite3_vfs *pVfs,      /* Pointer to vfs object */
   4476   int h,                  /* Open file descriptor of file being opened */
   4477   int syncDir,            /* True to sync directory on first sync */
   4478   sqlite3_file *pId,      /* Write to the unixFile structure here */
   4479   const char *zFilename,  /* Name of the file being opened */
   4480   int noLock,             /* Omit locking if true */
   4481   int isDelete,           /* Delete on close if true */
   4482   int isReadOnly          /* True if the file is opened read-only */
   4483 ){
   4484   const sqlite3_io_methods *pLockingStyle;
   4485   unixFile *pNew = (unixFile *)pId;
   4486   int rc = SQLITE_OK;
   4487 
   4488   assert( pNew->pInode==NULL );
   4489 
   4490   /* Parameter isDelete is only used on vxworks. Express this explicitly
   4491   ** here to prevent compiler warnings about unused parameters.
   4492   */
   4493   UNUSED_PARAMETER(isDelete);
   4494 
   4495   /* Usually the path zFilename should not be a relative pathname. The
   4496   ** exception is when opening the proxy "conch" file in builds that
   4497   ** include the special Apple locking styles.
   4498   */
   4499 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   4500   assert( zFilename==0 || zFilename[0]=='/'
   4501     || pVfs->pAppData==(void*)&autolockIoFinder );
   4502 #else
   4503   assert( zFilename==0 || zFilename[0]=='/' );
   4504 #endif
   4505 
   4506   OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
   4507   pNew->h = h;
   4508   pNew->zPath = zFilename;
   4509   if( strcmp(pVfs->zName,"unix-excl")==0 ){
   4510     pNew->ctrlFlags = UNIXFILE_EXCL;
   4511   }else{
   4512     pNew->ctrlFlags = 0;
   4513   }
   4514   if( isReadOnly ){
   4515     pNew->ctrlFlags |= UNIXFILE_RDONLY;
   4516   }
   4517   if( syncDir ){
   4518     pNew->ctrlFlags |= UNIXFILE_DIRSYNC;
   4519   }
   4520 
   4521 #if OS_VXWORKS
   4522   pNew->pId = vxworksFindFileId(zFilename);
   4523   if( pNew->pId==0 ){
   4524     noLock = 1;
   4525     rc = SQLITE_NOMEM;
   4526   }
   4527 #endif
   4528 
   4529   if( noLock ){
   4530     pLockingStyle = &nolockIoMethods;
   4531   }else{
   4532     pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
   4533 #if SQLITE_ENABLE_LOCKING_STYLE
   4534     /* Cache zFilename in the locking context (AFP and dotlock override) for
   4535     ** proxyLock activation is possible (remote proxy is based on db name)
   4536     ** zFilename remains valid until file is closed, to support */
   4537     pNew->lockingContext = (void*)zFilename;
   4538 #endif
   4539   }
   4540 
   4541   if( pLockingStyle == &posixIoMethods
   4542 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   4543     || pLockingStyle == &nfsIoMethods
   4544 #endif
   4545   ){
   4546     unixEnterMutex();
   4547     rc = findInodeInfo(pNew, &pNew->pInode);
   4548     if( rc!=SQLITE_OK ){
   4549       /* If an error occured in findInodeInfo(), close the file descriptor
   4550       ** immediately, before releasing the mutex. findInodeInfo() may fail
   4551       ** in two scenarios:
   4552       **
   4553       **   (a) A call to fstat() failed.
   4554       **   (b) A malloc failed.
   4555       **
   4556       ** Scenario (b) may only occur if the process is holding no other
   4557       ** file descriptors open on the same file. If there were other file
   4558       ** descriptors on this file, then no malloc would be required by
   4559       ** findInodeInfo(). If this is the case, it is quite safe to close
   4560       ** handle h - as it is guaranteed that no posix locks will be released
   4561       ** by doing so.
   4562       **
   4563       ** If scenario (a) caused the error then things are not so safe. The
   4564       ** implicit assumption here is that if fstat() fails, things are in
   4565       ** such bad shape that dropping a lock or two doesn't matter much.
   4566       */
   4567       robust_close(pNew, h, __LINE__);
   4568       h = -1;
   4569     }
   4570     unixLeaveMutex();
   4571   }
   4572 
   4573 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   4574   else if( pLockingStyle == &afpIoMethods ){
   4575     /* AFP locking uses the file path so it needs to be included in
   4576     ** the afpLockingContext.
   4577     */
   4578     afpLockingContext *pCtx;
   4579     pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
   4580     if( pCtx==0 ){
   4581       rc = SQLITE_NOMEM;
   4582     }else{
   4583       /* NB: zFilename exists and remains valid until the file is closed
   4584       ** according to requirement F11141.  So we do not need to make a
   4585       ** copy of the filename. */
   4586       pCtx->dbPath = zFilename;
   4587       pCtx->reserved = 0;
   4588       srandomdev();
   4589       unixEnterMutex();
   4590       rc = findInodeInfo(pNew, &pNew->pInode);
   4591       if( rc!=SQLITE_OK ){
   4592         sqlite3_free(pNew->lockingContext);
   4593         robust_close(pNew, h, __LINE__);
   4594         h = -1;
   4595       }
   4596       unixLeaveMutex();
   4597     }
   4598   }
   4599 #endif
   4600 
   4601   else if( pLockingStyle == &dotlockIoMethods ){
   4602     /* Dotfile locking uses the file path so it needs to be included in
   4603     ** the dotlockLockingContext
   4604     */
   4605     char *zLockFile;
   4606     int nFilename;
   4607     nFilename = (int)strlen(zFilename) + 6;
   4608     zLockFile = (char *)sqlite3_malloc(nFilename);
   4609     if( zLockFile==0 ){
   4610       rc = SQLITE_NOMEM;
   4611     }else{
   4612       sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
   4613     }
   4614     pNew->lockingContext = zLockFile;
   4615   }
   4616 
   4617 #if OS_VXWORKS
   4618   else if( pLockingStyle == &semIoMethods ){
   4619     /* Named semaphore locking uses the file path so it needs to be
   4620     ** included in the semLockingContext
   4621     */
   4622     unixEnterMutex();
   4623     rc = findInodeInfo(pNew, &pNew->pInode);
   4624     if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
   4625       char *zSemName = pNew->pInode->aSemName;
   4626       int n;
   4627       sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
   4628                        pNew->pId->zCanonicalName);
   4629       for( n=1; zSemName[n]; n++ )
   4630         if( zSemName[n]=='/' ) zSemName[n] = '_';
   4631       pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
   4632       if( pNew->pInode->pSem == SEM_FAILED ){
   4633         rc = SQLITE_NOMEM;
   4634         pNew->pInode->aSemName[0] = '\0';
   4635       }
   4636     }
   4637     unixLeaveMutex();
   4638   }
   4639 #endif
   4640 
   4641   pNew->lastErrno = 0;
   4642 #if OS_VXWORKS
   4643   if( rc!=SQLITE_OK ){
   4644     if( h>=0 ) robust_close(pNew, h, __LINE__);
   4645     h = -1;
   4646     osUnlink(zFilename);
   4647     isDelete = 0;
   4648   }
   4649   pNew->isDelete = isDelete;
   4650 #endif
   4651   if( rc!=SQLITE_OK ){
   4652     if( h>=0 ) robust_close(pNew, h, __LINE__);
   4653   }else{
   4654     pNew->pMethod = pLockingStyle;
   4655     OpenCounter(+1);
   4656   }
   4657   return rc;
   4658 }
   4659 
   4660 /*
   4661 ** Return the name of a directory in which to put temporary files.
   4662 ** If no suitable temporary file directory can be found, return NULL.
   4663 */
   4664 static const char *unixTempFileDir(void){
   4665   static const char *azDirs[] = {
   4666      0,
   4667      0,
   4668      "/var/tmp",
   4669      "/usr/tmp",
   4670      "/tmp",
   4671      0        /* List terminator */
   4672   };
   4673   unsigned int i;
   4674   struct stat buf;
   4675   const char *zDir = 0;
   4676 
   4677   azDirs[0] = sqlite3_temp_directory;
   4678   if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
   4679   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
   4680     if( zDir==0 ) continue;
   4681     if( osStat(zDir, &buf) ) continue;
   4682     if( !S_ISDIR(buf.st_mode) ) continue;
   4683     if( osAccess(zDir, 07) ) continue;
   4684     break;
   4685   }
   4686   return zDir;
   4687 }
   4688 
   4689 /*
   4690 ** Create a temporary file name in zBuf.  zBuf must be allocated
   4691 ** by the calling process and must be big enough to hold at least
   4692 ** pVfs->mxPathname bytes.
   4693 */
   4694 static int unixGetTempname(int nBuf, char *zBuf){
   4695   static const unsigned char zChars[] =
   4696     "abcdefghijklmnopqrstuvwxyz"
   4697     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
   4698     "0123456789";
   4699   unsigned int i, j;
   4700   const char *zDir;
   4701 
   4702   /* It's odd to simulate an io-error here, but really this is just
   4703   ** using the io-error infrastructure to test that SQLite handles this
   4704   ** function failing.
   4705   */
   4706   SimulateIOError( return SQLITE_IOERR );
   4707 
   4708   zDir = unixTempFileDir();
   4709   if( zDir==0 ) zDir = ".";
   4710 
   4711   /* Check that the output buffer is large enough for the temporary file
   4712   ** name. If it is not, return SQLITE_ERROR.
   4713   */
   4714   if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
   4715     return SQLITE_ERROR;
   4716   }
   4717 
   4718   do{
   4719     sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
   4720     j = (int)strlen(zBuf);
   4721     sqlite3_randomness(15, &zBuf[j]);
   4722     for(i=0; i<15; i++, j++){
   4723       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
   4724     }
   4725     zBuf[j] = 0;
   4726   }while( osAccess(zBuf,0)==0 );
   4727   return SQLITE_OK;
   4728 }
   4729 
   4730 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   4731 /*
   4732 ** Routine to transform a unixFile into a proxy-locking unixFile.
   4733 ** Implementation in the proxy-lock division, but used by unixOpen()
   4734 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
   4735 */
   4736 static int proxyTransformUnixFile(unixFile*, const char*);
   4737 #endif
   4738 
   4739 /*
   4740 ** Search for an unused file descriptor that was opened on the database
   4741 ** file (not a journal or master-journal file) identified by pathname
   4742 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
   4743 ** argument to this function.
   4744 **
   4745 ** Such a file descriptor may exist if a database connection was closed
   4746 ** but the associated file descriptor could not be closed because some
   4747 ** other file descriptor open on the same file is holding a file-lock.
   4748 ** Refer to comments in the unixClose() function and the lengthy comment
   4749 ** describing "Posix Advisory Locking" at the start of this file for
   4750 ** further details. Also, ticket #4018.
   4751 **
   4752 ** If a suitable file descriptor is found, then it is returned. If no
   4753 ** such file descriptor is located, -1 is returned.
   4754 */
   4755 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
   4756   UnixUnusedFd *pUnused = 0;
   4757 
   4758   /* Do not search for an unused file descriptor on vxworks. Not because
   4759   ** vxworks would not benefit from the change (it might, we're not sure),
   4760   ** but because no way to test it is currently available. It is better
   4761   ** not to risk breaking vxworks support for the sake of such an obscure
   4762   ** feature.  */
   4763 #if !OS_VXWORKS
   4764   struct stat sStat;                   /* Results of stat() call */
   4765 
   4766   /* A stat() call may fail for various reasons. If this happens, it is
   4767   ** almost certain that an open() call on the same path will also fail.
   4768   ** For this reason, if an error occurs in the stat() call here, it is
   4769   ** ignored and -1 is returned. The caller will try to open a new file
   4770   ** descriptor on the same path, fail, and return an error to SQLite.
   4771   **
   4772   ** Even if a subsequent open() call does succeed, the consequences of
   4773   ** not searching for a resusable file descriptor are not dire.  */
   4774   if( 0==osStat(zPath, &sStat) ){
   4775     unixInodeInfo *pInode;
   4776 
   4777     unixEnterMutex();
   4778     pInode = inodeList;
   4779     while( pInode && (pInode->fileId.dev!=sStat.st_dev
   4780                      || pInode->fileId.ino!=sStat.st_ino) ){
   4781        pInode = pInode->pNext;
   4782     }
   4783     if( pInode ){
   4784       UnixUnusedFd **pp;
   4785       for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
   4786       pUnused = *pp;
   4787       if( pUnused ){
   4788         *pp = pUnused->pNext;
   4789       }
   4790     }
   4791     unixLeaveMutex();
   4792   }
   4793 #endif    /* if !OS_VXWORKS */
   4794   return pUnused;
   4795 }
   4796 
   4797 /*
   4798 ** This function is called by unixOpen() to determine the unix permissions
   4799 ** to create new files with. If no error occurs, then SQLITE_OK is returned
   4800 ** and a value suitable for passing as the third argument to open(2) is
   4801 ** written to *pMode. If an IO error occurs, an SQLite error code is
   4802 ** returned and the value of *pMode is not modified.
   4803 **
   4804 ** If the file being opened is a temporary file, it is always created with
   4805 ** the octal permissions 0600 (read/writable by owner only). If the file
   4806 ** is a database or master journal file, it is created with the permissions
   4807 ** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
   4808 **
   4809 ** Finally, if the file being opened is a WAL or regular journal file, then
   4810 ** this function queries the file-system for the permissions on the
   4811 ** corresponding database file and sets *pMode to this value. Whenever
   4812 ** possible, WAL and journal files are created using the same permissions
   4813 ** as the associated database file.
   4814 */
   4815 static int findCreateFileMode(
   4816   const char *zPath,              /* Path of file (possibly) being created */
   4817   int flags,                      /* Flags passed as 4th argument to xOpen() */
   4818   mode_t *pMode                   /* OUT: Permissions to open file with */
   4819 ){
   4820   int rc = SQLITE_OK;             /* Return Code */
   4821   if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
   4822     char zDb[MAX_PATHNAME+1];     /* Database file path */
   4823     int nDb;                      /* Number of valid bytes in zDb */
   4824     struct stat sStat;            /* Output of stat() on database file */
   4825 
   4826     /* zPath is a path to a WAL or journal file. The following block derives
   4827     ** the path to the associated database file from zPath. This block handles
   4828     ** the following naming conventions:
   4829     **
   4830     **   "<path to db>-journal"
   4831     **   "<path to db>-wal"
   4832     **   "<path to db>-journal-NNNN"
   4833     **   "<path to db>-wal-NNNN"
   4834     **
   4835     ** where NNNN is a 4 digit decimal number. The NNNN naming schemes are
   4836     ** used by the test_multiplex.c module.
   4837     */
   4838     nDb = sqlite3Strlen30(zPath) - 1;
   4839     while( nDb>0 && zPath[nDb]!='l' ) nDb--;
   4840     nDb -= ((flags & SQLITE_OPEN_WAL) ? 3 : 7);
   4841     memcpy(zDb, zPath, nDb);
   4842     zDb[nDb] = '\0';
   4843 
   4844     if( 0==osStat(zDb, &sStat) ){
   4845       *pMode = sStat.st_mode & 0777;
   4846     }else{
   4847       rc = SQLITE_IOERR_FSTAT;
   4848     }
   4849   }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
   4850     *pMode = 0600;
   4851   }else{
   4852     *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
   4853   }
   4854   return rc;
   4855 }
   4856 
   4857 /*
   4858 ** Initializes a unixFile structure with zeros.
   4859 */
   4860 void chromium_sqlite3_initialize_unix_sqlite3_file(sqlite3_file* file) {
   4861   memset(file, 0, sizeof(unixFile));
   4862 }
   4863 
   4864 int chromium_sqlite3_fill_in_unix_sqlite3_file(sqlite3_vfs* vfs,
   4865                                                int fd,
   4866                                                int dirfd,
   4867                                                sqlite3_file* file,
   4868                                                const char* fileName,
   4869                                                int noLock,
   4870                                                int isDelete) {
   4871   return fillInUnixFile(vfs, fd, dirfd, file, fileName, noLock, isDelete, 0);
   4872 }
   4873 
   4874 /*
   4875 ** Search for an unused file descriptor that was opened on the database file.
   4876 ** If a suitable file descriptor if found, then it is stored in *fd; otherwise,
   4877 ** *fd is not modified.
   4878 **
   4879 ** If a reusable file descriptor is not found, and a new UnixUnusedFd cannot
   4880 ** be allocated, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK is returned.
   4881 */
   4882 int chromium_sqlite3_get_reusable_file_handle(sqlite3_file* file,
   4883                                               const char* fileName,
   4884                                               int flags,
   4885                                               int* fd) {
   4886   unixFile* unixSQLite3File = (unixFile*)file;
   4887   int fileType = flags & 0xFFFFFF00;
   4888   if (fileType == SQLITE_OPEN_MAIN_DB) {
   4889     UnixUnusedFd *unusedFd = findReusableFd(fileName, flags);
   4890     if (unusedFd) {
   4891       *fd = unusedFd->fd;
   4892     } else {
   4893       unusedFd = sqlite3_malloc(sizeof(*unusedFd));
   4894       if (!unusedFd) {
   4895         return SQLITE_NOMEM;
   4896       }
   4897     }
   4898     unixSQLite3File->pUnused = unusedFd;
   4899   }
   4900   return SQLITE_OK;
   4901 }
   4902 
   4903 /*
   4904 ** Marks 'fd' as the unused file descriptor for 'pFile'.
   4905 */
   4906 void chromium_sqlite3_update_reusable_file_handle(sqlite3_file* file,
   4907                                                   int fd,
   4908                                                   int flags) {
   4909   unixFile* unixSQLite3File = (unixFile*)file;
   4910   if (unixSQLite3File->pUnused) {
   4911     unixSQLite3File->pUnused->fd = fd;
   4912     unixSQLite3File->pUnused->flags = flags;
   4913   }
   4914 }
   4915 
   4916 /*
   4917 ** Destroys pFile's field that keeps track of the unused file descriptor.
   4918 */
   4919 void chromium_sqlite3_destroy_reusable_file_handle(sqlite3_file* file) {
   4920   unixFile* unixSQLite3File = (unixFile*)file;
   4921   sqlite3_free(unixSQLite3File->pUnused);
   4922 }
   4923 
   4924 /*
   4925 ** Open the file zPath.
   4926 **
   4927 ** Previously, the SQLite OS layer used three functions in place of this
   4928 ** one:
   4929 **
   4930 **     sqlite3OsOpenReadWrite();
   4931 **     sqlite3OsOpenReadOnly();
   4932 **     sqlite3OsOpenExclusive();
   4933 **
   4934 ** These calls correspond to the following combinations of flags:
   4935 **
   4936 **     ReadWrite() ->     (READWRITE | CREATE)
   4937 **     ReadOnly()  ->     (READONLY)
   4938 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
   4939 **
   4940 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
   4941 ** true, the file was configured to be automatically deleted when the
   4942 ** file handle closed. To achieve the same effect using this new
   4943 ** interface, add the DELETEONCLOSE flag to those specified above for
   4944 ** OpenExclusive().
   4945 */
   4946 static int unixOpen(
   4947   sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
   4948   const char *zPath,           /* Pathname of file to be opened */
   4949   sqlite3_file *pFile,         /* The file descriptor to be filled in */
   4950   int flags,                   /* Input flags to control the opening */
   4951   int *pOutFlags               /* Output flags returned to SQLite core */
   4952 ){
   4953   unixFile *p = (unixFile *)pFile;
   4954   int fd = -1;                   /* File descriptor returned by open() */
   4955   int openFlags = 0;             /* Flags to pass to open() */
   4956   int eType = flags&0xFFFFFF00;  /* Type of file to open */
   4957   int noLock;                    /* True to omit locking primitives */
   4958   int rc = SQLITE_OK;            /* Function Return Code */
   4959 
   4960   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
   4961   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
   4962   int isCreate     = (flags & SQLITE_OPEN_CREATE);
   4963   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
   4964   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
   4965 #if SQLITE_ENABLE_LOCKING_STYLE
   4966   int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
   4967 #endif
   4968 
   4969   /* If creating a master or main-file journal, this function will open
   4970   ** a file-descriptor on the directory too. The first time unixSync()
   4971   ** is called the directory file descriptor will be fsync()ed and close()d.
   4972   */
   4973   int syncDir = (isCreate && (
   4974         eType==SQLITE_OPEN_MASTER_JOURNAL
   4975      || eType==SQLITE_OPEN_MAIN_JOURNAL
   4976      || eType==SQLITE_OPEN_WAL
   4977   ));
   4978 
   4979   /* If argument zPath is a NULL pointer, this function is required to open
   4980   ** a temporary file. Use this buffer to store the file name in.
   4981   */
   4982   char zTmpname[MAX_PATHNAME+1];
   4983   const char *zName = zPath;
   4984 
   4985   /* Check the following statements are true:
   4986   **
   4987   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
   4988   **   (b) if CREATE is set, then READWRITE must also be set, and
   4989   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
   4990   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
   4991   */
   4992   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
   4993   assert(isCreate==0 || isReadWrite);
   4994   assert(isExclusive==0 || isCreate);
   4995   assert(isDelete==0 || isCreate);
   4996 
   4997   /* The main DB, main journal, WAL file and master journal are never
   4998   ** automatically deleted. Nor are they ever temporary files.  */
   4999   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
   5000   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
   5001   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
   5002   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
   5003 
   5004   /* Assert that the upper layer has set one of the "file-type" flags. */
   5005   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
   5006        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
   5007        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
   5008        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
   5009   );
   5010 
   5011   chromium_sqlite3_initialize_unix_sqlite3_file(pFile);
   5012 
   5013   if( eType==SQLITE_OPEN_MAIN_DB ){
   5014     rc = chromium_sqlite3_get_reusable_file_handle(pFile, zName, flags, &fd);
   5015     if( rc!=SQLITE_OK ){
   5016       return rc;
   5017     }
   5018   }else if( !zName ){
   5019     /* If zName is NULL, the upper layer is requesting a temp file. */
   5020     assert(isDelete && !syncDir);
   5021     rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
   5022     if( rc!=SQLITE_OK ){
   5023       return rc;
   5024     }
   5025     zName = zTmpname;
   5026   }
   5027 
   5028   /* Determine the value of the flags parameter passed to POSIX function
   5029   ** open(). These must be calculated even if open() is not called, as
   5030   ** they may be stored as part of the file handle and used by the
   5031   ** 'conch file' locking functions later on.  */
   5032   if( isReadonly )  openFlags |= O_RDONLY;
   5033   if( isReadWrite ) openFlags |= O_RDWR;
   5034   if( isCreate )    openFlags |= O_CREAT;
   5035   if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
   5036   openFlags |= (O_LARGEFILE|O_BINARY);
   5037 
   5038   if( fd<0 ){
   5039     mode_t openMode;              /* Permissions to create file with */
   5040     rc = findCreateFileMode(zName, flags, &openMode);
   5041     if( rc!=SQLITE_OK ){
   5042       assert( !p->pUnused );
   5043       assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
   5044       return rc;
   5045     }
   5046     fd = robust_open(zName, openFlags, openMode);
   5047     OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
   5048     if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
   5049       /* Failed to open the file for read/write access. Try read-only. */
   5050       flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
   5051       openFlags &= ~(O_RDWR|O_CREAT);
   5052       flags |= SQLITE_OPEN_READONLY;
   5053       openFlags |= O_RDONLY;
   5054       isReadonly = 1;
   5055       fd = robust_open(zName, openFlags, openMode);
   5056     }
   5057     if( fd<0 ){
   5058       rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
   5059       goto open_finished;
   5060     }
   5061   }
   5062   assert( fd>=0 );
   5063   if( pOutFlags ){
   5064     *pOutFlags = flags;
   5065   }
   5066 
   5067   chromium_sqlite3_update_reusable_file_handle(pFile, fd, flags);
   5068 
   5069   if( isDelete ){
   5070 #if OS_VXWORKS
   5071     zPath = zName;
   5072 #else
   5073     osUnlink(zName);
   5074 #endif
   5075   }
   5076 #if SQLITE_ENABLE_LOCKING_STYLE
   5077   else{
   5078     p->openFlags = openFlags;
   5079   }
   5080 #endif
   5081 
   5082 #ifdef FD_CLOEXEC
   5083   osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
   5084 #endif
   5085 
   5086   noLock = eType!=SQLITE_OPEN_MAIN_DB;
   5087 
   5088 
   5089 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
   5090   struct statfs fsInfo;
   5091   if( fstatfs(fd, &fsInfo) == -1 ){
   5092     ((unixFile*)pFile)->lastErrno = errno;
   5093     robust_close(p, fd, __LINE__);
   5094     return SQLITE_IOERR_ACCESS;
   5095   }
   5096   if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
   5097     ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
   5098   }
   5099 #endif
   5100 
   5101 #if SQLITE_ENABLE_LOCKING_STYLE
   5102 #if SQLITE_PREFER_PROXY_LOCKING
   5103   isAutoProxy = 1;
   5104 #endif
   5105   if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
   5106     char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
   5107     int useProxy = 0;
   5108 
   5109     /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
   5110     ** never use proxy, NULL means use proxy for non-local files only.  */
   5111     if( envforce!=NULL ){
   5112       useProxy = atoi(envforce)>0;
   5113     }else{
   5114       struct statfs fsInfo;
   5115       if( statfs(zPath, &fsInfo) == -1 ){
   5116         /* In theory, the close(fd) call is sub-optimal. If the file opened
   5117         ** with fd is a database file, and there are other connections open
   5118         ** on that file that are currently holding advisory locks on it,
   5119         ** then the call to close() will cancel those locks. In practice,
   5120         ** we're assuming that statfs() doesn't fail very often. At least
   5121         ** not while other file descriptors opened by the same process on
   5122         ** the same file are working.  */
   5123         p->lastErrno = errno;
   5124         robust_close(p, fd, __LINE__);
   5125         rc = SQLITE_IOERR_ACCESS;
   5126         goto open_finished;
   5127       }
   5128       useProxy = !(fsInfo.f_flags&MNT_LOCAL);
   5129     }
   5130     if( useProxy ){
   5131       rc = fillInUnixFile(pVfs, fd, syncDir, pFile, zPath, noLock,
   5132                           isDelete, isReadonly);
   5133       if( rc==SQLITE_OK ){
   5134         rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
   5135         if( rc!=SQLITE_OK ){
   5136           /* Use unixClose to clean up the resources added in fillInUnixFile
   5137           ** and clear all the structure's references.  Specifically,
   5138           ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
   5139           */
   5140           unixClose(pFile);
   5141           return rc;
   5142         }
   5143       }
   5144       goto open_finished;
   5145     }
   5146   }
   5147 #endif
   5148 
   5149   rc = fillInUnixFile(pVfs, fd, syncDir, pFile, zPath, noLock,
   5150                       isDelete, isReadonly);
   5151 open_finished:
   5152   if( rc!=SQLITE_OK ){
   5153     chromium_sqlite3_destroy_reusable_file_handle(pFile);
   5154   }
   5155   return rc;
   5156 }
   5157 
   5158 
   5159 /*
   5160 ** Delete the file at zPath. If the dirSync argument is true, fsync()
   5161 ** the directory after deleting the file.
   5162 */
   5163 static int unixDelete(
   5164   sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
   5165   const char *zPath,        /* Name of file to be deleted */
   5166   int dirSync               /* If true, fsync() directory after deleting file */
   5167 ){
   5168   int rc = SQLITE_OK;
   5169   UNUSED_PARAMETER(NotUsed);
   5170   SimulateIOError(return SQLITE_IOERR_DELETE);
   5171   if( osUnlink(zPath)==(-1) && errno!=ENOENT ){
   5172     return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
   5173   }
   5174 #ifndef SQLITE_DISABLE_DIRSYNC
   5175   if( dirSync ){
   5176     int fd;
   5177     rc = osOpenDirectory(zPath, &fd);
   5178     if( rc==SQLITE_OK ){
   5179 #if OS_VXWORKS
   5180       if( fsync(fd)==-1 )
   5181 #else
   5182       if( fsync(fd) )
   5183 #endif
   5184       {
   5185         rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
   5186       }
   5187       robust_close(0, fd, __LINE__);
   5188     }else if( rc==SQLITE_CANTOPEN ){
   5189       rc = SQLITE_OK;
   5190     }
   5191   }
   5192 #endif
   5193   return rc;
   5194 }
   5195 
   5196 /*
   5197 ** Test the existance of or access permissions of file zPath. The
   5198 ** test performed depends on the value of flags:
   5199 **
   5200 **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
   5201 **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
   5202 **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
   5203 **
   5204 ** Otherwise return 0.
   5205 */
   5206 static int unixAccess(
   5207   sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
   5208   const char *zPath,      /* Path of the file to examine */
   5209   int flags,              /* What do we want to learn about the zPath file? */
   5210   int *pResOut            /* Write result boolean here */
   5211 ){
   5212   int amode = 0;
   5213   UNUSED_PARAMETER(NotUsed);
   5214   SimulateIOError( return SQLITE_IOERR_ACCESS; );
   5215   switch( flags ){
   5216     case SQLITE_ACCESS_EXISTS:
   5217       amode = F_OK;
   5218       break;
   5219     case SQLITE_ACCESS_READWRITE:
   5220       amode = W_OK|R_OK;
   5221       break;
   5222     case SQLITE_ACCESS_READ:
   5223       amode = R_OK;
   5224       break;
   5225 
   5226     default:
   5227       assert(!"Invalid flags argument");
   5228   }
   5229   *pResOut = (osAccess(zPath, amode)==0);
   5230   if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
   5231     struct stat buf;
   5232     if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
   5233       *pResOut = 0;
   5234     }
   5235   }
   5236   return SQLITE_OK;
   5237 }
   5238 
   5239 
   5240 /*
   5241 ** Turn a relative pathname into a full pathname. The relative path
   5242 ** is stored as a nul-terminated string in the buffer pointed to by
   5243 ** zPath.
   5244 **
   5245 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
   5246 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
   5247 ** this buffer before returning.
   5248 */
   5249 static int unixFullPathname(
   5250   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
   5251   const char *zPath,            /* Possibly relative input path */
   5252   int nOut,                     /* Size of output buffer in bytes */
   5253   char *zOut                    /* Output buffer */
   5254 ){
   5255 
   5256   /* It's odd to simulate an io-error here, but really this is just
   5257   ** using the io-error infrastructure to test that SQLite handles this
   5258   ** function failing. This function could fail if, for example, the
   5259   ** current working directory has been unlinked.
   5260   */
   5261   SimulateIOError( return SQLITE_ERROR );
   5262 
   5263   assert( pVfs->mxPathname==MAX_PATHNAME );
   5264   UNUSED_PARAMETER(pVfs);
   5265 
   5266   zOut[nOut-1] = '\0';
   5267   if( zPath[0]=='/' ){
   5268     sqlite3_snprintf(nOut, zOut, "%s", zPath);
   5269   }else{
   5270     int nCwd;
   5271     if( osGetcwd(zOut, nOut-1)==0 ){
   5272       return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
   5273     }
   5274     nCwd = (int)strlen(zOut);
   5275     sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
   5276   }
   5277   return SQLITE_OK;
   5278 }
   5279 
   5280 
   5281 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   5282 /*
   5283 ** Interfaces for opening a shared library, finding entry points
   5284 ** within the shared library, and closing the shared library.
   5285 */
   5286 #include <dlfcn.h>
   5287 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
   5288   UNUSED_PARAMETER(NotUsed);
   5289   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
   5290 }
   5291 
   5292 /*
   5293 ** SQLite calls this function immediately after a call to unixDlSym() or
   5294 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
   5295 ** message is available, it is written to zBufOut. If no error message
   5296 ** is available, zBufOut is left unmodified and SQLite uses a default
   5297 ** error message.
   5298 */
   5299 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
   5300   const char *zErr;
   5301   UNUSED_PARAMETER(NotUsed);
   5302   unixEnterMutex();
   5303   zErr = dlerror();
   5304   if( zErr ){
   5305     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
   5306   }
   5307   unixLeaveMutex();
   5308 }
   5309 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
   5310   /*
   5311   ** GCC with -pedantic-errors says that C90 does not allow a void* to be
   5312   ** cast into a pointer to a function.  And yet the library dlsym() routine
   5313   ** returns a void* which is really a pointer to a function.  So how do we
   5314   ** use dlsym() with -pedantic-errors?
   5315   **
   5316   ** Variable x below is defined to be a pointer to a function taking
   5317   ** parameters void* and const char* and returning a pointer to a function.
   5318   ** We initialize x by assigning it a pointer to the dlsym() function.
   5319   ** (That assignment requires a cast.)  Then we call the function that
   5320   ** x points to.
   5321   **
   5322   ** This work-around is unlikely to work correctly on any system where
   5323   ** you really cannot cast a function pointer into void*.  But then, on the
   5324   ** other hand, dlsym() will not work on such a system either, so we have
   5325   ** not really lost anything.
   5326   */
   5327   void (*(*x)(void*,const char*))(void);
   5328   UNUSED_PARAMETER(NotUsed);
   5329   x = (void(*(*)(void*,const char*))(void))dlsym;
   5330   return (*x)(p, zSym);
   5331 }
   5332 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
   5333   UNUSED_PARAMETER(NotUsed);
   5334   dlclose(pHandle);
   5335 }
   5336 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
   5337   #define unixDlOpen  0
   5338   #define unixDlError 0
   5339   #define unixDlSym   0
   5340   #define unixDlClose 0
   5341 #endif
   5342 
   5343 /*
   5344 ** Write nBuf bytes of random data to the supplied buffer zBuf.
   5345 */
   5346 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
   5347   UNUSED_PARAMETER(NotUsed);
   5348   assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
   5349 
   5350   /* We have to initialize zBuf to prevent valgrind from reporting
   5351   ** errors.  The reports issued by valgrind are incorrect - we would
   5352   ** prefer that the randomness be increased by making use of the
   5353   ** uninitialized space in zBuf - but valgrind errors tend to worry
   5354   ** some users.  Rather than argue, it seems easier just to initialize
   5355   ** the whole array and silence valgrind, even if that means less randomness
   5356   ** in the random seed.
   5357   **
   5358   ** When testing, initializing zBuf[] to zero is all we do.  That means
   5359   ** that we always use the same random number sequence.  This makes the
   5360   ** tests repeatable.
   5361   */
   5362   memset(zBuf, 0, nBuf);
   5363 #if !defined(SQLITE_TEST)
   5364   {
   5365     int pid, fd;
   5366     fd = robust_open("/dev/urandom", O_RDONLY, 0);
   5367     if( fd<0 ){
   5368       time_t t;
   5369       time(&t);
   5370       memcpy(zBuf, &t, sizeof(t));
   5371       pid = getpid();
   5372       memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
   5373       assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
   5374       nBuf = sizeof(t) + sizeof(pid);
   5375     }else{
   5376       do{ nBuf = osRead(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
   5377       robust_close(0, fd, __LINE__);
   5378     }
   5379   }
   5380 #endif
   5381   return nBuf;
   5382 }
   5383 
   5384 
   5385 /*
   5386 ** Sleep for a little while.  Return the amount of time slept.
   5387 ** The argument is the number of microseconds we want to sleep.
   5388 ** The return value is the number of microseconds of sleep actually
   5389 ** requested from the underlying operating system, a number which
   5390 ** might be greater than or equal to the argument, but not less
   5391 ** than the argument.
   5392 */
   5393 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
   5394 #if OS_VXWORKS
   5395   struct timespec sp;
   5396 
   5397   sp.tv_sec = microseconds / 1000000;
   5398   sp.tv_nsec = (microseconds % 1000000) * 1000;
   5399   nanosleep(&sp, NULL);
   5400   UNUSED_PARAMETER(NotUsed);
   5401   return microseconds;
   5402 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
   5403   usleep(microseconds);
   5404   UNUSED_PARAMETER(NotUsed);
   5405   return microseconds;
   5406 #else
   5407   int seconds = (microseconds+999999)/1000000;
   5408   sleep(seconds);
   5409   UNUSED_PARAMETER(NotUsed);
   5410   return seconds*1000000;
   5411 #endif
   5412 }
   5413 
   5414 /*
   5415 ** The following variable, if set to a non-zero value, is interpreted as
   5416 ** the number of seconds since 1970 and is used to set the result of
   5417 ** sqlite3OsCurrentTime() during testing.
   5418 */
   5419 #ifdef SQLITE_TEST
   5420 int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
   5421 #endif
   5422 
   5423 /*
   5424 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
   5425 ** the current time and date as a Julian Day number times 86_400_000.  In
   5426 ** other words, write into *piNow the number of milliseconds since the Julian
   5427 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
   5428 ** proleptic Gregorian calendar.
   5429 **
   5430 ** On success, return 0.  Return 1 if the time and date cannot be found.
   5431 */
   5432 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
   5433   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
   5434 #if defined(NO_GETTOD)
   5435   time_t t;
   5436   time(&t);
   5437   *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
   5438 #elif OS_VXWORKS
   5439   struct timespec sNow;
   5440   clock_gettime(CLOCK_REALTIME, &sNow);
   5441   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
   5442 #else
   5443   struct timeval sNow;
   5444   gettimeofday(&sNow, 0);
   5445   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
   5446 #endif
   5447 
   5448 #ifdef SQLITE_TEST
   5449   if( sqlite3_current_time ){
   5450     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
   5451   }
   5452 #endif
   5453   UNUSED_PARAMETER(NotUsed);
   5454   return 0;
   5455 }
   5456 
   5457 /*
   5458 ** Find the current time (in Universal Coordinated Time).  Write the
   5459 ** current time and date as a Julian Day number into *prNow and
   5460 ** return 0.  Return 1 if the time and date cannot be found.
   5461 */
   5462 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
   5463   sqlite3_int64 i;
   5464   UNUSED_PARAMETER(NotUsed);
   5465   unixCurrentTimeInt64(0, &i);
   5466   *prNow = i/86400000.0;
   5467   return 0;
   5468 }
   5469 
   5470 /*
   5471 ** We added the xGetLastError() method with the intention of providing
   5472 ** better low-level error messages when operating-system problems come up
   5473 ** during SQLite operation.  But so far, none of that has been implemented
   5474 ** in the core.  So this routine is never called.  For now, it is merely
   5475 ** a place-holder.
   5476 */
   5477 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
   5478   UNUSED_PARAMETER(NotUsed);
   5479   UNUSED_PARAMETER(NotUsed2);
   5480   UNUSED_PARAMETER(NotUsed3);
   5481   return 0;
   5482 }
   5483 
   5484 
   5485 /*
   5486 ************************ End of sqlite3_vfs methods ***************************
   5487 ******************************************************************************/
   5488 
   5489 /******************************************************************************
   5490 ************************** Begin Proxy Locking ********************************
   5491 **
   5492 ** Proxy locking is a "uber-locking-method" in this sense:  It uses the
   5493 ** other locking methods on secondary lock files.  Proxy locking is a
   5494 ** meta-layer over top of the primitive locking implemented above.  For
   5495 ** this reason, the division that implements of proxy locking is deferred
   5496 ** until late in the file (here) after all of the other I/O methods have
   5497 ** been defined - so that the primitive locking methods are available
   5498 ** as services to help with the implementation of proxy locking.
   5499 **
   5500 ****
   5501 **
   5502 ** The default locking schemes in SQLite use byte-range locks on the
   5503 ** database file to coordinate safe, concurrent access by multiple readers
   5504 ** and writers [http://sqlite.org/lockingv3.html].  The five file locking
   5505 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
   5506 ** as POSIX read & write locks over fixed set of locations (via fsctl),
   5507 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
   5508 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
   5509 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
   5510 ** address in the shared range is taken for a SHARED lock, the entire
   5511 ** shared range is taken for an EXCLUSIVE lock):
   5512 **
   5513 **      PENDING_BYTE        0x40000000
   5514 **      RESERVED_BYTE       0x40000001
   5515 **      SHARED_RANGE        0x40000002 -> 0x40000200
   5516 **
   5517 ** This works well on the local file system, but shows a nearly 100x
   5518 ** slowdown in read performance on AFP because the AFP client disables
   5519 ** the read cache when byte-range locks are present.  Enabling the read
   5520 ** cache exposes a cache coherency problem that is present on all OS X
   5521 ** supported network file systems.  NFS and AFP both observe the
   5522 ** close-to-open semantics for ensuring cache coherency
   5523 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
   5524 ** address the requirements for concurrent database access by multiple
   5525 ** readers and writers
   5526 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
   5527 **
   5528 ** To address the performance and cache coherency issues, proxy file locking
   5529 ** changes the way database access is controlled by limiting access to a
   5530 ** single host at a time and moving file locks off of the database file
   5531 ** and onto a proxy file on the local file system.
   5532 **
   5533 **
   5534 ** Using proxy locks
   5535 ** -----------------
   5536 **
   5537 ** C APIs
   5538 **
   5539 **  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
   5540 **                       <proxy_path> | ":auto:");
   5541 **  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
   5542 **
   5543 **
   5544 ** SQL pragmas
   5545 **
   5546 **  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
   5547 **  PRAGMA [database.]lock_proxy_file
   5548 **
   5549 ** Specifying ":auto:" means that if there is a conch file with a matching
   5550 ** host ID in it, the proxy path in the conch file will be used, otherwise
   5551 ** a proxy path based on the user's temp dir
   5552 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
   5553 ** actual proxy file name is generated from the name and path of the
   5554 ** database file.  For example:
   5555 **
   5556 **       For database path "/Users/me/foo.db"
   5557 **       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
   5558 **
   5559 ** Once a lock proxy is configured for a database connection, it can not
   5560 ** be removed, however it may be switched to a different proxy path via
   5561 ** the above APIs (assuming the conch file is not being held by another
   5562 ** connection or process).
   5563 **
   5564 **
   5565 ** How proxy locking works
   5566 ** -----------------------
   5567 **
   5568 ** Proxy file locking relies primarily on two new supporting files:
   5569 **
   5570 **   *  conch file to limit access to the database file to a single host
   5571 **      at a time
   5572 **
   5573 **   *  proxy file to act as a proxy for the advisory locks normally
   5574 **      taken on the database
   5575 **
   5576 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
   5577 ** by taking an sqlite-style shared lock on the conch file, reading the
   5578 ** contents and comparing the host's unique host ID (see below) and lock
   5579 ** proxy path against the values stored in the conch.  The conch file is
   5580 ** stored in the same directory as the database file and the file name
   5581 ** is patterned after the database file name as ".<databasename>-conch".
   5582 ** If the conch file does not exist, or it's contents do not match the
   5583 ** host ID and/or proxy path, then the lock is escalated to an exclusive
   5584 ** lock and the conch file contents is updated with the host ID and proxy
   5585 ** path and the lock is downgraded to a shared lock again.  If the conch
   5586 ** is held by another process (with a shared lock), the exclusive lock
   5587 ** will fail and SQLITE_BUSY is returned.
   5588 **
   5589 ** The proxy file - a single-byte file used for all advisory file locks
   5590 ** normally taken on the database file.   This allows for safe sharing
   5591 ** of the database file for multiple readers and writers on the same
   5592 ** host (the conch ensures that they all use the same local lock file).
   5593 **
   5594 ** Requesting the lock proxy does not immediately take the conch, it is
   5595 ** only taken when the first request to lock database file is made.
   5596 ** This matches the semantics of the traditional locking behavior, where
   5597 ** opening a connection to a database file does not take a lock on it.
   5598 ** The shared lock and an open file descriptor are maintained until
   5599 ** the connection to the database is closed.
   5600 **
   5601 ** The proxy file and the lock file are never deleted so they only need
   5602 ** to be created the first time they are used.
   5603 **
   5604 ** Configuration options
   5605 ** ---------------------
   5606 **
   5607 **  SQLITE_PREFER_PROXY_LOCKING
   5608 **
   5609 **       Database files accessed on non-local file systems are
   5610 **       automatically configured for proxy locking, lock files are
   5611 **       named automatically using the same logic as
   5612 **       PRAGMA lock_proxy_file=":auto:"
   5613 **
   5614 **  SQLITE_PROXY_DEBUG
   5615 **
   5616 **       Enables the logging of error messages during host id file
   5617 **       retrieval and creation
   5618 **
   5619 **  LOCKPROXYDIR
   5620 **
   5621 **       Overrides the default directory used for lock proxy files that
   5622 **       are named automatically via the ":auto:" setting
   5623 **
   5624 **  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
   5625 **
   5626 **       Permissions to use when creating a directory for storing the
   5627 **       lock proxy files, only used when LOCKPROXYDIR is not set.
   5628 **
   5629 **
   5630 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
   5631 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
   5632 ** force proxy locking to be used for every database file opened, and 0
   5633 ** will force automatic proxy locking to be disabled for all database
   5634 ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
   5635 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
   5636 */
   5637 
   5638 /*
   5639 ** Proxy locking is only available on MacOSX
   5640 */
   5641 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   5642 
   5643 /*
   5644 ** The proxyLockingContext has the path and file structures for the remote
   5645 ** and local proxy files in it
   5646 */
   5647 typedef struct proxyLockingContext proxyLockingContext;
   5648 struct proxyLockingContext {
   5649   unixFile *conchFile;         /* Open conch file */
   5650   char *conchFilePath;         /* Name of the conch file */
   5651   unixFile *lockProxy;         /* Open proxy lock file */
   5652   char *lockProxyPath;         /* Name of the proxy lock file */
   5653   char *dbPath;                /* Name of the open file */
   5654   int conchHeld;               /* 1 if the conch is held, -1 if lockless */
   5655   void *oldLockingContext;     /* Original lockingcontext to restore on close */
   5656   sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
   5657 };
   5658 
   5659 /*
   5660 ** The proxy lock file path for the database at dbPath is written into lPath,
   5661 ** which must point to valid, writable memory large enough for a maxLen length
   5662 ** file path.
   5663 */
   5664 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
   5665   int len;
   5666   int dbLen;
   5667   int i;
   5668 
   5669 #ifdef LOCKPROXYDIR
   5670   len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
   5671 #else
   5672 # ifdef _CS_DARWIN_USER_TEMP_DIR
   5673   {
   5674     if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
   5675       OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
   5676                lPath, errno, getpid()));
   5677       return SQLITE_IOERR_LOCK;
   5678     }
   5679     len = strlcat(lPath, "sqliteplocks", maxLen);
   5680   }
   5681 # else
   5682   len = strlcpy(lPath, "/tmp/", maxLen);
   5683 # endif
   5684 #endif
   5685 
   5686   if( lPath[len-1]!='/' ){
   5687     len = strlcat(lPath, "/", maxLen);
   5688   }
   5689 
   5690   /* transform the db path to a unique cache name */
   5691   dbLen = (int)strlen(dbPath);
   5692   for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
   5693     char c = dbPath[i];
   5694     lPath[i+len] = (c=='/')?'_':c;
   5695   }
   5696   lPath[i+len]='\0';
   5697   strlcat(lPath, ":auto:", maxLen);
   5698   OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, getpid()));
   5699   return SQLITE_OK;
   5700 }
   5701 
   5702 /*
   5703  ** Creates the lock file and any missing directories in lockPath
   5704  */
   5705 static int proxyCreateLockPath(const char *lockPath){
   5706   int i, len;
   5707   char buf[MAXPATHLEN];
   5708   int start = 0;
   5709 
   5710   assert(lockPath!=NULL);
   5711   /* try to create all the intermediate directories */
   5712   len = (int)strlen(lockPath);
   5713   buf[0] = lockPath[0];
   5714   for( i=1; i<len; i++ ){
   5715     if( lockPath[i] == '/' && (i - start > 0) ){
   5716       /* only mkdir if leaf dir != "." or "/" or ".." */
   5717       if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
   5718          || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
   5719         buf[i]='\0';
   5720         if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
   5721           int err=errno;
   5722           if( err!=EEXIST ) {
   5723             OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
   5724                      "'%s' proxy lock path=%s pid=%d\n",
   5725                      buf, strerror(err), lockPath, getpid()));
   5726             return err;
   5727           }
   5728         }
   5729       }
   5730       start=i+1;
   5731     }
   5732     buf[i] = lockPath[i];
   5733   }
   5734   OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, getpid()));
   5735   return 0;
   5736 }
   5737 
   5738 /*
   5739 ** Create a new VFS file descriptor (stored in memory obtained from
   5740 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
   5741 **
   5742 ** The caller is responsible not only for closing the file descriptor
   5743 ** but also for freeing the memory associated with the file descriptor.
   5744 */
   5745 static int proxyCreateUnixFile(
   5746     const char *path,        /* path for the new unixFile */
   5747     unixFile **ppFile,       /* unixFile created and returned by ref */
   5748     int islockfile           /* if non zero missing dirs will be created */
   5749 ) {
   5750   int fd = -1;
   5751   unixFile *pNew;
   5752   int rc = SQLITE_OK;
   5753   int openFlags = O_RDWR | O_CREAT;
   5754   sqlite3_vfs dummyVfs;
   5755   int terrno = 0;
   5756   UnixUnusedFd *pUnused = NULL;
   5757 
   5758   /* 1. first try to open/create the file
   5759   ** 2. if that fails, and this is a lock file (not-conch), try creating
   5760   ** the parent directories and then try again.
   5761   ** 3. if that fails, try to open the file read-only
   5762   ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
   5763   */
   5764   pUnused = findReusableFd(path, openFlags);
   5765   if( pUnused ){
   5766     fd = pUnused->fd;
   5767   }else{
   5768     pUnused = sqlite3_malloc(sizeof(*pUnused));
   5769     if( !pUnused ){
   5770       return SQLITE_NOMEM;
   5771     }
   5772   }
   5773   if( fd<0 ){
   5774     fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
   5775     terrno = errno;
   5776     if( fd<0 && errno==ENOENT && islockfile ){
   5777       if( proxyCreateLockPath(path) == SQLITE_OK ){
   5778         fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
   5779       }
   5780     }
   5781   }
   5782   if( fd<0 ){
   5783     openFlags = O_RDONLY;
   5784     fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
   5785     terrno = errno;
   5786   }
   5787   if( fd<0 ){
   5788     if( islockfile ){
   5789       return SQLITE_BUSY;
   5790     }
   5791     switch (terrno) {
   5792       case EACCES:
   5793         return SQLITE_PERM;
   5794       case EIO:
   5795         return SQLITE_IOERR_LOCK; /* even though it is the conch */
   5796       default:
   5797         return SQLITE_CANTOPEN_BKPT;
   5798     }
   5799   }
   5800 
   5801   pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
   5802   if( pNew==NULL ){
   5803     rc = SQLITE_NOMEM;
   5804     goto end_create_proxy;
   5805   }
   5806   memset(pNew, 0, sizeof(unixFile));
   5807   pNew->openFlags = openFlags;
   5808   memset(&dummyVfs, 0, sizeof(dummyVfs));
   5809   dummyVfs.pAppData = (void*)&autolockIoFinder;
   5810   dummyVfs.zName = "dummy";
   5811   pUnused->fd = fd;
   5812   pUnused->flags = openFlags;
   5813   pNew->pUnused = pUnused;
   5814 
   5815   rc = fillInUnixFile(&dummyVfs, fd, 0, (sqlite3_file*)pNew, path, 0, 0, 0);
   5816   if( rc==SQLITE_OK ){
   5817     *ppFile = pNew;
   5818     return SQLITE_OK;
   5819   }
   5820 end_create_proxy:
   5821   robust_close(pNew, fd, __LINE__);
   5822   sqlite3_free(pNew);
   5823   sqlite3_free(pUnused);
   5824   return rc;
   5825 }
   5826 
   5827 #ifdef SQLITE_TEST
   5828 /* simulate multiple hosts by creating unique hostid file paths */
   5829 int sqlite3_hostid_num = 0;
   5830 #endif
   5831 
   5832 #define PROXY_HOSTIDLEN    16  /* conch file host id length */
   5833 
   5834 /* Not always defined in the headers as it ought to be */
   5835 extern int gethostuuid(uuid_t id, const struct timespec *wait);
   5836 
   5837 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
   5838 ** bytes of writable memory.
   5839 */
   5840 static int proxyGetHostID(unsigned char *pHostID, int *pError){
   5841   assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
   5842   memset(pHostID, 0, PROXY_HOSTIDLEN);
   5843 #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
   5844                && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
   5845   {
   5846     static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
   5847     if( gethostuuid(pHostID, &timeout) ){
   5848       int err = errno;
   5849       if( pError ){
   5850         *pError = err;
   5851       }
   5852       return SQLITE_IOERR;
   5853     }
   5854   }
   5855 #endif
   5856 #ifdef SQLITE_TEST
   5857   /* simulate multiple hosts by creating unique hostid file paths */
   5858   if( sqlite3_hostid_num != 0){
   5859     pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
   5860   }
   5861 #endif
   5862 
   5863   return SQLITE_OK;
   5864 }
   5865 
   5866 /* The conch file contains the header, host id and lock file path
   5867  */
   5868 #define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
   5869 #define PROXY_HEADERLEN    1   /* conch file header length */
   5870 #define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
   5871 #define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
   5872 
   5873 /*
   5874 ** Takes an open conch file, copies the contents to a new path and then moves
   5875 ** it back.  The newly created file's file descriptor is assigned to the
   5876 ** conch file structure and finally the original conch file descriptor is
   5877 ** closed.  Returns zero if successful.
   5878 */
   5879 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
   5880   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   5881   unixFile *conchFile = pCtx->conchFile;
   5882   char tPath[MAXPATHLEN];
   5883   char buf[PROXY_MAXCONCHLEN];
   5884   char *cPath = pCtx->conchFilePath;
   5885   size_t readLen = 0;
   5886   size_t pathLen = 0;
   5887   char errmsg[64] = "";
   5888   int fd = -1;
   5889   int rc = -1;
   5890   UNUSED_PARAMETER(myHostID);
   5891 
   5892   /* create a new path by replace the trailing '-conch' with '-break' */
   5893   pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
   5894   if( pathLen>MAXPATHLEN || pathLen<6 ||
   5895      (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
   5896     sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
   5897     goto end_breaklock;
   5898   }
   5899   /* read the conch content */
   5900   readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
   5901   if( readLen<PROXY_PATHINDEX ){
   5902     sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
   5903     goto end_breaklock;
   5904   }
   5905   /* write it out to the temporary break file */
   5906   fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL),
   5907                    SQLITE_DEFAULT_FILE_PERMISSIONS);
   5908   if( fd<0 ){
   5909     sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
   5910     goto end_breaklock;
   5911   }
   5912   if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
   5913     sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
   5914     goto end_breaklock;
   5915   }
   5916   if( rename(tPath, cPath) ){
   5917     sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
   5918     goto end_breaklock;
   5919   }
   5920   rc = 0;
   5921   fprintf(stderr, "broke stale lock on %s\n", cPath);
   5922   robust_close(pFile, conchFile->h, __LINE__);
   5923   conchFile->h = fd;
   5924   conchFile->openFlags = O_RDWR | O_CREAT;
   5925 
   5926 end_breaklock:
   5927   if( rc ){
   5928     if( fd>=0 ){
   5929       osUnlink(tPath);
   5930       robust_close(pFile, fd, __LINE__);
   5931     }
   5932     fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
   5933   }
   5934   return rc;
   5935 }
   5936 
   5937 /* Take the requested lock on the conch file and break a stale lock if the
   5938 ** host id matches.
   5939 */
   5940 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
   5941   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   5942   unixFile *conchFile = pCtx->conchFile;
   5943   int rc = SQLITE_OK;
   5944   int nTries = 0;
   5945   struct timespec conchModTime;
   5946 
   5947   do {
   5948     rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
   5949     nTries ++;
   5950     if( rc==SQLITE_BUSY ){
   5951       /* If the lock failed (busy):
   5952        * 1st try: get the mod time of the conch, wait 0.5s and try again.
   5953        * 2nd try: fail if the mod time changed or host id is different, wait
   5954        *           10 sec and try again
   5955        * 3rd try: break the lock unless the mod time has changed.
   5956        */
   5957       struct stat buf;
   5958       if( osFstat(conchFile->h, &buf) ){
   5959         pFile->lastErrno = errno;
   5960         return SQLITE_IOERR_LOCK;
   5961       }
   5962 
   5963       if( nTries==1 ){
   5964         conchModTime = buf.st_mtimespec;
   5965         usleep(500000); /* wait 0.5 sec and try the lock again*/
   5966         continue;
   5967       }
   5968 
   5969       assert( nTries>1 );
   5970       if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
   5971          conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
   5972         return SQLITE_BUSY;
   5973       }
   5974 
   5975       if( nTries==2 ){
   5976         char tBuf[PROXY_MAXCONCHLEN];
   5977         int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
   5978         if( len<0 ){
   5979           pFile->lastErrno = errno;
   5980           return SQLITE_IOERR_LOCK;
   5981         }
   5982         if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
   5983           /* don't break the lock if the host id doesn't match */
   5984           if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
   5985             return SQLITE_BUSY;
   5986           }
   5987         }else{
   5988           /* don't break the lock on short read or a version mismatch */
   5989           return SQLITE_BUSY;
   5990         }
   5991         usleep(10000000); /* wait 10 sec and try the lock again */
   5992         continue;
   5993       }
   5994 
   5995       assert( nTries==3 );
   5996       if( 0==proxyBreakConchLock(pFile, myHostID) ){
   5997         rc = SQLITE_OK;
   5998         if( lockType==EXCLUSIVE_LOCK ){
   5999           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
   6000         }
   6001         if( !rc ){
   6002           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
   6003         }
   6004       }
   6005     }
   6006   } while( rc==SQLITE_BUSY && nTries<3 );
   6007 
   6008   return rc;
   6009 }
   6010 
   6011 /* Takes the conch by taking a shared lock and read the contents conch, if
   6012 ** lockPath is non-NULL, the host ID and lock file path must match.  A NULL
   6013 ** lockPath means that the lockPath in the conch file will be used if the
   6014 ** host IDs match, or a new lock path will be generated automatically
   6015 ** and written to the conch file.
   6016 */
   6017 static int proxyTakeConch(unixFile *pFile){
   6018   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   6019 
   6020   if( pCtx->conchHeld!=0 ){
   6021     return SQLITE_OK;
   6022   }else{
   6023     unixFile *conchFile = pCtx->conchFile;
   6024     uuid_t myHostID;
   6025     int pError = 0;
   6026     char readBuf[PROXY_MAXCONCHLEN];
   6027     char lockPath[MAXPATHLEN];
   6028     char *tempLockPath = NULL;
   6029     int rc = SQLITE_OK;
   6030     int createConch = 0;
   6031     int hostIdMatch = 0;
   6032     int readLen = 0;
   6033     int tryOldLockPath = 0;
   6034     int forceNewLockPath = 0;
   6035 
   6036     OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
   6037              (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
   6038 
   6039     rc = proxyGetHostID(myHostID, &pError);
   6040     if( (rc&0xff)==SQLITE_IOERR ){
   6041       pFile->lastErrno = pError;
   6042       goto end_takeconch;
   6043     }
   6044     rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
   6045     if( rc!=SQLITE_OK ){
   6046       goto end_takeconch;
   6047     }
   6048     /* read the existing conch file */
   6049     readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
   6050     if( readLen<0 ){
   6051       /* I/O error: lastErrno set by seekAndRead */
   6052       pFile->lastErrno = conchFile->lastErrno;
   6053       rc = SQLITE_IOERR_READ;
   6054       goto end_takeconch;
   6055     }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
   6056              readBuf[0]!=(char)PROXY_CONCHVERSION ){
   6057       /* a short read or version format mismatch means we need to create a new
   6058       ** conch file.
   6059       */
   6060       createConch = 1;
   6061     }
   6062     /* if the host id matches and the lock path already exists in the conch
   6063     ** we'll try to use the path there, if we can't open that path, we'll
   6064     ** retry with a new auto-generated path
   6065     */
   6066     do { /* in case we need to try again for an :auto: named lock file */
   6067 
   6068       if( !createConch && !forceNewLockPath ){
   6069         hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
   6070                                   PROXY_HOSTIDLEN);
   6071         /* if the conch has data compare the contents */
   6072         if( !pCtx->lockProxyPath ){
   6073           /* for auto-named local lock file, just check the host ID and we'll
   6074            ** use the local lock file path that's already in there
   6075            */
   6076           if( hostIdMatch ){
   6077             size_t pathLen = (readLen - PROXY_PATHINDEX);
   6078 
   6079             if( pathLen>=MAXPATHLEN ){
   6080               pathLen=MAXPATHLEN-1;
   6081             }
   6082             memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
   6083             lockPath[pathLen] = 0;
   6084             tempLockPath = lockPath;
   6085             tryOldLockPath = 1;
   6086             /* create a copy of the lock path if the conch is taken */
   6087             goto end_takeconch;
   6088           }
   6089         }else if( hostIdMatch
   6090                && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
   6091                            readLen-PROXY_PATHINDEX)
   6092         ){
   6093           /* conch host and lock path match */
   6094           goto end_takeconch;
   6095         }
   6096       }
   6097 
   6098       /* if the conch isn't writable and doesn't match, we can't take it */
   6099       if( (conchFile->openFlags&O_RDWR) == 0 ){
   6100         rc = SQLITE_BUSY;
   6101         goto end_takeconch;
   6102       }
   6103 
   6104       /* either the conch didn't match or we need to create a new one */
   6105       if( !pCtx->lockProxyPath ){
   6106         proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
   6107         tempLockPath = lockPath;
   6108         /* create a copy of the lock path _only_ if the conch is taken */
   6109       }
   6110 
   6111       /* update conch with host and path (this will fail if other process
   6112       ** has a shared lock already), if the host id matches, use the big
   6113       ** stick.
   6114       */
   6115       futimes(conchFile->h, NULL);
   6116       if( hostIdMatch && !createConch ){
   6117         if( conchFile->pInode && conchFile->pInode->nShared>1 ){
   6118           /* We are trying for an exclusive lock but another thread in this
   6119            ** same process is still holding a shared lock. */
   6120           rc = SQLITE_BUSY;
   6121         } else {
   6122           rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
   6123         }
   6124       }else{
   6125         rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
   6126       }
   6127       if( rc==SQLITE_OK ){
   6128         char writeBuffer[PROXY_MAXCONCHLEN];
   6129         int writeSize = 0;
   6130 
   6131         writeBuffer[0] = (char)PROXY_CONCHVERSION;
   6132         memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
   6133         if( pCtx->lockProxyPath!=NULL ){
   6134           strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
   6135         }else{
   6136           strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
   6137         }
   6138         writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
   6139         robust_ftruncate(conchFile->h, writeSize);
   6140         rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
   6141         fsync(conchFile->h);
   6142         /* If we created a new conch file (not just updated the contents of a
   6143          ** valid conch file), try to match the permissions of the database
   6144          */
   6145         if( rc==SQLITE_OK && createConch ){
   6146           struct stat buf;
   6147           int err = osFstat(pFile->h, &buf);
   6148           if( err==0 ){
   6149             mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
   6150                                         S_IROTH|S_IWOTH);
   6151             /* try to match the database file R/W permissions, ignore failure */
   6152 #ifndef SQLITE_PROXY_DEBUG
   6153             osFchmod(conchFile->h, cmode);
   6154 #else
   6155             do{
   6156               rc = osFchmod(conchFile->h, cmode);
   6157             }while( rc==(-1) && errno==EINTR );
   6158             if( rc!=0 ){
   6159               int code = errno;
   6160               fprintf(stderr, "fchmod %o FAILED with %d %s\n",
   6161                       cmode, code, strerror(code));
   6162             } else {
   6163               fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
   6164             }
   6165           }else{
   6166             int code = errno;
   6167             fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
   6168                     err, code, strerror(code));
   6169 #endif
   6170           }
   6171         }
   6172       }
   6173       conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
   6174 
   6175     end_takeconch:
   6176       OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
   6177       if( rc==SQLITE_OK && pFile->openFlags ){
   6178         if( pFile->h>=0 ){
   6179           robust_close(pFile, pFile->h, __LINE__);
   6180         }
   6181         pFile->h = -1;
   6182         int fd = robust_open(pCtx->dbPath, pFile->openFlags,
   6183                       SQLITE_DEFAULT_FILE_PERMISSIONS);
   6184         OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
   6185         if( fd>=0 ){
   6186           pFile->h = fd;
   6187         }else{
   6188           rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
   6189            during locking */
   6190         }
   6191       }
   6192       if( rc==SQLITE_OK && !pCtx->lockProxy ){
   6193         char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
   6194         rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
   6195         if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
   6196           /* we couldn't create the proxy lock file with the old lock file path
   6197            ** so try again via auto-naming
   6198            */
   6199           forceNewLockPath = 1;
   6200           tryOldLockPath = 0;
   6201           continue; /* go back to the do {} while start point, try again */
   6202         }
   6203       }
   6204       if( rc==SQLITE_OK ){
   6205         /* Need to make a copy of path if we extracted the value
   6206          ** from the conch file or the path was allocated on the stack
   6207          */
   6208         if( tempLockPath ){
   6209           pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
   6210           if( !pCtx->lockProxyPath ){
   6211             rc = SQLITE_NOMEM;
   6212           }
   6213         }
   6214       }
   6215       if( rc==SQLITE_OK ){
   6216         pCtx->conchHeld = 1;
   6217 
   6218         if( pCtx->lockProxy->pMethod == &afpIoMethods ){
   6219           afpLockingContext *afpCtx;
   6220           afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
   6221           afpCtx->dbPath = pCtx->lockProxyPath;
   6222         }
   6223       } else {
   6224         conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
   6225       }
   6226       OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
   6227                rc==SQLITE_OK?"ok":"failed"));
   6228       return rc;
   6229     } while (1); /* in case we need to retry the :auto: lock file -
   6230                  ** we should never get here except via the 'continue' call. */
   6231   }
   6232 }
   6233 
   6234 /*
   6235 ** If pFile holds a lock on a conch file, then release that lock.
   6236 */
   6237 static int proxyReleaseConch(unixFile *pFile){
   6238   int rc = SQLITE_OK;         /* Subroutine return code */
   6239   proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
   6240   unixFile *conchFile;        /* Name of the conch file */
   6241 
   6242   pCtx = (proxyLockingContext *)pFile->lockingContext;
   6243   conchFile = pCtx->conchFile;
   6244   OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
   6245            (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
   6246            getpid()));
   6247   if( pCtx->conchHeld>0 ){
   6248     rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
   6249   }
   6250   pCtx->conchHeld = 0;
   6251   OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
   6252            (rc==SQLITE_OK ? "ok" : "failed")));
   6253   return rc;
   6254 }
   6255 
   6256 /*
   6257 ** Given the name of a database file, compute the name of its conch file.
   6258 ** Store the conch filename in memory obtained from sqlite3_malloc().
   6259 ** Make *pConchPath point to the new name.  Return SQLITE_OK on success
   6260 ** or SQLITE_NOMEM if unable to obtain memory.
   6261 **
   6262 ** The caller is responsible for ensuring that the allocated memory
   6263 ** space is eventually freed.
   6264 **
   6265 ** *pConchPath is set to NULL if a memory allocation error occurs.
   6266 */
   6267 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
   6268   int i;                        /* Loop counter */
   6269   int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
   6270   char *conchPath;              /* buffer in which to construct conch name */
   6271 
   6272   /* Allocate space for the conch filename and initialize the name to
   6273   ** the name of the original database file. */
   6274   *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
   6275   if( conchPath==0 ){
   6276     return SQLITE_NOMEM;
   6277   }
   6278   memcpy(conchPath, dbPath, len+1);
   6279 
   6280   /* now insert a "." before the last / character */
   6281   for( i=(len-1); i>=0; i-- ){
   6282     if( conchPath[i]=='/' ){
   6283       i++;
   6284       break;
   6285     }
   6286   }
   6287   conchPath[i]='.';
   6288   while ( i<len ){
   6289     conchPath[i+1]=dbPath[i];
   6290     i++;
   6291   }
   6292 
   6293   /* append the "-conch" suffix to the file */
   6294   memcpy(&conchPath[i+1], "-conch", 7);
   6295   assert( (int)strlen(conchPath) == len+7 );
   6296 
   6297   return SQLITE_OK;
   6298 }
   6299 
   6300 
   6301 /* Takes a fully configured proxy locking-style unix file and switches
   6302 ** the local lock file path
   6303 */
   6304 static int switchLockProxyPath(unixFile *pFile, const char *path) {
   6305   proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
   6306   char *oldPath = pCtx->lockProxyPath;
   6307   int rc = SQLITE_OK;
   6308 
   6309   if( pFile->eFileLock!=NO_LOCK ){
   6310     return SQLITE_BUSY;
   6311   }
   6312 
   6313   /* nothing to do if the path is NULL, :auto: or matches the existing path */
   6314   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
   6315     (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
   6316     return SQLITE_OK;
   6317   }else{
   6318     unixFile *lockProxy = pCtx->lockProxy;
   6319     pCtx->lockProxy=NULL;
   6320     pCtx->conchHeld = 0;
   6321     if( lockProxy!=NULL ){
   6322       rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
   6323       if( rc ) return rc;
   6324       sqlite3_free(lockProxy);
   6325     }
   6326     sqlite3_free(oldPath);
   6327     pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
   6328   }
   6329 
   6330   return rc;
   6331 }
   6332 
   6333 /*
   6334 ** pFile is a file that has been opened by a prior xOpen call.  dbPath
   6335 ** is a string buffer at least MAXPATHLEN+1 characters in size.
   6336 **
   6337 ** This routine find the filename associated with pFile and writes it
   6338 ** int dbPath.
   6339 */
   6340 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
   6341 #if defined(__APPLE__)
   6342   if( pFile->pMethod == &afpIoMethods ){
   6343     /* afp style keeps a reference to the db path in the filePath field
   6344     ** of the struct */
   6345     assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
   6346     strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
   6347   } else
   6348 #endif
   6349   if( pFile->pMethod == &dotlockIoMethods ){
   6350     /* dot lock style uses the locking context to store the dot lock
   6351     ** file path */
   6352     int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
   6353     memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
   6354   }else{
   6355     /* all other styles use the locking context to store the db file path */
   6356     assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
   6357     strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
   6358   }
   6359   return SQLITE_OK;
   6360 }
   6361 
   6362 /*
   6363 ** Takes an already filled in unix file and alters it so all file locking
   6364 ** will be performed on the local proxy lock file.  The following fields
   6365 ** are preserved in the locking context so that they can be restored and
   6366 ** the unix structure properly cleaned up at close time:
   6367 **  ->lockingContext
   6368 **  ->pMethod
   6369 */
   6370 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
   6371   proxyLockingContext *pCtx;
   6372   char dbPath[MAXPATHLEN+1];       /* Name of the database file */
   6373   char *lockPath=NULL;
   6374   int rc = SQLITE_OK;
   6375 
   6376   if( pFile->eFileLock!=NO_LOCK ){
   6377     return SQLITE_BUSY;
   6378   }
   6379   proxyGetDbPathForUnixFile(pFile, dbPath);
   6380   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
   6381     lockPath=NULL;
   6382   }else{
   6383     lockPath=(char *)path;
   6384   }
   6385 
   6386   OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
   6387            (lockPath ? lockPath : ":auto:"), getpid()));
   6388 
   6389   pCtx = sqlite3_malloc( sizeof(*pCtx) );
   6390   if( pCtx==0 ){
   6391     return SQLITE_NOMEM;
   6392   }
   6393   memset(pCtx, 0, sizeof(*pCtx));
   6394 
   6395   rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
   6396   if( rc==SQLITE_OK ){
   6397     rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
   6398     if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
   6399       /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
   6400       ** (c) the file system is read-only, then enable no-locking access.
   6401       ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
   6402       ** that openFlags will have only one of O_RDONLY or O_RDWR.
   6403       */
   6404       struct statfs fsInfo;
   6405       struct stat conchInfo;
   6406       int goLockless = 0;
   6407 
   6408       if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
   6409         int err = errno;
   6410         if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
   6411           goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
   6412         }
   6413       }
   6414       if( goLockless ){
   6415         pCtx->conchHeld = -1; /* read only FS/ lockless */
   6416         rc = SQLITE_OK;
   6417       }
   6418     }
   6419   }
   6420   if( rc==SQLITE_OK && lockPath ){
   6421     pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
   6422   }
   6423 
   6424   if( rc==SQLITE_OK ){
   6425     pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
   6426     if( pCtx->dbPath==NULL ){
   6427       rc = SQLITE_NOMEM;
   6428     }
   6429   }
   6430   if( rc==SQLITE_OK ){
   6431     /* all memory is allocated, proxys are created and assigned,
   6432     ** switch the locking context and pMethod then return.
   6433     */
   6434     pCtx->oldLockingContext = pFile->lockingContext;
   6435     pFile->lockingContext = pCtx;
   6436     pCtx->pOldMethod = pFile->pMethod;
   6437     pFile->pMethod = &proxyIoMethods;
   6438   }else{
   6439     if( pCtx->conchFile ){
   6440       pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
   6441       sqlite3_free(pCtx->conchFile);
   6442     }
   6443     sqlite3DbFree(0, pCtx->lockProxyPath);
   6444     sqlite3_free(pCtx->conchFilePath);
   6445     sqlite3_free(pCtx);
   6446   }
   6447   OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
   6448            (rc==SQLITE_OK ? "ok" : "failed")));
   6449   return rc;
   6450 }
   6451 
   6452 
   6453 /*
   6454 ** This routine handles sqlite3_file_control() calls that are specific
   6455 ** to proxy locking.
   6456 */
   6457 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
   6458   switch( op ){
   6459     case SQLITE_GET_LOCKPROXYFILE: {
   6460       unixFile *pFile = (unixFile*)id;
   6461       if( pFile->pMethod == &proxyIoMethods ){
   6462         proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
   6463         proxyTakeConch(pFile);
   6464         if( pCtx->lockProxyPath ){
   6465           *(const char **)pArg = pCtx->lockProxyPath;
   6466         }else{
   6467           *(const char **)pArg = ":auto: (not held)";
   6468         }
   6469       } else {
   6470         *(const char **)pArg = NULL;
   6471       }
   6472       return SQLITE_OK;
   6473     }
   6474     case SQLITE_SET_LOCKPROXYFILE: {
   6475       unixFile *pFile = (unixFile*)id;
   6476       int rc = SQLITE_OK;
   6477       int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
   6478       if( pArg==NULL || (const char *)pArg==0 ){
   6479         if( isProxyStyle ){
   6480           /* turn off proxy locking - not supported */
   6481           rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
   6482         }else{
   6483           /* turn off proxy locking - already off - NOOP */
   6484           rc = SQLITE_OK;
   6485         }
   6486       }else{
   6487         const char *proxyPath = (const char *)pArg;
   6488         if( isProxyStyle ){
   6489           proxyLockingContext *pCtx =
   6490             (proxyLockingContext*)pFile->lockingContext;
   6491           if( !strcmp(pArg, ":auto:")
   6492            || (pCtx->lockProxyPath &&
   6493                !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
   6494           ){
   6495             rc = SQLITE_OK;
   6496           }else{
   6497             rc = switchLockProxyPath(pFile, proxyPath);
   6498           }
   6499         }else{
   6500           /* turn on proxy file locking */
   6501           rc = proxyTransformUnixFile(pFile, proxyPath);
   6502         }
   6503       }
   6504       return rc;
   6505     }
   6506     default: {
   6507       assert( 0 );  /* The call assures that only valid opcodes are sent */
   6508     }
   6509   }
   6510   /*NOTREACHED*/
   6511   return SQLITE_ERROR;
   6512 }
   6513 
   6514 /*
   6515 ** Within this division (the proxying locking implementation) the procedures
   6516 ** above this point are all utilities.  The lock-related methods of the
   6517 ** proxy-locking sqlite3_io_method object follow.
   6518 */
   6519 
   6520 
   6521 /*
   6522 ** This routine checks if there is a RESERVED lock held on the specified
   6523 ** file by this or any other process. If such a lock is held, set *pResOut
   6524 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   6525 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   6526 */
   6527 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
   6528   unixFile *pFile = (unixFile*)id;
   6529   int rc = proxyTakeConch(pFile);
   6530   if( rc==SQLITE_OK ){
   6531     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   6532     if( pCtx->conchHeld>0 ){
   6533       unixFile *proxy = pCtx->lockProxy;
   6534       return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
   6535     }else{ /* conchHeld < 0 is lockless */
   6536       pResOut=0;
   6537     }
   6538   }
   6539   return rc;
   6540 }
   6541 
   6542 /*
   6543 ** Lock the file with the lock specified by parameter eFileLock - one
   6544 ** of the following:
   6545 **
   6546 **     (1) SHARED_LOCK
   6547 **     (2) RESERVED_LOCK
   6548 **     (3) PENDING_LOCK
   6549 **     (4) EXCLUSIVE_LOCK
   6550 **
   6551 ** Sometimes when requesting one lock state, additional lock states
   6552 ** are inserted in between.  The locking might fail on one of the later
   6553 ** transitions leaving the lock state different from what it started but
   6554 ** still short of its goal.  The following chart shows the allowed
   6555 ** transitions and the inserted intermediate states:
   6556 **
   6557 **    UNLOCKED -> SHARED
   6558 **    SHARED -> RESERVED
   6559 **    SHARED -> (PENDING) -> EXCLUSIVE
   6560 **    RESERVED -> (PENDING) -> EXCLUSIVE
   6561 **    PENDING -> EXCLUSIVE
   6562 **
   6563 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   6564 ** routine to lower a locking level.
   6565 */
   6566 static int proxyLock(sqlite3_file *id, int eFileLock) {
   6567   unixFile *pFile = (unixFile*)id;
   6568   int rc = proxyTakeConch(pFile);
   6569   if( rc==SQLITE_OK ){
   6570     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   6571     if( pCtx->conchHeld>0 ){
   6572       unixFile *proxy = pCtx->lockProxy;
   6573       rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
   6574       pFile->eFileLock = proxy->eFileLock;
   6575     }else{
   6576       /* conchHeld < 0 is lockless */
   6577     }
   6578   }
   6579   return rc;
   6580 }
   6581 
   6582 
   6583 /*
   6584 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   6585 ** must be either NO_LOCK or SHARED_LOCK.
   6586 **
   6587 ** If the locking level of the file descriptor is already at or below
   6588 ** the requested locking level, this routine is a no-op.
   6589 */
   6590 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
   6591   unixFile *pFile = (unixFile*)id;
   6592   int rc = proxyTakeConch(pFile);
   6593   if( rc==SQLITE_OK ){
   6594     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   6595     if( pCtx->conchHeld>0 ){
   6596       unixFile *proxy = pCtx->lockProxy;
   6597       rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
   6598       pFile->eFileLock = proxy->eFileLock;
   6599     }else{
   6600       /* conchHeld < 0 is lockless */
   6601     }
   6602   }
   6603   return rc;
   6604 }
   6605 
   6606 /*
   6607 ** Close a file that uses proxy locks.
   6608 */
   6609 static int proxyClose(sqlite3_file *id) {
   6610   if( id ){
   6611     unixFile *pFile = (unixFile*)id;
   6612     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   6613     unixFile *lockProxy = pCtx->lockProxy;
   6614     unixFile *conchFile = pCtx->conchFile;
   6615     int rc = SQLITE_OK;
   6616 
   6617     if( lockProxy ){
   6618       rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
   6619       if( rc ) return rc;
   6620       rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
   6621       if( rc ) return rc;
   6622       sqlite3_free(lockProxy);
   6623       pCtx->lockProxy = 0;
   6624     }
   6625     if( conchFile ){
   6626       if( pCtx->conchHeld ){
   6627         rc = proxyReleaseConch(pFile);
   6628         if( rc ) return rc;
   6629       }
   6630       rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
   6631       if( rc ) return rc;
   6632       sqlite3_free(conchFile);
   6633     }
   6634     sqlite3DbFree(0, pCtx->lockProxyPath);
   6635     sqlite3_free(pCtx->conchFilePath);
   6636     sqlite3DbFree(0, pCtx->dbPath);
   6637     /* restore the original locking context and pMethod then close it */
   6638     pFile->lockingContext = pCtx->oldLockingContext;
   6639     pFile->pMethod = pCtx->pOldMethod;
   6640     sqlite3_free(pCtx);
   6641     return pFile->pMethod->xClose(id);
   6642   }
   6643   return SQLITE_OK;
   6644 }
   6645 
   6646 
   6647 
   6648 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
   6649 /*
   6650 ** The proxy locking style is intended for use with AFP filesystems.
   6651 ** And since AFP is only supported on MacOSX, the proxy locking is also
   6652 ** restricted to MacOSX.
   6653 **
   6654 **
   6655 ******************* End of the proxy lock implementation **********************
   6656 ******************************************************************************/
   6657 
   6658 /*
   6659 ** Initialize the operating system interface.
   6660 **
   6661 ** This routine registers all VFS implementations for unix-like operating
   6662 ** systems.  This routine, and the sqlite3_os_end() routine that follows,
   6663 ** should be the only routines in this file that are visible from other
   6664 ** files.
   6665 **
   6666 ** This routine is called once during SQLite initialization and by a
   6667 ** single thread.  The memory allocation and mutex subsystems have not
   6668 ** necessarily been initialized when this routine is called, and so they
   6669 ** should not be used.
   6670 */
   6671 int sqlite3_os_init(void){
   6672   /*
   6673   ** The following macro defines an initializer for an sqlite3_vfs object.
   6674   ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
   6675   ** to the "finder" function.  (pAppData is a pointer to a pointer because
   6676   ** silly C90 rules prohibit a void* from being cast to a function pointer
   6677   ** and so we have to go through the intermediate pointer to avoid problems
   6678   ** when compiling with -pedantic-errors on GCC.)
   6679   **
   6680   ** The FINDER parameter to this macro is the name of the pointer to the
   6681   ** finder-function.  The finder-function returns a pointer to the
   6682   ** sqlite_io_methods object that implements the desired locking
   6683   ** behaviors.  See the division above that contains the IOMETHODS
   6684   ** macro for addition information on finder-functions.
   6685   **
   6686   ** Most finders simply return a pointer to a fixed sqlite3_io_methods
   6687   ** object.  But the "autolockIoFinder" available on MacOSX does a little
   6688   ** more than that; it looks at the filesystem type that hosts the
   6689   ** database file and tries to choose an locking method appropriate for
   6690   ** that filesystem time.
   6691   */
   6692   #define UNIXVFS(VFSNAME, FINDER) {                        \
   6693     3,                    /* iVersion */                    \
   6694     sizeof(unixFile),     /* szOsFile */                    \
   6695     MAX_PATHNAME,         /* mxPathname */                  \
   6696     0,                    /* pNext */                       \
   6697     VFSNAME,              /* zName */                       \
   6698     (void*)&FINDER,       /* pAppData */                    \
   6699     unixOpen,             /* xOpen */                       \
   6700     unixDelete,           /* xDelete */                     \
   6701     unixAccess,           /* xAccess */                     \
   6702     unixFullPathname,     /* xFullPathname */               \
   6703     unixDlOpen,           /* xDlOpen */                     \
   6704     unixDlError,          /* xDlError */                    \
   6705     unixDlSym,            /* xDlSym */                      \
   6706     unixDlClose,          /* xDlClose */                    \
   6707     unixRandomness,       /* xRandomness */                 \
   6708     unixSleep,            /* xSleep */                      \
   6709     unixCurrentTime,      /* xCurrentTime */                \
   6710     unixGetLastError,     /* xGetLastError */               \
   6711     unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
   6712     unixSetSystemCall,    /* xSetSystemCall */              \
   6713     unixGetSystemCall,    /* xGetSystemCall */              \
   6714     unixNextSystemCall,   /* xNextSystemCall */             \
   6715   }
   6716 
   6717   /*
   6718   ** All default VFSes for unix are contained in the following array.
   6719   **
   6720   ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
   6721   ** by the SQLite core when the VFS is registered.  So the following
   6722   ** array cannot be const.
   6723   */
   6724   static sqlite3_vfs aVfs[] = {
   6725 #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
   6726     UNIXVFS("unix",          autolockIoFinder ),
   6727 #else
   6728     UNIXVFS("unix",          posixIoFinder ),
   6729 #endif
   6730     UNIXVFS("unix-none",     nolockIoFinder ),
   6731     UNIXVFS("unix-dotfile",  dotlockIoFinder ),
   6732     UNIXVFS("unix-excl",     posixIoFinder ),
   6733 #if OS_VXWORKS
   6734     UNIXVFS("unix-namedsem", semIoFinder ),
   6735 #endif
   6736 #if SQLITE_ENABLE_LOCKING_STYLE
   6737     UNIXVFS("unix-posix",    posixIoFinder ),
   6738 #if !OS_VXWORKS
   6739     UNIXVFS("unix-flock",    flockIoFinder ),
   6740 #endif
   6741 #endif
   6742 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   6743     UNIXVFS("unix-afp",      afpIoFinder ),
   6744     UNIXVFS("unix-nfs",      nfsIoFinder ),
   6745     UNIXVFS("unix-proxy",    proxyIoFinder ),
   6746 #endif
   6747   };
   6748   unsigned int i;          /* Loop counter */
   6749 
   6750   /* Double-check that the aSyscall[] array has been constructed
   6751   ** correctly.  See ticket [bb3a86e890c8e96ab] */
   6752   assert( ArraySize(aSyscall)==18 );
   6753 
   6754   /* Register all VFSes defined in the aVfs[] array */
   6755   for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
   6756     sqlite3_vfs_register(&aVfs[i], i==0);
   6757   }
   6758   return SQLITE_OK;
   6759 }
   6760 
   6761 /*
   6762 ** Shutdown the operating system interface.
   6763 **
   6764 ** Some operating systems might need to do some cleanup in this routine,
   6765 ** to release dynamically allocated objects.  But not on unix.
   6766 ** This routine is a no-op for unix.
   6767 */
   6768 int sqlite3_os_end(void){
   6769   return SQLITE_OK;
   6770 }
   6771 
   6772 #endif /* SQLITE_OS_UNIX */
   6773