sl@0: /*
sl@0: ** 2004 May 22
sl@0: **
sl@0: ** The author disclaims copyright to this source code.  In place of
sl@0: ** a legal notice, here is a blessing:
sl@0: **
sl@0: **    May you do good and not evil.
sl@0: **    May you find forgiveness for yourself and forgive others.
sl@0: **    May you share freely, never taking more than you give.
sl@0: **
sl@0: ******************************************************************************
sl@0: **
sl@0: ** This file contains code that is specific to Unix systems.
sl@0: **
sl@0: ** $Id: os_unix.c,v 1.195 2008/07/30 17:28:04 drh Exp $
sl@0: */
sl@0: #include "sqliteInt.h"
sl@0: #if SQLITE_OS_UNIX              /* This file is used on unix only */
sl@0: 
sl@0: /*
sl@0: ** If SQLITE_ENABLE_LOCKING_STYLE is defined, then several different 
sl@0: ** locking implementations are provided:
sl@0: **
sl@0: **   * POSIX locking (the default),
sl@0: **   * No locking,
sl@0: **   * Dot-file locking,
sl@0: **   * flock() locking,
sl@0: **   * AFP locking (OSX only).
sl@0: */
sl@0: /* #define SQLITE_ENABLE_LOCKING_STYLE 0 */
sl@0: 
sl@0: /*
sl@0: ** These #defines should enable >2GB file support on Posix if the
sl@0: ** underlying operating system supports it.  If the OS lacks
sl@0: ** large file support, these should be no-ops.
sl@0: **
sl@0: ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
sl@0: ** on the compiler command line.  This is necessary if you are compiling
sl@0: ** on a recent machine (ex: RedHat 7.2) but you want your code to work
sl@0: ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
sl@0: ** without this option, LFS is enable.  But LFS does not exist in the kernel
sl@0: ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
sl@0: ** portability you should omit LFS.
sl@0: */
sl@0: #ifndef SQLITE_DISABLE_LFS
sl@0: # define _LARGE_FILE       1
sl@0: # ifndef _FILE_OFFSET_BITS
sl@0: #   define _FILE_OFFSET_BITS 64
sl@0: # endif
sl@0: # define _LARGEFILE_SOURCE 1
sl@0: #endif
sl@0: 
sl@0: /*
sl@0: ** standard include files.
sl@0: */
sl@0: #include <sys/types.h>
sl@0: #include <sys/stat.h>
sl@0: #include <fcntl.h>
sl@0: #include <unistd.h>
sl@0: #include <time.h>
sl@0: #include <sys/time.h>
sl@0: #include <errno.h>
sl@0: 
sl@0: #ifdef SQLITE_ENABLE_LOCKING_STYLE
sl@0: #include <sys/ioctl.h>
sl@0: #include <sys/param.h>
sl@0: #include <sys/mount.h>
sl@0: #endif /* SQLITE_ENABLE_LOCKING_STYLE */
sl@0: 
sl@0: /*
sl@0: ** If we are to be thread-safe, include the pthreads header and define
sl@0: ** the SQLITE_UNIX_THREADS macro.
sl@0: */
sl@0: #if SQLITE_THREADSAFE
sl@0: # include <pthread.h>
sl@0: # define SQLITE_UNIX_THREADS 1
sl@0: #endif
sl@0: 
sl@0: /*
sl@0: ** Default permissions when creating a new file
sl@0: */
sl@0: #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
sl@0: # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
sl@0: #endif
sl@0: 
sl@0: /*
sl@0: ** Maximum supported path-length.
sl@0: */
sl@0: #define MAX_PATHNAME 512
sl@0: 
sl@0: 
sl@0: /*
sl@0: ** The unixFile structure is subclass of sqlite3_file specific for the unix
sl@0: ** protability layer.
sl@0: */
sl@0: typedef struct unixFile unixFile;
sl@0: struct unixFile {
sl@0:   sqlite3_io_methods const *pMethod;  /* Always the first entry */
sl@0: #ifdef SQLITE_TEST
sl@0:   /* In test mode, increase the size of this structure a bit so that 
sl@0:   ** it is larger than the struct CrashFile defined in test6.c.
sl@0:   */
sl@0:   char aPadding[32];
sl@0: #endif
sl@0:   struct openCnt *pOpen;    /* Info about all open fd's on this inode */
sl@0:   struct lockInfo *pLock;   /* Info about locks on this inode */
sl@0: #ifdef SQLITE_ENABLE_LOCKING_STYLE
sl@0:   void *lockingContext;     /* Locking style specific state */
sl@0: #endif
sl@0:   int h;                    /* The file descriptor */
sl@0:   unsigned char locktype;   /* The type of lock held on this fd */
sl@0:   int dirfd;                /* File descriptor for the directory */
sl@0: #if SQLITE_THREADSAFE
sl@0:   pthread_t tid;            /* The thread that "owns" this unixFile */
sl@0: #endif
sl@0: };
sl@0: 
sl@0: /*
sl@0: ** Include code that is common to all os_*.c files
sl@0: */
sl@0: #include "os_common.h"
sl@0: 
sl@0: /*
sl@0: ** Define various macros that are missing from some systems.
sl@0: */
sl@0: #ifndef O_LARGEFILE
sl@0: # define O_LARGEFILE 0
sl@0: #endif
sl@0: #ifdef SQLITE_DISABLE_LFS
sl@0: # undef O_LARGEFILE
sl@0: # define O_LARGEFILE 0
sl@0: #endif
sl@0: #ifndef O_NOFOLLOW
sl@0: # define O_NOFOLLOW 0
sl@0: #endif
sl@0: #ifndef O_BINARY
sl@0: # define O_BINARY 0
sl@0: #endif
sl@0: 
sl@0: /*
sl@0: ** The DJGPP compiler environment looks mostly like Unix, but it
sl@0: ** lacks the fcntl() system call.  So redefine fcntl() to be something
sl@0: ** that always succeeds.  This means that locking does not occur under
sl@0: ** DJGPP.  But it is DOS - what did you expect?
sl@0: */
sl@0: #ifdef __DJGPP__
sl@0: # define fcntl(A,B,C) 0
sl@0: #endif
sl@0: 
sl@0: /*
sl@0: ** The threadid macro resolves to the thread-id or to 0.  Used for
sl@0: ** testing and debugging only.
sl@0: */
sl@0: #if SQLITE_THREADSAFE
sl@0: #define threadid pthread_self()
sl@0: #else
sl@0: #define threadid 0
sl@0: #endif
sl@0: 
sl@0: /*
sl@0: ** Set or check the unixFile.tid field.  This field is set when an unixFile
sl@0: ** is first opened.  All subsequent uses of the unixFile verify that the
sl@0: ** same thread is operating on the unixFile.  Some operating systems do
sl@0: ** not allow locks to be overridden by other threads and that restriction
sl@0: ** means that sqlite3* database handles cannot be moved from one thread
sl@0: ** to another.  This logic makes sure a user does not try to do that
sl@0: ** by mistake.
sl@0: **
sl@0: ** Version 3.3.1 (2006-01-15):  unixFile can be moved from one thread to
sl@0: ** another as long as we are running on a system that supports threads
sl@0: ** overriding each others locks (which now the most common behavior)
sl@0: ** or if no locks are held.  But the unixFile.pLock field needs to be
sl@0: ** recomputed because its key includes the thread-id.  See the 
sl@0: ** transferOwnership() function below for additional information
sl@0: */
sl@0: #if SQLITE_THREADSAFE
sl@0: # define SET_THREADID(X)   (X)->tid = pthread_self()
sl@0: # define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
sl@0:                             !pthread_equal((X)->tid, pthread_self()))
sl@0: #else
sl@0: # define SET_THREADID(X)
sl@0: # define CHECK_THREADID(X) 0
sl@0: #endif
sl@0: 
sl@0: /*
sl@0: ** Here is the dirt on POSIX advisory locks:  ANSI STD 1003.1 (1996)
sl@0: ** section 6.5.2.2 lines 483 through 490 specify that when a process
sl@0: ** sets or clears a lock, that operation overrides any prior locks set
sl@0: ** by the same process.  It does not explicitly say so, but this implies
sl@0: ** that it overrides locks set by the same process using a different
sl@0: ** file descriptor.  Consider this test case:
sl@0: **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
sl@0: **
sl@0: ** Suppose ./file1 and ./file2 are really the same file (because
sl@0: ** one is a hard or symbolic link to the other) then if you set
sl@0: ** an exclusive lock on fd1, then try to get an exclusive lock
sl@0: ** on fd2, it works.  I would have expected the second lock to
sl@0: ** fail since there was already a lock on the file due to fd1.
sl@0: ** But not so.  Since both locks came from the same process, the
sl@0: ** second overrides the first, even though they were on different
sl@0: ** file descriptors opened on different file names.
sl@0: **
sl@0: ** Bummer.  If you ask me, this is broken.  Badly broken.  It means
sl@0: ** that we cannot use POSIX locks to synchronize file access among
sl@0: ** competing threads of the same process.  POSIX locks will work fine
sl@0: ** to synchronize access for threads in separate processes, but not
sl@0: ** threads within the same process.
sl@0: **
sl@0: ** To work around the problem, SQLite has to manage file locks internally
sl@0: ** on its own.  Whenever a new database is opened, we have to find the
sl@0: ** specific inode of the database file (the inode is determined by the
sl@0: ** st_dev and st_ino fields of the stat structure that fstat() fills in)
sl@0: ** and check for locks already existing on that inode.  When locks are
sl@0: ** created or removed, we have to look at our own internal record of the
sl@0: ** locks to see if another thread has previously set a lock on that same
sl@0: ** inode.
sl@0: **
sl@0: ** The sqlite3_file structure for POSIX is no longer just an integer file
sl@0: ** descriptor.  It is now a structure that holds the integer file
sl@0: ** descriptor and a pointer to a structure that describes the internal
sl@0: ** locks on the corresponding inode.  There is one locking structure
sl@0: ** per inode, so if the same inode is opened twice, both unixFile structures
sl@0: ** point to the same locking structure.  The locking structure keeps
sl@0: ** a reference count (so we will know when to delete it) and a "cnt"
sl@0: ** field that tells us its internal lock status.  cnt==0 means the
sl@0: ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
sl@0: ** cnt>0 means there are cnt shared locks on the file.
sl@0: **
sl@0: ** Any attempt to lock or unlock a file first checks the locking
sl@0: ** structure.  The fcntl() system call is only invoked to set a 
sl@0: ** POSIX lock if the internal lock structure transitions between
sl@0: ** a locked and an unlocked state.
sl@0: **
sl@0: ** 2004-Jan-11:
sl@0: ** More recent discoveries about POSIX advisory locks.  (The more
sl@0: ** I discover, the more I realize the a POSIX advisory locks are
sl@0: ** an abomination.)
sl@0: **
sl@0: ** If you close a file descriptor that points to a file that has locks,
sl@0: ** all locks on that file that are owned by the current process are
sl@0: ** released.  To work around this problem, each unixFile structure contains
sl@0: ** a pointer to an openCnt structure.  There is one openCnt structure
sl@0: ** per open inode, which means that multiple unixFile can point to a single
sl@0: ** openCnt.  When an attempt is made to close an unixFile, if there are
sl@0: ** other unixFile open on the same inode that are holding locks, the call
sl@0: ** to close() the file descriptor is deferred until all of the locks clear.
sl@0: ** The openCnt structure keeps a list of file descriptors that need to
sl@0: ** be closed and that list is walked (and cleared) when the last lock
sl@0: ** clears.
sl@0: **
sl@0: ** First, under Linux threads, because each thread has a separate
sl@0: ** process ID, lock operations in one thread do not override locks
sl@0: ** to the same file in other threads.  Linux threads behave like
sl@0: ** separate processes in this respect.  But, if you close a file
sl@0: ** descriptor in linux threads, all locks are cleared, even locks
sl@0: ** on other threads and even though the other threads have different
sl@0: ** process IDs.  Linux threads is inconsistent in this respect.
sl@0: ** (I'm beginning to think that linux threads is an abomination too.)
sl@0: ** The consequence of this all is that the hash table for the lockInfo
sl@0: ** structure has to include the process id as part of its key because
sl@0: ** locks in different threads are treated as distinct.  But the 
sl@0: ** openCnt structure should not include the process id in its
sl@0: ** key because close() clears lock on all threads, not just the current
sl@0: ** thread.  Were it not for this goofiness in linux threads, we could
sl@0: ** combine the lockInfo and openCnt structures into a single structure.
sl@0: **
sl@0: ** 2004-Jun-28:
sl@0: ** On some versions of linux, threads can override each others locks.
sl@0: ** On others not.  Sometimes you can change the behavior on the same
sl@0: ** system by setting the LD_ASSUME_KERNEL environment variable.  The
sl@0: ** POSIX standard is silent as to which behavior is correct, as far
sl@0: ** as I can tell, so other versions of unix might show the same
sl@0: ** inconsistency.  There is no little doubt in my mind that posix
sl@0: ** advisory locks and linux threads are profoundly broken.
sl@0: **
sl@0: ** To work around the inconsistencies, we have to test at runtime 
sl@0: ** whether or not threads can override each others locks.  This test
sl@0: ** is run once, the first time any lock is attempted.  A static 
sl@0: ** variable is set to record the results of this test for future
sl@0: ** use.
sl@0: */
sl@0: 
sl@0: /*
sl@0: ** An instance of the following structure serves as the key used
sl@0: ** to locate a particular lockInfo structure given its inode.
sl@0: **
sl@0: ** If threads cannot override each others locks, then we set the
sl@0: ** lockKey.tid field to the thread ID.  If threads can override
sl@0: ** each others locks then tid is always set to zero.  tid is omitted
sl@0: ** if we compile without threading support.
sl@0: */
sl@0: struct lockKey {
sl@0:   dev_t dev;       /* Device number */
sl@0:   ino_t ino;       /* Inode number */
sl@0: #if SQLITE_THREADSAFE
sl@0:   pthread_t tid;   /* Thread ID or zero if threads can override each other */
sl@0: #endif
sl@0: };
sl@0: 
sl@0: /*
sl@0: ** An instance of the following structure is allocated for each open
sl@0: ** inode on each thread with a different process ID.  (Threads have
sl@0: ** different process IDs on linux, but not on most other unixes.)
sl@0: **
sl@0: ** A single inode can have multiple file descriptors, so each unixFile
sl@0: ** structure contains a pointer to an instance of this object and this
sl@0: ** object keeps a count of the number of unixFile pointing to it.
sl@0: */
sl@0: struct lockInfo {
sl@0:   struct lockKey key;  /* The lookup key */
sl@0:   int cnt;             /* Number of SHARED locks held */
sl@0:   int locktype;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
sl@0:   int nRef;            /* Number of pointers to this structure */
sl@0:   struct lockInfo *pNext, *pPrev;   /* List of all lockInfo objects */
sl@0: };
sl@0: 
sl@0: /*
sl@0: ** An instance of the following structure serves as the key used
sl@0: ** to locate a particular openCnt structure given its inode.  This
sl@0: ** is the same as the lockKey except that the thread ID is omitted.
sl@0: */
sl@0: struct openKey {
sl@0:   dev_t dev;   /* Device number */
sl@0:   ino_t ino;   /* Inode number */
sl@0: };
sl@0: 
sl@0: /*
sl@0: ** An instance of the following structure is allocated for each open
sl@0: ** inode.  This structure keeps track of the number of locks on that
sl@0: ** inode.  If a close is attempted against an inode that is holding
sl@0: ** locks, the close is deferred until all locks clear by adding the
sl@0: ** file descriptor to be closed to the pending list.
sl@0: */
sl@0: struct openCnt {
sl@0:   struct openKey key;   /* The lookup key */
sl@0:   int nRef;             /* Number of pointers to this structure */
sl@0:   int nLock;            /* Number of outstanding locks */
sl@0:   int nPending;         /* Number of pending close() operations */
sl@0:   int *aPending;        /* Malloced space holding fd's awaiting a close() */
sl@0:   struct openCnt *pNext, *pPrev;   /* List of all openCnt objects */
sl@0: };
sl@0: 
sl@0: /*
sl@0: ** List of all lockInfo and openCnt objects.  This used to be a hash
sl@0: ** table.  But the number of objects is rarely more than a dozen and
sl@0: ** never exceeds a few thousand.  And lookup is not on a critical
sl@0: ** path oo a simple linked list will suffice.
sl@0: */
sl@0: static struct lockInfo *lockList = 0;
sl@0: static struct openCnt *openList = 0;
sl@0: 
sl@0: /*
sl@0: ** The locking styles are associated with the different file locking
sl@0: ** capabilities supported by different file systems.  
sl@0: **
sl@0: ** POSIX locking style fully supports shared and exclusive byte-range locks 
sl@0: ** AFP locking only supports exclusive byte-range locks
sl@0: ** FLOCK only supports a single file-global exclusive lock
sl@0: ** DOTLOCK isn't a true locking style, it refers to the use of a special
sl@0: **   file named the same as the database file with a '.lock' extension, this
sl@0: **   can be used on file systems that do not offer any reliable file locking
sl@0: ** NO locking means that no locking will be attempted, this is only used for
sl@0: **   read-only file systems currently
sl@0: ** UNSUPPORTED means that no locking will be attempted, this is only used for
sl@0: **   file systems that are known to be unsupported
sl@0: */
sl@0: #define LOCKING_STYLE_POSIX        1
sl@0: #define LOCKING_STYLE_NONE         2
sl@0: #define LOCKING_STYLE_DOTFILE      3
sl@0: #define LOCKING_STYLE_FLOCK        4
sl@0: #define LOCKING_STYLE_AFP          5
sl@0: 
sl@0: /*
sl@0: ** Helper functions to obtain and relinquish the global mutex.
sl@0: */
sl@0: static void enterMutex(){
sl@0:   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
sl@0: }
sl@0: static void leaveMutex(){
sl@0:   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
sl@0: }
sl@0: 
sl@0: #if SQLITE_THREADSAFE
sl@0: /*
sl@0: ** This variable records whether or not threads can override each others
sl@0: ** locks.
sl@0: **
sl@0: **    0:  No.  Threads cannot override each others locks.
sl@0: **    1:  Yes.  Threads can override each others locks.
sl@0: **   -1:  We don't know yet.
sl@0: **
sl@0: ** On some systems, we know at compile-time if threads can override each
sl@0: ** others locks.  On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
sl@0: ** will be set appropriately.  On other systems, we have to check at
sl@0: ** runtime.  On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
sl@0: ** undefined.
sl@0: **
sl@0: ** This variable normally has file scope only.  But during testing, we make
sl@0: ** it a global so that the test code can change its value in order to verify
sl@0: ** that the right stuff happens in either case.
sl@0: */
sl@0: #ifndef SQLITE_THREAD_OVERRIDE_LOCK
sl@0: # define SQLITE_THREAD_OVERRIDE_LOCK -1
sl@0: #endif
sl@0: #ifdef SQLITE_TEST
sl@0: int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
sl@0: #else
sl@0: static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
sl@0: #endif
sl@0: 
sl@0: /*
sl@0: ** This structure holds information passed into individual test
sl@0: ** threads by the testThreadLockingBehavior() routine.
sl@0: */
sl@0: struct threadTestData {
sl@0:   int fd;                /* File to be locked */
sl@0:   struct flock lock;     /* The locking operation */
sl@0:   int result;            /* Result of the locking operation */
sl@0: };
sl@0: 
sl@0: #ifdef SQLITE_LOCK_TRACE
sl@0: /*
sl@0: ** Print out information about all locking operations.
sl@0: **
sl@0: ** This routine is used for troubleshooting locks on multithreaded
sl@0: ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
sl@0: ** command-line option on the compiler.  This code is normally
sl@0: ** turned off.
sl@0: */
sl@0: static int lockTrace(int fd, int op, struct flock *p){
sl@0:   char *zOpName, *zType;
sl@0:   int s;
sl@0:   int savedErrno;
sl@0:   if( op==F_GETLK ){
sl@0:     zOpName = "GETLK";
sl@0:   }else if( op==F_SETLK ){
sl@0:     zOpName = "SETLK";
sl@0:   }else{
sl@0:     s = fcntl(fd, op, p);
sl@0:     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
sl@0:     return s;
sl@0:   }
sl@0:   if( p->l_type==F_RDLCK ){
sl@0:     zType = "RDLCK";
sl@0:   }else if( p->l_type==F_WRLCK ){
sl@0:     zType = "WRLCK";
sl@0:   }else if( p->l_type==F_UNLCK ){
sl@0:     zType = "UNLCK";
sl@0:   }else{
sl@0:     assert( 0 );
sl@0:   }
sl@0:   assert( p->l_whence==SEEK_SET );
sl@0:   s = fcntl(fd, op, p);
sl@0:   savedErrno = errno;
sl@0:   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
sl@0:      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
sl@0:      (int)p->l_pid, s);
sl@0:   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
sl@0:     struct flock l2;
sl@0:     l2 = *p;
sl@0:     fcntl(fd, F_GETLK, &l2);
sl@0:     if( l2.l_type==F_RDLCK ){
sl@0:       zType = "RDLCK";
sl@0:     }else if( l2.l_type==F_WRLCK ){
sl@0:       zType = "WRLCK";
sl@0:     }else if( l2.l_type==F_UNLCK ){
sl@0:       zType = "UNLCK";
sl@0:     }else{
sl@0:       assert( 0 );
sl@0:     }
sl@0:     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
sl@0:        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
sl@0:   }
sl@0:   errno = savedErrno;
sl@0:   return s;
sl@0: }
sl@0: #define fcntl lockTrace
sl@0: #endif /* SQLITE_LOCK_TRACE */
sl@0: 
sl@0: /*
sl@0: ** The testThreadLockingBehavior() routine launches two separate
sl@0: ** threads on this routine.  This routine attempts to lock a file
sl@0: ** descriptor then returns.  The success or failure of that attempt
sl@0: ** allows the testThreadLockingBehavior() procedure to determine
sl@0: ** whether or not threads can override each others locks.
sl@0: */
sl@0: static void *threadLockingTest(void *pArg){
sl@0:   struct threadTestData *pData = (struct threadTestData*)pArg;
sl@0:   pData->result = fcntl(pData->fd, F_SETLK, &pData->lock);
sl@0:   return pArg;
sl@0: }
sl@0: 
sl@0: /*
sl@0: ** This procedure attempts to determine whether or not threads
sl@0: ** can override each others locks then sets the 
sl@0: ** threadsOverrideEachOthersLocks variable appropriately.
sl@0: */
sl@0: static void testThreadLockingBehavior(int fd_orig){
sl@0:   int fd;
sl@0:   struct threadTestData d[2];
sl@0:   pthread_t t[2];
sl@0: 
sl@0:   fd = dup(fd_orig);
sl@0:   if( fd<0 ) return;
sl@0:   memset(d, 0, sizeof(d));
sl@0:   d[0].fd = fd;
sl@0:   d[0].lock.l_type = F_RDLCK;
sl@0:   d[0].lock.l_len = 1;
sl@0:   d[0].lock.l_start = 0;
sl@0:   d[0].lock.l_whence = SEEK_SET;
sl@0:   d[1] = d[0];
sl@0:   d[1].lock.l_type = F_WRLCK;
sl@0:   pthread_create(&t[0], 0, threadLockingTest, &d[0]);
sl@0:   pthread_create(&t[1], 0, threadLockingTest, &d[1]);
sl@0:   pthread_join(t[0], 0);
sl@0:   pthread_join(t[1], 0);
sl@0:   close(fd);
sl@0:   threadsOverrideEachOthersLocks =  d[0].result==0 && d[1].result==0;
sl@0: }
sl@0: #endif /* SQLITE_THREADSAFE */
sl@0: 
sl@0: /*
sl@0: ** Release a lockInfo structure previously allocated by findLockInfo().
sl@0: */
sl@0: static void releaseLockInfo(struct lockInfo *pLock){
sl@0:   if( pLock ){
sl@0:     pLock->nRef--;
sl@0:     if( pLock->nRef==0 ){
sl@0:       if( pLock->pPrev ){
sl@0:         assert( pLock->pPrev->pNext==pLock );
sl@0:         pLock->pPrev->pNext = pLock->pNext;
sl@0:       }else{
sl@0:         assert( lockList==pLock );
sl@0:         lockList = pLock->pNext;
sl@0:       }
sl@0:       if( pLock->pNext ){
sl@0:         assert( pLock->pNext->pPrev==pLock );
sl@0:         pLock->pNext->pPrev = pLock->pPrev;
sl@0:       }
sl@0:       sqlite3_free(pLock);
sl@0:     }
sl@0:   }
sl@0: }
sl@0: 
sl@0: /*
sl@0: ** Release a openCnt structure previously allocated by findLockInfo().
sl@0: */
sl@0: static void releaseOpenCnt(struct openCnt *pOpen){
sl@0:   if( pOpen ){
sl@0:     pOpen->nRef--;
sl@0:     if( pOpen->nRef==0 ){
sl@0:       if( pOpen->pPrev ){
sl@0:         assert( pOpen->pPrev->pNext==pOpen );
sl@0:         pOpen->pPrev->pNext = pOpen->pNext;
sl@0:       }else{
sl@0:         assert( openList==pOpen );
sl@0:         openList = pOpen->pNext;
sl@0:       }
sl@0:       if( pOpen->pNext ){
sl@0:         assert( pOpen->pNext->pPrev==pOpen );
sl@0:         pOpen->pNext->pPrev = pOpen->pPrev;
sl@0:       }
sl@0:       sqlite3_free(pOpen->aPending);
sl@0:       sqlite3_free(pOpen);
sl@0:     }
sl@0:   }
sl@0: }
sl@0: 
sl@0: #ifdef SQLITE_ENABLE_LOCKING_STYLE
sl@0: /*
sl@0: ** Tests a byte-range locking query to see if byte range locks are 
sl@0: ** supported, if not we fall back to dotlockLockingStyle.
sl@0: */
sl@0: static int testLockingStyle(int fd){
sl@0:   struct flock lockInfo;
sl@0: 
sl@0:   /* Test byte-range lock using fcntl(). If the call succeeds, 
sl@0:   ** assume that the file-system supports POSIX style locks. 
sl@0:   */
sl@0:   lockInfo.l_len = 1;
sl@0:   lockInfo.l_start = 0;
sl@0:   lockInfo.l_whence = SEEK_SET;
sl@0:   lockInfo.l_type = F_RDLCK;
sl@0:   if( fcntl(fd, F_GETLK, &lockInfo)!=-1 ) {
sl@0:     return LOCKING_STYLE_POSIX;
sl@0:   }
sl@0:   
sl@0:   /* Testing for flock() can give false positives.  So if if the above 
sl@0:   ** test fails, then we fall back to using dot-file style locking.
sl@0:   */  
sl@0:   return LOCKING_STYLE_DOTFILE;
sl@0: }
sl@0: #endif
sl@0: 
sl@0: /* 
sl@0: ** If SQLITE_ENABLE_LOCKING_STYLE is defined, this function Examines the 
sl@0: ** f_fstypename entry in the statfs structure as returned by stat() for 
sl@0: ** the file system hosting the database file and selects  the appropriate
sl@0: ** locking style based on its value.  These values and assignments are 
sl@0: ** based on Darwin/OSX behavior and have not been thoroughly tested on 
sl@0: ** other systems.
sl@0: **
sl@0: ** If SQLITE_ENABLE_LOCKING_STYLE is not defined, this function always
sl@0: ** returns LOCKING_STYLE_POSIX.
sl@0: */
sl@0: static int detectLockingStyle(
sl@0:   sqlite3_vfs *pVfs,
sl@0:   const char *filePath, 
sl@0:   int fd
sl@0: ){
sl@0: #ifdef SQLITE_ENABLE_LOCKING_STYLE
sl@0:   struct Mapping {
sl@0:     const char *zFilesystem;
sl@0:     int eLockingStyle;
sl@0:   } aMap[] = {
sl@0:     { "hfs",    LOCKING_STYLE_POSIX },
sl@0:     { "ufs",    LOCKING_STYLE_POSIX },
sl@0:     { "afpfs",  LOCKING_STYLE_AFP },
sl@0:     { "smbfs",  LOCKING_STYLE_FLOCK },
sl@0:     { "msdos",  LOCKING_STYLE_DOTFILE },
sl@0:     { "webdav", LOCKING_STYLE_NONE },
sl@0:     { 0, 0 }
sl@0:   };
sl@0:   int i;
sl@0:   struct statfs fsInfo;
sl@0: 
sl@0:   if( !filePath ){
sl@0:     return LOCKING_STYLE_NONE;
sl@0:   }
sl@0:   if( pVfs->pAppData ){
sl@0:     return (int)pVfs->pAppData;
sl@0:   }
sl@0: 
sl@0:   if( statfs(filePath, &fsInfo) != -1 ){
sl@0:     if( fsInfo.f_flags & MNT_RDONLY ){
sl@0:       return LOCKING_STYLE_NONE;
sl@0:     }
sl@0:     for(i=0; aMap[i].zFilesystem; i++){
sl@0:       if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
sl@0:         return aMap[i].eLockingStyle;
sl@0:       }
sl@0:     }
sl@0:   }
sl@0: 
sl@0:   /* Default case. Handles, amongst others, "nfs". */
sl@0:   return testLockingStyle(fd);  
sl@0: #endif
sl@0:   return LOCKING_STYLE_POSIX;
sl@0: }
sl@0: 
sl@0: /*
sl@0: ** Given a file descriptor, locate lockInfo and openCnt structures that
sl@0: ** describes that file descriptor.  Create new ones if necessary.  The
sl@0: ** return values might be uninitialized if an error occurs.
sl@0: **
sl@0: ** Return an appropriate error code.
sl@0: */
sl@0: static int findLockInfo(
sl@0:   int fd,                      /* The file descriptor used in the key */
sl@0:   struct lockInfo **ppLock,    /* Return the lockInfo structure here */
sl@0:   struct openCnt **ppOpen      /* Return the openCnt structure here */
sl@0: ){
sl@0:   int rc;
sl@0:   struct lockKey key1;
sl@0:   struct openKey key2;
sl@0:   struct stat statbuf;
sl@0:   struct lockInfo *pLock;
sl@0:   struct openCnt *pOpen;
sl@0:   rc = fstat(fd, &statbuf);
sl@0:   if( rc!=0 ){
sl@0: #ifdef EOVERFLOW
sl@0:     if( errno==EOVERFLOW ) return SQLITE_NOLFS;
sl@0: #endif
sl@0:     return SQLITE_IOERR;
sl@0:   }
sl@0: 
sl@0:   /* On OS X on an msdos filesystem, the inode number is reported
sl@0:   ** incorrectly for zero-size files.  See ticket #3260.  To work
sl@0:   ** around this problem (we consider it a bug in OS X, not SQLite)
sl@0:   ** we always increase the file size to 1 by writing a single byte
sl@0:   ** prior to accessing the inode number.  The one byte written is
sl@0:   ** an ASCII 'S' character which also happens to be the first byte
sl@0:   ** in the header of every SQLite database.  In this way, if there
sl@0:   ** is a race condition such that another thread has already populated
sl@0:   ** the first page of the database, no damage is done.
sl@0:   */
sl@0:   if( statbuf.st_size==0 ){
sl@0:     write(fd, "S", 1);
sl@0:     rc = fstat(fd, &statbuf);
sl@0:     if( rc!=0 ){
sl@0:       return SQLITE_IOERR;
sl@0:     }
sl@0:   }
sl@0: 
sl@0:   memset(&key1, 0, sizeof(key1));
sl@0:   key1.dev = statbuf.st_dev;
sl@0:   key1.ino = statbuf.st_ino;
sl@0: #if SQLITE_THREADSAFE
sl@0:   if( threadsOverrideEachOthersLocks<0 ){
sl@0:     testThreadLockingBehavior(fd);
sl@0:   }
sl@0:   key1.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
sl@0: #endif
sl@0:   memset(&key2, 0, sizeof(key2));
sl@0:   key2.dev = statbuf.st_dev;
sl@0:   key2.ino = statbuf.st_ino;
sl@0:   pLock = lockList;
sl@0:   while( pLock && memcmp(&key1, &pLock->key, sizeof(key1)) ){
sl@0:     pLock = pLock->pNext;
sl@0:   }
sl@0:   if( pLock==0 ){
sl@0:     pLock = sqlite3_malloc( sizeof(*pLock) );
sl@0:     if( pLock==0 ){
sl@0:       rc = SQLITE_NOMEM;
sl@0:       goto exit_findlockinfo;
sl@0:     }
sl@0:     pLock->key = key1;
sl@0:     pLock->nRef = 1;
sl@0:     pLock->cnt = 0;
sl@0:     pLock->locktype = 0;
sl@0:     pLock->pNext = lockList;
sl@0:     pLock->pPrev = 0;
sl@0:     if( lockList ) lockList->pPrev = pLock;
sl@0:     lockList = pLock;
sl@0:   }else{
sl@0:     pLock->nRef++;
sl@0:   }
sl@0:   *ppLock = pLock;
sl@0:   if( ppOpen!=0 ){
sl@0:     pOpen = openList;
sl@0:     while( pOpen && memcmp(&key2, &pOpen->key, sizeof(key2)) ){
sl@0:       pOpen = pOpen->pNext;
sl@0:     }
sl@0:     if( pOpen==0 ){
sl@0:       pOpen = sqlite3_malloc( sizeof(*pOpen) );
sl@0:       if( pOpen==0 ){
sl@0:         releaseLockInfo(pLock);
sl@0:         rc = SQLITE_NOMEM;
sl@0:         goto exit_findlockinfo;
sl@0:       }
sl@0:       pOpen->key = key2;
sl@0:       pOpen->nRef = 1;
sl@0:       pOpen->nLock = 0;
sl@0:       pOpen->nPending = 0;
sl@0:       pOpen->aPending = 0;
sl@0:       pOpen->pNext = openList;
sl@0:       pOpen->pPrev = 0;
sl@0:       if( openList ) openList->pPrev = pOpen;
sl@0:       openList = pOpen;
sl@0:     }else{
sl@0:       pOpen->nRef++;
sl@0:     }
sl@0:     *ppOpen = pOpen;
sl@0:   }
sl@0: 
sl@0: exit_findlockinfo:
sl@0:   return rc;
sl@0: }
sl@0: 
sl@0: #ifdef SQLITE_DEBUG
sl@0: /*
sl@0: ** Helper function for printing out trace information from debugging
sl@0: ** binaries. This returns the string represetation of the supplied
sl@0: ** integer lock-type.
sl@0: */
sl@0: static const char *locktypeName(int locktype){
sl@0:   switch( locktype ){
sl@0:   case NO_LOCK: return "NONE";
sl@0:   case SHARED_LOCK: return "SHARED";
sl@0:   case RESERVED_LOCK: return "RESERVED";
sl@0:   case PENDING_LOCK: return "PENDING";
sl@0:   case EXCLUSIVE_LOCK: return "EXCLUSIVE";
sl@0:   }
sl@0:   return "ERROR";
sl@0: }
sl@0: #endif
sl@0: 
sl@0: /*
sl@0: ** If we are currently in a different thread than the thread that the
sl@0: ** unixFile argument belongs to, then transfer ownership of the unixFile
sl@0: ** over to the current thread.
sl@0: **
sl@0: ** A unixFile is only owned by a thread on systems where one thread is
sl@0: ** unable to override locks created by a different thread.  RedHat9 is
sl@0: ** an example of such a system.
sl@0: **
sl@0: ** Ownership transfer is only allowed if the unixFile is currently unlocked.
sl@0: ** If the unixFile is locked and an ownership is wrong, then return
sl@0: ** SQLITE_MISUSE.  SQLITE_OK is returned if everything works.
sl@0: */
sl@0: #if SQLITE_THREADSAFE
sl@0: static int transferOwnership(unixFile *pFile){
sl@0:   int rc;
sl@0:   pthread_t hSelf;
sl@0:   if( threadsOverrideEachOthersLocks ){
sl@0:     /* Ownership transfers not needed on this system */
sl@0:     return SQLITE_OK;
sl@0:   }
sl@0:   hSelf = pthread_self();
sl@0:   if( pthread_equal(pFile->tid, hSelf) ){
sl@0:     /* We are still in the same thread */
sl@0:     OSTRACE1("No-transfer, same thread\n");
sl@0:     return SQLITE_OK;
sl@0:   }
sl@0:   if( pFile->locktype!=NO_LOCK ){
sl@0:     /* We cannot change ownership while we are holding a lock! */
sl@0:     return SQLITE_MISUSE;
sl@0:   }
sl@0:   OSTRACE4("Transfer ownership of %d from %d to %d\n",
sl@0:             pFile->h, pFile->tid, hSelf);
sl@0:   pFile->tid = hSelf;
sl@0:   if (pFile->pLock != NULL) {
sl@0:     releaseLockInfo(pFile->pLock);
sl@0:     rc = findLockInfo(pFile->h, &pFile->pLock, 0);
sl@0:     OSTRACE5("LOCK    %d is now %s(%s,%d)\n", pFile->h,
sl@0:            locktypeName(pFile->locktype),
sl@0:            locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
sl@0:     return rc;
sl@0:   } else {
sl@0:     return SQLITE_OK;
sl@0:   }
sl@0: }
sl@0: #else
sl@0:   /* On single-threaded builds, ownership transfer is a no-op */
sl@0: # define transferOwnership(X) SQLITE_OK
sl@0: #endif
sl@0: 
sl@0: /*
sl@0: ** Seek to the offset passed as the second argument, then read cnt 
sl@0: ** bytes into pBuf. Return the number of bytes actually read.
sl@0: **
sl@0: ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
sl@0: ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
sl@0: ** one system to another.  Since SQLite does not define USE_PREAD
sl@0: ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
sl@0: ** See tickets #2741 and #2681.
sl@0: */
sl@0: static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
sl@0:   int got;
sl@0:   i64 newOffset;
sl@0:   TIMER_START;
sl@0: #if defined(USE_PREAD)
sl@0:   got = pread(id->h, pBuf, cnt, offset);
sl@0:   SimulateIOError( got = -1 );
sl@0: #elif defined(USE_PREAD64)
sl@0:   got = pread64(id->h, pBuf, cnt, offset);
sl@0:   SimulateIOError( got = -1 );
sl@0: #else
sl@0:   newOffset = lseek(id->h, offset, SEEK_SET);
sl@0:   SimulateIOError( newOffset-- );
sl@0:   if( newOffset!=offset ){
sl@0:     return -1;
sl@0:   }
sl@0:   got = read(id->h, pBuf, cnt);
sl@0: #endif
sl@0:   TIMER_END;
sl@0:   OSTRACE5("READ    %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
sl@0:   return got;
sl@0: }
sl@0: 
sl@0: /*
sl@0: ** Read data from a file into a buffer.  Return SQLITE_OK if all
sl@0: ** bytes were read successfully and SQLITE_IOERR if anything goes
sl@0: ** wrong.
sl@0: */
sl@0: static int unixRead(
sl@0:   sqlite3_file *id, 
sl@0:   void *pBuf, 
sl@0:   int amt,
sl@0:   sqlite3_int64 offset
sl@0: ){
sl@0:   int got;
sl@0:   assert( id );
sl@0:   got = seekAndRead((unixFile*)id, offset, pBuf, amt);
sl@0:   if( got==amt ){
sl@0:     return SQLITE_OK;
sl@0:   }else if( got<0 ){
sl@0:     return SQLITE_IOERR_READ;
sl@0:   }else{
sl@0:     memset(&((char*)pBuf)[got], 0, amt-got);
sl@0:     return SQLITE_IOERR_SHORT_READ;
sl@0:   }
sl@0: }
sl@0: 
sl@0: /*
sl@0: ** Seek to the offset in id->offset then read cnt bytes into pBuf.
sl@0: ** Return the number of bytes actually read.  Update the offset.
sl@0: */
sl@0: static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
sl@0:   int got;
sl@0:   i64 newOffset;
sl@0:   TIMER_START;
sl@0: #if defined(USE_PREAD)
sl@0:   got = pwrite(id->h, pBuf, cnt, offset);
sl@0: #elif defined(USE_PREAD64)
sl@0:   got = pwrite64(id->h, pBuf, cnt, offset);
sl@0: #else
sl@0:   newOffset = lseek(id->h, offset, SEEK_SET);
sl@0:   if( newOffset!=offset ){
sl@0:     return -1;
sl@0:   }
sl@0:   got = write(id->h, pBuf, cnt);
sl@0: #endif
sl@0:   TIMER_END;
sl@0:   OSTRACE5("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
sl@0:   return got;
sl@0: }
sl@0: 
sl@0: 
sl@0: /*
sl@0: ** Write data from a buffer into a file.  Return SQLITE_OK on success
sl@0: ** or some other error code on failure.
sl@0: */
sl@0: static int unixWrite(
sl@0:   sqlite3_file *id, 
sl@0:   const void *pBuf, 
sl@0:   int amt,
sl@0:   sqlite3_int64 offset 
sl@0: ){
sl@0:   int wrote = 0;
sl@0:   assert( id );
sl@0:   assert( amt>0 );
sl@0:   while( amt>0 && (wrote = seekAndWrite((unixFile*)id, offset, pBuf, amt))>0 ){
sl@0:     amt -= wrote;
sl@0:     offset += wrote;
sl@0:     pBuf = &((char*)pBuf)[wrote];
sl@0:   }
sl@0:   SimulateIOError(( wrote=(-1), amt=1 ));
sl@0:   SimulateDiskfullError(( wrote=0, amt=1 ));
sl@0:   if( amt>0 ){
sl@0:     if( wrote<0 ){
sl@0:       return SQLITE_IOERR_WRITE;
sl@0:     }else{
sl@0:       return SQLITE_FULL;
sl@0:     }
sl@0:   }
sl@0:   return SQLITE_OK;
sl@0: }
sl@0: 
sl@0: #ifdef SQLITE_TEST
sl@0: /*
sl@0: ** Count the number of fullsyncs and normal syncs.  This is used to test
sl@0: ** that syncs and fullsyncs are occuring at the right times.
sl@0: */
sl@0: int sqlite3_sync_count = 0;
sl@0: int sqlite3_fullsync_count = 0;
sl@0: #endif
sl@0: 
sl@0: /*
sl@0: ** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
sl@0: ** Otherwise use fsync() in its place.
sl@0: */
sl@0: #ifndef HAVE_FDATASYNC
sl@0: # define fdatasync fsync
sl@0: #endif
sl@0: 
sl@0: /*
sl@0: ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
sl@0: ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
sl@0: ** only available on Mac OS X.  But that could change.
sl@0: */
sl@0: #ifdef F_FULLFSYNC
sl@0: # define HAVE_FULLFSYNC 1
sl@0: #else
sl@0: # define HAVE_FULLFSYNC 0
sl@0: #endif
sl@0: 
sl@0: 
sl@0: /*
sl@0: ** The fsync() system call does not work as advertised on many
sl@0: ** unix systems.  The following procedure is an attempt to make
sl@0: ** it work better.
sl@0: **
sl@0: ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
sl@0: ** for testing when we want to run through the test suite quickly.
sl@0: ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
sl@0: ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
sl@0: ** or power failure will likely corrupt the database file.
sl@0: */
sl@0: static int full_fsync(int fd, int fullSync, int dataOnly){
sl@0:   int rc;
sl@0: 
sl@0:   /* Record the number of times that we do a normal fsync() and 
sl@0:   ** FULLSYNC.  This is used during testing to verify that this procedure
sl@0:   ** gets called with the correct arguments.
sl@0:   */
sl@0: #ifdef SQLITE_TEST
sl@0:   if( fullSync ) sqlite3_fullsync_count++;
sl@0:   sqlite3_sync_count++;
sl@0: #endif
sl@0: 
sl@0:   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
sl@0:   ** no-op
sl@0:   */
sl@0: #ifdef SQLITE_NO_SYNC
sl@0:   rc = SQLITE_OK;
sl@0: #else
sl@0: 
sl@0: #if HAVE_FULLFSYNC
sl@0:   if( fullSync ){
sl@0:     rc = fcntl(fd, F_FULLFSYNC, 0);
sl@0:   }else{
sl@0:     rc = 1;
sl@0:   }
sl@0:   /* If the FULLFSYNC failed, fall back to attempting an fsync().
sl@0:    * It shouldn't be possible for fullfsync to fail on the local 
sl@0:    * file system (on OSX), so failure indicates that FULLFSYNC
sl@0:    * isn't supported for this file system. So, attempt an fsync 
sl@0:    * and (for now) ignore the overhead of a superfluous fcntl call.  
sl@0:    * It'd be better to detect fullfsync support once and avoid 
sl@0:    * the fcntl call every time sync is called.
sl@0:    */
sl@0:   if( rc ) rc = fsync(fd);
sl@0: 
sl@0: #else 
sl@0:   if( dataOnly ){
sl@0:     rc = fdatasync(fd);
sl@0:   }else{
sl@0:     rc = fsync(fd);
sl@0:   }
sl@0: #endif /* HAVE_FULLFSYNC */
sl@0: #endif /* defined(SQLITE_NO_SYNC) */
sl@0: 
sl@0:   return rc;
sl@0: }
sl@0: 
sl@0: /*
sl@0: ** Make sure all writes to a particular file are committed to disk.
sl@0: **
sl@0: ** If dataOnly==0 then both the file itself and its metadata (file
sl@0: ** size, access time, etc) are synced.  If dataOnly!=0 then only the
sl@0: ** file data is synced.
sl@0: **
sl@0: ** Under Unix, also make sure that the directory entry for the file
sl@0: ** has been created by fsync-ing the directory that contains the file.
sl@0: ** If we do not do this and we encounter a power failure, the directory
sl@0: ** entry for the journal might not exist after we reboot.  The next
sl@0: ** SQLite to access the file will not know that the journal exists (because
sl@0: ** the directory entry for the journal was never created) and the transaction
sl@0: ** will not roll back - possibly leading to database corruption.
sl@0: */
sl@0: static int unixSync(sqlite3_file *id, int flags){
sl@0:   int rc;
sl@0:   unixFile *pFile = (unixFile*)id;
sl@0: 
sl@0:   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
sl@0:   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
sl@0: 
sl@0:   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
sl@0:   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
sl@0:       || (flags&0x0F)==SQLITE_SYNC_FULL
sl@0:   );
sl@0: 
sl@0:   assert( pFile );
sl@0:   OSTRACE2("SYNC    %-3d\n", pFile->h);
sl@0:   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
sl@0:   SimulateIOError( rc=1 );
sl@0:   if( rc ){
sl@0:     return SQLITE_IOERR_FSYNC;
sl@0:   }
sl@0:   if( pFile->dirfd>=0 ){
sl@0:     OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
sl@0:             HAVE_FULLFSYNC, isFullsync);
sl@0: #ifndef SQLITE_DISABLE_DIRSYNC
sl@0:     /* The directory sync is only attempted if full_fsync is
sl@0:     ** turned off or unavailable.  If a full_fsync occurred above,
sl@0:     ** then the directory sync is superfluous.
sl@0:     */
sl@0:     if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
sl@0:        /*
sl@0:        ** We have received multiple reports of fsync() returning
sl@0:        ** errors when applied to directories on certain file systems.
sl@0:        ** A failed directory sync is not a big deal.  So it seems
sl@0:        ** better to ignore the error.  Ticket #1657
sl@0:        */
sl@0:        /* return SQLITE_IOERR; */
sl@0:     }
sl@0: #endif
sl@0:     close(pFile->dirfd);  /* Only need to sync once, so close the directory */
sl@0:     pFile->dirfd = -1;    /* when we are done. */
sl@0:   }
sl@0:   return SQLITE_OK;
sl@0: }
sl@0: 
sl@0: /*
sl@0: ** Truncate an open file to a specified size
sl@0: */
sl@0: static int unixTruncate(sqlite3_file *id, i64 nByte){
sl@0:   int rc;
sl@0:   assert( id );
sl@0:   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
sl@0:   rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
sl@0:   if( rc ){
sl@0:     return SQLITE_IOERR_TRUNCATE;
sl@0:   }else{
sl@0:     return SQLITE_OK;
sl@0:   }
sl@0: }
sl@0: 
sl@0: /*
sl@0: ** Determine the current size of a file in bytes
sl@0: */
sl@0: static int unixFileSize(sqlite3_file *id, i64 *pSize){
sl@0:   int rc;
sl@0:   struct stat buf;
sl@0:   assert( id );
sl@0:   rc = fstat(((unixFile*)id)->h, &buf);
sl@0:   SimulateIOError( rc=1 );
sl@0:   if( rc!=0 ){
sl@0:     return SQLITE_IOERR_FSTAT;
sl@0:   }
sl@0:   *pSize = buf.st_size;
sl@0: 
sl@0:   /* When opening a zero-size database, the findLockInfo() procedure
sl@0:   ** writes a single byte into that file in order to work around a bug
sl@0:   ** in the OS-X msdos filesystem.  In order to avoid problems with upper
sl@0:   ** layers, we need to report this file size as zero even though it is
sl@0:   ** really 1.   Ticket #3260.
sl@0:   */
sl@0:   if( *pSize==1 ) *pSize = 0;
sl@0: 
sl@0: 
sl@0:   return SQLITE_OK;
sl@0: }
sl@0: 
sl@0: /*
sl@0: ** This routine checks if there is a RESERVED lock held on the specified
sl@0: ** file by this or any other process. If such a lock is held, return
sl@0: ** non-zero.  If the file is unlocked or holds only SHARED locks, then
sl@0: ** return zero.
sl@0: */
sl@0: static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
sl@0:   int r = 0;
sl@0:   unixFile *pFile = (unixFile*)id;
sl@0: 
sl@0:   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
sl@0: 
sl@0:   assert( pFile );
sl@0:   enterMutex(); /* Because pFile->pLock is shared across threads */
sl@0: 
sl@0:   /* Check if a thread in this process holds such a lock */
sl@0:   if( pFile->pLock->locktype>SHARED_LOCK ){
sl@0:     r = 1;
sl@0:   }
sl@0: 
sl@0:   /* Otherwise see if some other process holds it.
sl@0:   */
sl@0:   if( !r ){
sl@0:     struct flock lock;
sl@0:     lock.l_whence = SEEK_SET;
sl@0:     lock.l_start = RESERVED_BYTE;
sl@0:     lock.l_len = 1;
sl@0:     lock.l_type = F_WRLCK;
sl@0:     fcntl(pFile->h, F_GETLK, &lock);
sl@0:     if( lock.l_type!=F_UNLCK ){
sl@0:       r = 1;
sl@0:     }
sl@0:   }
sl@0:   
sl@0:   leaveMutex();
sl@0:   OSTRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
sl@0: 
sl@0:   *pResOut = r;
sl@0:   return SQLITE_OK;
sl@0: }
sl@0: 
sl@0: /*
sl@0: ** Lock the file with the lock specified by parameter locktype - one
sl@0: ** of the following:
sl@0: **
sl@0: **     (1) SHARED_LOCK
sl@0: **     (2) RESERVED_LOCK
sl@0: **     (3) PENDING_LOCK
sl@0: **     (4) EXCLUSIVE_LOCK
sl@0: **
sl@0: ** Sometimes when requesting one lock state, additional lock states
sl@0: ** are inserted in between.  The locking might fail on one of the later
sl@0: ** transitions leaving the lock state different from what it started but
sl@0: ** still short of its goal.  The following chart shows the allowed
sl@0: ** transitions and the inserted intermediate states:
sl@0: **
sl@0: **    UNLOCKED -> SHARED
sl@0: **    SHARED -> RESERVED
sl@0: **    SHARED -> (PENDING) -> EXCLUSIVE
sl@0: **    RESERVED -> (PENDING) -> EXCLUSIVE
sl@0: **    PENDING -> EXCLUSIVE
sl@0: **
sl@0: ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
sl@0: ** routine to lower a locking level.
sl@0: */
sl@0: static int unixLock(sqlite3_file *id, int locktype){
sl@0:   /* The following describes the implementation of the various locks and
sl@0:   ** lock transitions in terms of the POSIX advisory shared and exclusive
sl@0:   ** lock primitives (called read-locks and write-locks below, to avoid
sl@0:   ** confusion with SQLite lock names). The algorithms are complicated
sl@0:   ** slightly in order to be compatible with windows systems simultaneously
sl@0:   ** accessing the same database file, in case that is ever required.
sl@0:   **
sl@0:   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
sl@0:   ** byte', each single bytes at well known offsets, and the 'shared byte
sl@0:   ** range', a range of 510 bytes at a well known offset.
sl@0:   **
sl@0:   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
sl@0:   ** byte'.  If this is successful, a random byte from the 'shared byte
sl@0:   ** range' is read-locked and the lock on the 'pending byte' released.
sl@0:   **
sl@0:   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
sl@0:   ** A RESERVED lock is implemented by grabbing a write-lock on the
sl@0:   ** 'reserved byte'. 
sl@0:   **
sl@0:   ** A process may only obtain a PENDING lock after it has obtained a
sl@0:   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
sl@0:   ** on the 'pending byte'. This ensures that no new SHARED locks can be
sl@0:   ** obtained, but existing SHARED locks are allowed to persist. A process
sl@0:   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
sl@0:   ** This property is used by the algorithm for rolling back a journal file
sl@0:   ** after a crash.
sl@0:   **
sl@0:   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
sl@0:   ** implemented by obtaining a write-lock on the entire 'shared byte
sl@0:   ** range'. Since all other locks require a read-lock on one of the bytes
sl@0:   ** within this range, this ensures that no other locks are held on the
sl@0:   ** database. 
sl@0:   **
sl@0:   ** The reason a single byte cannot be used instead of the 'shared byte
sl@0:   ** range' is that some versions of windows do not support read-locks. By
sl@0:   ** locking a random byte from a range, concurrent SHARED locks may exist
sl@0:   ** even if the locking primitive used is always a write-lock.
sl@0:   */
sl@0:   int rc = SQLITE_OK;
sl@0:   unixFile *pFile = (unixFile*)id;
sl@0:   struct lockInfo *pLock = pFile->pLock;
sl@0:   struct flock lock;
sl@0:   int s;
sl@0: 
sl@0:   assert( pFile );
sl@0:   OSTRACE7("LOCK    %d %s was %s(%s,%d) pid=%d\n", pFile->h,
sl@0:       locktypeName(locktype), locktypeName(pFile->locktype),
sl@0:       locktypeName(pLock->locktype), pLock->cnt , getpid());
sl@0: 
sl@0:   /* If there is already a lock of this type or more restrictive on the
sl@0:   ** unixFile, do nothing. Don't use the end_lock: exit path, as
sl@0:   ** enterMutex() hasn't been called yet.
sl@0:   */
sl@0:   if( pFile->locktype>=locktype ){
sl@0:     OSTRACE3("LOCK    %d %s ok (already held)\n", pFile->h,
sl@0:             locktypeName(locktype));
sl@0:     return SQLITE_OK;
sl@0:   }
sl@0: 
sl@0:   /* Make sure the locking sequence is correct
sl@0:   */
sl@0:   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
sl@0:   assert( locktype!=PENDING_LOCK );
sl@0:   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
sl@0: 
sl@0:   /* This mutex is needed because pFile->pLock is shared across threads
sl@0:   */
sl@0:   enterMutex();
sl@0: 
sl@0:   /* Make sure the current thread owns the pFile.
sl@0:   */
sl@0:   rc = transferOwnership(pFile);
sl@0:   if( rc!=SQLITE_OK ){
sl@0:     leaveMutex();
sl@0:     return rc;
sl@0:   }
sl@0:   pLock = pFile->pLock;
sl@0: 
sl@0:   /* If some thread using this PID has a lock via a different unixFile*
sl@0:   ** handle that precludes the requested lock, return BUSY.
sl@0:   */
sl@0:   if( (pFile->locktype!=pLock->locktype && 
sl@0:           (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
sl@0:   ){
sl@0:     rc = SQLITE_BUSY;
sl@0:     goto end_lock;
sl@0:   }
sl@0: 
sl@0:   /* If a SHARED lock is requested, and some thread using this PID already
sl@0:   ** has a SHARED or RESERVED lock, then increment reference counts and
sl@0:   ** return SQLITE_OK.
sl@0:   */
sl@0:   if( locktype==SHARED_LOCK && 
sl@0:       (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
sl@0:     assert( locktype==SHARED_LOCK );
sl@0:     assert( pFile->locktype==0 );
sl@0:     assert( pLock->cnt>0 );
sl@0:     pFile->locktype = SHARED_LOCK;
sl@0:     pLock->cnt++;
sl@0:     pFile->pOpen->nLock++;
sl@0:     goto end_lock;
sl@0:   }
sl@0: 
sl@0:   lock.l_len = 1L;
sl@0: 
sl@0:   lock.l_whence = SEEK_SET;
sl@0: 
sl@0:   /* A PENDING lock is needed before acquiring a SHARED lock and before
sl@0:   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
sl@0:   ** be released.
sl@0:   */
sl@0:   if( locktype==SHARED_LOCK 
sl@0:       || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
sl@0:   ){
sl@0:     lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
sl@0:     lock.l_start = PENDING_BYTE;
sl@0:     s = fcntl(pFile->h, F_SETLK, &lock);
sl@0:     if( s==(-1) ){
sl@0:       rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
sl@0:       goto end_lock;
sl@0:     }
sl@0:   }
sl@0: 
sl@0: 
sl@0:   /* If control gets to this point, then actually go ahead and make
sl@0:   ** operating system calls for the specified lock.
sl@0:   */
sl@0:   if( locktype==SHARED_LOCK ){
sl@0:     assert( pLock->cnt==0 );
sl@0:     assert( pLock->locktype==0 );
sl@0: 
sl@0:     /* Now get the read-lock */
sl@0:     lock.l_start = SHARED_FIRST;
sl@0:     lock.l_len = SHARED_SIZE;
sl@0:     s = fcntl(pFile->h, F_SETLK, &lock);
sl@0: 
sl@0:     /* Drop the temporary PENDING lock */
sl@0:     lock.l_start = PENDING_BYTE;
sl@0:     lock.l_len = 1L;
sl@0:     lock.l_type = F_UNLCK;
sl@0:     if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
sl@0:       rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
sl@0:       goto end_lock;
sl@0:     }
sl@0:     if( s==(-1) ){
sl@0:       rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
sl@0:     }else{
sl@0:       pFile->locktype = SHARED_LOCK;
sl@0:       pFile->pOpen->nLock++;
sl@0:       pLock->cnt = 1;
sl@0:     }
sl@0:   }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
sl@0:     /* We are trying for an exclusive lock but another thread in this
sl@0:     ** same process is still holding a shared lock. */
sl@0:     rc = SQLITE_BUSY;
sl@0:   }else{
sl@0:     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
sl@0:     ** assumed that there is a SHARED or greater lock on the file
sl@0:     ** already.
sl@0:     */
sl@0:     assert( 0!=pFile->locktype );
sl@0:     lock.l_type = F_WRLCK;
sl@0:     switch( locktype ){
sl@0:       case RESERVED_LOCK:
sl@0:         lock.l_start = RESERVED_BYTE;
sl@0:         break;
sl@0:       case EXCLUSIVE_LOCK:
sl@0:         lock.l_start = SHARED_FIRST;
sl@0:         lock.l_len = SHARED_SIZE;
sl@0:         break;
sl@0:       default:
sl@0:         assert(0);
sl@0:     }
sl@0:     s = fcntl(pFile->h, F_SETLK, &lock);
sl@0:     if( s==(-1) ){
sl@0:       rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
sl@0:     }
sl@0:   }
sl@0:   
sl@0:   if( rc==SQLITE_OK ){
sl@0:     pFile->locktype = locktype;
sl@0:     pLock->locktype = locktype;
sl@0:   }else if( locktype==EXCLUSIVE_LOCK ){
sl@0:     pFile->locktype = PENDING_LOCK;
sl@0:     pLock->locktype = PENDING_LOCK;
sl@0:   }
sl@0: 
sl@0: end_lock:
sl@0:   leaveMutex();
sl@0:   OSTRACE4("LOCK    %d %s %s\n", pFile->h, locktypeName(locktype), 
sl@0:       rc==SQLITE_OK ? "ok" : "failed");
sl@0:   return rc;
sl@0: }
sl@0: 
sl@0: /*
sl@0: ** Lower the locking level on file descriptor pFile to locktype.  locktype
sl@0: ** must be either NO_LOCK or SHARED_LOCK.
sl@0: **
sl@0: ** If the locking level of the file descriptor is already at or below
sl@0: ** the requested locking level, this routine is a no-op.
sl@0: */
sl@0: static int unixUnlock(sqlite3_file *id, int locktype){
sl@0:   struct lockInfo *pLock;
sl@0:   struct flock lock;
sl@0:   int rc = SQLITE_OK;
sl@0:   unixFile *pFile = (unixFile*)id;
sl@0:   int h;
sl@0: 
sl@0:   assert( pFile );
sl@0:   OSTRACE7("UNLOCK  %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
sl@0:       pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
sl@0: 
sl@0:   assert( locktype<=SHARED_LOCK );
sl@0:   if( pFile->locktype<=locktype ){
sl@0:     return SQLITE_OK;
sl@0:   }
sl@0:   if( CHECK_THREADID(pFile) ){
sl@0:     return SQLITE_MISUSE;
sl@0:   }
sl@0:   enterMutex();
sl@0:   h = pFile->h;
sl@0:   pLock = pFile->pLock;
sl@0:   assert( pLock->cnt!=0 );
sl@0:   if( pFile->locktype>SHARED_LOCK ){
sl@0:     assert( pLock->locktype==pFile->locktype );
sl@0:     SimulateIOErrorBenign(1);
sl@0:     SimulateIOError( h=(-1) )
sl@0:     SimulateIOErrorBenign(0);
sl@0:     if( locktype==SHARED_LOCK ){
sl@0:       lock.l_type = F_RDLCK;
sl@0:       lock.l_whence = SEEK_SET;
sl@0:       lock.l_start = SHARED_FIRST;
sl@0:       lock.l_len = SHARED_SIZE;
sl@0:       if( fcntl(h, F_SETLK, &lock)==(-1) ){
sl@0:         rc = SQLITE_IOERR_RDLOCK;
sl@0:       }
sl@0:     }
sl@0:     lock.l_type = F_UNLCK;
sl@0:     lock.l_whence = SEEK_SET;
sl@0:     lock.l_start = PENDING_BYTE;
sl@0:     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
sl@0:     if( fcntl(h, F_SETLK, &lock)!=(-1) ){
sl@0:       pLock->locktype = SHARED_LOCK;
sl@0:     }else{
sl@0:       rc = SQLITE_IOERR_UNLOCK;
sl@0:     }
sl@0:   }
sl@0:   if( locktype==NO_LOCK ){
sl@0:     struct openCnt *pOpen;
sl@0: 
sl@0:     /* Decrement the shared lock counter.  Release the lock using an
sl@0:     ** OS call only when all threads in this same process have released
sl@0:     ** the lock.
sl@0:     */
sl@0:     pLock->cnt--;
sl@0:     if( pLock->cnt==0 ){
sl@0:       lock.l_type = F_UNLCK;
sl@0:       lock.l_whence = SEEK_SET;
sl@0:       lock.l_start = lock.l_len = 0L;
sl@0:       SimulateIOErrorBenign(1);
sl@0:       SimulateIOError( h=(-1) )
sl@0:       SimulateIOErrorBenign(0);
sl@0:       if( fcntl(h, F_SETLK, &lock)!=(-1) ){
sl@0:         pLock->locktype = NO_LOCK;
sl@0:       }else{
sl@0:         rc = SQLITE_IOERR_UNLOCK;
sl@0:         pLock->cnt = 1;
sl@0:       }
sl@0:     }
sl@0: 
sl@0:     /* Decrement the count of locks against this same file.  When the
sl@0:     ** count reaches zero, close any other file descriptors whose close
sl@0:     ** was deferred because of outstanding locks.
sl@0:     */
sl@0:     if( rc==SQLITE_OK ){
sl@0:       pOpen = pFile->pOpen;
sl@0:       pOpen->nLock--;
sl@0:       assert( pOpen->nLock>=0 );
sl@0:       if( pOpen->nLock==0 && pOpen->nPending>0 ){
sl@0:         int i;
sl@0:         for(i=0; i<pOpen->nPending; i++){
sl@0:           close(pOpen->aPending[i]);
sl@0:         }
sl@0:         sqlite3_free(pOpen->aPending);
sl@0:         pOpen->nPending = 0;
sl@0:         pOpen->aPending = 0;
sl@0:       }
sl@0:     }
sl@0:   }
sl@0:   leaveMutex();
sl@0:   if( rc==SQLITE_OK ) pFile->locktype = locktype;
sl@0:   return rc;
sl@0: }
sl@0: 
sl@0: /*
sl@0: ** This function performs the parts of the "close file" operation 
sl@0: ** common to all locking schemes. It closes the directory and file
sl@0: ** handles, if they are valid, and sets all fields of the unixFile
sl@0: ** structure to 0.
sl@0: */
sl@0: static int closeUnixFile(sqlite3_file *id){
sl@0:   unixFile *pFile = (unixFile*)id;
sl@0:   if( pFile ){
sl@0:     if( pFile->dirfd>=0 ){
sl@0:       close(pFile->dirfd);
sl@0:     }
sl@0:     if( pFile->h>=0 ){
sl@0:       close(pFile->h);
sl@0:     }
sl@0:     OSTRACE2("CLOSE   %-3d\n", pFile->h);
sl@0:     OpenCounter(-1);
sl@0:     memset(pFile, 0, sizeof(unixFile));
sl@0:   }
sl@0:   return SQLITE_OK;
sl@0: }
sl@0: 
sl@0: /*
sl@0: ** Close a file.
sl@0: */
sl@0: static int unixClose(sqlite3_file *id){
sl@0:   if( id ){
sl@0:     unixFile *pFile = (unixFile *)id;
sl@0:     unixUnlock(id, NO_LOCK);
sl@0:     enterMutex();
sl@0:     if( pFile->pOpen && pFile->pOpen->nLock ){
sl@0:       /* If there are outstanding locks, do not actually close the file just
sl@0:       ** yet because that would clear those locks.  Instead, add the file
sl@0:       ** descriptor to pOpen->aPending.  It will be automatically closed when
sl@0:       ** the last lock is cleared.
sl@0:       */
sl@0:       int *aNew;
sl@0:       struct openCnt *pOpen = pFile->pOpen;
sl@0:       aNew = sqlite3_realloc(pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
sl@0:       if( aNew==0 ){
sl@0:         /* If a malloc fails, just leak the file descriptor */
sl@0:       }else{
sl@0:         pOpen->aPending = aNew;
sl@0:         pOpen->aPending[pOpen->nPending] = pFile->h;
sl@0:         pOpen->nPending++;
sl@0:         pFile->h = -1;
sl@0:       }
sl@0:     }
sl@0:     releaseLockInfo(pFile->pLock);
sl@0:     releaseOpenCnt(pFile->pOpen);
sl@0:     closeUnixFile(id);
sl@0:     leaveMutex();
sl@0:   }
sl@0:   return SQLITE_OK;
sl@0: }
sl@0: 
sl@0: 
sl@0: #ifdef SQLITE_ENABLE_LOCKING_STYLE
sl@0: #pragma mark AFP Support
sl@0: 
sl@0: /*
sl@0:  ** The afpLockingContext structure contains all afp lock specific state
sl@0:  */
sl@0: typedef struct afpLockingContext afpLockingContext;
sl@0: struct afpLockingContext {
sl@0:   unsigned long long sharedLockByte;
sl@0:   const char *filePath;
sl@0: };
sl@0: 
sl@0: struct ByteRangeLockPB2
sl@0: {
sl@0:   unsigned long long offset;        /* offset to first byte to lock */
sl@0:   unsigned long long length;        /* nbr of bytes to lock */
sl@0:   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
sl@0:   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
sl@0:   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
sl@0:   int fd;                           /* file desc to assoc this lock with */
sl@0: };
sl@0: 
sl@0: #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
sl@0: 
sl@0: /* 
sl@0: ** Return 0 on success, 1 on failure.  To match the behavior of the 
sl@0: ** normal posix file locking (used in unixLock for example), we should 
sl@0: ** provide 'richer' return codes - specifically to differentiate between
sl@0: ** 'file busy' and 'file system error' results.
sl@0: */
sl@0: static int _AFPFSSetLock(
sl@0:   const char *path, 
sl@0:   int fd, 
sl@0:   unsigned long long offset, 
sl@0:   unsigned long long length, 
sl@0:   int setLockFlag
sl@0: ){
sl@0:   struct ByteRangeLockPB2       pb;
sl@0:   int                     err;
sl@0:   
sl@0:   pb.unLockFlag = setLockFlag ? 0 : 1;
sl@0:   pb.startEndFlag = 0;
sl@0:   pb.offset = offset;
sl@0:   pb.length = length; 
sl@0:   pb.fd = fd;
sl@0:   OSTRACE5("AFPLOCK setting lock %s for %d in range %llx:%llx\n", 
sl@0:     (setLockFlag?"ON":"OFF"), fd, offset, length);
sl@0:   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
sl@0:   if ( err==-1 ) {
sl@0:     OSTRACE4("AFPLOCK failed to fsctl() '%s' %d %s\n", path, errno, 
sl@0:       strerror(errno));
sl@0:     return 1; /* error */
sl@0:   } else {
sl@0:     return 0;
sl@0:   }
sl@0: }
sl@0: 
sl@0: /*
sl@0:  ** This routine checks if there is a RESERVED lock held on the specified
sl@0:  ** file by this or any other process. If such a lock is held, return
sl@0:  ** non-zero.  If the file is unlocked or holds only SHARED locks, then
sl@0:  ** return zero.
sl@0:  */
sl@0: static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
sl@0:   int r = 0;
sl@0:   unixFile *pFile = (unixFile*)id;
sl@0:   
sl@0:   assert( pFile ); 
sl@0:   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
sl@0:   
sl@0:   /* Check if a thread in this process holds such a lock */
sl@0:   if( pFile->locktype>SHARED_LOCK ){
sl@0:     r = 1;
sl@0:   }
sl@0:   
sl@0:   /* Otherwise see if some other process holds it.
sl@0:    */
sl@0:   if ( !r ) {
sl@0:     /* lock the byte */
sl@0:     int failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);  
sl@0:     if (failed) {
sl@0:       /* if we failed to get the lock then someone else must have it */
sl@0:       r = 1;
sl@0:     } else {
sl@0:       /* if we succeeded in taking the reserved lock, unlock it to restore
sl@0:       ** the original state */
sl@0:       _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0);
sl@0:     }
sl@0:   }
sl@0:   OSTRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
sl@0:   
sl@0:   *pResOut = r;
sl@0:   return SQLITE_OK;
sl@0: }
sl@0: 
sl@0: /* AFP-style locking following the behavior of unixLock, see the unixLock 
sl@0: ** function comments for details of lock management. */
sl@0: static int afpLock(sqlite3_file *id, int locktype){
sl@0:   int rc = SQLITE_OK;
sl@0:   unixFile *pFile = (unixFile*)id;
sl@0:   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
sl@0:   
sl@0:   assert( pFile );
sl@0:   OSTRACE5("LOCK    %d %s was %s pid=%d\n", pFile->h,
sl@0:          locktypeName(locktype), locktypeName(pFile->locktype), getpid());
sl@0: 
sl@0:   /* If there is already a lock of this type or more restrictive on the
sl@0:   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
sl@0:   ** enterMutex() hasn't been called yet.
sl@0:   */
sl@0:   if( pFile->locktype>=locktype ){
sl@0:     OSTRACE3("LOCK    %d %s ok (already held)\n", pFile->h,
sl@0:            locktypeName(locktype));
sl@0:     return SQLITE_OK;
sl@0:   }
sl@0: 
sl@0:   /* Make sure the locking sequence is correct
sl@0:   */
sl@0:   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
sl@0:   assert( locktype!=PENDING_LOCK );
sl@0:   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
sl@0:   
sl@0:   /* This mutex is needed because pFile->pLock is shared across threads
sl@0:   */
sl@0:   enterMutex();
sl@0: 
sl@0:   /* Make sure the current thread owns the pFile.
sl@0:   */
sl@0:   rc = transferOwnership(pFile);
sl@0:   if( rc!=SQLITE_OK ){
sl@0:     leaveMutex();
sl@0:     return rc;
sl@0:   }
sl@0:     
sl@0:   /* A PENDING lock is needed before acquiring a SHARED lock and before
sl@0:   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
sl@0:   ** be released.
sl@0:   */
sl@0:   if( locktype==SHARED_LOCK 
sl@0:       || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
sl@0:   ){
sl@0:     int failed;
sl@0:     failed = _AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 1);
sl@0:     if (failed) {
sl@0:       rc = SQLITE_BUSY;
sl@0:       goto afp_end_lock;
sl@0:     }
sl@0:   }
sl@0:   
sl@0:   /* If control gets to this point, then actually go ahead and make
sl@0:   ** operating system calls for the specified lock.
sl@0:   */
sl@0:   if( locktype==SHARED_LOCK ){
sl@0:     int lk, failed;
sl@0:     
sl@0:     /* Now get the read-lock */
sl@0:     /* note that the quality of the randomness doesn't matter that much */
sl@0:     lk = random(); 
sl@0:     context->sharedLockByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
sl@0:     failed = _AFPFSSetLock(context->filePath, pFile->h, 
sl@0:       SHARED_FIRST+context->sharedLockByte, 1, 1);
sl@0:     
sl@0:     /* Drop the temporary PENDING lock */
sl@0:     if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)) {
sl@0:       rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
sl@0:       goto afp_end_lock;
sl@0:     }
sl@0:     
sl@0:     if( failed ){
sl@0:       rc = SQLITE_BUSY;
sl@0:     } else {
sl@0:       pFile->locktype = SHARED_LOCK;
sl@0:     }
sl@0:   }else{
sl@0:     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
sl@0:     ** assumed that there is a SHARED or greater lock on the file
sl@0:     ** already.
sl@0:     */
sl@0:     int failed = 0;
sl@0:     assert( 0!=pFile->locktype );
sl@0:     if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
sl@0:         /* Acquire a RESERVED lock */
sl@0:         failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);
sl@0:     }
sl@0:     if (!failed && locktype == EXCLUSIVE_LOCK) {
sl@0:       /* Acquire an EXCLUSIVE lock */
sl@0:         
sl@0:       /* Remove the shared lock before trying the range.  we'll need to 
sl@0:       ** reestablish the shared lock if we can't get the  afpUnlock
sl@0:       */
sl@0:       if (!_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
sl@0:                          context->sharedLockByte, 1, 0)) {
sl@0:         /* now attemmpt to get the exclusive lock range */
sl@0:         failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST, 
sl@0:                                SHARED_SIZE, 1);
sl@0:         if (failed && _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
sl@0:                                     context->sharedLockByte, 1, 1)) {
sl@0:           rc = SQLITE_IOERR_RDLOCK; /* this should never happen */
sl@0:         }
sl@0:       } else {
sl@0:         /* */
sl@0:         rc = SQLITE_IOERR_UNLOCK; /* this should never happen */
sl@0:       }
sl@0:     }
sl@0:     if( failed && rc == SQLITE_OK){
sl@0:       rc = SQLITE_BUSY;
sl@0:     }
sl@0:   }
sl@0:   
sl@0:   if( rc==SQLITE_OK ){
sl@0:     pFile->locktype = locktype;
sl@0:   }else if( locktype==EXCLUSIVE_LOCK ){
sl@0:     pFile->locktype = PENDING_LOCK;
sl@0:   }
sl@0:   
sl@0: afp_end_lock:
sl@0:   leaveMutex();
sl@0:   OSTRACE4("LOCK    %d %s %s\n", pFile->h, locktypeName(locktype), 
sl@0:          rc==SQLITE_OK ? "ok" : "failed");
sl@0:   return rc;
sl@0: }
sl@0: 
sl@0: /*
sl@0: ** Lower the locking level on file descriptor pFile to locktype.  locktype
sl@0: ** must be either NO_LOCK or SHARED_LOCK.
sl@0: **
sl@0: ** If the locking level of the file descriptor is already at or below
sl@0: ** the requested locking level, this routine is a no-op.
sl@0: */
sl@0: static int afpUnlock(sqlite3_file *id, int locktype) {
sl@0:   int rc = SQLITE_OK;
sl@0:   unixFile *pFile = (unixFile*)id;
sl@0:   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
sl@0: 
sl@0:   assert( pFile );
sl@0:   OSTRACE5("UNLOCK  %d %d was %d pid=%d\n", pFile->h, locktype,
sl@0:          pFile->locktype, getpid());
sl@0:   
sl@0:   assert( locktype<=SHARED_LOCK );
sl@0:   if( pFile->locktype<=locktype ){
sl@0:     return SQLITE_OK;
sl@0:   }
sl@0:   if( CHECK_THREADID(pFile) ){
sl@0:     return SQLITE_MISUSE;
sl@0:   }
sl@0:   enterMutex();
sl@0:   if( pFile->locktype>SHARED_LOCK ){
sl@0:     if( locktype==SHARED_LOCK ){
sl@0:       int failed = 0;
sl@0: 
sl@0:       /* unlock the exclusive range - then re-establish the shared lock */
sl@0:       if (pFile->locktype==EXCLUSIVE_LOCK) {
sl@0:         failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST, 
sl@0:                                  SHARED_SIZE, 0);
sl@0:         if (!failed) {
sl@0:           /* successfully removed the exclusive lock */
sl@0:           if (_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST+
sl@0:                             context->sharedLockByte, 1, 1)) {
sl@0:             /* failed to re-establish our shared lock */
sl@0:             rc = SQLITE_IOERR_RDLOCK; /* This should never happen */
sl@0:           }
sl@0:         } else {
sl@0:           /* This should never happen - failed to unlock the exclusive range */
sl@0:           rc = SQLITE_IOERR_UNLOCK;
sl@0:         } 
sl@0:       }
sl@0:     }
sl@0:     if (rc == SQLITE_OK && pFile->locktype>=PENDING_LOCK) {
sl@0:       if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)){
sl@0:         /* failed to release the pending lock */
sl@0:         rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
sl@0:       }
sl@0:     } 
sl@0:     if (rc == SQLITE_OK && pFile->locktype>=RESERVED_LOCK) {
sl@0:       if (_AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0)) {
sl@0:         /* failed to release the reserved lock */
sl@0:         rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
sl@0:       }
sl@0:     } 
sl@0:   }
sl@0:   if( locktype==NO_LOCK ){
sl@0:     int failed = _AFPFSSetLock(context->filePath, pFile->h, 
sl@0:                                SHARED_FIRST + context->sharedLockByte, 1, 0);
sl@0:     if (failed) {
sl@0:       rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
sl@0:     }
sl@0:   }
sl@0:   if (rc == SQLITE_OK)
sl@0:     pFile->locktype = locktype;
sl@0:   leaveMutex();
sl@0:   return rc;
sl@0: }
sl@0: 
sl@0: /*
sl@0: ** Close a file & cleanup AFP specific locking context 
sl@0: */
sl@0: static int afpClose(sqlite3_file *id) {
sl@0:   if( id ){
sl@0:     unixFile *pFile = (unixFile*)id;
sl@0:     afpUnlock(id, NO_LOCK);
sl@0:     sqlite3_free(pFile->lockingContext);
sl@0:   }
sl@0:   return closeUnixFile(id);
sl@0: }
sl@0: 
sl@0: 
sl@0: #pragma mark flock() style locking
sl@0: 
sl@0: /*
sl@0: ** The flockLockingContext is not used
sl@0: */
sl@0: typedef void flockLockingContext;
sl@0: 
sl@0: static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
sl@0:   int r = 1;
sl@0:   unixFile *pFile = (unixFile*)id;
sl@0:   
sl@0:   if (pFile->locktype != RESERVED_LOCK) {
sl@0:     /* attempt to get the lock */
sl@0:     int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
sl@0:     if (!rc) {
sl@0:       /* got the lock, unlock it */
sl@0:       flock(pFile->h, LOCK_UN);
sl@0:       r = 0;  /* no one has it reserved */
sl@0:     }
sl@0:   }
sl@0: 
sl@0:   *pResOut = r;
sl@0:   return SQLITE_OK;
sl@0: }
sl@0: 
sl@0: static int flockLock(sqlite3_file *id, int locktype) {
sl@0:   unixFile *pFile = (unixFile*)id;
sl@0:   
sl@0:   /* if we already have a lock, it is exclusive.  
sl@0:   ** Just adjust level and punt on outta here. */
sl@0:   if (pFile->locktype > NO_LOCK) {
sl@0:     pFile->locktype = locktype;
sl@0:     return SQLITE_OK;
sl@0:   }
sl@0:   
sl@0:   /* grab an exclusive lock */
sl@0:   int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
sl@0:   if (rc) {
sl@0:     /* didn't get, must be busy */
sl@0:     return SQLITE_BUSY;
sl@0:   } else {
sl@0:     /* got it, set the type and return ok */
sl@0:     pFile->locktype = locktype;
sl@0:     return SQLITE_OK;
sl@0:   }
sl@0: }
sl@0: 
sl@0: static int flockUnlock(sqlite3_file *id, int locktype) {
sl@0:   unixFile *pFile = (unixFile*)id;
sl@0:   
sl@0:   assert( locktype<=SHARED_LOCK );
sl@0:   
sl@0:   /* no-op if possible */
sl@0:   if( pFile->locktype==locktype ){
sl@0:     return SQLITE_OK;
sl@0:   }
sl@0:   
sl@0:   /* shared can just be set because we always have an exclusive */
sl@0:   if (locktype==SHARED_LOCK) {
sl@0:     pFile->locktype = locktype;
sl@0:     return SQLITE_OK;
sl@0:   }
sl@0:   
sl@0:   /* no, really, unlock. */
sl@0:   int rc = flock(pFile->h, LOCK_UN);
sl@0:   if (rc)
sl@0:     return SQLITE_IOERR_UNLOCK;
sl@0:   else {
sl@0:     pFile->locktype = NO_LOCK;
sl@0:     return SQLITE_OK;
sl@0:   }
sl@0: }
sl@0: 
sl@0: /*
sl@0: ** Close a file.
sl@0: */
sl@0: static int flockClose(sqlite3_file *id) {
sl@0:   if( id ){
sl@0:     flockUnlock(id, NO_LOCK);
sl@0:   }
sl@0:   return closeUnixFile(id);
sl@0: }
sl@0: 
sl@0: #pragma mark Old-School .lock file based locking
sl@0: 
sl@0: static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
sl@0:   int r = 1;
sl@0:   unixFile *pFile = (unixFile*)id;
sl@0:   char *zLockFile = (char *)pFile->lockingContext;
sl@0: 
sl@0:   if (pFile->locktype != RESERVED_LOCK) {
sl@0:     struct stat statBuf;
sl@0:     if (lstat(zLockFile, &statBuf) != 0){
sl@0:       /* file does not exist, we could have it if we want it */
sl@0:       r = 0;
sl@0:     }
sl@0:   }
sl@0: 
sl@0:   *pResOut = r;
sl@0:   return SQLITE_OK;
sl@0: }
sl@0: 
sl@0: static int dotlockLock(sqlite3_file *id, int locktype) {
sl@0:   unixFile *pFile = (unixFile*)id;
sl@0:   int fd;
sl@0:   char *zLockFile = (char *)pFile->lockingContext;
sl@0: 
sl@0:   /* if we already have a lock, it is exclusive.  
sl@0:   ** Just adjust level and punt on outta here. */
sl@0:   if (pFile->locktype > NO_LOCK) {
sl@0:     pFile->locktype = locktype;
sl@0:     
sl@0:     /* Always update the timestamp on the old file */
sl@0:     utimes(zLockFile, NULL);
sl@0:     return SQLITE_OK;
sl@0:   }
sl@0:   
sl@0:   /* check to see if lock file already exists */
sl@0:   struct stat statBuf;
sl@0:   if (lstat(zLockFile,&statBuf) == 0){
sl@0:     return SQLITE_BUSY; /* it does, busy */
sl@0:   }
sl@0:   
sl@0:   /* grab an exclusive lock */
sl@0:   fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
sl@0:   if( fd<0 ){
sl@0:     /* failed to open/create the file, someone else may have stolen the lock */
sl@0:     return SQLITE_BUSY; 
sl@0:   }
sl@0:   close(fd);
sl@0:   
sl@0:   /* got it, set the type and return ok */
sl@0:   pFile->locktype = locktype;
sl@0:   return SQLITE_OK;
sl@0: }
sl@0: 
sl@0: static int dotlockUnlock(sqlite3_file *id, int locktype) {
sl@0:   unixFile *pFile = (unixFile*)id;
sl@0:   char *zLockFile = (char *)pFile->lockingContext;
sl@0: 
sl@0:   assert( locktype<=SHARED_LOCK );
sl@0:   
sl@0:   /* no-op if possible */
sl@0:   if( pFile->locktype==locktype ){
sl@0:     return SQLITE_OK;
sl@0:   }
sl@0:   
sl@0:   /* shared can just be set because we always have an exclusive */
sl@0:   if (locktype==SHARED_LOCK) {
sl@0:     pFile->locktype = locktype;
sl@0:     return SQLITE_OK;
sl@0:   }
sl@0:   
sl@0:   /* no, really, unlock. */
sl@0:   unlink(zLockFile);
sl@0:   pFile->locktype = NO_LOCK;
sl@0:   return SQLITE_OK;
sl@0: }
sl@0: 
sl@0: /*
sl@0:  ** Close a file.
sl@0:  */
sl@0: static int dotlockClose(sqlite3_file *id) {
sl@0:   if( id ){
sl@0:     unixFile *pFile = (unixFile*)id;
sl@0:     dotlockUnlock(id, NO_LOCK);
sl@0:     sqlite3_free(pFile->lockingContext);
sl@0:   }
sl@0:   return closeUnixFile(id);
sl@0: }
sl@0: 
sl@0: 
sl@0: #endif /* SQLITE_ENABLE_LOCKING_STYLE */
sl@0: 
sl@0: /*
sl@0: ** The nolockLockingContext is void
sl@0: */
sl@0: typedef void nolockLockingContext;
sl@0: 
sl@0: static int nolockCheckReservedLock(sqlite3_file *id, int *pResOut) {
sl@0:   *pResOut = 0;
sl@0:   return SQLITE_OK;
sl@0: }
sl@0: 
sl@0: static int nolockLock(sqlite3_file *id, int locktype) {
sl@0:   return SQLITE_OK;
sl@0: }
sl@0: 
sl@0: static int nolockUnlock(sqlite3_file *id, int locktype) {
sl@0:   return SQLITE_OK;
sl@0: }
sl@0: 
sl@0: /*
sl@0: ** Close a file.
sl@0: */
sl@0: static int nolockClose(sqlite3_file *id) {
sl@0:   return closeUnixFile(id);
sl@0: }
sl@0: 
sl@0: 
sl@0: /*
sl@0: ** Information and control of an open file handle.
sl@0: */
sl@0: static int unixFileControl(sqlite3_file *id, int op, void *pArg){
sl@0:   switch( op ){
sl@0:     case SQLITE_FCNTL_LOCKSTATE: {
sl@0:       *(int*)pArg = ((unixFile*)id)->locktype;
sl@0:       return SQLITE_OK;
sl@0:     }
sl@0:   }
sl@0:   return SQLITE_ERROR;
sl@0: }
sl@0: 
sl@0: /*
sl@0: ** Return the sector size in bytes of the underlying block device for
sl@0: ** the specified file. This is almost always 512 bytes, but may be
sl@0: ** larger for some devices.
sl@0: **
sl@0: ** SQLite code assumes this function cannot fail. It also assumes that
sl@0: ** if two files are created in the same file-system directory (i.e.
sl@0: ** a database and its journal file) that the sector size will be the
sl@0: ** same for both.
sl@0: */
sl@0: static int unixSectorSize(sqlite3_file *id){
sl@0:   return SQLITE_DEFAULT_SECTOR_SIZE;
sl@0: }
sl@0: 
sl@0: /*
sl@0: ** Return the device characteristics for the file. This is always 0.
sl@0: */
sl@0: static int unixDeviceCharacteristics(sqlite3_file *id){
sl@0:   return 0;
sl@0: }
sl@0: 
sl@0: /*
sl@0: ** Initialize the contents of the unixFile structure pointed to by pId.
sl@0: **
sl@0: ** When locking extensions are enabled, the filepath and locking style 
sl@0: ** are needed to determine the unixFile pMethod to use for locking operations.
sl@0: ** The locking-style specific lockingContext data structure is created 
sl@0: ** and assigned here also.
sl@0: */
sl@0: static int fillInUnixFile(
sl@0:   sqlite3_vfs *pVfs,      /* Pointer to vfs object */
sl@0:   int h,                  /* Open file descriptor of file being opened */
sl@0:   int dirfd,              /* Directory file descriptor */
sl@0:   sqlite3_file *pId,      /* Write to the unixFile structure here */
sl@0:   const char *zFilename,  /* Name of the file being opened */
sl@0:   int noLock              /* Omit locking if true */
sl@0: ){
sl@0:   int eLockingStyle;
sl@0:   unixFile *pNew = (unixFile *)pId;
sl@0:   int rc = SQLITE_OK;
sl@0: 
sl@0:   /* Macro to define the static contents of an sqlite3_io_methods 
sl@0:   ** structure for a unix backend file. Different locking methods
sl@0:   ** require different functions for the xClose, xLock, xUnlock and
sl@0:   ** xCheckReservedLock methods.
sl@0:   */
sl@0:   #define IOMETHODS(xClose, xLock, xUnlock, xCheckReservedLock) {    \
sl@0:     1,                          /* iVersion */                           \
sl@0:     xClose,                     /* xClose */                             \
sl@0:     unixRead,                   /* xRead */                              \
sl@0:     unixWrite,                  /* xWrite */                             \
sl@0:     unixTruncate,               /* xTruncate */                          \
sl@0:     unixSync,                   /* xSync */                              \
sl@0:     unixFileSize,               /* xFileSize */                          \
sl@0:     xLock,                      /* xLock */                              \
sl@0:     xUnlock,                    /* xUnlock */                            \
sl@0:     xCheckReservedLock,         /* xCheckReservedLock */                 \
sl@0:     unixFileControl,            /* xFileControl */                       \
sl@0:     unixSectorSize,             /* xSectorSize */                        \
sl@0:     unixDeviceCharacteristics   /* xDeviceCapabilities */                \
sl@0:   }
sl@0:   static sqlite3_io_methods aIoMethod[] = {
sl@0:     IOMETHODS(unixClose, unixLock, unixUnlock, unixCheckReservedLock) 
sl@0:    ,IOMETHODS(nolockClose, nolockLock, nolockUnlock, nolockCheckReservedLock)
sl@0: #ifdef SQLITE_ENABLE_LOCKING_STYLE
sl@0:    ,IOMETHODS(dotlockClose, dotlockLock, dotlockUnlock,dotlockCheckReservedLock)
sl@0:    ,IOMETHODS(flockClose, flockLock, flockUnlock, flockCheckReservedLock)
sl@0:    ,IOMETHODS(afpClose, afpLock, afpUnlock, afpCheckReservedLock)
sl@0: #endif
sl@0:   };
sl@0:   /* The order of the IOMETHODS macros above is important.  It must be the
sl@0:   ** same order as the LOCKING_STYLE numbers
sl@0:   */
sl@0:   assert(LOCKING_STYLE_POSIX==1);
sl@0:   assert(LOCKING_STYLE_NONE==2);
sl@0:   assert(LOCKING_STYLE_DOTFILE==3);
sl@0:   assert(LOCKING_STYLE_FLOCK==4);
sl@0:   assert(LOCKING_STYLE_AFP==5);
sl@0: 
sl@0:   assert( pNew->pLock==NULL );
sl@0:   assert( pNew->pOpen==NULL );
sl@0: 
sl@0:   OSTRACE3("OPEN    %-3d %s\n", h, zFilename);    
sl@0:   pNew->h = h;
sl@0:   pNew->dirfd = dirfd;
sl@0:   SET_THREADID(pNew);
sl@0: 
sl@0:   if( noLock ){
sl@0:     eLockingStyle = LOCKING_STYLE_NONE;
sl@0:   }else{
sl@0:     eLockingStyle = detectLockingStyle(pVfs, zFilename, h);
sl@0:   }
sl@0: 
sl@0:   switch( eLockingStyle ){
sl@0: 
sl@0:     case LOCKING_STYLE_POSIX: {
sl@0:       enterMutex();
sl@0:       rc = findLockInfo(h, &pNew->pLock, &pNew->pOpen);
sl@0:       leaveMutex();
sl@0:       break;
sl@0:     }
sl@0: 
sl@0: #ifdef SQLITE_ENABLE_LOCKING_STYLE
sl@0:     case LOCKING_STYLE_AFP: {
sl@0:       /* AFP locking uses the file path so it needs to be included in
sl@0:       ** the afpLockingContext.
sl@0:       */
sl@0:       afpLockingContext *pCtx;
sl@0:       pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
sl@0:       if( pCtx==0 ){
sl@0:         rc = SQLITE_NOMEM;
sl@0:       }else{
sl@0:         /* NB: zFilename exists and remains valid until the file is closed
sl@0:         ** according to requirement F11141.  So we do not need to make a
sl@0:         ** copy of the filename. */
sl@0:         pCtx->filePath = zFilename;
sl@0:         srandomdev();
sl@0:       }
sl@0:       break;
sl@0:     }
sl@0: 
sl@0:     case LOCKING_STYLE_DOTFILE: {
sl@0:       /* Dotfile locking uses the file path so it needs to be included in
sl@0:       ** the dotlockLockingContext 
sl@0:       */
sl@0:       char *zLockFile;
sl@0:       int nFilename;
sl@0:       nFilename = strlen(zFilename) + 6;
sl@0:       zLockFile = (char *)sqlite3_malloc(nFilename);
sl@0:       if( zLockFile==0 ){
sl@0:         rc = SQLITE_NOMEM;
sl@0:       }else{
sl@0:         sqlite3_snprintf(nFilename, zLockFile, "%s.lock", zFilename);
sl@0:       }
sl@0:       pNew->lockingContext = zLockFile;
sl@0:       break;
sl@0:     }
sl@0: 
sl@0:     case LOCKING_STYLE_FLOCK: 
sl@0:     case LOCKING_STYLE_NONE: 
sl@0:       break;
sl@0: #endif
sl@0:   }
sl@0: 
sl@0:   if( rc!=SQLITE_OK ){
sl@0:     if( dirfd>=0 ) close(dirfd);
sl@0:     close(h);
sl@0:   }else{
sl@0:     pNew->pMethod = &aIoMethod[eLockingStyle-1];
sl@0:     OpenCounter(+1);
sl@0:   }
sl@0:   return rc;
sl@0: }
sl@0: 
sl@0: /*
sl@0: ** Open a file descriptor to the directory containing file zFilename.
sl@0: ** If successful, *pFd is set to the opened file descriptor and
sl@0: ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
sl@0: ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
sl@0: ** value.
sl@0: **
sl@0: ** If SQLITE_OK is returned, the caller is responsible for closing
sl@0: ** the file descriptor *pFd using close().
sl@0: */
sl@0: static int openDirectory(const char *zFilename, int *pFd){
sl@0:   int ii;
sl@0:   int fd = -1;
sl@0:   char zDirname[MAX_PATHNAME+1];
sl@0: 
sl@0:   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
sl@0:   for(ii=strlen(zDirname); ii>=0 && zDirname[ii]!='/'; ii--);
sl@0:   if( ii>0 ){
sl@0:     zDirname[ii] = '\0';
sl@0:     fd = open(zDirname, O_RDONLY|O_BINARY, 0);
sl@0:     if( fd>=0 ){
sl@0: #ifdef FD_CLOEXEC
sl@0:       fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
sl@0: #endif
sl@0:       OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
sl@0:     }
sl@0:   }
sl@0:   *pFd = fd;
sl@0:   return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN);
sl@0: }
sl@0: 
sl@0: /*
sl@0: ** Create a temporary file name in zBuf.  zBuf must be allocated
sl@0: ** by the calling process and must be big enough to hold at least
sl@0: ** pVfs->mxPathname bytes.
sl@0: */
sl@0: static int getTempname(int nBuf, char *zBuf){
sl@0:   static const char *azDirs[] = {
sl@0:      0,
sl@0:      "/var/tmp",
sl@0:      "/usr/tmp",
sl@0:      "/tmp",
sl@0:      ".",
sl@0:   };
sl@0:   static const unsigned char zChars[] =
sl@0:     "abcdefghijklmnopqrstuvwxyz"
sl@0:     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
sl@0:     "0123456789";
sl@0:   int i, j;
sl@0:   struct stat buf;
sl@0:   const char *zDir = ".";
sl@0: 
sl@0:   /* It's odd to simulate an io-error here, but really this is just
sl@0:   ** using the io-error infrastructure to test that SQLite handles this
sl@0:   ** function failing. 
sl@0:   */
sl@0:   SimulateIOError( return SQLITE_IOERR );
sl@0: 
sl@0:   azDirs[0] = sqlite3_temp_directory;
sl@0:   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
sl@0:     if( azDirs[i]==0 ) continue;
sl@0:     if( stat(azDirs[i], &buf) ) continue;
sl@0:     if( !S_ISDIR(buf.st_mode) ) continue;
sl@0:     if( access(azDirs[i], 07) ) continue;
sl@0:     zDir = azDirs[i];
sl@0:     break;
sl@0:   }
sl@0: 
sl@0:   /* Check that the output buffer is large enough for the temporary file 
sl@0:   ** name. If it is not, return SQLITE_ERROR.
sl@0:   */
sl@0:   if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= nBuf ){
sl@0:     return SQLITE_ERROR;
sl@0:   }
sl@0: 
sl@0:   do{
sl@0:     sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
sl@0:     j = strlen(zBuf);
sl@0:     sqlite3_randomness(15, &zBuf[j]);
sl@0:     for(i=0; i<15; i++, j++){
sl@0:       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
sl@0:     }
sl@0:     zBuf[j] = 0;
sl@0:   }while( access(zBuf,0)==0 );
sl@0:   return SQLITE_OK;
sl@0: }
sl@0: 
sl@0: 
sl@0: /*
sl@0: ** Open the file zPath.
sl@0: ** 
sl@0: ** Previously, the SQLite OS layer used three functions in place of this
sl@0: ** one:
sl@0: **
sl@0: **     sqlite3OsOpenReadWrite();
sl@0: **     sqlite3OsOpenReadOnly();
sl@0: **     sqlite3OsOpenExclusive();
sl@0: **
sl@0: ** These calls correspond to the following combinations of flags:
sl@0: **
sl@0: **     ReadWrite() ->     (READWRITE | CREATE)
sl@0: **     ReadOnly()  ->     (READONLY) 
sl@0: **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
sl@0: **
sl@0: ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
sl@0: ** true, the file was configured to be automatically deleted when the
sl@0: ** file handle closed. To achieve the same effect using this new 
sl@0: ** interface, add the DELETEONCLOSE flag to those specified above for 
sl@0: ** OpenExclusive().
sl@0: */
sl@0: static int unixOpen(
sl@0:   sqlite3_vfs *pVfs, 
sl@0:   const char *zPath, 
sl@0:   sqlite3_file *pFile,
sl@0:   int flags,
sl@0:   int *pOutFlags
sl@0: ){
sl@0:   int fd = 0;                    /* File descriptor returned by open() */
sl@0:   int dirfd = -1;                /* Directory file descriptor */
sl@0:   int oflags = 0;                /* Flags to pass to open() */
sl@0:   int eType = flags&0xFFFFFF00;  /* Type of file to open */
sl@0:   int noLock;                    /* True to omit locking primitives */
sl@0: 
sl@0:   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
sl@0:   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
sl@0:   int isCreate     = (flags & SQLITE_OPEN_CREATE);
sl@0:   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
sl@0:   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
sl@0: 
sl@0:   /* If creating a master or main-file journal, this function will open
sl@0:   ** a file-descriptor on the directory too. The first time unixSync()
sl@0:   ** is called the directory file descriptor will be fsync()ed and close()d.
sl@0:   */
sl@0:   int isOpenDirectory = (isCreate && 
sl@0:       (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
sl@0:   );
sl@0: 
sl@0:   /* If argument zPath is a NULL pointer, this function is required to open
sl@0:   ** a temporary file. Use this buffer to store the file name in.
sl@0:   */
sl@0:   char zTmpname[MAX_PATHNAME+1];
sl@0:   const char *zName = zPath;
sl@0: 
sl@0:   /* Check the following statements are true: 
sl@0:   **
sl@0:   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
sl@0:   **   (b) if CREATE is set, then READWRITE must also be set, and
sl@0:   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
sl@0:   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
sl@0:   */
sl@0:   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
sl@0:   assert(isCreate==0 || isReadWrite);
sl@0:   assert(isExclusive==0 || isCreate);
sl@0:   assert(isDelete==0 || isCreate);
sl@0: 
sl@0:   /* The main DB, main journal, and master journal are never automatically
sl@0:   ** deleted
sl@0:   */
sl@0:   assert( eType!=SQLITE_OPEN_MAIN_DB || !isDelete );
sl@0:   assert( eType!=SQLITE_OPEN_MAIN_JOURNAL || !isDelete );
sl@0:   assert( eType!=SQLITE_OPEN_MASTER_JOURNAL || !isDelete );
sl@0: 
sl@0:   /* Assert that the upper layer has set one of the "file-type" flags. */
sl@0:   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
sl@0:        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
sl@0:        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
sl@0:        || eType==SQLITE_OPEN_TRANSIENT_DB
sl@0:   );
sl@0: 
sl@0:   memset(pFile, 0, sizeof(unixFile));
sl@0: 
sl@0:   if( !zName ){
sl@0:     int rc;
sl@0:     assert(isDelete && !isOpenDirectory);
sl@0:     rc = getTempname(MAX_PATHNAME+1, zTmpname);
sl@0:     if( rc!=SQLITE_OK ){
sl@0:       return rc;
sl@0:     }
sl@0:     zName = zTmpname;
sl@0:   }
sl@0: 
sl@0:   if( isReadonly )  oflags |= O_RDONLY;
sl@0:   if( isReadWrite ) oflags |= O_RDWR;
sl@0:   if( isCreate )    oflags |= O_CREAT;
sl@0:   if( isExclusive ) oflags |= (O_EXCL|O_NOFOLLOW);
sl@0:   oflags |= (O_LARGEFILE|O_BINARY);
sl@0: 
sl@0:   fd = open(zName, oflags, isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
sl@0:   if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
sl@0:     /* Failed to open the file for read/write access. Try read-only. */
sl@0:     flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
sl@0:     flags |= SQLITE_OPEN_READONLY;
sl@0:     return unixOpen(pVfs, zPath, pFile, flags, pOutFlags);
sl@0:   }
sl@0:   if( fd<0 ){
sl@0:     return SQLITE_CANTOPEN;
sl@0:   }
sl@0:   if( isDelete ){
sl@0:     unlink(zName);
sl@0:   }
sl@0:   if( pOutFlags ){
sl@0:     *pOutFlags = flags;
sl@0:   }
sl@0: 
sl@0:   assert(fd!=0);
sl@0:   if( isOpenDirectory ){
sl@0:     int rc = openDirectory(zPath, &dirfd);
sl@0:     if( rc!=SQLITE_OK ){
sl@0:       close(fd);
sl@0:       return rc;
sl@0:     }
sl@0:   }
sl@0: 
sl@0: #ifdef FD_CLOEXEC
sl@0:   fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
sl@0: #endif
sl@0: 
sl@0:   noLock = eType!=SQLITE_OPEN_MAIN_DB;
sl@0:   return fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock);
sl@0: }
sl@0: 
sl@0: /*
sl@0: ** Delete the file at zPath. If the dirSync argument is true, fsync()
sl@0: ** the directory after deleting the file.
sl@0: */
sl@0: static int unixDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
sl@0:   int rc = SQLITE_OK;
sl@0:   SimulateIOError(return SQLITE_IOERR_DELETE);
sl@0:   unlink(zPath);
sl@0:   if( dirSync ){
sl@0:     int fd;
sl@0:     rc = openDirectory(zPath, &fd);
sl@0:     if( rc==SQLITE_OK ){
sl@0:       if( fsync(fd) ){
sl@0:         rc = SQLITE_IOERR_DIR_FSYNC;
sl@0:       }
sl@0:       close(fd);
sl@0:     }
sl@0:   }
sl@0:   return rc;
sl@0: }
sl@0: 
sl@0: /*
sl@0: ** Test the existance of or access permissions of file zPath. The
sl@0: ** test performed depends on the value of flags:
sl@0: **
sl@0: **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
sl@0: **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
sl@0: **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
sl@0: **
sl@0: ** Otherwise return 0.
sl@0: */
sl@0: static int unixAccess(
sl@0:   sqlite3_vfs *pVfs, 
sl@0:   const char *zPath, 
sl@0:   int flags, 
sl@0:   int *pResOut
sl@0: ){
sl@0:   int amode = 0;
sl@0:   SimulateIOError( return SQLITE_IOERR_ACCESS; );
sl@0:   switch( flags ){
sl@0:     case SQLITE_ACCESS_EXISTS:
sl@0:       amode = F_OK;
sl@0:       break;
sl@0:     case SQLITE_ACCESS_READWRITE:
sl@0:       amode = W_OK|R_OK;
sl@0:       break;
sl@0:     case SQLITE_ACCESS_READ:
sl@0:       amode = R_OK;
sl@0:       break;
sl@0: 
sl@0:     default:
sl@0:       assert(!"Invalid flags argument");
sl@0:   }
sl@0:   *pResOut = (access(zPath, amode)==0);
sl@0:   return SQLITE_OK;
sl@0: }
sl@0: 
sl@0: 
sl@0: /*
sl@0: ** Turn a relative pathname into a full pathname. The relative path
sl@0: ** is stored as a nul-terminated string in the buffer pointed to by
sl@0: ** zPath. 
sl@0: **
sl@0: ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes 
sl@0: ** (in this case, MAX_PATHNAME bytes). The full-path is written to
sl@0: ** this buffer before returning.
sl@0: */
sl@0: static int unixFullPathname(
sl@0:   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
sl@0:   const char *zPath,            /* Possibly relative input path */
sl@0:   int nOut,                     /* Size of output buffer in bytes */
sl@0:   char *zOut                    /* Output buffer */
sl@0: ){
sl@0: 
sl@0:   /* It's odd to simulate an io-error here, but really this is just
sl@0:   ** using the io-error infrastructure to test that SQLite handles this
sl@0:   ** function failing. This function could fail if, for example, the
sl@0:   ** current working directly has been unlinked.
sl@0:   */
sl@0:   SimulateIOError( return SQLITE_ERROR );
sl@0: 
sl@0:   assert( pVfs->mxPathname==MAX_PATHNAME );
sl@0:   zOut[nOut-1] = '\0';
sl@0:   if( zPath[0]=='/' ){
sl@0:     sqlite3_snprintf(nOut, zOut, "%s", zPath);
sl@0:   }else{
sl@0:     int nCwd;
sl@0:     if( getcwd(zOut, nOut-1)==0 ){
sl@0:       return SQLITE_CANTOPEN;
sl@0:     }
sl@0:     nCwd = strlen(zOut);
sl@0:     sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
sl@0:   }
sl@0:   return SQLITE_OK;
sl@0: 
sl@0: #if 0
sl@0:   /*
sl@0:   ** Remove "/./" path elements and convert "/A/./" path elements
sl@0:   ** to just "/".
sl@0:   */
sl@0:   if( zFull ){
sl@0:     int i, j;
sl@0:     for(i=j=0; zFull[i]; i++){
sl@0:       if( zFull[i]=='/' ){
sl@0:         if( zFull[i+1]=='/' ) continue;
sl@0:         if( zFull[i+1]=='.' && zFull[i+2]=='/' ){
sl@0:           i += 1;
sl@0:           continue;
sl@0:         }
sl@0:         if( zFull[i+1]=='.' && zFull[i+2]=='.' && zFull[i+3]=='/' ){
sl@0:           while( j>0 && zFull[j-1]!='/' ){ j--; }
sl@0:           i += 3;
sl@0:           continue;
sl@0:         }
sl@0:       }
sl@0:       zFull[j++] = zFull[i];
sl@0:     }
sl@0:     zFull[j] = 0;
sl@0:   }
sl@0: #endif
sl@0: }
sl@0: 
sl@0: 
sl@0: #ifndef SQLITE_OMIT_LOAD_EXTENSION
sl@0: /*
sl@0: ** Interfaces for opening a shared library, finding entry points
sl@0: ** within the shared library, and closing the shared library.
sl@0: */
sl@0: #include <dlfcn.h>
sl@0: static void *unixDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
sl@0:   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
sl@0: }
sl@0: 
sl@0: /*
sl@0: ** SQLite calls this function immediately after a call to unixDlSym() or
sl@0: ** unixDlOpen() fails (returns a null pointer). If a more detailed error
sl@0: ** message is available, it is written to zBufOut. If no error message
sl@0: ** is available, zBufOut is left unmodified and SQLite uses a default
sl@0: ** error message.
sl@0: */
sl@0: static void unixDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
sl@0:   char *zErr;
sl@0:   enterMutex();
sl@0:   zErr = dlerror();
sl@0:   if( zErr ){
sl@0:     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
sl@0:   }
sl@0:   leaveMutex();
sl@0: }
sl@0: static void *unixDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
sl@0:   return dlsym(pHandle, zSymbol);
sl@0: }
sl@0: static void unixDlClose(sqlite3_vfs *pVfs, void *pHandle){
sl@0:   dlclose(pHandle);
sl@0: }
sl@0: #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
sl@0:   #define unixDlOpen  0
sl@0:   #define unixDlError 0
sl@0:   #define unixDlSym   0
sl@0:   #define unixDlClose 0
sl@0: #endif
sl@0: 
sl@0: /*
sl@0: ** Write nBuf bytes of random data to the supplied buffer zBuf.
sl@0: */
sl@0: static int unixRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
sl@0: 
sl@0:   assert(nBuf>=(sizeof(time_t)+sizeof(int)));
sl@0: 
sl@0:   /* We have to initialize zBuf to prevent valgrind from reporting
sl@0:   ** errors.  The reports issued by valgrind are incorrect - we would
sl@0:   ** prefer that the randomness be increased by making use of the
sl@0:   ** uninitialized space in zBuf - but valgrind errors tend to worry
sl@0:   ** some users.  Rather than argue, it seems easier just to initialize
sl@0:   ** the whole array and silence valgrind, even if that means less randomness
sl@0:   ** in the random seed.
sl@0:   **
sl@0:   ** When testing, initializing zBuf[] to zero is all we do.  That means
sl@0:   ** that we always use the same random number sequence.  This makes the
sl@0:   ** tests repeatable.
sl@0:   */
sl@0:   memset(zBuf, 0, nBuf);
sl@0: #if !defined(SQLITE_TEST)
sl@0:   {
sl@0:     int pid, fd;
sl@0:     fd = open("/dev/urandom", O_RDONLY);
sl@0:     if( fd<0 ){
sl@0:       time_t t;
sl@0:       time(&t);
sl@0:       memcpy(zBuf, &t, sizeof(t));
sl@0:       pid = getpid();
sl@0:       memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
sl@0:     }else{
sl@0:       read(fd, zBuf, nBuf);
sl@0:       close(fd);
sl@0:     }
sl@0:   }
sl@0: #endif
sl@0:   return SQLITE_OK;
sl@0: }
sl@0: 
sl@0: 
sl@0: /*
sl@0: ** Sleep for a little while.  Return the amount of time slept.
sl@0: ** The argument is the number of microseconds we want to sleep.
sl@0: ** The return value is the number of microseconds of sleep actually
sl@0: ** requested from the underlying operating system, a number which
sl@0: ** might be greater than or equal to the argument, but not less
sl@0: ** than the argument.
sl@0: */
sl@0: static int unixSleep(sqlite3_vfs *pVfs, int microseconds){
sl@0: #if defined(HAVE_USLEEP) && HAVE_USLEEP
sl@0:   usleep(microseconds);
sl@0:   return microseconds;
sl@0: #else
sl@0:   int seconds = (microseconds+999999)/1000000;
sl@0:   sleep(seconds);
sl@0:   return seconds*1000000;
sl@0: #endif
sl@0: }
sl@0: 
sl@0: /*
sl@0: ** The following variable, if set to a non-zero value, becomes the result
sl@0: ** returned from sqlite3OsCurrentTime().  This is used for testing.
sl@0: */
sl@0: #ifdef SQLITE_TEST
sl@0: int sqlite3_current_time = 0;
sl@0: #endif
sl@0: 
sl@0: /*
sl@0: ** Find the current time (in Universal Coordinated Time).  Write the
sl@0: ** current time and date as a Julian Day number into *prNow and
sl@0: ** return 0.  Return 1 if the time and date cannot be found.
sl@0: */
sl@0: static int unixCurrentTime(sqlite3_vfs *pVfs, double *prNow){
sl@0: #ifdef NO_GETTOD
sl@0:   time_t t;
sl@0:   time(&t);
sl@0:   *prNow = t/86400.0 + 2440587.5;
sl@0: #else
sl@0:   struct timeval sNow;
sl@0:   gettimeofday(&sNow, 0);
sl@0:   *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
sl@0: #endif
sl@0: #ifdef SQLITE_TEST
sl@0:   if( sqlite3_current_time ){
sl@0:     *prNow = sqlite3_current_time/86400.0 + 2440587.5;
sl@0:   }
sl@0: #endif
sl@0:   return 0;
sl@0: }
sl@0: 
sl@0: static int unixGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
sl@0:   return 0;
sl@0: }
sl@0: 
sl@0: /*
sl@0: ** Initialize the operating system interface.
sl@0: */
sl@0: int sqlite3_os_init(void){ 
sl@0:   /* Macro to define the static contents of an sqlite3_vfs structure for
sl@0:   ** the unix backend. The two parameters are the values to use for
sl@0:   ** the sqlite3_vfs.zName and sqlite3_vfs.pAppData fields, respectively.
sl@0:   ** 
sl@0:   */
sl@0:   #define UNIXVFS(zVfsName, pVfsAppData) {                  \
sl@0:     1,                    /* iVersion */                    \
sl@0:     sizeof(unixFile),     /* szOsFile */                    \
sl@0:     MAX_PATHNAME,         /* mxPathname */                  \
sl@0:     0,                    /* pNext */                       \
sl@0:     zVfsName,             /* zName */                       \
sl@0:     (void *)pVfsAppData,  /* pAppData */                    \
sl@0:     unixOpen,             /* xOpen */                       \
sl@0:     unixDelete,           /* xDelete */                     \
sl@0:     unixAccess,           /* xAccess */                     \
sl@0:     unixFullPathname,     /* xFullPathname */               \
sl@0:     unixDlOpen,           /* xDlOpen */                     \
sl@0:     unixDlError,          /* xDlError */                    \
sl@0:     unixDlSym,            /* xDlSym */                      \
sl@0:     unixDlClose,          /* xDlClose */                    \
sl@0:     unixRandomness,       /* xRandomness */                 \
sl@0:     unixSleep,            /* xSleep */                      \
sl@0:     unixCurrentTime,      /* xCurrentTime */                \
sl@0:     unixGetLastError      /* xGetLastError */               \
sl@0:   }
sl@0: 
sl@0:   static sqlite3_vfs unixVfs = UNIXVFS("unix", 0);
sl@0: #ifdef SQLITE_ENABLE_LOCKING_STYLE
sl@0: #if 0
sl@0:   int i;
sl@0:   static sqlite3_vfs aVfs[] = {
sl@0:     UNIXVFS("unix-posix",   LOCKING_STYLE_POSIX), 
sl@0:     UNIXVFS("unix-afp",     LOCKING_STYLE_AFP), 
sl@0:     UNIXVFS("unix-flock",   LOCKING_STYLE_FLOCK), 
sl@0:     UNIXVFS("unix-dotfile", LOCKING_STYLE_DOTFILE), 
sl@0:     UNIXVFS("unix-none",    LOCKING_STYLE_NONE)
sl@0:   };
sl@0:   for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
sl@0:     sqlite3_vfs_register(&aVfs[i], 0);
sl@0:   }
sl@0: #endif
sl@0: #endif
sl@0:   sqlite3_vfs_register(&unixVfs, 1);
sl@0:   return SQLITE_OK; 
sl@0: }
sl@0: 
sl@0: /*
sl@0: ** Shutdown the operating system interface. This is a no-op for unix.
sl@0: */
sl@0: int sqlite3_os_end(void){ 
sl@0:   return SQLITE_OK; 
sl@0: }
sl@0:  
sl@0: #endif /* SQLITE_OS_UNIX */