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