Snapshot of upstream SQLite 3.32.2
[sqlcipher.git] / src / os_unix.c
blobd510711087eeff13ea55dcf561f8ce5a02565e3c
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
74 /* Use pread() and pwrite() if they are available */
75 #if defined(__APPLE__)
76 # define HAVE_PREAD 1
77 # define HAVE_PWRITE 1
78 #endif
79 #if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
80 # undef USE_PREAD
81 # define USE_PREAD64 1
82 #elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)
83 # undef USE_PREAD64
84 # define USE_PREAD 1
85 #endif
88 ** standard include files.
90 #include <sys/types.h>
91 #include <sys/stat.h>
92 #include <fcntl.h>
93 #include <sys/ioctl.h>
94 #include <unistd.h>
95 #include <time.h>
96 #include <sys/time.h>
97 #include <errno.h>
98 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
99 # include <sys/mman.h>
100 #endif
102 #if SQLITE_ENABLE_LOCKING_STYLE
103 # include <sys/ioctl.h>
104 # include <sys/file.h>
105 # include <sys/param.h>
106 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
109 ** Try to determine if gethostuuid() is available based on standard
110 ** macros. This might sometimes compute the wrong value for some
111 ** obscure platforms. For those cases, simply compile with one of
112 ** the following:
114 ** -DHAVE_GETHOSTUUID=0
115 ** -DHAVE_GETHOSTUUID=1
117 ** None if this matters except when building on Apple products with
118 ** -DSQLITE_ENABLE_LOCKING_STYLE.
120 #ifndef HAVE_GETHOSTUUID
121 # define HAVE_GETHOSTUUID 0
122 # if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
123 (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
124 # if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
125 && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
126 # undef HAVE_GETHOSTUUID
127 # define HAVE_GETHOSTUUID 1
128 # else
129 # warning "gethostuuid() is disabled."
130 # endif
131 # endif
132 #endif
135 #if OS_VXWORKS
136 # include <sys/ioctl.h>
137 # include <semaphore.h>
138 # include <limits.h>
139 #endif /* OS_VXWORKS */
141 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
142 # include <sys/mount.h>
143 #endif
145 #ifdef HAVE_UTIME
146 # include <utime.h>
147 #endif
150 ** Allowed values of unixFile.fsFlags
152 #define SQLITE_FSFLAGS_IS_MSDOS 0x1
155 ** If we are to be thread-safe, include the pthreads header.
157 #if SQLITE_THREADSAFE
158 # include <pthread.h>
159 #endif
162 ** Default permissions when creating a new file
164 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
165 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
166 #endif
169 ** Default permissions when creating auto proxy dir
171 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
172 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
173 #endif
176 ** Maximum supported path-length.
178 #define MAX_PATHNAME 512
181 ** Maximum supported symbolic links
183 #define SQLITE_MAX_SYMLINKS 100
185 /* Always cast the getpid() return type for compatibility with
186 ** kernel modules in VxWorks. */
187 #define osGetpid(X) (pid_t)getpid()
190 ** Only set the lastErrno if the error code is a real error and not
191 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
193 #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
195 /* Forward references */
196 typedef struct unixShm unixShm; /* Connection shared memory */
197 typedef struct unixShmNode unixShmNode; /* Shared memory instance */
198 typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
199 typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
202 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
203 ** cannot be closed immediately. In these cases, instances of the following
204 ** structure are used to store the file descriptor while waiting for an
205 ** opportunity to either close or reuse it.
207 struct UnixUnusedFd {
208 int fd; /* File descriptor to close */
209 int flags; /* Flags this file descriptor was opened with */
210 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
214 ** The unixFile structure is subclass of sqlite3_file specific to the unix
215 ** VFS implementations.
217 typedef struct unixFile unixFile;
218 struct unixFile {
219 sqlite3_io_methods const *pMethod; /* Always the first entry */
220 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
221 unixInodeInfo *pInode; /* Info about locks on this inode */
222 int h; /* The file descriptor */
223 unsigned char eFileLock; /* The type of lock held on this fd */
224 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
225 int lastErrno; /* The unix errno from last I/O error */
226 void *lockingContext; /* Locking style specific state */
227 UnixUnusedFd *pPreallocatedUnused; /* Pre-allocated UnixUnusedFd */
228 const char *zPath; /* Name of the file */
229 unixShm *pShm; /* Shared memory segment information */
230 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
231 #if SQLITE_MAX_MMAP_SIZE>0
232 int nFetchOut; /* Number of outstanding xFetch refs */
233 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
234 sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
235 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
236 void *pMapRegion; /* Memory mapped region */
237 #endif
238 int sectorSize; /* Device sector size */
239 int deviceCharacteristics; /* Precomputed device characteristics */
240 #if SQLITE_ENABLE_LOCKING_STYLE
241 int openFlags; /* The flags specified at open() */
242 #endif
243 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
244 unsigned fsFlags; /* cached details from statfs() */
245 #endif
246 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
247 unsigned iBusyTimeout; /* Wait this many millisec on locks */
248 #endif
249 #if OS_VXWORKS
250 struct vxworksFileId *pId; /* Unique file ID */
251 #endif
252 #ifdef SQLITE_DEBUG
253 /* The next group of variables are used to track whether or not the
254 ** transaction counter in bytes 24-27 of database files are updated
255 ** whenever any part of the database changes. An assertion fault will
256 ** occur if a file is updated without also updating the transaction
257 ** counter. This test is made to avoid new problems similar to the
258 ** one described by ticket #3584.
260 unsigned char transCntrChng; /* True if the transaction counter changed */
261 unsigned char dbUpdate; /* True if any part of database file changed */
262 unsigned char inNormalWrite; /* True if in a normal write operation */
264 #endif
266 #ifdef SQLITE_TEST
267 /* In test mode, increase the size of this structure a bit so that
268 ** it is larger than the struct CrashFile defined in test6.c.
270 char aPadding[32];
271 #endif
274 /* This variable holds the process id (pid) from when the xRandomness()
275 ** method was called. If xOpen() is called from a different process id,
276 ** indicating that a fork() has occurred, the PRNG will be reset.
278 static pid_t randomnessPid = 0;
281 ** Allowed values for the unixFile.ctrlFlags bitmask:
283 #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
284 #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
285 #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
286 #ifndef SQLITE_DISABLE_DIRSYNC
287 # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
288 #else
289 # define UNIXFILE_DIRSYNC 0x00
290 #endif
291 #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
292 #define UNIXFILE_DELETE 0x20 /* Delete on close */
293 #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
294 #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
297 ** Include code that is common to all os_*.c files
299 #include "os_common.h"
302 ** Define various macros that are missing from some systems.
304 #ifndef O_LARGEFILE
305 # define O_LARGEFILE 0
306 #endif
307 #ifdef SQLITE_DISABLE_LFS
308 # undef O_LARGEFILE
309 # define O_LARGEFILE 0
310 #endif
311 #ifndef O_NOFOLLOW
312 # define O_NOFOLLOW 0
313 #endif
314 #ifndef O_BINARY
315 # define O_BINARY 0
316 #endif
319 ** The threadid macro resolves to the thread-id or to 0. Used for
320 ** testing and debugging only.
322 #if SQLITE_THREADSAFE
323 #define threadid pthread_self()
324 #else
325 #define threadid 0
326 #endif
329 ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
331 #if !defined(HAVE_MREMAP)
332 # if defined(__linux__) && defined(_GNU_SOURCE)
333 # define HAVE_MREMAP 1
334 # else
335 # define HAVE_MREMAP 0
336 # endif
337 #endif
340 ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
341 ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
343 #ifdef __ANDROID__
344 # define lseek lseek64
345 #endif
347 #ifdef __linux__
349 ** Linux-specific IOCTL magic numbers used for controlling F2FS
351 #define F2FS_IOCTL_MAGIC 0xf5
352 #define F2FS_IOC_START_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 1)
353 #define F2FS_IOC_COMMIT_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 2)
354 #define F2FS_IOC_START_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 3)
355 #define F2FS_IOC_ABORT_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 5)
356 #define F2FS_IOC_GET_FEATURES _IOR(F2FS_IOCTL_MAGIC, 12, u32)
357 #define F2FS_FEATURE_ATOMIC_WRITE 0x0004
358 #endif /* __linux__ */
362 ** Different Unix systems declare open() in different ways. Same use
363 ** open(const char*,int,mode_t). Others use open(const char*,int,...).
364 ** The difference is important when using a pointer to the function.
366 ** The safest way to deal with the problem is to always use this wrapper
367 ** which always has the same well-defined interface.
369 static int posixOpen(const char *zFile, int flags, int mode){
370 return open(zFile, flags, mode);
373 /* Forward reference */
374 static int openDirectory(const char*, int*);
375 static int unixGetpagesize(void);
378 ** Many system calls are accessed through pointer-to-functions so that
379 ** they may be overridden at runtime to facilitate fault injection during
380 ** testing and sandboxing. The following array holds the names and pointers
381 ** to all overrideable system calls.
383 static struct unix_syscall {
384 const char *zName; /* Name of the system call */
385 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
386 sqlite3_syscall_ptr pDefault; /* Default value */
387 } aSyscall[] = {
388 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
389 #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
391 { "close", (sqlite3_syscall_ptr)close, 0 },
392 #define osClose ((int(*)(int))aSyscall[1].pCurrent)
394 { "access", (sqlite3_syscall_ptr)access, 0 },
395 #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
397 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
398 #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
400 { "stat", (sqlite3_syscall_ptr)stat, 0 },
401 #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
404 ** The DJGPP compiler environment looks mostly like Unix, but it
405 ** lacks the fcntl() system call. So redefine fcntl() to be something
406 ** that always succeeds. This means that locking does not occur under
407 ** DJGPP. But it is DOS - what did you expect?
409 #ifdef __DJGPP__
410 { "fstat", 0, 0 },
411 #define osFstat(a,b,c) 0
412 #else
413 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
414 #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
415 #endif
417 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
418 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
420 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
421 #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
423 { "read", (sqlite3_syscall_ptr)read, 0 },
424 #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
426 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
427 { "pread", (sqlite3_syscall_ptr)pread, 0 },
428 #else
429 { "pread", (sqlite3_syscall_ptr)0, 0 },
430 #endif
431 #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
433 #if defined(USE_PREAD64)
434 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
435 #else
436 { "pread64", (sqlite3_syscall_ptr)0, 0 },
437 #endif
438 #define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
440 { "write", (sqlite3_syscall_ptr)write, 0 },
441 #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
443 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
444 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
445 #else
446 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
447 #endif
448 #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
449 aSyscall[12].pCurrent)
451 #if defined(USE_PREAD64)
452 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
453 #else
454 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
455 #endif
456 #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off64_t))\
457 aSyscall[13].pCurrent)
459 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
460 #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
462 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
463 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
464 #else
465 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
466 #endif
467 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
469 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
470 #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
472 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
473 #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
475 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
476 #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
478 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
479 #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
481 #if defined(HAVE_FCHOWN)
482 { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
483 #else
484 { "fchown", (sqlite3_syscall_ptr)0, 0 },
485 #endif
486 #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
488 #if defined(HAVE_FCHOWN)
489 { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
490 #else
491 { "geteuid", (sqlite3_syscall_ptr)0, 0 },
492 #endif
493 #define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
495 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
496 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
497 #else
498 { "mmap", (sqlite3_syscall_ptr)0, 0 },
499 #endif
500 #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
502 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
503 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
504 #else
505 { "munmap", (sqlite3_syscall_ptr)0, 0 },
506 #endif
507 #define osMunmap ((int(*)(void*,size_t))aSyscall[23].pCurrent)
509 #if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
510 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
511 #else
512 { "mremap", (sqlite3_syscall_ptr)0, 0 },
513 #endif
514 #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
516 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
517 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
518 #else
519 { "getpagesize", (sqlite3_syscall_ptr)0, 0 },
520 #endif
521 #define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
523 #if defined(HAVE_READLINK)
524 { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
525 #else
526 { "readlink", (sqlite3_syscall_ptr)0, 0 },
527 #endif
528 #define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
530 #if defined(HAVE_LSTAT)
531 { "lstat", (sqlite3_syscall_ptr)lstat, 0 },
532 #else
533 { "lstat", (sqlite3_syscall_ptr)0, 0 },
534 #endif
535 #define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
537 #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
538 # ifdef __ANDROID__
539 { "ioctl", (sqlite3_syscall_ptr)(int(*)(int, int, ...))ioctl, 0 },
540 #define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent)
541 # else
542 { "ioctl", (sqlite3_syscall_ptr)ioctl, 0 },
543 #define osIoctl ((int(*)(int,unsigned long,...))aSyscall[28].pCurrent)
544 # endif
545 #else
546 { "ioctl", (sqlite3_syscall_ptr)0, 0 },
547 #endif
549 }; /* End of the overrideable system calls */
553 ** On some systems, calls to fchown() will trigger a message in a security
554 ** log if they come from non-root processes. So avoid calling fchown() if
555 ** we are not running as root.
557 static int robustFchown(int fd, uid_t uid, gid_t gid){
558 #if defined(HAVE_FCHOWN)
559 return osGeteuid() ? 0 : osFchown(fd,uid,gid);
560 #else
561 return 0;
562 #endif
566 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
567 ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
568 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
569 ** system call named zName.
571 static int unixSetSystemCall(
572 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
573 const char *zName, /* Name of system call to override */
574 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
576 unsigned int i;
577 int rc = SQLITE_NOTFOUND;
579 UNUSED_PARAMETER(pNotUsed);
580 if( zName==0 ){
581 /* If no zName is given, restore all system calls to their default
582 ** settings and return NULL
584 rc = SQLITE_OK;
585 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
586 if( aSyscall[i].pDefault ){
587 aSyscall[i].pCurrent = aSyscall[i].pDefault;
590 }else{
591 /* If zName is specified, operate on only the one system call
592 ** specified.
594 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
595 if( strcmp(zName, aSyscall[i].zName)==0 ){
596 if( aSyscall[i].pDefault==0 ){
597 aSyscall[i].pDefault = aSyscall[i].pCurrent;
599 rc = SQLITE_OK;
600 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
601 aSyscall[i].pCurrent = pNewFunc;
602 break;
606 return rc;
610 ** Return the value of a system call. Return NULL if zName is not a
611 ** recognized system call name. NULL is also returned if the system call
612 ** is currently undefined.
614 static sqlite3_syscall_ptr unixGetSystemCall(
615 sqlite3_vfs *pNotUsed,
616 const char *zName
618 unsigned int i;
620 UNUSED_PARAMETER(pNotUsed);
621 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
622 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
624 return 0;
628 ** Return the name of the first system call after zName. If zName==NULL
629 ** then return the name of the first system call. Return NULL if zName
630 ** is the last system call or if zName is not the name of a valid
631 ** system call.
633 static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
634 int i = -1;
636 UNUSED_PARAMETER(p);
637 if( zName ){
638 for(i=0; i<ArraySize(aSyscall)-1; i++){
639 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
642 for(i++; i<ArraySize(aSyscall); i++){
643 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
645 return 0;
649 ** Do not accept any file descriptor less than this value, in order to avoid
650 ** opening database file using file descriptors that are commonly used for
651 ** standard input, output, and error.
653 #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
654 # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
655 #endif
658 ** Invoke open(). Do so multiple times, until it either succeeds or
659 ** fails for some reason other than EINTR.
661 ** If the file creation mode "m" is 0 then set it to the default for
662 ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
663 ** 0644) as modified by the system umask. If m is not 0, then
664 ** make the file creation mode be exactly m ignoring the umask.
666 ** The m parameter will be non-zero only when creating -wal, -journal,
667 ** and -shm files. We want those files to have *exactly* the same
668 ** permissions as their original database, unadulterated by the umask.
669 ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
670 ** transaction crashes and leaves behind hot journals, then any
671 ** process that is able to write to the database will also be able to
672 ** recover the hot journals.
674 static int robust_open(const char *z, int f, mode_t m){
675 int fd;
676 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
677 while(1){
678 #if defined(O_CLOEXEC)
679 fd = osOpen(z,f|O_CLOEXEC,m2);
680 #else
681 fd = osOpen(z,f,m2);
682 #endif
683 if( fd<0 ){
684 if( errno==EINTR ) continue;
685 break;
687 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
688 osClose(fd);
689 sqlite3_log(SQLITE_WARNING,
690 "attempt to open \"%s\" as file descriptor %d", z, fd);
691 fd = -1;
692 if( osOpen("/dev/null", O_RDONLY, m)<0 ) break;
694 if( fd>=0 ){
695 if( m!=0 ){
696 struct stat statbuf;
697 if( osFstat(fd, &statbuf)==0
698 && statbuf.st_size==0
699 && (statbuf.st_mode&0777)!=m
701 osFchmod(fd, m);
704 #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
705 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
706 #endif
708 return fd;
712 ** Helper functions to obtain and relinquish the global mutex. The
713 ** global mutex is used to protect the unixInodeInfo and
714 ** vxworksFileId objects used by this file, all of which may be
715 ** shared by multiple threads.
717 ** Function unixMutexHeld() is used to assert() that the global mutex
718 ** is held when required. This function is only used as part of assert()
719 ** statements. e.g.
721 ** unixEnterMutex()
722 ** assert( unixMutexHeld() );
723 ** unixEnterLeave()
725 ** To prevent deadlock, the global unixBigLock must must be acquired
726 ** before the unixInodeInfo.pLockMutex mutex, if both are held. It is
727 ** OK to get the pLockMutex without holding unixBigLock first, but if
728 ** that happens, the unixBigLock mutex must not be acquired until after
729 ** pLockMutex is released.
731 ** OK: enter(unixBigLock), enter(pLockInfo)
732 ** OK: enter(unixBigLock)
733 ** OK: enter(pLockInfo)
734 ** ERROR: enter(pLockInfo), enter(unixBigLock)
736 static sqlite3_mutex *unixBigLock = 0;
737 static void unixEnterMutex(void){
738 assert( sqlite3_mutex_notheld(unixBigLock) ); /* Not a recursive mutex */
739 sqlite3_mutex_enter(unixBigLock);
741 static void unixLeaveMutex(void){
742 assert( sqlite3_mutex_held(unixBigLock) );
743 sqlite3_mutex_leave(unixBigLock);
745 #ifdef SQLITE_DEBUG
746 static int unixMutexHeld(void) {
747 return sqlite3_mutex_held(unixBigLock);
749 #endif
752 #ifdef SQLITE_HAVE_OS_TRACE
754 ** Helper function for printing out trace information from debugging
755 ** binaries. This returns the string representation of the supplied
756 ** integer lock-type.
758 static const char *azFileLock(int eFileLock){
759 switch( eFileLock ){
760 case NO_LOCK: return "NONE";
761 case SHARED_LOCK: return "SHARED";
762 case RESERVED_LOCK: return "RESERVED";
763 case PENDING_LOCK: return "PENDING";
764 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
766 return "ERROR";
768 #endif
770 #ifdef SQLITE_LOCK_TRACE
772 ** Print out information about all locking operations.
774 ** This routine is used for troubleshooting locks on multithreaded
775 ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
776 ** command-line option on the compiler. This code is normally
777 ** turned off.
779 static int lockTrace(int fd, int op, struct flock *p){
780 char *zOpName, *zType;
781 int s;
782 int savedErrno;
783 if( op==F_GETLK ){
784 zOpName = "GETLK";
785 }else if( op==F_SETLK ){
786 zOpName = "SETLK";
787 }else{
788 s = osFcntl(fd, op, p);
789 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
790 return s;
792 if( p->l_type==F_RDLCK ){
793 zType = "RDLCK";
794 }else if( p->l_type==F_WRLCK ){
795 zType = "WRLCK";
796 }else if( p->l_type==F_UNLCK ){
797 zType = "UNLCK";
798 }else{
799 assert( 0 );
801 assert( p->l_whence==SEEK_SET );
802 s = osFcntl(fd, op, p);
803 savedErrno = errno;
804 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
805 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
806 (int)p->l_pid, s);
807 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
808 struct flock l2;
809 l2 = *p;
810 osFcntl(fd, F_GETLK, &l2);
811 if( l2.l_type==F_RDLCK ){
812 zType = "RDLCK";
813 }else if( l2.l_type==F_WRLCK ){
814 zType = "WRLCK";
815 }else if( l2.l_type==F_UNLCK ){
816 zType = "UNLCK";
817 }else{
818 assert( 0 );
820 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
821 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
823 errno = savedErrno;
824 return s;
826 #undef osFcntl
827 #define osFcntl lockTrace
828 #endif /* SQLITE_LOCK_TRACE */
831 ** Retry ftruncate() calls that fail due to EINTR
833 ** All calls to ftruncate() within this file should be made through
834 ** this wrapper. On the Android platform, bypassing the logic below
835 ** could lead to a corrupt database.
837 static int robust_ftruncate(int h, sqlite3_int64 sz){
838 int rc;
839 #ifdef __ANDROID__
840 /* On Android, ftruncate() always uses 32-bit offsets, even if
841 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
842 ** truncate a file to any size larger than 2GiB. Silently ignore any
843 ** such attempts. */
844 if( sz>(sqlite3_int64)0x7FFFFFFF ){
845 rc = SQLITE_OK;
846 }else
847 #endif
848 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
849 return rc;
853 ** This routine translates a standard POSIX errno code into something
854 ** useful to the clients of the sqlite3 functions. Specifically, it is
855 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
856 ** and a variety of "please close the file descriptor NOW" errors into
857 ** SQLITE_IOERR
859 ** Errors during initialization of locks, or file system support for locks,
860 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
862 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
863 assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
864 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
865 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
866 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
867 switch (posixError) {
868 case EACCES:
869 case EAGAIN:
870 case ETIMEDOUT:
871 case EBUSY:
872 case EINTR:
873 case ENOLCK:
874 /* random NFS retry error, unless during file system support
875 * introspection, in which it actually means what it says */
876 return SQLITE_BUSY;
878 case EPERM:
879 return SQLITE_PERM;
881 default:
882 return sqliteIOErr;
887 /******************************************************************************
888 ****************** Begin Unique File ID Utility Used By VxWorks ***************
890 ** On most versions of unix, we can get a unique ID for a file by concatenating
891 ** the device number and the inode number. But this does not work on VxWorks.
892 ** On VxWorks, a unique file id must be based on the canonical filename.
894 ** A pointer to an instance of the following structure can be used as a
895 ** unique file ID in VxWorks. Each instance of this structure contains
896 ** a copy of the canonical filename. There is also a reference count.
897 ** The structure is reclaimed when the number of pointers to it drops to
898 ** zero.
900 ** There are never very many files open at one time and lookups are not
901 ** a performance-critical path, so it is sufficient to put these
902 ** structures on a linked list.
904 struct vxworksFileId {
905 struct vxworksFileId *pNext; /* Next in a list of them all */
906 int nRef; /* Number of references to this one */
907 int nName; /* Length of the zCanonicalName[] string */
908 char *zCanonicalName; /* Canonical filename */
911 #if OS_VXWORKS
913 ** All unique filenames are held on a linked list headed by this
914 ** variable:
916 static struct vxworksFileId *vxworksFileList = 0;
919 ** Simplify a filename into its canonical form
920 ** by making the following changes:
922 ** * removing any trailing and duplicate /
923 ** * convert /./ into just /
924 ** * convert /A/../ where A is any simple name into just /
926 ** Changes are made in-place. Return the new name length.
928 ** The original filename is in z[0..n-1]. Return the number of
929 ** characters in the simplified name.
931 static int vxworksSimplifyName(char *z, int n){
932 int i, j;
933 while( n>1 && z[n-1]=='/' ){ n--; }
934 for(i=j=0; i<n; i++){
935 if( z[i]=='/' ){
936 if( z[i+1]=='/' ) continue;
937 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
938 i += 1;
939 continue;
941 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
942 while( j>0 && z[j-1]!='/' ){ j--; }
943 if( j>0 ){ j--; }
944 i += 2;
945 continue;
948 z[j++] = z[i];
950 z[j] = 0;
951 return j;
955 ** Find a unique file ID for the given absolute pathname. Return
956 ** a pointer to the vxworksFileId object. This pointer is the unique
957 ** file ID.
959 ** The nRef field of the vxworksFileId object is incremented before
960 ** the object is returned. A new vxworksFileId object is created
961 ** and added to the global list if necessary.
963 ** If a memory allocation error occurs, return NULL.
965 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
966 struct vxworksFileId *pNew; /* search key and new file ID */
967 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
968 int n; /* Length of zAbsoluteName string */
970 assert( zAbsoluteName[0]=='/' );
971 n = (int)strlen(zAbsoluteName);
972 pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
973 if( pNew==0 ) return 0;
974 pNew->zCanonicalName = (char*)&pNew[1];
975 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
976 n = vxworksSimplifyName(pNew->zCanonicalName, n);
978 /* Search for an existing entry that matching the canonical name.
979 ** If found, increment the reference count and return a pointer to
980 ** the existing file ID.
982 unixEnterMutex();
983 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
984 if( pCandidate->nName==n
985 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
987 sqlite3_free(pNew);
988 pCandidate->nRef++;
989 unixLeaveMutex();
990 return pCandidate;
994 /* No match was found. We will make a new file ID */
995 pNew->nRef = 1;
996 pNew->nName = n;
997 pNew->pNext = vxworksFileList;
998 vxworksFileList = pNew;
999 unixLeaveMutex();
1000 return pNew;
1004 ** Decrement the reference count on a vxworksFileId object. Free
1005 ** the object when the reference count reaches zero.
1007 static void vxworksReleaseFileId(struct vxworksFileId *pId){
1008 unixEnterMutex();
1009 assert( pId->nRef>0 );
1010 pId->nRef--;
1011 if( pId->nRef==0 ){
1012 struct vxworksFileId **pp;
1013 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
1014 assert( *pp==pId );
1015 *pp = pId->pNext;
1016 sqlite3_free(pId);
1018 unixLeaveMutex();
1020 #endif /* OS_VXWORKS */
1021 /*************** End of Unique File ID Utility Used By VxWorks ****************
1022 ******************************************************************************/
1025 /******************************************************************************
1026 *************************** Posix Advisory Locking ****************************
1028 ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
1029 ** section 6.5.2.2 lines 483 through 490 specify that when a process
1030 ** sets or clears a lock, that operation overrides any prior locks set
1031 ** by the same process. It does not explicitly say so, but this implies
1032 ** that it overrides locks set by the same process using a different
1033 ** file descriptor. Consider this test case:
1035 ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
1036 ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
1038 ** Suppose ./file1 and ./file2 are really the same file (because
1039 ** one is a hard or symbolic link to the other) then if you set
1040 ** an exclusive lock on fd1, then try to get an exclusive lock
1041 ** on fd2, it works. I would have expected the second lock to
1042 ** fail since there was already a lock on the file due to fd1.
1043 ** But not so. Since both locks came from the same process, the
1044 ** second overrides the first, even though they were on different
1045 ** file descriptors opened on different file names.
1047 ** This means that we cannot use POSIX locks to synchronize file access
1048 ** among competing threads of the same process. POSIX locks will work fine
1049 ** to synchronize access for threads in separate processes, but not
1050 ** threads within the same process.
1052 ** To work around the problem, SQLite has to manage file locks internally
1053 ** on its own. Whenever a new database is opened, we have to find the
1054 ** specific inode of the database file (the inode is determined by the
1055 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
1056 ** and check for locks already existing on that inode. When locks are
1057 ** created or removed, we have to look at our own internal record of the
1058 ** locks to see if another thread has previously set a lock on that same
1059 ** inode.
1061 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
1062 ** For VxWorks, we have to use the alternative unique ID system based on
1063 ** canonical filename and implemented in the previous division.)
1065 ** The sqlite3_file structure for POSIX is no longer just an integer file
1066 ** descriptor. It is now a structure that holds the integer file
1067 ** descriptor and a pointer to a structure that describes the internal
1068 ** locks on the corresponding inode. There is one locking structure
1069 ** per inode, so if the same inode is opened twice, both unixFile structures
1070 ** point to the same locking structure. The locking structure keeps
1071 ** a reference count (so we will know when to delete it) and a "cnt"
1072 ** field that tells us its internal lock status. cnt==0 means the
1073 ** file is unlocked. cnt==-1 means the file has an exclusive lock.
1074 ** cnt>0 means there are cnt shared locks on the file.
1076 ** Any attempt to lock or unlock a file first checks the locking
1077 ** structure. The fcntl() system call is only invoked to set a
1078 ** POSIX lock if the internal lock structure transitions between
1079 ** a locked and an unlocked state.
1081 ** But wait: there are yet more problems with POSIX advisory locks.
1083 ** If you close a file descriptor that points to a file that has locks,
1084 ** all locks on that file that are owned by the current process are
1085 ** released. To work around this problem, each unixInodeInfo object
1086 ** maintains a count of the number of pending locks on tha inode.
1087 ** When an attempt is made to close an unixFile, if there are
1088 ** other unixFile open on the same inode that are holding locks, the call
1089 ** to close() the file descriptor is deferred until all of the locks clear.
1090 ** The unixInodeInfo structure keeps a list of file descriptors that need to
1091 ** be closed and that list is walked (and cleared) when the last lock
1092 ** clears.
1094 ** Yet another problem: LinuxThreads do not play well with posix locks.
1096 ** Many older versions of linux use the LinuxThreads library which is
1097 ** not posix compliant. Under LinuxThreads, a lock created by thread
1098 ** A cannot be modified or overridden by a different thread B.
1099 ** Only thread A can modify the lock. Locking behavior is correct
1100 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
1101 ** on linux - with NPTL a lock created by thread A can override locks
1102 ** in thread B. But there is no way to know at compile-time which
1103 ** threading library is being used. So there is no way to know at
1104 ** compile-time whether or not thread A can override locks on thread B.
1105 ** One has to do a run-time check to discover the behavior of the
1106 ** current process.
1108 ** SQLite used to support LinuxThreads. But support for LinuxThreads
1109 ** was dropped beginning with version 3.7.0. SQLite will still work with
1110 ** LinuxThreads provided that (1) there is no more than one connection
1111 ** per database file in the same process and (2) database connections
1112 ** do not move across threads.
1116 ** An instance of the following structure serves as the key used
1117 ** to locate a particular unixInodeInfo object.
1119 struct unixFileId {
1120 dev_t dev; /* Device number */
1121 #if OS_VXWORKS
1122 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
1123 #else
1124 /* We are told that some versions of Android contain a bug that
1125 ** sizes ino_t at only 32-bits instead of 64-bits. (See
1126 ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
1127 ** To work around this, always allocate 64-bits for the inode number.
1128 ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
1129 ** but that should not be a big deal. */
1130 /* WAS: ino_t ino; */
1131 u64 ino; /* Inode number */
1132 #endif
1136 ** An instance of the following structure is allocated for each open
1137 ** inode.
1139 ** A single inode can have multiple file descriptors, so each unixFile
1140 ** structure contains a pointer to an instance of this object and this
1141 ** object keeps a count of the number of unixFile pointing to it.
1143 ** Mutex rules:
1145 ** (1) Only the pLockMutex mutex must be held in order to read or write
1146 ** any of the locking fields:
1147 ** nShared, nLock, eFileLock, bProcessLock, pUnused
1149 ** (2) When nRef>0, then the following fields are unchanging and can
1150 ** be read (but not written) without holding any mutex:
1151 ** fileId, pLockMutex
1153 ** (3) With the exceptions above, all the fields may only be read
1154 ** or written while holding the global unixBigLock mutex.
1156 ** Deadlock prevention: The global unixBigLock mutex may not
1157 ** be acquired while holding the pLockMutex mutex. If both unixBigLock
1158 ** and pLockMutex are needed, then unixBigLock must be acquired first.
1160 struct unixInodeInfo {
1161 struct unixFileId fileId; /* The lookup key */
1162 sqlite3_mutex *pLockMutex; /* Hold this mutex for... */
1163 int nShared; /* Number of SHARED locks held */
1164 int nLock; /* Number of outstanding file locks */
1165 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1166 unsigned char bProcessLock; /* An exclusive process lock is held */
1167 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1168 int nRef; /* Number of pointers to this structure */
1169 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1170 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1171 unixInodeInfo *pPrev; /* .... doubly linked */
1172 #if SQLITE_ENABLE_LOCKING_STYLE
1173 unsigned long long sharedByte; /* for AFP simulated shared lock */
1174 #endif
1175 #if OS_VXWORKS
1176 sem_t *pSem; /* Named POSIX semaphore */
1177 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
1178 #endif
1182 ** A lists of all unixInodeInfo objects.
1184 ** Must hold unixBigLock in order to read or write this variable.
1186 static unixInodeInfo *inodeList = 0; /* All unixInodeInfo objects */
1188 #ifdef SQLITE_DEBUG
1190 ** True if the inode mutex (on the unixFile.pFileMutex field) is held, or not.
1191 ** This routine is used only within assert() to help verify correct mutex
1192 ** usage.
1194 int unixFileMutexHeld(unixFile *pFile){
1195 assert( pFile->pInode );
1196 return sqlite3_mutex_held(pFile->pInode->pLockMutex);
1198 int unixFileMutexNotheld(unixFile *pFile){
1199 assert( pFile->pInode );
1200 return sqlite3_mutex_notheld(pFile->pInode->pLockMutex);
1202 #endif
1206 ** This function - unixLogErrorAtLine(), is only ever called via the macro
1207 ** unixLogError().
1209 ** It is invoked after an error occurs in an OS function and errno has been
1210 ** set. It logs a message using sqlite3_log() containing the current value of
1211 ** errno and, if possible, the human-readable equivalent from strerror() or
1212 ** strerror_r().
1214 ** The first argument passed to the macro should be the error code that
1215 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1216 ** The two subsequent arguments should be the name of the OS function that
1217 ** failed (e.g. "unlink", "open") and the associated file-system path,
1218 ** if any.
1220 #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1221 static int unixLogErrorAtLine(
1222 int errcode, /* SQLite error code */
1223 const char *zFunc, /* Name of OS function that failed */
1224 const char *zPath, /* File path associated with error */
1225 int iLine /* Source line number where error occurred */
1227 char *zErr; /* Message from strerror() or equivalent */
1228 int iErrno = errno; /* Saved syscall error number */
1230 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1231 ** the strerror() function to obtain the human-readable error message
1232 ** equivalent to errno. Otherwise, use strerror_r().
1234 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1235 char aErr[80];
1236 memset(aErr, 0, sizeof(aErr));
1237 zErr = aErr;
1239 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
1240 ** assume that the system provides the GNU version of strerror_r() that
1241 ** returns a pointer to a buffer containing the error message. That pointer
1242 ** may point to aErr[], or it may point to some static storage somewhere.
1243 ** Otherwise, assume that the system provides the POSIX version of
1244 ** strerror_r(), which always writes an error message into aErr[].
1246 ** If the code incorrectly assumes that it is the POSIX version that is
1247 ** available, the error message will often be an empty string. Not a
1248 ** huge problem. Incorrectly concluding that the GNU version is available
1249 ** could lead to a segfault though.
1251 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1252 zErr =
1253 # endif
1254 strerror_r(iErrno, aErr, sizeof(aErr)-1);
1256 #elif SQLITE_THREADSAFE
1257 /* This is a threadsafe build, but strerror_r() is not available. */
1258 zErr = "";
1259 #else
1260 /* Non-threadsafe build, use strerror(). */
1261 zErr = strerror(iErrno);
1262 #endif
1264 if( zPath==0 ) zPath = "";
1265 sqlite3_log(errcode,
1266 "os_unix.c:%d: (%d) %s(%s) - %s",
1267 iLine, iErrno, zFunc, zPath, zErr
1270 return errcode;
1274 ** Close a file descriptor.
1276 ** We assume that close() almost always works, since it is only in a
1277 ** very sick application or on a very sick platform that it might fail.
1278 ** If it does fail, simply leak the file descriptor, but do log the
1279 ** error.
1281 ** Note that it is not safe to retry close() after EINTR since the
1282 ** file descriptor might have already been reused by another thread.
1283 ** So we don't even try to recover from an EINTR. Just log the error
1284 ** and move on.
1286 static void robust_close(unixFile *pFile, int h, int lineno){
1287 if( osClose(h) ){
1288 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1289 pFile ? pFile->zPath : 0, lineno);
1294 ** Set the pFile->lastErrno. Do this in a subroutine as that provides
1295 ** a convenient place to set a breakpoint.
1297 static void storeLastErrno(unixFile *pFile, int error){
1298 pFile->lastErrno = error;
1302 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
1304 static void closePendingFds(unixFile *pFile){
1305 unixInodeInfo *pInode = pFile->pInode;
1306 UnixUnusedFd *p;
1307 UnixUnusedFd *pNext;
1308 assert( unixFileMutexHeld(pFile) );
1309 for(p=pInode->pUnused; p; p=pNext){
1310 pNext = p->pNext;
1311 robust_close(pFile, p->fd, __LINE__);
1312 sqlite3_free(p);
1314 pInode->pUnused = 0;
1318 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
1320 ** The global mutex must be held when this routine is called, but the mutex
1321 ** on the inode being deleted must NOT be held.
1323 static void releaseInodeInfo(unixFile *pFile){
1324 unixInodeInfo *pInode = pFile->pInode;
1325 assert( unixMutexHeld() );
1326 assert( unixFileMutexNotheld(pFile) );
1327 if( ALWAYS(pInode) ){
1328 pInode->nRef--;
1329 if( pInode->nRef==0 ){
1330 assert( pInode->pShmNode==0 );
1331 sqlite3_mutex_enter(pInode->pLockMutex);
1332 closePendingFds(pFile);
1333 sqlite3_mutex_leave(pInode->pLockMutex);
1334 if( pInode->pPrev ){
1335 assert( pInode->pPrev->pNext==pInode );
1336 pInode->pPrev->pNext = pInode->pNext;
1337 }else{
1338 assert( inodeList==pInode );
1339 inodeList = pInode->pNext;
1341 if( pInode->pNext ){
1342 assert( pInode->pNext->pPrev==pInode );
1343 pInode->pNext->pPrev = pInode->pPrev;
1345 sqlite3_mutex_free(pInode->pLockMutex);
1346 sqlite3_free(pInode);
1352 ** Given a file descriptor, locate the unixInodeInfo object that
1353 ** describes that file descriptor. Create a new one if necessary. The
1354 ** return value might be uninitialized if an error occurs.
1356 ** The global mutex must held when calling this routine.
1358 ** Return an appropriate error code.
1360 static int findInodeInfo(
1361 unixFile *pFile, /* Unix file with file desc used in the key */
1362 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
1364 int rc; /* System call return code */
1365 int fd; /* The file descriptor for pFile */
1366 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1367 struct stat statbuf; /* Low-level file information */
1368 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
1370 assert( unixMutexHeld() );
1372 /* Get low-level information about the file that we can used to
1373 ** create a unique name for the file.
1375 fd = pFile->h;
1376 rc = osFstat(fd, &statbuf);
1377 if( rc!=0 ){
1378 storeLastErrno(pFile, errno);
1379 #if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
1380 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1381 #endif
1382 return SQLITE_IOERR;
1385 #ifdef __APPLE__
1386 /* On OS X on an msdos filesystem, the inode number is reported
1387 ** incorrectly for zero-size files. See ticket #3260. To work
1388 ** around this problem (we consider it a bug in OS X, not SQLite)
1389 ** we always increase the file size to 1 by writing a single byte
1390 ** prior to accessing the inode number. The one byte written is
1391 ** an ASCII 'S' character which also happens to be the first byte
1392 ** in the header of every SQLite database. In this way, if there
1393 ** is a race condition such that another thread has already populated
1394 ** the first page of the database, no damage is done.
1396 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
1397 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
1398 if( rc!=1 ){
1399 storeLastErrno(pFile, errno);
1400 return SQLITE_IOERR;
1402 rc = osFstat(fd, &statbuf);
1403 if( rc!=0 ){
1404 storeLastErrno(pFile, errno);
1405 return SQLITE_IOERR;
1408 #endif
1410 memset(&fileId, 0, sizeof(fileId));
1411 fileId.dev = statbuf.st_dev;
1412 #if OS_VXWORKS
1413 fileId.pId = pFile->pId;
1414 #else
1415 fileId.ino = (u64)statbuf.st_ino;
1416 #endif
1417 assert( unixMutexHeld() );
1418 pInode = inodeList;
1419 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1420 pInode = pInode->pNext;
1422 if( pInode==0 ){
1423 pInode = sqlite3_malloc64( sizeof(*pInode) );
1424 if( pInode==0 ){
1425 return SQLITE_NOMEM_BKPT;
1427 memset(pInode, 0, sizeof(*pInode));
1428 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1429 if( sqlite3GlobalConfig.bCoreMutex ){
1430 pInode->pLockMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
1431 if( pInode->pLockMutex==0 ){
1432 sqlite3_free(pInode);
1433 return SQLITE_NOMEM_BKPT;
1436 pInode->nRef = 1;
1437 assert( unixMutexHeld() );
1438 pInode->pNext = inodeList;
1439 pInode->pPrev = 0;
1440 if( inodeList ) inodeList->pPrev = pInode;
1441 inodeList = pInode;
1442 }else{
1443 pInode->nRef++;
1445 *ppInode = pInode;
1446 return SQLITE_OK;
1450 ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1452 static int fileHasMoved(unixFile *pFile){
1453 #if OS_VXWORKS
1454 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1455 #else
1456 struct stat buf;
1457 return pFile->pInode!=0 &&
1458 (osStat(pFile->zPath, &buf)!=0
1459 || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
1460 #endif
1465 ** Check a unixFile that is a database. Verify the following:
1467 ** (1) There is exactly one hard link on the file
1468 ** (2) The file is not a symbolic link
1469 ** (3) The file has not been renamed or unlinked
1471 ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1473 static void verifyDbFile(unixFile *pFile){
1474 struct stat buf;
1475 int rc;
1477 /* These verifications occurs for the main database only */
1478 if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
1480 rc = osFstat(pFile->h, &buf);
1481 if( rc!=0 ){
1482 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
1483 return;
1485 if( buf.st_nlink==0 ){
1486 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
1487 return;
1489 if( buf.st_nlink>1 ){
1490 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
1491 return;
1493 if( fileHasMoved(pFile) ){
1494 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
1495 return;
1501 ** This routine checks if there is a RESERVED lock held on the specified
1502 ** file by this or any other process. If such a lock is held, set *pResOut
1503 ** to a non-zero value otherwise *pResOut is set to zero. The return value
1504 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1506 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
1507 int rc = SQLITE_OK;
1508 int reserved = 0;
1509 unixFile *pFile = (unixFile*)id;
1511 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1513 assert( pFile );
1514 assert( pFile->eFileLock<=SHARED_LOCK );
1515 sqlite3_mutex_enter(pFile->pInode->pLockMutex);
1517 /* Check if a thread in this process holds such a lock */
1518 if( pFile->pInode->eFileLock>SHARED_LOCK ){
1519 reserved = 1;
1522 /* Otherwise see if some other process holds it.
1524 #ifndef __DJGPP__
1525 if( !reserved && !pFile->pInode->bProcessLock ){
1526 struct flock lock;
1527 lock.l_whence = SEEK_SET;
1528 lock.l_start = RESERVED_BYTE;
1529 lock.l_len = 1;
1530 lock.l_type = F_WRLCK;
1531 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1532 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1533 storeLastErrno(pFile, errno);
1534 } else if( lock.l_type!=F_UNLCK ){
1535 reserved = 1;
1538 #endif
1540 sqlite3_mutex_leave(pFile->pInode->pLockMutex);
1541 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
1543 *pResOut = reserved;
1544 return rc;
1548 ** Set a posix-advisory-lock.
1550 ** There are two versions of this routine. If compiled with
1551 ** SQLITE_ENABLE_SETLK_TIMEOUT then the routine has an extra parameter
1552 ** which is a pointer to a unixFile. If the unixFile->iBusyTimeout
1553 ** value is set, then it is the number of milliseconds to wait before
1554 ** failing the lock. The iBusyTimeout value is always reset back to
1555 ** zero on each call.
1557 ** If SQLITE_ENABLE_SETLK_TIMEOUT is not defined, then do a non-blocking
1558 ** attempt to set the lock.
1560 #ifndef SQLITE_ENABLE_SETLK_TIMEOUT
1561 # define osSetPosixAdvisoryLock(h,x,t) osFcntl(h,F_SETLK,x)
1562 #else
1563 static int osSetPosixAdvisoryLock(
1564 int h, /* The file descriptor on which to take the lock */
1565 struct flock *pLock, /* The description of the lock */
1566 unixFile *pFile /* Structure holding timeout value */
1568 int tm = pFile->iBusyTimeout;
1569 int rc = osFcntl(h,F_SETLK,pLock);
1570 while( rc<0 && tm>0 ){
1571 /* On systems that support some kind of blocking file lock with a timeout,
1572 ** make appropriate changes here to invoke that blocking file lock. On
1573 ** generic posix, however, there is no such API. So we simply try the
1574 ** lock once every millisecond until either the timeout expires, or until
1575 ** the lock is obtained. */
1576 usleep(1000);
1577 rc = osFcntl(h,F_SETLK,pLock);
1578 tm--;
1580 return rc;
1582 #endif /* SQLITE_ENABLE_SETLK_TIMEOUT */
1586 ** Attempt to set a system-lock on the file pFile. The lock is
1587 ** described by pLock.
1589 ** If the pFile was opened read/write from unix-excl, then the only lock
1590 ** ever obtained is an exclusive lock, and it is obtained exactly once
1591 ** the first time any lock is attempted. All subsequent system locking
1592 ** operations become no-ops. Locking operations still happen internally,
1593 ** in order to coordinate access between separate database connections
1594 ** within this process, but all of that is handled in memory and the
1595 ** operating system does not participate.
1597 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1598 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1599 ** and is read-only.
1601 ** Zero is returned if the call completes successfully, or -1 if a call
1602 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
1604 static int unixFileLock(unixFile *pFile, struct flock *pLock){
1605 int rc;
1606 unixInodeInfo *pInode = pFile->pInode;
1607 assert( pInode!=0 );
1608 assert( sqlite3_mutex_held(pInode->pLockMutex) );
1609 if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
1610 if( pInode->bProcessLock==0 ){
1611 struct flock lock;
1612 assert( pInode->nLock==0 );
1613 lock.l_whence = SEEK_SET;
1614 lock.l_start = SHARED_FIRST;
1615 lock.l_len = SHARED_SIZE;
1616 lock.l_type = F_WRLCK;
1617 rc = osSetPosixAdvisoryLock(pFile->h, &lock, pFile);
1618 if( rc<0 ) return rc;
1619 pInode->bProcessLock = 1;
1620 pInode->nLock++;
1621 }else{
1622 rc = 0;
1624 }else{
1625 rc = osSetPosixAdvisoryLock(pFile->h, pLock, pFile);
1627 return rc;
1631 ** Lock the file with the lock specified by parameter eFileLock - one
1632 ** of the following:
1634 ** (1) SHARED_LOCK
1635 ** (2) RESERVED_LOCK
1636 ** (3) PENDING_LOCK
1637 ** (4) EXCLUSIVE_LOCK
1639 ** Sometimes when requesting one lock state, additional lock states
1640 ** are inserted in between. The locking might fail on one of the later
1641 ** transitions leaving the lock state different from what it started but
1642 ** still short of its goal. The following chart shows the allowed
1643 ** transitions and the inserted intermediate states:
1645 ** UNLOCKED -> SHARED
1646 ** SHARED -> RESERVED
1647 ** SHARED -> (PENDING) -> EXCLUSIVE
1648 ** RESERVED -> (PENDING) -> EXCLUSIVE
1649 ** PENDING -> EXCLUSIVE
1651 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
1652 ** routine to lower a locking level.
1654 static int unixLock(sqlite3_file *id, int eFileLock){
1655 /* The following describes the implementation of the various locks and
1656 ** lock transitions in terms of the POSIX advisory shared and exclusive
1657 ** lock primitives (called read-locks and write-locks below, to avoid
1658 ** confusion with SQLite lock names). The algorithms are complicated
1659 ** slightly in order to be compatible with Windows95 systems simultaneously
1660 ** accessing the same database file, in case that is ever required.
1662 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1663 ** byte', each single bytes at well known offsets, and the 'shared byte
1664 ** range', a range of 510 bytes at a well known offset.
1666 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1667 ** byte'. If this is successful, 'shared byte range' is read-locked
1668 ** and the lock on the 'pending byte' released. (Legacy note: When
1669 ** SQLite was first developed, Windows95 systems were still very common,
1670 ** and Widnows95 lacks a shared-lock capability. So on Windows95, a
1671 ** single randomly selected by from the 'shared byte range' is locked.
1672 ** Windows95 is now pretty much extinct, but this work-around for the
1673 ** lack of shared-locks on Windows95 lives on, for backwards
1674 ** compatibility.)
1676 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1677 ** A RESERVED lock is implemented by grabbing a write-lock on the
1678 ** 'reserved byte'.
1680 ** A process may only obtain a PENDING lock after it has obtained a
1681 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1682 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1683 ** obtained, but existing SHARED locks are allowed to persist. A process
1684 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1685 ** This property is used by the algorithm for rolling back a journal file
1686 ** after a crash.
1688 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1689 ** implemented by obtaining a write-lock on the entire 'shared byte
1690 ** range'. Since all other locks require a read-lock on one of the bytes
1691 ** within this range, this ensures that no other locks are held on the
1692 ** database.
1694 int rc = SQLITE_OK;
1695 unixFile *pFile = (unixFile*)id;
1696 unixInodeInfo *pInode;
1697 struct flock lock;
1698 int tErrno = 0;
1700 assert( pFile );
1701 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1702 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
1703 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
1704 osGetpid(0)));
1706 /* If there is already a lock of this type or more restrictive on the
1707 ** unixFile, do nothing. Don't use the end_lock: exit path, as
1708 ** unixEnterMutex() hasn't been called yet.
1710 if( pFile->eFileLock>=eFileLock ){
1711 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1712 azFileLock(eFileLock)));
1713 return SQLITE_OK;
1716 /* Make sure the locking sequence is correct.
1717 ** (1) We never move from unlocked to anything higher than shared lock.
1718 ** (2) SQLite never explicitly requests a pendig lock.
1719 ** (3) A shared lock is always held when a reserve lock is requested.
1721 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1722 assert( eFileLock!=PENDING_LOCK );
1723 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
1725 /* This mutex is needed because pFile->pInode is shared across threads
1727 pInode = pFile->pInode;
1728 sqlite3_mutex_enter(pInode->pLockMutex);
1730 /* If some thread using this PID has a lock via a different unixFile*
1731 ** handle that precludes the requested lock, return BUSY.
1733 if( (pFile->eFileLock!=pInode->eFileLock &&
1734 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
1736 rc = SQLITE_BUSY;
1737 goto end_lock;
1740 /* If a SHARED lock is requested, and some thread using this PID already
1741 ** has a SHARED or RESERVED lock, then increment reference counts and
1742 ** return SQLITE_OK.
1744 if( eFileLock==SHARED_LOCK &&
1745 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
1746 assert( eFileLock==SHARED_LOCK );
1747 assert( pFile->eFileLock==0 );
1748 assert( pInode->nShared>0 );
1749 pFile->eFileLock = SHARED_LOCK;
1750 pInode->nShared++;
1751 pInode->nLock++;
1752 goto end_lock;
1756 /* A PENDING lock is needed before acquiring a SHARED lock and before
1757 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1758 ** be released.
1760 lock.l_len = 1L;
1761 lock.l_whence = SEEK_SET;
1762 if( eFileLock==SHARED_LOCK
1763 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
1765 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
1766 lock.l_start = PENDING_BYTE;
1767 if( unixFileLock(pFile, &lock) ){
1768 tErrno = errno;
1769 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1770 if( rc!=SQLITE_BUSY ){
1771 storeLastErrno(pFile, tErrno);
1773 goto end_lock;
1778 /* If control gets to this point, then actually go ahead and make
1779 ** operating system calls for the specified lock.
1781 if( eFileLock==SHARED_LOCK ){
1782 assert( pInode->nShared==0 );
1783 assert( pInode->eFileLock==0 );
1784 assert( rc==SQLITE_OK );
1786 /* Now get the read-lock */
1787 lock.l_start = SHARED_FIRST;
1788 lock.l_len = SHARED_SIZE;
1789 if( unixFileLock(pFile, &lock) ){
1790 tErrno = errno;
1791 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1794 /* Drop the temporary PENDING lock */
1795 lock.l_start = PENDING_BYTE;
1796 lock.l_len = 1L;
1797 lock.l_type = F_UNLCK;
1798 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1799 /* This could happen with a network mount */
1800 tErrno = errno;
1801 rc = SQLITE_IOERR_UNLOCK;
1804 if( rc ){
1805 if( rc!=SQLITE_BUSY ){
1806 storeLastErrno(pFile, tErrno);
1808 goto end_lock;
1809 }else{
1810 pFile->eFileLock = SHARED_LOCK;
1811 pInode->nLock++;
1812 pInode->nShared = 1;
1814 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
1815 /* We are trying for an exclusive lock but another thread in this
1816 ** same process is still holding a shared lock. */
1817 rc = SQLITE_BUSY;
1818 }else{
1819 /* The request was for a RESERVED or EXCLUSIVE lock. It is
1820 ** assumed that there is a SHARED or greater lock on the file
1821 ** already.
1823 assert( 0!=pFile->eFileLock );
1824 lock.l_type = F_WRLCK;
1826 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1827 if( eFileLock==RESERVED_LOCK ){
1828 lock.l_start = RESERVED_BYTE;
1829 lock.l_len = 1L;
1830 }else{
1831 lock.l_start = SHARED_FIRST;
1832 lock.l_len = SHARED_SIZE;
1835 if( unixFileLock(pFile, &lock) ){
1836 tErrno = errno;
1837 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1838 if( rc!=SQLITE_BUSY ){
1839 storeLastErrno(pFile, tErrno);
1845 #ifdef SQLITE_DEBUG
1846 /* Set up the transaction-counter change checking flags when
1847 ** transitioning from a SHARED to a RESERVED lock. The change
1848 ** from SHARED to RESERVED marks the beginning of a normal
1849 ** write operation (not a hot journal rollback).
1851 if( rc==SQLITE_OK
1852 && pFile->eFileLock<=SHARED_LOCK
1853 && eFileLock==RESERVED_LOCK
1855 pFile->transCntrChng = 0;
1856 pFile->dbUpdate = 0;
1857 pFile->inNormalWrite = 1;
1859 #endif
1862 if( rc==SQLITE_OK ){
1863 pFile->eFileLock = eFileLock;
1864 pInode->eFileLock = eFileLock;
1865 }else if( eFileLock==EXCLUSIVE_LOCK ){
1866 pFile->eFileLock = PENDING_LOCK;
1867 pInode->eFileLock = PENDING_LOCK;
1870 end_lock:
1871 sqlite3_mutex_leave(pInode->pLockMutex);
1872 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1873 rc==SQLITE_OK ? "ok" : "failed"));
1874 return rc;
1878 ** Add the file descriptor used by file handle pFile to the corresponding
1879 ** pUnused list.
1881 static void setPendingFd(unixFile *pFile){
1882 unixInodeInfo *pInode = pFile->pInode;
1883 UnixUnusedFd *p = pFile->pPreallocatedUnused;
1884 assert( unixFileMutexHeld(pFile) );
1885 p->pNext = pInode->pUnused;
1886 pInode->pUnused = p;
1887 pFile->h = -1;
1888 pFile->pPreallocatedUnused = 0;
1892 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
1893 ** must be either NO_LOCK or SHARED_LOCK.
1895 ** If the locking level of the file descriptor is already at or below
1896 ** the requested locking level, this routine is a no-op.
1898 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1899 ** the byte range is divided into 2 parts and the first part is unlocked then
1900 ** set to a read lock, then the other part is simply unlocked. This works
1901 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1902 ** remove the write lock on a region when a read lock is set.
1904 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
1905 unixFile *pFile = (unixFile*)id;
1906 unixInodeInfo *pInode;
1907 struct flock lock;
1908 int rc = SQLITE_OK;
1910 assert( pFile );
1911 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
1912 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
1913 osGetpid(0)));
1915 assert( eFileLock<=SHARED_LOCK );
1916 if( pFile->eFileLock<=eFileLock ){
1917 return SQLITE_OK;
1919 pInode = pFile->pInode;
1920 sqlite3_mutex_enter(pInode->pLockMutex);
1921 assert( pInode->nShared!=0 );
1922 if( pFile->eFileLock>SHARED_LOCK ){
1923 assert( pInode->eFileLock==pFile->eFileLock );
1925 #ifdef SQLITE_DEBUG
1926 /* When reducing a lock such that other processes can start
1927 ** reading the database file again, make sure that the
1928 ** transaction counter was updated if any part of the database
1929 ** file changed. If the transaction counter is not updated,
1930 ** other connections to the same file might not realize that
1931 ** the file has changed and hence might not know to flush their
1932 ** cache. The use of a stale cache can lead to database corruption.
1934 pFile->inNormalWrite = 0;
1935 #endif
1937 /* downgrading to a shared lock on NFS involves clearing the write lock
1938 ** before establishing the readlock - to avoid a race condition we downgrade
1939 ** the lock in 2 blocks, so that part of the range will be covered by a
1940 ** write lock until the rest is covered by a read lock:
1941 ** 1: [WWWWW]
1942 ** 2: [....W]
1943 ** 3: [RRRRW]
1944 ** 4: [RRRR.]
1946 if( eFileLock==SHARED_LOCK ){
1947 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
1948 (void)handleNFSUnlock;
1949 assert( handleNFSUnlock==0 );
1950 #endif
1951 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
1952 if( handleNFSUnlock ){
1953 int tErrno; /* Error code from system call errors */
1954 off_t divSize = SHARED_SIZE - 1;
1956 lock.l_type = F_UNLCK;
1957 lock.l_whence = SEEK_SET;
1958 lock.l_start = SHARED_FIRST;
1959 lock.l_len = divSize;
1960 if( unixFileLock(pFile, &lock)==(-1) ){
1961 tErrno = errno;
1962 rc = SQLITE_IOERR_UNLOCK;
1963 storeLastErrno(pFile, tErrno);
1964 goto end_unlock;
1966 lock.l_type = F_RDLCK;
1967 lock.l_whence = SEEK_SET;
1968 lock.l_start = SHARED_FIRST;
1969 lock.l_len = divSize;
1970 if( unixFileLock(pFile, &lock)==(-1) ){
1971 tErrno = errno;
1972 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1973 if( IS_LOCK_ERROR(rc) ){
1974 storeLastErrno(pFile, tErrno);
1976 goto end_unlock;
1978 lock.l_type = F_UNLCK;
1979 lock.l_whence = SEEK_SET;
1980 lock.l_start = SHARED_FIRST+divSize;
1981 lock.l_len = SHARED_SIZE-divSize;
1982 if( unixFileLock(pFile, &lock)==(-1) ){
1983 tErrno = errno;
1984 rc = SQLITE_IOERR_UNLOCK;
1985 storeLastErrno(pFile, tErrno);
1986 goto end_unlock;
1988 }else
1989 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1991 lock.l_type = F_RDLCK;
1992 lock.l_whence = SEEK_SET;
1993 lock.l_start = SHARED_FIRST;
1994 lock.l_len = SHARED_SIZE;
1995 if( unixFileLock(pFile, &lock) ){
1996 /* In theory, the call to unixFileLock() cannot fail because another
1997 ** process is holding an incompatible lock. If it does, this
1998 ** indicates that the other process is not following the locking
1999 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
2000 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
2001 ** an assert to fail). */
2002 rc = SQLITE_IOERR_RDLOCK;
2003 storeLastErrno(pFile, errno);
2004 goto end_unlock;
2008 lock.l_type = F_UNLCK;
2009 lock.l_whence = SEEK_SET;
2010 lock.l_start = PENDING_BYTE;
2011 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
2012 if( unixFileLock(pFile, &lock)==0 ){
2013 pInode->eFileLock = SHARED_LOCK;
2014 }else{
2015 rc = SQLITE_IOERR_UNLOCK;
2016 storeLastErrno(pFile, errno);
2017 goto end_unlock;
2020 if( eFileLock==NO_LOCK ){
2021 /* Decrement the shared lock counter. Release the lock using an
2022 ** OS call only when all threads in this same process have released
2023 ** the lock.
2025 pInode->nShared--;
2026 if( pInode->nShared==0 ){
2027 lock.l_type = F_UNLCK;
2028 lock.l_whence = SEEK_SET;
2029 lock.l_start = lock.l_len = 0L;
2030 if( unixFileLock(pFile, &lock)==0 ){
2031 pInode->eFileLock = NO_LOCK;
2032 }else{
2033 rc = SQLITE_IOERR_UNLOCK;
2034 storeLastErrno(pFile, errno);
2035 pInode->eFileLock = NO_LOCK;
2036 pFile->eFileLock = NO_LOCK;
2040 /* Decrement the count of locks against this same file. When the
2041 ** count reaches zero, close any other file descriptors whose close
2042 ** was deferred because of outstanding locks.
2044 pInode->nLock--;
2045 assert( pInode->nLock>=0 );
2046 if( pInode->nLock==0 ) closePendingFds(pFile);
2049 end_unlock:
2050 sqlite3_mutex_leave(pInode->pLockMutex);
2051 if( rc==SQLITE_OK ){
2052 pFile->eFileLock = eFileLock;
2054 return rc;
2058 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
2059 ** must be either NO_LOCK or SHARED_LOCK.
2061 ** If the locking level of the file descriptor is already at or below
2062 ** the requested locking level, this routine is a no-op.
2064 static int unixUnlock(sqlite3_file *id, int eFileLock){
2065 #if SQLITE_MAX_MMAP_SIZE>0
2066 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
2067 #endif
2068 return posixUnlock(id, eFileLock, 0);
2071 #if SQLITE_MAX_MMAP_SIZE>0
2072 static int unixMapfile(unixFile *pFd, i64 nByte);
2073 static void unixUnmapfile(unixFile *pFd);
2074 #endif
2077 ** This function performs the parts of the "close file" operation
2078 ** common to all locking schemes. It closes the directory and file
2079 ** handles, if they are valid, and sets all fields of the unixFile
2080 ** structure to 0.
2082 ** It is *not* necessary to hold the mutex when this routine is called,
2083 ** even on VxWorks. A mutex will be acquired on VxWorks by the
2084 ** vxworksReleaseFileId() routine.
2086 static int closeUnixFile(sqlite3_file *id){
2087 unixFile *pFile = (unixFile*)id;
2088 #if SQLITE_MAX_MMAP_SIZE>0
2089 unixUnmapfile(pFile);
2090 #endif
2091 if( pFile->h>=0 ){
2092 robust_close(pFile, pFile->h, __LINE__);
2093 pFile->h = -1;
2095 #if OS_VXWORKS
2096 if( pFile->pId ){
2097 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
2098 osUnlink(pFile->pId->zCanonicalName);
2100 vxworksReleaseFileId(pFile->pId);
2101 pFile->pId = 0;
2103 #endif
2104 #ifdef SQLITE_UNLINK_AFTER_CLOSE
2105 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
2106 osUnlink(pFile->zPath);
2107 sqlite3_free(*(char**)&pFile->zPath);
2108 pFile->zPath = 0;
2110 #endif
2111 OSTRACE(("CLOSE %-3d\n", pFile->h));
2112 OpenCounter(-1);
2113 sqlite3_free(pFile->pPreallocatedUnused);
2114 memset(pFile, 0, sizeof(unixFile));
2115 return SQLITE_OK;
2119 ** Close a file.
2121 static int unixClose(sqlite3_file *id){
2122 int rc = SQLITE_OK;
2123 unixFile *pFile = (unixFile *)id;
2124 unixInodeInfo *pInode = pFile->pInode;
2126 assert( pInode!=0 );
2127 verifyDbFile(pFile);
2128 unixUnlock(id, NO_LOCK);
2129 assert( unixFileMutexNotheld(pFile) );
2130 unixEnterMutex();
2132 /* unixFile.pInode is always valid here. Otherwise, a different close
2133 ** routine (e.g. nolockClose()) would be called instead.
2135 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
2136 sqlite3_mutex_enter(pInode->pLockMutex);
2137 if( pInode->nLock ){
2138 /* If there are outstanding locks, do not actually close the file just
2139 ** yet because that would clear those locks. Instead, add the file
2140 ** descriptor to pInode->pUnused list. It will be automatically closed
2141 ** when the last lock is cleared.
2143 setPendingFd(pFile);
2145 sqlite3_mutex_leave(pInode->pLockMutex);
2146 releaseInodeInfo(pFile);
2147 rc = closeUnixFile(id);
2148 unixLeaveMutex();
2149 return rc;
2152 /************** End of the posix advisory lock implementation *****************
2153 ******************************************************************************/
2155 /******************************************************************************
2156 ****************************** No-op Locking **********************************
2158 ** Of the various locking implementations available, this is by far the
2159 ** simplest: locking is ignored. No attempt is made to lock the database
2160 ** file for reading or writing.
2162 ** This locking mode is appropriate for use on read-only databases
2163 ** (ex: databases that are burned into CD-ROM, for example.) It can
2164 ** also be used if the application employs some external mechanism to
2165 ** prevent simultaneous access of the same database by two or more
2166 ** database connections. But there is a serious risk of database
2167 ** corruption if this locking mode is used in situations where multiple
2168 ** database connections are accessing the same database file at the same
2169 ** time and one or more of those connections are writing.
2172 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
2173 UNUSED_PARAMETER(NotUsed);
2174 *pResOut = 0;
2175 return SQLITE_OK;
2177 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
2178 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2179 return SQLITE_OK;
2181 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
2182 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2183 return SQLITE_OK;
2187 ** Close the file.
2189 static int nolockClose(sqlite3_file *id) {
2190 return closeUnixFile(id);
2193 /******************* End of the no-op lock implementation *********************
2194 ******************************************************************************/
2196 /******************************************************************************
2197 ************************* Begin dot-file Locking ******************************
2199 ** The dotfile locking implementation uses the existence of separate lock
2200 ** files (really a directory) to control access to the database. This works
2201 ** on just about every filesystem imaginable. But there are serious downsides:
2203 ** (1) There is zero concurrency. A single reader blocks all other
2204 ** connections from reading or writing the database.
2206 ** (2) An application crash or power loss can leave stale lock files
2207 ** sitting around that need to be cleared manually.
2209 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
2210 ** other locking strategy is available.
2212 ** Dotfile locking works by creating a subdirectory in the same directory as
2213 ** the database and with the same name but with a ".lock" extension added.
2214 ** The existence of a lock directory implies an EXCLUSIVE lock. All other
2215 ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
2219 ** The file suffix added to the data base filename in order to create the
2220 ** lock directory.
2222 #define DOTLOCK_SUFFIX ".lock"
2225 ** This routine checks if there is a RESERVED lock held on the specified
2226 ** file by this or any other process. If such a lock is held, set *pResOut
2227 ** to a non-zero value otherwise *pResOut is set to zero. The return value
2228 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2230 ** In dotfile locking, either a lock exists or it does not. So in this
2231 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
2232 ** is held on the file and false if the file is unlocked.
2234 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2235 int rc = SQLITE_OK;
2236 int reserved = 0;
2237 unixFile *pFile = (unixFile*)id;
2239 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2241 assert( pFile );
2242 reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
2243 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
2244 *pResOut = reserved;
2245 return rc;
2249 ** Lock the file with the lock specified by parameter eFileLock - one
2250 ** of the following:
2252 ** (1) SHARED_LOCK
2253 ** (2) RESERVED_LOCK
2254 ** (3) PENDING_LOCK
2255 ** (4) EXCLUSIVE_LOCK
2257 ** Sometimes when requesting one lock state, additional lock states
2258 ** are inserted in between. The locking might fail on one of the later
2259 ** transitions leaving the lock state different from what it started but
2260 ** still short of its goal. The following chart shows the allowed
2261 ** transitions and the inserted intermediate states:
2263 ** UNLOCKED -> SHARED
2264 ** SHARED -> RESERVED
2265 ** SHARED -> (PENDING) -> EXCLUSIVE
2266 ** RESERVED -> (PENDING) -> EXCLUSIVE
2267 ** PENDING -> EXCLUSIVE
2269 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
2270 ** routine to lower a locking level.
2272 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
2273 ** But we track the other locking levels internally.
2275 static int dotlockLock(sqlite3_file *id, int eFileLock) {
2276 unixFile *pFile = (unixFile*)id;
2277 char *zLockFile = (char *)pFile->lockingContext;
2278 int rc = SQLITE_OK;
2281 /* If we have any lock, then the lock file already exists. All we have
2282 ** to do is adjust our internal record of the lock level.
2284 if( pFile->eFileLock > NO_LOCK ){
2285 pFile->eFileLock = eFileLock;
2286 /* Always update the timestamp on the old file */
2287 #ifdef HAVE_UTIME
2288 utime(zLockFile, NULL);
2289 #else
2290 utimes(zLockFile, NULL);
2291 #endif
2292 return SQLITE_OK;
2295 /* grab an exclusive lock */
2296 rc = osMkdir(zLockFile, 0777);
2297 if( rc<0 ){
2298 /* failed to open/create the lock directory */
2299 int tErrno = errno;
2300 if( EEXIST == tErrno ){
2301 rc = SQLITE_BUSY;
2302 } else {
2303 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2304 if( rc!=SQLITE_BUSY ){
2305 storeLastErrno(pFile, tErrno);
2308 return rc;
2311 /* got it, set the type and return ok */
2312 pFile->eFileLock = eFileLock;
2313 return rc;
2317 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
2318 ** must be either NO_LOCK or SHARED_LOCK.
2320 ** If the locking level of the file descriptor is already at or below
2321 ** the requested locking level, this routine is a no-op.
2323 ** When the locking level reaches NO_LOCK, delete the lock file.
2325 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
2326 unixFile *pFile = (unixFile*)id;
2327 char *zLockFile = (char *)pFile->lockingContext;
2328 int rc;
2330 assert( pFile );
2331 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
2332 pFile->eFileLock, osGetpid(0)));
2333 assert( eFileLock<=SHARED_LOCK );
2335 /* no-op if possible */
2336 if( pFile->eFileLock==eFileLock ){
2337 return SQLITE_OK;
2340 /* To downgrade to shared, simply update our internal notion of the
2341 ** lock state. No need to mess with the file on disk.
2343 if( eFileLock==SHARED_LOCK ){
2344 pFile->eFileLock = SHARED_LOCK;
2345 return SQLITE_OK;
2348 /* To fully unlock the database, delete the lock file */
2349 assert( eFileLock==NO_LOCK );
2350 rc = osRmdir(zLockFile);
2351 if( rc<0 ){
2352 int tErrno = errno;
2353 if( tErrno==ENOENT ){
2354 rc = SQLITE_OK;
2355 }else{
2356 rc = SQLITE_IOERR_UNLOCK;
2357 storeLastErrno(pFile, tErrno);
2359 return rc;
2361 pFile->eFileLock = NO_LOCK;
2362 return SQLITE_OK;
2366 ** Close a file. Make sure the lock has been released before closing.
2368 static int dotlockClose(sqlite3_file *id) {
2369 unixFile *pFile = (unixFile*)id;
2370 assert( id!=0 );
2371 dotlockUnlock(id, NO_LOCK);
2372 sqlite3_free(pFile->lockingContext);
2373 return closeUnixFile(id);
2375 /****************** End of the dot-file lock implementation *******************
2376 ******************************************************************************/
2378 /******************************************************************************
2379 ************************** Begin flock Locking ********************************
2381 ** Use the flock() system call to do file locking.
2383 ** flock() locking is like dot-file locking in that the various
2384 ** fine-grain locking levels supported by SQLite are collapsed into
2385 ** a single exclusive lock. In other words, SHARED, RESERVED, and
2386 ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2387 ** still works when you do this, but concurrency is reduced since
2388 ** only a single process can be reading the database at a time.
2390 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
2392 #if SQLITE_ENABLE_LOCKING_STYLE
2395 ** Retry flock() calls that fail with EINTR
2397 #ifdef EINTR
2398 static int robust_flock(int fd, int op){
2399 int rc;
2400 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2401 return rc;
2403 #else
2404 # define robust_flock(a,b) flock(a,b)
2405 #endif
2409 ** This routine checks if there is a RESERVED lock held on the specified
2410 ** file by this or any other process. If such a lock is held, set *pResOut
2411 ** to a non-zero value otherwise *pResOut is set to zero. The return value
2412 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2414 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2415 int rc = SQLITE_OK;
2416 int reserved = 0;
2417 unixFile *pFile = (unixFile*)id;
2419 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2421 assert( pFile );
2423 /* Check if a thread in this process holds such a lock */
2424 if( pFile->eFileLock>SHARED_LOCK ){
2425 reserved = 1;
2428 /* Otherwise see if some other process holds it. */
2429 if( !reserved ){
2430 /* attempt to get the lock */
2431 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
2432 if( !lrc ){
2433 /* got the lock, unlock it */
2434 lrc = robust_flock(pFile->h, LOCK_UN);
2435 if ( lrc ) {
2436 int tErrno = errno;
2437 /* unlock failed with an error */
2438 lrc = SQLITE_IOERR_UNLOCK;
2439 storeLastErrno(pFile, tErrno);
2440 rc = lrc;
2442 } else {
2443 int tErrno = errno;
2444 reserved = 1;
2445 /* someone else might have it reserved */
2446 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2447 if( IS_LOCK_ERROR(lrc) ){
2448 storeLastErrno(pFile, tErrno);
2449 rc = lrc;
2453 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
2455 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2456 if( (rc & 0xff) == SQLITE_IOERR ){
2457 rc = SQLITE_OK;
2458 reserved=1;
2460 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2461 *pResOut = reserved;
2462 return rc;
2466 ** Lock the file with the lock specified by parameter eFileLock - one
2467 ** of the following:
2469 ** (1) SHARED_LOCK
2470 ** (2) RESERVED_LOCK
2471 ** (3) PENDING_LOCK
2472 ** (4) EXCLUSIVE_LOCK
2474 ** Sometimes when requesting one lock state, additional lock states
2475 ** are inserted in between. The locking might fail on one of the later
2476 ** transitions leaving the lock state different from what it started but
2477 ** still short of its goal. The following chart shows the allowed
2478 ** transitions and the inserted intermediate states:
2480 ** UNLOCKED -> SHARED
2481 ** SHARED -> RESERVED
2482 ** SHARED -> (PENDING) -> EXCLUSIVE
2483 ** RESERVED -> (PENDING) -> EXCLUSIVE
2484 ** PENDING -> EXCLUSIVE
2486 ** flock() only really support EXCLUSIVE locks. We track intermediate
2487 ** lock states in the sqlite3_file structure, but all locks SHARED or
2488 ** above are really EXCLUSIVE locks and exclude all other processes from
2489 ** access the file.
2491 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
2492 ** routine to lower a locking level.
2494 static int flockLock(sqlite3_file *id, int eFileLock) {
2495 int rc = SQLITE_OK;
2496 unixFile *pFile = (unixFile*)id;
2498 assert( pFile );
2500 /* if we already have a lock, it is exclusive.
2501 ** Just adjust level and punt on outta here. */
2502 if (pFile->eFileLock > NO_LOCK) {
2503 pFile->eFileLock = eFileLock;
2504 return SQLITE_OK;
2507 /* grab an exclusive lock */
2509 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
2510 int tErrno = errno;
2511 /* didn't get, must be busy */
2512 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2513 if( IS_LOCK_ERROR(rc) ){
2514 storeLastErrno(pFile, tErrno);
2516 } else {
2517 /* got it, set the type and return ok */
2518 pFile->eFileLock = eFileLock;
2520 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2521 rc==SQLITE_OK ? "ok" : "failed"));
2522 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2523 if( (rc & 0xff) == SQLITE_IOERR ){
2524 rc = SQLITE_BUSY;
2526 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2527 return rc;
2532 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
2533 ** must be either NO_LOCK or SHARED_LOCK.
2535 ** If the locking level of the file descriptor is already at or below
2536 ** the requested locking level, this routine is a no-op.
2538 static int flockUnlock(sqlite3_file *id, int eFileLock) {
2539 unixFile *pFile = (unixFile*)id;
2541 assert( pFile );
2542 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2543 pFile->eFileLock, osGetpid(0)));
2544 assert( eFileLock<=SHARED_LOCK );
2546 /* no-op if possible */
2547 if( pFile->eFileLock==eFileLock ){
2548 return SQLITE_OK;
2551 /* shared can just be set because we always have an exclusive */
2552 if (eFileLock==SHARED_LOCK) {
2553 pFile->eFileLock = eFileLock;
2554 return SQLITE_OK;
2557 /* no, really, unlock. */
2558 if( robust_flock(pFile->h, LOCK_UN) ){
2559 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2560 return SQLITE_OK;
2561 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2562 return SQLITE_IOERR_UNLOCK;
2563 }else{
2564 pFile->eFileLock = NO_LOCK;
2565 return SQLITE_OK;
2570 ** Close a file.
2572 static int flockClose(sqlite3_file *id) {
2573 assert( id!=0 );
2574 flockUnlock(id, NO_LOCK);
2575 return closeUnixFile(id);
2578 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2580 /******************* End of the flock lock implementation *********************
2581 ******************************************************************************/
2583 /******************************************************************************
2584 ************************ Begin Named Semaphore Locking ************************
2586 ** Named semaphore locking is only supported on VxWorks.
2588 ** Semaphore locking is like dot-lock and flock in that it really only
2589 ** supports EXCLUSIVE locking. Only a single process can read or write
2590 ** the database file at a time. This reduces potential concurrency, but
2591 ** makes the lock implementation much easier.
2593 #if OS_VXWORKS
2596 ** This routine checks if there is a RESERVED lock held on the specified
2597 ** file by this or any other process. If such a lock is held, set *pResOut
2598 ** to a non-zero value otherwise *pResOut is set to zero. The return value
2599 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2601 static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
2602 int rc = SQLITE_OK;
2603 int reserved = 0;
2604 unixFile *pFile = (unixFile*)id;
2606 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2608 assert( pFile );
2610 /* Check if a thread in this process holds such a lock */
2611 if( pFile->eFileLock>SHARED_LOCK ){
2612 reserved = 1;
2615 /* Otherwise see if some other process holds it. */
2616 if( !reserved ){
2617 sem_t *pSem = pFile->pInode->pSem;
2619 if( sem_trywait(pSem)==-1 ){
2620 int tErrno = errno;
2621 if( EAGAIN != tErrno ){
2622 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2623 storeLastErrno(pFile, tErrno);
2624 } else {
2625 /* someone else has the lock when we are in NO_LOCK */
2626 reserved = (pFile->eFileLock < SHARED_LOCK);
2628 }else{
2629 /* we could have it if we want it */
2630 sem_post(pSem);
2633 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
2635 *pResOut = reserved;
2636 return rc;
2640 ** Lock the file with the lock specified by parameter eFileLock - one
2641 ** of the following:
2643 ** (1) SHARED_LOCK
2644 ** (2) RESERVED_LOCK
2645 ** (3) PENDING_LOCK
2646 ** (4) EXCLUSIVE_LOCK
2648 ** Sometimes when requesting one lock state, additional lock states
2649 ** are inserted in between. The locking might fail on one of the later
2650 ** transitions leaving the lock state different from what it started but
2651 ** still short of its goal. The following chart shows the allowed
2652 ** transitions and the inserted intermediate states:
2654 ** UNLOCKED -> SHARED
2655 ** SHARED -> RESERVED
2656 ** SHARED -> (PENDING) -> EXCLUSIVE
2657 ** RESERVED -> (PENDING) -> EXCLUSIVE
2658 ** PENDING -> EXCLUSIVE
2660 ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2661 ** lock states in the sqlite3_file structure, but all locks SHARED or
2662 ** above are really EXCLUSIVE locks and exclude all other processes from
2663 ** access the file.
2665 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
2666 ** routine to lower a locking level.
2668 static int semXLock(sqlite3_file *id, int eFileLock) {
2669 unixFile *pFile = (unixFile*)id;
2670 sem_t *pSem = pFile->pInode->pSem;
2671 int rc = SQLITE_OK;
2673 /* if we already have a lock, it is exclusive.
2674 ** Just adjust level and punt on outta here. */
2675 if (pFile->eFileLock > NO_LOCK) {
2676 pFile->eFileLock = eFileLock;
2677 rc = SQLITE_OK;
2678 goto sem_end_lock;
2681 /* lock semaphore now but bail out when already locked. */
2682 if( sem_trywait(pSem)==-1 ){
2683 rc = SQLITE_BUSY;
2684 goto sem_end_lock;
2687 /* got it, set the type and return ok */
2688 pFile->eFileLock = eFileLock;
2690 sem_end_lock:
2691 return rc;
2695 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
2696 ** must be either NO_LOCK or SHARED_LOCK.
2698 ** If the locking level of the file descriptor is already at or below
2699 ** the requested locking level, this routine is a no-op.
2701 static int semXUnlock(sqlite3_file *id, int eFileLock) {
2702 unixFile *pFile = (unixFile*)id;
2703 sem_t *pSem = pFile->pInode->pSem;
2705 assert( pFile );
2706 assert( pSem );
2707 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2708 pFile->eFileLock, osGetpid(0)));
2709 assert( eFileLock<=SHARED_LOCK );
2711 /* no-op if possible */
2712 if( pFile->eFileLock==eFileLock ){
2713 return SQLITE_OK;
2716 /* shared can just be set because we always have an exclusive */
2717 if (eFileLock==SHARED_LOCK) {
2718 pFile->eFileLock = eFileLock;
2719 return SQLITE_OK;
2722 /* no, really unlock. */
2723 if ( sem_post(pSem)==-1 ) {
2724 int rc, tErrno = errno;
2725 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2726 if( IS_LOCK_ERROR(rc) ){
2727 storeLastErrno(pFile, tErrno);
2729 return rc;
2731 pFile->eFileLock = NO_LOCK;
2732 return SQLITE_OK;
2736 ** Close a file.
2738 static int semXClose(sqlite3_file *id) {
2739 if( id ){
2740 unixFile *pFile = (unixFile*)id;
2741 semXUnlock(id, NO_LOCK);
2742 assert( pFile );
2743 assert( unixFileMutexNotheld(pFile) );
2744 unixEnterMutex();
2745 releaseInodeInfo(pFile);
2746 unixLeaveMutex();
2747 closeUnixFile(id);
2749 return SQLITE_OK;
2752 #endif /* OS_VXWORKS */
2754 ** Named semaphore locking is only available on VxWorks.
2756 *************** End of the named semaphore lock implementation ****************
2757 ******************************************************************************/
2760 /******************************************************************************
2761 *************************** Begin AFP Locking *********************************
2763 ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2764 ** on Apple Macintosh computers - both OS9 and OSX.
2766 ** Third-party implementations of AFP are available. But this code here
2767 ** only works on OSX.
2770 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2772 ** The afpLockingContext structure contains all afp lock specific state
2774 typedef struct afpLockingContext afpLockingContext;
2775 struct afpLockingContext {
2776 int reserved;
2777 const char *dbPath; /* Name of the open file */
2780 struct ByteRangeLockPB2
2782 unsigned long long offset; /* offset to first byte to lock */
2783 unsigned long long length; /* nbr of bytes to lock */
2784 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2785 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2786 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2787 int fd; /* file desc to assoc this lock with */
2790 #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
2793 ** This is a utility for setting or clearing a bit-range lock on an
2794 ** AFP filesystem.
2796 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2798 static int afpSetLock(
2799 const char *path, /* Name of the file to be locked or unlocked */
2800 unixFile *pFile, /* Open file descriptor on path */
2801 unsigned long long offset, /* First byte to be locked */
2802 unsigned long long length, /* Number of bytes to lock */
2803 int setLockFlag /* True to set lock. False to clear lock */
2805 struct ByteRangeLockPB2 pb;
2806 int err;
2808 pb.unLockFlag = setLockFlag ? 0 : 1;
2809 pb.startEndFlag = 0;
2810 pb.offset = offset;
2811 pb.length = length;
2812 pb.fd = pFile->h;
2814 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
2815 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
2816 offset, length));
2817 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2818 if ( err==-1 ) {
2819 int rc;
2820 int tErrno = errno;
2821 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2822 path, tErrno, strerror(tErrno)));
2823 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2824 rc = SQLITE_BUSY;
2825 #else
2826 rc = sqliteErrorFromPosixError(tErrno,
2827 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
2828 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
2829 if( IS_LOCK_ERROR(rc) ){
2830 storeLastErrno(pFile, tErrno);
2832 return rc;
2833 } else {
2834 return SQLITE_OK;
2839 ** This routine checks if there is a RESERVED lock held on the specified
2840 ** file by this or any other process. If such a lock is held, set *pResOut
2841 ** to a non-zero value otherwise *pResOut is set to zero. The return value
2842 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2844 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
2845 int rc = SQLITE_OK;
2846 int reserved = 0;
2847 unixFile *pFile = (unixFile*)id;
2848 afpLockingContext *context;
2850 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2852 assert( pFile );
2853 context = (afpLockingContext *) pFile->lockingContext;
2854 if( context->reserved ){
2855 *pResOut = 1;
2856 return SQLITE_OK;
2858 sqlite3_mutex_enter(pFile->pInode->pLockMutex);
2859 /* Check if a thread in this process holds such a lock */
2860 if( pFile->pInode->eFileLock>SHARED_LOCK ){
2861 reserved = 1;
2864 /* Otherwise see if some other process holds it.
2866 if( !reserved ){
2867 /* lock the RESERVED byte */
2868 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
2869 if( SQLITE_OK==lrc ){
2870 /* if we succeeded in taking the reserved lock, unlock it to restore
2871 ** the original state */
2872 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2873 } else {
2874 /* if we failed to get the lock then someone else must have it */
2875 reserved = 1;
2877 if( IS_LOCK_ERROR(lrc) ){
2878 rc=lrc;
2882 sqlite3_mutex_leave(pFile->pInode->pLockMutex);
2883 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
2885 *pResOut = reserved;
2886 return rc;
2890 ** Lock the file with the lock specified by parameter eFileLock - one
2891 ** of the following:
2893 ** (1) SHARED_LOCK
2894 ** (2) RESERVED_LOCK
2895 ** (3) PENDING_LOCK
2896 ** (4) EXCLUSIVE_LOCK
2898 ** Sometimes when requesting one lock state, additional lock states
2899 ** are inserted in between. The locking might fail on one of the later
2900 ** transitions leaving the lock state different from what it started but
2901 ** still short of its goal. The following chart shows the allowed
2902 ** transitions and the inserted intermediate states:
2904 ** UNLOCKED -> SHARED
2905 ** SHARED -> RESERVED
2906 ** SHARED -> (PENDING) -> EXCLUSIVE
2907 ** RESERVED -> (PENDING) -> EXCLUSIVE
2908 ** PENDING -> EXCLUSIVE
2910 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
2911 ** routine to lower a locking level.
2913 static int afpLock(sqlite3_file *id, int eFileLock){
2914 int rc = SQLITE_OK;
2915 unixFile *pFile = (unixFile*)id;
2916 unixInodeInfo *pInode = pFile->pInode;
2917 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2919 assert( pFile );
2920 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2921 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
2922 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
2924 /* If there is already a lock of this type or more restrictive on the
2925 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
2926 ** unixEnterMutex() hasn't been called yet.
2928 if( pFile->eFileLock>=eFileLock ){
2929 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2930 azFileLock(eFileLock)));
2931 return SQLITE_OK;
2934 /* Make sure the locking sequence is correct
2935 ** (1) We never move from unlocked to anything higher than shared lock.
2936 ** (2) SQLite never explicitly requests a pendig lock.
2937 ** (3) A shared lock is always held when a reserve lock is requested.
2939 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2940 assert( eFileLock!=PENDING_LOCK );
2941 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
2943 /* This mutex is needed because pFile->pInode is shared across threads
2945 pInode = pFile->pInode;
2946 sqlite3_mutex_enter(pInode->pLockMutex);
2948 /* If some thread using this PID has a lock via a different unixFile*
2949 ** handle that precludes the requested lock, return BUSY.
2951 if( (pFile->eFileLock!=pInode->eFileLock &&
2952 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
2954 rc = SQLITE_BUSY;
2955 goto afp_end_lock;
2958 /* If a SHARED lock is requested, and some thread using this PID already
2959 ** has a SHARED or RESERVED lock, then increment reference counts and
2960 ** return SQLITE_OK.
2962 if( eFileLock==SHARED_LOCK &&
2963 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
2964 assert( eFileLock==SHARED_LOCK );
2965 assert( pFile->eFileLock==0 );
2966 assert( pInode->nShared>0 );
2967 pFile->eFileLock = SHARED_LOCK;
2968 pInode->nShared++;
2969 pInode->nLock++;
2970 goto afp_end_lock;
2973 /* A PENDING lock is needed before acquiring a SHARED lock and before
2974 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2975 ** be released.
2977 if( eFileLock==SHARED_LOCK
2978 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
2980 int failed;
2981 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
2982 if (failed) {
2983 rc = failed;
2984 goto afp_end_lock;
2988 /* If control gets to this point, then actually go ahead and make
2989 ** operating system calls for the specified lock.
2991 if( eFileLock==SHARED_LOCK ){
2992 int lrc1, lrc2, lrc1Errno = 0;
2993 long lk, mask;
2995 assert( pInode->nShared==0 );
2996 assert( pInode->eFileLock==0 );
2998 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
2999 /* Now get the read-lock SHARED_LOCK */
3000 /* note that the quality of the randomness doesn't matter that much */
3001 lk = random();
3002 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
3003 lrc1 = afpSetLock(context->dbPath, pFile,
3004 SHARED_FIRST+pInode->sharedByte, 1, 1);
3005 if( IS_LOCK_ERROR(lrc1) ){
3006 lrc1Errno = pFile->lastErrno;
3008 /* Drop the temporary PENDING lock */
3009 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
3011 if( IS_LOCK_ERROR(lrc1) ) {
3012 storeLastErrno(pFile, lrc1Errno);
3013 rc = lrc1;
3014 goto afp_end_lock;
3015 } else if( IS_LOCK_ERROR(lrc2) ){
3016 rc = lrc2;
3017 goto afp_end_lock;
3018 } else if( lrc1 != SQLITE_OK ) {
3019 rc = lrc1;
3020 } else {
3021 pFile->eFileLock = SHARED_LOCK;
3022 pInode->nLock++;
3023 pInode->nShared = 1;
3025 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
3026 /* We are trying for an exclusive lock but another thread in this
3027 ** same process is still holding a shared lock. */
3028 rc = SQLITE_BUSY;
3029 }else{
3030 /* The request was for a RESERVED or EXCLUSIVE lock. It is
3031 ** assumed that there is a SHARED or greater lock on the file
3032 ** already.
3034 int failed = 0;
3035 assert( 0!=pFile->eFileLock );
3036 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
3037 /* Acquire a RESERVED lock */
3038 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
3039 if( !failed ){
3040 context->reserved = 1;
3043 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
3044 /* Acquire an EXCLUSIVE lock */
3046 /* Remove the shared lock before trying the range. we'll need to
3047 ** reestablish the shared lock if we can't get the afpUnlock
3049 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
3050 pInode->sharedByte, 1, 0)) ){
3051 int failed2 = SQLITE_OK;
3052 /* now attemmpt to get the exclusive lock range */
3053 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
3054 SHARED_SIZE, 1);
3055 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
3056 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
3057 /* Can't reestablish the shared lock. Sqlite can't deal, this is
3058 ** a critical I/O error
3060 rc = ((failed & 0xff) == SQLITE_IOERR) ? failed2 :
3061 SQLITE_IOERR_LOCK;
3062 goto afp_end_lock;
3064 }else{
3065 rc = failed;
3068 if( failed ){
3069 rc = failed;
3073 if( rc==SQLITE_OK ){
3074 pFile->eFileLock = eFileLock;
3075 pInode->eFileLock = eFileLock;
3076 }else if( eFileLock==EXCLUSIVE_LOCK ){
3077 pFile->eFileLock = PENDING_LOCK;
3078 pInode->eFileLock = PENDING_LOCK;
3081 afp_end_lock:
3082 sqlite3_mutex_leave(pInode->pLockMutex);
3083 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
3084 rc==SQLITE_OK ? "ok" : "failed"));
3085 return rc;
3089 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
3090 ** must be either NO_LOCK or SHARED_LOCK.
3092 ** If the locking level of the file descriptor is already at or below
3093 ** the requested locking level, this routine is a no-op.
3095 static int afpUnlock(sqlite3_file *id, int eFileLock) {
3096 int rc = SQLITE_OK;
3097 unixFile *pFile = (unixFile*)id;
3098 unixInodeInfo *pInode;
3099 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
3100 int skipShared = 0;
3101 #ifdef SQLITE_TEST
3102 int h = pFile->h;
3103 #endif
3105 assert( pFile );
3106 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
3107 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
3108 osGetpid(0)));
3110 assert( eFileLock<=SHARED_LOCK );
3111 if( pFile->eFileLock<=eFileLock ){
3112 return SQLITE_OK;
3114 pInode = pFile->pInode;
3115 sqlite3_mutex_enter(pInode->pLockMutex);
3116 assert( pInode->nShared!=0 );
3117 if( pFile->eFileLock>SHARED_LOCK ){
3118 assert( pInode->eFileLock==pFile->eFileLock );
3119 SimulateIOErrorBenign(1);
3120 SimulateIOError( h=(-1) )
3121 SimulateIOErrorBenign(0);
3123 #ifdef SQLITE_DEBUG
3124 /* When reducing a lock such that other processes can start
3125 ** reading the database file again, make sure that the
3126 ** transaction counter was updated if any part of the database
3127 ** file changed. If the transaction counter is not updated,
3128 ** other connections to the same file might not realize that
3129 ** the file has changed and hence might not know to flush their
3130 ** cache. The use of a stale cache can lead to database corruption.
3132 assert( pFile->inNormalWrite==0
3133 || pFile->dbUpdate==0
3134 || pFile->transCntrChng==1 );
3135 pFile->inNormalWrite = 0;
3136 #endif
3138 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
3139 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
3140 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
3141 /* only re-establish the shared lock if necessary */
3142 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3143 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
3144 } else {
3145 skipShared = 1;
3148 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
3149 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
3151 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
3152 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
3153 if( !rc ){
3154 context->reserved = 0;
3157 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
3158 pInode->eFileLock = SHARED_LOCK;
3161 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
3163 /* Decrement the shared lock counter. Release the lock using an
3164 ** OS call only when all threads in this same process have released
3165 ** the lock.
3167 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3168 pInode->nShared--;
3169 if( pInode->nShared==0 ){
3170 SimulateIOErrorBenign(1);
3171 SimulateIOError( h=(-1) )
3172 SimulateIOErrorBenign(0);
3173 if( !skipShared ){
3174 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
3176 if( !rc ){
3177 pInode->eFileLock = NO_LOCK;
3178 pFile->eFileLock = NO_LOCK;
3181 if( rc==SQLITE_OK ){
3182 pInode->nLock--;
3183 assert( pInode->nLock>=0 );
3184 if( pInode->nLock==0 ) closePendingFds(pFile);
3188 sqlite3_mutex_leave(pInode->pLockMutex);
3189 if( rc==SQLITE_OK ){
3190 pFile->eFileLock = eFileLock;
3192 return rc;
3196 ** Close a file & cleanup AFP specific locking context
3198 static int afpClose(sqlite3_file *id) {
3199 int rc = SQLITE_OK;
3200 unixFile *pFile = (unixFile*)id;
3201 assert( id!=0 );
3202 afpUnlock(id, NO_LOCK);
3203 assert( unixFileMutexNotheld(pFile) );
3204 unixEnterMutex();
3205 if( pFile->pInode ){
3206 unixInodeInfo *pInode = pFile->pInode;
3207 sqlite3_mutex_enter(pInode->pLockMutex);
3208 if( pInode->nLock ){
3209 /* If there are outstanding locks, do not actually close the file just
3210 ** yet because that would clear those locks. Instead, add the file
3211 ** descriptor to pInode->aPending. It will be automatically closed when
3212 ** the last lock is cleared.
3214 setPendingFd(pFile);
3216 sqlite3_mutex_leave(pInode->pLockMutex);
3218 releaseInodeInfo(pFile);
3219 sqlite3_free(pFile->lockingContext);
3220 rc = closeUnixFile(id);
3221 unixLeaveMutex();
3222 return rc;
3225 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3227 ** The code above is the AFP lock implementation. The code is specific
3228 ** to MacOSX and does not work on other unix platforms. No alternative
3229 ** is available. If you don't compile for a mac, then the "unix-afp"
3230 ** VFS is not available.
3232 ********************* End of the AFP lock implementation **********************
3233 ******************************************************************************/
3235 /******************************************************************************
3236 *************************** Begin NFS Locking ********************************/
3238 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3240 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
3241 ** must be either NO_LOCK or SHARED_LOCK.
3243 ** If the locking level of the file descriptor is already at or below
3244 ** the requested locking level, this routine is a no-op.
3246 static int nfsUnlock(sqlite3_file *id, int eFileLock){
3247 return posixUnlock(id, eFileLock, 1);
3250 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3252 ** The code above is the NFS lock implementation. The code is specific
3253 ** to MacOSX and does not work on other unix platforms. No alternative
3254 ** is available.
3256 ********************* End of the NFS lock implementation **********************
3257 ******************************************************************************/
3259 /******************************************************************************
3260 **************** Non-locking sqlite3_file methods *****************************
3262 ** The next division contains implementations for all methods of the
3263 ** sqlite3_file object other than the locking methods. The locking
3264 ** methods were defined in divisions above (one locking method per
3265 ** division). Those methods that are common to all locking modes
3266 ** are gather together into this division.
3270 ** Seek to the offset passed as the second argument, then read cnt
3271 ** bytes into pBuf. Return the number of bytes actually read.
3273 ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3274 ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3275 ** one system to another. Since SQLite does not define USE_PREAD
3276 ** in any form by default, we will not attempt to define _XOPEN_SOURCE.
3277 ** See tickets #2741 and #2681.
3279 ** To avoid stomping the errno value on a failed read the lastErrno value
3280 ** is set before returning.
3282 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3283 int got;
3284 int prior = 0;
3285 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
3286 i64 newOffset;
3287 #endif
3288 TIMER_START;
3289 assert( cnt==(cnt&0x1ffff) );
3290 assert( id->h>2 );
3292 #if defined(USE_PREAD)
3293 got = osPread(id->h, pBuf, cnt, offset);
3294 SimulateIOError( got = -1 );
3295 #elif defined(USE_PREAD64)
3296 got = osPread64(id->h, pBuf, cnt, offset);
3297 SimulateIOError( got = -1 );
3298 #else
3299 newOffset = lseek(id->h, offset, SEEK_SET);
3300 SimulateIOError( newOffset = -1 );
3301 if( newOffset<0 ){
3302 storeLastErrno((unixFile*)id, errno);
3303 return -1;
3305 got = osRead(id->h, pBuf, cnt);
3306 #endif
3307 if( got==cnt ) break;
3308 if( got<0 ){
3309 if( errno==EINTR ){ got = 1; continue; }
3310 prior = 0;
3311 storeLastErrno((unixFile*)id, errno);
3312 break;
3313 }else if( got>0 ){
3314 cnt -= got;
3315 offset += got;
3316 prior += got;
3317 pBuf = (void*)(got + (char*)pBuf);
3319 }while( got>0 );
3320 TIMER_END;
3321 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3322 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3323 return got+prior;
3327 ** Read data from a file into a buffer. Return SQLITE_OK if all
3328 ** bytes were read successfully and SQLITE_IOERR if anything goes
3329 ** wrong.
3331 static int unixRead(
3332 sqlite3_file *id,
3333 void *pBuf,
3334 int amt,
3335 sqlite3_int64 offset
3337 unixFile *pFile = (unixFile *)id;
3338 int got;
3339 assert( id );
3340 assert( offset>=0 );
3341 assert( amt>0 );
3343 /* If this is a database file (not a journal, master-journal or temp
3344 ** file), the bytes in the locking range should never be read or written. */
3345 #if 0
3346 assert( pFile->pPreallocatedUnused==0
3347 || offset>=PENDING_BYTE+512
3348 || offset+amt<=PENDING_BYTE
3350 #endif
3352 #if SQLITE_MAX_MMAP_SIZE>0
3353 /* Deal with as much of this read request as possible by transfering
3354 ** data from the memory mapping using memcpy(). */
3355 if( offset<pFile->mmapSize ){
3356 if( offset+amt <= pFile->mmapSize ){
3357 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3358 return SQLITE_OK;
3359 }else{
3360 int nCopy = pFile->mmapSize - offset;
3361 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3362 pBuf = &((u8 *)pBuf)[nCopy];
3363 amt -= nCopy;
3364 offset += nCopy;
3367 #endif
3369 got = seekAndRead(pFile, offset, pBuf, amt);
3370 if( got==amt ){
3371 return SQLITE_OK;
3372 }else if( got<0 ){
3373 /* lastErrno set by seekAndRead */
3374 return SQLITE_IOERR_READ;
3375 }else{
3376 storeLastErrno(pFile, 0); /* not a system error */
3377 /* Unread parts of the buffer must be zero-filled */
3378 memset(&((char*)pBuf)[got], 0, amt-got);
3379 return SQLITE_IOERR_SHORT_READ;
3384 ** Attempt to seek the file-descriptor passed as the first argument to
3385 ** absolute offset iOff, then attempt to write nBuf bytes of data from
3386 ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3387 ** return the actual number of bytes written (which may be less than
3388 ** nBuf).
3390 static int seekAndWriteFd(
3391 int fd, /* File descriptor to write to */
3392 i64 iOff, /* File offset to begin writing at */
3393 const void *pBuf, /* Copy data from this buffer to the file */
3394 int nBuf, /* Size of buffer pBuf in bytes */
3395 int *piErrno /* OUT: Error number if error occurs */
3397 int rc = 0; /* Value returned by system call */
3399 assert( nBuf==(nBuf&0x1ffff) );
3400 assert( fd>2 );
3401 assert( piErrno!=0 );
3402 nBuf &= 0x1ffff;
3403 TIMER_START;
3405 #if defined(USE_PREAD)
3406 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
3407 #elif defined(USE_PREAD64)
3408 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
3409 #else
3411 i64 iSeek = lseek(fd, iOff, SEEK_SET);
3412 SimulateIOError( iSeek = -1 );
3413 if( iSeek<0 ){
3414 rc = -1;
3415 break;
3417 rc = osWrite(fd, pBuf, nBuf);
3418 }while( rc<0 && errno==EINTR );
3419 #endif
3421 TIMER_END;
3422 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3424 if( rc<0 ) *piErrno = errno;
3425 return rc;
3430 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
3431 ** Return the number of bytes actually read. Update the offset.
3433 ** To avoid stomping the errno value on a failed write the lastErrno value
3434 ** is set before returning.
3436 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
3437 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
3442 ** Write data from a buffer into a file. Return SQLITE_OK on success
3443 ** or some other error code on failure.
3445 static int unixWrite(
3446 sqlite3_file *id,
3447 const void *pBuf,
3448 int amt,
3449 sqlite3_int64 offset
3451 unixFile *pFile = (unixFile*)id;
3452 int wrote = 0;
3453 assert( id );
3454 assert( amt>0 );
3456 /* If this is a database file (not a journal, master-journal or temp
3457 ** file), the bytes in the locking range should never be read or written. */
3458 #if 0
3459 assert( pFile->pPreallocatedUnused==0
3460 || offset>=PENDING_BYTE+512
3461 || offset+amt<=PENDING_BYTE
3463 #endif
3465 #ifdef SQLITE_DEBUG
3466 /* If we are doing a normal write to a database file (as opposed to
3467 ** doing a hot-journal rollback or a write to some file other than a
3468 ** normal database file) then record the fact that the database
3469 ** has changed. If the transaction counter is modified, record that
3470 ** fact too.
3472 if( pFile->inNormalWrite ){
3473 pFile->dbUpdate = 1; /* The database has been modified */
3474 if( offset<=24 && offset+amt>=27 ){
3475 int rc;
3476 char oldCntr[4];
3477 SimulateIOErrorBenign(1);
3478 rc = seekAndRead(pFile, 24, oldCntr, 4);
3479 SimulateIOErrorBenign(0);
3480 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
3481 pFile->transCntrChng = 1; /* The transaction counter has changed */
3485 #endif
3487 #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
3488 /* Deal with as much of this write request as possible by transfering
3489 ** data from the memory mapping using memcpy(). */
3490 if( offset<pFile->mmapSize ){
3491 if( offset+amt <= pFile->mmapSize ){
3492 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3493 return SQLITE_OK;
3494 }else{
3495 int nCopy = pFile->mmapSize - offset;
3496 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3497 pBuf = &((u8 *)pBuf)[nCopy];
3498 amt -= nCopy;
3499 offset += nCopy;
3502 #endif
3504 while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
3505 amt -= wrote;
3506 offset += wrote;
3507 pBuf = &((char*)pBuf)[wrote];
3509 SimulateIOError(( wrote=(-1), amt=1 ));
3510 SimulateDiskfullError(( wrote=0, amt=1 ));
3512 if( amt>wrote ){
3513 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
3514 /* lastErrno set by seekAndWrite */
3515 return SQLITE_IOERR_WRITE;
3516 }else{
3517 storeLastErrno(pFile, 0); /* not a system error */
3518 return SQLITE_FULL;
3522 return SQLITE_OK;
3525 #ifdef SQLITE_TEST
3527 ** Count the number of fullsyncs and normal syncs. This is used to test
3528 ** that syncs and fullsyncs are occurring at the right times.
3530 int sqlite3_sync_count = 0;
3531 int sqlite3_fullsync_count = 0;
3532 #endif
3535 ** We do not trust systems to provide a working fdatasync(). Some do.
3536 ** Others do no. To be safe, we will stick with the (slightly slower)
3537 ** fsync(). If you know that your system does support fdatasync() correctly,
3538 ** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
3540 #if !defined(fdatasync) && !HAVE_FDATASYNC
3541 # define fdatasync fsync
3542 #endif
3545 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3546 ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3547 ** only available on Mac OS X. But that could change.
3549 #ifdef F_FULLFSYNC
3550 # define HAVE_FULLFSYNC 1
3551 #else
3552 # define HAVE_FULLFSYNC 0
3553 #endif
3557 ** The fsync() system call does not work as advertised on many
3558 ** unix systems. The following procedure is an attempt to make
3559 ** it work better.
3561 ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3562 ** for testing when we want to run through the test suite quickly.
3563 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3564 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3565 ** or power failure will likely corrupt the database file.
3567 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
3568 ** The idea behind dataOnly is that it should only write the file content
3569 ** to disk, not the inode. We only set dataOnly if the file size is
3570 ** unchanged since the file size is part of the inode. However,
3571 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
3572 ** file size has changed. The only real difference between fdatasync()
3573 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
3574 ** inode if the mtime or owner or other inode attributes have changed.
3575 ** We only care about the file size, not the other file attributes, so
3576 ** as far as SQLite is concerned, an fdatasync() is always adequate.
3577 ** So, we always use fdatasync() if it is available, regardless of
3578 ** the value of the dataOnly flag.
3580 static int full_fsync(int fd, int fullSync, int dataOnly){
3581 int rc;
3583 /* The following "ifdef/elif/else/" block has the same structure as
3584 ** the one below. It is replicated here solely to avoid cluttering
3585 ** up the real code with the UNUSED_PARAMETER() macros.
3587 #ifdef SQLITE_NO_SYNC
3588 UNUSED_PARAMETER(fd);
3589 UNUSED_PARAMETER(fullSync);
3590 UNUSED_PARAMETER(dataOnly);
3591 #elif HAVE_FULLFSYNC
3592 UNUSED_PARAMETER(dataOnly);
3593 #else
3594 UNUSED_PARAMETER(fullSync);
3595 UNUSED_PARAMETER(dataOnly);
3596 #endif
3598 /* Record the number of times that we do a normal fsync() and
3599 ** FULLSYNC. This is used during testing to verify that this procedure
3600 ** gets called with the correct arguments.
3602 #ifdef SQLITE_TEST
3603 if( fullSync ) sqlite3_fullsync_count++;
3604 sqlite3_sync_count++;
3605 #endif
3607 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3608 ** no-op. But go ahead and call fstat() to validate the file
3609 ** descriptor as we need a method to provoke a failure during
3610 ** coverate testing.
3612 #ifdef SQLITE_NO_SYNC
3614 struct stat buf;
3615 rc = osFstat(fd, &buf);
3617 #elif HAVE_FULLFSYNC
3618 if( fullSync ){
3619 rc = osFcntl(fd, F_FULLFSYNC, 0);
3620 }else{
3621 rc = 1;
3623 /* If the FULLFSYNC failed, fall back to attempting an fsync().
3624 ** It shouldn't be possible for fullfsync to fail on the local
3625 ** file system (on OSX), so failure indicates that FULLFSYNC
3626 ** isn't supported for this file system. So, attempt an fsync
3627 ** and (for now) ignore the overhead of a superfluous fcntl call.
3628 ** It'd be better to detect fullfsync support once and avoid
3629 ** the fcntl call every time sync is called.
3631 if( rc ) rc = fsync(fd);
3633 #elif defined(__APPLE__)
3634 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3635 ** so currently we default to the macro that redefines fdatasync to fsync
3637 rc = fsync(fd);
3638 #else
3639 rc = fdatasync(fd);
3640 #if OS_VXWORKS
3641 if( rc==-1 && errno==ENOTSUP ){
3642 rc = fsync(fd);
3644 #endif /* OS_VXWORKS */
3645 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3647 if( OS_VXWORKS && rc!= -1 ){
3648 rc = 0;
3650 return rc;
3654 ** Open a file descriptor to the directory containing file zFilename.
3655 ** If successful, *pFd is set to the opened file descriptor and
3656 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3657 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3658 ** value.
3660 ** The directory file descriptor is used for only one thing - to
3661 ** fsync() a directory to make sure file creation and deletion events
3662 ** are flushed to disk. Such fsyncs are not needed on newer
3663 ** journaling filesystems, but are required on older filesystems.
3665 ** This routine can be overridden using the xSetSysCall interface.
3666 ** The ability to override this routine was added in support of the
3667 ** chromium sandbox. Opening a directory is a security risk (we are
3668 ** told) so making it overrideable allows the chromium sandbox to
3669 ** replace this routine with a harmless no-op. To make this routine
3670 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3671 ** *pFd set to a negative number.
3673 ** If SQLITE_OK is returned, the caller is responsible for closing
3674 ** the file descriptor *pFd using close().
3676 static int openDirectory(const char *zFilename, int *pFd){
3677 int ii;
3678 int fd = -1;
3679 char zDirname[MAX_PATHNAME+1];
3681 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3682 for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
3683 if( ii>0 ){
3684 zDirname[ii] = '\0';
3685 }else{
3686 if( zDirname[0]!='/' ) zDirname[0] = '.';
3687 zDirname[1] = 0;
3689 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3690 if( fd>=0 ){
3691 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3693 *pFd = fd;
3694 if( fd>=0 ) return SQLITE_OK;
3695 return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
3699 ** Make sure all writes to a particular file are committed to disk.
3701 ** If dataOnly==0 then both the file itself and its metadata (file
3702 ** size, access time, etc) are synced. If dataOnly!=0 then only the
3703 ** file data is synced.
3705 ** Under Unix, also make sure that the directory entry for the file
3706 ** has been created by fsync-ing the directory that contains the file.
3707 ** If we do not do this and we encounter a power failure, the directory
3708 ** entry for the journal might not exist after we reboot. The next
3709 ** SQLite to access the file will not know that the journal exists (because
3710 ** the directory entry for the journal was never created) and the transaction
3711 ** will not roll back - possibly leading to database corruption.
3713 static int unixSync(sqlite3_file *id, int flags){
3714 int rc;
3715 unixFile *pFile = (unixFile*)id;
3717 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3718 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3720 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3721 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3722 || (flags&0x0F)==SQLITE_SYNC_FULL
3725 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3726 ** line is to test that doing so does not cause any problems.
3728 SimulateDiskfullError( return SQLITE_FULL );
3730 assert( pFile );
3731 OSTRACE(("SYNC %-3d\n", pFile->h));
3732 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3733 SimulateIOError( rc=1 );
3734 if( rc ){
3735 storeLastErrno(pFile, errno);
3736 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
3739 /* Also fsync the directory containing the file if the DIRSYNC flag
3740 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
3741 ** are unable to fsync a directory, so ignore errors on the fsync.
3743 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3744 int dirfd;
3745 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
3746 HAVE_FULLFSYNC, isFullsync));
3747 rc = osOpenDirectory(pFile->zPath, &dirfd);
3748 if( rc==SQLITE_OK ){
3749 full_fsync(dirfd, 0, 0);
3750 robust_close(pFile, dirfd, __LINE__);
3751 }else{
3752 assert( rc==SQLITE_CANTOPEN );
3753 rc = SQLITE_OK;
3755 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
3757 return rc;
3761 ** Truncate an open file to a specified size
3763 static int unixTruncate(sqlite3_file *id, i64 nByte){
3764 unixFile *pFile = (unixFile *)id;
3765 int rc;
3766 assert( pFile );
3767 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
3769 /* If the user has configured a chunk-size for this file, truncate the
3770 ** file so that it consists of an integer number of chunks (i.e. the
3771 ** actual file size after the operation may be larger than the requested
3772 ** size).
3774 if( pFile->szChunk>0 ){
3775 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3778 rc = robust_ftruncate(pFile->h, nByte);
3779 if( rc ){
3780 storeLastErrno(pFile, errno);
3781 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3782 }else{
3783 #ifdef SQLITE_DEBUG
3784 /* If we are doing a normal write to a database file (as opposed to
3785 ** doing a hot-journal rollback or a write to some file other than a
3786 ** normal database file) and we truncate the file to zero length,
3787 ** that effectively updates the change counter. This might happen
3788 ** when restoring a database using the backup API from a zero-length
3789 ** source.
3791 if( pFile->inNormalWrite && nByte==0 ){
3792 pFile->transCntrChng = 1;
3794 #endif
3796 #if SQLITE_MAX_MMAP_SIZE>0
3797 /* If the file was just truncated to a size smaller than the currently
3798 ** mapped region, reduce the effective mapping size as well. SQLite will
3799 ** use read() and write() to access data beyond this point from now on.
3801 if( nByte<pFile->mmapSize ){
3802 pFile->mmapSize = nByte;
3804 #endif
3806 return SQLITE_OK;
3811 ** Determine the current size of a file in bytes
3813 static int unixFileSize(sqlite3_file *id, i64 *pSize){
3814 int rc;
3815 struct stat buf;
3816 assert( id );
3817 rc = osFstat(((unixFile*)id)->h, &buf);
3818 SimulateIOError( rc=1 );
3819 if( rc!=0 ){
3820 storeLastErrno((unixFile*)id, errno);
3821 return SQLITE_IOERR_FSTAT;
3823 *pSize = buf.st_size;
3825 /* When opening a zero-size database, the findInodeInfo() procedure
3826 ** writes a single byte into that file in order to work around a bug
3827 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3828 ** layers, we need to report this file size as zero even though it is
3829 ** really 1. Ticket #3260.
3831 if( *pSize==1 ) *pSize = 0;
3834 return SQLITE_OK;
3837 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
3839 ** Handler for proxy-locking file-control verbs. Defined below in the
3840 ** proxying locking division.
3842 static int proxyFileControl(sqlite3_file*,int,void*);
3843 #endif
3846 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
3847 ** file-control operation. Enlarge the database to nBytes in size
3848 ** (rounded up to the next chunk-size). If the database is already
3849 ** nBytes or larger, this routine is a no-op.
3851 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
3852 if( pFile->szChunk>0 ){
3853 i64 nSize; /* Required file size */
3854 struct stat buf; /* Used to hold return values of fstat() */
3856 if( osFstat(pFile->h, &buf) ){
3857 return SQLITE_IOERR_FSTAT;
3860 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3861 if( nSize>(i64)buf.st_size ){
3863 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
3864 /* The code below is handling the return value of osFallocate()
3865 ** correctly. posix_fallocate() is defined to "returns zero on success,
3866 ** or an error number on failure". See the manpage for details. */
3867 int err;
3869 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3870 }while( err==EINTR );
3871 if( err && err!=EINVAL ) return SQLITE_IOERR_WRITE;
3872 #else
3873 /* If the OS does not have posix_fallocate(), fake it. Write a
3874 ** single byte to the last byte in each block that falls entirely
3875 ** within the extended region. Then, if required, a single byte
3876 ** at offset (nSize-1), to set the size of the file correctly.
3877 ** This is a similar technique to that used by glibc on systems
3878 ** that do not have a real fallocate() call.
3880 int nBlk = buf.st_blksize; /* File-system block size */
3881 int nWrite = 0; /* Number of bytes written by seekAndWrite */
3882 i64 iWrite; /* Next offset to write to */
3884 iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
3885 assert( iWrite>=buf.st_size );
3886 assert( ((iWrite+1)%nBlk)==0 );
3887 for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
3888 if( iWrite>=nSize ) iWrite = nSize - 1;
3889 nWrite = seekAndWrite(pFile, iWrite, "", 1);
3890 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
3892 #endif
3896 #if SQLITE_MAX_MMAP_SIZE>0
3897 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
3898 int rc;
3899 if( pFile->szChunk<=0 ){
3900 if( robust_ftruncate(pFile->h, nByte) ){
3901 storeLastErrno(pFile, errno);
3902 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3906 rc = unixMapfile(pFile, nByte);
3907 return rc;
3909 #endif
3911 return SQLITE_OK;
3915 ** If *pArg is initially negative then this is a query. Set *pArg to
3916 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3918 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3920 static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3921 if( *pArg<0 ){
3922 *pArg = (pFile->ctrlFlags & mask)!=0;
3923 }else if( (*pArg)==0 ){
3924 pFile->ctrlFlags &= ~mask;
3925 }else{
3926 pFile->ctrlFlags |= mask;
3930 /* Forward declaration */
3931 static int unixGetTempname(int nBuf, char *zBuf);
3934 ** Information and control of an open file handle.
3936 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
3937 unixFile *pFile = (unixFile*)id;
3938 switch( op ){
3939 #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
3940 case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: {
3941 int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE);
3942 return rc ? SQLITE_IOERR_BEGIN_ATOMIC : SQLITE_OK;
3944 case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: {
3945 int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE);
3946 return rc ? SQLITE_IOERR_COMMIT_ATOMIC : SQLITE_OK;
3948 case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: {
3949 int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE);
3950 return rc ? SQLITE_IOERR_ROLLBACK_ATOMIC : SQLITE_OK;
3952 #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
3954 case SQLITE_FCNTL_LOCKSTATE: {
3955 *(int*)pArg = pFile->eFileLock;
3956 return SQLITE_OK;
3958 case SQLITE_FCNTL_LAST_ERRNO: {
3959 *(int*)pArg = pFile->lastErrno;
3960 return SQLITE_OK;
3962 case SQLITE_FCNTL_CHUNK_SIZE: {
3963 pFile->szChunk = *(int *)pArg;
3964 return SQLITE_OK;
3966 case SQLITE_FCNTL_SIZE_HINT: {
3967 int rc;
3968 SimulateIOErrorBenign(1);
3969 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3970 SimulateIOErrorBenign(0);
3971 return rc;
3973 case SQLITE_FCNTL_PERSIST_WAL: {
3974 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3975 return SQLITE_OK;
3977 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3978 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
3979 return SQLITE_OK;
3981 case SQLITE_FCNTL_VFSNAME: {
3982 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3983 return SQLITE_OK;
3985 case SQLITE_FCNTL_TEMPFILENAME: {
3986 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
3987 if( zTFile ){
3988 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3989 *(char**)pArg = zTFile;
3991 return SQLITE_OK;
3993 case SQLITE_FCNTL_HAS_MOVED: {
3994 *(int*)pArg = fileHasMoved(pFile);
3995 return SQLITE_OK;
3997 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
3998 case SQLITE_FCNTL_LOCK_TIMEOUT: {
3999 int iOld = pFile->iBusyTimeout;
4000 pFile->iBusyTimeout = *(int*)pArg;
4001 *(int*)pArg = iOld;
4002 return SQLITE_OK;
4004 #endif
4005 #if SQLITE_MAX_MMAP_SIZE>0
4006 case SQLITE_FCNTL_MMAP_SIZE: {
4007 i64 newLimit = *(i64*)pArg;
4008 int rc = SQLITE_OK;
4009 if( newLimit>sqlite3GlobalConfig.mxMmap ){
4010 newLimit = sqlite3GlobalConfig.mxMmap;
4013 /* The value of newLimit may be eventually cast to (size_t) and passed
4014 ** to mmap(). Restrict its value to 2GB if (size_t) is not at least a
4015 ** 64-bit type. */
4016 if( newLimit>0 && sizeof(size_t)<8 ){
4017 newLimit = (newLimit & 0x7FFFFFFF);
4020 *(i64*)pArg = pFile->mmapSizeMax;
4021 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
4022 pFile->mmapSizeMax = newLimit;
4023 if( pFile->mmapSize>0 ){
4024 unixUnmapfile(pFile);
4025 rc = unixMapfile(pFile, -1);
4028 return rc;
4030 #endif
4031 #ifdef SQLITE_DEBUG
4032 /* The pager calls this method to signal that it has done
4033 ** a rollback and that the database is therefore unchanged and
4034 ** it hence it is OK for the transaction change counter to be
4035 ** unchanged.
4037 case SQLITE_FCNTL_DB_UNCHANGED: {
4038 ((unixFile*)id)->dbUpdate = 0;
4039 return SQLITE_OK;
4041 #endif
4042 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
4043 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
4044 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
4045 return proxyFileControl(id,op,pArg);
4047 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
4049 return SQLITE_NOTFOUND;
4053 ** If pFd->sectorSize is non-zero when this function is called, it is a
4054 ** no-op. Otherwise, the values of pFd->sectorSize and
4055 ** pFd->deviceCharacteristics are set according to the file-system
4056 ** characteristics.
4058 ** There are two versions of this function. One for QNX and one for all
4059 ** other systems.
4061 #ifndef __QNXNTO__
4062 static void setDeviceCharacteristics(unixFile *pFd){
4063 assert( pFd->deviceCharacteristics==0 || pFd->sectorSize!=0 );
4064 if( pFd->sectorSize==0 ){
4065 #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
4066 int res;
4067 u32 f = 0;
4069 /* Check for support for F2FS atomic batch writes. */
4070 res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES, &f);
4071 if( res==0 && (f & F2FS_FEATURE_ATOMIC_WRITE) ){
4072 pFd->deviceCharacteristics = SQLITE_IOCAP_BATCH_ATOMIC;
4074 #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
4076 /* Set the POWERSAFE_OVERWRITE flag if requested. */
4077 if( pFd->ctrlFlags & UNIXFILE_PSOW ){
4078 pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
4081 pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4084 #else
4085 #include <sys/dcmd_blk.h>
4086 #include <sys/statvfs.h>
4087 static void setDeviceCharacteristics(unixFile *pFile){
4088 if( pFile->sectorSize == 0 ){
4089 struct statvfs fsInfo;
4091 /* Set defaults for non-supported filesystems */
4092 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4093 pFile->deviceCharacteristics = 0;
4094 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
4095 return;
4098 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
4099 pFile->sectorSize = fsInfo.f_bsize;
4100 pFile->deviceCharacteristics =
4101 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
4102 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4103 ** the write succeeds */
4104 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4105 ** so it is ordered */
4107 }else if( strstr(fsInfo.f_basetype, "etfs") ){
4108 pFile->sectorSize = fsInfo.f_bsize;
4109 pFile->deviceCharacteristics =
4110 /* etfs cluster size writes are atomic */
4111 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
4112 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4113 ** the write succeeds */
4114 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4115 ** so it is ordered */
4117 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
4118 pFile->sectorSize = fsInfo.f_bsize;
4119 pFile->deviceCharacteristics =
4120 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
4121 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4122 ** the write succeeds */
4123 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4124 ** so it is ordered */
4126 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
4127 pFile->sectorSize = fsInfo.f_bsize;
4128 pFile->deviceCharacteristics =
4129 /* full bitset of atomics from max sector size and smaller */
4130 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
4131 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4132 ** so it is ordered */
4134 }else if( strstr(fsInfo.f_basetype, "dos") ){
4135 pFile->sectorSize = fsInfo.f_bsize;
4136 pFile->deviceCharacteristics =
4137 /* full bitset of atomics from max sector size and smaller */
4138 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
4139 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4140 ** so it is ordered */
4142 }else{
4143 pFile->deviceCharacteristics =
4144 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
4145 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4146 ** the write succeeds */
4150 /* Last chance verification. If the sector size isn't a multiple of 512
4151 ** then it isn't valid.*/
4152 if( pFile->sectorSize % 512 != 0 ){
4153 pFile->deviceCharacteristics = 0;
4154 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4157 #endif
4160 ** Return the sector size in bytes of the underlying block device for
4161 ** the specified file. This is almost always 512 bytes, but may be
4162 ** larger for some devices.
4164 ** SQLite code assumes this function cannot fail. It also assumes that
4165 ** if two files are created in the same file-system directory (i.e.
4166 ** a database and its journal file) that the sector size will be the
4167 ** same for both.
4169 static int unixSectorSize(sqlite3_file *id){
4170 unixFile *pFd = (unixFile*)id;
4171 setDeviceCharacteristics(pFd);
4172 return pFd->sectorSize;
4176 ** Return the device characteristics for the file.
4178 ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
4179 ** However, that choice is controversial since technically the underlying
4180 ** file system does not always provide powersafe overwrites. (In other
4181 ** words, after a power-loss event, parts of the file that were never
4182 ** written might end up being altered.) However, non-PSOW behavior is very,
4183 ** very rare. And asserting PSOW makes a large reduction in the amount
4184 ** of required I/O for journaling, since a lot of padding is eliminated.
4185 ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
4186 ** available to turn it off and URI query parameter available to turn it off.
4188 static int unixDeviceCharacteristics(sqlite3_file *id){
4189 unixFile *pFd = (unixFile*)id;
4190 setDeviceCharacteristics(pFd);
4191 return pFd->deviceCharacteristics;
4194 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
4197 ** Return the system page size.
4199 ** This function should not be called directly by other code in this file.
4200 ** Instead, it should be called via macro osGetpagesize().
4202 static int unixGetpagesize(void){
4203 #if OS_VXWORKS
4204 return 1024;
4205 #elif defined(_BSD_SOURCE)
4206 return getpagesize();
4207 #else
4208 return (int)sysconf(_SC_PAGESIZE);
4209 #endif
4212 #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
4214 #ifndef SQLITE_OMIT_WAL
4217 ** Object used to represent an shared memory buffer.
4219 ** When multiple threads all reference the same wal-index, each thread
4220 ** has its own unixShm object, but they all point to a single instance
4221 ** of this unixShmNode object. In other words, each wal-index is opened
4222 ** only once per process.
4224 ** Each unixShmNode object is connected to a single unixInodeInfo object.
4225 ** We could coalesce this object into unixInodeInfo, but that would mean
4226 ** every open file that does not use shared memory (in other words, most
4227 ** open files) would have to carry around this extra information. So
4228 ** the unixInodeInfo object contains a pointer to this unixShmNode object
4229 ** and the unixShmNode object is created only when needed.
4231 ** unixMutexHeld() must be true when creating or destroying
4232 ** this object or while reading or writing the following fields:
4234 ** nRef
4236 ** The following fields are read-only after the object is created:
4238 ** hShm
4239 ** zFilename
4241 ** Either unixShmNode.pShmMutex must be held or unixShmNode.nRef==0 and
4242 ** unixMutexHeld() is true when reading or writing any other field
4243 ** in this structure.
4245 struct unixShmNode {
4246 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
4247 sqlite3_mutex *pShmMutex; /* Mutex to access this object */
4248 char *zFilename; /* Name of the mmapped file */
4249 int hShm; /* Open file descriptor */
4250 int szRegion; /* Size of shared-memory regions */
4251 u16 nRegion; /* Size of array apRegion */
4252 u8 isReadonly; /* True if read-only */
4253 u8 isUnlocked; /* True if no DMS lock held */
4254 char **apRegion; /* Array of mapped shared-memory regions */
4255 int nRef; /* Number of unixShm objects pointing to this */
4256 unixShm *pFirst; /* All unixShm objects pointing to this */
4257 #ifdef SQLITE_DEBUG
4258 u8 exclMask; /* Mask of exclusive locks held */
4259 u8 sharedMask; /* Mask of shared locks held */
4260 u8 nextShmId; /* Next available unixShm.id value */
4261 #endif
4265 ** Structure used internally by this VFS to record the state of an
4266 ** open shared memory connection.
4268 ** The following fields are initialized when this object is created and
4269 ** are read-only thereafter:
4271 ** unixShm.pShmNode
4272 ** unixShm.id
4274 ** All other fields are read/write. The unixShm.pShmNode->pShmMutex must
4275 ** be held while accessing any read/write fields.
4277 struct unixShm {
4278 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4279 unixShm *pNext; /* Next unixShm with the same unixShmNode */
4280 u8 hasMutex; /* True if holding the unixShmNode->pShmMutex */
4281 u8 id; /* Id of this connection within its unixShmNode */
4282 u16 sharedMask; /* Mask of shared locks held */
4283 u16 exclMask; /* Mask of exclusive locks held */
4287 ** Constants used for locking
4289 #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
4290 #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
4293 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
4295 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4296 ** otherwise.
4298 static int unixShmSystemLock(
4299 unixFile *pFile, /* Open connection to the WAL file */
4300 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
4301 int ofst, /* First byte of the locking range */
4302 int n /* Number of bytes to lock */
4304 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4305 struct flock f; /* The posix advisory locking structure */
4306 int rc = SQLITE_OK; /* Result code form fcntl() */
4308 /* Access to the unixShmNode object is serialized by the caller */
4309 pShmNode = pFile->pInode->pShmNode;
4310 assert( pShmNode->nRef==0 || sqlite3_mutex_held(pShmNode->pShmMutex) );
4311 assert( pShmNode->nRef>0 || unixMutexHeld() );
4313 /* Shared locks never span more than one byte */
4314 assert( n==1 || lockType!=F_RDLCK );
4316 /* Locks are within range */
4317 assert( n>=1 && n<=SQLITE_SHM_NLOCK );
4319 if( pShmNode->hShm>=0 ){
4320 int res;
4321 /* Initialize the locking parameters */
4322 f.l_type = lockType;
4323 f.l_whence = SEEK_SET;
4324 f.l_start = ofst;
4325 f.l_len = n;
4326 res = osSetPosixAdvisoryLock(pShmNode->hShm, &f, pFile);
4327 if( res==-1 ){
4328 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
4329 rc = (pFile->iBusyTimeout ? SQLITE_BUSY_TIMEOUT : SQLITE_BUSY);
4330 #else
4331 rc = SQLITE_BUSY;
4332 #endif
4336 /* Update the global lock state and do debug tracing */
4337 #ifdef SQLITE_DEBUG
4338 { u16 mask;
4339 OSTRACE(("SHM-LOCK "));
4340 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
4341 if( rc==SQLITE_OK ){
4342 if( lockType==F_UNLCK ){
4343 OSTRACE(("unlock %d ok", ofst));
4344 pShmNode->exclMask &= ~mask;
4345 pShmNode->sharedMask &= ~mask;
4346 }else if( lockType==F_RDLCK ){
4347 OSTRACE(("read-lock %d ok", ofst));
4348 pShmNode->exclMask &= ~mask;
4349 pShmNode->sharedMask |= mask;
4350 }else{
4351 assert( lockType==F_WRLCK );
4352 OSTRACE(("write-lock %d ok", ofst));
4353 pShmNode->exclMask |= mask;
4354 pShmNode->sharedMask &= ~mask;
4356 }else{
4357 if( lockType==F_UNLCK ){
4358 OSTRACE(("unlock %d failed", ofst));
4359 }else if( lockType==F_RDLCK ){
4360 OSTRACE(("read-lock failed"));
4361 }else{
4362 assert( lockType==F_WRLCK );
4363 OSTRACE(("write-lock %d failed", ofst));
4366 OSTRACE((" - afterwards %03x,%03x\n",
4367 pShmNode->sharedMask, pShmNode->exclMask));
4369 #endif
4371 return rc;
4375 ** Return the minimum number of 32KB shm regions that should be mapped at
4376 ** a time, assuming that each mapping must be an integer multiple of the
4377 ** current system page-size.
4379 ** Usually, this is 1. The exception seems to be systems that are configured
4380 ** to use 64KB pages - in this case each mapping must cover at least two
4381 ** shm regions.
4383 static int unixShmRegionPerMap(void){
4384 int shmsz = 32*1024; /* SHM region size */
4385 int pgsz = osGetpagesize(); /* System page size */
4386 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4387 if( pgsz<shmsz ) return 1;
4388 return pgsz/shmsz;
4392 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
4394 ** This is not a VFS shared-memory method; it is a utility function called
4395 ** by VFS shared-memory methods.
4397 static void unixShmPurge(unixFile *pFd){
4398 unixShmNode *p = pFd->pInode->pShmNode;
4399 assert( unixMutexHeld() );
4400 if( p && ALWAYS(p->nRef==0) ){
4401 int nShmPerMap = unixShmRegionPerMap();
4402 int i;
4403 assert( p->pInode==pFd->pInode );
4404 sqlite3_mutex_free(p->pShmMutex);
4405 for(i=0; i<p->nRegion; i+=nShmPerMap){
4406 if( p->hShm>=0 ){
4407 osMunmap(p->apRegion[i], p->szRegion);
4408 }else{
4409 sqlite3_free(p->apRegion[i]);
4412 sqlite3_free(p->apRegion);
4413 if( p->hShm>=0 ){
4414 robust_close(pFd, p->hShm, __LINE__);
4415 p->hShm = -1;
4417 p->pInode->pShmNode = 0;
4418 sqlite3_free(p);
4423 ** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
4424 ** take it now. Return SQLITE_OK if successful, or an SQLite error
4425 ** code otherwise.
4427 ** If the DMS cannot be locked because this is a readonly_shm=1
4428 ** connection and no other process already holds a lock, return
4429 ** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
4431 static int unixLockSharedMemory(unixFile *pDbFd, unixShmNode *pShmNode){
4432 struct flock lock;
4433 int rc = SQLITE_OK;
4435 /* Use F_GETLK to determine the locks other processes are holding
4436 ** on the DMS byte. If it indicates that another process is holding
4437 ** a SHARED lock, then this process may also take a SHARED lock
4438 ** and proceed with opening the *-shm file.
4440 ** Or, if no other process is holding any lock, then this process
4441 ** is the first to open it. In this case take an EXCLUSIVE lock on the
4442 ** DMS byte and truncate the *-shm file to zero bytes in size. Then
4443 ** downgrade to a SHARED lock on the DMS byte.
4445 ** If another process is holding an EXCLUSIVE lock on the DMS byte,
4446 ** return SQLITE_BUSY to the caller (it will try again). An earlier
4447 ** version of this code attempted the SHARED lock at this point. But
4448 ** this introduced a subtle race condition: if the process holding
4449 ** EXCLUSIVE failed just before truncating the *-shm file, then this
4450 ** process might open and use the *-shm file without truncating it.
4451 ** And if the *-shm file has been corrupted by a power failure or
4452 ** system crash, the database itself may also become corrupt. */
4453 lock.l_whence = SEEK_SET;
4454 lock.l_start = UNIX_SHM_DMS;
4455 lock.l_len = 1;
4456 lock.l_type = F_WRLCK;
4457 if( osFcntl(pShmNode->hShm, F_GETLK, &lock)!=0 ) {
4458 rc = SQLITE_IOERR_LOCK;
4459 }else if( lock.l_type==F_UNLCK ){
4460 if( pShmNode->isReadonly ){
4461 pShmNode->isUnlocked = 1;
4462 rc = SQLITE_READONLY_CANTINIT;
4463 }else{
4464 rc = unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1);
4465 /* The first connection to attach must truncate the -shm file. We
4466 ** truncate to 3 bytes (an arbitrary small number, less than the
4467 ** -shm header size) rather than 0 as a system debugging aid, to
4468 ** help detect if a -shm file truncation is legitimate or is the work
4469 ** or a rogue process. */
4470 if( rc==SQLITE_OK && robust_ftruncate(pShmNode->hShm, 3) ){
4471 rc = unixLogError(SQLITE_IOERR_SHMOPEN,"ftruncate",pShmNode->zFilename);
4474 }else if( lock.l_type==F_WRLCK ){
4475 rc = SQLITE_BUSY;
4478 if( rc==SQLITE_OK ){
4479 assert( lock.l_type==F_UNLCK || lock.l_type==F_RDLCK );
4480 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
4482 return rc;
4486 ** Open a shared-memory area associated with open database file pDbFd.
4487 ** This particular implementation uses mmapped files.
4489 ** The file used to implement shared-memory is in the same directory
4490 ** as the open database file and has the same name as the open database
4491 ** file with the "-shm" suffix added. For example, if the database file
4492 ** is "/home/user1/config.db" then the file that is created and mmapped
4493 ** for shared memory will be called "/home/user1/config.db-shm".
4495 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
4496 ** some other tmpfs mount. But if a file in a different directory
4497 ** from the database file is used, then differing access permissions
4498 ** or a chroot() might cause two different processes on the same
4499 ** database to end up using different files for shared memory -
4500 ** meaning that their memory would not really be shared - resulting
4501 ** in database corruption. Nevertheless, this tmpfs file usage
4502 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4503 ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4504 ** option results in an incompatible build of SQLite; builds of SQLite
4505 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4506 ** same database file at the same time, database corruption will likely
4507 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4508 ** "unsupported" and may go away in a future SQLite release.
4510 ** When opening a new shared-memory file, if no other instances of that
4511 ** file are currently open, in this process or in other processes, then
4512 ** the file must be truncated to zero length or have its header cleared.
4514 ** If the original database file (pDbFd) is using the "unix-excl" VFS
4515 ** that means that an exclusive lock is held on the database file and
4516 ** that no other processes are able to read or write the database. In
4517 ** that case, we do not really need shared memory. No shared memory
4518 ** file is created. The shared memory will be simulated with heap memory.
4520 static int unixOpenSharedMemory(unixFile *pDbFd){
4521 struct unixShm *p = 0; /* The connection to be opened */
4522 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4523 int rc = SQLITE_OK; /* Result code */
4524 unixInodeInfo *pInode; /* The inode of fd */
4525 char *zShm; /* Name of the file used for SHM */
4526 int nShmFilename; /* Size of the SHM filename in bytes */
4528 /* Allocate space for the new unixShm object. */
4529 p = sqlite3_malloc64( sizeof(*p) );
4530 if( p==0 ) return SQLITE_NOMEM_BKPT;
4531 memset(p, 0, sizeof(*p));
4532 assert( pDbFd->pShm==0 );
4534 /* Check to see if a unixShmNode object already exists. Reuse an existing
4535 ** one if present. Create a new one if necessary.
4537 assert( unixFileMutexNotheld(pDbFd) );
4538 unixEnterMutex();
4539 pInode = pDbFd->pInode;
4540 pShmNode = pInode->pShmNode;
4541 if( pShmNode==0 ){
4542 struct stat sStat; /* fstat() info for database file */
4543 #ifndef SQLITE_SHM_DIRECTORY
4544 const char *zBasePath = pDbFd->zPath;
4545 #endif
4547 /* Call fstat() to figure out the permissions on the database file. If
4548 ** a new *-shm file is created, an attempt will be made to create it
4549 ** with the same permissions.
4551 if( osFstat(pDbFd->h, &sStat) ){
4552 rc = SQLITE_IOERR_FSTAT;
4553 goto shm_open_err;
4556 #ifdef SQLITE_SHM_DIRECTORY
4557 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
4558 #else
4559 nShmFilename = 6 + (int)strlen(zBasePath);
4560 #endif
4561 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
4562 if( pShmNode==0 ){
4563 rc = SQLITE_NOMEM_BKPT;
4564 goto shm_open_err;
4566 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
4567 zShm = pShmNode->zFilename = (char*)&pShmNode[1];
4568 #ifdef SQLITE_SHM_DIRECTORY
4569 sqlite3_snprintf(nShmFilename, zShm,
4570 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4571 (u32)sStat.st_ino, (u32)sStat.st_dev);
4572 #else
4573 sqlite3_snprintf(nShmFilename, zShm, "%s-shm", zBasePath);
4574 sqlite3FileSuffix3(pDbFd->zPath, zShm);
4575 #endif
4576 pShmNode->hShm = -1;
4577 pDbFd->pInode->pShmNode = pShmNode;
4578 pShmNode->pInode = pDbFd->pInode;
4579 if( sqlite3GlobalConfig.bCoreMutex ){
4580 pShmNode->pShmMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4581 if( pShmNode->pShmMutex==0 ){
4582 rc = SQLITE_NOMEM_BKPT;
4583 goto shm_open_err;
4587 if( pInode->bProcessLock==0 ){
4588 if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
4589 pShmNode->hShm = robust_open(zShm, O_RDWR|O_CREAT|O_NOFOLLOW,
4590 (sStat.st_mode&0777));
4592 if( pShmNode->hShm<0 ){
4593 pShmNode->hShm = robust_open(zShm, O_RDONLY|O_NOFOLLOW,
4594 (sStat.st_mode&0777));
4595 if( pShmNode->hShm<0 ){
4596 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShm);
4597 goto shm_open_err;
4599 pShmNode->isReadonly = 1;
4602 /* If this process is running as root, make sure that the SHM file
4603 ** is owned by the same user that owns the original database. Otherwise,
4604 ** the original owner will not be able to connect.
4606 robustFchown(pShmNode->hShm, sStat.st_uid, sStat.st_gid);
4608 rc = unixLockSharedMemory(pDbFd, pShmNode);
4609 if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
4613 /* Make the new connection a child of the unixShmNode */
4614 p->pShmNode = pShmNode;
4615 #ifdef SQLITE_DEBUG
4616 p->id = pShmNode->nextShmId++;
4617 #endif
4618 pShmNode->nRef++;
4619 pDbFd->pShm = p;
4620 unixLeaveMutex();
4622 /* The reference count on pShmNode has already been incremented under
4623 ** the cover of the unixEnterMutex() mutex and the pointer from the
4624 ** new (struct unixShm) object to the pShmNode has been set. All that is
4625 ** left to do is to link the new object into the linked list starting
4626 ** at pShmNode->pFirst. This must be done while holding the
4627 ** pShmNode->pShmMutex.
4629 sqlite3_mutex_enter(pShmNode->pShmMutex);
4630 p->pNext = pShmNode->pFirst;
4631 pShmNode->pFirst = p;
4632 sqlite3_mutex_leave(pShmNode->pShmMutex);
4633 return rc;
4635 /* Jump here on any error */
4636 shm_open_err:
4637 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
4638 sqlite3_free(p);
4639 unixLeaveMutex();
4640 return rc;
4644 ** This function is called to obtain a pointer to region iRegion of the
4645 ** shared-memory associated with the database file fd. Shared-memory regions
4646 ** are numbered starting from zero. Each shared-memory region is szRegion
4647 ** bytes in size.
4649 ** If an error occurs, an error code is returned and *pp is set to NULL.
4651 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4652 ** region has not been allocated (by any client, including one running in a
4653 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4654 ** bExtend is non-zero and the requested shared-memory region has not yet
4655 ** been allocated, it is allocated by this function.
4657 ** If the shared-memory region has already been allocated or is allocated by
4658 ** this call as described above, then it is mapped into this processes
4659 ** address space (if it is not already), *pp is set to point to the mapped
4660 ** memory and SQLITE_OK returned.
4662 static int unixShmMap(
4663 sqlite3_file *fd, /* Handle open on database file */
4664 int iRegion, /* Region to retrieve */
4665 int szRegion, /* Size of regions */
4666 int bExtend, /* True to extend file if necessary */
4667 void volatile **pp /* OUT: Mapped memory */
4669 unixFile *pDbFd = (unixFile*)fd;
4670 unixShm *p;
4671 unixShmNode *pShmNode;
4672 int rc = SQLITE_OK;
4673 int nShmPerMap = unixShmRegionPerMap();
4674 int nReqRegion;
4676 /* If the shared-memory file has not yet been opened, open it now. */
4677 if( pDbFd->pShm==0 ){
4678 rc = unixOpenSharedMemory(pDbFd);
4679 if( rc!=SQLITE_OK ) return rc;
4682 p = pDbFd->pShm;
4683 pShmNode = p->pShmNode;
4684 sqlite3_mutex_enter(pShmNode->pShmMutex);
4685 if( pShmNode->isUnlocked ){
4686 rc = unixLockSharedMemory(pDbFd, pShmNode);
4687 if( rc!=SQLITE_OK ) goto shmpage_out;
4688 pShmNode->isUnlocked = 0;
4690 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
4691 assert( pShmNode->pInode==pDbFd->pInode );
4692 assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );
4693 assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );
4695 /* Minimum number of regions required to be mapped. */
4696 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4698 if( pShmNode->nRegion<nReqRegion ){
4699 char **apNew; /* New apRegion[] array */
4700 int nByte = nReqRegion*szRegion; /* Minimum required file size */
4701 struct stat sStat; /* Used by fstat() */
4703 pShmNode->szRegion = szRegion;
4705 if( pShmNode->hShm>=0 ){
4706 /* The requested region is not mapped into this processes address space.
4707 ** Check to see if it has been allocated (i.e. if the wal-index file is
4708 ** large enough to contain the requested region).
4710 if( osFstat(pShmNode->hShm, &sStat) ){
4711 rc = SQLITE_IOERR_SHMSIZE;
4712 goto shmpage_out;
4715 if( sStat.st_size<nByte ){
4716 /* The requested memory region does not exist. If bExtend is set to
4717 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
4719 if( !bExtend ){
4720 goto shmpage_out;
4723 /* Alternatively, if bExtend is true, extend the file. Do this by
4724 ** writing a single byte to the end of each (OS) page being
4725 ** allocated or extended. Technically, we need only write to the
4726 ** last page in order to extend the file. But writing to all new
4727 ** pages forces the OS to allocate them immediately, which reduces
4728 ** the chances of SIGBUS while accessing the mapped region later on.
4730 else{
4731 static const int pgsz = 4096;
4732 int iPg;
4734 /* Write to the last byte of each newly allocated or extended page */
4735 assert( (nByte % pgsz)==0 );
4736 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
4737 int x = 0;
4738 if( seekAndWriteFd(pShmNode->hShm, iPg*pgsz + pgsz-1,"",1,&x)!=1 ){
4739 const char *zFile = pShmNode->zFilename;
4740 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4741 goto shmpage_out;
4748 /* Map the requested memory region into this processes address space. */
4749 apNew = (char **)sqlite3_realloc(
4750 pShmNode->apRegion, nReqRegion*sizeof(char *)
4752 if( !apNew ){
4753 rc = SQLITE_IOERR_NOMEM_BKPT;
4754 goto shmpage_out;
4756 pShmNode->apRegion = apNew;
4757 while( pShmNode->nRegion<nReqRegion ){
4758 int nMap = szRegion*nShmPerMap;
4759 int i;
4760 void *pMem;
4761 if( pShmNode->hShm>=0 ){
4762 pMem = osMmap(0, nMap,
4763 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
4764 MAP_SHARED, pShmNode->hShm, szRegion*(i64)pShmNode->nRegion
4766 if( pMem==MAP_FAILED ){
4767 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
4768 goto shmpage_out;
4770 }else{
4771 pMem = sqlite3_malloc64(nMap);
4772 if( pMem==0 ){
4773 rc = SQLITE_NOMEM_BKPT;
4774 goto shmpage_out;
4776 memset(pMem, 0, nMap);
4779 for(i=0; i<nShmPerMap; i++){
4780 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4782 pShmNode->nRegion += nShmPerMap;
4786 shmpage_out:
4787 if( pShmNode->nRegion>iRegion ){
4788 *pp = pShmNode->apRegion[iRegion];
4789 }else{
4790 *pp = 0;
4792 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
4793 sqlite3_mutex_leave(pShmNode->pShmMutex);
4794 return rc;
4798 ** Change the lock state for a shared-memory segment.
4800 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4801 ** different here than in posix. In xShmLock(), one can go from unlocked
4802 ** to shared and back or from unlocked to exclusive and back. But one may
4803 ** not go from shared to exclusive or from exclusive to shared.
4805 static int unixShmLock(
4806 sqlite3_file *fd, /* Database file holding the shared memory */
4807 int ofst, /* First lock to acquire or release */
4808 int n, /* Number of locks to acquire or release */
4809 int flags /* What to do with the lock */
4811 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4812 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4813 unixShm *pX; /* For looping over all siblings */
4814 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4815 int rc = SQLITE_OK; /* Result code */
4816 u16 mask; /* Mask of locks to take or release */
4818 assert( pShmNode==pDbFd->pInode->pShmNode );
4819 assert( pShmNode->pInode==pDbFd->pInode );
4820 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
4821 assert( n>=1 );
4822 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4823 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4824 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4825 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4826 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
4827 assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );
4828 assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );
4830 /* Check that, if this to be a blocking lock, no locks that occur later
4831 ** in the following list than the lock being obtained are already held:
4833 ** 1. Checkpointer lock (ofst==1).
4834 ** 2. Write lock (ofst==0).
4835 ** 3. Read locks (ofst>=3 && ofst<SQLITE_SHM_NLOCK).
4837 ** In other words, if this is a blocking lock, none of the locks that
4838 ** occur later in the above list than the lock being obtained may be
4839 ** held. */
4840 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
4841 assert( (flags & SQLITE_SHM_UNLOCK) || pDbFd->iBusyTimeout==0 || (
4842 (ofst!=2) /* not RECOVER */
4843 && (ofst!=1 || (p->exclMask|p->sharedMask)==0)
4844 && (ofst!=0 || (p->exclMask|p->sharedMask)<3)
4845 && (ofst<3 || (p->exclMask|p->sharedMask)<(1<<ofst))
4847 #endif
4849 mask = (1<<(ofst+n)) - (1<<ofst);
4850 assert( n>1 || mask==(1<<ofst) );
4851 sqlite3_mutex_enter(pShmNode->pShmMutex);
4852 if( flags & SQLITE_SHM_UNLOCK ){
4853 u16 allMask = 0; /* Mask of locks held by siblings */
4855 /* See if any siblings hold this same lock */
4856 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4857 if( pX==p ) continue;
4858 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4859 allMask |= pX->sharedMask;
4862 /* Unlock the system-level locks */
4863 if( (mask & allMask)==0 ){
4864 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
4865 }else{
4866 rc = SQLITE_OK;
4869 /* Undo the local locks */
4870 if( rc==SQLITE_OK ){
4871 p->exclMask &= ~mask;
4872 p->sharedMask &= ~mask;
4874 }else if( flags & SQLITE_SHM_SHARED ){
4875 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4877 /* Find out which shared locks are already held by sibling connections.
4878 ** If any sibling already holds an exclusive lock, go ahead and return
4879 ** SQLITE_BUSY.
4881 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4882 if( (pX->exclMask & mask)!=0 ){
4883 rc = SQLITE_BUSY;
4884 break;
4886 allShared |= pX->sharedMask;
4889 /* Get shared locks at the system level, if necessary */
4890 if( rc==SQLITE_OK ){
4891 if( (allShared & mask)==0 ){
4892 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
4893 }else{
4894 rc = SQLITE_OK;
4898 /* Get the local shared locks */
4899 if( rc==SQLITE_OK ){
4900 p->sharedMask |= mask;
4902 }else{
4903 /* Make sure no sibling connections hold locks that will block this
4904 ** lock. If any do, return SQLITE_BUSY right away.
4906 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4907 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4908 rc = SQLITE_BUSY;
4909 break;
4913 /* Get the exclusive locks at the system level. Then if successful
4914 ** also mark the local connection as being locked.
4916 if( rc==SQLITE_OK ){
4917 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
4918 if( rc==SQLITE_OK ){
4919 assert( (p->sharedMask & mask)==0 );
4920 p->exclMask |= mask;
4924 sqlite3_mutex_leave(pShmNode->pShmMutex);
4925 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4926 p->id, osGetpid(0), p->sharedMask, p->exclMask));
4927 return rc;
4931 ** Implement a memory barrier or memory fence on shared memory.
4933 ** All loads and stores begun before the barrier must complete before
4934 ** any load or store begun after the barrier.
4936 static void unixShmBarrier(
4937 sqlite3_file *fd /* Database file holding the shared memory */
4939 UNUSED_PARAMETER(fd);
4940 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
4941 assert( fd->pMethods->xLock==nolockLock
4942 || unixFileMutexNotheld((unixFile*)fd)
4944 unixEnterMutex(); /* Also mutex, for redundancy */
4945 unixLeaveMutex();
4949 ** Close a connection to shared-memory. Delete the underlying
4950 ** storage if deleteFlag is true.
4952 ** If there is no shared memory associated with the connection then this
4953 ** routine is a harmless no-op.
4955 static int unixShmUnmap(
4956 sqlite3_file *fd, /* The underlying database file */
4957 int deleteFlag /* Delete shared-memory if true */
4959 unixShm *p; /* The connection to be closed */
4960 unixShmNode *pShmNode; /* The underlying shared-memory file */
4961 unixShm **pp; /* For looping over sibling connections */
4962 unixFile *pDbFd; /* The underlying database file */
4964 pDbFd = (unixFile*)fd;
4965 p = pDbFd->pShm;
4966 if( p==0 ) return SQLITE_OK;
4967 pShmNode = p->pShmNode;
4969 assert( pShmNode==pDbFd->pInode->pShmNode );
4970 assert( pShmNode->pInode==pDbFd->pInode );
4972 /* Remove connection p from the set of connections associated
4973 ** with pShmNode */
4974 sqlite3_mutex_enter(pShmNode->pShmMutex);
4975 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4976 *pp = p->pNext;
4978 /* Free the connection p */
4979 sqlite3_free(p);
4980 pDbFd->pShm = 0;
4981 sqlite3_mutex_leave(pShmNode->pShmMutex);
4983 /* If pShmNode->nRef has reached 0, then close the underlying
4984 ** shared-memory file, too */
4985 assert( unixFileMutexNotheld(pDbFd) );
4986 unixEnterMutex();
4987 assert( pShmNode->nRef>0 );
4988 pShmNode->nRef--;
4989 if( pShmNode->nRef==0 ){
4990 if( deleteFlag && pShmNode->hShm>=0 ){
4991 osUnlink(pShmNode->zFilename);
4993 unixShmPurge(pDbFd);
4995 unixLeaveMutex();
4997 return SQLITE_OK;
5001 #else
5002 # define unixShmMap 0
5003 # define unixShmLock 0
5004 # define unixShmBarrier 0
5005 # define unixShmUnmap 0
5006 #endif /* #ifndef SQLITE_OMIT_WAL */
5008 #if SQLITE_MAX_MMAP_SIZE>0
5010 ** If it is currently memory mapped, unmap file pFd.
5012 static void unixUnmapfile(unixFile *pFd){
5013 assert( pFd->nFetchOut==0 );
5014 if( pFd->pMapRegion ){
5015 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
5016 pFd->pMapRegion = 0;
5017 pFd->mmapSize = 0;
5018 pFd->mmapSizeActual = 0;
5023 ** Attempt to set the size of the memory mapping maintained by file
5024 ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
5026 ** If successful, this function sets the following variables:
5028 ** unixFile.pMapRegion
5029 ** unixFile.mmapSize
5030 ** unixFile.mmapSizeActual
5032 ** If unsuccessful, an error message is logged via sqlite3_log() and
5033 ** the three variables above are zeroed. In this case SQLite should
5034 ** continue accessing the database using the xRead() and xWrite()
5035 ** methods.
5037 static void unixRemapfile(
5038 unixFile *pFd, /* File descriptor object */
5039 i64 nNew /* Required mapping size */
5041 const char *zErr = "mmap";
5042 int h = pFd->h; /* File descriptor open on db file */
5043 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
5044 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
5045 u8 *pNew = 0; /* Location of new mapping */
5046 int flags = PROT_READ; /* Flags to pass to mmap() */
5048 assert( pFd->nFetchOut==0 );
5049 assert( nNew>pFd->mmapSize );
5050 assert( nNew<=pFd->mmapSizeMax );
5051 assert( nNew>0 );
5052 assert( pFd->mmapSizeActual>=pFd->mmapSize );
5053 assert( MAP_FAILED!=0 );
5055 #ifdef SQLITE_MMAP_READWRITE
5056 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
5057 #endif
5059 if( pOrig ){
5060 #if HAVE_MREMAP
5061 i64 nReuse = pFd->mmapSize;
5062 #else
5063 const int szSyspage = osGetpagesize();
5064 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
5065 #endif
5066 u8 *pReq = &pOrig[nReuse];
5068 /* Unmap any pages of the existing mapping that cannot be reused. */
5069 if( nReuse!=nOrig ){
5070 osMunmap(pReq, nOrig-nReuse);
5073 #if HAVE_MREMAP
5074 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
5075 zErr = "mremap";
5076 #else
5077 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
5078 if( pNew!=MAP_FAILED ){
5079 if( pNew!=pReq ){
5080 osMunmap(pNew, nNew - nReuse);
5081 pNew = 0;
5082 }else{
5083 pNew = pOrig;
5086 #endif
5088 /* The attempt to extend the existing mapping failed. Free it. */
5089 if( pNew==MAP_FAILED || pNew==0 ){
5090 osMunmap(pOrig, nReuse);
5094 /* If pNew is still NULL, try to create an entirely new mapping. */
5095 if( pNew==0 ){
5096 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
5099 if( pNew==MAP_FAILED ){
5100 pNew = 0;
5101 nNew = 0;
5102 unixLogError(SQLITE_OK, zErr, pFd->zPath);
5104 /* If the mmap() above failed, assume that all subsequent mmap() calls
5105 ** will probably fail too. Fall back to using xRead/xWrite exclusively
5106 ** in this case. */
5107 pFd->mmapSizeMax = 0;
5109 pFd->pMapRegion = (void *)pNew;
5110 pFd->mmapSize = pFd->mmapSizeActual = nNew;
5114 ** Memory map or remap the file opened by file-descriptor pFd (if the file
5115 ** is already mapped, the existing mapping is replaced by the new). Or, if
5116 ** there already exists a mapping for this file, and there are still
5117 ** outstanding xFetch() references to it, this function is a no-op.
5119 ** If parameter nByte is non-negative, then it is the requested size of
5120 ** the mapping to create. Otherwise, if nByte is less than zero, then the
5121 ** requested size is the size of the file on disk. The actual size of the
5122 ** created mapping is either the requested size or the value configured
5123 ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
5125 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
5126 ** recreated as a result of outstanding references) or an SQLite error
5127 ** code otherwise.
5129 static int unixMapfile(unixFile *pFd, i64 nMap){
5130 assert( nMap>=0 || pFd->nFetchOut==0 );
5131 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
5132 if( pFd->nFetchOut>0 ) return SQLITE_OK;
5134 if( nMap<0 ){
5135 struct stat statbuf; /* Low-level file information */
5136 if( osFstat(pFd->h, &statbuf) ){
5137 return SQLITE_IOERR_FSTAT;
5139 nMap = statbuf.st_size;
5141 if( nMap>pFd->mmapSizeMax ){
5142 nMap = pFd->mmapSizeMax;
5145 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
5146 if( nMap!=pFd->mmapSize ){
5147 unixRemapfile(pFd, nMap);
5150 return SQLITE_OK;
5152 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
5155 ** If possible, return a pointer to a mapping of file fd starting at offset
5156 ** iOff. The mapping must be valid for at least nAmt bytes.
5158 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
5159 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
5160 ** Finally, if an error does occur, return an SQLite error code. The final
5161 ** value of *pp is undefined in this case.
5163 ** If this function does return a pointer, the caller must eventually
5164 ** release the reference by calling unixUnfetch().
5166 static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
5167 #if SQLITE_MAX_MMAP_SIZE>0
5168 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
5169 #endif
5170 *pp = 0;
5172 #if SQLITE_MAX_MMAP_SIZE>0
5173 if( pFd->mmapSizeMax>0 ){
5174 if( pFd->pMapRegion==0 ){
5175 int rc = unixMapfile(pFd, -1);
5176 if( rc!=SQLITE_OK ) return rc;
5178 if( pFd->mmapSize >= iOff+nAmt ){
5179 *pp = &((u8 *)pFd->pMapRegion)[iOff];
5180 pFd->nFetchOut++;
5183 #endif
5184 return SQLITE_OK;
5188 ** If the third argument is non-NULL, then this function releases a
5189 ** reference obtained by an earlier call to unixFetch(). The second
5190 ** argument passed to this function must be the same as the corresponding
5191 ** argument that was passed to the unixFetch() invocation.
5193 ** Or, if the third argument is NULL, then this function is being called
5194 ** to inform the VFS layer that, according to POSIX, any existing mapping
5195 ** may now be invalid and should be unmapped.
5197 static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
5198 #if SQLITE_MAX_MMAP_SIZE>0
5199 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
5200 UNUSED_PARAMETER(iOff);
5202 /* If p==0 (unmap the entire file) then there must be no outstanding
5203 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
5204 ** then there must be at least one outstanding. */
5205 assert( (p==0)==(pFd->nFetchOut==0) );
5207 /* If p!=0, it must match the iOff value. */
5208 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
5210 if( p ){
5211 pFd->nFetchOut--;
5212 }else{
5213 unixUnmapfile(pFd);
5216 assert( pFd->nFetchOut>=0 );
5217 #else
5218 UNUSED_PARAMETER(fd);
5219 UNUSED_PARAMETER(p);
5220 UNUSED_PARAMETER(iOff);
5221 #endif
5222 return SQLITE_OK;
5226 ** Here ends the implementation of all sqlite3_file methods.
5228 ********************** End sqlite3_file Methods *******************************
5229 ******************************************************************************/
5232 ** This division contains definitions of sqlite3_io_methods objects that
5233 ** implement various file locking strategies. It also contains definitions
5234 ** of "finder" functions. A finder-function is used to locate the appropriate
5235 ** sqlite3_io_methods object for a particular database file. The pAppData
5236 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
5237 ** the correct finder-function for that VFS.
5239 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
5240 ** object. The only interesting finder-function is autolockIoFinder, which
5241 ** looks at the filesystem type and tries to guess the best locking
5242 ** strategy from that.
5244 ** For finder-function F, two objects are created:
5246 ** (1) The real finder-function named "FImpt()".
5248 ** (2) A constant pointer to this function named just "F".
5251 ** A pointer to the F pointer is used as the pAppData value for VFS
5252 ** objects. We have to do this instead of letting pAppData point
5253 ** directly at the finder-function since C90 rules prevent a void*
5254 ** from be cast into a function pointer.
5257 ** Each instance of this macro generates two objects:
5259 ** * A constant sqlite3_io_methods object call METHOD that has locking
5260 ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
5262 ** * An I/O method finder function called FINDER that returns a pointer
5263 ** to the METHOD object in the previous bullet.
5265 #define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
5266 static const sqlite3_io_methods METHOD = { \
5267 VERSION, /* iVersion */ \
5268 CLOSE, /* xClose */ \
5269 unixRead, /* xRead */ \
5270 unixWrite, /* xWrite */ \
5271 unixTruncate, /* xTruncate */ \
5272 unixSync, /* xSync */ \
5273 unixFileSize, /* xFileSize */ \
5274 LOCK, /* xLock */ \
5275 UNLOCK, /* xUnlock */ \
5276 CKLOCK, /* xCheckReservedLock */ \
5277 unixFileControl, /* xFileControl */ \
5278 unixSectorSize, /* xSectorSize */ \
5279 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
5280 SHMMAP, /* xShmMap */ \
5281 unixShmLock, /* xShmLock */ \
5282 unixShmBarrier, /* xShmBarrier */ \
5283 unixShmUnmap, /* xShmUnmap */ \
5284 unixFetch, /* xFetch */ \
5285 unixUnfetch, /* xUnfetch */ \
5286 }; \
5287 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
5288 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
5289 return &METHOD; \
5291 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
5292 = FINDER##Impl;
5295 ** Here are all of the sqlite3_io_methods objects for each of the
5296 ** locking strategies. Functions that return pointers to these methods
5297 ** are also created.
5299 IOMETHODS(
5300 posixIoFinder, /* Finder function name */
5301 posixIoMethods, /* sqlite3_io_methods object name */
5302 3, /* shared memory and mmap are enabled */
5303 unixClose, /* xClose method */
5304 unixLock, /* xLock method */
5305 unixUnlock, /* xUnlock method */
5306 unixCheckReservedLock, /* xCheckReservedLock method */
5307 unixShmMap /* xShmMap method */
5309 IOMETHODS(
5310 nolockIoFinder, /* Finder function name */
5311 nolockIoMethods, /* sqlite3_io_methods object name */
5312 3, /* shared memory and mmap are enabled */
5313 nolockClose, /* xClose method */
5314 nolockLock, /* xLock method */
5315 nolockUnlock, /* xUnlock method */
5316 nolockCheckReservedLock, /* xCheckReservedLock method */
5317 0 /* xShmMap method */
5319 IOMETHODS(
5320 dotlockIoFinder, /* Finder function name */
5321 dotlockIoMethods, /* sqlite3_io_methods object name */
5322 1, /* shared memory is disabled */
5323 dotlockClose, /* xClose method */
5324 dotlockLock, /* xLock method */
5325 dotlockUnlock, /* xUnlock method */
5326 dotlockCheckReservedLock, /* xCheckReservedLock method */
5327 0 /* xShmMap method */
5330 #if SQLITE_ENABLE_LOCKING_STYLE
5331 IOMETHODS(
5332 flockIoFinder, /* Finder function name */
5333 flockIoMethods, /* sqlite3_io_methods object name */
5334 1, /* shared memory is disabled */
5335 flockClose, /* xClose method */
5336 flockLock, /* xLock method */
5337 flockUnlock, /* xUnlock method */
5338 flockCheckReservedLock, /* xCheckReservedLock method */
5339 0 /* xShmMap method */
5341 #endif
5343 #if OS_VXWORKS
5344 IOMETHODS(
5345 semIoFinder, /* Finder function name */
5346 semIoMethods, /* sqlite3_io_methods object name */
5347 1, /* shared memory is disabled */
5348 semXClose, /* xClose method */
5349 semXLock, /* xLock method */
5350 semXUnlock, /* xUnlock method */
5351 semXCheckReservedLock, /* xCheckReservedLock method */
5352 0 /* xShmMap method */
5354 #endif
5356 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5357 IOMETHODS(
5358 afpIoFinder, /* Finder function name */
5359 afpIoMethods, /* sqlite3_io_methods object name */
5360 1, /* shared memory is disabled */
5361 afpClose, /* xClose method */
5362 afpLock, /* xLock method */
5363 afpUnlock, /* xUnlock method */
5364 afpCheckReservedLock, /* xCheckReservedLock method */
5365 0 /* xShmMap method */
5367 #endif
5370 ** The proxy locking method is a "super-method" in the sense that it
5371 ** opens secondary file descriptors for the conch and lock files and
5372 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
5373 ** secondary files. For this reason, the division that implements
5374 ** proxy locking is located much further down in the file. But we need
5375 ** to go ahead and define the sqlite3_io_methods and finder function
5376 ** for proxy locking here. So we forward declare the I/O methods.
5378 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5379 static int proxyClose(sqlite3_file*);
5380 static int proxyLock(sqlite3_file*, int);
5381 static int proxyUnlock(sqlite3_file*, int);
5382 static int proxyCheckReservedLock(sqlite3_file*, int*);
5383 IOMETHODS(
5384 proxyIoFinder, /* Finder function name */
5385 proxyIoMethods, /* sqlite3_io_methods object name */
5386 1, /* shared memory is disabled */
5387 proxyClose, /* xClose method */
5388 proxyLock, /* xLock method */
5389 proxyUnlock, /* xUnlock method */
5390 proxyCheckReservedLock, /* xCheckReservedLock method */
5391 0 /* xShmMap method */
5393 #endif
5395 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5396 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5397 IOMETHODS(
5398 nfsIoFinder, /* Finder function name */
5399 nfsIoMethods, /* sqlite3_io_methods object name */
5400 1, /* shared memory is disabled */
5401 unixClose, /* xClose method */
5402 unixLock, /* xLock method */
5403 nfsUnlock, /* xUnlock method */
5404 unixCheckReservedLock, /* xCheckReservedLock method */
5405 0 /* xShmMap method */
5407 #endif
5409 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5411 ** This "finder" function attempts to determine the best locking strategy
5412 ** for the database file "filePath". It then returns the sqlite3_io_methods
5413 ** object that implements that strategy.
5415 ** This is for MacOSX only.
5417 static const sqlite3_io_methods *autolockIoFinderImpl(
5418 const char *filePath, /* name of the database file */
5419 unixFile *pNew /* open file object for the database file */
5421 static const struct Mapping {
5422 const char *zFilesystem; /* Filesystem type name */
5423 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
5424 } aMap[] = {
5425 { "hfs", &posixIoMethods },
5426 { "ufs", &posixIoMethods },
5427 { "afpfs", &afpIoMethods },
5428 { "smbfs", &afpIoMethods },
5429 { "webdav", &nolockIoMethods },
5430 { 0, 0 }
5432 int i;
5433 struct statfs fsInfo;
5434 struct flock lockInfo;
5436 if( !filePath ){
5437 /* If filePath==NULL that means we are dealing with a transient file
5438 ** that does not need to be locked. */
5439 return &nolockIoMethods;
5441 if( statfs(filePath, &fsInfo) != -1 ){
5442 if( fsInfo.f_flags & MNT_RDONLY ){
5443 return &nolockIoMethods;
5445 for(i=0; aMap[i].zFilesystem; i++){
5446 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5447 return aMap[i].pMethods;
5452 /* Default case. Handles, amongst others, "nfs".
5453 ** Test byte-range lock using fcntl(). If the call succeeds,
5454 ** assume that the file-system supports POSIX style locks.
5456 lockInfo.l_len = 1;
5457 lockInfo.l_start = 0;
5458 lockInfo.l_whence = SEEK_SET;
5459 lockInfo.l_type = F_RDLCK;
5460 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
5461 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5462 return &nfsIoMethods;
5463 } else {
5464 return &posixIoMethods;
5466 }else{
5467 return &dotlockIoMethods;
5470 static const sqlite3_io_methods
5471 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
5473 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
5475 #if OS_VXWORKS
5477 ** This "finder" function for VxWorks checks to see if posix advisory
5478 ** locking works. If it does, then that is what is used. If it does not
5479 ** work, then fallback to named semaphore locking.
5481 static const sqlite3_io_methods *vxworksIoFinderImpl(
5482 const char *filePath, /* name of the database file */
5483 unixFile *pNew /* the open file object */
5485 struct flock lockInfo;
5487 if( !filePath ){
5488 /* If filePath==NULL that means we are dealing with a transient file
5489 ** that does not need to be locked. */
5490 return &nolockIoMethods;
5493 /* Test if fcntl() is supported and use POSIX style locks.
5494 ** Otherwise fall back to the named semaphore method.
5496 lockInfo.l_len = 1;
5497 lockInfo.l_start = 0;
5498 lockInfo.l_whence = SEEK_SET;
5499 lockInfo.l_type = F_RDLCK;
5500 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
5501 return &posixIoMethods;
5502 }else{
5503 return &semIoMethods;
5506 static const sqlite3_io_methods
5507 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
5509 #endif /* OS_VXWORKS */
5512 ** An abstract type for a pointer to an IO method finder function:
5514 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
5517 /****************************************************************************
5518 **************************** sqlite3_vfs methods ****************************
5520 ** This division contains the implementation of methods on the
5521 ** sqlite3_vfs object.
5525 ** Initialize the contents of the unixFile structure pointed to by pId.
5527 static int fillInUnixFile(
5528 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5529 int h, /* Open file descriptor of file being opened */
5530 sqlite3_file *pId, /* Write to the unixFile structure here */
5531 const char *zFilename, /* Name of the file being opened */
5532 int ctrlFlags /* Zero or more UNIXFILE_* values */
5534 const sqlite3_io_methods *pLockingStyle;
5535 unixFile *pNew = (unixFile *)pId;
5536 int rc = SQLITE_OK;
5538 assert( pNew->pInode==NULL );
5540 /* No locking occurs in temporary files */
5541 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
5543 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
5544 pNew->h = h;
5545 pNew->pVfs = pVfs;
5546 pNew->zPath = zFilename;
5547 pNew->ctrlFlags = (u8)ctrlFlags;
5548 #if SQLITE_MAX_MMAP_SIZE>0
5549 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
5550 #endif
5551 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5552 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
5553 pNew->ctrlFlags |= UNIXFILE_PSOW;
5555 if( strcmp(pVfs->zName,"unix-excl")==0 ){
5556 pNew->ctrlFlags |= UNIXFILE_EXCL;
5559 #if OS_VXWORKS
5560 pNew->pId = vxworksFindFileId(zFilename);
5561 if( pNew->pId==0 ){
5562 ctrlFlags |= UNIXFILE_NOLOCK;
5563 rc = SQLITE_NOMEM_BKPT;
5565 #endif
5567 if( ctrlFlags & UNIXFILE_NOLOCK ){
5568 pLockingStyle = &nolockIoMethods;
5569 }else{
5570 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
5571 #if SQLITE_ENABLE_LOCKING_STYLE
5572 /* Cache zFilename in the locking context (AFP and dotlock override) for
5573 ** proxyLock activation is possible (remote proxy is based on db name)
5574 ** zFilename remains valid until file is closed, to support */
5575 pNew->lockingContext = (void*)zFilename;
5576 #endif
5579 if( pLockingStyle == &posixIoMethods
5580 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5581 || pLockingStyle == &nfsIoMethods
5582 #endif
5584 unixEnterMutex();
5585 rc = findInodeInfo(pNew, &pNew->pInode);
5586 if( rc!=SQLITE_OK ){
5587 /* If an error occurred in findInodeInfo(), close the file descriptor
5588 ** immediately, before releasing the mutex. findInodeInfo() may fail
5589 ** in two scenarios:
5591 ** (a) A call to fstat() failed.
5592 ** (b) A malloc failed.
5594 ** Scenario (b) may only occur if the process is holding no other
5595 ** file descriptors open on the same file. If there were other file
5596 ** descriptors on this file, then no malloc would be required by
5597 ** findInodeInfo(). If this is the case, it is quite safe to close
5598 ** handle h - as it is guaranteed that no posix locks will be released
5599 ** by doing so.
5601 ** If scenario (a) caused the error then things are not so safe. The
5602 ** implicit assumption here is that if fstat() fails, things are in
5603 ** such bad shape that dropping a lock or two doesn't matter much.
5605 robust_close(pNew, h, __LINE__);
5606 h = -1;
5608 unixLeaveMutex();
5611 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
5612 else if( pLockingStyle == &afpIoMethods ){
5613 /* AFP locking uses the file path so it needs to be included in
5614 ** the afpLockingContext.
5616 afpLockingContext *pCtx;
5617 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
5618 if( pCtx==0 ){
5619 rc = SQLITE_NOMEM_BKPT;
5620 }else{
5621 /* NB: zFilename exists and remains valid until the file is closed
5622 ** according to requirement F11141. So we do not need to make a
5623 ** copy of the filename. */
5624 pCtx->dbPath = zFilename;
5625 pCtx->reserved = 0;
5626 srandomdev();
5627 unixEnterMutex();
5628 rc = findInodeInfo(pNew, &pNew->pInode);
5629 if( rc!=SQLITE_OK ){
5630 sqlite3_free(pNew->lockingContext);
5631 robust_close(pNew, h, __LINE__);
5632 h = -1;
5634 unixLeaveMutex();
5637 #endif
5639 else if( pLockingStyle == &dotlockIoMethods ){
5640 /* Dotfile locking uses the file path so it needs to be included in
5641 ** the dotlockLockingContext
5643 char *zLockFile;
5644 int nFilename;
5645 assert( zFilename!=0 );
5646 nFilename = (int)strlen(zFilename) + 6;
5647 zLockFile = (char *)sqlite3_malloc64(nFilename);
5648 if( zLockFile==0 ){
5649 rc = SQLITE_NOMEM_BKPT;
5650 }else{
5651 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
5653 pNew->lockingContext = zLockFile;
5656 #if OS_VXWORKS
5657 else if( pLockingStyle == &semIoMethods ){
5658 /* Named semaphore locking uses the file path so it needs to be
5659 ** included in the semLockingContext
5661 unixEnterMutex();
5662 rc = findInodeInfo(pNew, &pNew->pInode);
5663 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5664 char *zSemName = pNew->pInode->aSemName;
5665 int n;
5666 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
5667 pNew->pId->zCanonicalName);
5668 for( n=1; zSemName[n]; n++ )
5669 if( zSemName[n]=='/' ) zSemName[n] = '_';
5670 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5671 if( pNew->pInode->pSem == SEM_FAILED ){
5672 rc = SQLITE_NOMEM_BKPT;
5673 pNew->pInode->aSemName[0] = '\0';
5676 unixLeaveMutex();
5678 #endif
5680 storeLastErrno(pNew, 0);
5681 #if OS_VXWORKS
5682 if( rc!=SQLITE_OK ){
5683 if( h>=0 ) robust_close(pNew, h, __LINE__);
5684 h = -1;
5685 osUnlink(zFilename);
5686 pNew->ctrlFlags |= UNIXFILE_DELETE;
5688 #endif
5689 if( rc!=SQLITE_OK ){
5690 if( h>=0 ) robust_close(pNew, h, __LINE__);
5691 }else{
5692 pNew->pMethod = pLockingStyle;
5693 OpenCounter(+1);
5694 verifyDbFile(pNew);
5696 return rc;
5700 ** Return the name of a directory in which to put temporary files.
5701 ** If no suitable temporary file directory can be found, return NULL.
5703 static const char *unixTempFileDir(void){
5704 static const char *azDirs[] = {
5707 "/var/tmp",
5708 "/usr/tmp",
5709 "/tmp",
5712 unsigned int i = 0;
5713 struct stat buf;
5714 const char *zDir = sqlite3_temp_directory;
5716 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
5717 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
5718 while(1){
5719 if( zDir!=0
5720 && osStat(zDir, &buf)==0
5721 && S_ISDIR(buf.st_mode)
5722 && osAccess(zDir, 03)==0
5724 return zDir;
5726 if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
5727 zDir = azDirs[i++];
5729 return 0;
5733 ** Create a temporary file name in zBuf. zBuf must be allocated
5734 ** by the calling process and must be big enough to hold at least
5735 ** pVfs->mxPathname bytes.
5737 static int unixGetTempname(int nBuf, char *zBuf){
5738 const char *zDir;
5739 int iLimit = 0;
5741 /* It's odd to simulate an io-error here, but really this is just
5742 ** using the io-error infrastructure to test that SQLite handles this
5743 ** function failing.
5745 zBuf[0] = 0;
5746 SimulateIOError( return SQLITE_IOERR );
5748 zDir = unixTempFileDir();
5749 if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
5751 u64 r;
5752 sqlite3_randomness(sizeof(r), &r);
5753 assert( nBuf>2 );
5754 zBuf[nBuf-2] = 0;
5755 sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
5756 zDir, r, 0);
5757 if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
5758 }while( osAccess(zBuf,0)==0 );
5759 return SQLITE_OK;
5762 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
5764 ** Routine to transform a unixFile into a proxy-locking unixFile.
5765 ** Implementation in the proxy-lock division, but used by unixOpen()
5766 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
5768 static int proxyTransformUnixFile(unixFile*, const char*);
5769 #endif
5772 ** Search for an unused file descriptor that was opened on the database
5773 ** file (not a journal or master-journal file) identified by pathname
5774 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5775 ** argument to this function.
5777 ** Such a file descriptor may exist if a database connection was closed
5778 ** but the associated file descriptor could not be closed because some
5779 ** other file descriptor open on the same file is holding a file-lock.
5780 ** Refer to comments in the unixClose() function and the lengthy comment
5781 ** describing "Posix Advisory Locking" at the start of this file for
5782 ** further details. Also, ticket #4018.
5784 ** If a suitable file descriptor is found, then it is returned. If no
5785 ** such file descriptor is located, -1 is returned.
5787 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5788 UnixUnusedFd *pUnused = 0;
5790 /* Do not search for an unused file descriptor on vxworks. Not because
5791 ** vxworks would not benefit from the change (it might, we're not sure),
5792 ** but because no way to test it is currently available. It is better
5793 ** not to risk breaking vxworks support for the sake of such an obscure
5794 ** feature. */
5795 #if !OS_VXWORKS
5796 struct stat sStat; /* Results of stat() call */
5798 unixEnterMutex();
5800 /* A stat() call may fail for various reasons. If this happens, it is
5801 ** almost certain that an open() call on the same path will also fail.
5802 ** For this reason, if an error occurs in the stat() call here, it is
5803 ** ignored and -1 is returned. The caller will try to open a new file
5804 ** descriptor on the same path, fail, and return an error to SQLite.
5806 ** Even if a subsequent open() call does succeed, the consequences of
5807 ** not searching for a reusable file descriptor are not dire. */
5808 if( inodeList!=0 && 0==osStat(zPath, &sStat) ){
5809 unixInodeInfo *pInode;
5811 pInode = inodeList;
5812 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5813 || pInode->fileId.ino!=(u64)sStat.st_ino) ){
5814 pInode = pInode->pNext;
5816 if( pInode ){
5817 UnixUnusedFd **pp;
5818 assert( sqlite3_mutex_notheld(pInode->pLockMutex) );
5819 sqlite3_mutex_enter(pInode->pLockMutex);
5820 flags &= (SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE);
5821 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
5822 pUnused = *pp;
5823 if( pUnused ){
5824 *pp = pUnused->pNext;
5826 sqlite3_mutex_leave(pInode->pLockMutex);
5829 unixLeaveMutex();
5830 #endif /* if !OS_VXWORKS */
5831 return pUnused;
5835 ** Find the mode, uid and gid of file zFile.
5837 static int getFileMode(
5838 const char *zFile, /* File name */
5839 mode_t *pMode, /* OUT: Permissions of zFile */
5840 uid_t *pUid, /* OUT: uid of zFile. */
5841 gid_t *pGid /* OUT: gid of zFile. */
5843 struct stat sStat; /* Output of stat() on database file */
5844 int rc = SQLITE_OK;
5845 if( 0==osStat(zFile, &sStat) ){
5846 *pMode = sStat.st_mode & 0777;
5847 *pUid = sStat.st_uid;
5848 *pGid = sStat.st_gid;
5849 }else{
5850 rc = SQLITE_IOERR_FSTAT;
5852 return rc;
5856 ** This function is called by unixOpen() to determine the unix permissions
5857 ** to create new files with. If no error occurs, then SQLITE_OK is returned
5858 ** and a value suitable for passing as the third argument to open(2) is
5859 ** written to *pMode. If an IO error occurs, an SQLite error code is
5860 ** returned and the value of *pMode is not modified.
5862 ** In most cases, this routine sets *pMode to 0, which will become
5863 ** an indication to robust_open() to create the file using
5864 ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5865 ** But if the file being opened is a WAL or regular journal file, then
5866 ** this function queries the file-system for the permissions on the
5867 ** corresponding database file and sets *pMode to this value. Whenever
5868 ** possible, WAL and journal files are created using the same permissions
5869 ** as the associated database file.
5871 ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5872 ** original filename is unavailable. But 8_3_NAMES is only used for
5873 ** FAT filesystems and permissions do not matter there, so just use
5874 ** the default permissions. In 8_3_NAMES mode, leave *pMode set to zero.
5876 static int findCreateFileMode(
5877 const char *zPath, /* Path of file (possibly) being created */
5878 int flags, /* Flags passed as 4th argument to xOpen() */
5879 mode_t *pMode, /* OUT: Permissions to open file with */
5880 uid_t *pUid, /* OUT: uid to set on the file */
5881 gid_t *pGid /* OUT: gid to set on the file */
5883 int rc = SQLITE_OK; /* Return Code */
5884 *pMode = 0;
5885 *pUid = 0;
5886 *pGid = 0;
5887 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
5888 char zDb[MAX_PATHNAME+1]; /* Database file path */
5889 int nDb; /* Number of valid bytes in zDb */
5891 /* zPath is a path to a WAL or journal file. The following block derives
5892 ** the path to the associated database file from zPath. This block handles
5893 ** the following naming conventions:
5895 ** "<path to db>-journal"
5896 ** "<path to db>-wal"
5897 ** "<path to db>-journalNN"
5898 ** "<path to db>-walNN"
5900 ** where NN is a decimal number. The NN naming schemes are
5901 ** used by the test_multiplex.c module.
5903 nDb = sqlite3Strlen30(zPath) - 1;
5904 while( zPath[nDb]!='-' ){
5905 /* In normal operation, the journal file name will always contain
5906 ** a '-' character. However in 8+3 filename mode, or if a corrupt
5907 ** rollback journal specifies a master journal with a goofy name, then
5908 ** the '-' might be missing. */
5909 if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
5910 nDb--;
5912 memcpy(zDb, zPath, nDb);
5913 zDb[nDb] = '\0';
5915 rc = getFileMode(zDb, pMode, pUid, pGid);
5916 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5917 *pMode = 0600;
5918 }else if( flags & SQLITE_OPEN_URI ){
5919 /* If this is a main database file and the file was opened using a URI
5920 ** filename, check for the "modeof" parameter. If present, interpret
5921 ** its value as a filename and try to copy the mode, uid and gid from
5922 ** that file. */
5923 const char *z = sqlite3_uri_parameter(zPath, "modeof");
5924 if( z ){
5925 rc = getFileMode(z, pMode, pUid, pGid);
5928 return rc;
5932 ** Open the file zPath.
5934 ** Previously, the SQLite OS layer used three functions in place of this
5935 ** one:
5937 ** sqlite3OsOpenReadWrite();
5938 ** sqlite3OsOpenReadOnly();
5939 ** sqlite3OsOpenExclusive();
5941 ** These calls correspond to the following combinations of flags:
5943 ** ReadWrite() -> (READWRITE | CREATE)
5944 ** ReadOnly() -> (READONLY)
5945 ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5947 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5948 ** true, the file was configured to be automatically deleted when the
5949 ** file handle closed. To achieve the same effect using this new
5950 ** interface, add the DELETEONCLOSE flag to those specified above for
5951 ** OpenExclusive().
5953 static int unixOpen(
5954 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5955 const char *zPath, /* Pathname of file to be opened */
5956 sqlite3_file *pFile, /* The file descriptor to be filled in */
5957 int flags, /* Input flags to control the opening */
5958 int *pOutFlags /* Output flags returned to SQLite core */
5960 unixFile *p = (unixFile *)pFile;
5961 int fd = -1; /* File descriptor returned by open() */
5962 int openFlags = 0; /* Flags to pass to open() */
5963 int eType = flags&0x0FFF00; /* Type of file to open */
5964 int noLock; /* True to omit locking primitives */
5965 int rc = SQLITE_OK; /* Function Return Code */
5966 int ctrlFlags = 0; /* UNIXFILE_* flags */
5968 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5969 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5970 int isCreate = (flags & SQLITE_OPEN_CREATE);
5971 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5972 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
5973 #if SQLITE_ENABLE_LOCKING_STYLE
5974 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5975 #endif
5976 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5977 struct statfs fsInfo;
5978 #endif
5980 /* If creating a master or main-file journal, this function will open
5981 ** a file-descriptor on the directory too. The first time unixSync()
5982 ** is called the directory file descriptor will be fsync()ed and close()d.
5984 int isNewJrnl = (isCreate && (
5985 eType==SQLITE_OPEN_MASTER_JOURNAL
5986 || eType==SQLITE_OPEN_MAIN_JOURNAL
5987 || eType==SQLITE_OPEN_WAL
5990 /* If argument zPath is a NULL pointer, this function is required to open
5991 ** a temporary file. Use this buffer to store the file name in.
5993 char zTmpname[MAX_PATHNAME+2];
5994 const char *zName = zPath;
5996 /* Check the following statements are true:
5998 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5999 ** (b) if CREATE is set, then READWRITE must also be set, and
6000 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
6001 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
6003 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
6004 assert(isCreate==0 || isReadWrite);
6005 assert(isExclusive==0 || isCreate);
6006 assert(isDelete==0 || isCreate);
6008 /* The main DB, main journal, WAL file and master journal are never
6009 ** automatically deleted. Nor are they ever temporary files. */
6010 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
6011 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
6012 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
6013 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
6015 /* Assert that the upper layer has set one of the "file-type" flags. */
6016 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
6017 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
6018 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
6019 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
6022 /* Detect a pid change and reset the PRNG. There is a race condition
6023 ** here such that two or more threads all trying to open databases at
6024 ** the same instant might all reset the PRNG. But multiple resets
6025 ** are harmless.
6027 if( randomnessPid!=osGetpid(0) ){
6028 randomnessPid = osGetpid(0);
6029 sqlite3_randomness(0,0);
6031 memset(p, 0, sizeof(unixFile));
6033 if( eType==SQLITE_OPEN_MAIN_DB ){
6034 UnixUnusedFd *pUnused;
6035 pUnused = findReusableFd(zName, flags);
6036 if( pUnused ){
6037 fd = pUnused->fd;
6038 }else{
6039 pUnused = sqlite3_malloc64(sizeof(*pUnused));
6040 if( !pUnused ){
6041 return SQLITE_NOMEM_BKPT;
6044 p->pPreallocatedUnused = pUnused;
6046 /* Database filenames are double-zero terminated if they are not
6047 ** URIs with parameters. Hence, they can always be passed into
6048 ** sqlite3_uri_parameter(). */
6049 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
6051 }else if( !zName ){
6052 /* If zName is NULL, the upper layer is requesting a temp file. */
6053 assert(isDelete && !isNewJrnl);
6054 rc = unixGetTempname(pVfs->mxPathname, zTmpname);
6055 if( rc!=SQLITE_OK ){
6056 return rc;
6058 zName = zTmpname;
6060 /* Generated temporary filenames are always double-zero terminated
6061 ** for use by sqlite3_uri_parameter(). */
6062 assert( zName[strlen(zName)+1]==0 );
6065 /* Determine the value of the flags parameter passed to POSIX function
6066 ** open(). These must be calculated even if open() is not called, as
6067 ** they may be stored as part of the file handle and used by the
6068 ** 'conch file' locking functions later on. */
6069 if( isReadonly ) openFlags |= O_RDONLY;
6070 if( isReadWrite ) openFlags |= O_RDWR;
6071 if( isCreate ) openFlags |= O_CREAT;
6072 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
6073 openFlags |= (O_LARGEFILE|O_BINARY|O_NOFOLLOW);
6075 if( fd<0 ){
6076 mode_t openMode; /* Permissions to create file with */
6077 uid_t uid; /* Userid for the file */
6078 gid_t gid; /* Groupid for the file */
6079 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
6080 if( rc!=SQLITE_OK ){
6081 assert( !p->pPreallocatedUnused );
6082 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
6083 return rc;
6085 fd = robust_open(zName, openFlags, openMode);
6086 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
6087 assert( !isExclusive || (openFlags & O_CREAT)!=0 );
6088 if( fd<0 ){
6089 if( isNewJrnl && errno==EACCES && osAccess(zName, F_OK) ){
6090 /* If unable to create a journal because the directory is not
6091 ** writable, change the error code to indicate that. */
6092 rc = SQLITE_READONLY_DIRECTORY;
6093 }else if( errno!=EISDIR && isReadWrite ){
6094 /* Failed to open the file for read/write access. Try read-only. */
6095 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
6096 openFlags &= ~(O_RDWR|O_CREAT);
6097 flags |= SQLITE_OPEN_READONLY;
6098 openFlags |= O_RDONLY;
6099 isReadonly = 1;
6100 fd = robust_open(zName, openFlags, openMode);
6103 if( fd<0 ){
6104 int rc2 = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
6105 if( rc==SQLITE_OK ) rc = rc2;
6106 goto open_finished;
6109 /* The owner of the rollback journal or WAL file should always be the
6110 ** same as the owner of the database file. Try to ensure that this is
6111 ** the case. The chown() system call will be a no-op if the current
6112 ** process lacks root privileges, be we should at least try. Without
6113 ** this step, if a root process opens a database file, it can leave
6114 ** behinds a journal/WAL that is owned by root and hence make the
6115 ** database inaccessible to unprivileged processes.
6117 ** If openMode==0, then that means uid and gid are not set correctly
6118 ** (probably because SQLite is configured to use 8+3 filename mode) and
6119 ** in that case we do not want to attempt the chown().
6121 if( openMode && (flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL))!=0 ){
6122 robustFchown(fd, uid, gid);
6125 assert( fd>=0 );
6126 if( pOutFlags ){
6127 *pOutFlags = flags;
6130 if( p->pPreallocatedUnused ){
6131 p->pPreallocatedUnused->fd = fd;
6132 p->pPreallocatedUnused->flags =
6133 flags & (SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE);
6136 if( isDelete ){
6137 #if OS_VXWORKS
6138 zPath = zName;
6139 #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
6140 zPath = sqlite3_mprintf("%s", zName);
6141 if( zPath==0 ){
6142 robust_close(p, fd, __LINE__);
6143 return SQLITE_NOMEM_BKPT;
6145 #else
6146 osUnlink(zName);
6147 #endif
6149 #if SQLITE_ENABLE_LOCKING_STYLE
6150 else{
6151 p->openFlags = openFlags;
6153 #endif
6155 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
6156 if( fstatfs(fd, &fsInfo) == -1 ){
6157 storeLastErrno(p, errno);
6158 robust_close(p, fd, __LINE__);
6159 return SQLITE_IOERR_ACCESS;
6161 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
6162 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
6164 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
6165 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
6167 #endif
6169 /* Set up appropriate ctrlFlags */
6170 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
6171 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
6172 noLock = eType!=SQLITE_OPEN_MAIN_DB;
6173 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
6174 if( isNewJrnl ) ctrlFlags |= UNIXFILE_DIRSYNC;
6175 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
6177 #if SQLITE_ENABLE_LOCKING_STYLE
6178 #if SQLITE_PREFER_PROXY_LOCKING
6179 isAutoProxy = 1;
6180 #endif
6181 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
6182 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
6183 int useProxy = 0;
6185 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
6186 ** never use proxy, NULL means use proxy for non-local files only. */
6187 if( envforce!=NULL ){
6188 useProxy = atoi(envforce)>0;
6189 }else{
6190 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
6192 if( useProxy ){
6193 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
6194 if( rc==SQLITE_OK ){
6195 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
6196 if( rc!=SQLITE_OK ){
6197 /* Use unixClose to clean up the resources added in fillInUnixFile
6198 ** and clear all the structure's references. Specifically,
6199 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
6201 unixClose(pFile);
6202 return rc;
6205 goto open_finished;
6208 #endif
6210 assert( zPath==0 || zPath[0]=='/'
6211 || eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL
6213 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
6215 open_finished:
6216 if( rc!=SQLITE_OK ){
6217 sqlite3_free(p->pPreallocatedUnused);
6219 return rc;
6224 ** Delete the file at zPath. If the dirSync argument is true, fsync()
6225 ** the directory after deleting the file.
6227 static int unixDelete(
6228 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
6229 const char *zPath, /* Name of file to be deleted */
6230 int dirSync /* If true, fsync() directory after deleting file */
6232 int rc = SQLITE_OK;
6233 UNUSED_PARAMETER(NotUsed);
6234 SimulateIOError(return SQLITE_IOERR_DELETE);
6235 if( osUnlink(zPath)==(-1) ){
6236 if( errno==ENOENT
6237 #if OS_VXWORKS
6238 || osAccess(zPath,0)!=0
6239 #endif
6241 rc = SQLITE_IOERR_DELETE_NOENT;
6242 }else{
6243 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
6245 return rc;
6247 #ifndef SQLITE_DISABLE_DIRSYNC
6248 if( (dirSync & 1)!=0 ){
6249 int fd;
6250 rc = osOpenDirectory(zPath, &fd);
6251 if( rc==SQLITE_OK ){
6252 if( full_fsync(fd,0,0) ){
6253 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
6255 robust_close(0, fd, __LINE__);
6256 }else{
6257 assert( rc==SQLITE_CANTOPEN );
6258 rc = SQLITE_OK;
6261 #endif
6262 return rc;
6266 ** Test the existence of or access permissions of file zPath. The
6267 ** test performed depends on the value of flags:
6269 ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
6270 ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
6271 ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
6273 ** Otherwise return 0.
6275 static int unixAccess(
6276 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
6277 const char *zPath, /* Path of the file to examine */
6278 int flags, /* What do we want to learn about the zPath file? */
6279 int *pResOut /* Write result boolean here */
6281 UNUSED_PARAMETER(NotUsed);
6282 SimulateIOError( return SQLITE_IOERR_ACCESS; );
6283 assert( pResOut!=0 );
6285 /* The spec says there are three possible values for flags. But only
6286 ** two of them are actually used */
6287 assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
6289 if( flags==SQLITE_ACCESS_EXISTS ){
6290 struct stat buf;
6291 *pResOut = 0==osStat(zPath, &buf) &&
6292 (!S_ISREG(buf.st_mode) || buf.st_size>0);
6293 }else{
6294 *pResOut = osAccess(zPath, W_OK|R_OK)==0;
6296 return SQLITE_OK;
6302 static int mkFullPathname(
6303 const char *zPath, /* Input path */
6304 char *zOut, /* Output buffer */
6305 int nOut /* Allocated size of buffer zOut */
6307 int nPath = sqlite3Strlen30(zPath);
6308 int iOff = 0;
6309 if( zPath[0]!='/' ){
6310 if( osGetcwd(zOut, nOut-2)==0 ){
6311 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
6313 iOff = sqlite3Strlen30(zOut);
6314 zOut[iOff++] = '/';
6316 if( (iOff+nPath+1)>nOut ){
6317 /* SQLite assumes that xFullPathname() nul-terminates the output buffer
6318 ** even if it returns an error. */
6319 zOut[iOff] = '\0';
6320 return SQLITE_CANTOPEN_BKPT;
6322 sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
6323 return SQLITE_OK;
6327 ** Turn a relative pathname into a full pathname. The relative path
6328 ** is stored as a nul-terminated string in the buffer pointed to by
6329 ** zPath.
6331 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
6332 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
6333 ** this buffer before returning.
6335 static int unixFullPathname(
6336 sqlite3_vfs *pVfs, /* Pointer to vfs object */
6337 const char *zPath, /* Possibly relative input path */
6338 int nOut, /* Size of output buffer in bytes */
6339 char *zOut /* Output buffer */
6341 #if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
6342 return mkFullPathname(zPath, zOut, nOut);
6343 #else
6344 int rc = SQLITE_OK;
6345 int nByte;
6346 int nLink = 0; /* Number of symbolic links followed so far */
6347 const char *zIn = zPath; /* Input path for each iteration of loop */
6348 char *zDel = 0;
6350 assert( pVfs->mxPathname==MAX_PATHNAME );
6351 UNUSED_PARAMETER(pVfs);
6353 /* It's odd to simulate an io-error here, but really this is just
6354 ** using the io-error infrastructure to test that SQLite handles this
6355 ** function failing. This function could fail if, for example, the
6356 ** current working directory has been unlinked.
6358 SimulateIOError( return SQLITE_ERROR );
6360 do {
6362 /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
6363 ** link, or false otherwise. */
6364 int bLink = 0;
6365 struct stat buf;
6366 if( osLstat(zIn, &buf)!=0 ){
6367 if( errno!=ENOENT ){
6368 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
6370 }else{
6371 bLink = S_ISLNK(buf.st_mode);
6374 if( bLink ){
6375 nLink++;
6376 if( zDel==0 ){
6377 zDel = sqlite3_malloc(nOut);
6378 if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
6379 }else if( nLink>=SQLITE_MAX_SYMLINKS ){
6380 rc = SQLITE_CANTOPEN_BKPT;
6383 if( rc==SQLITE_OK ){
6384 nByte = osReadlink(zIn, zDel, nOut-1);
6385 if( nByte<0 ){
6386 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
6387 }else{
6388 if( zDel[0]!='/' ){
6389 int n;
6390 for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
6391 if( nByte+n+1>nOut ){
6392 rc = SQLITE_CANTOPEN_BKPT;
6393 }else{
6394 memmove(&zDel[n], zDel, nByte+1);
6395 memcpy(zDel, zIn, n);
6396 nByte += n;
6399 zDel[nByte] = '\0';
6403 zIn = zDel;
6406 assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
6407 if( rc==SQLITE_OK && zIn!=zOut ){
6408 rc = mkFullPathname(zIn, zOut, nOut);
6410 if( bLink==0 ) break;
6411 zIn = zOut;
6412 }while( rc==SQLITE_OK );
6414 sqlite3_free(zDel);
6415 if( rc==SQLITE_OK && nLink ) rc = SQLITE_OK_SYMLINK;
6416 return rc;
6417 #endif /* HAVE_READLINK && HAVE_LSTAT */
6421 #ifndef SQLITE_OMIT_LOAD_EXTENSION
6423 ** Interfaces for opening a shared library, finding entry points
6424 ** within the shared library, and closing the shared library.
6426 #include <dlfcn.h>
6427 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6428 UNUSED_PARAMETER(NotUsed);
6429 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6433 ** SQLite calls this function immediately after a call to unixDlSym() or
6434 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
6435 ** message is available, it is written to zBufOut. If no error message
6436 ** is available, zBufOut is left unmodified and SQLite uses a default
6437 ** error message.
6439 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
6440 const char *zErr;
6441 UNUSED_PARAMETER(NotUsed);
6442 unixEnterMutex();
6443 zErr = dlerror();
6444 if( zErr ){
6445 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
6447 unixLeaveMutex();
6449 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6451 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6452 ** cast into a pointer to a function. And yet the library dlsym() routine
6453 ** returns a void* which is really a pointer to a function. So how do we
6454 ** use dlsym() with -pedantic-errors?
6456 ** Variable x below is defined to be a pointer to a function taking
6457 ** parameters void* and const char* and returning a pointer to a function.
6458 ** We initialize x by assigning it a pointer to the dlsym() function.
6459 ** (That assignment requires a cast.) Then we call the function that
6460 ** x points to.
6462 ** This work-around is unlikely to work correctly on any system where
6463 ** you really cannot cast a function pointer into void*. But then, on the
6464 ** other hand, dlsym() will not work on such a system either, so we have
6465 ** not really lost anything.
6467 void (*(*x)(void*,const char*))(void);
6468 UNUSED_PARAMETER(NotUsed);
6469 x = (void(*(*)(void*,const char*))(void))dlsym;
6470 return (*x)(p, zSym);
6472 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6473 UNUSED_PARAMETER(NotUsed);
6474 dlclose(pHandle);
6476 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6477 #define unixDlOpen 0
6478 #define unixDlError 0
6479 #define unixDlSym 0
6480 #define unixDlClose 0
6481 #endif
6484 ** Write nBuf bytes of random data to the supplied buffer zBuf.
6486 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6487 UNUSED_PARAMETER(NotUsed);
6488 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
6490 /* We have to initialize zBuf to prevent valgrind from reporting
6491 ** errors. The reports issued by valgrind are incorrect - we would
6492 ** prefer that the randomness be increased by making use of the
6493 ** uninitialized space in zBuf - but valgrind errors tend to worry
6494 ** some users. Rather than argue, it seems easier just to initialize
6495 ** the whole array and silence valgrind, even if that means less randomness
6496 ** in the random seed.
6498 ** When testing, initializing zBuf[] to zero is all we do. That means
6499 ** that we always use the same random number sequence. This makes the
6500 ** tests repeatable.
6502 memset(zBuf, 0, nBuf);
6503 randomnessPid = osGetpid(0);
6504 #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
6506 int fd, got;
6507 fd = robust_open("/dev/urandom", O_RDONLY, 0);
6508 if( fd<0 ){
6509 time_t t;
6510 time(&t);
6511 memcpy(zBuf, &t, sizeof(t));
6512 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6513 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6514 nBuf = sizeof(t) + sizeof(randomnessPid);
6515 }else{
6516 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
6517 robust_close(0, fd, __LINE__);
6520 #endif
6521 return nBuf;
6526 ** Sleep for a little while. Return the amount of time slept.
6527 ** The argument is the number of microseconds we want to sleep.
6528 ** The return value is the number of microseconds of sleep actually
6529 ** requested from the underlying operating system, a number which
6530 ** might be greater than or equal to the argument, but not less
6531 ** than the argument.
6533 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
6534 #if OS_VXWORKS
6535 struct timespec sp;
6537 sp.tv_sec = microseconds / 1000000;
6538 sp.tv_nsec = (microseconds % 1000000) * 1000;
6539 nanosleep(&sp, NULL);
6540 UNUSED_PARAMETER(NotUsed);
6541 return microseconds;
6542 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
6543 usleep(microseconds);
6544 UNUSED_PARAMETER(NotUsed);
6545 return microseconds;
6546 #else
6547 int seconds = (microseconds+999999)/1000000;
6548 sleep(seconds);
6549 UNUSED_PARAMETER(NotUsed);
6550 return seconds*1000000;
6551 #endif
6555 ** The following variable, if set to a non-zero value, is interpreted as
6556 ** the number of seconds since 1970 and is used to set the result of
6557 ** sqlite3OsCurrentTime() during testing.
6559 #ifdef SQLITE_TEST
6560 int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
6561 #endif
6564 ** Find the current time (in Universal Coordinated Time). Write into *piNow
6565 ** the current time and date as a Julian Day number times 86_400_000. In
6566 ** other words, write into *piNow the number of milliseconds since the Julian
6567 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6568 ** proleptic Gregorian calendar.
6570 ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6571 ** cannot be found.
6573 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6574 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
6575 int rc = SQLITE_OK;
6576 #if defined(NO_GETTOD)
6577 time_t t;
6578 time(&t);
6579 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
6580 #elif OS_VXWORKS
6581 struct timespec sNow;
6582 clock_gettime(CLOCK_REALTIME, &sNow);
6583 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6584 #else
6585 struct timeval sNow;
6586 (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
6587 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
6588 #endif
6590 #ifdef SQLITE_TEST
6591 if( sqlite3_current_time ){
6592 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6594 #endif
6595 UNUSED_PARAMETER(NotUsed);
6596 return rc;
6599 #ifndef SQLITE_OMIT_DEPRECATED
6601 ** Find the current time (in Universal Coordinated Time). Write the
6602 ** current time and date as a Julian Day number into *prNow and
6603 ** return 0. Return 1 if the time and date cannot be found.
6605 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
6606 sqlite3_int64 i = 0;
6607 int rc;
6608 UNUSED_PARAMETER(NotUsed);
6609 rc = unixCurrentTimeInt64(0, &i);
6610 *prNow = i/86400000.0;
6611 return rc;
6613 #else
6614 # define unixCurrentTime 0
6615 #endif
6618 ** The xGetLastError() method is designed to return a better
6619 ** low-level error message when operating-system problems come up
6620 ** during SQLite operation. Only the integer return code is currently
6621 ** used.
6623 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6624 UNUSED_PARAMETER(NotUsed);
6625 UNUSED_PARAMETER(NotUsed2);
6626 UNUSED_PARAMETER(NotUsed3);
6627 return errno;
6632 ************************ End of sqlite3_vfs methods ***************************
6633 ******************************************************************************/
6635 /******************************************************************************
6636 ************************** Begin Proxy Locking ********************************
6638 ** Proxy locking is a "uber-locking-method" in this sense: It uses the
6639 ** other locking methods on secondary lock files. Proxy locking is a
6640 ** meta-layer over top of the primitive locking implemented above. For
6641 ** this reason, the division that implements of proxy locking is deferred
6642 ** until late in the file (here) after all of the other I/O methods have
6643 ** been defined - so that the primitive locking methods are available
6644 ** as services to help with the implementation of proxy locking.
6646 ****
6648 ** The default locking schemes in SQLite use byte-range locks on the
6649 ** database file to coordinate safe, concurrent access by multiple readers
6650 ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6651 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6652 ** as POSIX read & write locks over fixed set of locations (via fsctl),
6653 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
6654 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6655 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6656 ** address in the shared range is taken for a SHARED lock, the entire
6657 ** shared range is taken for an EXCLUSIVE lock):
6659 ** PENDING_BYTE 0x40000000
6660 ** RESERVED_BYTE 0x40000001
6661 ** SHARED_RANGE 0x40000002 -> 0x40000200
6663 ** This works well on the local file system, but shows a nearly 100x
6664 ** slowdown in read performance on AFP because the AFP client disables
6665 ** the read cache when byte-range locks are present. Enabling the read
6666 ** cache exposes a cache coherency problem that is present on all OS X
6667 ** supported network file systems. NFS and AFP both observe the
6668 ** close-to-open semantics for ensuring cache coherency
6669 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6670 ** address the requirements for concurrent database access by multiple
6671 ** readers and writers
6672 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6674 ** To address the performance and cache coherency issues, proxy file locking
6675 ** changes the way database access is controlled by limiting access to a
6676 ** single host at a time and moving file locks off of the database file
6677 ** and onto a proxy file on the local file system.
6680 ** Using proxy locks
6681 ** -----------------
6683 ** C APIs
6685 ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
6686 ** <proxy_path> | ":auto:");
6687 ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6688 ** &<proxy_path>);
6691 ** SQL pragmas
6693 ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6694 ** PRAGMA [database.]lock_proxy_file
6696 ** Specifying ":auto:" means that if there is a conch file with a matching
6697 ** host ID in it, the proxy path in the conch file will be used, otherwise
6698 ** a proxy path based on the user's temp dir
6699 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6700 ** actual proxy file name is generated from the name and path of the
6701 ** database file. For example:
6703 ** For database path "/Users/me/foo.db"
6704 ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6706 ** Once a lock proxy is configured for a database connection, it can not
6707 ** be removed, however it may be switched to a different proxy path via
6708 ** the above APIs (assuming the conch file is not being held by another
6709 ** connection or process).
6712 ** How proxy locking works
6713 ** -----------------------
6715 ** Proxy file locking relies primarily on two new supporting files:
6717 ** * conch file to limit access to the database file to a single host
6718 ** at a time
6720 ** * proxy file to act as a proxy for the advisory locks normally
6721 ** taken on the database
6723 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
6724 ** by taking an sqlite-style shared lock on the conch file, reading the
6725 ** contents and comparing the host's unique host ID (see below) and lock
6726 ** proxy path against the values stored in the conch. The conch file is
6727 ** stored in the same directory as the database file and the file name
6728 ** is patterned after the database file name as ".<databasename>-conch".
6729 ** If the conch file does not exist, or its contents do not match the
6730 ** host ID and/or proxy path, then the lock is escalated to an exclusive
6731 ** lock and the conch file contents is updated with the host ID and proxy
6732 ** path and the lock is downgraded to a shared lock again. If the conch
6733 ** is held by another process (with a shared lock), the exclusive lock
6734 ** will fail and SQLITE_BUSY is returned.
6736 ** The proxy file - a single-byte file used for all advisory file locks
6737 ** normally taken on the database file. This allows for safe sharing
6738 ** of the database file for multiple readers and writers on the same
6739 ** host (the conch ensures that they all use the same local lock file).
6741 ** Requesting the lock proxy does not immediately take the conch, it is
6742 ** only taken when the first request to lock database file is made.
6743 ** This matches the semantics of the traditional locking behavior, where
6744 ** opening a connection to a database file does not take a lock on it.
6745 ** The shared lock and an open file descriptor are maintained until
6746 ** the connection to the database is closed.
6748 ** The proxy file and the lock file are never deleted so they only need
6749 ** to be created the first time they are used.
6751 ** Configuration options
6752 ** ---------------------
6754 ** SQLITE_PREFER_PROXY_LOCKING
6756 ** Database files accessed on non-local file systems are
6757 ** automatically configured for proxy locking, lock files are
6758 ** named automatically using the same logic as
6759 ** PRAGMA lock_proxy_file=":auto:"
6761 ** SQLITE_PROXY_DEBUG
6763 ** Enables the logging of error messages during host id file
6764 ** retrieval and creation
6766 ** LOCKPROXYDIR
6768 ** Overrides the default directory used for lock proxy files that
6769 ** are named automatically via the ":auto:" setting
6771 ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6773 ** Permissions to use when creating a directory for storing the
6774 ** lock proxy files, only used when LOCKPROXYDIR is not set.
6777 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6778 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6779 ** force proxy locking to be used for every database file opened, and 0
6780 ** will force automatic proxy locking to be disabled for all database
6781 ** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
6782 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6786 ** Proxy locking is only available on MacOSX
6788 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
6791 ** The proxyLockingContext has the path and file structures for the remote
6792 ** and local proxy files in it
6794 typedef struct proxyLockingContext proxyLockingContext;
6795 struct proxyLockingContext {
6796 unixFile *conchFile; /* Open conch file */
6797 char *conchFilePath; /* Name of the conch file */
6798 unixFile *lockProxy; /* Open proxy lock file */
6799 char *lockProxyPath; /* Name of the proxy lock file */
6800 char *dbPath; /* Name of the open file */
6801 int conchHeld; /* 1 if the conch is held, -1 if lockless */
6802 int nFails; /* Number of conch taking failures */
6803 void *oldLockingContext; /* Original lockingcontext to restore on close */
6804 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6808 ** The proxy lock file path for the database at dbPath is written into lPath,
6809 ** which must point to valid, writable memory large enough for a maxLen length
6810 ** file path.
6812 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6813 int len;
6814 int dbLen;
6815 int i;
6817 #ifdef LOCKPROXYDIR
6818 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6819 #else
6820 # ifdef _CS_DARWIN_USER_TEMP_DIR
6822 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
6823 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
6824 lPath, errno, osGetpid(0)));
6825 return SQLITE_IOERR_LOCK;
6827 len = strlcat(lPath, "sqliteplocks", maxLen);
6829 # else
6830 len = strlcpy(lPath, "/tmp/", maxLen);
6831 # endif
6832 #endif
6834 if( lPath[len-1]!='/' ){
6835 len = strlcat(lPath, "/", maxLen);
6838 /* transform the db path to a unique cache name */
6839 dbLen = (int)strlen(dbPath);
6840 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
6841 char c = dbPath[i];
6842 lPath[i+len] = (c=='/')?'_':c;
6844 lPath[i+len]='\0';
6845 strlcat(lPath, ":auto:", maxLen);
6846 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
6847 return SQLITE_OK;
6851 ** Creates the lock file and any missing directories in lockPath
6853 static int proxyCreateLockPath(const char *lockPath){
6854 int i, len;
6855 char buf[MAXPATHLEN];
6856 int start = 0;
6858 assert(lockPath!=NULL);
6859 /* try to create all the intermediate directories */
6860 len = (int)strlen(lockPath);
6861 buf[0] = lockPath[0];
6862 for( i=1; i<len; i++ ){
6863 if( lockPath[i] == '/' && (i - start > 0) ){
6864 /* only mkdir if leaf dir != "." or "/" or ".." */
6865 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6866 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6867 buf[i]='\0';
6868 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
6869 int err=errno;
6870 if( err!=EEXIST ) {
6871 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
6872 "'%s' proxy lock path=%s pid=%d\n",
6873 buf, strerror(err), lockPath, osGetpid(0)));
6874 return err;
6878 start=i+1;
6880 buf[i] = lockPath[i];
6882 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
6883 return 0;
6887 ** Create a new VFS file descriptor (stored in memory obtained from
6888 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
6890 ** The caller is responsible not only for closing the file descriptor
6891 ** but also for freeing the memory associated with the file descriptor.
6893 static int proxyCreateUnixFile(
6894 const char *path, /* path for the new unixFile */
6895 unixFile **ppFile, /* unixFile created and returned by ref */
6896 int islockfile /* if non zero missing dirs will be created */
6898 int fd = -1;
6899 unixFile *pNew;
6900 int rc = SQLITE_OK;
6901 int openFlags = O_RDWR | O_CREAT | O_NOFOLLOW;
6902 sqlite3_vfs dummyVfs;
6903 int terrno = 0;
6904 UnixUnusedFd *pUnused = NULL;
6906 /* 1. first try to open/create the file
6907 ** 2. if that fails, and this is a lock file (not-conch), try creating
6908 ** the parent directories and then try again.
6909 ** 3. if that fails, try to open the file read-only
6910 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6912 pUnused = findReusableFd(path, openFlags);
6913 if( pUnused ){
6914 fd = pUnused->fd;
6915 }else{
6916 pUnused = sqlite3_malloc64(sizeof(*pUnused));
6917 if( !pUnused ){
6918 return SQLITE_NOMEM_BKPT;
6921 if( fd<0 ){
6922 fd = robust_open(path, openFlags, 0);
6923 terrno = errno;
6924 if( fd<0 && errno==ENOENT && islockfile ){
6925 if( proxyCreateLockPath(path) == SQLITE_OK ){
6926 fd = robust_open(path, openFlags, 0);
6930 if( fd<0 ){
6931 openFlags = O_RDONLY | O_NOFOLLOW;
6932 fd = robust_open(path, openFlags, 0);
6933 terrno = errno;
6935 if( fd<0 ){
6936 if( islockfile ){
6937 return SQLITE_BUSY;
6939 switch (terrno) {
6940 case EACCES:
6941 return SQLITE_PERM;
6942 case EIO:
6943 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6944 default:
6945 return SQLITE_CANTOPEN_BKPT;
6949 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
6950 if( pNew==NULL ){
6951 rc = SQLITE_NOMEM_BKPT;
6952 goto end_create_proxy;
6954 memset(pNew, 0, sizeof(unixFile));
6955 pNew->openFlags = openFlags;
6956 memset(&dummyVfs, 0, sizeof(dummyVfs));
6957 dummyVfs.pAppData = (void*)&autolockIoFinder;
6958 dummyVfs.zName = "dummy";
6959 pUnused->fd = fd;
6960 pUnused->flags = openFlags;
6961 pNew->pPreallocatedUnused = pUnused;
6963 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
6964 if( rc==SQLITE_OK ){
6965 *ppFile = pNew;
6966 return SQLITE_OK;
6968 end_create_proxy:
6969 robust_close(pNew, fd, __LINE__);
6970 sqlite3_free(pNew);
6971 sqlite3_free(pUnused);
6972 return rc;
6975 #ifdef SQLITE_TEST
6976 /* simulate multiple hosts by creating unique hostid file paths */
6977 int sqlite3_hostid_num = 0;
6978 #endif
6980 #define PROXY_HOSTIDLEN 16 /* conch file host id length */
6982 #if HAVE_GETHOSTUUID
6983 /* Not always defined in the headers as it ought to be */
6984 extern int gethostuuid(uuid_t id, const struct timespec *wait);
6985 #endif
6987 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6988 ** bytes of writable memory.
6990 static int proxyGetHostID(unsigned char *pHostID, int *pError){
6991 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6992 memset(pHostID, 0, PROXY_HOSTIDLEN);
6993 #if HAVE_GETHOSTUUID
6995 struct timespec timeout = {1, 0}; /* 1 sec timeout */
6996 if( gethostuuid(pHostID, &timeout) ){
6997 int err = errno;
6998 if( pError ){
6999 *pError = err;
7001 return SQLITE_IOERR;
7004 #else
7005 UNUSED_PARAMETER(pError);
7006 #endif
7007 #ifdef SQLITE_TEST
7008 /* simulate multiple hosts by creating unique hostid file paths */
7009 if( sqlite3_hostid_num != 0){
7010 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
7012 #endif
7014 return SQLITE_OK;
7017 /* The conch file contains the header, host id and lock file path
7019 #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
7020 #define PROXY_HEADERLEN 1 /* conch file header length */
7021 #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
7022 #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
7025 ** Takes an open conch file, copies the contents to a new path and then moves
7026 ** it back. The newly created file's file descriptor is assigned to the
7027 ** conch file structure and finally the original conch file descriptor is
7028 ** closed. Returns zero if successful.
7030 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
7031 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7032 unixFile *conchFile = pCtx->conchFile;
7033 char tPath[MAXPATHLEN];
7034 char buf[PROXY_MAXCONCHLEN];
7035 char *cPath = pCtx->conchFilePath;
7036 size_t readLen = 0;
7037 size_t pathLen = 0;
7038 char errmsg[64] = "";
7039 int fd = -1;
7040 int rc = -1;
7041 UNUSED_PARAMETER(myHostID);
7043 /* create a new path by replace the trailing '-conch' with '-break' */
7044 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
7045 if( pathLen>MAXPATHLEN || pathLen<6 ||
7046 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
7047 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
7048 goto end_breaklock;
7050 /* read the conch content */
7051 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
7052 if( readLen<PROXY_PATHINDEX ){
7053 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
7054 goto end_breaklock;
7056 /* write it out to the temporary break file */
7057 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW), 0);
7058 if( fd<0 ){
7059 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
7060 goto end_breaklock;
7062 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
7063 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
7064 goto end_breaklock;
7066 if( rename(tPath, cPath) ){
7067 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
7068 goto end_breaklock;
7070 rc = 0;
7071 fprintf(stderr, "broke stale lock on %s\n", cPath);
7072 robust_close(pFile, conchFile->h, __LINE__);
7073 conchFile->h = fd;
7074 conchFile->openFlags = O_RDWR | O_CREAT;
7076 end_breaklock:
7077 if( rc ){
7078 if( fd>=0 ){
7079 osUnlink(tPath);
7080 robust_close(pFile, fd, __LINE__);
7082 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
7084 return rc;
7087 /* Take the requested lock on the conch file and break a stale lock if the
7088 ** host id matches.
7090 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
7091 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7092 unixFile *conchFile = pCtx->conchFile;
7093 int rc = SQLITE_OK;
7094 int nTries = 0;
7095 struct timespec conchModTime;
7097 memset(&conchModTime, 0, sizeof(conchModTime));
7098 do {
7099 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
7100 nTries ++;
7101 if( rc==SQLITE_BUSY ){
7102 /* If the lock failed (busy):
7103 * 1st try: get the mod time of the conch, wait 0.5s and try again.
7104 * 2nd try: fail if the mod time changed or host id is different, wait
7105 * 10 sec and try again
7106 * 3rd try: break the lock unless the mod time has changed.
7108 struct stat buf;
7109 if( osFstat(conchFile->h, &buf) ){
7110 storeLastErrno(pFile, errno);
7111 return SQLITE_IOERR_LOCK;
7114 if( nTries==1 ){
7115 conchModTime = buf.st_mtimespec;
7116 usleep(500000); /* wait 0.5 sec and try the lock again*/
7117 continue;
7120 assert( nTries>1 );
7121 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
7122 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
7123 return SQLITE_BUSY;
7126 if( nTries==2 ){
7127 char tBuf[PROXY_MAXCONCHLEN];
7128 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
7129 if( len<0 ){
7130 storeLastErrno(pFile, errno);
7131 return SQLITE_IOERR_LOCK;
7133 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
7134 /* don't break the lock if the host id doesn't match */
7135 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
7136 return SQLITE_BUSY;
7138 }else{
7139 /* don't break the lock on short read or a version mismatch */
7140 return SQLITE_BUSY;
7142 usleep(10000000); /* wait 10 sec and try the lock again */
7143 continue;
7146 assert( nTries==3 );
7147 if( 0==proxyBreakConchLock(pFile, myHostID) ){
7148 rc = SQLITE_OK;
7149 if( lockType==EXCLUSIVE_LOCK ){
7150 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
7152 if( !rc ){
7153 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
7157 } while( rc==SQLITE_BUSY && nTries<3 );
7159 return rc;
7162 /* Takes the conch by taking a shared lock and read the contents conch, if
7163 ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
7164 ** lockPath means that the lockPath in the conch file will be used if the
7165 ** host IDs match, or a new lock path will be generated automatically
7166 ** and written to the conch file.
7168 static int proxyTakeConch(unixFile *pFile){
7169 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7171 if( pCtx->conchHeld!=0 ){
7172 return SQLITE_OK;
7173 }else{
7174 unixFile *conchFile = pCtx->conchFile;
7175 uuid_t myHostID;
7176 int pError = 0;
7177 char readBuf[PROXY_MAXCONCHLEN];
7178 char lockPath[MAXPATHLEN];
7179 char *tempLockPath = NULL;
7180 int rc = SQLITE_OK;
7181 int createConch = 0;
7182 int hostIdMatch = 0;
7183 int readLen = 0;
7184 int tryOldLockPath = 0;
7185 int forceNewLockPath = 0;
7187 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
7188 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
7189 osGetpid(0)));
7191 rc = proxyGetHostID(myHostID, &pError);
7192 if( (rc&0xff)==SQLITE_IOERR ){
7193 storeLastErrno(pFile, pError);
7194 goto end_takeconch;
7196 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
7197 if( rc!=SQLITE_OK ){
7198 goto end_takeconch;
7200 /* read the existing conch file */
7201 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
7202 if( readLen<0 ){
7203 /* I/O error: lastErrno set by seekAndRead */
7204 storeLastErrno(pFile, conchFile->lastErrno);
7205 rc = SQLITE_IOERR_READ;
7206 goto end_takeconch;
7207 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
7208 readBuf[0]!=(char)PROXY_CONCHVERSION ){
7209 /* a short read or version format mismatch means we need to create a new
7210 ** conch file.
7212 createConch = 1;
7214 /* if the host id matches and the lock path already exists in the conch
7215 ** we'll try to use the path there, if we can't open that path, we'll
7216 ** retry with a new auto-generated path
7218 do { /* in case we need to try again for an :auto: named lock file */
7220 if( !createConch && !forceNewLockPath ){
7221 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
7222 PROXY_HOSTIDLEN);
7223 /* if the conch has data compare the contents */
7224 if( !pCtx->lockProxyPath ){
7225 /* for auto-named local lock file, just check the host ID and we'll
7226 ** use the local lock file path that's already in there
7228 if( hostIdMatch ){
7229 size_t pathLen = (readLen - PROXY_PATHINDEX);
7231 if( pathLen>=MAXPATHLEN ){
7232 pathLen=MAXPATHLEN-1;
7234 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
7235 lockPath[pathLen] = 0;
7236 tempLockPath = lockPath;
7237 tryOldLockPath = 1;
7238 /* create a copy of the lock path if the conch is taken */
7239 goto end_takeconch;
7241 }else if( hostIdMatch
7242 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
7243 readLen-PROXY_PATHINDEX)
7245 /* conch host and lock path match */
7246 goto end_takeconch;
7250 /* if the conch isn't writable and doesn't match, we can't take it */
7251 if( (conchFile->openFlags&O_RDWR) == 0 ){
7252 rc = SQLITE_BUSY;
7253 goto end_takeconch;
7256 /* either the conch didn't match or we need to create a new one */
7257 if( !pCtx->lockProxyPath ){
7258 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
7259 tempLockPath = lockPath;
7260 /* create a copy of the lock path _only_ if the conch is taken */
7263 /* update conch with host and path (this will fail if other process
7264 ** has a shared lock already), if the host id matches, use the big
7265 ** stick.
7267 futimes(conchFile->h, NULL);
7268 if( hostIdMatch && !createConch ){
7269 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
7270 /* We are trying for an exclusive lock but another thread in this
7271 ** same process is still holding a shared lock. */
7272 rc = SQLITE_BUSY;
7273 } else {
7274 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
7276 }else{
7277 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
7279 if( rc==SQLITE_OK ){
7280 char writeBuffer[PROXY_MAXCONCHLEN];
7281 int writeSize = 0;
7283 writeBuffer[0] = (char)PROXY_CONCHVERSION;
7284 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
7285 if( pCtx->lockProxyPath!=NULL ){
7286 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
7287 MAXPATHLEN);
7288 }else{
7289 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
7291 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
7292 robust_ftruncate(conchFile->h, writeSize);
7293 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
7294 full_fsync(conchFile->h,0,0);
7295 /* If we created a new conch file (not just updated the contents of a
7296 ** valid conch file), try to match the permissions of the database
7298 if( rc==SQLITE_OK && createConch ){
7299 struct stat buf;
7300 int err = osFstat(pFile->h, &buf);
7301 if( err==0 ){
7302 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
7303 S_IROTH|S_IWOTH);
7304 /* try to match the database file R/W permissions, ignore failure */
7305 #ifndef SQLITE_PROXY_DEBUG
7306 osFchmod(conchFile->h, cmode);
7307 #else
7309 rc = osFchmod(conchFile->h, cmode);
7310 }while( rc==(-1) && errno==EINTR );
7311 if( rc!=0 ){
7312 int code = errno;
7313 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
7314 cmode, code, strerror(code));
7315 } else {
7316 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
7318 }else{
7319 int code = errno;
7320 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
7321 err, code, strerror(code));
7322 #endif
7326 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
7328 end_takeconch:
7329 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
7330 if( rc==SQLITE_OK && pFile->openFlags ){
7331 int fd;
7332 if( pFile->h>=0 ){
7333 robust_close(pFile, pFile->h, __LINE__);
7335 pFile->h = -1;
7336 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
7337 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
7338 if( fd>=0 ){
7339 pFile->h = fd;
7340 }else{
7341 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
7342 during locking */
7345 if( rc==SQLITE_OK && !pCtx->lockProxy ){
7346 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
7347 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
7348 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
7349 /* we couldn't create the proxy lock file with the old lock file path
7350 ** so try again via auto-naming
7352 forceNewLockPath = 1;
7353 tryOldLockPath = 0;
7354 continue; /* go back to the do {} while start point, try again */
7357 if( rc==SQLITE_OK ){
7358 /* Need to make a copy of path if we extracted the value
7359 ** from the conch file or the path was allocated on the stack
7361 if( tempLockPath ){
7362 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
7363 if( !pCtx->lockProxyPath ){
7364 rc = SQLITE_NOMEM_BKPT;
7368 if( rc==SQLITE_OK ){
7369 pCtx->conchHeld = 1;
7371 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
7372 afpLockingContext *afpCtx;
7373 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
7374 afpCtx->dbPath = pCtx->lockProxyPath;
7376 } else {
7377 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7379 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
7380 rc==SQLITE_OK?"ok":"failed"));
7381 return rc;
7382 } while (1); /* in case we need to retry the :auto: lock file -
7383 ** we should never get here except via the 'continue' call. */
7388 ** If pFile holds a lock on a conch file, then release that lock.
7390 static int proxyReleaseConch(unixFile *pFile){
7391 int rc = SQLITE_OK; /* Subroutine return code */
7392 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
7393 unixFile *conchFile; /* Name of the conch file */
7395 pCtx = (proxyLockingContext *)pFile->lockingContext;
7396 conchFile = pCtx->conchFile;
7397 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
7398 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
7399 osGetpid(0)));
7400 if( pCtx->conchHeld>0 ){
7401 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7403 pCtx->conchHeld = 0;
7404 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
7405 (rc==SQLITE_OK ? "ok" : "failed")));
7406 return rc;
7410 ** Given the name of a database file, compute the name of its conch file.
7411 ** Store the conch filename in memory obtained from sqlite3_malloc64().
7412 ** Make *pConchPath point to the new name. Return SQLITE_OK on success
7413 ** or SQLITE_NOMEM if unable to obtain memory.
7415 ** The caller is responsible for ensuring that the allocated memory
7416 ** space is eventually freed.
7418 ** *pConchPath is set to NULL if a memory allocation error occurs.
7420 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7421 int i; /* Loop counter */
7422 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
7423 char *conchPath; /* buffer in which to construct conch name */
7425 /* Allocate space for the conch filename and initialize the name to
7426 ** the name of the original database file. */
7427 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
7428 if( conchPath==0 ){
7429 return SQLITE_NOMEM_BKPT;
7431 memcpy(conchPath, dbPath, len+1);
7433 /* now insert a "." before the last / character */
7434 for( i=(len-1); i>=0; i-- ){
7435 if( conchPath[i]=='/' ){
7436 i++;
7437 break;
7440 conchPath[i]='.';
7441 while ( i<len ){
7442 conchPath[i+1]=dbPath[i];
7443 i++;
7446 /* append the "-conch" suffix to the file */
7447 memcpy(&conchPath[i+1], "-conch", 7);
7448 assert( (int)strlen(conchPath) == len+7 );
7450 return SQLITE_OK;
7454 /* Takes a fully configured proxy locking-style unix file and switches
7455 ** the local lock file path
7457 static int switchLockProxyPath(unixFile *pFile, const char *path) {
7458 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7459 char *oldPath = pCtx->lockProxyPath;
7460 int rc = SQLITE_OK;
7462 if( pFile->eFileLock!=NO_LOCK ){
7463 return SQLITE_BUSY;
7466 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7467 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7468 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7469 return SQLITE_OK;
7470 }else{
7471 unixFile *lockProxy = pCtx->lockProxy;
7472 pCtx->lockProxy=NULL;
7473 pCtx->conchHeld = 0;
7474 if( lockProxy!=NULL ){
7475 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7476 if( rc ) return rc;
7477 sqlite3_free(lockProxy);
7479 sqlite3_free(oldPath);
7480 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7483 return rc;
7487 ** pFile is a file that has been opened by a prior xOpen call. dbPath
7488 ** is a string buffer at least MAXPATHLEN+1 characters in size.
7490 ** This routine find the filename associated with pFile and writes it
7491 ** int dbPath.
7493 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
7494 #if defined(__APPLE__)
7495 if( pFile->pMethod == &afpIoMethods ){
7496 /* afp style keeps a reference to the db path in the filePath field
7497 ** of the struct */
7498 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
7499 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7500 MAXPATHLEN);
7501 } else
7502 #endif
7503 if( pFile->pMethod == &dotlockIoMethods ){
7504 /* dot lock style uses the locking context to store the dot lock
7505 ** file path */
7506 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7507 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7508 }else{
7509 /* all other styles use the locking context to store the db file path */
7510 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
7511 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
7513 return SQLITE_OK;
7517 ** Takes an already filled in unix file and alters it so all file locking
7518 ** will be performed on the local proxy lock file. The following fields
7519 ** are preserved in the locking context so that they can be restored and
7520 ** the unix structure properly cleaned up at close time:
7521 ** ->lockingContext
7522 ** ->pMethod
7524 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7525 proxyLockingContext *pCtx;
7526 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7527 char *lockPath=NULL;
7528 int rc = SQLITE_OK;
7530 if( pFile->eFileLock!=NO_LOCK ){
7531 return SQLITE_BUSY;
7533 proxyGetDbPathForUnixFile(pFile, dbPath);
7534 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7535 lockPath=NULL;
7536 }else{
7537 lockPath=(char *)path;
7540 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
7541 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
7543 pCtx = sqlite3_malloc64( sizeof(*pCtx) );
7544 if( pCtx==0 ){
7545 return SQLITE_NOMEM_BKPT;
7547 memset(pCtx, 0, sizeof(*pCtx));
7549 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7550 if( rc==SQLITE_OK ){
7551 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7552 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7553 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7554 ** (c) the file system is read-only, then enable no-locking access.
7555 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7556 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7558 struct statfs fsInfo;
7559 struct stat conchInfo;
7560 int goLockless = 0;
7562 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
7563 int err = errno;
7564 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7565 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7568 if( goLockless ){
7569 pCtx->conchHeld = -1; /* read only FS/ lockless */
7570 rc = SQLITE_OK;
7574 if( rc==SQLITE_OK && lockPath ){
7575 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7578 if( rc==SQLITE_OK ){
7579 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7580 if( pCtx->dbPath==NULL ){
7581 rc = SQLITE_NOMEM_BKPT;
7584 if( rc==SQLITE_OK ){
7585 /* all memory is allocated, proxys are created and assigned,
7586 ** switch the locking context and pMethod then return.
7588 pCtx->oldLockingContext = pFile->lockingContext;
7589 pFile->lockingContext = pCtx;
7590 pCtx->pOldMethod = pFile->pMethod;
7591 pFile->pMethod = &proxyIoMethods;
7592 }else{
7593 if( pCtx->conchFile ){
7594 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
7595 sqlite3_free(pCtx->conchFile);
7597 sqlite3DbFree(0, pCtx->lockProxyPath);
7598 sqlite3_free(pCtx->conchFilePath);
7599 sqlite3_free(pCtx);
7601 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7602 (rc==SQLITE_OK ? "ok" : "failed")));
7603 return rc;
7608 ** This routine handles sqlite3_file_control() calls that are specific
7609 ** to proxy locking.
7611 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7612 switch( op ){
7613 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
7614 unixFile *pFile = (unixFile*)id;
7615 if( pFile->pMethod == &proxyIoMethods ){
7616 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7617 proxyTakeConch(pFile);
7618 if( pCtx->lockProxyPath ){
7619 *(const char **)pArg = pCtx->lockProxyPath;
7620 }else{
7621 *(const char **)pArg = ":auto: (not held)";
7623 } else {
7624 *(const char **)pArg = NULL;
7626 return SQLITE_OK;
7628 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
7629 unixFile *pFile = (unixFile*)id;
7630 int rc = SQLITE_OK;
7631 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7632 if( pArg==NULL || (const char *)pArg==0 ){
7633 if( isProxyStyle ){
7634 /* turn off proxy locking - not supported. If support is added for
7635 ** switching proxy locking mode off then it will need to fail if
7636 ** the journal mode is WAL mode.
7638 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7639 }else{
7640 /* turn off proxy locking - already off - NOOP */
7641 rc = SQLITE_OK;
7643 }else{
7644 const char *proxyPath = (const char *)pArg;
7645 if( isProxyStyle ){
7646 proxyLockingContext *pCtx =
7647 (proxyLockingContext*)pFile->lockingContext;
7648 if( !strcmp(pArg, ":auto:")
7649 || (pCtx->lockProxyPath &&
7650 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7652 rc = SQLITE_OK;
7653 }else{
7654 rc = switchLockProxyPath(pFile, proxyPath);
7656 }else{
7657 /* turn on proxy file locking */
7658 rc = proxyTransformUnixFile(pFile, proxyPath);
7661 return rc;
7663 default: {
7664 assert( 0 ); /* The call assures that only valid opcodes are sent */
7667 /*NOTREACHED*/ assert(0);
7668 return SQLITE_ERROR;
7672 ** Within this division (the proxying locking implementation) the procedures
7673 ** above this point are all utilities. The lock-related methods of the
7674 ** proxy-locking sqlite3_io_method object follow.
7679 ** This routine checks if there is a RESERVED lock held on the specified
7680 ** file by this or any other process. If such a lock is held, set *pResOut
7681 ** to a non-zero value otherwise *pResOut is set to zero. The return value
7682 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7684 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7685 unixFile *pFile = (unixFile*)id;
7686 int rc = proxyTakeConch(pFile);
7687 if( rc==SQLITE_OK ){
7688 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7689 if( pCtx->conchHeld>0 ){
7690 unixFile *proxy = pCtx->lockProxy;
7691 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7692 }else{ /* conchHeld < 0 is lockless */
7693 pResOut=0;
7696 return rc;
7700 ** Lock the file with the lock specified by parameter eFileLock - one
7701 ** of the following:
7703 ** (1) SHARED_LOCK
7704 ** (2) RESERVED_LOCK
7705 ** (3) PENDING_LOCK
7706 ** (4) EXCLUSIVE_LOCK
7708 ** Sometimes when requesting one lock state, additional lock states
7709 ** are inserted in between. The locking might fail on one of the later
7710 ** transitions leaving the lock state different from what it started but
7711 ** still short of its goal. The following chart shows the allowed
7712 ** transitions and the inserted intermediate states:
7714 ** UNLOCKED -> SHARED
7715 ** SHARED -> RESERVED
7716 ** SHARED -> (PENDING) -> EXCLUSIVE
7717 ** RESERVED -> (PENDING) -> EXCLUSIVE
7718 ** PENDING -> EXCLUSIVE
7720 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
7721 ** routine to lower a locking level.
7723 static int proxyLock(sqlite3_file *id, int eFileLock) {
7724 unixFile *pFile = (unixFile*)id;
7725 int rc = proxyTakeConch(pFile);
7726 if( rc==SQLITE_OK ){
7727 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7728 if( pCtx->conchHeld>0 ){
7729 unixFile *proxy = pCtx->lockProxy;
7730 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7731 pFile->eFileLock = proxy->eFileLock;
7732 }else{
7733 /* conchHeld < 0 is lockless */
7736 return rc;
7741 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
7742 ** must be either NO_LOCK or SHARED_LOCK.
7744 ** If the locking level of the file descriptor is already at or below
7745 ** the requested locking level, this routine is a no-op.
7747 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
7748 unixFile *pFile = (unixFile*)id;
7749 int rc = proxyTakeConch(pFile);
7750 if( rc==SQLITE_OK ){
7751 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7752 if( pCtx->conchHeld>0 ){
7753 unixFile *proxy = pCtx->lockProxy;
7754 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7755 pFile->eFileLock = proxy->eFileLock;
7756 }else{
7757 /* conchHeld < 0 is lockless */
7760 return rc;
7764 ** Close a file that uses proxy locks.
7766 static int proxyClose(sqlite3_file *id) {
7767 if( ALWAYS(id) ){
7768 unixFile *pFile = (unixFile*)id;
7769 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7770 unixFile *lockProxy = pCtx->lockProxy;
7771 unixFile *conchFile = pCtx->conchFile;
7772 int rc = SQLITE_OK;
7774 if( lockProxy ){
7775 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7776 if( rc ) return rc;
7777 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7778 if( rc ) return rc;
7779 sqlite3_free(lockProxy);
7780 pCtx->lockProxy = 0;
7782 if( conchFile ){
7783 if( pCtx->conchHeld ){
7784 rc = proxyReleaseConch(pFile);
7785 if( rc ) return rc;
7787 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7788 if( rc ) return rc;
7789 sqlite3_free(conchFile);
7791 sqlite3DbFree(0, pCtx->lockProxyPath);
7792 sqlite3_free(pCtx->conchFilePath);
7793 sqlite3DbFree(0, pCtx->dbPath);
7794 /* restore the original locking context and pMethod then close it */
7795 pFile->lockingContext = pCtx->oldLockingContext;
7796 pFile->pMethod = pCtx->pOldMethod;
7797 sqlite3_free(pCtx);
7798 return pFile->pMethod->xClose(id);
7800 return SQLITE_OK;
7805 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
7807 ** The proxy locking style is intended for use with AFP filesystems.
7808 ** And since AFP is only supported on MacOSX, the proxy locking is also
7809 ** restricted to MacOSX.
7812 ******************* End of the proxy lock implementation **********************
7813 ******************************************************************************/
7816 ** Initialize the operating system interface.
7818 ** This routine registers all VFS implementations for unix-like operating
7819 ** systems. This routine, and the sqlite3_os_end() routine that follows,
7820 ** should be the only routines in this file that are visible from other
7821 ** files.
7823 ** This routine is called once during SQLite initialization and by a
7824 ** single thread. The memory allocation and mutex subsystems have not
7825 ** necessarily been initialized when this routine is called, and so they
7826 ** should not be used.
7828 int sqlite3_os_init(void){
7830 ** The following macro defines an initializer for an sqlite3_vfs object.
7831 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7832 ** to the "finder" function. (pAppData is a pointer to a pointer because
7833 ** silly C90 rules prohibit a void* from being cast to a function pointer
7834 ** and so we have to go through the intermediate pointer to avoid problems
7835 ** when compiling with -pedantic-errors on GCC.)
7837 ** The FINDER parameter to this macro is the name of the pointer to the
7838 ** finder-function. The finder-function returns a pointer to the
7839 ** sqlite_io_methods object that implements the desired locking
7840 ** behaviors. See the division above that contains the IOMETHODS
7841 ** macro for addition information on finder-functions.
7843 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7844 ** object. But the "autolockIoFinder" available on MacOSX does a little
7845 ** more than that; it looks at the filesystem type that hosts the
7846 ** database file and tries to choose an locking method appropriate for
7847 ** that filesystem time.
7849 #define UNIXVFS(VFSNAME, FINDER) { \
7850 3, /* iVersion */ \
7851 sizeof(unixFile), /* szOsFile */ \
7852 MAX_PATHNAME, /* mxPathname */ \
7853 0, /* pNext */ \
7854 VFSNAME, /* zName */ \
7855 (void*)&FINDER, /* pAppData */ \
7856 unixOpen, /* xOpen */ \
7857 unixDelete, /* xDelete */ \
7858 unixAccess, /* xAccess */ \
7859 unixFullPathname, /* xFullPathname */ \
7860 unixDlOpen, /* xDlOpen */ \
7861 unixDlError, /* xDlError */ \
7862 unixDlSym, /* xDlSym */ \
7863 unixDlClose, /* xDlClose */ \
7864 unixRandomness, /* xRandomness */ \
7865 unixSleep, /* xSleep */ \
7866 unixCurrentTime, /* xCurrentTime */ \
7867 unixGetLastError, /* xGetLastError */ \
7868 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
7869 unixSetSystemCall, /* xSetSystemCall */ \
7870 unixGetSystemCall, /* xGetSystemCall */ \
7871 unixNextSystemCall, /* xNextSystemCall */ \
7875 ** All default VFSes for unix are contained in the following array.
7877 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7878 ** by the SQLite core when the VFS is registered. So the following
7879 ** array cannot be const.
7881 static sqlite3_vfs aVfs[] = {
7882 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
7883 UNIXVFS("unix", autolockIoFinder ),
7884 #elif OS_VXWORKS
7885 UNIXVFS("unix", vxworksIoFinder ),
7886 #else
7887 UNIXVFS("unix", posixIoFinder ),
7888 #endif
7889 UNIXVFS("unix-none", nolockIoFinder ),
7890 UNIXVFS("unix-dotfile", dotlockIoFinder ),
7891 UNIXVFS("unix-excl", posixIoFinder ),
7892 #if OS_VXWORKS
7893 UNIXVFS("unix-namedsem", semIoFinder ),
7894 #endif
7895 #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
7896 UNIXVFS("unix-posix", posixIoFinder ),
7897 #endif
7898 #if SQLITE_ENABLE_LOCKING_STYLE
7899 UNIXVFS("unix-flock", flockIoFinder ),
7900 #endif
7901 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
7902 UNIXVFS("unix-afp", afpIoFinder ),
7903 UNIXVFS("unix-nfs", nfsIoFinder ),
7904 UNIXVFS("unix-proxy", proxyIoFinder ),
7905 #endif
7907 unsigned int i; /* Loop counter */
7909 /* Double-check that the aSyscall[] array has been constructed
7910 ** correctly. See ticket [bb3a86e890c8e96ab] */
7911 assert( ArraySize(aSyscall)==29 );
7913 /* Register all VFSes defined in the aVfs[] array */
7914 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
7915 sqlite3_vfs_register(&aVfs[i], i==0);
7917 unixBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
7918 return SQLITE_OK;
7922 ** Shutdown the operating system interface.
7924 ** Some operating systems might need to do some cleanup in this routine,
7925 ** to release dynamically allocated objects. But not on unix.
7926 ** This routine is a no-op for unix.
7928 int sqlite3_os_end(void){
7929 unixBigLock = 0;
7930 return SQLITE_OK;
7933 #endif /* SQLITE_OS_UNIX */