extensions/sqlite/sqlite-source/os_unix.c
changeset 3594 0a382baff180
parent 3593 f04de1a697bd
child 3595 09c38814fe7b
     1.1 --- a/extensions/sqlite/sqlite-source/os_unix.c	Fri Aug 03 07:56:31 2012 -0400
     1.2 +++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.3 @@ -1,2749 +0,0 @@
     1.4 -/*
     1.5 -** 2004 May 22
     1.6 -**
     1.7 -** The author disclaims copyright to this source code.  In place of
     1.8 -** a legal notice, here is a blessing:
     1.9 -**
    1.10 -**    May you do good and not evil.
    1.11 -**    May you find forgiveness for yourself and forgive others.
    1.12 -**    May you share freely, never taking more than you give.
    1.13 -**
    1.14 -******************************************************************************
    1.15 -**
    1.16 -** This file contains code that is specific to Unix systems.
    1.17 -*/
    1.18 -#include "sqliteInt.h"
    1.19 -#if OS_UNIX              /* This file is used on unix only */
    1.20 -
    1.21 -/* #define SQLITE_ENABLE_LOCKING_STYLE 0 */
    1.22 -
    1.23 -/*
    1.24 -** These #defines should enable >2GB file support on Posix if the
    1.25 -** underlying operating system supports it.  If the OS lacks
    1.26 -** large file support, these should be no-ops.
    1.27 -**
    1.28 -** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
    1.29 -** on the compiler command line.  This is necessary if you are compiling
    1.30 -** on a recent machine (ex: RedHat 7.2) but you want your code to work
    1.31 -** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
    1.32 -** without this option, LFS is enable.  But LFS does not exist in the kernel
    1.33 -** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
    1.34 -** portability you should omit LFS.
    1.35 -*/
    1.36 -#ifndef SQLITE_DISABLE_LFS
    1.37 -# define _LARGE_FILE       1
    1.38 -# ifndef _FILE_OFFSET_BITS
    1.39 -#   define _FILE_OFFSET_BITS 64
    1.40 -# endif
    1.41 -# define _LARGEFILE_SOURCE 1
    1.42 -#endif
    1.43 -
    1.44 -/*
    1.45 -** standard include files.
    1.46 -*/
    1.47 -#include <sys/types.h>
    1.48 -#include <sys/stat.h>
    1.49 -#include <fcntl.h>
    1.50 -#include <unistd.h>
    1.51 -#include <time.h>
    1.52 -#include <sys/time.h>
    1.53 -#include <errno.h>
    1.54 -#ifdef SQLITE_ENABLE_LOCKING_STYLE
    1.55 -#include <sys/ioctl.h>
    1.56 -#include <sys/param.h>
    1.57 -#include <sys/mount.h>
    1.58 -#endif /* SQLITE_ENABLE_LOCKING_STYLE */
    1.59 -
    1.60 -/*
    1.61 -** If we are to be thread-safe, include the pthreads header and define
    1.62 -** the SQLITE_UNIX_THREADS macro.
    1.63 -*/
    1.64 -#if SQLITE_THREADSAFE
    1.65 -# include <pthread.h>
    1.66 -# define SQLITE_UNIX_THREADS 1
    1.67 -#endif
    1.68 -
    1.69 -/*
    1.70 -** Default permissions when creating a new file
    1.71 -*/
    1.72 -#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
    1.73 -# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
    1.74 -#endif
    1.75 -
    1.76 -/*
    1.77 -** Maximum supported path-length.
    1.78 -*/
    1.79 -#define MAX_PATHNAME 512
    1.80 -
    1.81 -
    1.82 -/*
    1.83 -** The unixFile structure is subclass of sqlite3_file specific for the unix
    1.84 -** protability layer.
    1.85 -*/
    1.86 -typedef struct unixFile unixFile;
    1.87 -struct unixFile {
    1.88 -  sqlite3_io_methods const *pMethod;  /* Always the first entry */
    1.89 -#ifdef SQLITE_TEST
    1.90 -  /* In test mode, increase the size of this structure a bit so that 
    1.91 -  ** it is larger than the struct CrashFile defined in test6.c.
    1.92 -  */
    1.93 -  char aPadding[32];
    1.94 -#endif
    1.95 -  struct openCnt *pOpen;    /* Info about all open fd's on this inode */
    1.96 -  struct lockInfo *pLock;   /* Info about locks on this inode */
    1.97 -#ifdef SQLITE_ENABLE_LOCKING_STYLE
    1.98 -  void *lockingContext;     /* Locking style specific state */
    1.99 -#endif /* SQLITE_ENABLE_LOCKING_STYLE */
   1.100 -  int h;                    /* The file descriptor */
   1.101 -  unsigned char locktype;   /* The type of lock held on this fd */
   1.102 -  int dirfd;                /* File descriptor for the directory */
   1.103 -#if SQLITE_THREADSAFE
   1.104 -  pthread_t tid;            /* The thread that "owns" this unixFile */
   1.105 -#endif
   1.106 -};
   1.107 -
   1.108 -/*
   1.109 -** Include code that is common to all os_*.c files
   1.110 -*/
   1.111 -#include "os_common.h"
   1.112 -
   1.113 -/*
   1.114 -** Define various macros that are missing from some systems.
   1.115 -*/
   1.116 -#ifndef O_LARGEFILE
   1.117 -# define O_LARGEFILE 0
   1.118 -#endif
   1.119 -#ifdef SQLITE_DISABLE_LFS
   1.120 -# undef O_LARGEFILE
   1.121 -# define O_LARGEFILE 0
   1.122 -#endif
   1.123 -#ifndef O_NOFOLLOW
   1.124 -# define O_NOFOLLOW 0
   1.125 -#endif
   1.126 -#ifndef O_BINARY
   1.127 -# define O_BINARY 0
   1.128 -#endif
   1.129 -
   1.130 -/*
   1.131 -** The DJGPP compiler environment looks mostly like Unix, but it
   1.132 -** lacks the fcntl() system call.  So redefine fcntl() to be something
   1.133 -** that always succeeds.  This means that locking does not occur under
   1.134 -** DJGPP.  But it's DOS - what did you expect?
   1.135 -*/
   1.136 -#ifdef __DJGPP__
   1.137 -# define fcntl(A,B,C) 0
   1.138 -#endif
   1.139 -
   1.140 -/*
   1.141 -** The threadid macro resolves to the thread-id or to 0.  Used for
   1.142 -** testing and debugging only.
   1.143 -*/
   1.144 -#if SQLITE_THREADSAFE
   1.145 -#define threadid pthread_self()
   1.146 -#else
   1.147 -#define threadid 0
   1.148 -#endif
   1.149 -
   1.150 -/*
   1.151 -** Set or check the unixFile.tid field.  This field is set when an unixFile
   1.152 -** is first opened.  All subsequent uses of the unixFile verify that the
   1.153 -** same thread is operating on the unixFile.  Some operating systems do
   1.154 -** not allow locks to be overridden by other threads and that restriction
   1.155 -** means that sqlite3* database handles cannot be moved from one thread
   1.156 -** to another.  This logic makes sure a user does not try to do that
   1.157 -** by mistake.
   1.158 -**
   1.159 -** Version 3.3.1 (2006-01-15):  unixFile can be moved from one thread to
   1.160 -** another as long as we are running on a system that supports threads
   1.161 -** overriding each others locks (which now the most common behavior)
   1.162 -** or if no locks are held.  But the unixFile.pLock field needs to be
   1.163 -** recomputed because its key includes the thread-id.  See the 
   1.164 -** transferOwnership() function below for additional information
   1.165 -*/
   1.166 -#if SQLITE_THREADSAFE
   1.167 -# define SET_THREADID(X)   (X)->tid = pthread_self()
   1.168 -# define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
   1.169 -                            !pthread_equal((X)->tid, pthread_self()))
   1.170 -#else
   1.171 -# define SET_THREADID(X)
   1.172 -# define CHECK_THREADID(X) 0
   1.173 -#endif
   1.174 -
   1.175 -/*
   1.176 -** Here is the dirt on POSIX advisory locks:  ANSI STD 1003.1 (1996)
   1.177 -** section 6.5.2.2 lines 483 through 490 specify that when a process
   1.178 -** sets or clears a lock, that operation overrides any prior locks set
   1.179 -** by the same process.  It does not explicitly say so, but this implies
   1.180 -** that it overrides locks set by the same process using a different
   1.181 -** file descriptor.  Consider this test case:
   1.182 -**
   1.183 -**       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
   1.184 -**       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
   1.185 -**
   1.186 -** Suppose ./file1 and ./file2 are really the same file (because
   1.187 -** one is a hard or symbolic link to the other) then if you set
   1.188 -** an exclusive lock on fd1, then try to get an exclusive lock
   1.189 -** on fd2, it works.  I would have expected the second lock to
   1.190 -** fail since there was already a lock on the file due to fd1.
   1.191 -** But not so.  Since both locks came from the same process, the
   1.192 -** second overrides the first, even though they were on different
   1.193 -** file descriptors opened on different file names.
   1.194 -**
   1.195 -** Bummer.  If you ask me, this is broken.  Badly broken.  It means
   1.196 -** that we cannot use POSIX locks to synchronize file access among
   1.197 -** competing threads of the same process.  POSIX locks will work fine
   1.198 -** to synchronize access for threads in separate processes, but not
   1.199 -** threads within the same process.
   1.200 -**
   1.201 -** To work around the problem, SQLite has to manage file locks internally
   1.202 -** on its own.  Whenever a new database is opened, we have to find the
   1.203 -** specific inode of the database file (the inode is determined by the
   1.204 -** st_dev and st_ino fields of the stat structure that fstat() fills in)
   1.205 -** and check for locks already existing on that inode.  When locks are
   1.206 -** created or removed, we have to look at our own internal record of the
   1.207 -** locks to see if another thread has previously set a lock on that same
   1.208 -** inode.
   1.209 -**
   1.210 -** The sqlite3_file structure for POSIX is no longer just an integer file
   1.211 -** descriptor.  It is now a structure that holds the integer file
   1.212 -** descriptor and a pointer to a structure that describes the internal
   1.213 -** locks on the corresponding inode.  There is one locking structure
   1.214 -** per inode, so if the same inode is opened twice, both unixFile structures
   1.215 -** point to the same locking structure.  The locking structure keeps
   1.216 -** a reference count (so we will know when to delete it) and a "cnt"
   1.217 -** field that tells us its internal lock status.  cnt==0 means the
   1.218 -** file is unlocked.  cnt==-1 means the file has an exclusive lock.
   1.219 -** cnt>0 means there are cnt shared locks on the file.
   1.220 -**
   1.221 -** Any attempt to lock or unlock a file first checks the locking
   1.222 -** structure.  The fcntl() system call is only invoked to set a 
   1.223 -** POSIX lock if the internal lock structure transitions between
   1.224 -** a locked and an unlocked state.
   1.225 -**
   1.226 -** 2004-Jan-11:
   1.227 -** More recent discoveries about POSIX advisory locks.  (The more
   1.228 -** I discover, the more I realize the a POSIX advisory locks are
   1.229 -** an abomination.)
   1.230 -**
   1.231 -** If you close a file descriptor that points to a file that has locks,
   1.232 -** all locks on that file that are owned by the current process are
   1.233 -** released.  To work around this problem, each unixFile structure contains
   1.234 -** a pointer to an openCnt structure.  There is one openCnt structure
   1.235 -** per open inode, which means that multiple unixFile can point to a single
   1.236 -** openCnt.  When an attempt is made to close an unixFile, if there are
   1.237 -** other unixFile open on the same inode that are holding locks, the call
   1.238 -** to close() the file descriptor is deferred until all of the locks clear.
   1.239 -** The openCnt structure keeps a list of file descriptors that need to
   1.240 -** be closed and that list is walked (and cleared) when the last lock
   1.241 -** clears.
   1.242 -**
   1.243 -** First, under Linux threads, because each thread has a separate
   1.244 -** process ID, lock operations in one thread do not override locks
   1.245 -** to the same file in other threads.  Linux threads behave like
   1.246 -** separate processes in this respect.  But, if you close a file
   1.247 -** descriptor in linux threads, all locks are cleared, even locks
   1.248 -** on other threads and even though the other threads have different
   1.249 -** process IDs.  Linux threads is inconsistent in this respect.
   1.250 -** (I'm beginning to think that linux threads is an abomination too.)
   1.251 -** The consequence of this all is that the hash table for the lockInfo
   1.252 -** structure has to include the process id as part of its key because
   1.253 -** locks in different threads are treated as distinct.  But the 
   1.254 -** openCnt structure should not include the process id in its
   1.255 -** key because close() clears lock on all threads, not just the current
   1.256 -** thread.  Were it not for this goofiness in linux threads, we could
   1.257 -** combine the lockInfo and openCnt structures into a single structure.
   1.258 -**
   1.259 -** 2004-Jun-28:
   1.260 -** On some versions of linux, threads can override each others locks.
   1.261 -** On others not.  Sometimes you can change the behavior on the same
   1.262 -** system by setting the LD_ASSUME_KERNEL environment variable.  The
   1.263 -** POSIX standard is silent as to which behavior is correct, as far
   1.264 -** as I can tell, so other versions of unix might show the same
   1.265 -** inconsistency.  There is no little doubt in my mind that posix
   1.266 -** advisory locks and linux threads are profoundly broken.
   1.267 -**
   1.268 -** To work around the inconsistencies, we have to test at runtime 
   1.269 -** whether or not threads can override each others locks.  This test
   1.270 -** is run once, the first time any lock is attempted.  A static 
   1.271 -** variable is set to record the results of this test for future
   1.272 -** use.
   1.273 -*/
   1.274 -
   1.275 -/*
   1.276 -** An instance of the following structure serves as the key used
   1.277 -** to locate a particular lockInfo structure given its inode.
   1.278 -**
   1.279 -** If threads cannot override each others locks, then we set the
   1.280 -** lockKey.tid field to the thread ID.  If threads can override
   1.281 -** each others locks then tid is always set to zero.  tid is omitted
   1.282 -** if we compile without threading support.
   1.283 -*/
   1.284 -struct lockKey {
   1.285 -  dev_t dev;       /* Device number */
   1.286 -  ino_t ino;       /* Inode number */
   1.287 -#if SQLITE_THREADSAFE
   1.288 -  pthread_t tid;   /* Thread ID or zero if threads can override each other */
   1.289 -#endif
   1.290 -};
   1.291 -
   1.292 -/*
   1.293 -** An instance of the following structure is allocated for each open
   1.294 -** inode on each thread with a different process ID.  (Threads have
   1.295 -** different process IDs on linux, but not on most other unixes.)
   1.296 -**
   1.297 -** A single inode can have multiple file descriptors, so each unixFile
   1.298 -** structure contains a pointer to an instance of this object and this
   1.299 -** object keeps a count of the number of unixFile pointing to it.
   1.300 -*/
   1.301 -struct lockInfo {
   1.302 -  struct lockKey key;  /* The lookup key */
   1.303 -  int cnt;             /* Number of SHARED locks held */
   1.304 -  int locktype;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
   1.305 -  int nRef;            /* Number of pointers to this structure */
   1.306 -};
   1.307 -
   1.308 -/*
   1.309 -** An instance of the following structure serves as the key used
   1.310 -** to locate a particular openCnt structure given its inode.  This
   1.311 -** is the same as the lockKey except that the thread ID is omitted.
   1.312 -*/
   1.313 -struct openKey {
   1.314 -  dev_t dev;   /* Device number */
   1.315 -  ino_t ino;   /* Inode number */
   1.316 -};
   1.317 -
   1.318 -/*
   1.319 -** An instance of the following structure is allocated for each open
   1.320 -** inode.  This structure keeps track of the number of locks on that
   1.321 -** inode.  If a close is attempted against an inode that is holding
   1.322 -** locks, the close is deferred until all locks clear by adding the
   1.323 -** file descriptor to be closed to the pending list.
   1.324 -*/
   1.325 -struct openCnt {
   1.326 -  struct openKey key;   /* The lookup key */
   1.327 -  int nRef;             /* Number of pointers to this structure */
   1.328 -  int nLock;            /* Number of outstanding locks */
   1.329 -  int nPending;         /* Number of pending close() operations */
   1.330 -  int *aPending;        /* Malloced space holding fd's awaiting a close() */
   1.331 -};
   1.332 -
   1.333 -/* 
   1.334 -** These hash tables map inodes and file descriptors (really, lockKey and
   1.335 -** openKey structures) into lockInfo and openCnt structures.  Access to 
   1.336 -** these hash tables must be protected by a mutex.
   1.337 -*/
   1.338 -static Hash lockHash = {SQLITE_HASH_BINARY, 0, 0, 0, 0, 0};
   1.339 -static Hash openHash = {SQLITE_HASH_BINARY, 0, 0, 0, 0, 0};
   1.340 -
   1.341 -#ifdef SQLITE_ENABLE_LOCKING_STYLE
   1.342 -/*
   1.343 -** The locking styles are associated with the different file locking
   1.344 -** capabilities supported by different file systems.  
   1.345 -**
   1.346 -** POSIX locking style fully supports shared and exclusive byte-range locks 
   1.347 -** ADP locking only supports exclusive byte-range locks
   1.348 -** FLOCK only supports a single file-global exclusive lock
   1.349 -** DOTLOCK isn't a true locking style, it refers to the use of a special
   1.350 -**   file named the same as the database file with a '.lock' extension, this
   1.351 -**   can be used on file systems that do not offer any reliable file locking
   1.352 -** NO locking means that no locking will be attempted, this is only used for
   1.353 -**   read-only file systems currently
   1.354 -** UNSUPPORTED means that no locking will be attempted, this is only used for
   1.355 -**   file systems that are known to be unsupported
   1.356 -*/
   1.357 -typedef enum {
   1.358 -        posixLockingStyle = 0,       /* standard posix-advisory locks */
   1.359 -        afpLockingStyle,             /* use afp locks */
   1.360 -        flockLockingStyle,           /* use flock() */
   1.361 -        dotlockLockingStyle,         /* use <file>.lock files */
   1.362 -        noLockingStyle,              /* useful for read-only file system */
   1.363 -        unsupportedLockingStyle      /* indicates unsupported file system */
   1.364 -} sqlite3LockingStyle;
   1.365 -#endif /* SQLITE_ENABLE_LOCKING_STYLE */
   1.366 -
   1.367 -/*
   1.368 -** Helper functions to obtain and relinquish the global mutex.
   1.369 -*/
   1.370 -static void enterMutex(){
   1.371 -  sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
   1.372 -}
   1.373 -static void leaveMutex(){
   1.374 -  sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
   1.375 -}
   1.376 -
   1.377 -#if SQLITE_THREADSAFE
   1.378 -/*
   1.379 -** This variable records whether or not threads can override each others
   1.380 -** locks.
   1.381 -**
   1.382 -**    0:  No.  Threads cannot override each others locks.
   1.383 -**    1:  Yes.  Threads can override each others locks.
   1.384 -**   -1:  We don't know yet.
   1.385 -**
   1.386 -** On some systems, we know at compile-time if threads can override each
   1.387 -** others locks.  On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
   1.388 -** will be set appropriately.  On other systems, we have to check at
   1.389 -** runtime.  On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
   1.390 -** undefined.
   1.391 -**
   1.392 -** This variable normally has file scope only.  But during testing, we make
   1.393 -** it a global so that the test code can change its value in order to verify
   1.394 -** that the right stuff happens in either case.
   1.395 -*/
   1.396 -#ifndef SQLITE_THREAD_OVERRIDE_LOCK
   1.397 -# define SQLITE_THREAD_OVERRIDE_LOCK -1
   1.398 -#endif
   1.399 -#ifdef SQLITE_TEST
   1.400 -int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
   1.401 -#else
   1.402 -static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
   1.403 -#endif
   1.404 -
   1.405 -/*
   1.406 -** This structure holds information passed into individual test
   1.407 -** threads by the testThreadLockingBehavior() routine.
   1.408 -*/
   1.409 -struct threadTestData {
   1.410 -  int fd;                /* File to be locked */
   1.411 -  struct flock lock;     /* The locking operation */
   1.412 -  int result;            /* Result of the locking operation */
   1.413 -};
   1.414 -
   1.415 -#ifdef SQLITE_LOCK_TRACE
   1.416 -/*
   1.417 -** Print out information about all locking operations.
   1.418 -**
   1.419 -** This routine is used for troubleshooting locks on multithreaded
   1.420 -** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
   1.421 -** command-line option on the compiler.  This code is normally
   1.422 -** turned off.
   1.423 -*/
   1.424 -static int lockTrace(int fd, int op, struct flock *p){
   1.425 -  char *zOpName, *zType;
   1.426 -  int s;
   1.427 -  int savedErrno;
   1.428 -  if( op==F_GETLK ){
   1.429 -    zOpName = "GETLK";
   1.430 -  }else if( op==F_SETLK ){
   1.431 -    zOpName = "SETLK";
   1.432 -  }else{
   1.433 -    s = fcntl(fd, op, p);
   1.434 -    sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
   1.435 -    return s;
   1.436 -  }
   1.437 -  if( p->l_type==F_RDLCK ){
   1.438 -    zType = "RDLCK";
   1.439 -  }else if( p->l_type==F_WRLCK ){
   1.440 -    zType = "WRLCK";
   1.441 -  }else if( p->l_type==F_UNLCK ){
   1.442 -    zType = "UNLCK";
   1.443 -  }else{
   1.444 -    assert( 0 );
   1.445 -  }
   1.446 -  assert( p->l_whence==SEEK_SET );
   1.447 -  s = fcntl(fd, op, p);
   1.448 -  savedErrno = errno;
   1.449 -  sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
   1.450 -     threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
   1.451 -     (int)p->l_pid, s);
   1.452 -  if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
   1.453 -    struct flock l2;
   1.454 -    l2 = *p;
   1.455 -    fcntl(fd, F_GETLK, &l2);
   1.456 -    if( l2.l_type==F_RDLCK ){
   1.457 -      zType = "RDLCK";
   1.458 -    }else if( l2.l_type==F_WRLCK ){
   1.459 -      zType = "WRLCK";
   1.460 -    }else if( l2.l_type==F_UNLCK ){
   1.461 -      zType = "UNLCK";
   1.462 -    }else{
   1.463 -      assert( 0 );
   1.464 -    }
   1.465 -    sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
   1.466 -       zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
   1.467 -  }
   1.468 -  errno = savedErrno;
   1.469 -  return s;
   1.470 -}
   1.471 -#define fcntl lockTrace
   1.472 -#endif /* SQLITE_LOCK_TRACE */
   1.473 -
   1.474 -/*
   1.475 -** The testThreadLockingBehavior() routine launches two separate
   1.476 -** threads on this routine.  This routine attempts to lock a file
   1.477 -** descriptor then returns.  The success or failure of that attempt
   1.478 -** allows the testThreadLockingBehavior() procedure to determine
   1.479 -** whether or not threads can override each others locks.
   1.480 -*/
   1.481 -static void *threadLockingTest(void *pArg){
   1.482 -  struct threadTestData *pData = (struct threadTestData*)pArg;
   1.483 -  pData->result = fcntl(pData->fd, F_SETLK, &pData->lock);
   1.484 -  return pArg;
   1.485 -}
   1.486 -
   1.487 -/*
   1.488 -** This procedure attempts to determine whether or not threads
   1.489 -** can override each others locks then sets the 
   1.490 -** threadsOverrideEachOthersLocks variable appropriately.
   1.491 -*/
   1.492 -static void testThreadLockingBehavior(int fd_orig){
   1.493 -  int fd;
   1.494 -  struct threadTestData d[2];
   1.495 -  pthread_t t[2];
   1.496 -
   1.497 -  fd = dup(fd_orig);
   1.498 -  if( fd<0 ) return;
   1.499 -  memset(d, 0, sizeof(d));
   1.500 -  d[0].fd = fd;
   1.501 -  d[0].lock.l_type = F_RDLCK;
   1.502 -  d[0].lock.l_len = 1;
   1.503 -  d[0].lock.l_start = 0;
   1.504 -  d[0].lock.l_whence = SEEK_SET;
   1.505 -  d[1] = d[0];
   1.506 -  d[1].lock.l_type = F_WRLCK;
   1.507 -  pthread_create(&t[0], 0, threadLockingTest, &d[0]);
   1.508 -  pthread_create(&t[1], 0, threadLockingTest, &d[1]);
   1.509 -  pthread_join(t[0], 0);
   1.510 -  pthread_join(t[1], 0);
   1.511 -  close(fd);
   1.512 -  threadsOverrideEachOthersLocks =  d[0].result==0 && d[1].result==0;
   1.513 -}
   1.514 -#endif /* SQLITE_THREADSAFE */
   1.515 -
   1.516 -/*
   1.517 -** Release a lockInfo structure previously allocated by findLockInfo().
   1.518 -*/
   1.519 -static void releaseLockInfo(struct lockInfo *pLock){
   1.520 -  if (pLock == NULL)
   1.521 -    return;
   1.522 -  pLock->nRef--;
   1.523 -  if( pLock->nRef==0 ){
   1.524 -    sqlite3HashInsert(&lockHash, &pLock->key, sizeof(pLock->key), 0);
   1.525 -    sqlite3_free(pLock);
   1.526 -  }
   1.527 -}
   1.528 -
   1.529 -/*
   1.530 -** Release a openCnt structure previously allocated by findLockInfo().
   1.531 -*/
   1.532 -static void releaseOpenCnt(struct openCnt *pOpen){
   1.533 -  if (pOpen == NULL)
   1.534 -    return;
   1.535 -  pOpen->nRef--;
   1.536 -  if( pOpen->nRef==0 ){
   1.537 -    sqlite3HashInsert(&openHash, &pOpen->key, sizeof(pOpen->key), 0);
   1.538 -    free(pOpen->aPending);
   1.539 -    sqlite3_free(pOpen);
   1.540 -  }
   1.541 -}
   1.542 -
   1.543 -#ifdef SQLITE_ENABLE_LOCKING_STYLE
   1.544 -/*
   1.545 -** Tests a byte-range locking query to see if byte range locks are 
   1.546 -** supported, if not we fall back to dotlockLockingStyle.
   1.547 -*/
   1.548 -static sqlite3LockingStyle sqlite3TestLockingStyle(
   1.549 -  const char *filePath, 
   1.550 -  int fd
   1.551 -){
   1.552 -  /* test byte-range lock using fcntl */
   1.553 -  struct flock lockInfo;
   1.554 -  
   1.555 -  lockInfo.l_len = 1;
   1.556 -  lockInfo.l_start = 0;
   1.557 -  lockInfo.l_whence = SEEK_SET;
   1.558 -  lockInfo.l_type = F_RDLCK;
   1.559 -  
   1.560 -  if( fcntl(fd, F_GETLK, &lockInfo)!=-1 ) {
   1.561 -    return posixLockingStyle;
   1.562 -  } 
   1.563 -  
   1.564 -  /* testing for flock can give false positives.  So if if the above test
   1.565 -  ** fails, then we fall back to using dot-lock style locking.
   1.566 -  */  
   1.567 -  return dotlockLockingStyle;
   1.568 -}
   1.569 -
   1.570 -/* 
   1.571 -** Examines the f_fstypename entry in the statfs structure as returned by 
   1.572 -** stat() for the file system hosting the database file, assigns the 
   1.573 -** appropriate locking style based on it's value.  These values and 
   1.574 -** assignments are based on Darwin/OSX behavior and have not been tested on 
   1.575 -** other systems.
   1.576 -*/
   1.577 -static sqlite3LockingStyle sqlite3DetectLockingStyle(
   1.578 -  const char *filePath, 
   1.579 -  int fd
   1.580 -){
   1.581 -
   1.582 -#ifdef SQLITE_FIXED_LOCKING_STYLE
   1.583 -  return (sqlite3LockingStyle)SQLITE_FIXED_LOCKING_STYLE;
   1.584 -#else
   1.585 -  struct statfs fsInfo;
   1.586 -
   1.587 -  if (statfs(filePath, &fsInfo) == -1)
   1.588 -    return sqlite3TestLockingStyle(filePath, fd);
   1.589 -  
   1.590 -  if (fsInfo.f_flags & MNT_RDONLY)
   1.591 -    return noLockingStyle;
   1.592 -  
   1.593 -  if( (!strcmp(fsInfo.f_fstypename, "hfs")) ||
   1.594 -    (!strcmp(fsInfo.f_fstypename, "ufs")) )
   1.595 -                return posixLockingStyle;
   1.596 -  
   1.597 -  if(!strcmp(fsInfo.f_fstypename, "afpfs"))
   1.598 -    return afpLockingStyle;
   1.599 -  
   1.600 -  if(!strcmp(fsInfo.f_fstypename, "nfs")) 
   1.601 -    return sqlite3TestLockingStyle(filePath, fd);
   1.602 -  
   1.603 -  if(!strcmp(fsInfo.f_fstypename, "smbfs"))
   1.604 -    return flockLockingStyle;
   1.605 -  
   1.606 -  if(!strcmp(fsInfo.f_fstypename, "msdos"))
   1.607 -    return dotlockLockingStyle;
   1.608 -  
   1.609 -  if(!strcmp(fsInfo.f_fstypename, "webdav"))
   1.610 -    return unsupportedLockingStyle;
   1.611 -  
   1.612 -  return sqlite3TestLockingStyle(filePath, fd);  
   1.613 -#endif /* SQLITE_FIXED_LOCKING_STYLE */
   1.614 -}
   1.615 -
   1.616 -#endif /* SQLITE_ENABLE_LOCKING_STYLE */
   1.617 -
   1.618 -/*
   1.619 -** Given a file descriptor, locate lockInfo and openCnt structures that
   1.620 -** describes that file descriptor.  Create new ones if necessary.  The
   1.621 -** return values might be uninitialized if an error occurs.
   1.622 -**
   1.623 -** Return the number of errors.
   1.624 -*/
   1.625 -static int findLockInfo(
   1.626 -  int fd,                      /* The file descriptor used in the key */
   1.627 -  struct lockInfo **ppLock,    /* Return the lockInfo structure here */
   1.628 -  struct openCnt **ppOpen      /* Return the openCnt structure here */
   1.629 -){
   1.630 -  int rc;
   1.631 -  struct lockKey key1;
   1.632 -  struct openKey key2;
   1.633 -  struct stat statbuf;
   1.634 -  struct lockInfo *pLock;
   1.635 -  struct openCnt *pOpen;
   1.636 -  rc = fstat(fd, &statbuf);
   1.637 -  if( rc!=0 ) return 1;
   1.638 -
   1.639 -  memset(&key1, 0, sizeof(key1));
   1.640 -  key1.dev = statbuf.st_dev;
   1.641 -  key1.ino = statbuf.st_ino;
   1.642 -#if SQLITE_THREADSAFE
   1.643 -  if( threadsOverrideEachOthersLocks<0 ){
   1.644 -    testThreadLockingBehavior(fd);
   1.645 -  }
   1.646 -  key1.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
   1.647 -#endif
   1.648 -  memset(&key2, 0, sizeof(key2));
   1.649 -  key2.dev = statbuf.st_dev;
   1.650 -  key2.ino = statbuf.st_ino;
   1.651 -  pLock = (struct lockInfo*)sqlite3HashFind(&lockHash, &key1, sizeof(key1));
   1.652 -  if( pLock==0 ){
   1.653 -    struct lockInfo *pOld;
   1.654 -    pLock = sqlite3_malloc( sizeof(*pLock) );
   1.655 -    if( pLock==0 ){
   1.656 -      rc = 1;
   1.657 -      goto exit_findlockinfo;
   1.658 -    }
   1.659 -    pLock->key = key1;
   1.660 -    pLock->nRef = 1;
   1.661 -    pLock->cnt = 0;
   1.662 -    pLock->locktype = 0;
   1.663 -    pOld = sqlite3HashInsert(&lockHash, &pLock->key, sizeof(key1), pLock);
   1.664 -    if( pOld!=0 ){
   1.665 -      assert( pOld==pLock );
   1.666 -      sqlite3_free(pLock);
   1.667 -      rc = 1;
   1.668 -      goto exit_findlockinfo;
   1.669 -    }
   1.670 -  }else{
   1.671 -    pLock->nRef++;
   1.672 -  }
   1.673 -  *ppLock = pLock;
   1.674 -  if( ppOpen!=0 ){
   1.675 -    pOpen = (struct openCnt*)sqlite3HashFind(&openHash, &key2, sizeof(key2));
   1.676 -    if( pOpen==0 ){
   1.677 -      struct openCnt *pOld;
   1.678 -      pOpen = sqlite3_malloc( sizeof(*pOpen) );
   1.679 -      if( pOpen==0 ){
   1.680 -        releaseLockInfo(pLock);
   1.681 -        rc = 1;
   1.682 -        goto exit_findlockinfo;
   1.683 -      }
   1.684 -      pOpen->key = key2;
   1.685 -      pOpen->nRef = 1;
   1.686 -      pOpen->nLock = 0;
   1.687 -      pOpen->nPending = 0;
   1.688 -      pOpen->aPending = 0;
   1.689 -      pOld = sqlite3HashInsert(&openHash, &pOpen->key, sizeof(key2), pOpen);
   1.690 -      if( pOld!=0 ){
   1.691 -        assert( pOld==pOpen );
   1.692 -        sqlite3_free(pOpen);
   1.693 -        releaseLockInfo(pLock);
   1.694 -        rc = 1;
   1.695 -        goto exit_findlockinfo;
   1.696 -      }
   1.697 -    }else{
   1.698 -      pOpen->nRef++;
   1.699 -    }
   1.700 -    *ppOpen = pOpen;
   1.701 -  }
   1.702 -
   1.703 -exit_findlockinfo:
   1.704 -  return rc;
   1.705 -}
   1.706 -
   1.707 -#ifdef SQLITE_DEBUG
   1.708 -/*
   1.709 -** Helper function for printing out trace information from debugging
   1.710 -** binaries. This returns the string represetation of the supplied
   1.711 -** integer lock-type.
   1.712 -*/
   1.713 -static const char *locktypeName(int locktype){
   1.714 -  switch( locktype ){
   1.715 -  case NO_LOCK: return "NONE";
   1.716 -  case SHARED_LOCK: return "SHARED";
   1.717 -  case RESERVED_LOCK: return "RESERVED";
   1.718 -  case PENDING_LOCK: return "PENDING";
   1.719 -  case EXCLUSIVE_LOCK: return "EXCLUSIVE";
   1.720 -  }
   1.721 -  return "ERROR";
   1.722 -}
   1.723 -#endif
   1.724 -
   1.725 -/*
   1.726 -** If we are currently in a different thread than the thread that the
   1.727 -** unixFile argument belongs to, then transfer ownership of the unixFile
   1.728 -** over to the current thread.
   1.729 -**
   1.730 -** A unixFile is only owned by a thread on systems where one thread is
   1.731 -** unable to override locks created by a different thread.  RedHat9 is
   1.732 -** an example of such a system.
   1.733 -**
   1.734 -** Ownership transfer is only allowed if the unixFile is currently unlocked.
   1.735 -** If the unixFile is locked and an ownership is wrong, then return
   1.736 -** SQLITE_MISUSE.  SQLITE_OK is returned if everything works.
   1.737 -*/
   1.738 -#if SQLITE_THREADSAFE
   1.739 -static int transferOwnership(unixFile *pFile){
   1.740 -  int rc;
   1.741 -  pthread_t hSelf;
   1.742 -  if( threadsOverrideEachOthersLocks ){
   1.743 -    /* Ownership transfers not needed on this system */
   1.744 -    return SQLITE_OK;
   1.745 -  }
   1.746 -  hSelf = pthread_self();
   1.747 -  if( pthread_equal(pFile->tid, hSelf) ){
   1.748 -    /* We are still in the same thread */
   1.749 -    OSTRACE1("No-transfer, same thread\n");
   1.750 -    return SQLITE_OK;
   1.751 -  }
   1.752 -  if( pFile->locktype!=NO_LOCK ){
   1.753 -    /* We cannot change ownership while we are holding a lock! */
   1.754 -    return SQLITE_MISUSE;
   1.755 -  }
   1.756 -  OSTRACE4("Transfer ownership of %d from %d to %d\n",
   1.757 -            pFile->h, pFile->tid, hSelf);
   1.758 -  pFile->tid = hSelf;
   1.759 -  if (pFile->pLock != NULL) {
   1.760 -    releaseLockInfo(pFile->pLock);
   1.761 -    rc = findLockInfo(pFile->h, &pFile->pLock, 0);
   1.762 -    OSTRACE5("LOCK    %d is now %s(%s,%d)\n", pFile->h,
   1.763 -           locktypeName(pFile->locktype),
   1.764 -           locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
   1.765 -    return rc;
   1.766 -  } else {
   1.767 -    return SQLITE_OK;
   1.768 -  }
   1.769 -}
   1.770 -#else
   1.771 -  /* On single-threaded builds, ownership transfer is a no-op */
   1.772 -# define transferOwnership(X) SQLITE_OK
   1.773 -#endif
   1.774 -
   1.775 -/*
   1.776 -** Seek to the offset passed as the second argument, then read cnt 
   1.777 -** bytes into pBuf. Return the number of bytes actually read.
   1.778 -*/
   1.779 -static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
   1.780 -  int got;
   1.781 -  i64 newOffset;
   1.782 -  TIMER_START;
   1.783 -#if defined(USE_PREAD)
   1.784 -  got = pread(id->h, pBuf, cnt, offset);
   1.785 -  SimulateIOError( got = -1 );
   1.786 -#elif defined(USE_PREAD64)
   1.787 -  got = pread64(id->h, pBuf, cnt, offset);
   1.788 -  SimulateIOError( got = -1 );
   1.789 -#else
   1.790 -  newOffset = lseek(id->h, offset, SEEK_SET);
   1.791 -  SimulateIOError( newOffset-- );
   1.792 -  if( newOffset!=offset ){
   1.793 -    return -1;
   1.794 -  }
   1.795 -  got = read(id->h, pBuf, cnt);
   1.796 -#endif
   1.797 -  TIMER_END;
   1.798 -  OSTRACE5("READ    %-3d %5d %7lld %d\n", id->h, got, offset, TIMER_ELAPSED);
   1.799 -  return got;
   1.800 -}
   1.801 -
   1.802 -/*
   1.803 -** Read data from a file into a buffer.  Return SQLITE_OK if all
   1.804 -** bytes were read successfully and SQLITE_IOERR if anything goes
   1.805 -** wrong.
   1.806 -*/
   1.807 -static int unixRead(
   1.808 -  sqlite3_file *id, 
   1.809 -  void *pBuf, 
   1.810 -  int amt,
   1.811 -  sqlite3_int64 offset
   1.812 -){
   1.813 -  int got;
   1.814 -  assert( id );
   1.815 -  got = seekAndRead((unixFile*)id, offset, pBuf, amt);
   1.816 -  if( got==amt ){
   1.817 -    return SQLITE_OK;
   1.818 -  }else if( got<0 ){
   1.819 -    return SQLITE_IOERR_READ;
   1.820 -  }else{
   1.821 -    memset(&((char*)pBuf)[got], 0, amt-got);
   1.822 -    return SQLITE_IOERR_SHORT_READ;
   1.823 -  }
   1.824 -}
   1.825 -
   1.826 -/*
   1.827 -** Seek to the offset in id->offset then read cnt bytes into pBuf.
   1.828 -** Return the number of bytes actually read.  Update the offset.
   1.829 -*/
   1.830 -static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
   1.831 -  int got;
   1.832 -  i64 newOffset;
   1.833 -  TIMER_START;
   1.834 -#if defined(USE_PREAD)
   1.835 -  got = pwrite(id->h, pBuf, cnt, offset);
   1.836 -#elif defined(USE_PREAD64)
   1.837 -  got = pwrite64(id->h, pBuf, cnt, offset);
   1.838 -#else
   1.839 -  newOffset = lseek(id->h, offset, SEEK_SET);
   1.840 -  if( newOffset!=offset ){
   1.841 -    return -1;
   1.842 -  }
   1.843 -  got = write(id->h, pBuf, cnt);
   1.844 -#endif
   1.845 -  TIMER_END;
   1.846 -  OSTRACE5("WRITE   %-3d %5d %7lld %d\n", id->h, got, offset, TIMER_ELAPSED);
   1.847 -  return got;
   1.848 -}
   1.849 -
   1.850 -
   1.851 -/*
   1.852 -** Write data from a buffer into a file.  Return SQLITE_OK on success
   1.853 -** or some other error code on failure.
   1.854 -*/
   1.855 -static int unixWrite(
   1.856 -  sqlite3_file *id, 
   1.857 -  const void *pBuf, 
   1.858 -  int amt,
   1.859 -  sqlite3_int64 offset 
   1.860 -){
   1.861 -  int wrote = 0;
   1.862 -  assert( id );
   1.863 -  assert( amt>0 );
   1.864 -  while( amt>0 && (wrote = seekAndWrite((unixFile*)id, offset, pBuf, amt))>0 ){
   1.865 -    amt -= wrote;
   1.866 -    offset += wrote;
   1.867 -    pBuf = &((char*)pBuf)[wrote];
   1.868 -  }
   1.869 -  SimulateIOError(( wrote=(-1), amt=1 ));
   1.870 -  SimulateDiskfullError(( wrote=0, amt=1 ));
   1.871 -  if( amt>0 ){
   1.872 -    if( wrote<0 ){
   1.873 -      return SQLITE_IOERR_WRITE;
   1.874 -    }else{
   1.875 -      return SQLITE_FULL;
   1.876 -    }
   1.877 -  }
   1.878 -  return SQLITE_OK;
   1.879 -}
   1.880 -
   1.881 -#ifdef SQLITE_TEST
   1.882 -/*
   1.883 -** Count the number of fullsyncs and normal syncs.  This is used to test
   1.884 -** that syncs and fullsyncs are occuring at the right times.
   1.885 -*/
   1.886 -int sqlite3_sync_count = 0;
   1.887 -int sqlite3_fullsync_count = 0;
   1.888 -#endif
   1.889 -
   1.890 -/*
   1.891 -** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
   1.892 -** Otherwise use fsync() in its place.
   1.893 -*/
   1.894 -#ifndef HAVE_FDATASYNC
   1.895 -# define fdatasync fsync
   1.896 -#endif
   1.897 -
   1.898 -/*
   1.899 -** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
   1.900 -** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
   1.901 -** only available on Mac OS X.  But that could change.
   1.902 -*/
   1.903 -#ifdef F_FULLFSYNC
   1.904 -# define HAVE_FULLFSYNC 1
   1.905 -#else
   1.906 -# define HAVE_FULLFSYNC 0
   1.907 -#endif
   1.908 -
   1.909 -
   1.910 -/*
   1.911 -** The fsync() system call does not work as advertised on many
   1.912 -** unix systems.  The following procedure is an attempt to make
   1.913 -** it work better.
   1.914 -**
   1.915 -** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
   1.916 -** for testing when we want to run through the test suite quickly.
   1.917 -** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
   1.918 -** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
   1.919 -** or power failure will likely corrupt the database file.
   1.920 -*/
   1.921 -static int full_fsync(int fd, int fullSync, int dataOnly){
   1.922 -  int rc;
   1.923 -
   1.924 -  /* Record the number of times that we do a normal fsync() and 
   1.925 -  ** FULLSYNC.  This is used during testing to verify that this procedure
   1.926 -  ** gets called with the correct arguments.
   1.927 -  */
   1.928 -#ifdef SQLITE_TEST
   1.929 -  if( fullSync ) sqlite3_fullsync_count++;
   1.930 -  sqlite3_sync_count++;
   1.931 -#endif
   1.932 -
   1.933 -  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
   1.934 -  ** no-op
   1.935 -  */
   1.936 -#ifdef SQLITE_NO_SYNC
   1.937 -  rc = SQLITE_OK;
   1.938 -#else
   1.939 -
   1.940 -#if HAVE_FULLFSYNC
   1.941 -  if( fullSync ){
   1.942 -    rc = fcntl(fd, F_FULLFSYNC, 0);
   1.943 -  }else{
   1.944 -    rc = 1;
   1.945 -  }
   1.946 -  /* If the FULLFSYNC failed, fall back to attempting an fsync().
   1.947 -   * It shouldn't be possible for fullfsync to fail on the local 
   1.948 -   * file system (on OSX), so failure indicates that FULLFSYNC
   1.949 -   * isn't supported for this file system. So, attempt an fsync 
   1.950 -   * and (for now) ignore the overhead of a superfluous fcntl call.  
   1.951 -   * It'd be better to detect fullfsync support once and avoid 
   1.952 -   * the fcntl call every time sync is called.
   1.953 -   */
   1.954 -  if( rc ) rc = fsync(fd);
   1.955 -
   1.956 -#else 
   1.957 -  if( dataOnly ){
   1.958 -    rc = fdatasync(fd);
   1.959 -  }else{
   1.960 -    rc = fsync(fd);
   1.961 -  }
   1.962 -#endif /* HAVE_FULLFSYNC */
   1.963 -#endif /* defined(SQLITE_NO_SYNC) */
   1.964 -
   1.965 -  return rc;
   1.966 -}
   1.967 -
   1.968 -/*
   1.969 -** Make sure all writes to a particular file are committed to disk.
   1.970 -**
   1.971 -** If dataOnly==0 then both the file itself and its metadata (file
   1.972 -** size, access time, etc) are synced.  If dataOnly!=0 then only the
   1.973 -** file data is synced.
   1.974 -**
   1.975 -** Under Unix, also make sure that the directory entry for the file
   1.976 -** has been created by fsync-ing the directory that contains the file.
   1.977 -** If we do not do this and we encounter a power failure, the directory
   1.978 -** entry for the journal might not exist after we reboot.  The next
   1.979 -** SQLite to access the file will not know that the journal exists (because
   1.980 -** the directory entry for the journal was never created) and the transaction
   1.981 -** will not roll back - possibly leading to database corruption.
   1.982 -*/
   1.983 -static int unixSync(sqlite3_file *id, int flags){
   1.984 -  int rc;
   1.985 -  unixFile *pFile = (unixFile*)id;
   1.986 -
   1.987 -  int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
   1.988 -  int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
   1.989 -
   1.990 -  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
   1.991 -  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
   1.992 -      || (flags&0x0F)==SQLITE_SYNC_FULL
   1.993 -  );
   1.994 -
   1.995 -  assert( pFile );
   1.996 -  OSTRACE2("SYNC    %-3d\n", pFile->h);
   1.997 -  rc = full_fsync(pFile->h, isFullsync, isDataOnly);
   1.998 -  SimulateIOError( rc=1 );
   1.999 -  if( rc ){
  1.1000 -    return SQLITE_IOERR_FSYNC;
  1.1001 -  }
  1.1002 -  if( pFile->dirfd>=0 ){
  1.1003 -    OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
  1.1004 -            HAVE_FULLFSYNC, isFullsync);
  1.1005 -#ifndef SQLITE_DISABLE_DIRSYNC
  1.1006 -    /* The directory sync is only attempted if full_fsync is
  1.1007 -    ** turned off or unavailable.  If a full_fsync occurred above,
  1.1008 -    ** then the directory sync is superfluous.
  1.1009 -    */
  1.1010 -    if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
  1.1011 -       /*
  1.1012 -       ** We have received multiple reports of fsync() returning
  1.1013 -       ** errors when applied to directories on certain file systems.
  1.1014 -       ** A failed directory sync is not a big deal.  So it seems
  1.1015 -       ** better to ignore the error.  Ticket #1657
  1.1016 -       */
  1.1017 -       /* return SQLITE_IOERR; */
  1.1018 -    }
  1.1019 -#endif
  1.1020 -    close(pFile->dirfd);  /* Only need to sync once, so close the directory */
  1.1021 -    pFile->dirfd = -1;    /* when we are done. */
  1.1022 -  }
  1.1023 -  return SQLITE_OK;
  1.1024 -}
  1.1025 -
  1.1026 -/*
  1.1027 -** Truncate an open file to a specified size
  1.1028 -*/
  1.1029 -static int unixTruncate(sqlite3_file *id, i64 nByte){
  1.1030 -  int rc;
  1.1031 -  assert( id );
  1.1032 -  rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
  1.1033 -  SimulateIOError( rc=1 );
  1.1034 -  if( rc ){
  1.1035 -    return SQLITE_IOERR_TRUNCATE;
  1.1036 -  }else{
  1.1037 -    return SQLITE_OK;
  1.1038 -  }
  1.1039 -}
  1.1040 -
  1.1041 -/*
  1.1042 -** Determine the current size of a file in bytes
  1.1043 -*/
  1.1044 -static int unixFileSize(sqlite3_file *id, i64 *pSize){
  1.1045 -  int rc;
  1.1046 -  struct stat buf;
  1.1047 -  assert( id );
  1.1048 -  rc = fstat(((unixFile*)id)->h, &buf);
  1.1049 -  SimulateIOError( rc=1 );
  1.1050 -  if( rc!=0 ){
  1.1051 -    return SQLITE_IOERR_FSTAT;
  1.1052 -  }
  1.1053 -  *pSize = buf.st_size;
  1.1054 -  return SQLITE_OK;
  1.1055 -}
  1.1056 -
  1.1057 -/*
  1.1058 -** This routine checks if there is a RESERVED lock held on the specified
  1.1059 -** file by this or any other process. If such a lock is held, return
  1.1060 -** non-zero.  If the file is unlocked or holds only SHARED locks, then
  1.1061 -** return zero.
  1.1062 -*/
  1.1063 -static int unixCheckReservedLock(sqlite3_file *id){
  1.1064 -  int r = 0;
  1.1065 -  unixFile *pFile = (unixFile*)id;
  1.1066 -
  1.1067 -  assert( pFile );
  1.1068 -  enterMutex(); /* Because pFile->pLock is shared across threads */
  1.1069 -
  1.1070 -  /* Check if a thread in this process holds such a lock */
  1.1071 -  if( pFile->pLock->locktype>SHARED_LOCK ){
  1.1072 -    r = 1;
  1.1073 -  }
  1.1074 -
  1.1075 -  /* Otherwise see if some other process holds it.
  1.1076 -  */
  1.1077 -  if( !r ){
  1.1078 -    struct flock lock;
  1.1079 -    lock.l_whence = SEEK_SET;
  1.1080 -    lock.l_start = RESERVED_BYTE;
  1.1081 -    lock.l_len = 1;
  1.1082 -    lock.l_type = F_WRLCK;
  1.1083 -    fcntl(pFile->h, F_GETLK, &lock);
  1.1084 -    if( lock.l_type!=F_UNLCK ){
  1.1085 -      r = 1;
  1.1086 -    }
  1.1087 -  }
  1.1088 -  
  1.1089 -  leaveMutex();
  1.1090 -  OSTRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
  1.1091 -
  1.1092 -  return r;
  1.1093 -}
  1.1094 -
  1.1095 -/*
  1.1096 -** Lock the file with the lock specified by parameter locktype - one
  1.1097 -** of the following:
  1.1098 -**
  1.1099 -**     (1) SHARED_LOCK
  1.1100 -**     (2) RESERVED_LOCK
  1.1101 -**     (3) PENDING_LOCK
  1.1102 -**     (4) EXCLUSIVE_LOCK
  1.1103 -**
  1.1104 -** Sometimes when requesting one lock state, additional lock states
  1.1105 -** are inserted in between.  The locking might fail on one of the later
  1.1106 -** transitions leaving the lock state different from what it started but
  1.1107 -** still short of its goal.  The following chart shows the allowed
  1.1108 -** transitions and the inserted intermediate states:
  1.1109 -**
  1.1110 -**    UNLOCKED -> SHARED
  1.1111 -**    SHARED -> RESERVED
  1.1112 -**    SHARED -> (PENDING) -> EXCLUSIVE
  1.1113 -**    RESERVED -> (PENDING) -> EXCLUSIVE
  1.1114 -**    PENDING -> EXCLUSIVE
  1.1115 -**
  1.1116 -** This routine will only increase a lock.  Use the sqlite3OsUnlock()
  1.1117 -** routine to lower a locking level.
  1.1118 -*/
  1.1119 -static int unixLock(sqlite3_file *id, int locktype){
  1.1120 -  /* The following describes the implementation of the various locks and
  1.1121 -  ** lock transitions in terms of the POSIX advisory shared and exclusive
  1.1122 -  ** lock primitives (called read-locks and write-locks below, to avoid
  1.1123 -  ** confusion with SQLite lock names). The algorithms are complicated
  1.1124 -  ** slightly in order to be compatible with windows systems simultaneously
  1.1125 -  ** accessing the same database file, in case that is ever required.
  1.1126 -  **
  1.1127 -  ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
  1.1128 -  ** byte', each single bytes at well known offsets, and the 'shared byte
  1.1129 -  ** range', a range of 510 bytes at a well known offset.
  1.1130 -  **
  1.1131 -  ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
  1.1132 -  ** byte'.  If this is successful, a random byte from the 'shared byte
  1.1133 -  ** range' is read-locked and the lock on the 'pending byte' released.
  1.1134 -  **
  1.1135 -  ** A process may only obtain a RESERVED lock after it has a SHARED lock.
  1.1136 -  ** A RESERVED lock is implemented by grabbing a write-lock on the
  1.1137 -  ** 'reserved byte'. 
  1.1138 -  **
  1.1139 -  ** A process may only obtain a PENDING lock after it has obtained a
  1.1140 -  ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
  1.1141 -  ** on the 'pending byte'. This ensures that no new SHARED locks can be
  1.1142 -  ** obtained, but existing SHARED locks are allowed to persist. A process
  1.1143 -  ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
  1.1144 -  ** This property is used by the algorithm for rolling back a journal file
  1.1145 -  ** after a crash.
  1.1146 -  **
  1.1147 -  ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
  1.1148 -  ** implemented by obtaining a write-lock on the entire 'shared byte
  1.1149 -  ** range'. Since all other locks require a read-lock on one of the bytes
  1.1150 -  ** within this range, this ensures that no other locks are held on the
  1.1151 -  ** database. 
  1.1152 -  **
  1.1153 -  ** The reason a single byte cannot be used instead of the 'shared byte
  1.1154 -  ** range' is that some versions of windows do not support read-locks. By
  1.1155 -  ** locking a random byte from a range, concurrent SHARED locks may exist
  1.1156 -  ** even if the locking primitive used is always a write-lock.
  1.1157 -  */
  1.1158 -  int rc = SQLITE_OK;
  1.1159 -  unixFile *pFile = (unixFile*)id;
  1.1160 -  struct lockInfo *pLock = pFile->pLock;
  1.1161 -  struct flock lock;
  1.1162 -  int s;
  1.1163 -
  1.1164 -  assert( pFile );
  1.1165 -  OSTRACE7("LOCK    %d %s was %s(%s,%d) pid=%d\n", pFile->h,
  1.1166 -      locktypeName(locktype), locktypeName(pFile->locktype),
  1.1167 -      locktypeName(pLock->locktype), pLock->cnt , getpid());
  1.1168 -
  1.1169 -  /* If there is already a lock of this type or more restrictive on the
  1.1170 -  ** unixFile, do nothing. Don't use the end_lock: exit path, as
  1.1171 -  ** enterMutex() hasn't been called yet.
  1.1172 -  */
  1.1173 -  if( pFile->locktype>=locktype ){
  1.1174 -    OSTRACE3("LOCK    %d %s ok (already held)\n", pFile->h,
  1.1175 -            locktypeName(locktype));
  1.1176 -    return SQLITE_OK;
  1.1177 -  }
  1.1178 -
  1.1179 -  /* Make sure the locking sequence is correct
  1.1180 -  */
  1.1181 -  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  1.1182 -  assert( locktype!=PENDING_LOCK );
  1.1183 -  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  1.1184 -
  1.1185 -  /* This mutex is needed because pFile->pLock is shared across threads
  1.1186 -  */
  1.1187 -  enterMutex();
  1.1188 -
  1.1189 -  /* Make sure the current thread owns the pFile.
  1.1190 -  */
  1.1191 -  rc = transferOwnership(pFile);
  1.1192 -  if( rc!=SQLITE_OK ){
  1.1193 -    leaveMutex();
  1.1194 -    return rc;
  1.1195 -  }
  1.1196 -  pLock = pFile->pLock;
  1.1197 -
  1.1198 -  /* If some thread using this PID has a lock via a different unixFile*
  1.1199 -  ** handle that precludes the requested lock, return BUSY.
  1.1200 -  */
  1.1201 -  if( (pFile->locktype!=pLock->locktype && 
  1.1202 -          (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
  1.1203 -  ){
  1.1204 -    rc = SQLITE_BUSY;
  1.1205 -    goto end_lock;
  1.1206 -  }
  1.1207 -
  1.1208 -  /* If a SHARED lock is requested, and some thread using this PID already
  1.1209 -  ** has a SHARED or RESERVED lock, then increment reference counts and
  1.1210 -  ** return SQLITE_OK.
  1.1211 -  */
  1.1212 -  if( locktype==SHARED_LOCK && 
  1.1213 -      (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
  1.1214 -    assert( locktype==SHARED_LOCK );
  1.1215 -    assert( pFile->locktype==0 );
  1.1216 -    assert( pLock->cnt>0 );
  1.1217 -    pFile->locktype = SHARED_LOCK;
  1.1218 -    pLock->cnt++;
  1.1219 -    pFile->pOpen->nLock++;
  1.1220 -    goto end_lock;
  1.1221 -  }
  1.1222 -
  1.1223 -  lock.l_len = 1L;
  1.1224 -
  1.1225 -  lock.l_whence = SEEK_SET;
  1.1226 -
  1.1227 -  /* A PENDING lock is needed before acquiring a SHARED lock and before
  1.1228 -  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
  1.1229 -  ** be released.
  1.1230 -  */
  1.1231 -  if( locktype==SHARED_LOCK 
  1.1232 -      || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
  1.1233 -  ){
  1.1234 -    lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
  1.1235 -    lock.l_start = PENDING_BYTE;
  1.1236 -    s = fcntl(pFile->h, F_SETLK, &lock);
  1.1237 -    if( s==(-1) ){
  1.1238 -      rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
  1.1239 -      goto end_lock;
  1.1240 -    }
  1.1241 -  }
  1.1242 -
  1.1243 -
  1.1244 -  /* If control gets to this point, then actually go ahead and make
  1.1245 -  ** operating system calls for the specified lock.
  1.1246 -  */
  1.1247 -  if( locktype==SHARED_LOCK ){
  1.1248 -    assert( pLock->cnt==0 );
  1.1249 -    assert( pLock->locktype==0 );
  1.1250 -
  1.1251 -    /* Now get the read-lock */
  1.1252 -    lock.l_start = SHARED_FIRST;
  1.1253 -    lock.l_len = SHARED_SIZE;
  1.1254 -    s = fcntl(pFile->h, F_SETLK, &lock);
  1.1255 -
  1.1256 -    /* Drop the temporary PENDING lock */
  1.1257 -    lock.l_start = PENDING_BYTE;
  1.1258 -    lock.l_len = 1L;
  1.1259 -    lock.l_type = F_UNLCK;
  1.1260 -    if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
  1.1261 -      rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
  1.1262 -      goto end_lock;
  1.1263 -    }
  1.1264 -    if( s==(-1) ){
  1.1265 -      rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
  1.1266 -    }else{
  1.1267 -      pFile->locktype = SHARED_LOCK;
  1.1268 -      pFile->pOpen->nLock++;
  1.1269 -      pLock->cnt = 1;
  1.1270 -    }
  1.1271 -  }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
  1.1272 -    /* We are trying for an exclusive lock but another thread in this
  1.1273 -    ** same process is still holding a shared lock. */
  1.1274 -    rc = SQLITE_BUSY;
  1.1275 -  }else{
  1.1276 -    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
  1.1277 -    ** assumed that there is a SHARED or greater lock on the file
  1.1278 -    ** already.
  1.1279 -    */
  1.1280 -    assert( 0!=pFile->locktype );
  1.1281 -    lock.l_type = F_WRLCK;
  1.1282 -    switch( locktype ){
  1.1283 -      case RESERVED_LOCK:
  1.1284 -        lock.l_start = RESERVED_BYTE;
  1.1285 -        break;
  1.1286 -      case EXCLUSIVE_LOCK:
  1.1287 -        lock.l_start = SHARED_FIRST;
  1.1288 -        lock.l_len = SHARED_SIZE;
  1.1289 -        break;
  1.1290 -      default:
  1.1291 -        assert(0);
  1.1292 -    }
  1.1293 -    s = fcntl(pFile->h, F_SETLK, &lock);
  1.1294 -    if( s==(-1) ){
  1.1295 -      rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
  1.1296 -    }
  1.1297 -  }
  1.1298 -  
  1.1299 -  if( rc==SQLITE_OK ){
  1.1300 -    pFile->locktype = locktype;
  1.1301 -    pLock->locktype = locktype;
  1.1302 -  }else if( locktype==EXCLUSIVE_LOCK ){
  1.1303 -    pFile->locktype = PENDING_LOCK;
  1.1304 -    pLock->locktype = PENDING_LOCK;
  1.1305 -  }
  1.1306 -
  1.1307 -end_lock:
  1.1308 -  leaveMutex();
  1.1309 -  OSTRACE4("LOCK    %d %s %s\n", pFile->h, locktypeName(locktype), 
  1.1310 -      rc==SQLITE_OK ? "ok" : "failed");
  1.1311 -  return rc;
  1.1312 -}
  1.1313 -
  1.1314 -/*
  1.1315 -** Lower the locking level on file descriptor pFile to locktype.  locktype
  1.1316 -** must be either NO_LOCK or SHARED_LOCK.
  1.1317 -**
  1.1318 -** If the locking level of the file descriptor is already at or below
  1.1319 -** the requested locking level, this routine is a no-op.
  1.1320 -*/
  1.1321 -static int unixUnlock(sqlite3_file *id, int locktype){
  1.1322 -  struct lockInfo *pLock;
  1.1323 -  struct flock lock;
  1.1324 -  int rc = SQLITE_OK;
  1.1325 -  unixFile *pFile = (unixFile*)id;
  1.1326 -
  1.1327 -  assert( pFile );
  1.1328 -  OSTRACE7("UNLOCK  %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
  1.1329 -      pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
  1.1330 -
  1.1331 -  assert( locktype<=SHARED_LOCK );
  1.1332 -  if( pFile->locktype<=locktype ){
  1.1333 -    return SQLITE_OK;
  1.1334 -  }
  1.1335 -  if( CHECK_THREADID(pFile) ){
  1.1336 -    return SQLITE_MISUSE;
  1.1337 -  }
  1.1338 -  enterMutex();
  1.1339 -  pLock = pFile->pLock;
  1.1340 -  assert( pLock->cnt!=0 );
  1.1341 -  if( pFile->locktype>SHARED_LOCK ){
  1.1342 -    assert( pLock->locktype==pFile->locktype );
  1.1343 -    if( locktype==SHARED_LOCK ){
  1.1344 -      lock.l_type = F_RDLCK;
  1.1345 -      lock.l_whence = SEEK_SET;
  1.1346 -      lock.l_start = SHARED_FIRST;
  1.1347 -      lock.l_len = SHARED_SIZE;
  1.1348 -      if( fcntl(pFile->h, F_SETLK, &lock)==(-1) ){
  1.1349 -        /* This should never happen */
  1.1350 -        rc = SQLITE_IOERR_RDLOCK;
  1.1351 -      }
  1.1352 -    }
  1.1353 -    lock.l_type = F_UNLCK;
  1.1354 -    lock.l_whence = SEEK_SET;
  1.1355 -    lock.l_start = PENDING_BYTE;
  1.1356 -    lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
  1.1357 -    if( fcntl(pFile->h, F_SETLK, &lock)!=(-1) ){
  1.1358 -      pLock->locktype = SHARED_LOCK;
  1.1359 -    }else{
  1.1360 -      rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
  1.1361 -    }
  1.1362 -  }
  1.1363 -  if( locktype==NO_LOCK ){
  1.1364 -    struct openCnt *pOpen;
  1.1365 -
  1.1366 -    /* Decrement the shared lock counter.  Release the lock using an
  1.1367 -    ** OS call only when all threads in this same process have released
  1.1368 -    ** the lock.
  1.1369 -    */
  1.1370 -    pLock->cnt--;
  1.1371 -    if( pLock->cnt==0 ){
  1.1372 -      lock.l_type = F_UNLCK;
  1.1373 -      lock.l_whence = SEEK_SET;
  1.1374 -      lock.l_start = lock.l_len = 0L;
  1.1375 -      if( fcntl(pFile->h, F_SETLK, &lock)!=(-1) ){
  1.1376 -        pLock->locktype = NO_LOCK;
  1.1377 -      }else{
  1.1378 -        rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
  1.1379 -      }
  1.1380 -    }
  1.1381 -
  1.1382 -    /* Decrement the count of locks against this same file.  When the
  1.1383 -    ** count reaches zero, close any other file descriptors whose close
  1.1384 -    ** was deferred because of outstanding locks.
  1.1385 -    */
  1.1386 -    pOpen = pFile->pOpen;
  1.1387 -    pOpen->nLock--;
  1.1388 -    assert( pOpen->nLock>=0 );
  1.1389 -    if( pOpen->nLock==0 && pOpen->nPending>0 ){
  1.1390 -      int i;
  1.1391 -      for(i=0; i<pOpen->nPending; i++){
  1.1392 -        close(pOpen->aPending[i]);
  1.1393 -      }
  1.1394 -      free(pOpen->aPending);
  1.1395 -      pOpen->nPending = 0;
  1.1396 -      pOpen->aPending = 0;
  1.1397 -    }
  1.1398 -  }
  1.1399 -  leaveMutex();
  1.1400 -  pFile->locktype = locktype;
  1.1401 -  return rc;
  1.1402 -}
  1.1403 -
  1.1404 -/*
  1.1405 -** Close a file.
  1.1406 -*/
  1.1407 -static int unixClose(sqlite3_file *id){
  1.1408 -  unixFile *pFile = (unixFile *)id;
  1.1409 -  if( !pFile ) return SQLITE_OK;
  1.1410 -  unixUnlock(id, NO_LOCK);
  1.1411 -  if( pFile->dirfd>=0 ) close(pFile->dirfd);
  1.1412 -  pFile->dirfd = -1;
  1.1413 -  enterMutex();
  1.1414 -
  1.1415 -  if( pFile->pOpen->nLock ){
  1.1416 -    /* If there are outstanding locks, do not actually close the file just
  1.1417 -    ** yet because that would clear those locks.  Instead, add the file
  1.1418 -    ** descriptor to pOpen->aPending.  It will be automatically closed when
  1.1419 -    ** the last lock is cleared.
  1.1420 -    */
  1.1421 -    int *aNew;
  1.1422 -    struct openCnt *pOpen = pFile->pOpen;
  1.1423 -    aNew = realloc( pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
  1.1424 -    if( aNew==0 ){
  1.1425 -      /* If a malloc fails, just leak the file descriptor */
  1.1426 -    }else{
  1.1427 -      pOpen->aPending = aNew;
  1.1428 -      pOpen->aPending[pOpen->nPending] = pFile->h;
  1.1429 -      pOpen->nPending++;
  1.1430 -    }
  1.1431 -  }else{
  1.1432 -    /* There are no outstanding locks so we can close the file immediately */
  1.1433 -    close(pFile->h);
  1.1434 -  }
  1.1435 -  releaseLockInfo(pFile->pLock);
  1.1436 -  releaseOpenCnt(pFile->pOpen);
  1.1437 -
  1.1438 -  leaveMutex();
  1.1439 -  OSTRACE2("CLOSE   %-3d\n", pFile->h);
  1.1440 -  OpenCounter(-1);
  1.1441 -  memset(pFile, 0, sizeof(unixFile));
  1.1442 -  return SQLITE_OK;
  1.1443 -}
  1.1444 -
  1.1445 -
  1.1446 -#ifdef SQLITE_ENABLE_LOCKING_STYLE
  1.1447 -#pragma mark AFP Support
  1.1448 -
  1.1449 -/*
  1.1450 - ** The afpLockingContext structure contains all afp lock specific state
  1.1451 - */
  1.1452 -typedef struct afpLockingContext afpLockingContext;
  1.1453 -struct afpLockingContext {
  1.1454 -  unsigned long long sharedLockByte;
  1.1455 -  char *filePath;
  1.1456 -};
  1.1457 -
  1.1458 -struct ByteRangeLockPB2
  1.1459 -{
  1.1460 -  unsigned long long offset;        /* offset to first byte to lock */
  1.1461 -  unsigned long long length;        /* nbr of bytes to lock */
  1.1462 -  unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
  1.1463 -  unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
  1.1464 -  unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
  1.1465 -  int fd;                           /* file desc to assoc this lock with */
  1.1466 -};
  1.1467 -
  1.1468 -#define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
  1.1469 -
  1.1470 -/* 
  1.1471 -** Return 0 on success, 1 on failure.  To match the behavior of the 
  1.1472 -** normal posix file locking (used in unixLock for example), we should 
  1.1473 -** provide 'richer' return codes - specifically to differentiate between
  1.1474 -** 'file busy' and 'file system error' results.
  1.1475 -*/
  1.1476 -static int _AFPFSSetLock(
  1.1477 -  const char *path, 
  1.1478 -  int fd, 
  1.1479 -  unsigned long long offset, 
  1.1480 -  unsigned long long length, 
  1.1481 -  int setLockFlag
  1.1482 -){
  1.1483 -  struct ByteRangeLockPB2       pb;
  1.1484 -  int                     err;
  1.1485 -  
  1.1486 -  pb.unLockFlag = setLockFlag ? 0 : 1;
  1.1487 -  pb.startEndFlag = 0;
  1.1488 -  pb.offset = offset;
  1.1489 -  pb.length = length; 
  1.1490 -  pb.fd = fd;
  1.1491 -  OSTRACE5("AFPLOCK setting lock %s for %d in range %llx:%llx\n", 
  1.1492 -    (setLockFlag?"ON":"OFF"), fd, offset, length);
  1.1493 -  err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
  1.1494 -  if ( err==-1 ) {
  1.1495 -    OSTRACE4("AFPLOCK failed to fsctl() '%s' %d %s\n", path, errno, 
  1.1496 -      strerror(errno));
  1.1497 -    return 1; /* error */
  1.1498 -  } else {
  1.1499 -    return 0;
  1.1500 -  }
  1.1501 -}
  1.1502 -
  1.1503 -/*
  1.1504 - ** This routine checks if there is a RESERVED lock held on the specified
  1.1505 - ** file by this or any other process. If such a lock is held, return
  1.1506 - ** non-zero.  If the file is unlocked or holds only SHARED locks, then
  1.1507 - ** return zero.
  1.1508 - */
  1.1509 -static int afpUnixCheckReservedLock(sqlite3_file *id){
  1.1510 -  int r = 0;
  1.1511 -  unixFile *pFile = (unixFile*)id;
  1.1512 -  
  1.1513 -  assert( pFile ); 
  1.1514 -  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  1.1515 -  
  1.1516 -  /* Check if a thread in this process holds such a lock */
  1.1517 -  if( pFile->locktype>SHARED_LOCK ){
  1.1518 -    r = 1;
  1.1519 -  }
  1.1520 -  
  1.1521 -  /* Otherwise see if some other process holds it.
  1.1522 -   */
  1.1523 -  if ( !r ) {
  1.1524 -    /* lock the byte */
  1.1525 -    int failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);  
  1.1526 -    if (failed) {
  1.1527 -      /* if we failed to get the lock then someone else must have it */
  1.1528 -      r = 1;
  1.1529 -    } else {
  1.1530 -      /* if we succeeded in taking the reserved lock, unlock it to restore
  1.1531 -      ** the original state */
  1.1532 -      _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0);
  1.1533 -    }
  1.1534 -  }
  1.1535 -  OSTRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
  1.1536 -  
  1.1537 -  return r;
  1.1538 -}
  1.1539 -
  1.1540 -/* AFP-style locking following the behavior of unixLock, see the unixLock 
  1.1541 -** function comments for details of lock management. */
  1.1542 -static int afpUnixLock(sqlite3_file *id, int locktype)
  1.1543 -{
  1.1544 -  int rc = SQLITE_OK;
  1.1545 -  unixFile *pFile = (unixFile*)id;
  1.1546 -  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  1.1547 -  int gotPendingLock = 0;
  1.1548 -  
  1.1549 -  assert( pFile );
  1.1550 -  OSTRACE5("LOCK    %d %s was %s pid=%d\n", pFile->h,
  1.1551 -         locktypeName(locktype), locktypeName(pFile->locktype), getpid());  
  1.1552 -  /* If there is already a lock of this type or more restrictive on the
  1.1553 -    ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
  1.1554 -    ** enterMutex() hasn't been called yet.
  1.1555 -    */
  1.1556 -  if( pFile->locktype>=locktype ){
  1.1557 -    OSTRACE3("LOCK    %d %s ok (already held)\n", pFile->h,
  1.1558 -           locktypeName(locktype));
  1.1559 -    return SQLITE_OK;
  1.1560 -  }
  1.1561 -
  1.1562 -  /* Make sure the locking sequence is correct
  1.1563 -    */
  1.1564 -  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  1.1565 -  assert( locktype!=PENDING_LOCK );
  1.1566 -  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  1.1567 -  
  1.1568 -  /* This mutex is needed because pFile->pLock is shared across threads
  1.1569 -    */
  1.1570 -  enterMutex();
  1.1571 -
  1.1572 -  /* Make sure the current thread owns the pFile.
  1.1573 -    */
  1.1574 -  rc = transferOwnership(pFile);
  1.1575 -  if( rc!=SQLITE_OK ){
  1.1576 -    leaveMutex();
  1.1577 -    return rc;
  1.1578 -  }
  1.1579 -    
  1.1580 -  /* A PENDING lock is needed before acquiring a SHARED lock and before
  1.1581 -    ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
  1.1582 -    ** be released.
  1.1583 -    */
  1.1584 -  if( locktype==SHARED_LOCK 
  1.1585 -      || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
  1.1586 -      ){
  1.1587 -    int failed = _AFPFSSetLock(context->filePath, pFile->h, 
  1.1588 -      PENDING_BYTE, 1, 1);
  1.1589 -    if (failed) {
  1.1590 -      rc = SQLITE_BUSY;
  1.1591 -      goto afp_end_lock;
  1.1592 -    }
  1.1593 -  }
  1.1594 -  
  1.1595 -  /* If control gets to this point, then actually go ahead and make
  1.1596 -    ** operating system calls for the specified lock.
  1.1597 -    */
  1.1598 -  if( locktype==SHARED_LOCK ){
  1.1599 -    int lk, failed;
  1.1600 -    int tries = 0;
  1.1601 -    
  1.1602 -    /* Now get the read-lock */
  1.1603 -    /* note that the quality of the randomness doesn't matter that much */
  1.1604 -    lk = random(); 
  1.1605 -    context->sharedLockByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
  1.1606 -    failed = _AFPFSSetLock(context->filePath, pFile->h, 
  1.1607 -      SHARED_FIRST+context->sharedLockByte, 1, 1);
  1.1608 -    
  1.1609 -    /* Drop the temporary PENDING lock */
  1.1610 -    if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)) {
  1.1611 -      rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
  1.1612 -      goto afp_end_lock;
  1.1613 -    }
  1.1614 -    
  1.1615 -    if( failed ){
  1.1616 -      rc = SQLITE_BUSY;
  1.1617 -    } else {
  1.1618 -      pFile->locktype = SHARED_LOCK;
  1.1619 -    }
  1.1620 -  }else{
  1.1621 -    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
  1.1622 -    ** assumed that there is a SHARED or greater lock on the file
  1.1623 -    ** already.
  1.1624 -    */
  1.1625 -    int failed = 0;
  1.1626 -    assert( 0!=pFile->locktype );
  1.1627 -    if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
  1.1628 -        /* Acquire a RESERVED lock */
  1.1629 -        failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);
  1.1630 -    }
  1.1631 -    if (!failed && locktype == EXCLUSIVE_LOCK) {
  1.1632 -      /* Acquire an EXCLUSIVE lock */
  1.1633 -        
  1.1634 -      /* Remove the shared lock before trying the range.  we'll need to 
  1.1635 -      ** reestablish the shared lock if we can't get the  afpUnixUnlock
  1.1636 -      */
  1.1637 -      if (!_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
  1.1638 -                         context->sharedLockByte, 1, 0)) {
  1.1639 -        /* now attemmpt to get the exclusive lock range */
  1.1640 -        failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST, 
  1.1641 -                               SHARED_SIZE, 1);
  1.1642 -        if (failed && _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
  1.1643 -                                    context->sharedLockByte, 1, 1)) {
  1.1644 -          rc = SQLITE_IOERR_RDLOCK; /* this should never happen */
  1.1645 -        }
  1.1646 -      } else {
  1.1647 -        /* */
  1.1648 -        rc = SQLITE_IOERR_UNLOCK; /* this should never happen */
  1.1649 -      }
  1.1650 -    }
  1.1651 -    if( failed && rc == SQLITE_OK){
  1.1652 -      rc = SQLITE_BUSY;
  1.1653 -    }
  1.1654 -  }
  1.1655 -  
  1.1656 -  if( rc==SQLITE_OK ){
  1.1657 -    pFile->locktype = locktype;
  1.1658 -  }else if( locktype==EXCLUSIVE_LOCK ){
  1.1659 -    pFile->locktype = PENDING_LOCK;
  1.1660 -  }
  1.1661 -  
  1.1662 -afp_end_lock:
  1.1663 -    leaveMutex();
  1.1664 -  OSTRACE4("LOCK    %d %s %s\n", pFile->h, locktypeName(locktype), 
  1.1665 -         rc==SQLITE_OK ? "ok" : "failed");
  1.1666 -  return rc;
  1.1667 -}
  1.1668 -
  1.1669 -/*
  1.1670 - ** Lower the locking level on file descriptor pFile to locktype.  locktype
  1.1671 - ** must be either NO_LOCK or SHARED_LOCK.
  1.1672 - **
  1.1673 - ** If the locking level of the file descriptor is already at or below
  1.1674 - ** the requested locking level, this routine is a no-op.
  1.1675 - */
  1.1676 -static int afpUnixUnlock(sqlite3_file *id, int locktype) {
  1.1677 -  struct flock lock;
  1.1678 -  int rc = SQLITE_OK;
  1.1679 -  unixFile *pFile = (unixFile*)id;
  1.1680 -  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  1.1681 -
  1.1682 -  assert( pFile );
  1.1683 -  OSTRACE5("UNLOCK  %d %d was %d pid=%d\n", pFile->h, locktype,
  1.1684 -         pFile->locktype, getpid());
  1.1685 -  
  1.1686 -  assert( locktype<=SHARED_LOCK );
  1.1687 -  if( pFile->locktype<=locktype ){
  1.1688 -    return SQLITE_OK;
  1.1689 -  }
  1.1690 -  if( CHECK_THREADID(pFile) ){
  1.1691 -    return SQLITE_MISUSE;
  1.1692 -  }
  1.1693 -  enterMutex();
  1.1694 -  if( pFile->locktype>SHARED_LOCK ){
  1.1695 -    if( locktype==SHARED_LOCK ){
  1.1696 -      int failed = 0;
  1.1697 -
  1.1698 -      /* unlock the exclusive range - then re-establish the shared lock */
  1.1699 -      if (pFile->locktype==EXCLUSIVE_LOCK) {
  1.1700 -        failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST, 
  1.1701 -                                 SHARED_SIZE, 0);
  1.1702 -        if (!failed) {
  1.1703 -          /* successfully removed the exclusive lock */
  1.1704 -          if (_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST+
  1.1705 -                            context->sharedLockByte, 1, 1)) {
  1.1706 -            /* failed to re-establish our shared lock */
  1.1707 -            rc = SQLITE_IOERR_RDLOCK; /* This should never happen */
  1.1708 -          }
  1.1709 -        } else {
  1.1710 -          /* This should never happen - failed to unlock the exclusive range */
  1.1711 -          rc = SQLITE_IOERR_UNLOCK;
  1.1712 -        } 
  1.1713 -      }
  1.1714 -    }
  1.1715 -    if (rc == SQLITE_OK && pFile->locktype>=PENDING_LOCK) {
  1.1716 -      if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)){
  1.1717 -        /* failed to release the pending lock */
  1.1718 -        rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
  1.1719 -      }
  1.1720 -    } 
  1.1721 -    if (rc == SQLITE_OK && pFile->locktype>=RESERVED_LOCK) {
  1.1722 -      if (_AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0)) {
  1.1723 -        /* failed to release the reserved lock */
  1.1724 -        rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
  1.1725 -      }
  1.1726 -    } 
  1.1727 -  }
  1.1728 -  if( locktype==NO_LOCK ){
  1.1729 -    int failed = _AFPFSSetLock(context->filePath, pFile->h, 
  1.1730 -                               SHARED_FIRST + context->sharedLockByte, 1, 0);
  1.1731 -    if (failed) {
  1.1732 -      rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
  1.1733 -    }
  1.1734 -  }
  1.1735 -  if (rc == SQLITE_OK)
  1.1736 -    pFile->locktype = locktype;
  1.1737 -  leaveMutex();
  1.1738 -  return rc;
  1.1739 -}
  1.1740 -
  1.1741 -/*
  1.1742 - ** Close a file & cleanup AFP specific locking context 
  1.1743 - */
  1.1744 -static int afpUnixClose(sqlite3_file *id) {
  1.1745 -  unixFile *pFile = (unixFile*)pId;
  1.1746 -
  1.1747 -  if( !pFile ) return SQLITE_OK;
  1.1748 -  afpUnixUnlock(*pId, NO_LOCK);
  1.1749 -  /* free the AFP locking structure */
  1.1750 -  if (pFile->lockingContext != NULL) {
  1.1751 -    if (((afpLockingContext *)pFile->lockingContext)->filePath != NULL)
  1.1752 -      sqlite3_free(((afpLockingContext*)pFile->lockingContext)->filePath);
  1.1753 -    sqlite3_free(pFile->lockingContext);
  1.1754 -  }
  1.1755 -
  1.1756 -  if( pFile->dirfd>=0 ) close(pFile->dirfd);
  1.1757 -  pFile->dirfd = -1;
  1.1758 -  close(pFile->h);
  1.1759 -  OSTRACE2("CLOSE   %-3d\n", pFile->h);
  1.1760 -  OpenCounter(-1);
  1.1761 -  return SQLITE_OK;
  1.1762 -}
  1.1763 -
  1.1764 -
  1.1765 -#pragma mark flock() style locking
  1.1766 -
  1.1767 -/*
  1.1768 - ** The flockLockingContext is not used
  1.1769 - */
  1.1770 -typedef void flockLockingContext;
  1.1771 -
  1.1772 -static int flockUnixCheckReservedLock(sqlite3_file *id) {
  1.1773 -  unixFile *pFile = (unixFile*)id;
  1.1774 -  
  1.1775 -  if (pFile->locktype == RESERVED_LOCK) {
  1.1776 -    return 1; /* already have a reserved lock */
  1.1777 -  } else {
  1.1778 -    /* attempt to get the lock */
  1.1779 -    int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
  1.1780 -    if (!rc) {
  1.1781 -      /* got the lock, unlock it */
  1.1782 -      flock(pFile->h, LOCK_UN);
  1.1783 -      return 0;  /* no one has it reserved */
  1.1784 -    }
  1.1785 -    return 1; /* someone else might have it reserved */
  1.1786 -  }
  1.1787 -}
  1.1788 -
  1.1789 -static int flockUnixLock(sqlite3_file *id, int locktype) {
  1.1790 -  unixFile *pFile = (unixFile*)id;
  1.1791 -  
  1.1792 -  /* if we already have a lock, it is exclusive.  
  1.1793 -  ** Just adjust level and punt on outta here. */
  1.1794 -  if (pFile->locktype > NO_LOCK) {
  1.1795 -    pFile->locktype = locktype;
  1.1796 -    return SQLITE_OK;
  1.1797 -  }
  1.1798 -  
  1.1799 -  /* grab an exclusive lock */
  1.1800 -  int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
  1.1801 -  if (rc) {
  1.1802 -    /* didn't get, must be busy */
  1.1803 -    return SQLITE_BUSY;
  1.1804 -  } else {
  1.1805 -    /* got it, set the type and return ok */
  1.1806 -    pFile->locktype = locktype;
  1.1807 -    return SQLITE_OK;
  1.1808 -  }
  1.1809 -}
  1.1810 -
  1.1811 -static int flockUnixUnlock(sqlite3_file *id, int locktype) {
  1.1812 -  unixFile *pFile = (unixFile*)id;
  1.1813 -  
  1.1814 -  assert( locktype<=SHARED_LOCK );
  1.1815 -  
  1.1816 -  /* no-op if possible */
  1.1817 -  if( pFile->locktype==locktype ){
  1.1818 -    return SQLITE_OK;
  1.1819 -  }
  1.1820 -  
  1.1821 -  /* shared can just be set because we always have an exclusive */
  1.1822 -  if (locktype==SHARED_LOCK) {
  1.1823 -    pFile->locktype = locktype;
  1.1824 -    return SQLITE_OK;
  1.1825 -  }
  1.1826 -  
  1.1827 -  /* no, really, unlock. */
  1.1828 -  int rc = flock(pFile->h, LOCK_UN);
  1.1829 -  if (rc)
  1.1830 -    return SQLITE_IOERR_UNLOCK;
  1.1831 -  else {
  1.1832 -    pFile->locktype = NO_LOCK;
  1.1833 -    return SQLITE_OK;
  1.1834 -  }
  1.1835 -}
  1.1836 -
  1.1837 -/*
  1.1838 - ** Close a file.
  1.1839 - */
  1.1840 -static int flockUnixClose(sqlite3_file *pId) {
  1.1841 -  unixFile *pFile = (unixFile*)*pId;
  1.1842 -  
  1.1843 -  if( !pFile ) return SQLITE_OK;
  1.1844 -  flockUnixUnlock(*pId, NO_LOCK);
  1.1845 -  
  1.1846 -  if( pFile->dirfd>=0 ) close(pFile->dirfd);
  1.1847 -  pFile->dirfd = -1;
  1.1848 -  enterMutex();
  1.1849 -  
  1.1850 -  close(pFile->h);  
  1.1851 -  leaveMutex();
  1.1852 -  OSTRACE2("CLOSE   %-3d\n", pFile->h);
  1.1853 -  OpenCounter(-1);
  1.1854 -  return SQLITE_OK;
  1.1855 -}
  1.1856 -
  1.1857 -#pragma mark Old-School .lock file based locking
  1.1858 -
  1.1859 -/*
  1.1860 - ** The dotlockLockingContext structure contains all dotlock (.lock) lock
  1.1861 - ** specific state
  1.1862 - */
  1.1863 -typedef struct dotlockLockingContext dotlockLockingContext;
  1.1864 -struct dotlockLockingContext {
  1.1865 -  char *lockPath;
  1.1866 -};
  1.1867 -
  1.1868 -
  1.1869 -static int dotlockUnixCheckReservedLock(sqlite3_file *id) {
  1.1870 -  unixFile *pFile = (unixFile*)id;
  1.1871 -  dotlockLockingContext *context = 
  1.1872 -    (dotlockLockingContext *) pFile->lockingContext;
  1.1873 -  
  1.1874 -  if (pFile->locktype == RESERVED_LOCK) {
  1.1875 -    return 1; /* already have a reserved lock */
  1.1876 -  } else {
  1.1877 -    struct stat statBuf;
  1.1878 -    if (lstat(context->lockPath,&statBuf) == 0)
  1.1879 -      /* file exists, someone else has the lock */
  1.1880 -      return 1;
  1.1881 -    else
  1.1882 -      /* file does not exist, we could have it if we want it */
  1.1883 -      return 0;
  1.1884 -  }
  1.1885 -}
  1.1886 -
  1.1887 -static int dotlockUnixLock(sqlite3_file *id, int locktype) {
  1.1888 -  unixFile *pFile = (unixFile*)id;
  1.1889 -  dotlockLockingContext *context = 
  1.1890 -    (dotlockLockingContext *) pFile->lockingContext;
  1.1891 -  
  1.1892 -  /* if we already have a lock, it is exclusive.  
  1.1893 -  ** Just adjust level and punt on outta here. */
  1.1894 -  if (pFile->locktype > NO_LOCK) {
  1.1895 -    pFile->locktype = locktype;
  1.1896 -    
  1.1897 -    /* Always update the timestamp on the old file */
  1.1898 -    utimes(context->lockPath,NULL);
  1.1899 -    return SQLITE_OK;
  1.1900 -  }
  1.1901 -  
  1.1902 -  /* check to see if lock file already exists */
  1.1903 -  struct stat statBuf;
  1.1904 -  if (lstat(context->lockPath,&statBuf) == 0){
  1.1905 -    return SQLITE_BUSY; /* it does, busy */
  1.1906 -  }
  1.1907 -  
  1.1908 -  /* grab an exclusive lock */
  1.1909 -  int fd = open(context->lockPath,O_RDONLY|O_CREAT|O_EXCL,0600);
  1.1910 -  if (fd < 0) {
  1.1911 -    /* failed to open/create the file, someone else may have stolen the lock */
  1.1912 -    return SQLITE_BUSY; 
  1.1913 -  }
  1.1914 -  close(fd);
  1.1915 -  
  1.1916 -  /* got it, set the type and return ok */
  1.1917 -  pFile->locktype = locktype;
  1.1918 -  return SQLITE_OK;
  1.1919 -}
  1.1920 -
  1.1921 -static int dotlockUnixUnlock(sqlite3_file *id, int locktype) {
  1.1922 -  unixFile *pFile = (unixFile*)id;
  1.1923 -  dotlockLockingContext *context = 
  1.1924 -    (dotlockLockingContext *) pFile->lockingContext;
  1.1925 -  
  1.1926 -  assert( locktype<=SHARED_LOCK );
  1.1927 -  
  1.1928 -  /* no-op if possible */
  1.1929 -  if( pFile->locktype==locktype ){
  1.1930 -    return SQLITE_OK;
  1.1931 -  }
  1.1932 -  
  1.1933 -  /* shared can just be set because we always have an exclusive */
  1.1934 -  if (locktype==SHARED_LOCK) {
  1.1935 -    pFile->locktype = locktype;
  1.1936 -    return SQLITE_OK;
  1.1937 -  }
  1.1938 -  
  1.1939 -  /* no, really, unlock. */
  1.1940 -  unlink(context->lockPath);
  1.1941 -  pFile->locktype = NO_LOCK;
  1.1942 -  return SQLITE_OK;
  1.1943 -}
  1.1944 -
  1.1945 -/*
  1.1946 - ** Close a file.
  1.1947 - */
  1.1948 -static int dotlockUnixClose(sqlite3_file *id) {
  1.1949 -  unixFile *pFile = (unixFile*)id;
  1.1950 -  
  1.1951 -  if( !pFile ) return SQLITE_OK;
  1.1952 -  dotlockUnixUnlock(*pId, NO_LOCK);
  1.1953 -  /* free the dotlock locking structure */
  1.1954 -  if (pFile->lockingContext != NULL) {
  1.1955 -    if (((dotlockLockingContext *)pFile->lockingContext)->lockPath != NULL)
  1.1956 -      sqlite3_free( ( (dotlockLockingContext *)
  1.1957 -        pFile->lockingContext)->lockPath);
  1.1958 -    sqlite3_free(pFile->lockingContext);
  1.1959 -  }
  1.1960 -  
  1.1961 -  if( pFile->dirfd>=0 ) close(pFile->dirfd);
  1.1962 -  pFile->dirfd = -1;
  1.1963 -  enterMutex();
  1.1964 -  
  1.1965 -  close(pFile->h);
  1.1966 -  
  1.1967 -  leaveMutex();
  1.1968 -  OSTRACE2("CLOSE   %-3d\n", pFile->h);
  1.1969 -  OpenCounter(-1);
  1.1970 -  return SQLITE_OK;
  1.1971 -}
  1.1972 -
  1.1973 -
  1.1974 -#pragma mark No locking
  1.1975 -
  1.1976 -/*
  1.1977 - ** The nolockLockingContext is void
  1.1978 - */
  1.1979 -typedef void nolockLockingContext;
  1.1980 -
  1.1981 -static int nolockUnixCheckReservedLock(sqlite3_file *id) {
  1.1982 -  return 0;
  1.1983 -}
  1.1984 -
  1.1985 -static int nolockUnixLock(sqlite3_file *id, int locktype) {
  1.1986 -  return SQLITE_OK;
  1.1987 -}
  1.1988 -
  1.1989 -static int nolockUnixUnlock(sqlite3_file *id, int locktype) {
  1.1990 -  return SQLITE_OK;
  1.1991 -}
  1.1992 -
  1.1993 -/*
  1.1994 - ** Close a file.
  1.1995 - */
  1.1996 -static int nolockUnixClose(sqlite3_file *id) {
  1.1997 -  unixFile *pFile = (unixFile*)id;
  1.1998 -  
  1.1999 -  if( !pFile ) return SQLITE_OK;
  1.2000 -  if( pFile->dirfd>=0 ) close(pFile->dirfd);
  1.2001 -  pFile->dirfd = -1;
  1.2002 -  enterMutex();
  1.2003 -  
  1.2004 -  close(pFile->h);
  1.2005 -  
  1.2006 -  leaveMutex();
  1.2007 -  OSTRACE2("CLOSE   %-3d\n", pFile->h);
  1.2008 -  OpenCounter(-1);
  1.2009 -  return SQLITE_OK;
  1.2010 -}
  1.2011 -
  1.2012 -#endif /* SQLITE_ENABLE_LOCKING_STYLE */
  1.2013 -
  1.2014 -
  1.2015 -/*
  1.2016 -** Information and control of an open file handle.
  1.2017 -*/
  1.2018 -static int unixFileControl(sqlite3_file *id, int op, void *pArg){
  1.2019 -  switch( op ){
  1.2020 -    case SQLITE_FCNTL_LOCKSTATE: {
  1.2021 -      *(int*)pArg = ((unixFile*)id)->locktype;
  1.2022 -      return SQLITE_OK;
  1.2023 -    }
  1.2024 -  }
  1.2025 -  return SQLITE_ERROR;
  1.2026 -}
  1.2027 -
  1.2028 -/*
  1.2029 -** Return the sector size in bytes of the underlying block device for
  1.2030 -** the specified file. This is almost always 512 bytes, but may be
  1.2031 -** larger for some devices.
  1.2032 -**
  1.2033 -** SQLite code assumes this function cannot fail. It also assumes that
  1.2034 -** if two files are created in the same file-system directory (i.e.
  1.2035 -** a database and it's journal file) that the sector size will be the
  1.2036 -** same for both.
  1.2037 -*/
  1.2038 -static int unixSectorSize(sqlite3_file *id){
  1.2039 -  return SQLITE_DEFAULT_SECTOR_SIZE;
  1.2040 -}
  1.2041 -
  1.2042 -/*
  1.2043 -** Return the device characteristics for the file. This is always 0.
  1.2044 -*/
  1.2045 -static int unixDeviceCharacteristics(sqlite3_file *id){
  1.2046 -  return 0;
  1.2047 -}
  1.2048 -
  1.2049 -/*
  1.2050 -** This vector defines all the methods that can operate on an sqlite3_file
  1.2051 -** for unix.
  1.2052 -*/
  1.2053 -static const sqlite3_io_methods sqlite3UnixIoMethod = {
  1.2054 -  1,                        /* iVersion */
  1.2055 -  unixClose,
  1.2056 -  unixRead,
  1.2057 -  unixWrite,
  1.2058 -  unixTruncate,
  1.2059 -  unixSync,
  1.2060 -  unixFileSize,
  1.2061 -  unixLock,
  1.2062 -  unixUnlock,
  1.2063 -  unixCheckReservedLock,
  1.2064 -  unixFileControl,
  1.2065 -  unixSectorSize,
  1.2066 -  unixDeviceCharacteristics
  1.2067 -};
  1.2068 -
  1.2069 -#ifdef SQLITE_ENABLE_LOCKING_STYLE
  1.2070 -/*
  1.2071 -** This vector defines all the methods that can operate on an sqlite3_file
  1.2072 -** for unix with AFP style file locking.
  1.2073 -*/
  1.2074 -static const sqlite3_io_methods sqlite3AFPLockingUnixIoMethod = {
  1.2075 -  1,                        /* iVersion */
  1.2076 -  unixClose,
  1.2077 -  unixRead,
  1.2078 -  unixWrite,
  1.2079 -  unixTruncate,
  1.2080 -  unixSync,
  1.2081 -  unixFileSize,
  1.2082 -  afpUnixLock,
  1.2083 -  afpUnixUnlock,
  1.2084 -  afpUnixCheckReservedLock,
  1.2085 -  unixFileControl,
  1.2086 -  unixSectorSize,
  1.2087 -  unixDeviceCharacteristics
  1.2088 -};
  1.2089 -
  1.2090 -/*
  1.2091 -** This vector defines all the methods that can operate on an sqlite3_file
  1.2092 -** for unix with flock() style file locking.
  1.2093 -*/
  1.2094 -static const sqlite3_io_methods sqlite3FlockLockingUnixIoMethod = {
  1.2095 -  1,                        /* iVersion */
  1.2096 -  flockUnixClose,
  1.2097 -  unixRead,
  1.2098 -  unixWrite,
  1.2099 -  unixTruncate,
  1.2100 -  unixSync,
  1.2101 -  unixFileSize,
  1.2102 -  flockUnixLock,
  1.2103 -  flockUnixUnlock,
  1.2104 -  flockUnixCheckReservedLock,
  1.2105 -  unixFileControl,
  1.2106 -  unixSectorSize,
  1.2107 -  unixDeviceCharacteristics
  1.2108 -};
  1.2109 -
  1.2110 -/*
  1.2111 -** This vector defines all the methods that can operate on an sqlite3_file
  1.2112 -** for unix with dotlock style file locking.
  1.2113 -*/
  1.2114 -static const sqlite3_io_methods sqlite3DotlockLockingUnixIoMethod = {
  1.2115 -  1,                        /* iVersion */
  1.2116 -  dotlockUnixClose,
  1.2117 -  unixRead,
  1.2118 -  unixWrite,
  1.2119 -  unixTruncate,
  1.2120 -  unixSync,
  1.2121 -  unixFileSize,
  1.2122 -  dotlockUnixLock,
  1.2123 -  dotlockUnixUnlock,
  1.2124 -  dotlockUnixCheckReservedLock,
  1.2125 -  unixFileControl,
  1.2126 -  unixSectorSize,
  1.2127 -  unixDeviceCharacteristics
  1.2128 -};
  1.2129 -
  1.2130 -/*
  1.2131 -** This vector defines all the methods that can operate on an sqlite3_file
  1.2132 -** for unix with dotlock style file locking.
  1.2133 -*/
  1.2134 -static const sqlite3_io_methods sqlite3NolockLockingUnixIoMethod = {
  1.2135 -  1,                        /* iVersion */
  1.2136 -  nolockUnixClose,
  1.2137 -  unixRead,
  1.2138 -  unixWrite,
  1.2139 -  unixTruncate,
  1.2140 -  unixSync,
  1.2141 -  unixFileSize,
  1.2142 -  nolockUnixLock,
  1.2143 -  nolockUnixUnlock,
  1.2144 -  nolockUnixCheckReservedLock,
  1.2145 -  unixFileControl,
  1.2146 -  unixSectorSize,
  1.2147 -  unixDeviceCharacteristics
  1.2148 -};
  1.2149 -
  1.2150 -#endif /* SQLITE_ENABLE_LOCKING_STYLE */
  1.2151 -
  1.2152 -/*
  1.2153 -** Allocate memory for a new unixFile and initialize that unixFile.
  1.2154 -** Write a pointer to the new unixFile into *pId.
  1.2155 -** If we run out of memory, close the file and return an error.
  1.2156 -*/
  1.2157 -#ifdef SQLITE_ENABLE_LOCKING_STYLE
  1.2158 -/* 
  1.2159 -** When locking extensions are enabled, the filepath and locking style 
  1.2160 -** are needed to determine the unixFile pMethod to use for locking operations.
  1.2161 -** The locking-style specific lockingContext data structure is created 
  1.2162 -** and assigned here also.
  1.2163 -*/
  1.2164 -static int fillInUnixFile(
  1.2165 -  int h,                  /* Open file descriptor of file being opened */
  1.2166 -  int dirfd,              /* Directory file descriptor */
  1.2167 -  sqlite3_file *pId,      /* Write completed initialization here */
  1.2168 -  const char *zFilename,  /* Name of the file being opened */
  1.2169 -){
  1.2170 -  sqlite3LockingStyle lockingStyle;
  1.2171 -  unixFile *pNew = (unixFile *)pId;
  1.2172 -  int rc;
  1.2173 -
  1.2174 -  memset(pNew, 0, sizeof(unixFile));
  1.2175 -  lockingStyle = sqlite3DetectLockingStyle(zFilename, h);
  1.2176 -  if ( lockingStyle == posixLockingStyle ) {
  1.2177 -    enterMutex();
  1.2178 -    rc = findLockInfo(h, &pNew->pLock, &pNew->pOpen);
  1.2179 -    leaveMutex();
  1.2180 -    if( rc ){
  1.2181 -      close(h);
  1.2182 -      unlink(zFilename);
  1.2183 -      return SQLITE_NOMEM;
  1.2184 -    }
  1.2185 -  } else {
  1.2186 -    /*  pLock and pOpen are only used for posix advisory locking */
  1.2187 -    pNew->pLock = NULL;
  1.2188 -    pNew->pOpen = NULL;
  1.2189 -  }
  1.2190 -  pNew->dirfd = -1;
  1.2191 -  pNew->h = h;
  1.2192 -  SET_THREADID(pNew);
  1.2193 -  pNew = sqlite3_malloc( sizeof(unixFile) );
  1.2194 -  if( pNew==0 ){
  1.2195 -    close(h);
  1.2196 -    enterMutex();
  1.2197 -    releaseLockInfo(pNew->pLock);
  1.2198 -    releaseOpenCnt(pNew->pOpen);
  1.2199 -    leaveMutex();
  1.2200 -    return SQLITE_NOMEM;
  1.2201 -  }else{
  1.2202 -    switch(lockingStyle) {
  1.2203 -      case afpLockingStyle: {
  1.2204 -        /* afp locking uses the file path so it needs to be included in
  1.2205 -        ** the afpLockingContext */
  1.2206 -        int nFilename;
  1.2207 -        pNew->pMethod = &sqlite3AFPLockingUnixIoMethod;
  1.2208 -        pNew->lockingContext = 
  1.2209 -          sqlite3_malloc(sizeof(afpLockingContext));
  1.2210 -        nFilename = strlen(zFilename)+1;
  1.2211 -        ((afpLockingContext *)pNew->lockingContext)->filePath = 
  1.2212 -          sqlite3_malloc(nFilename);
  1.2213 -        memcpy(((afpLockingContext *)pNew->lockingContext)->filePath, 
  1.2214 -               zFilename, nFilename);
  1.2215 -        srandomdev();
  1.2216 -        break;
  1.2217 -      }
  1.2218 -      case flockLockingStyle:
  1.2219 -        /* flock locking doesn't need additional lockingContext information */
  1.2220 -        pNew->pMethod = &sqlite3FlockLockingUnixIoMethod;
  1.2221 -        break;
  1.2222 -      case dotlockLockingStyle: {
  1.2223 -        /* dotlock locking uses the file path so it needs to be included in
  1.2224 -         ** the dotlockLockingContext */
  1.2225 -        int nFilename;
  1.2226 -        pNew->pMethod = &sqlite3DotlockLockingUnixIoMethod;
  1.2227 -        pNew->lockingContext = sqlite3_malloc(
  1.2228 -          sizeof(dotlockLockingContext));
  1.2229 -        nFilename = strlen(zFilename) + 6;
  1.2230 -        ((dotlockLockingContext *)pNew->lockingContext)->lockPath = 
  1.2231 -            sqlite3_malloc( nFilename );
  1.2232 -        sqlite3_snprintf(nFilename, 
  1.2233 -                ((dotlockLockingContext *)pNew->lockingContext)->lockPath, 
  1.2234 -                "%s.lock", zFilename);
  1.2235 -        break;
  1.2236 -      }
  1.2237 -      case posixLockingStyle:
  1.2238 -        /* posix locking doesn't need additional lockingContext information */
  1.2239 -        pNew->pMethod = &sqlite3UnixIoMethod;
  1.2240 -        break;
  1.2241 -      case noLockingStyle:
  1.2242 -      case unsupportedLockingStyle:
  1.2243 -      default: 
  1.2244 -        pNew->pMethod = &sqlite3NolockLockingUnixIoMethod;
  1.2245 -    }
  1.2246 -    OpenCounter(+1);
  1.2247 -    return SQLITE_OK;
  1.2248 -  }
  1.2249 -}
  1.2250 -#else /* SQLITE_ENABLE_LOCKING_STYLE */
  1.2251 -static int fillInUnixFile(
  1.2252 -  int h,                 /* Open file descriptor on file being opened */
  1.2253 -  int dirfd,
  1.2254 -  sqlite3_file *pId,     /* Write to the unixFile structure here */
  1.2255 -  const char *zFilename  /* Name of the file being opened */
  1.2256 -){
  1.2257 -  unixFile *pNew = (unixFile *)pId;
  1.2258 -  int rc;
  1.2259 -
  1.2260 -#ifdef FD_CLOEXEC
  1.2261 -  fcntl(h, F_SETFD, fcntl(h, F_GETFD, 0) | FD_CLOEXEC);
  1.2262 -#endif
  1.2263 -
  1.2264 -  enterMutex();
  1.2265 -  rc = findLockInfo(h, &pNew->pLock, &pNew->pOpen);
  1.2266 -  leaveMutex();
  1.2267 -  if( rc ){
  1.2268 -    close(h);
  1.2269 -    return SQLITE_NOMEM;
  1.2270 -  }
  1.2271 -
  1.2272 -  OSTRACE3("OPEN    %-3d %s\n", h, zFilename);
  1.2273 -  pNew->dirfd = -1;
  1.2274 -  pNew->h = h;
  1.2275 -  pNew->dirfd = dirfd;
  1.2276 -  SET_THREADID(pNew);
  1.2277 -
  1.2278 -  pNew->pMethod = &sqlite3UnixIoMethod;
  1.2279 -  OpenCounter(+1);
  1.2280 -  return SQLITE_OK;
  1.2281 -}
  1.2282 -#endif /* SQLITE_ENABLE_LOCKING_STYLE */
  1.2283 -
  1.2284 -/*
  1.2285 -** Open a file descriptor to the directory containing file zFilename.
  1.2286 -** If successful, *pFd is set to the opened file descriptor and
  1.2287 -** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
  1.2288 -** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
  1.2289 -** value.
  1.2290 -**
  1.2291 -** If SQLITE_OK is returned, the caller is responsible for closing
  1.2292 -** the file descriptor *pFd using close().
  1.2293 -*/
  1.2294 -static int openDirectory(const char *zFilename, int *pFd){
  1.2295 -  int ii;
  1.2296 -  int fd = -1;
  1.2297 -  char zDirname[MAX_PATHNAME+1];
  1.2298 -
  1.2299 -  sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
  1.2300 -  for(ii=strlen(zDirname); ii>=0 && zDirname[ii]!='/'; ii--);
  1.2301 -  if( ii>0 ){
  1.2302 -    zDirname[ii] = '\0';
  1.2303 -    fd = open(zDirname, O_RDONLY|O_BINARY, 0);
  1.2304 -    if( fd>=0 ){
  1.2305 -#ifdef FD_CLOEXEC
  1.2306 -      fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
  1.2307 -#endif
  1.2308 -      OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
  1.2309 -    }
  1.2310 -  }
  1.2311 -  *pFd = fd;
  1.2312 -  return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN);
  1.2313 -}
  1.2314 -
  1.2315 -/*
  1.2316 -** Open the file zPath.
  1.2317 -** 
  1.2318 -** Previously, the SQLite OS layer used three functions in place of this
  1.2319 -** one:
  1.2320 -**
  1.2321 -**     sqlite3OsOpenReadWrite();
  1.2322 -**     sqlite3OsOpenReadOnly();
  1.2323 -**     sqlite3OsOpenExclusive();
  1.2324 -**
  1.2325 -** These calls correspond to the following combinations of flags:
  1.2326 -**
  1.2327 -**     ReadWrite() ->     (READWRITE | CREATE)
  1.2328 -**     ReadOnly()  ->     (READONLY) 
  1.2329 -**     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
  1.2330 -**
  1.2331 -** The old OpenExclusive() accepted a boolean argument - "delFlag". If
  1.2332 -** true, the file was configured to be automatically deleted when the
  1.2333 -** file handle closed. To achieve the same effect using this new 
  1.2334 -** interface, add the DELETEONCLOSE flag to those specified above for 
  1.2335 -** OpenExclusive().
  1.2336 -*/
  1.2337 -static int unixOpen(
  1.2338 -  sqlite3_vfs *pVfs, 
  1.2339 -  const char *zPath, 
  1.2340 -  sqlite3_file *pFile,
  1.2341 -  int flags,
  1.2342 -  int *pOutFlags
  1.2343 -){
  1.2344 -  int fd = 0;                    /* File descriptor returned by open() */
  1.2345 -  int dirfd = -1;                /* Directory file descriptor */
  1.2346 -  int oflags = 0;                /* Flags to pass to open() */
  1.2347 -  int eType = flags&0xFFFFFF00;  /* Type of file to open */
  1.2348 -
  1.2349 -  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
  1.2350 -  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
  1.2351 -  int isCreate     = (flags & SQLITE_OPEN_CREATE);
  1.2352 -  int isReadonly   = (flags & SQLITE_OPEN_READONLY);
  1.2353 -  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
  1.2354 -
  1.2355 -  /* If creating a master or main-file journal, this function will open
  1.2356 -  ** a file-descriptor on the directory too. The first time unixSync()
  1.2357 -  ** is called the directory file descriptor will be fsync()ed and close()d.
  1.2358 -  */
  1.2359 -  int isOpenDirectory = (isCreate && 
  1.2360 -      (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
  1.2361 -  );
  1.2362 -
  1.2363 -  /* Check the following statements are true: 
  1.2364 -  **
  1.2365 -  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
  1.2366 -  **   (b) if CREATE is set, then READWRITE must also be set, and
  1.2367 -  **   (c) if EXCLUSIVE is set, then CREATE must also be set.
  1.2368 -  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
  1.2369 -  */
  1.2370 -  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  1.2371 -  assert(isCreate==0 || isReadWrite);
  1.2372 -  assert(isExclusive==0 || isCreate);
  1.2373 -  assert(isDelete==0 || isCreate);
  1.2374 -
  1.2375 -
  1.2376 -  /* The main DB, main journal, and master journal are never automatically
  1.2377 -  ** deleted
  1.2378 -  */
  1.2379 -  assert( eType!=SQLITE_OPEN_MAIN_DB || !isDelete );
  1.2380 -  assert( eType!=SQLITE_OPEN_MAIN_JOURNAL || !isDelete );
  1.2381 -  assert( eType!=SQLITE_OPEN_MASTER_JOURNAL || !isDelete );
  1.2382 -
  1.2383 -  /* Assert that the upper layer has set one of the "file-type" flags. */
  1.2384 -  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
  1.2385 -       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
  1.2386 -       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
  1.2387 -       || eType==SQLITE_OPEN_TRANSIENT_DB
  1.2388 -  );
  1.2389 -
  1.2390 -  if( isReadonly )  oflags |= O_RDONLY;
  1.2391 -  if( isReadWrite ) oflags |= O_RDWR;
  1.2392 -  if( isCreate )    oflags |= O_CREAT;
  1.2393 -  if( isExclusive ) oflags |= (O_EXCL|O_NOFOLLOW);
  1.2394 -  oflags |= (O_LARGEFILE|O_BINARY);
  1.2395 -
  1.2396 -  memset(pFile, 0, sizeof(unixFile));
  1.2397 -  fd = open(zPath, oflags, isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
  1.2398 -  if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
  1.2399 -    /* Failed to open the file for read/write access. Try read-only. */
  1.2400 -    flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
  1.2401 -    flags |= SQLITE_OPEN_READONLY;
  1.2402 -    return unixOpen(pVfs, zPath, pFile, flags, pOutFlags);
  1.2403 -  }
  1.2404 -  if( fd<0 ){
  1.2405 -    return SQLITE_CANTOPEN;
  1.2406 -  }
  1.2407 -  if( isDelete ){
  1.2408 -    unlink(zPath);
  1.2409 -  }
  1.2410 -  if( pOutFlags ){
  1.2411 -    *pOutFlags = flags;
  1.2412 -  }
  1.2413 -
  1.2414 -  assert(fd!=0);
  1.2415 -  if( isOpenDirectory ){
  1.2416 -    int rc = openDirectory(zPath, &dirfd);
  1.2417 -    if( rc!=SQLITE_OK ){
  1.2418 -      close(fd);
  1.2419 -      return rc;
  1.2420 -    }
  1.2421 -  }
  1.2422 -  return fillInUnixFile(fd, dirfd, pFile, zPath);
  1.2423 -}
  1.2424 -
  1.2425 -/*
  1.2426 -** Delete the file at zPath. If the dirSync argument is true, fsync()
  1.2427 -** the directory after deleting the file.
  1.2428 -*/
  1.2429 -static int unixDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  1.2430 -  int rc = SQLITE_OK;
  1.2431 -  SimulateIOError(return SQLITE_IOERR_DELETE);
  1.2432 -  unlink(zPath);
  1.2433 -  if( dirSync ){
  1.2434 -    int fd;
  1.2435 -    rc = openDirectory(zPath, &fd);
  1.2436 -    if( rc==SQLITE_OK ){
  1.2437 -      if( fsync(fd) ){
  1.2438 -        rc = SQLITE_IOERR_DIR_FSYNC;
  1.2439 -      }
  1.2440 -      close(fd);
  1.2441 -    }
  1.2442 -  }
  1.2443 -  return rc;
  1.2444 -}
  1.2445 -
  1.2446 -/*
  1.2447 -** Test the existance of or access permissions of file zPath. The
  1.2448 -** test performed depends on the value of flags:
  1.2449 -**
  1.2450 -**     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
  1.2451 -**     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
  1.2452 -**     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
  1.2453 -**
  1.2454 -** Otherwise return 0.
  1.2455 -*/
  1.2456 -static int unixAccess(sqlite3_vfs *pVfs, const char *zPath, int flags){
  1.2457 -  int amode = 0;
  1.2458 -  switch( flags ){
  1.2459 -    case SQLITE_ACCESS_EXISTS:
  1.2460 -      amode = F_OK;
  1.2461 -      break;
  1.2462 -    case SQLITE_ACCESS_READWRITE:
  1.2463 -      amode = W_OK|R_OK;
  1.2464 -      break;
  1.2465 -    case SQLITE_ACCESS_READ:
  1.2466 -      amode = R_OK;
  1.2467 -      break;
  1.2468 -
  1.2469 -    default:
  1.2470 -      assert(!"Invalid flags argument");
  1.2471 -  }
  1.2472 -  return (access(zPath, amode)==0);
  1.2473 -}
  1.2474 -
  1.2475 -/*
  1.2476 -** Create a temporary file name in zBuf.  zBuf must be allocated
  1.2477 -** by the calling process and must be big enough to hold at least
  1.2478 -** pVfs->mxPathname bytes.
  1.2479 -*/
  1.2480 -static int unixGetTempname(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  1.2481 -  static const char *azDirs[] = {
  1.2482 -     0,
  1.2483 -     "/var/tmp",
  1.2484 -     "/usr/tmp",
  1.2485 -     "/tmp",
  1.2486 -     ".",
  1.2487 -  };
  1.2488 -  static const unsigned char zChars[] =
  1.2489 -    "abcdefghijklmnopqrstuvwxyz"
  1.2490 -    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  1.2491 -    "0123456789";
  1.2492 -  int i, j;
  1.2493 -  struct stat buf;
  1.2494 -  const char *zDir = ".";
  1.2495 -
  1.2496 -  /* It's odd to simulate an io-error here, but really this is just
  1.2497 -  ** using the io-error infrastructure to test that SQLite handles this
  1.2498 -  ** function failing. 
  1.2499 -  */
  1.2500 -  SimulateIOError( return SQLITE_ERROR );
  1.2501 -
  1.2502 -  azDirs[0] = sqlite3_temp_directory;
  1.2503 -  for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
  1.2504 -    if( azDirs[i]==0 ) continue;
  1.2505 -    if( stat(azDirs[i], &buf) ) continue;
  1.2506 -    if( !S_ISDIR(buf.st_mode) ) continue;
  1.2507 -    if( access(azDirs[i], 07) ) continue;
  1.2508 -    zDir = azDirs[i];
  1.2509 -    break;
  1.2510 -  }
  1.2511 -  do{
  1.2512 -    assert( pVfs->mxPathname==MAX_PATHNAME );
  1.2513 -    assert( nBuf>=MAX_PATHNAME );
  1.2514 -    sqlite3_snprintf(MAX_PATHNAME-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
  1.2515 -    j = strlen(zBuf);
  1.2516 -    sqlite3Randomness(15, &zBuf[j]);
  1.2517 -    for(i=0; i<15; i++, j++){
  1.2518 -      zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  1.2519 -    }
  1.2520 -    zBuf[j] = 0;
  1.2521 -  }while( access(zBuf,0)==0 );
  1.2522 -  return SQLITE_OK;
  1.2523 -}
  1.2524 -
  1.2525 -
  1.2526 -/*
  1.2527 -** Turn a relative pathname into a full pathname. The relative path
  1.2528 -** is stored as a nul-terminated string in the buffer pointed to by
  1.2529 -** zPath. 
  1.2530 -**
  1.2531 -** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes 
  1.2532 -** (in this case, MAX_PATHNAME bytes). The full-path is written to
  1.2533 -** this buffer before returning.
  1.2534 -*/
  1.2535 -static int unixFullPathname(
  1.2536 -  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
  1.2537 -  const char *zPath,            /* Possibly relative input path */
  1.2538 -  int nOut,                     /* Size of output buffer in bytes */
  1.2539 -  char *zOut                    /* Output buffer */
  1.2540 -){
  1.2541 -
  1.2542 -  /* It's odd to simulate an io-error here, but really this is just
  1.2543 -  ** using the io-error infrastructure to test that SQLite handles this
  1.2544 -  ** function failing. This function could fail if, for example, the
  1.2545 -  ** current working directly has been unlinked.
  1.2546 -  */
  1.2547 -  SimulateIOError( return SQLITE_ERROR );
  1.2548 -
  1.2549 -  assert( pVfs->mxPathname==MAX_PATHNAME );
  1.2550 -  zOut[MAX_PATHNAME-1] = '\0';
  1.2551 -  if( zPath[0]=='/' ){
  1.2552 -    sqlite3_snprintf(MAX_PATHNAME, zOut, "%s", zPath);
  1.2553 -  }else{
  1.2554 -    int nCwd;
  1.2555 -    if( getcwd(zOut, MAX_PATHNAME-1)==0 ){
  1.2556 -      return SQLITE_CANTOPEN;
  1.2557 -    }
  1.2558 -    nCwd = strlen(zOut);
  1.2559 -    sqlite3_snprintf(MAX_PATHNAME-nCwd, &zOut[nCwd], "/%s", zPath);
  1.2560 -  }
  1.2561 -  return SQLITE_OK;
  1.2562 -
  1.2563 -#if 0
  1.2564 -  /*
  1.2565 -  ** Remove "/./" path elements and convert "/A/./" path elements
  1.2566 -  ** to just "/".
  1.2567 -  */
  1.2568 -  if( zFull ){
  1.2569 -    int i, j;
  1.2570 -    for(i=j=0; zFull[i]; i++){
  1.2571 -      if( zFull[i]=='/' ){
  1.2572 -        if( zFull[i+1]=='/' ) continue;
  1.2573 -        if( zFull[i+1]=='.' && zFull[i+2]=='/' ){
  1.2574 -          i += 1;
  1.2575 -          continue;
  1.2576 -        }
  1.2577 -        if( zFull[i+1]=='.' && zFull[i+2]=='.' && zFull[i+3]=='/' ){
  1.2578 -          while( j>0 && zFull[j-1]!='/' ){ j--; }
  1.2579 -          i += 3;
  1.2580 -          continue;
  1.2581 -        }
  1.2582 -      }
  1.2583 -      zFull[j++] = zFull[i];
  1.2584 -    }
  1.2585 -    zFull[j] = 0;
  1.2586 -  }
  1.2587 -#endif
  1.2588 -}
  1.2589 -
  1.2590 -
  1.2591 -#ifndef SQLITE_OMIT_LOAD_EXTENSION
  1.2592 -/*
  1.2593 -** Interfaces for opening a shared library, finding entry points
  1.2594 -** within the shared library, and closing the shared library.
  1.2595 -*/
  1.2596 -#include <dlfcn.h>
  1.2597 -static void *unixDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
  1.2598 -  return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
  1.2599 -}
  1.2600 -
  1.2601 -/*
  1.2602 -** SQLite calls this function immediately after a call to unixDlSym() or
  1.2603 -** unixDlOpen() fails (returns a null pointer). If a more detailed error
  1.2604 -** message is available, it is written to zBufOut. If no error message
  1.2605 -** is available, zBufOut is left unmodified and SQLite uses a default
  1.2606 -** error message.
  1.2607 -*/
  1.2608 -static void unixDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
  1.2609 -  char *zErr;
  1.2610 -  enterMutex();
  1.2611 -  zErr = dlerror();
  1.2612 -  if( zErr ){
  1.2613 -    sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
  1.2614 -  }
  1.2615 -  leaveMutex();
  1.2616 -}
  1.2617 -static void *unixDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
  1.2618 -  return dlsym(pHandle, zSymbol);
  1.2619 -}
  1.2620 -static void unixDlClose(sqlite3_vfs *pVfs, void *pHandle){
  1.2621 -  dlclose(pHandle);
  1.2622 -}
  1.2623 -#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  1.2624 -  #define unixDlOpen  0
  1.2625 -  #define unixDlError 0
  1.2626 -  #define unixDlSym   0
  1.2627 -  #define unixDlClose 0
  1.2628 -#endif
  1.2629 -
  1.2630 -/*
  1.2631 -** Write nBuf bytes of random data to the supplied buffer zBuf.
  1.2632 -*/
  1.2633 -static int unixRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  1.2634 -
  1.2635 -  assert(nBuf>=(sizeof(time_t)+sizeof(int)));
  1.2636 -
  1.2637 -  /* We have to initialize zBuf to prevent valgrind from reporting
  1.2638 -  ** errors.  The reports issued by valgrind are incorrect - we would
  1.2639 -  ** prefer that the randomness be increased by making use of the
  1.2640 -  ** uninitialized space in zBuf - but valgrind errors tend to worry
  1.2641 -  ** some users.  Rather than argue, it seems easier just to initialize
  1.2642 -  ** the whole array and silence valgrind, even if that means less randomness
  1.2643 -  ** in the random seed.
  1.2644 -  **
  1.2645 -  ** When testing, initializing zBuf[] to zero is all we do.  That means
  1.2646 -  ** that we always use the same random number sequence.  This makes the
  1.2647 -  ** tests repeatable.
  1.2648 -  */
  1.2649 -  memset(zBuf, 0, nBuf);
  1.2650 -#if !defined(SQLITE_TEST)
  1.2651 -  {
  1.2652 -    int pid, fd;
  1.2653 -    fd = open("/dev/urandom", O_RDONLY);
  1.2654 -    if( fd<0 ){
  1.2655 -      time_t t;
  1.2656 -      time(&t);
  1.2657 -      memcpy(zBuf, &t, sizeof(t));
  1.2658 -      pid = getpid();
  1.2659 -      memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
  1.2660 -    }else{
  1.2661 -      read(fd, zBuf, nBuf);
  1.2662 -      close(fd);
  1.2663 -    }
  1.2664 -  }
  1.2665 -#endif
  1.2666 -  return SQLITE_OK;
  1.2667 -}
  1.2668 -
  1.2669 -
  1.2670 -/*
  1.2671 -** Sleep for a little while.  Return the amount of time slept.
  1.2672 -** The argument is the number of microseconds we want to sleep.
  1.2673 -** The return value is the number of microseconds of sleep actually
  1.2674 -** requested from the underlying operating system, a number which
  1.2675 -** might be greater than or equal to the argument, but not less
  1.2676 -** than the argument.
  1.2677 -*/
  1.2678 -static int unixSleep(sqlite3_vfs *pVfs, int microseconds){
  1.2679 -#if defined(HAVE_USLEEP) && HAVE_USLEEP
  1.2680 -  usleep(microseconds);
  1.2681 -  return microseconds;
  1.2682 -#else
  1.2683 -  int seconds = (microseconds+999999)/1000000;
  1.2684 -  sleep(seconds);
  1.2685 -  return seconds*1000000;
  1.2686 -#endif
  1.2687 -}
  1.2688 -
  1.2689 -/*
  1.2690 -** The following variable, if set to a non-zero value, becomes the result
  1.2691 -** returned from sqlite3OsCurrentTime().  This is used for testing.
  1.2692 -*/
  1.2693 -#ifdef SQLITE_TEST
  1.2694 -int sqlite3_current_time = 0;
  1.2695 -#endif
  1.2696 -
  1.2697 -/*
  1.2698 -** Find the current time (in Universal Coordinated Time).  Write the
  1.2699 -** current time and date as a Julian Day number into *prNow and
  1.2700 -** return 0.  Return 1 if the time and date cannot be found.
  1.2701 -*/
  1.2702 -static int unixCurrentTime(sqlite3_vfs *pVfs, double *prNow){
  1.2703 -#ifdef NO_GETTOD
  1.2704 -  time_t t;
  1.2705 -  time(&t);
  1.2706 -  *prNow = t/86400.0 + 2440587.5;
  1.2707 -#else
  1.2708 -  struct timeval sNow;
  1.2709 -  gettimeofday(&sNow, 0);
  1.2710 -  *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
  1.2711 -#endif
  1.2712 -#ifdef SQLITE_TEST
  1.2713 -  if( sqlite3_current_time ){
  1.2714 -    *prNow = sqlite3_current_time/86400.0 + 2440587.5;
  1.2715 -  }
  1.2716 -#endif
  1.2717 -  return 0;
  1.2718 -}
  1.2719 -
  1.2720 -/*
  1.2721 -** Return a pointer to the sqlite3DefaultVfs structure.   We use
  1.2722 -** a function rather than give the structure global scope because
  1.2723 -** some compilers (MSVC) do not allow forward declarations of
  1.2724 -** initialized structures.
  1.2725 -*/
  1.2726 -sqlite3_vfs *sqlite3OsDefaultVfs(void){
  1.2727 -  static sqlite3_vfs unixVfs = {
  1.2728 -    1,                  /* iVersion */
  1.2729 -    sizeof(unixFile),   /* szOsFile */
  1.2730 -    MAX_PATHNAME,       /* mxPathname */
  1.2731 -    0,                  /* pNext */
  1.2732 -    "unix",             /* zName */
  1.2733 -    0,                  /* pAppData */
  1.2734 -  
  1.2735 -    unixOpen,           /* xOpen */
  1.2736 -    unixDelete,         /* xDelete */
  1.2737 -    unixAccess,         /* xAccess */
  1.2738 -    unixGetTempname,    /* xGetTempName */
  1.2739 -    unixFullPathname,   /* xFullPathname */
  1.2740 -    unixDlOpen,         /* xDlOpen */
  1.2741 -    unixDlError,        /* xDlError */
  1.2742 -    unixDlSym,          /* xDlSym */
  1.2743 -    unixDlClose,        /* xDlClose */
  1.2744 -    unixRandomness,     /* xRandomness */
  1.2745 -    unixSleep,          /* xSleep */
  1.2746 -    unixCurrentTime     /* xCurrentTime */
  1.2747 -  };
  1.2748 -  
  1.2749 -  return &unixVfs;
  1.2750 -}
  1.2751 - 
  1.2752 -#endif /* OS_UNIX */