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