extensions/sqlite/sqlite-source/os_unix.c
author David Anderson <dvander@alliedmods.net>
Sun Oct 28 05:48:06 2007 +0000 (2007-10-28)
changeset 1645 27307df4d711
parent 1203 633c25ce6405
permissions -rw-r--r--
updated to sqlite-3.5.1 now that it's stable
used new shared cache functionality (yay)
     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 code that is specific to Unix systems.
    14 */
    15 #include "sqliteInt.h"
    16 #if OS_UNIX              /* This file is used on unix only */
    17 
    18 /* #define SQLITE_ENABLE_LOCKING_STYLE 0 */
    19 
    20 /*
    21 ** These #defines should enable >2GB file support on Posix if the
    22 ** underlying operating system supports it.  If the OS lacks
    23 ** large file support, these should be no-ops.
    24 **
    25 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
    26 ** on the compiler command line.  This is necessary if you are compiling
    27 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
    28 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
    29 ** without this option, LFS is enable.  But LFS does not exist in the kernel
    30 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
    31 ** portability you should omit LFS.
    32 */
    33 #ifndef SQLITE_DISABLE_LFS
    34 # define _LARGE_FILE       1
    35 # ifndef _FILE_OFFSET_BITS
    36 #   define _FILE_OFFSET_BITS 64
    37 # endif
    38 # define _LARGEFILE_SOURCE 1
    39 #endif
    40 
    41 /*
    42 ** standard include files.
    43 */
    44 #include <sys/types.h>
    45 #include <sys/stat.h>
    46 #include <fcntl.h>
    47 #include <unistd.h>
    48 #include <time.h>
    49 #include <sys/time.h>
    50 #include <errno.h>
    51 #ifdef SQLITE_ENABLE_LOCKING_STYLE
    52 #include <sys/ioctl.h>
    53 #include <sys/param.h>
    54 #include <sys/mount.h>
    55 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
    56 
    57 /*
    58 ** If we are to be thread-safe, include the pthreads header and define
    59 ** the SQLITE_UNIX_THREADS macro.
    60 */
    61 #if SQLITE_THREADSAFE
    62 # include <pthread.h>
    63 # define SQLITE_UNIX_THREADS 1
    64 #endif
    65 
    66 /*
    67 ** Default permissions when creating a new file
    68 */
    69 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
    70 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
    71 #endif
    72 
    73 /*
    74 ** Maximum supported path-length.
    75 */
    76 #define MAX_PATHNAME 512
    77 
    78 
    79 /*
    80 ** The unixFile structure is subclass of sqlite3_file specific for the unix
    81 ** protability layer.
    82 */
    83 typedef struct unixFile unixFile;
    84 struct unixFile {
    85   sqlite3_io_methods const *pMethod;  /* Always the first entry */
    86 #ifdef SQLITE_TEST
    87   /* In test mode, increase the size of this structure a bit so that 
    88   ** it is larger than the struct CrashFile defined in test6.c.
    89   */
    90   char aPadding[32];
    91 #endif
    92   struct openCnt *pOpen;    /* Info about all open fd's on this inode */
    93   struct lockInfo *pLock;   /* Info about locks on this inode */
    94 #ifdef SQLITE_ENABLE_LOCKING_STYLE
    95   void *lockingContext;     /* Locking style specific state */
    96 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
    97   int h;                    /* The file descriptor */
    98   unsigned char locktype;   /* The type of lock held on this fd */
    99   int dirfd;                /* File descriptor for the directory */
   100 #if SQLITE_THREADSAFE
   101   pthread_t tid;            /* The thread that "owns" this unixFile */
   102 #endif
   103 };
   104 
   105 /*
   106 ** Include code that is common to all os_*.c files
   107 */
   108 #include "os_common.h"
   109 
   110 /*
   111 ** Define various macros that are missing from some systems.
   112 */
   113 #ifndef O_LARGEFILE
   114 # define O_LARGEFILE 0
   115 #endif
   116 #ifdef SQLITE_DISABLE_LFS
   117 # undef O_LARGEFILE
   118 # define O_LARGEFILE 0
   119 #endif
   120 #ifndef O_NOFOLLOW
   121 # define O_NOFOLLOW 0
   122 #endif
   123 #ifndef O_BINARY
   124 # define O_BINARY 0
   125 #endif
   126 
   127 /*
   128 ** The DJGPP compiler environment looks mostly like Unix, but it
   129 ** lacks the fcntl() system call.  So redefine fcntl() to be something
   130 ** that always succeeds.  This means that locking does not occur under
   131 ** DJGPP.  But it's DOS - what did you expect?
   132 */
   133 #ifdef __DJGPP__
   134 # define fcntl(A,B,C) 0
   135 #endif
   136 
   137 /*
   138 ** The threadid macro resolves to the thread-id or to 0.  Used for
   139 ** testing and debugging only.
   140 */
   141 #if SQLITE_THREADSAFE
   142 #define threadid pthread_self()
   143 #else
   144 #define threadid 0
   145 #endif
   146 
   147 /*
   148 ** Set or check the unixFile.tid field.  This field is set when an unixFile
   149 ** is first opened.  All subsequent uses of the unixFile verify that the
   150 ** same thread is operating on the unixFile.  Some operating systems do
   151 ** not allow locks to be overridden by other threads and that restriction
   152 ** means that sqlite3* database handles cannot be moved from one thread
   153 ** to another.  This logic makes sure a user does not try to do that
   154 ** by mistake.
   155 **
   156 ** Version 3.3.1 (2006-01-15):  unixFile can be moved from one thread to
   157 ** another as long as we are running on a system that supports threads
   158 ** overriding each others locks (which now the most common behavior)
   159 ** or if no locks are held.  But the unixFile.pLock field needs to be
   160 ** recomputed because its key includes the thread-id.  See the 
   161 ** transferOwnership() function below for additional information
   162 */
   163 #if SQLITE_THREADSAFE
   164 # define SET_THREADID(X)   (X)->tid = pthread_self()
   165 # define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
   166                             !pthread_equal((X)->tid, pthread_self()))
   167 #else
   168 # define SET_THREADID(X)
   169 # define CHECK_THREADID(X) 0
   170 #endif
   171 
   172 /*
   173 ** Here is the dirt on POSIX advisory locks:  ANSI STD 1003.1 (1996)
   174 ** section 6.5.2.2 lines 483 through 490 specify that when a process
   175 ** sets or clears a lock, that operation overrides any prior locks set
   176 ** by the same process.  It does not explicitly say so, but this implies
   177 ** that it overrides locks set by the same process using a different
   178 ** file descriptor.  Consider this test case:
   179 **
   180 **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
   181 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
   182 **
   183 ** Suppose ./file1 and ./file2 are really the same file (because
   184 ** one is a hard or symbolic link to the other) then if you set
   185 ** an exclusive lock on fd1, then try to get an exclusive lock
   186 ** on fd2, it works.  I would have expected the second lock to
   187 ** fail since there was already a lock on the file due to fd1.
   188 ** But not so.  Since both locks came from the same process, the
   189 ** second overrides the first, even though they were on different
   190 ** file descriptors opened on different file names.
   191 **
   192 ** Bummer.  If you ask me, this is broken.  Badly broken.  It means
   193 ** that we cannot use POSIX locks to synchronize file access among
   194 ** competing threads of the same process.  POSIX locks will work fine
   195 ** to synchronize access for threads in separate processes, but not
   196 ** threads within the same process.
   197 **
   198 ** To work around the problem, SQLite has to manage file locks internally
   199 ** on its own.  Whenever a new database is opened, we have to find the
   200 ** specific inode of the database file (the inode is determined by the
   201 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
   202 ** and check for locks already existing on that inode.  When locks are
   203 ** created or removed, we have to look at our own internal record of the
   204 ** locks to see if another thread has previously set a lock on that same
   205 ** inode.
   206 **
   207 ** The sqlite3_file structure for POSIX is no longer just an integer file
   208 ** descriptor.  It is now a structure that holds the integer file
   209 ** descriptor and a pointer to a structure that describes the internal
   210 ** locks on the corresponding inode.  There is one locking structure
   211 ** per inode, so if the same inode is opened twice, both unixFile structures
   212 ** point to the same locking structure.  The locking structure keeps
   213 ** a reference count (so we will know when to delete it) and a "cnt"
   214 ** field that tells us its internal lock status.  cnt==0 means the
   215 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
   216 ** cnt>0 means there are cnt shared locks on the file.
   217 **
   218 ** Any attempt to lock or unlock a file first checks the locking
   219 ** structure.  The fcntl() system call is only invoked to set a 
   220 ** POSIX lock if the internal lock structure transitions between
   221 ** a locked and an unlocked state.
   222 **
   223 ** 2004-Jan-11:
   224 ** More recent discoveries about POSIX advisory locks.  (The more
   225 ** I discover, the more I realize the a POSIX advisory locks are
   226 ** an abomination.)
   227 **
   228 ** If you close a file descriptor that points to a file that has locks,
   229 ** all locks on that file that are owned by the current process are
   230 ** released.  To work around this problem, each unixFile structure contains
   231 ** a pointer to an openCnt structure.  There is one openCnt structure
   232 ** per open inode, which means that multiple unixFile can point to a single
   233 ** openCnt.  When an attempt is made to close an unixFile, if there are
   234 ** other unixFile open on the same inode that are holding locks, the call
   235 ** to close() the file descriptor is deferred until all of the locks clear.
   236 ** The openCnt structure keeps a list of file descriptors that need to
   237 ** be closed and that list is walked (and cleared) when the last lock
   238 ** clears.
   239 **
   240 ** First, under Linux threads, because each thread has a separate
   241 ** process ID, lock operations in one thread do not override locks
   242 ** to the same file in other threads.  Linux threads behave like
   243 ** separate processes in this respect.  But, if you close a file
   244 ** descriptor in linux threads, all locks are cleared, even locks
   245 ** on other threads and even though the other threads have different
   246 ** process IDs.  Linux threads is inconsistent in this respect.
   247 ** (I'm beginning to think that linux threads is an abomination too.)
   248 ** The consequence of this all is that the hash table for the lockInfo
   249 ** structure has to include the process id as part of its key because
   250 ** locks in different threads are treated as distinct.  But the 
   251 ** openCnt structure should not include the process id in its
   252 ** key because close() clears lock on all threads, not just the current
   253 ** thread.  Were it not for this goofiness in linux threads, we could
   254 ** combine the lockInfo and openCnt structures into a single structure.
   255 **
   256 ** 2004-Jun-28:
   257 ** On some versions of linux, threads can override each others locks.
   258 ** On others not.  Sometimes you can change the behavior on the same
   259 ** system by setting the LD_ASSUME_KERNEL environment variable.  The
   260 ** POSIX standard is silent as to which behavior is correct, as far
   261 ** as I can tell, so other versions of unix might show the same
   262 ** inconsistency.  There is no little doubt in my mind that posix
   263 ** advisory locks and linux threads are profoundly broken.
   264 **
   265 ** To work around the inconsistencies, we have to test at runtime 
   266 ** whether or not threads can override each others locks.  This test
   267 ** is run once, the first time any lock is attempted.  A static 
   268 ** variable is set to record the results of this test for future
   269 ** use.
   270 */
   271 
   272 /*
   273 ** An instance of the following structure serves as the key used
   274 ** to locate a particular lockInfo structure given its inode.
   275 **
   276 ** If threads cannot override each others locks, then we set the
   277 ** lockKey.tid field to the thread ID.  If threads can override
   278 ** each others locks then tid is always set to zero.  tid is omitted
   279 ** if we compile without threading support.
   280 */
   281 struct lockKey {
   282   dev_t dev;       /* Device number */
   283   ino_t ino;       /* Inode number */
   284 #if SQLITE_THREADSAFE
   285   pthread_t tid;   /* Thread ID or zero if threads can override each other */
   286 #endif
   287 };
   288 
   289 /*
   290 ** An instance of the following structure is allocated for each open
   291 ** inode on each thread with a different process ID.  (Threads have
   292 ** different process IDs on linux, but not on most other unixes.)
   293 **
   294 ** A single inode can have multiple file descriptors, so each unixFile
   295 ** structure contains a pointer to an instance of this object and this
   296 ** object keeps a count of the number of unixFile pointing to it.
   297 */
   298 struct lockInfo {
   299   struct lockKey key;  /* The lookup key */
   300   int cnt;             /* Number of SHARED locks held */
   301   int locktype;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
   302   int nRef;            /* Number of pointers to this structure */
   303 };
   304 
   305 /*
   306 ** An instance of the following structure serves as the key used
   307 ** to locate a particular openCnt structure given its inode.  This
   308 ** is the same as the lockKey except that the thread ID is omitted.
   309 */
   310 struct openKey {
   311   dev_t dev;   /* Device number */
   312   ino_t ino;   /* Inode number */
   313 };
   314 
   315 /*
   316 ** An instance of the following structure is allocated for each open
   317 ** inode.  This structure keeps track of the number of locks on that
   318 ** inode.  If a close is attempted against an inode that is holding
   319 ** locks, the close is deferred until all locks clear by adding the
   320 ** file descriptor to be closed to the pending list.
   321 */
   322 struct openCnt {
   323   struct openKey key;   /* The lookup key */
   324   int nRef;             /* Number of pointers to this structure */
   325   int nLock;            /* Number of outstanding locks */
   326   int nPending;         /* Number of pending close() operations */
   327   int *aPending;        /* Malloced space holding fd's awaiting a close() */
   328 };
   329 
   330 /* 
   331 ** These hash tables map inodes and file descriptors (really, lockKey and
   332 ** openKey structures) into lockInfo and openCnt structures.  Access to 
   333 ** these hash tables must be protected by a mutex.
   334 */
   335 static Hash lockHash = {SQLITE_HASH_BINARY, 0, 0, 0, 0, 0};
   336 static Hash openHash = {SQLITE_HASH_BINARY, 0, 0, 0, 0, 0};
   337 
   338 #ifdef SQLITE_ENABLE_LOCKING_STYLE
   339 /*
   340 ** The locking styles are associated with the different file locking
   341 ** capabilities supported by different file systems.  
   342 **
   343 ** POSIX locking style fully supports shared and exclusive byte-range locks 
   344 ** ADP locking only supports exclusive byte-range locks
   345 ** FLOCK only supports a single file-global exclusive lock
   346 ** DOTLOCK isn't a true locking style, it refers to the use of a special
   347 **   file named the same as the database file with a '.lock' extension, this
   348 **   can be used on file systems that do not offer any reliable file locking
   349 ** NO locking means that no locking will be attempted, this is only used for
   350 **   read-only file systems currently
   351 ** UNSUPPORTED means that no locking will be attempted, this is only used for
   352 **   file systems that are known to be unsupported
   353 */
   354 typedef enum {
   355         posixLockingStyle = 0,       /* standard posix-advisory locks */
   356         afpLockingStyle,             /* use afp locks */
   357         flockLockingStyle,           /* use flock() */
   358         dotlockLockingStyle,         /* use <file>.lock files */
   359         noLockingStyle,              /* useful for read-only file system */
   360         unsupportedLockingStyle      /* indicates unsupported file system */
   361 } sqlite3LockingStyle;
   362 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
   363 
   364 /*
   365 ** Helper functions to obtain and relinquish the global mutex.
   366 */
   367 static void enterMutex(){
   368   sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
   369 }
   370 static void leaveMutex(){
   371   sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
   372 }
   373 
   374 #if SQLITE_THREADSAFE
   375 /*
   376 ** This variable records whether or not threads can override each others
   377 ** locks.
   378 **
   379 **    0:  No.  Threads cannot override each others locks.
   380 **    1:  Yes.  Threads can override each others locks.
   381 **   -1:  We don't know yet.
   382 **
   383 ** On some systems, we know at compile-time if threads can override each
   384 ** others locks.  On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
   385 ** will be set appropriately.  On other systems, we have to check at
   386 ** runtime.  On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
   387 ** undefined.
   388 **
   389 ** This variable normally has file scope only.  But during testing, we make
   390 ** it a global so that the test code can change its value in order to verify
   391 ** that the right stuff happens in either case.
   392 */
   393 #ifndef SQLITE_THREAD_OVERRIDE_LOCK
   394 # define SQLITE_THREAD_OVERRIDE_LOCK -1
   395 #endif
   396 #ifdef SQLITE_TEST
   397 int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
   398 #else
   399 static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
   400 #endif
   401 
   402 /*
   403 ** This structure holds information passed into individual test
   404 ** threads by the testThreadLockingBehavior() routine.
   405 */
   406 struct threadTestData {
   407   int fd;                /* File to be locked */
   408   struct flock lock;     /* The locking operation */
   409   int result;            /* Result of the locking operation */
   410 };
   411 
   412 #ifdef SQLITE_LOCK_TRACE
   413 /*
   414 ** Print out information about all locking operations.
   415 **
   416 ** This routine is used for troubleshooting locks on multithreaded
   417 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
   418 ** command-line option on the compiler.  This code is normally
   419 ** turned off.
   420 */
   421 static int lockTrace(int fd, int op, struct flock *p){
   422   char *zOpName, *zType;
   423   int s;
   424   int savedErrno;
   425   if( op==F_GETLK ){
   426     zOpName = "GETLK";
   427   }else if( op==F_SETLK ){
   428     zOpName = "SETLK";
   429   }else{
   430     s = fcntl(fd, op, p);
   431     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
   432     return s;
   433   }
   434   if( p->l_type==F_RDLCK ){
   435     zType = "RDLCK";
   436   }else if( p->l_type==F_WRLCK ){
   437     zType = "WRLCK";
   438   }else if( p->l_type==F_UNLCK ){
   439     zType = "UNLCK";
   440   }else{
   441     assert( 0 );
   442   }
   443   assert( p->l_whence==SEEK_SET );
   444   s = fcntl(fd, op, p);
   445   savedErrno = errno;
   446   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
   447      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
   448      (int)p->l_pid, s);
   449   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
   450     struct flock l2;
   451     l2 = *p;
   452     fcntl(fd, F_GETLK, &l2);
   453     if( l2.l_type==F_RDLCK ){
   454       zType = "RDLCK";
   455     }else if( l2.l_type==F_WRLCK ){
   456       zType = "WRLCK";
   457     }else if( l2.l_type==F_UNLCK ){
   458       zType = "UNLCK";
   459     }else{
   460       assert( 0 );
   461     }
   462     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
   463        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
   464   }
   465   errno = savedErrno;
   466   return s;
   467 }
   468 #define fcntl lockTrace
   469 #endif /* SQLITE_LOCK_TRACE */
   470 
   471 /*
   472 ** The testThreadLockingBehavior() routine launches two separate
   473 ** threads on this routine.  This routine attempts to lock a file
   474 ** descriptor then returns.  The success or failure of that attempt
   475 ** allows the testThreadLockingBehavior() procedure to determine
   476 ** whether or not threads can override each others locks.
   477 */
   478 static void *threadLockingTest(void *pArg){
   479   struct threadTestData *pData = (struct threadTestData*)pArg;
   480   pData->result = fcntl(pData->fd, F_SETLK, &pData->lock);
   481   return pArg;
   482 }
   483 
   484 /*
   485 ** This procedure attempts to determine whether or not threads
   486 ** can override each others locks then sets the 
   487 ** threadsOverrideEachOthersLocks variable appropriately.
   488 */
   489 static void testThreadLockingBehavior(int fd_orig){
   490   int fd;
   491   struct threadTestData d[2];
   492   pthread_t t[2];
   493 
   494   fd = dup(fd_orig);
   495   if( fd<0 ) return;
   496   memset(d, 0, sizeof(d));
   497   d[0].fd = fd;
   498   d[0].lock.l_type = F_RDLCK;
   499   d[0].lock.l_len = 1;
   500   d[0].lock.l_start = 0;
   501   d[0].lock.l_whence = SEEK_SET;
   502   d[1] = d[0];
   503   d[1].lock.l_type = F_WRLCK;
   504   pthread_create(&t[0], 0, threadLockingTest, &d[0]);
   505   pthread_create(&t[1], 0, threadLockingTest, &d[1]);
   506   pthread_join(t[0], 0);
   507   pthread_join(t[1], 0);
   508   close(fd);
   509   threadsOverrideEachOthersLocks =  d[0].result==0 && d[1].result==0;
   510 }
   511 #endif /* SQLITE_THREADSAFE */
   512 
   513 /*
   514 ** Release a lockInfo structure previously allocated by findLockInfo().
   515 */
   516 static void releaseLockInfo(struct lockInfo *pLock){
   517   if (pLock == NULL)
   518     return;
   519   pLock->nRef--;
   520   if( pLock->nRef==0 ){
   521     sqlite3HashInsert(&lockHash, &pLock->key, sizeof(pLock->key), 0);
   522     sqlite3_free(pLock);
   523   }
   524 }
   525 
   526 /*
   527 ** Release a openCnt structure previously allocated by findLockInfo().
   528 */
   529 static void releaseOpenCnt(struct openCnt *pOpen){
   530   if (pOpen == NULL)
   531     return;
   532   pOpen->nRef--;
   533   if( pOpen->nRef==0 ){
   534     sqlite3HashInsert(&openHash, &pOpen->key, sizeof(pOpen->key), 0);
   535     free(pOpen->aPending);
   536     sqlite3_free(pOpen);
   537   }
   538 }
   539 
   540 #ifdef SQLITE_ENABLE_LOCKING_STYLE
   541 /*
   542 ** Tests a byte-range locking query to see if byte range locks are 
   543 ** supported, if not we fall back to dotlockLockingStyle.
   544 */
   545 static sqlite3LockingStyle sqlite3TestLockingStyle(
   546   const char *filePath, 
   547   int fd
   548 ){
   549   /* test byte-range lock using fcntl */
   550   struct flock lockInfo;
   551   
   552   lockInfo.l_len = 1;
   553   lockInfo.l_start = 0;
   554   lockInfo.l_whence = SEEK_SET;
   555   lockInfo.l_type = F_RDLCK;
   556   
   557   if( fcntl(fd, F_GETLK, &lockInfo)!=-1 ) {
   558     return posixLockingStyle;
   559   } 
   560   
   561   /* testing for flock can give false positives.  So if if the above test
   562   ** fails, then we fall back to using dot-lock style locking.
   563   */  
   564   return dotlockLockingStyle;
   565 }
   566 
   567 /* 
   568 ** Examines the f_fstypename entry in the statfs structure as returned by 
   569 ** stat() for the file system hosting the database file, assigns the 
   570 ** appropriate locking style based on it's value.  These values and 
   571 ** assignments are based on Darwin/OSX behavior and have not been tested on 
   572 ** other systems.
   573 */
   574 static sqlite3LockingStyle sqlite3DetectLockingStyle(
   575   const char *filePath, 
   576   int fd
   577 ){
   578 
   579 #ifdef SQLITE_FIXED_LOCKING_STYLE
   580   return (sqlite3LockingStyle)SQLITE_FIXED_LOCKING_STYLE;
   581 #else
   582   struct statfs fsInfo;
   583 
   584   if (statfs(filePath, &fsInfo) == -1)
   585     return sqlite3TestLockingStyle(filePath, fd);
   586   
   587   if (fsInfo.f_flags & MNT_RDONLY)
   588     return noLockingStyle;
   589   
   590   if( (!strcmp(fsInfo.f_fstypename, "hfs")) ||
   591     (!strcmp(fsInfo.f_fstypename, "ufs")) )
   592                 return posixLockingStyle;
   593   
   594   if(!strcmp(fsInfo.f_fstypename, "afpfs"))
   595     return afpLockingStyle;
   596   
   597   if(!strcmp(fsInfo.f_fstypename, "nfs")) 
   598     return sqlite3TestLockingStyle(filePath, fd);
   599   
   600   if(!strcmp(fsInfo.f_fstypename, "smbfs"))
   601     return flockLockingStyle;
   602   
   603   if(!strcmp(fsInfo.f_fstypename, "msdos"))
   604     return dotlockLockingStyle;
   605   
   606   if(!strcmp(fsInfo.f_fstypename, "webdav"))
   607     return unsupportedLockingStyle;
   608   
   609   return sqlite3TestLockingStyle(filePath, fd);  
   610 #endif /* SQLITE_FIXED_LOCKING_STYLE */
   611 }
   612 
   613 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
   614 
   615 /*
   616 ** Given a file descriptor, locate lockInfo and openCnt structures that
   617 ** describes that file descriptor.  Create new ones if necessary.  The
   618 ** return values might be uninitialized if an error occurs.
   619 **
   620 ** Return the number of errors.
   621 */
   622 static int findLockInfo(
   623   int fd,                      /* The file descriptor used in the key */
   624   struct lockInfo **ppLock,    /* Return the lockInfo structure here */
   625   struct openCnt **ppOpen      /* Return the openCnt structure here */
   626 ){
   627   int rc;
   628   struct lockKey key1;
   629   struct openKey key2;
   630   struct stat statbuf;
   631   struct lockInfo *pLock;
   632   struct openCnt *pOpen;
   633   rc = fstat(fd, &statbuf);
   634   if( rc!=0 ) return 1;
   635 
   636   memset(&key1, 0, sizeof(key1));
   637   key1.dev = statbuf.st_dev;
   638   key1.ino = statbuf.st_ino;
   639 #if SQLITE_THREADSAFE
   640   if( threadsOverrideEachOthersLocks<0 ){
   641     testThreadLockingBehavior(fd);
   642   }
   643   key1.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
   644 #endif
   645   memset(&key2, 0, sizeof(key2));
   646   key2.dev = statbuf.st_dev;
   647   key2.ino = statbuf.st_ino;
   648   pLock = (struct lockInfo*)sqlite3HashFind(&lockHash, &key1, sizeof(key1));
   649   if( pLock==0 ){
   650     struct lockInfo *pOld;
   651     pLock = sqlite3_malloc( sizeof(*pLock) );
   652     if( pLock==0 ){
   653       rc = 1;
   654       goto exit_findlockinfo;
   655     }
   656     pLock->key = key1;
   657     pLock->nRef = 1;
   658     pLock->cnt = 0;
   659     pLock->locktype = 0;
   660     pOld = sqlite3HashInsert(&lockHash, &pLock->key, sizeof(key1), pLock);
   661     if( pOld!=0 ){
   662       assert( pOld==pLock );
   663       sqlite3_free(pLock);
   664       rc = 1;
   665       goto exit_findlockinfo;
   666     }
   667   }else{
   668     pLock->nRef++;
   669   }
   670   *ppLock = pLock;
   671   if( ppOpen!=0 ){
   672     pOpen = (struct openCnt*)sqlite3HashFind(&openHash, &key2, sizeof(key2));
   673     if( pOpen==0 ){
   674       struct openCnt *pOld;
   675       pOpen = sqlite3_malloc( sizeof(*pOpen) );
   676       if( pOpen==0 ){
   677         releaseLockInfo(pLock);
   678         rc = 1;
   679         goto exit_findlockinfo;
   680       }
   681       pOpen->key = key2;
   682       pOpen->nRef = 1;
   683       pOpen->nLock = 0;
   684       pOpen->nPending = 0;
   685       pOpen->aPending = 0;
   686       pOld = sqlite3HashInsert(&openHash, &pOpen->key, sizeof(key2), pOpen);
   687       if( pOld!=0 ){
   688         assert( pOld==pOpen );
   689         sqlite3_free(pOpen);
   690         releaseLockInfo(pLock);
   691         rc = 1;
   692         goto exit_findlockinfo;
   693       }
   694     }else{
   695       pOpen->nRef++;
   696     }
   697     *ppOpen = pOpen;
   698   }
   699 
   700 exit_findlockinfo:
   701   return rc;
   702 }
   703 
   704 #ifdef SQLITE_DEBUG
   705 /*
   706 ** Helper function for printing out trace information from debugging
   707 ** binaries. This returns the string represetation of the supplied
   708 ** integer lock-type.
   709 */
   710 static const char *locktypeName(int locktype){
   711   switch( locktype ){
   712   case NO_LOCK: return "NONE";
   713   case SHARED_LOCK: return "SHARED";
   714   case RESERVED_LOCK: return "RESERVED";
   715   case PENDING_LOCK: return "PENDING";
   716   case EXCLUSIVE_LOCK: return "EXCLUSIVE";
   717   }
   718   return "ERROR";
   719 }
   720 #endif
   721 
   722 /*
   723 ** If we are currently in a different thread than the thread that the
   724 ** unixFile argument belongs to, then transfer ownership of the unixFile
   725 ** over to the current thread.
   726 **
   727 ** A unixFile is only owned by a thread on systems where one thread is
   728 ** unable to override locks created by a different thread.  RedHat9 is
   729 ** an example of such a system.
   730 **
   731 ** Ownership transfer is only allowed if the unixFile is currently unlocked.
   732 ** If the unixFile is locked and an ownership is wrong, then return
   733 ** SQLITE_MISUSE.  SQLITE_OK is returned if everything works.
   734 */
   735 #if SQLITE_THREADSAFE
   736 static int transferOwnership(unixFile *pFile){
   737   int rc;
   738   pthread_t hSelf;
   739   if( threadsOverrideEachOthersLocks ){
   740     /* Ownership transfers not needed on this system */
   741     return SQLITE_OK;
   742   }
   743   hSelf = pthread_self();
   744   if( pthread_equal(pFile->tid, hSelf) ){
   745     /* We are still in the same thread */
   746     OSTRACE1("No-transfer, same thread\n");
   747     return SQLITE_OK;
   748   }
   749   if( pFile->locktype!=NO_LOCK ){
   750     /* We cannot change ownership while we are holding a lock! */
   751     return SQLITE_MISUSE;
   752   }
   753   OSTRACE4("Transfer ownership of %d from %d to %d\n",
   754             pFile->h, pFile->tid, hSelf);
   755   pFile->tid = hSelf;
   756   if (pFile->pLock != NULL) {
   757     releaseLockInfo(pFile->pLock);
   758     rc = findLockInfo(pFile->h, &pFile->pLock, 0);
   759     OSTRACE5("LOCK    %d is now %s(%s,%d)\n", pFile->h,
   760            locktypeName(pFile->locktype),
   761            locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
   762     return rc;
   763   } else {
   764     return SQLITE_OK;
   765   }
   766 }
   767 #else
   768   /* On single-threaded builds, ownership transfer is a no-op */
   769 # define transferOwnership(X) SQLITE_OK
   770 #endif
   771 
   772 /*
   773 ** Seek to the offset passed as the second argument, then read cnt 
   774 ** bytes into pBuf. Return the number of bytes actually read.
   775 */
   776 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
   777   int got;
   778   i64 newOffset;
   779   TIMER_START;
   780 #if defined(USE_PREAD)
   781   got = pread(id->h, pBuf, cnt, offset);
   782   SimulateIOError( got = -1 );
   783 #elif defined(USE_PREAD64)
   784   got = pread64(id->h, pBuf, cnt, offset);
   785   SimulateIOError( got = -1 );
   786 #else
   787   newOffset = lseek(id->h, offset, SEEK_SET);
   788   SimulateIOError( newOffset-- );
   789   if( newOffset!=offset ){
   790     return -1;
   791   }
   792   got = read(id->h, pBuf, cnt);
   793 #endif
   794   TIMER_END;
   795   OSTRACE5("READ    %-3d %5d %7lld %d\n", id->h, got, offset, TIMER_ELAPSED);
   796   return got;
   797 }
   798 
   799 /*
   800 ** Read data from a file into a buffer.  Return SQLITE_OK if all
   801 ** bytes were read successfully and SQLITE_IOERR if anything goes
   802 ** wrong.
   803 */
   804 static int unixRead(
   805   sqlite3_file *id, 
   806   void *pBuf, 
   807   int amt,
   808   sqlite3_int64 offset
   809 ){
   810   int got;
   811   assert( id );
   812   got = seekAndRead((unixFile*)id, offset, pBuf, amt);
   813   if( got==amt ){
   814     return SQLITE_OK;
   815   }else if( got<0 ){
   816     return SQLITE_IOERR_READ;
   817   }else{
   818     memset(&((char*)pBuf)[got], 0, amt-got);
   819     return SQLITE_IOERR_SHORT_READ;
   820   }
   821 }
   822 
   823 /*
   824 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
   825 ** Return the number of bytes actually read.  Update the offset.
   826 */
   827 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
   828   int got;
   829   i64 newOffset;
   830   TIMER_START;
   831 #if defined(USE_PREAD)
   832   got = pwrite(id->h, pBuf, cnt, offset);
   833 #elif defined(USE_PREAD64)
   834   got = pwrite64(id->h, pBuf, cnt, offset);
   835 #else
   836   newOffset = lseek(id->h, offset, SEEK_SET);
   837   if( newOffset!=offset ){
   838     return -1;
   839   }
   840   got = write(id->h, pBuf, cnt);
   841 #endif
   842   TIMER_END;
   843   OSTRACE5("WRITE   %-3d %5d %7lld %d\n", id->h, got, offset, TIMER_ELAPSED);
   844   return got;
   845 }
   846 
   847 
   848 /*
   849 ** Write data from a buffer into a file.  Return SQLITE_OK on success
   850 ** or some other error code on failure.
   851 */
   852 static int unixWrite(
   853   sqlite3_file *id, 
   854   const void *pBuf, 
   855   int amt,
   856   sqlite3_int64 offset 
   857 ){
   858   int wrote = 0;
   859   assert( id );
   860   assert( amt>0 );
   861   while( amt>0 && (wrote = seekAndWrite((unixFile*)id, offset, pBuf, amt))>0 ){
   862     amt -= wrote;
   863     offset += wrote;
   864     pBuf = &((char*)pBuf)[wrote];
   865   }
   866   SimulateIOError(( wrote=(-1), amt=1 ));
   867   SimulateDiskfullError(( wrote=0, amt=1 ));
   868   if( amt>0 ){
   869     if( wrote<0 ){
   870       return SQLITE_IOERR_WRITE;
   871     }else{
   872       return SQLITE_FULL;
   873     }
   874   }
   875   return SQLITE_OK;
   876 }
   877 
   878 #ifdef SQLITE_TEST
   879 /*
   880 ** Count the number of fullsyncs and normal syncs.  This is used to test
   881 ** that syncs and fullsyncs are occuring at the right times.
   882 */
   883 int sqlite3_sync_count = 0;
   884 int sqlite3_fullsync_count = 0;
   885 #endif
   886 
   887 /*
   888 ** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
   889 ** Otherwise use fsync() in its place.
   890 */
   891 #ifndef HAVE_FDATASYNC
   892 # define fdatasync fsync
   893 #endif
   894 
   895 /*
   896 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
   897 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
   898 ** only available on Mac OS X.  But that could change.
   899 */
   900 #ifdef F_FULLFSYNC
   901 # define HAVE_FULLFSYNC 1
   902 #else
   903 # define HAVE_FULLFSYNC 0
   904 #endif
   905 
   906 
   907 /*
   908 ** The fsync() system call does not work as advertised on many
   909 ** unix systems.  The following procedure is an attempt to make
   910 ** it work better.
   911 **
   912 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
   913 ** for testing when we want to run through the test suite quickly.
   914 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
   915 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
   916 ** or power failure will likely corrupt the database file.
   917 */
   918 static int full_fsync(int fd, int fullSync, int dataOnly){
   919   int rc;
   920 
   921   /* Record the number of times that we do a normal fsync() and 
   922   ** FULLSYNC.  This is used during testing to verify that this procedure
   923   ** gets called with the correct arguments.
   924   */
   925 #ifdef SQLITE_TEST
   926   if( fullSync ) sqlite3_fullsync_count++;
   927   sqlite3_sync_count++;
   928 #endif
   929 
   930   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
   931   ** no-op
   932   */
   933 #ifdef SQLITE_NO_SYNC
   934   rc = SQLITE_OK;
   935 #else
   936 
   937 #if HAVE_FULLFSYNC
   938   if( fullSync ){
   939     rc = fcntl(fd, F_FULLFSYNC, 0);
   940   }else{
   941     rc = 1;
   942   }
   943   /* If the FULLFSYNC failed, fall back to attempting an fsync().
   944    * It shouldn't be possible for fullfsync to fail on the local 
   945    * file system (on OSX), so failure indicates that FULLFSYNC
   946    * isn't supported for this file system. So, attempt an fsync 
   947    * and (for now) ignore the overhead of a superfluous fcntl call.  
   948    * It'd be better to detect fullfsync support once and avoid 
   949    * the fcntl call every time sync is called.
   950    */
   951   if( rc ) rc = fsync(fd);
   952 
   953 #else 
   954   if( dataOnly ){
   955     rc = fdatasync(fd);
   956   }else{
   957     rc = fsync(fd);
   958   }
   959 #endif /* HAVE_FULLFSYNC */
   960 #endif /* defined(SQLITE_NO_SYNC) */
   961 
   962   return rc;
   963 }
   964 
   965 /*
   966 ** Make sure all writes to a particular file are committed to disk.
   967 **
   968 ** If dataOnly==0 then both the file itself and its metadata (file
   969 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
   970 ** file data is synced.
   971 **
   972 ** Under Unix, also make sure that the directory entry for the file
   973 ** has been created by fsync-ing the directory that contains the file.
   974 ** If we do not do this and we encounter a power failure, the directory
   975 ** entry for the journal might not exist after we reboot.  The next
   976 ** SQLite to access the file will not know that the journal exists (because
   977 ** the directory entry for the journal was never created) and the transaction
   978 ** will not roll back - possibly leading to database corruption.
   979 */
   980 static int unixSync(sqlite3_file *id, int flags){
   981   int rc;
   982   unixFile *pFile = (unixFile*)id;
   983 
   984   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
   985   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
   986 
   987   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
   988   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
   989       || (flags&0x0F)==SQLITE_SYNC_FULL
   990   );
   991 
   992   assert( pFile );
   993   OSTRACE2("SYNC    %-3d\n", pFile->h);
   994   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
   995   SimulateIOError( rc=1 );
   996   if( rc ){
   997     return SQLITE_IOERR_FSYNC;
   998   }
   999   if( pFile->dirfd>=0 ){
  1000     OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
  1001             HAVE_FULLFSYNC, isFullsync);
  1002 #ifndef SQLITE_DISABLE_DIRSYNC
  1003     /* The directory sync is only attempted if full_fsync is
  1004     ** turned off or unavailable.  If a full_fsync occurred above,
  1005     ** then the directory sync is superfluous.
  1006     */
  1007     if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
  1008        /*
  1009        ** We have received multiple reports of fsync() returning
  1010        ** errors when applied to directories on certain file systems.
  1011        ** A failed directory sync is not a big deal.  So it seems
  1012        ** better to ignore the error.  Ticket #1657
  1013        */
  1014        /* return SQLITE_IOERR; */
  1015     }
  1016 #endif
  1017     close(pFile->dirfd);  /* Only need to sync once, so close the directory */
  1018     pFile->dirfd = -1;    /* when we are done. */
  1019   }
  1020   return SQLITE_OK;
  1021 }
  1022 
  1023 /*
  1024 ** Truncate an open file to a specified size
  1025 */
  1026 static int unixTruncate(sqlite3_file *id, i64 nByte){
  1027   int rc;
  1028   assert( id );
  1029   rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
  1030   SimulateIOError( rc=1 );
  1031   if( rc ){
  1032     return SQLITE_IOERR_TRUNCATE;
  1033   }else{
  1034     return SQLITE_OK;
  1035   }
  1036 }
  1037 
  1038 /*
  1039 ** Determine the current size of a file in bytes
  1040 */
  1041 static int unixFileSize(sqlite3_file *id, i64 *pSize){
  1042   int rc;
  1043   struct stat buf;
  1044   assert( id );
  1045   rc = fstat(((unixFile*)id)->h, &buf);
  1046   SimulateIOError( rc=1 );
  1047   if( rc!=0 ){
  1048     return SQLITE_IOERR_FSTAT;
  1049   }
  1050   *pSize = buf.st_size;
  1051   return SQLITE_OK;
  1052 }
  1053 
  1054 /*
  1055 ** This routine checks if there is a RESERVED lock held on the specified
  1056 ** file by this or any other process. If such a lock is held, return
  1057 ** non-zero.  If the file is unlocked or holds only SHARED locks, then
  1058 ** return zero.
  1059 */
  1060 static int unixCheckReservedLock(sqlite3_file *id){
  1061   int r = 0;
  1062   unixFile *pFile = (unixFile*)id;
  1063 
  1064   assert( pFile );
  1065   enterMutex(); /* Because pFile->pLock is shared across threads */
  1066 
  1067   /* Check if a thread in this process holds such a lock */
  1068   if( pFile->pLock->locktype>SHARED_LOCK ){
  1069     r = 1;
  1070   }
  1071 
  1072   /* Otherwise see if some other process holds it.
  1073   */
  1074   if( !r ){
  1075     struct flock lock;
  1076     lock.l_whence = SEEK_SET;
  1077     lock.l_start = RESERVED_BYTE;
  1078     lock.l_len = 1;
  1079     lock.l_type = F_WRLCK;
  1080     fcntl(pFile->h, F_GETLK, &lock);
  1081     if( lock.l_type!=F_UNLCK ){
  1082       r = 1;
  1083     }
  1084   }
  1085   
  1086   leaveMutex();
  1087   OSTRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
  1088 
  1089   return r;
  1090 }
  1091 
  1092 /*
  1093 ** Lock the file with the lock specified by parameter locktype - one
  1094 ** of the following:
  1095 **
  1096 **     (1) SHARED_LOCK
  1097 **     (2) RESERVED_LOCK
  1098 **     (3) PENDING_LOCK
  1099 **     (4) EXCLUSIVE_LOCK
  1100 **
  1101 ** Sometimes when requesting one lock state, additional lock states
  1102 ** are inserted in between.  The locking might fail on one of the later
  1103 ** transitions leaving the lock state different from what it started but
  1104 ** still short of its goal.  The following chart shows the allowed
  1105 ** transitions and the inserted intermediate states:
  1106 **
  1107 **    UNLOCKED -> SHARED
  1108 **    SHARED -> RESERVED
  1109 **    SHARED -> (PENDING) -> EXCLUSIVE
  1110 **    RESERVED -> (PENDING) -> EXCLUSIVE
  1111 **    PENDING -> EXCLUSIVE
  1112 **
  1113 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
  1114 ** routine to lower a locking level.
  1115 */
  1116 static int unixLock(sqlite3_file *id, int locktype){
  1117   /* The following describes the implementation of the various locks and
  1118   ** lock transitions in terms of the POSIX advisory shared and exclusive
  1119   ** lock primitives (called read-locks and write-locks below, to avoid
  1120   ** confusion with SQLite lock names). The algorithms are complicated
  1121   ** slightly in order to be compatible with windows systems simultaneously
  1122   ** accessing the same database file, in case that is ever required.
  1123   **
  1124   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
  1125   ** byte', each single bytes at well known offsets, and the 'shared byte
  1126   ** range', a range of 510 bytes at a well known offset.
  1127   **
  1128   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
  1129   ** byte'.  If this is successful, a random byte from the 'shared byte
  1130   ** range' is read-locked and the lock on the 'pending byte' released.
  1131   **
  1132   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
  1133   ** A RESERVED lock is implemented by grabbing a write-lock on the
  1134   ** 'reserved byte'. 
  1135   **
  1136   ** A process may only obtain a PENDING lock after it has obtained a
  1137   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
  1138   ** on the 'pending byte'. This ensures that no new SHARED locks can be
  1139   ** obtained, but existing SHARED locks are allowed to persist. A process
  1140   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
  1141   ** This property is used by the algorithm for rolling back a journal file
  1142   ** after a crash.
  1143   **
  1144   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
  1145   ** implemented by obtaining a write-lock on the entire 'shared byte
  1146   ** range'. Since all other locks require a read-lock on one of the bytes
  1147   ** within this range, this ensures that no other locks are held on the
  1148   ** database. 
  1149   **
  1150   ** The reason a single byte cannot be used instead of the 'shared byte
  1151   ** range' is that some versions of windows do not support read-locks. By
  1152   ** locking a random byte from a range, concurrent SHARED locks may exist
  1153   ** even if the locking primitive used is always a write-lock.
  1154   */
  1155   int rc = SQLITE_OK;
  1156   unixFile *pFile = (unixFile*)id;
  1157   struct lockInfo *pLock = pFile->pLock;
  1158   struct flock lock;
  1159   int s;
  1160 
  1161   assert( pFile );
  1162   OSTRACE7("LOCK    %d %s was %s(%s,%d) pid=%d\n", pFile->h,
  1163       locktypeName(locktype), locktypeName(pFile->locktype),
  1164       locktypeName(pLock->locktype), pLock->cnt , getpid());
  1165 
  1166   /* If there is already a lock of this type or more restrictive on the
  1167   ** unixFile, do nothing. Don't use the end_lock: exit path, as
  1168   ** enterMutex() hasn't been called yet.
  1169   */
  1170   if( pFile->locktype>=locktype ){
  1171     OSTRACE3("LOCK    %d %s ok (already held)\n", pFile->h,
  1172             locktypeName(locktype));
  1173     return SQLITE_OK;
  1174   }
  1175 
  1176   /* Make sure the locking sequence is correct
  1177   */
  1178   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  1179   assert( locktype!=PENDING_LOCK );
  1180   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  1181 
  1182   /* This mutex is needed because pFile->pLock is shared across threads
  1183   */
  1184   enterMutex();
  1185 
  1186   /* Make sure the current thread owns the pFile.
  1187   */
  1188   rc = transferOwnership(pFile);
  1189   if( rc!=SQLITE_OK ){
  1190     leaveMutex();
  1191     return rc;
  1192   }
  1193   pLock = pFile->pLock;
  1194 
  1195   /* If some thread using this PID has a lock via a different unixFile*
  1196   ** handle that precludes the requested lock, return BUSY.
  1197   */
  1198   if( (pFile->locktype!=pLock->locktype && 
  1199           (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
  1200   ){
  1201     rc = SQLITE_BUSY;
  1202     goto end_lock;
  1203   }
  1204 
  1205   /* If a SHARED lock is requested, and some thread using this PID already
  1206   ** has a SHARED or RESERVED lock, then increment reference counts and
  1207   ** return SQLITE_OK.
  1208   */
  1209   if( locktype==SHARED_LOCK && 
  1210       (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
  1211     assert( locktype==SHARED_LOCK );
  1212     assert( pFile->locktype==0 );
  1213     assert( pLock->cnt>0 );
  1214     pFile->locktype = SHARED_LOCK;
  1215     pLock->cnt++;
  1216     pFile->pOpen->nLock++;
  1217     goto end_lock;
  1218   }
  1219 
  1220   lock.l_len = 1L;
  1221 
  1222   lock.l_whence = SEEK_SET;
  1223 
  1224   /* A PENDING lock is needed before acquiring a SHARED lock and before
  1225   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
  1226   ** be released.
  1227   */
  1228   if( locktype==SHARED_LOCK 
  1229       || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
  1230   ){
  1231     lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
  1232     lock.l_start = PENDING_BYTE;
  1233     s = fcntl(pFile->h, F_SETLK, &lock);
  1234     if( s==(-1) ){
  1235       rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
  1236       goto end_lock;
  1237     }
  1238   }
  1239 
  1240 
  1241   /* If control gets to this point, then actually go ahead and make
  1242   ** operating system calls for the specified lock.
  1243   */
  1244   if( locktype==SHARED_LOCK ){
  1245     assert( pLock->cnt==0 );
  1246     assert( pLock->locktype==0 );
  1247 
  1248     /* Now get the read-lock */
  1249     lock.l_start = SHARED_FIRST;
  1250     lock.l_len = SHARED_SIZE;
  1251     s = fcntl(pFile->h, F_SETLK, &lock);
  1252 
  1253     /* Drop the temporary PENDING lock */
  1254     lock.l_start = PENDING_BYTE;
  1255     lock.l_len = 1L;
  1256     lock.l_type = F_UNLCK;
  1257     if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
  1258       rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
  1259       goto end_lock;
  1260     }
  1261     if( s==(-1) ){
  1262       rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
  1263     }else{
  1264       pFile->locktype = SHARED_LOCK;
  1265       pFile->pOpen->nLock++;
  1266       pLock->cnt = 1;
  1267     }
  1268   }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
  1269     /* We are trying for an exclusive lock but another thread in this
  1270     ** same process is still holding a shared lock. */
  1271     rc = SQLITE_BUSY;
  1272   }else{
  1273     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
  1274     ** assumed that there is a SHARED or greater lock on the file
  1275     ** already.
  1276     */
  1277     assert( 0!=pFile->locktype );
  1278     lock.l_type = F_WRLCK;
  1279     switch( locktype ){
  1280       case RESERVED_LOCK:
  1281         lock.l_start = RESERVED_BYTE;
  1282         break;
  1283       case EXCLUSIVE_LOCK:
  1284         lock.l_start = SHARED_FIRST;
  1285         lock.l_len = SHARED_SIZE;
  1286         break;
  1287       default:
  1288         assert(0);
  1289     }
  1290     s = fcntl(pFile->h, F_SETLK, &lock);
  1291     if( s==(-1) ){
  1292       rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
  1293     }
  1294   }
  1295   
  1296   if( rc==SQLITE_OK ){
  1297     pFile->locktype = locktype;
  1298     pLock->locktype = locktype;
  1299   }else if( locktype==EXCLUSIVE_LOCK ){
  1300     pFile->locktype = PENDING_LOCK;
  1301     pLock->locktype = PENDING_LOCK;
  1302   }
  1303 
  1304 end_lock:
  1305   leaveMutex();
  1306   OSTRACE4("LOCK    %d %s %s\n", pFile->h, locktypeName(locktype), 
  1307       rc==SQLITE_OK ? "ok" : "failed");
  1308   return rc;
  1309 }
  1310 
  1311 /*
  1312 ** Lower the locking level on file descriptor pFile to locktype.  locktype
  1313 ** must be either NO_LOCK or SHARED_LOCK.
  1314 **
  1315 ** If the locking level of the file descriptor is already at or below
  1316 ** the requested locking level, this routine is a no-op.
  1317 */
  1318 static int unixUnlock(sqlite3_file *id, int locktype){
  1319   struct lockInfo *pLock;
  1320   struct flock lock;
  1321   int rc = SQLITE_OK;
  1322   unixFile *pFile = (unixFile*)id;
  1323 
  1324   assert( pFile );
  1325   OSTRACE7("UNLOCK  %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
  1326       pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
  1327 
  1328   assert( locktype<=SHARED_LOCK );
  1329   if( pFile->locktype<=locktype ){
  1330     return SQLITE_OK;
  1331   }
  1332   if( CHECK_THREADID(pFile) ){
  1333     return SQLITE_MISUSE;
  1334   }
  1335   enterMutex();
  1336   pLock = pFile->pLock;
  1337   assert( pLock->cnt!=0 );
  1338   if( pFile->locktype>SHARED_LOCK ){
  1339     assert( pLock->locktype==pFile->locktype );
  1340     if( locktype==SHARED_LOCK ){
  1341       lock.l_type = F_RDLCK;
  1342       lock.l_whence = SEEK_SET;
  1343       lock.l_start = SHARED_FIRST;
  1344       lock.l_len = SHARED_SIZE;
  1345       if( fcntl(pFile->h, F_SETLK, &lock)==(-1) ){
  1346         /* This should never happen */
  1347         rc = SQLITE_IOERR_RDLOCK;
  1348       }
  1349     }
  1350     lock.l_type = F_UNLCK;
  1351     lock.l_whence = SEEK_SET;
  1352     lock.l_start = PENDING_BYTE;
  1353     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
  1354     if( fcntl(pFile->h, F_SETLK, &lock)!=(-1) ){
  1355       pLock->locktype = SHARED_LOCK;
  1356     }else{
  1357       rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
  1358     }
  1359   }
  1360   if( locktype==NO_LOCK ){
  1361     struct openCnt *pOpen;
  1362 
  1363     /* Decrement the shared lock counter.  Release the lock using an
  1364     ** OS call only when all threads in this same process have released
  1365     ** the lock.
  1366     */
  1367     pLock->cnt--;
  1368     if( pLock->cnt==0 ){
  1369       lock.l_type = F_UNLCK;
  1370       lock.l_whence = SEEK_SET;
  1371       lock.l_start = lock.l_len = 0L;
  1372       if( fcntl(pFile->h, F_SETLK, &lock)!=(-1) ){
  1373         pLock->locktype = NO_LOCK;
  1374       }else{
  1375         rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
  1376       }
  1377     }
  1378 
  1379     /* Decrement the count of locks against this same file.  When the
  1380     ** count reaches zero, close any other file descriptors whose close
  1381     ** was deferred because of outstanding locks.
  1382     */
  1383     pOpen = pFile->pOpen;
  1384     pOpen->nLock--;
  1385     assert( pOpen->nLock>=0 );
  1386     if( pOpen->nLock==0 && pOpen->nPending>0 ){
  1387       int i;
  1388       for(i=0; i<pOpen->nPending; i++){
  1389         close(pOpen->aPending[i]);
  1390       }
  1391       free(pOpen->aPending);
  1392       pOpen->nPending = 0;
  1393       pOpen->aPending = 0;
  1394     }
  1395   }
  1396   leaveMutex();
  1397   pFile->locktype = locktype;
  1398   return rc;
  1399 }
  1400 
  1401 /*
  1402 ** Close a file.
  1403 */
  1404 static int unixClose(sqlite3_file *id){
  1405   unixFile *pFile = (unixFile *)id;
  1406   if( !pFile ) return SQLITE_OK;
  1407   unixUnlock(id, NO_LOCK);
  1408   if( pFile->dirfd>=0 ) close(pFile->dirfd);
  1409   pFile->dirfd = -1;
  1410   enterMutex();
  1411 
  1412   if( pFile->pOpen->nLock ){
  1413     /* If there are outstanding locks, do not actually close the file just
  1414     ** yet because that would clear those locks.  Instead, add the file
  1415     ** descriptor to pOpen->aPending.  It will be automatically closed when
  1416     ** the last lock is cleared.
  1417     */
  1418     int *aNew;
  1419     struct openCnt *pOpen = pFile->pOpen;
  1420     aNew = realloc( pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
  1421     if( aNew==0 ){
  1422       /* If a malloc fails, just leak the file descriptor */
  1423     }else{
  1424       pOpen->aPending = aNew;
  1425       pOpen->aPending[pOpen->nPending] = pFile->h;
  1426       pOpen->nPending++;
  1427     }
  1428   }else{
  1429     /* There are no outstanding locks so we can close the file immediately */
  1430     close(pFile->h);
  1431   }
  1432   releaseLockInfo(pFile->pLock);
  1433   releaseOpenCnt(pFile->pOpen);
  1434 
  1435   leaveMutex();
  1436   OSTRACE2("CLOSE   %-3d\n", pFile->h);
  1437   OpenCounter(-1);
  1438   memset(pFile, 0, sizeof(unixFile));
  1439   return SQLITE_OK;
  1440 }
  1441 
  1442 
  1443 #ifdef SQLITE_ENABLE_LOCKING_STYLE
  1444 #pragma mark AFP Support
  1445 
  1446 /*
  1447  ** The afpLockingContext structure contains all afp lock specific state
  1448  */
  1449 typedef struct afpLockingContext afpLockingContext;
  1450 struct afpLockingContext {
  1451   unsigned long long sharedLockByte;
  1452   char *filePath;
  1453 };
  1454 
  1455 struct ByteRangeLockPB2
  1456 {
  1457   unsigned long long offset;        /* offset to first byte to lock */
  1458   unsigned long long length;        /* nbr of bytes to lock */
  1459   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
  1460   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
  1461   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
  1462   int fd;                           /* file desc to assoc this lock with */
  1463 };
  1464 
  1465 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
  1466 
  1467 /* 
  1468 ** Return 0 on success, 1 on failure.  To match the behavior of the 
  1469 ** normal posix file locking (used in unixLock for example), we should 
  1470 ** provide 'richer' return codes - specifically to differentiate between
  1471 ** 'file busy' and 'file system error' results.
  1472 */
  1473 static int _AFPFSSetLock(
  1474   const char *path, 
  1475   int fd, 
  1476   unsigned long long offset, 
  1477   unsigned long long length, 
  1478   int setLockFlag
  1479 ){
  1480   struct ByteRangeLockPB2       pb;
  1481   int                     err;
  1482   
  1483   pb.unLockFlag = setLockFlag ? 0 : 1;
  1484   pb.startEndFlag = 0;
  1485   pb.offset = offset;
  1486   pb.length = length; 
  1487   pb.fd = fd;
  1488   OSTRACE5("AFPLOCK setting lock %s for %d in range %llx:%llx\n", 
  1489     (setLockFlag?"ON":"OFF"), fd, offset, length);
  1490   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
  1491   if ( err==-1 ) {
  1492     OSTRACE4("AFPLOCK failed to fsctl() '%s' %d %s\n", path, errno, 
  1493       strerror(errno));
  1494     return 1; /* error */
  1495   } else {
  1496     return 0;
  1497   }
  1498 }
  1499 
  1500 /*
  1501  ** This routine checks if there is a RESERVED lock held on the specified
  1502  ** file by this or any other process. If such a lock is held, return
  1503  ** non-zero.  If the file is unlocked or holds only SHARED locks, then
  1504  ** return zero.
  1505  */
  1506 static int afpUnixCheckReservedLock(sqlite3_file *id){
  1507   int r = 0;
  1508   unixFile *pFile = (unixFile*)id;
  1509   
  1510   assert( pFile ); 
  1511   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  1512   
  1513   /* Check if a thread in this process holds such a lock */
  1514   if( pFile->locktype>SHARED_LOCK ){
  1515     r = 1;
  1516   }
  1517   
  1518   /* Otherwise see if some other process holds it.
  1519    */
  1520   if ( !r ) {
  1521     /* lock the byte */
  1522     int failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);  
  1523     if (failed) {
  1524       /* if we failed to get the lock then someone else must have it */
  1525       r = 1;
  1526     } else {
  1527       /* if we succeeded in taking the reserved lock, unlock it to restore
  1528       ** the original state */
  1529       _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0);
  1530     }
  1531   }
  1532   OSTRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
  1533   
  1534   return r;
  1535 }
  1536 
  1537 /* AFP-style locking following the behavior of unixLock, see the unixLock 
  1538 ** function comments for details of lock management. */
  1539 static int afpUnixLock(sqlite3_file *id, int locktype)
  1540 {
  1541   int rc = SQLITE_OK;
  1542   unixFile *pFile = (unixFile*)id;
  1543   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  1544   int gotPendingLock = 0;
  1545   
  1546   assert( pFile );
  1547   OSTRACE5("LOCK    %d %s was %s pid=%d\n", pFile->h,
  1548          locktypeName(locktype), locktypeName(pFile->locktype), getpid());  
  1549   /* If there is already a lock of this type or more restrictive on the
  1550     ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
  1551     ** enterMutex() hasn't been called yet.
  1552     */
  1553   if( pFile->locktype>=locktype ){
  1554     OSTRACE3("LOCK    %d %s ok (already held)\n", pFile->h,
  1555            locktypeName(locktype));
  1556     return SQLITE_OK;
  1557   }
  1558 
  1559   /* Make sure the locking sequence is correct
  1560     */
  1561   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  1562   assert( locktype!=PENDING_LOCK );
  1563   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  1564   
  1565   /* This mutex is needed because pFile->pLock is shared across threads
  1566     */
  1567   enterMutex();
  1568 
  1569   /* Make sure the current thread owns the pFile.
  1570     */
  1571   rc = transferOwnership(pFile);
  1572   if( rc!=SQLITE_OK ){
  1573     leaveMutex();
  1574     return rc;
  1575   }
  1576     
  1577   /* A PENDING lock is needed before acquiring a SHARED lock and before
  1578     ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
  1579     ** be released.
  1580     */
  1581   if( locktype==SHARED_LOCK 
  1582       || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
  1583       ){
  1584     int failed = _AFPFSSetLock(context->filePath, pFile->h, 
  1585       PENDING_BYTE, 1, 1);
  1586     if (failed) {
  1587       rc = SQLITE_BUSY;
  1588       goto afp_end_lock;
  1589     }
  1590   }
  1591   
  1592   /* If control gets to this point, then actually go ahead and make
  1593     ** operating system calls for the specified lock.
  1594     */
  1595   if( locktype==SHARED_LOCK ){
  1596     int lk, failed;
  1597     int tries = 0;
  1598     
  1599     /* Now get the read-lock */
  1600     /* note that the quality of the randomness doesn't matter that much */
  1601     lk = random(); 
  1602     context->sharedLockByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
  1603     failed = _AFPFSSetLock(context->filePath, pFile->h, 
  1604       SHARED_FIRST+context->sharedLockByte, 1, 1);
  1605     
  1606     /* Drop the temporary PENDING lock */
  1607     if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)) {
  1608       rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
  1609       goto afp_end_lock;
  1610     }
  1611     
  1612     if( failed ){
  1613       rc = SQLITE_BUSY;
  1614     } else {
  1615       pFile->locktype = SHARED_LOCK;
  1616     }
  1617   }else{
  1618     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
  1619     ** assumed that there is a SHARED or greater lock on the file
  1620     ** already.
  1621     */
  1622     int failed = 0;
  1623     assert( 0!=pFile->locktype );
  1624     if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
  1625         /* Acquire a RESERVED lock */
  1626         failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);
  1627     }
  1628     if (!failed && locktype == EXCLUSIVE_LOCK) {
  1629       /* Acquire an EXCLUSIVE lock */
  1630         
  1631       /* Remove the shared lock before trying the range.  we'll need to 
  1632       ** reestablish the shared lock if we can't get the  afpUnixUnlock
  1633       */
  1634       if (!_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
  1635                          context->sharedLockByte, 1, 0)) {
  1636         /* now attemmpt to get the exclusive lock range */
  1637         failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST, 
  1638                                SHARED_SIZE, 1);
  1639         if (failed && _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
  1640                                     context->sharedLockByte, 1, 1)) {
  1641           rc = SQLITE_IOERR_RDLOCK; /* this should never happen */
  1642         }
  1643       } else {
  1644         /* */
  1645         rc = SQLITE_IOERR_UNLOCK; /* this should never happen */
  1646       }
  1647     }
  1648     if( failed && rc == SQLITE_OK){
  1649       rc = SQLITE_BUSY;
  1650     }
  1651   }
  1652   
  1653   if( rc==SQLITE_OK ){
  1654     pFile->locktype = locktype;
  1655   }else if( locktype==EXCLUSIVE_LOCK ){
  1656     pFile->locktype = PENDING_LOCK;
  1657   }
  1658   
  1659 afp_end_lock:
  1660     leaveMutex();
  1661   OSTRACE4("LOCK    %d %s %s\n", pFile->h, locktypeName(locktype), 
  1662          rc==SQLITE_OK ? "ok" : "failed");
  1663   return rc;
  1664 }
  1665 
  1666 /*
  1667  ** Lower the locking level on file descriptor pFile to locktype.  locktype
  1668  ** must be either NO_LOCK or SHARED_LOCK.
  1669  **
  1670  ** If the locking level of the file descriptor is already at or below
  1671  ** the requested locking level, this routine is a no-op.
  1672  */
  1673 static int afpUnixUnlock(sqlite3_file *id, int locktype) {
  1674   struct flock lock;
  1675   int rc = SQLITE_OK;
  1676   unixFile *pFile = (unixFile*)id;
  1677   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  1678 
  1679   assert( pFile );
  1680   OSTRACE5("UNLOCK  %d %d was %d pid=%d\n", pFile->h, locktype,
  1681          pFile->locktype, getpid());
  1682   
  1683   assert( locktype<=SHARED_LOCK );
  1684   if( pFile->locktype<=locktype ){
  1685     return SQLITE_OK;
  1686   }
  1687   if( CHECK_THREADID(pFile) ){
  1688     return SQLITE_MISUSE;
  1689   }
  1690   enterMutex();
  1691   if( pFile->locktype>SHARED_LOCK ){
  1692     if( locktype==SHARED_LOCK ){
  1693       int failed = 0;
  1694 
  1695       /* unlock the exclusive range - then re-establish the shared lock */
  1696       if (pFile->locktype==EXCLUSIVE_LOCK) {
  1697         failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST, 
  1698                                  SHARED_SIZE, 0);
  1699         if (!failed) {
  1700           /* successfully removed the exclusive lock */
  1701           if (_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST+
  1702                             context->sharedLockByte, 1, 1)) {
  1703             /* failed to re-establish our shared lock */
  1704             rc = SQLITE_IOERR_RDLOCK; /* This should never happen */
  1705           }
  1706         } else {
  1707           /* This should never happen - failed to unlock the exclusive range */
  1708           rc = SQLITE_IOERR_UNLOCK;
  1709         } 
  1710       }
  1711     }
  1712     if (rc == SQLITE_OK && pFile->locktype>=PENDING_LOCK) {
  1713       if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)){
  1714         /* failed to release the pending lock */
  1715         rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
  1716       }
  1717     } 
  1718     if (rc == SQLITE_OK && pFile->locktype>=RESERVED_LOCK) {
  1719       if (_AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0)) {
  1720         /* failed to release the reserved lock */
  1721         rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
  1722       }
  1723     } 
  1724   }
  1725   if( locktype==NO_LOCK ){
  1726     int failed = _AFPFSSetLock(context->filePath, pFile->h, 
  1727                                SHARED_FIRST + context->sharedLockByte, 1, 0);
  1728     if (failed) {
  1729       rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
  1730     }
  1731   }
  1732   if (rc == SQLITE_OK)
  1733     pFile->locktype = locktype;
  1734   leaveMutex();
  1735   return rc;
  1736 }
  1737 
  1738 /*
  1739  ** Close a file & cleanup AFP specific locking context 
  1740  */
  1741 static int afpUnixClose(sqlite3_file *id) {
  1742   unixFile *pFile = (unixFile*)pId;
  1743 
  1744   if( !pFile ) return SQLITE_OK;
  1745   afpUnixUnlock(*pId, NO_LOCK);
  1746   /* free the AFP locking structure */
  1747   if (pFile->lockingContext != NULL) {
  1748     if (((afpLockingContext *)pFile->lockingContext)->filePath != NULL)
  1749       sqlite3_free(((afpLockingContext*)pFile->lockingContext)->filePath);
  1750     sqlite3_free(pFile->lockingContext);
  1751   }
  1752 
  1753   if( pFile->dirfd>=0 ) close(pFile->dirfd);
  1754   pFile->dirfd = -1;
  1755   close(pFile->h);
  1756   OSTRACE2("CLOSE   %-3d\n", pFile->h);
  1757   OpenCounter(-1);
  1758   return SQLITE_OK;
  1759 }
  1760 
  1761 
  1762 #pragma mark flock() style locking
  1763 
  1764 /*
  1765  ** The flockLockingContext is not used
  1766  */
  1767 typedef void flockLockingContext;
  1768 
  1769 static int flockUnixCheckReservedLock(sqlite3_file *id) {
  1770   unixFile *pFile = (unixFile*)id;
  1771   
  1772   if (pFile->locktype == RESERVED_LOCK) {
  1773     return 1; /* already have a reserved lock */
  1774   } else {
  1775     /* attempt to get the lock */
  1776     int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
  1777     if (!rc) {
  1778       /* got the lock, unlock it */
  1779       flock(pFile->h, LOCK_UN);
  1780       return 0;  /* no one has it reserved */
  1781     }
  1782     return 1; /* someone else might have it reserved */
  1783   }
  1784 }
  1785 
  1786 static int flockUnixLock(sqlite3_file *id, int locktype) {
  1787   unixFile *pFile = (unixFile*)id;
  1788   
  1789   /* if we already have a lock, it is exclusive.  
  1790   ** Just adjust level and punt on outta here. */
  1791   if (pFile->locktype > NO_LOCK) {
  1792     pFile->locktype = locktype;
  1793     return SQLITE_OK;
  1794   }
  1795   
  1796   /* grab an exclusive lock */
  1797   int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
  1798   if (rc) {
  1799     /* didn't get, must be busy */
  1800     return SQLITE_BUSY;
  1801   } else {
  1802     /* got it, set the type and return ok */
  1803     pFile->locktype = locktype;
  1804     return SQLITE_OK;
  1805   }
  1806 }
  1807 
  1808 static int flockUnixUnlock(sqlite3_file *id, int locktype) {
  1809   unixFile *pFile = (unixFile*)id;
  1810   
  1811   assert( locktype<=SHARED_LOCK );
  1812   
  1813   /* no-op if possible */
  1814   if( pFile->locktype==locktype ){
  1815     return SQLITE_OK;
  1816   }
  1817   
  1818   /* shared can just be set because we always have an exclusive */
  1819   if (locktype==SHARED_LOCK) {
  1820     pFile->locktype = locktype;
  1821     return SQLITE_OK;
  1822   }
  1823   
  1824   /* no, really, unlock. */
  1825   int rc = flock(pFile->h, LOCK_UN);
  1826   if (rc)
  1827     return SQLITE_IOERR_UNLOCK;
  1828   else {
  1829     pFile->locktype = NO_LOCK;
  1830     return SQLITE_OK;
  1831   }
  1832 }
  1833 
  1834 /*
  1835  ** Close a file.
  1836  */
  1837 static int flockUnixClose(sqlite3_file *pId) {
  1838   unixFile *pFile = (unixFile*)*pId;
  1839   
  1840   if( !pFile ) return SQLITE_OK;
  1841   flockUnixUnlock(*pId, NO_LOCK);
  1842   
  1843   if( pFile->dirfd>=0 ) close(pFile->dirfd);
  1844   pFile->dirfd = -1;
  1845   enterMutex();
  1846   
  1847   close(pFile->h);  
  1848   leaveMutex();
  1849   OSTRACE2("CLOSE   %-3d\n", pFile->h);
  1850   OpenCounter(-1);
  1851   return SQLITE_OK;
  1852 }
  1853 
  1854 #pragma mark Old-School .lock file based locking
  1855 
  1856 /*
  1857  ** The dotlockLockingContext structure contains all dotlock (.lock) lock
  1858  ** specific state
  1859  */
  1860 typedef struct dotlockLockingContext dotlockLockingContext;
  1861 struct dotlockLockingContext {
  1862   char *lockPath;
  1863 };
  1864 
  1865 
  1866 static int dotlockUnixCheckReservedLock(sqlite3_file *id) {
  1867   unixFile *pFile = (unixFile*)id;
  1868   dotlockLockingContext *context = 
  1869     (dotlockLockingContext *) pFile->lockingContext;
  1870   
  1871   if (pFile->locktype == RESERVED_LOCK) {
  1872     return 1; /* already have a reserved lock */
  1873   } else {
  1874     struct stat statBuf;
  1875     if (lstat(context->lockPath,&statBuf) == 0)
  1876       /* file exists, someone else has the lock */
  1877       return 1;
  1878     else
  1879       /* file does not exist, we could have it if we want it */
  1880       return 0;
  1881   }
  1882 }
  1883 
  1884 static int dotlockUnixLock(sqlite3_file *id, int locktype) {
  1885   unixFile *pFile = (unixFile*)id;
  1886   dotlockLockingContext *context = 
  1887     (dotlockLockingContext *) pFile->lockingContext;
  1888   
  1889   /* if we already have a lock, it is exclusive.  
  1890   ** Just adjust level and punt on outta here. */
  1891   if (pFile->locktype > NO_LOCK) {
  1892     pFile->locktype = locktype;
  1893     
  1894     /* Always update the timestamp on the old file */
  1895     utimes(context->lockPath,NULL);
  1896     return SQLITE_OK;
  1897   }
  1898   
  1899   /* check to see if lock file already exists */
  1900   struct stat statBuf;
  1901   if (lstat(context->lockPath,&statBuf) == 0){
  1902     return SQLITE_BUSY; /* it does, busy */
  1903   }
  1904   
  1905   /* grab an exclusive lock */
  1906   int fd = open(context->lockPath,O_RDONLY|O_CREAT|O_EXCL,0600);
  1907   if (fd < 0) {
  1908     /* failed to open/create the file, someone else may have stolen the lock */
  1909     return SQLITE_BUSY; 
  1910   }
  1911   close(fd);
  1912   
  1913   /* got it, set the type and return ok */
  1914   pFile->locktype = locktype;
  1915   return SQLITE_OK;
  1916 }
  1917 
  1918 static int dotlockUnixUnlock(sqlite3_file *id, int locktype) {
  1919   unixFile *pFile = (unixFile*)id;
  1920   dotlockLockingContext *context = 
  1921     (dotlockLockingContext *) pFile->lockingContext;
  1922   
  1923   assert( locktype<=SHARED_LOCK );
  1924   
  1925   /* no-op if possible */
  1926   if( pFile->locktype==locktype ){
  1927     return SQLITE_OK;
  1928   }
  1929   
  1930   /* shared can just be set because we always have an exclusive */
  1931   if (locktype==SHARED_LOCK) {
  1932     pFile->locktype = locktype;
  1933     return SQLITE_OK;
  1934   }
  1935   
  1936   /* no, really, unlock. */
  1937   unlink(context->lockPath);
  1938   pFile->locktype = NO_LOCK;
  1939   return SQLITE_OK;
  1940 }
  1941 
  1942 /*
  1943  ** Close a file.
  1944  */
  1945 static int dotlockUnixClose(sqlite3_file *id) {
  1946   unixFile *pFile = (unixFile*)id;
  1947   
  1948   if( !pFile ) return SQLITE_OK;
  1949   dotlockUnixUnlock(*pId, NO_LOCK);
  1950   /* free the dotlock locking structure */
  1951   if (pFile->lockingContext != NULL) {
  1952     if (((dotlockLockingContext *)pFile->lockingContext)->lockPath != NULL)
  1953       sqlite3_free( ( (dotlockLockingContext *)
  1954         pFile->lockingContext)->lockPath);
  1955     sqlite3_free(pFile->lockingContext);
  1956   }
  1957   
  1958   if( pFile->dirfd>=0 ) close(pFile->dirfd);
  1959   pFile->dirfd = -1;
  1960   enterMutex();
  1961   
  1962   close(pFile->h);
  1963   
  1964   leaveMutex();
  1965   OSTRACE2("CLOSE   %-3d\n", pFile->h);
  1966   OpenCounter(-1);
  1967   return SQLITE_OK;
  1968 }
  1969 
  1970 
  1971 #pragma mark No locking
  1972 
  1973 /*
  1974  ** The nolockLockingContext is void
  1975  */
  1976 typedef void nolockLockingContext;
  1977 
  1978 static int nolockUnixCheckReservedLock(sqlite3_file *id) {
  1979   return 0;
  1980 }
  1981 
  1982 static int nolockUnixLock(sqlite3_file *id, int locktype) {
  1983   return SQLITE_OK;
  1984 }
  1985 
  1986 static int nolockUnixUnlock(sqlite3_file *id, int locktype) {
  1987   return SQLITE_OK;
  1988 }
  1989 
  1990 /*
  1991  ** Close a file.
  1992  */
  1993 static int nolockUnixClose(sqlite3_file *id) {
  1994   unixFile *pFile = (unixFile*)id;
  1995   
  1996   if( !pFile ) return SQLITE_OK;
  1997   if( pFile->dirfd>=0 ) close(pFile->dirfd);
  1998   pFile->dirfd = -1;
  1999   enterMutex();
  2000   
  2001   close(pFile->h);
  2002   
  2003   leaveMutex();
  2004   OSTRACE2("CLOSE   %-3d\n", pFile->h);
  2005   OpenCounter(-1);
  2006   return SQLITE_OK;
  2007 }
  2008 
  2009 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  2010 
  2011 
  2012 /*
  2013 ** Information and control of an open file handle.
  2014 */
  2015 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
  2016   switch( op ){
  2017     case SQLITE_FCNTL_LOCKSTATE: {
  2018       *(int*)pArg = ((unixFile*)id)->locktype;
  2019       return SQLITE_OK;
  2020     }
  2021   }
  2022   return SQLITE_ERROR;
  2023 }
  2024 
  2025 /*
  2026 ** Return the sector size in bytes of the underlying block device for
  2027 ** the specified file. This is almost always 512 bytes, but may be
  2028 ** larger for some devices.
  2029 **
  2030 ** SQLite code assumes this function cannot fail. It also assumes that
  2031 ** if two files are created in the same file-system directory (i.e.
  2032 ** a database and it's journal file) that the sector size will be the
  2033 ** same for both.
  2034 */
  2035 static int unixSectorSize(sqlite3_file *id){
  2036   return SQLITE_DEFAULT_SECTOR_SIZE;
  2037 }
  2038 
  2039 /*
  2040 ** Return the device characteristics for the file. This is always 0.
  2041 */
  2042 static int unixDeviceCharacteristics(sqlite3_file *id){
  2043   return 0;
  2044 }
  2045 
  2046 /*
  2047 ** This vector defines all the methods that can operate on an sqlite3_file
  2048 ** for unix.
  2049 */
  2050 static const sqlite3_io_methods sqlite3UnixIoMethod = {
  2051   1,                        /* iVersion */
  2052   unixClose,
  2053   unixRead,
  2054   unixWrite,
  2055   unixTruncate,
  2056   unixSync,
  2057   unixFileSize,
  2058   unixLock,
  2059   unixUnlock,
  2060   unixCheckReservedLock,
  2061   unixFileControl,
  2062   unixSectorSize,
  2063   unixDeviceCharacteristics
  2064 };
  2065 
  2066 #ifdef SQLITE_ENABLE_LOCKING_STYLE
  2067 /*
  2068 ** This vector defines all the methods that can operate on an sqlite3_file
  2069 ** for unix with AFP style file locking.
  2070 */
  2071 static const sqlite3_io_methods sqlite3AFPLockingUnixIoMethod = {
  2072   1,                        /* iVersion */
  2073   unixClose,
  2074   unixRead,
  2075   unixWrite,
  2076   unixTruncate,
  2077   unixSync,
  2078   unixFileSize,
  2079   afpUnixLock,
  2080   afpUnixUnlock,
  2081   afpUnixCheckReservedLock,
  2082   unixFileControl,
  2083   unixSectorSize,
  2084   unixDeviceCharacteristics
  2085 };
  2086 
  2087 /*
  2088 ** This vector defines all the methods that can operate on an sqlite3_file
  2089 ** for unix with flock() style file locking.
  2090 */
  2091 static const sqlite3_io_methods sqlite3FlockLockingUnixIoMethod = {
  2092   1,                        /* iVersion */
  2093   flockUnixClose,
  2094   unixRead,
  2095   unixWrite,
  2096   unixTruncate,
  2097   unixSync,
  2098   unixFileSize,
  2099   flockUnixLock,
  2100   flockUnixUnlock,
  2101   flockUnixCheckReservedLock,
  2102   unixFileControl,
  2103   unixSectorSize,
  2104   unixDeviceCharacteristics
  2105 };
  2106 
  2107 /*
  2108 ** This vector defines all the methods that can operate on an sqlite3_file
  2109 ** for unix with dotlock style file locking.
  2110 */
  2111 static const sqlite3_io_methods sqlite3DotlockLockingUnixIoMethod = {
  2112   1,                        /* iVersion */
  2113   dotlockUnixClose,
  2114   unixRead,
  2115   unixWrite,
  2116   unixTruncate,
  2117   unixSync,
  2118   unixFileSize,
  2119   dotlockUnixLock,
  2120   dotlockUnixUnlock,
  2121   dotlockUnixCheckReservedLock,
  2122   unixFileControl,
  2123   unixSectorSize,
  2124   unixDeviceCharacteristics
  2125 };
  2126 
  2127 /*
  2128 ** This vector defines all the methods that can operate on an sqlite3_file
  2129 ** for unix with dotlock style file locking.
  2130 */
  2131 static const sqlite3_io_methods sqlite3NolockLockingUnixIoMethod = {
  2132   1,                        /* iVersion */
  2133   nolockUnixClose,
  2134   unixRead,
  2135   unixWrite,
  2136   unixTruncate,
  2137   unixSync,
  2138   unixFileSize,
  2139   nolockUnixLock,
  2140   nolockUnixUnlock,
  2141   nolockUnixCheckReservedLock,
  2142   unixFileControl,
  2143   unixSectorSize,
  2144   unixDeviceCharacteristics
  2145 };
  2146 
  2147 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  2148 
  2149 /*
  2150 ** Allocate memory for a new unixFile and initialize that unixFile.
  2151 ** Write a pointer to the new unixFile into *pId.
  2152 ** If we run out of memory, close the file and return an error.
  2153 */
  2154 #ifdef SQLITE_ENABLE_LOCKING_STYLE
  2155 /* 
  2156 ** When locking extensions are enabled, the filepath and locking style 
  2157 ** are needed to determine the unixFile pMethod to use for locking operations.
  2158 ** The locking-style specific lockingContext data structure is created 
  2159 ** and assigned here also.
  2160 */
  2161 static int fillInUnixFile(
  2162   int h,                  /* Open file descriptor of file being opened */
  2163   int dirfd,              /* Directory file descriptor */
  2164   sqlite3_file *pId,      /* Write completed initialization here */
  2165   const char *zFilename,  /* Name of the file being opened */
  2166 ){
  2167   sqlite3LockingStyle lockingStyle;
  2168   unixFile *pNew = (unixFile *)pId;
  2169   int rc;
  2170 
  2171   memset(pNew, 0, sizeof(unixFile));
  2172   lockingStyle = sqlite3DetectLockingStyle(zFilename, h);
  2173   if ( lockingStyle == posixLockingStyle ) {
  2174     enterMutex();
  2175     rc = findLockInfo(h, &pNew->pLock, &pNew->pOpen);
  2176     leaveMutex();
  2177     if( rc ){
  2178       close(h);
  2179       unlink(zFilename);
  2180       return SQLITE_NOMEM;
  2181     }
  2182   } else {
  2183     /*  pLock and pOpen are only used for posix advisory locking */
  2184     pNew->pLock = NULL;
  2185     pNew->pOpen = NULL;
  2186   }
  2187   pNew->dirfd = -1;
  2188   pNew->h = h;
  2189   SET_THREADID(pNew);
  2190   pNew = sqlite3_malloc( sizeof(unixFile) );
  2191   if( pNew==0 ){
  2192     close(h);
  2193     enterMutex();
  2194     releaseLockInfo(pNew->pLock);
  2195     releaseOpenCnt(pNew->pOpen);
  2196     leaveMutex();
  2197     return SQLITE_NOMEM;
  2198   }else{
  2199     switch(lockingStyle) {
  2200       case afpLockingStyle: {
  2201         /* afp locking uses the file path so it needs to be included in
  2202         ** the afpLockingContext */
  2203         int nFilename;
  2204         pNew->pMethod = &sqlite3AFPLockingUnixIoMethod;
  2205         pNew->lockingContext = 
  2206           sqlite3_malloc(sizeof(afpLockingContext));
  2207         nFilename = strlen(zFilename)+1;
  2208         ((afpLockingContext *)pNew->lockingContext)->filePath = 
  2209           sqlite3_malloc(nFilename);
  2210         memcpy(((afpLockingContext *)pNew->lockingContext)->filePath, 
  2211                zFilename, nFilename);
  2212         srandomdev();
  2213         break;
  2214       }
  2215       case flockLockingStyle:
  2216         /* flock locking doesn't need additional lockingContext information */
  2217         pNew->pMethod = &sqlite3FlockLockingUnixIoMethod;
  2218         break;
  2219       case dotlockLockingStyle: {
  2220         /* dotlock locking uses the file path so it needs to be included in
  2221          ** the dotlockLockingContext */
  2222         int nFilename;
  2223         pNew->pMethod = &sqlite3DotlockLockingUnixIoMethod;
  2224         pNew->lockingContext = sqlite3_malloc(
  2225           sizeof(dotlockLockingContext));
  2226         nFilename = strlen(zFilename) + 6;
  2227         ((dotlockLockingContext *)pNew->lockingContext)->lockPath = 
  2228             sqlite3_malloc( nFilename );
  2229         sqlite3_snprintf(nFilename, 
  2230                 ((dotlockLockingContext *)pNew->lockingContext)->lockPath, 
  2231                 "%s.lock", zFilename);
  2232         break;
  2233       }
  2234       case posixLockingStyle:
  2235         /* posix locking doesn't need additional lockingContext information */
  2236         pNew->pMethod = &sqlite3UnixIoMethod;
  2237         break;
  2238       case noLockingStyle:
  2239       case unsupportedLockingStyle:
  2240       default: 
  2241         pNew->pMethod = &sqlite3NolockLockingUnixIoMethod;
  2242     }
  2243     OpenCounter(+1);
  2244     return SQLITE_OK;
  2245   }
  2246 }
  2247 #else /* SQLITE_ENABLE_LOCKING_STYLE */
  2248 static int fillInUnixFile(
  2249   int h,                 /* Open file descriptor on file being opened */
  2250   int dirfd,
  2251   sqlite3_file *pId,     /* Write to the unixFile structure here */
  2252   const char *zFilename  /* Name of the file being opened */
  2253 ){
  2254   unixFile *pNew = (unixFile *)pId;
  2255   int rc;
  2256 
  2257 #ifdef FD_CLOEXEC
  2258   fcntl(h, F_SETFD, fcntl(h, F_GETFD, 0) | FD_CLOEXEC);
  2259 #endif
  2260 
  2261   enterMutex();
  2262   rc = findLockInfo(h, &pNew->pLock, &pNew->pOpen);
  2263   leaveMutex();
  2264   if( rc ){
  2265     close(h);
  2266     return SQLITE_NOMEM;
  2267   }
  2268 
  2269   OSTRACE3("OPEN    %-3d %s\n", h, zFilename);
  2270   pNew->dirfd = -1;
  2271   pNew->h = h;
  2272   pNew->dirfd = dirfd;
  2273   SET_THREADID(pNew);
  2274 
  2275   pNew->pMethod = &sqlite3UnixIoMethod;
  2276   OpenCounter(+1);
  2277   return SQLITE_OK;
  2278 }
  2279 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  2280 
  2281 /*
  2282 ** Open a file descriptor to the directory containing file zFilename.
  2283 ** If successful, *pFd is set to the opened file descriptor and
  2284 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
  2285 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
  2286 ** value.
  2287 **
  2288 ** If SQLITE_OK is returned, the caller is responsible for closing
  2289 ** the file descriptor *pFd using close().
  2290 */
  2291 static int openDirectory(const char *zFilename, int *pFd){
  2292   int ii;
  2293   int fd = -1;
  2294   char zDirname[MAX_PATHNAME+1];
  2295 
  2296   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
  2297   for(ii=strlen(zDirname); ii>=0 && zDirname[ii]!='/'; ii--);
  2298   if( ii>0 ){
  2299     zDirname[ii] = '\0';
  2300     fd = open(zDirname, O_RDONLY|O_BINARY, 0);
  2301     if( fd>=0 ){
  2302 #ifdef FD_CLOEXEC
  2303       fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
  2304 #endif
  2305       OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
  2306     }
  2307   }
  2308   *pFd = fd;
  2309   return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN);
  2310 }
  2311 
  2312 /*
  2313 ** Open the file zPath.
  2314 ** 
  2315 ** Previously, the SQLite OS layer used three functions in place of this
  2316 ** one:
  2317 **
  2318 **     sqlite3OsOpenReadWrite();
  2319 **     sqlite3OsOpenReadOnly();
  2320 **     sqlite3OsOpenExclusive();
  2321 **
  2322 ** These calls correspond to the following combinations of flags:
  2323 **
  2324 **     ReadWrite() ->     (READWRITE | CREATE)
  2325 **     ReadOnly()  ->     (READONLY) 
  2326 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
  2327 **
  2328 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
  2329 ** true, the file was configured to be automatically deleted when the
  2330 ** file handle closed. To achieve the same effect using this new 
  2331 ** interface, add the DELETEONCLOSE flag to those specified above for 
  2332 ** OpenExclusive().
  2333 */
  2334 static int unixOpen(
  2335   sqlite3_vfs *pVfs, 
  2336   const char *zPath, 
  2337   sqlite3_file *pFile,
  2338   int flags,
  2339   int *pOutFlags
  2340 ){
  2341   int fd = 0;                    /* File descriptor returned by open() */
  2342   int dirfd = -1;                /* Directory file descriptor */
  2343   int oflags = 0;                /* Flags to pass to open() */
  2344   int eType = flags&0xFFFFFF00;  /* Type of file to open */
  2345 
  2346   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
  2347   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
  2348   int isCreate     = (flags & SQLITE_OPEN_CREATE);
  2349   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
  2350   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
  2351 
  2352   /* If creating a master or main-file journal, this function will open
  2353   ** a file-descriptor on the directory too. The first time unixSync()
  2354   ** is called the directory file descriptor will be fsync()ed and close()d.
  2355   */
  2356   int isOpenDirectory = (isCreate && 
  2357       (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
  2358   );
  2359 
  2360   /* Check the following statements are true: 
  2361   **
  2362   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
  2363   **   (b) if CREATE is set, then READWRITE must also be set, and
  2364   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
  2365   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
  2366   */
  2367   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  2368   assert(isCreate==0 || isReadWrite);
  2369   assert(isExclusive==0 || isCreate);
  2370   assert(isDelete==0 || isCreate);
  2371 
  2372 
  2373   /* The main DB, main journal, and master journal are never automatically
  2374   ** deleted
  2375   */
  2376   assert( eType!=SQLITE_OPEN_MAIN_DB || !isDelete );
  2377   assert( eType!=SQLITE_OPEN_MAIN_JOURNAL || !isDelete );
  2378   assert( eType!=SQLITE_OPEN_MASTER_JOURNAL || !isDelete );
  2379 
  2380   /* Assert that the upper layer has set one of the "file-type" flags. */
  2381   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
  2382        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
  2383        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
  2384        || eType==SQLITE_OPEN_TRANSIENT_DB
  2385   );
  2386 
  2387   if( isReadonly )  oflags |= O_RDONLY;
  2388   if( isReadWrite ) oflags |= O_RDWR;
  2389   if( isCreate )    oflags |= O_CREAT;
  2390   if( isExclusive ) oflags |= (O_EXCL|O_NOFOLLOW);
  2391   oflags |= (O_LARGEFILE|O_BINARY);
  2392 
  2393   memset(pFile, 0, sizeof(unixFile));
  2394   fd = open(zPath, oflags, isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
  2395   if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
  2396     /* Failed to open the file for read/write access. Try read-only. */
  2397     flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
  2398     flags |= SQLITE_OPEN_READONLY;
  2399     return unixOpen(pVfs, zPath, pFile, flags, pOutFlags);
  2400   }
  2401   if( fd<0 ){
  2402     return SQLITE_CANTOPEN;
  2403   }
  2404   if( isDelete ){
  2405     unlink(zPath);
  2406   }
  2407   if( pOutFlags ){
  2408     *pOutFlags = flags;
  2409   }
  2410 
  2411   assert(fd!=0);
  2412   if( isOpenDirectory ){
  2413     int rc = openDirectory(zPath, &dirfd);
  2414     if( rc!=SQLITE_OK ){
  2415       close(fd);
  2416       return rc;
  2417     }
  2418   }
  2419   return fillInUnixFile(fd, dirfd, pFile, zPath);
  2420 }
  2421 
  2422 /*
  2423 ** Delete the file at zPath. If the dirSync argument is true, fsync()
  2424 ** the directory after deleting the file.
  2425 */
  2426 static int unixDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  2427   int rc = SQLITE_OK;
  2428   SimulateIOError(return SQLITE_IOERR_DELETE);
  2429   unlink(zPath);
  2430   if( dirSync ){
  2431     int fd;
  2432     rc = openDirectory(zPath, &fd);
  2433     if( rc==SQLITE_OK ){
  2434       if( fsync(fd) ){
  2435         rc = SQLITE_IOERR_DIR_FSYNC;
  2436       }
  2437       close(fd);
  2438     }
  2439   }
  2440   return rc;
  2441 }
  2442 
  2443 /*
  2444 ** Test the existance of or access permissions of file zPath. The
  2445 ** test performed depends on the value of flags:
  2446 **
  2447 **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
  2448 **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
  2449 **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
  2450 **
  2451 ** Otherwise return 0.
  2452 */
  2453 static int unixAccess(sqlite3_vfs *pVfs, const char *zPath, int flags){
  2454   int amode = 0;
  2455   switch( flags ){
  2456     case SQLITE_ACCESS_EXISTS:
  2457       amode = F_OK;
  2458       break;
  2459     case SQLITE_ACCESS_READWRITE:
  2460       amode = W_OK|R_OK;
  2461       break;
  2462     case SQLITE_ACCESS_READ:
  2463       amode = R_OK;
  2464       break;
  2465 
  2466     default:
  2467       assert(!"Invalid flags argument");
  2468   }
  2469   return (access(zPath, amode)==0);
  2470 }
  2471 
  2472 /*
  2473 ** Create a temporary file name in zBuf.  zBuf must be allocated
  2474 ** by the calling process and must be big enough to hold at least
  2475 ** pVfs->mxPathname bytes.
  2476 */
  2477 static int unixGetTempname(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  2478   static const char *azDirs[] = {
  2479      0,
  2480      "/var/tmp",
  2481      "/usr/tmp",
  2482      "/tmp",
  2483      ".",
  2484   };
  2485   static const unsigned char zChars[] =
  2486     "abcdefghijklmnopqrstuvwxyz"
  2487     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  2488     "0123456789";
  2489   int i, j;
  2490   struct stat buf;
  2491   const char *zDir = ".";
  2492 
  2493   /* It's odd to simulate an io-error here, but really this is just
  2494   ** using the io-error infrastructure to test that SQLite handles this
  2495   ** function failing. 
  2496   */
  2497   SimulateIOError( return SQLITE_ERROR );
  2498 
  2499   azDirs[0] = sqlite3_temp_directory;
  2500   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
  2501     if( azDirs[i]==0 ) continue;
  2502     if( stat(azDirs[i], &buf) ) continue;
  2503     if( !S_ISDIR(buf.st_mode) ) continue;
  2504     if( access(azDirs[i], 07) ) continue;
  2505     zDir = azDirs[i];
  2506     break;
  2507   }
  2508   do{
  2509     assert( pVfs->mxPathname==MAX_PATHNAME );
  2510     assert( nBuf>=MAX_PATHNAME );
  2511     sqlite3_snprintf(MAX_PATHNAME-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
  2512     j = strlen(zBuf);
  2513     sqlite3Randomness(15, &zBuf[j]);
  2514     for(i=0; i<15; i++, j++){
  2515       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  2516     }
  2517     zBuf[j] = 0;
  2518   }while( access(zBuf,0)==0 );
  2519   return SQLITE_OK;
  2520 }
  2521 
  2522 
  2523 /*
  2524 ** Turn a relative pathname into a full pathname. The relative path
  2525 ** is stored as a nul-terminated string in the buffer pointed to by
  2526 ** zPath. 
  2527 **
  2528 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes 
  2529 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
  2530 ** this buffer before returning.
  2531 */
  2532 static int unixFullPathname(
  2533   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
  2534   const char *zPath,            /* Possibly relative input path */
  2535   int nOut,                     /* Size of output buffer in bytes */
  2536   char *zOut                    /* Output buffer */
  2537 ){
  2538 
  2539   /* It's odd to simulate an io-error here, but really this is just
  2540   ** using the io-error infrastructure to test that SQLite handles this
  2541   ** function failing. This function could fail if, for example, the
  2542   ** current working directly has been unlinked.
  2543   */
  2544   SimulateIOError( return SQLITE_ERROR );
  2545 
  2546   assert( pVfs->mxPathname==MAX_PATHNAME );
  2547   zOut[MAX_PATHNAME-1] = '\0';
  2548   if( zPath[0]=='/' ){
  2549     sqlite3_snprintf(MAX_PATHNAME, zOut, "%s", zPath);
  2550   }else{
  2551     int nCwd;
  2552     if( getcwd(zOut, MAX_PATHNAME-1)==0 ){
  2553       return SQLITE_CANTOPEN;
  2554     }
  2555     nCwd = strlen(zOut);
  2556     sqlite3_snprintf(MAX_PATHNAME-nCwd, &zOut[nCwd], "/%s", zPath);
  2557   }
  2558   return SQLITE_OK;
  2559 
  2560 #if 0
  2561   /*
  2562   ** Remove "/./" path elements and convert "/A/./" path elements
  2563   ** to just "/".
  2564   */
  2565   if( zFull ){
  2566     int i, j;
  2567     for(i=j=0; zFull[i]; i++){
  2568       if( zFull[i]=='/' ){
  2569         if( zFull[i+1]=='/' ) continue;
  2570         if( zFull[i+1]=='.' && zFull[i+2]=='/' ){
  2571           i += 1;
  2572           continue;
  2573         }
  2574         if( zFull[i+1]=='.' && zFull[i+2]=='.' && zFull[i+3]=='/' ){
  2575           while( j>0 && zFull[j-1]!='/' ){ j--; }
  2576           i += 3;
  2577           continue;
  2578         }
  2579       }
  2580       zFull[j++] = zFull[i];
  2581     }
  2582     zFull[j] = 0;
  2583   }
  2584 #endif
  2585 }
  2586 
  2587 
  2588 #ifndef SQLITE_OMIT_LOAD_EXTENSION
  2589 /*
  2590 ** Interfaces for opening a shared library, finding entry points
  2591 ** within the shared library, and closing the shared library.
  2592 */
  2593 #include <dlfcn.h>
  2594 static void *unixDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
  2595   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
  2596 }
  2597 
  2598 /*
  2599 ** SQLite calls this function immediately after a call to unixDlSym() or
  2600 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
  2601 ** message is available, it is written to zBufOut. If no error message
  2602 ** is available, zBufOut is left unmodified and SQLite uses a default
  2603 ** error message.
  2604 */
  2605 static void unixDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
  2606   char *zErr;
  2607   enterMutex();
  2608   zErr = dlerror();
  2609   if( zErr ){
  2610     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
  2611   }
  2612   leaveMutex();
  2613 }
  2614 static void *unixDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
  2615   return dlsym(pHandle, zSymbol);
  2616 }
  2617 static void unixDlClose(sqlite3_vfs *pVfs, void *pHandle){
  2618   dlclose(pHandle);
  2619 }
  2620 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  2621   #define unixDlOpen  0
  2622   #define unixDlError 0
  2623   #define unixDlSym   0
  2624   #define unixDlClose 0
  2625 #endif
  2626 
  2627 /*
  2628 ** Write nBuf bytes of random data to the supplied buffer zBuf.
  2629 */
  2630 static int unixRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  2631 
  2632   assert(nBuf>=(sizeof(time_t)+sizeof(int)));
  2633 
  2634   /* We have to initialize zBuf to prevent valgrind from reporting
  2635   ** errors.  The reports issued by valgrind are incorrect - we would
  2636   ** prefer that the randomness be increased by making use of the
  2637   ** uninitialized space in zBuf - but valgrind errors tend to worry
  2638   ** some users.  Rather than argue, it seems easier just to initialize
  2639   ** the whole array and silence valgrind, even if that means less randomness
  2640   ** in the random seed.
  2641   **
  2642   ** When testing, initializing zBuf[] to zero is all we do.  That means
  2643   ** that we always use the same random number sequence.  This makes the
  2644   ** tests repeatable.
  2645   */
  2646   memset(zBuf, 0, nBuf);
  2647 #if !defined(SQLITE_TEST)
  2648   {
  2649     int pid, fd;
  2650     fd = open("/dev/urandom", O_RDONLY);
  2651     if( fd<0 ){
  2652       time_t t;
  2653       time(&t);
  2654       memcpy(zBuf, &t, sizeof(t));
  2655       pid = getpid();
  2656       memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
  2657     }else{
  2658       read(fd, zBuf, nBuf);
  2659       close(fd);
  2660     }
  2661   }
  2662 #endif
  2663   return SQLITE_OK;
  2664 }
  2665 
  2666 
  2667 /*
  2668 ** Sleep for a little while.  Return the amount of time slept.
  2669 ** The argument is the number of microseconds we want to sleep.
  2670 ** The return value is the number of microseconds of sleep actually
  2671 ** requested from the underlying operating system, a number which
  2672 ** might be greater than or equal to the argument, but not less
  2673 ** than the argument.
  2674 */
  2675 static int unixSleep(sqlite3_vfs *pVfs, int microseconds){
  2676 #if defined(HAVE_USLEEP) && HAVE_USLEEP
  2677   usleep(microseconds);
  2678   return microseconds;
  2679 #else
  2680   int seconds = (microseconds+999999)/1000000;
  2681   sleep(seconds);
  2682   return seconds*1000000;
  2683 #endif
  2684 }
  2685 
  2686 /*
  2687 ** The following variable, if set to a non-zero value, becomes the result
  2688 ** returned from sqlite3OsCurrentTime().  This is used for testing.
  2689 */
  2690 #ifdef SQLITE_TEST
  2691 int sqlite3_current_time = 0;
  2692 #endif
  2693 
  2694 /*
  2695 ** Find the current time (in Universal Coordinated Time).  Write the
  2696 ** current time and date as a Julian Day number into *prNow and
  2697 ** return 0.  Return 1 if the time and date cannot be found.
  2698 */
  2699 static int unixCurrentTime(sqlite3_vfs *pVfs, double *prNow){
  2700 #ifdef NO_GETTOD
  2701   time_t t;
  2702   time(&t);
  2703   *prNow = t/86400.0 + 2440587.5;
  2704 #else
  2705   struct timeval sNow;
  2706   gettimeofday(&sNow, 0);
  2707   *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
  2708 #endif
  2709 #ifdef SQLITE_TEST
  2710   if( sqlite3_current_time ){
  2711     *prNow = sqlite3_current_time/86400.0 + 2440587.5;
  2712   }
  2713 #endif
  2714   return 0;
  2715 }
  2716 
  2717 /*
  2718 ** Return a pointer to the sqlite3DefaultVfs structure.   We use
  2719 ** a function rather than give the structure global scope because
  2720 ** some compilers (MSVC) do not allow forward declarations of
  2721 ** initialized structures.
  2722 */
  2723 sqlite3_vfs *sqlite3OsDefaultVfs(void){
  2724   static sqlite3_vfs unixVfs = {
  2725     1,                  /* iVersion */
  2726     sizeof(unixFile),   /* szOsFile */
  2727     MAX_PATHNAME,       /* mxPathname */
  2728     0,                  /* pNext */
  2729     "unix",             /* zName */
  2730     0,                  /* pAppData */
  2731   
  2732     unixOpen,           /* xOpen */
  2733     unixDelete,         /* xDelete */
  2734     unixAccess,         /* xAccess */
  2735     unixGetTempname,    /* xGetTempName */
  2736     unixFullPathname,   /* xFullPathname */
  2737     unixDlOpen,         /* xDlOpen */
  2738     unixDlError,        /* xDlError */
  2739     unixDlSym,          /* xDlSym */
  2740     unixDlClose,        /* xDlClose */
  2741     unixRandomness,     /* xRandomness */
  2742     unixSleep,          /* xSleep */
  2743     unixCurrentTime     /* xCurrentTime */
  2744   };
  2745   
  2746   return &unixVfs;
  2747 }
  2748  
  2749 #endif /* OS_UNIX */