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