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