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