Merge sqlite-release(3.44.2) into prerelease-integration
[sqlcipher.git] / src / os_unix.c
bloba33e6f4dff3984f1afee0744d69df9d3a18d6c7f
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 labelled.
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__) || defined(__linux__)
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> /* amalgamator: keep */
91 #include <sys/stat.h> /* amalgamator: keep */
92 #include <fcntl.h>
93 #include <sys/ioctl.h>
94 #include <unistd.h> /* amalgamator: keep */
95 #include <time.h>
96 #include <sys/time.h> /* amalgamator: keep */
97 #include <errno.h>
98 #if (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) \
99 && !defined(SQLITE_WASI)
100 # include <sys/mman.h>
101 #endif
103 #if SQLITE_ENABLE_LOCKING_STYLE
104 # include <sys/ioctl.h>
105 # include <sys/file.h>
106 # include <sys/param.h>
107 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
110 ** Try to determine if gethostuuid() is available based on standard
111 ** macros. This might sometimes compute the wrong value for some
112 ** obscure platforms. For those cases, simply compile with one of
113 ** the following:
115 ** -DHAVE_GETHOSTUUID=0
116 ** -DHAVE_GETHOSTUUID=1
118 ** None if this matters except when building on Apple products with
119 ** -DSQLITE_ENABLE_LOCKING_STYLE.
121 #ifndef HAVE_GETHOSTUUID
122 # define HAVE_GETHOSTUUID 0
123 # if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
124 (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
125 # if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
126 && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))\
127 && (!defined(TARGET_OS_MACCATALYST) || (TARGET_OS_MACCATALYST==0))
128 # undef HAVE_GETHOSTUUID
129 # define HAVE_GETHOSTUUID 1
130 # else
131 # warning "gethostuuid() is disabled."
132 # endif
133 # endif
134 #endif
137 #if OS_VXWORKS
138 # include <sys/ioctl.h>
139 # include <semaphore.h>
140 # include <limits.h>
141 #endif /* OS_VXWORKS */
143 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
144 # include <sys/mount.h>
145 #endif
147 #ifdef HAVE_UTIME
148 # include <utime.h>
149 #endif
152 ** Allowed values of unixFile.fsFlags
154 #define SQLITE_FSFLAGS_IS_MSDOS 0x1
157 ** If we are to be thread-safe, include the pthreads header.
159 #if SQLITE_THREADSAFE
160 # include <pthread.h>
161 #endif
164 ** Default permissions when creating a new file
166 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
167 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
168 #endif
171 ** Default permissions when creating auto proxy dir
173 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
174 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
175 #endif
178 ** Maximum supported path-length.
180 #define MAX_PATHNAME 512
183 ** Maximum supported symbolic links
185 #define SQLITE_MAX_SYMLINKS 100
188 ** Remove and stub certain info for WASI (WebAssembly System
189 ** Interface) builds.
191 #ifdef SQLITE_WASI
192 # undef HAVE_FCHMOD
193 # undef HAVE_FCHOWN
194 # undef HAVE_MREMAP
195 # define HAVE_MREMAP 0
196 # ifndef SQLITE_DEFAULT_UNIX_VFS
197 # define SQLITE_DEFAULT_UNIX_VFS "unix-dotfile"
198 /* ^^^ should SQLITE_DEFAULT_UNIX_VFS be "unix-none"? */
199 # endif
200 # ifndef F_RDLCK
201 # define F_RDLCK 0
202 # define F_WRLCK 1
203 # define F_UNLCK 2
204 # if __LONG_MAX == 0x7fffffffL
205 # define F_GETLK 12
206 # define F_SETLK 13
207 # define F_SETLKW 14
208 # else
209 # define F_GETLK 5
210 # define F_SETLK 6
211 # define F_SETLKW 7
212 # endif
213 # endif
214 #else /* !SQLITE_WASI */
215 # ifndef HAVE_FCHMOD
216 # define HAVE_FCHMOD
217 # endif
218 #endif /* SQLITE_WASI */
220 #ifdef SQLITE_WASI
221 # define osGetpid(X) (pid_t)1
222 #else
223 /* Always cast the getpid() return type for compatibility with
224 ** kernel modules in VxWorks. */
225 # define osGetpid(X) (pid_t)getpid()
226 #endif
229 ** Only set the lastErrno if the error code is a real error and not
230 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
232 #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
234 /* Forward references */
235 typedef struct unixShm unixShm; /* Connection shared memory */
236 typedef struct unixShmNode unixShmNode; /* Shared memory instance */
237 typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
238 typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
241 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
242 ** cannot be closed immediately. In these cases, instances of the following
243 ** structure are used to store the file descriptor while waiting for an
244 ** opportunity to either close or reuse it.
246 struct UnixUnusedFd {
247 int fd; /* File descriptor to close */
248 int flags; /* Flags this file descriptor was opened with */
249 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
253 ** The unixFile structure is subclass of sqlite3_file specific to the unix
254 ** VFS implementations.
256 typedef struct unixFile unixFile;
257 struct unixFile {
258 sqlite3_io_methods const *pMethod; /* Always the first entry */
259 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
260 unixInodeInfo *pInode; /* Info about locks on this inode */
261 int h; /* The file descriptor */
262 unsigned char eFileLock; /* The type of lock held on this fd */
263 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
264 int lastErrno; /* The unix errno from last I/O error */
265 void *lockingContext; /* Locking style specific state */
266 UnixUnusedFd *pPreallocatedUnused; /* Pre-allocated UnixUnusedFd */
267 const char *zPath; /* Name of the file */
268 unixShm *pShm; /* Shared memory segment information */
269 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
270 #if SQLITE_MAX_MMAP_SIZE>0
271 int nFetchOut; /* Number of outstanding xFetch refs */
272 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
273 sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
274 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
275 void *pMapRegion; /* Memory mapped region */
276 #endif
277 int sectorSize; /* Device sector size */
278 int deviceCharacteristics; /* Precomputed device characteristics */
279 #if SQLITE_ENABLE_LOCKING_STYLE
280 int openFlags; /* The flags specified at open() */
281 #endif
282 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
283 unsigned fsFlags; /* cached details from statfs() */
284 #endif
285 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
286 unsigned iBusyTimeout; /* Wait this many millisec on locks */
287 #endif
288 #if OS_VXWORKS
289 struct vxworksFileId *pId; /* Unique file ID */
290 #endif
291 #ifdef SQLITE_DEBUG
292 /* The next group of variables are used to track whether or not the
293 ** transaction counter in bytes 24-27 of database files are updated
294 ** whenever any part of the database changes. An assertion fault will
295 ** occur if a file is updated without also updating the transaction
296 ** counter. This test is made to avoid new problems similar to the
297 ** one described by ticket #3584.
299 unsigned char transCntrChng; /* True if the transaction counter changed */
300 unsigned char dbUpdate; /* True if any part of database file changed */
301 unsigned char inNormalWrite; /* True if in a normal write operation */
303 #endif
305 #ifdef SQLITE_TEST
306 /* In test mode, increase the size of this structure a bit so that
307 ** it is larger than the struct CrashFile defined in test6.c.
309 char aPadding[32];
310 #endif
313 /* This variable holds the process id (pid) from when the xRandomness()
314 ** method was called. If xOpen() is called from a different process id,
315 ** indicating that a fork() has occurred, the PRNG will be reset.
317 static pid_t randomnessPid = 0;
320 ** Allowed values for the unixFile.ctrlFlags bitmask:
322 #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
323 #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
324 #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
325 #ifndef SQLITE_DISABLE_DIRSYNC
326 # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
327 #else
328 # define UNIXFILE_DIRSYNC 0x00
329 #endif
330 #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
331 #define UNIXFILE_DELETE 0x20 /* Delete on close */
332 #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
333 #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
336 ** Include code that is common to all os_*.c files
338 #include "os_common.h"
341 ** Define various macros that are missing from some systems.
343 #ifndef O_LARGEFILE
344 # define O_LARGEFILE 0
345 #endif
346 #ifdef SQLITE_DISABLE_LFS
347 # undef O_LARGEFILE
348 # define O_LARGEFILE 0
349 #endif
350 #ifndef O_NOFOLLOW
351 # define O_NOFOLLOW 0
352 #endif
353 #ifndef O_BINARY
354 # define O_BINARY 0
355 #endif
358 ** The threadid macro resolves to the thread-id or to 0. Used for
359 ** testing and debugging only.
361 #if SQLITE_THREADSAFE
362 #define threadid pthread_self()
363 #else
364 #define threadid 0
365 #endif
368 ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
370 #if !defined(HAVE_MREMAP)
371 # if defined(__linux__) && defined(_GNU_SOURCE)
372 # define HAVE_MREMAP 1
373 # else
374 # define HAVE_MREMAP 0
375 # endif
376 #endif
379 ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
380 ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
382 #ifdef __ANDROID__
383 # define lseek lseek64
384 #endif
386 #ifdef __linux__
388 ** Linux-specific IOCTL magic numbers used for controlling F2FS
390 #define F2FS_IOCTL_MAGIC 0xf5
391 #define F2FS_IOC_START_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 1)
392 #define F2FS_IOC_COMMIT_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 2)
393 #define F2FS_IOC_START_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 3)
394 #define F2FS_IOC_ABORT_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 5)
395 #define F2FS_IOC_GET_FEATURES _IOR(F2FS_IOCTL_MAGIC, 12, u32)
396 #define F2FS_FEATURE_ATOMIC_WRITE 0x0004
397 #endif /* __linux__ */
401 ** Different Unix systems declare open() in different ways. Same use
402 ** open(const char*,int,mode_t). Others use open(const char*,int,...).
403 ** The difference is important when using a pointer to the function.
405 ** The safest way to deal with the problem is to always use this wrapper
406 ** which always has the same well-defined interface.
408 static int posixOpen(const char *zFile, int flags, int mode){
409 return open(zFile, flags, mode);
412 /* Forward reference */
413 static int openDirectory(const char*, int*);
414 static int unixGetpagesize(void);
417 ** Many system calls are accessed through pointer-to-functions so that
418 ** they may be overridden at runtime to facilitate fault injection during
419 ** testing and sandboxing. The following array holds the names and pointers
420 ** to all overrideable system calls.
422 static struct unix_syscall {
423 const char *zName; /* Name of the system call */
424 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
425 sqlite3_syscall_ptr pDefault; /* Default value */
426 } aSyscall[] = {
427 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
428 #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
430 { "close", (sqlite3_syscall_ptr)close, 0 },
431 #define osClose ((int(*)(int))aSyscall[1].pCurrent)
433 { "access", (sqlite3_syscall_ptr)access, 0 },
434 #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
436 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
437 #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
439 { "stat", (sqlite3_syscall_ptr)stat, 0 },
440 #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
443 ** The DJGPP compiler environment looks mostly like Unix, but it
444 ** lacks the fcntl() system call. So redefine fcntl() to be something
445 ** that always succeeds. This means that locking does not occur under
446 ** DJGPP. But it is DOS - what did you expect?
448 #ifdef __DJGPP__
449 { "fstat", 0, 0 },
450 #define osFstat(a,b,c) 0
451 #else
452 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
453 #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
454 #endif
456 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
457 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
459 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
460 #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
462 { "read", (sqlite3_syscall_ptr)read, 0 },
463 #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
465 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
466 { "pread", (sqlite3_syscall_ptr)pread, 0 },
467 #else
468 { "pread", (sqlite3_syscall_ptr)0, 0 },
469 #endif
470 #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
472 #if defined(USE_PREAD64)
473 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
474 #else
475 { "pread64", (sqlite3_syscall_ptr)0, 0 },
476 #endif
477 #define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
479 { "write", (sqlite3_syscall_ptr)write, 0 },
480 #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
482 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
483 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
484 #else
485 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
486 #endif
487 #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
488 aSyscall[12].pCurrent)
490 #if defined(USE_PREAD64)
491 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
492 #else
493 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
494 #endif
495 #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off64_t))\
496 aSyscall[13].pCurrent)
498 #if defined(HAVE_FCHMOD)
499 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
500 #else
501 { "fchmod", (sqlite3_syscall_ptr)0, 0 },
502 #endif
503 #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
505 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
506 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
507 #else
508 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
509 #endif
510 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
512 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
513 #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
515 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
516 #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
518 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
519 #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
521 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
522 #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
524 #if defined(HAVE_FCHOWN)
525 { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
526 #else
527 { "fchown", (sqlite3_syscall_ptr)0, 0 },
528 #endif
529 #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
531 #if defined(HAVE_FCHOWN)
532 { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
533 #else
534 { "geteuid", (sqlite3_syscall_ptr)0, 0 },
535 #endif
536 #define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
538 #if (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) \
539 && !defined(SQLITE_WASI)
540 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
541 #else
542 { "mmap", (sqlite3_syscall_ptr)0, 0 },
543 #endif
544 #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
546 #if (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) \
547 && !defined(SQLITE_WASI)
548 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
549 #else
550 { "munmap", (sqlite3_syscall_ptr)0, 0 },
551 #endif
552 #define osMunmap ((int(*)(void*,size_t))aSyscall[23].pCurrent)
554 #if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
555 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
556 #else
557 { "mremap", (sqlite3_syscall_ptr)0, 0 },
558 #endif
559 #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
561 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
562 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
563 #else
564 { "getpagesize", (sqlite3_syscall_ptr)0, 0 },
565 #endif
566 #define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
568 #if defined(HAVE_READLINK)
569 { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
570 #else
571 { "readlink", (sqlite3_syscall_ptr)0, 0 },
572 #endif
573 #define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
575 #if defined(HAVE_LSTAT)
576 { "lstat", (sqlite3_syscall_ptr)lstat, 0 },
577 #else
578 { "lstat", (sqlite3_syscall_ptr)0, 0 },
579 #endif
580 #define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
582 #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
583 # ifdef __ANDROID__
584 { "ioctl", (sqlite3_syscall_ptr)(int(*)(int, int, ...))ioctl, 0 },
585 #define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent)
586 # else
587 { "ioctl", (sqlite3_syscall_ptr)ioctl, 0 },
588 #define osIoctl ((int(*)(int,unsigned long,...))aSyscall[28].pCurrent)
589 # endif
590 #else
591 { "ioctl", (sqlite3_syscall_ptr)0, 0 },
592 #endif
594 }; /* End of the overrideable system calls */
598 ** On some systems, calls to fchown() will trigger a message in a security
599 ** log if they come from non-root processes. So avoid calling fchown() if
600 ** we are not running as root.
602 static int robustFchown(int fd, uid_t uid, gid_t gid){
603 #if defined(HAVE_FCHOWN)
604 return osGeteuid() ? 0 : osFchown(fd,uid,gid);
605 #else
606 return 0;
607 #endif
611 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
612 ** "unix" VFSes. Return SQLITE_OK upon successfully updating the
613 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
614 ** system call named zName.
616 static int unixSetSystemCall(
617 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
618 const char *zName, /* Name of system call to override */
619 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
621 unsigned int i;
622 int rc = SQLITE_NOTFOUND;
624 UNUSED_PARAMETER(pNotUsed);
625 if( zName==0 ){
626 /* If no zName is given, restore all system calls to their default
627 ** settings and return NULL
629 rc = SQLITE_OK;
630 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
631 if( aSyscall[i].pDefault ){
632 aSyscall[i].pCurrent = aSyscall[i].pDefault;
635 }else{
636 /* If zName is specified, operate on only the one system call
637 ** specified.
639 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
640 if( strcmp(zName, aSyscall[i].zName)==0 ){
641 if( aSyscall[i].pDefault==0 ){
642 aSyscall[i].pDefault = aSyscall[i].pCurrent;
644 rc = SQLITE_OK;
645 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
646 aSyscall[i].pCurrent = pNewFunc;
647 break;
651 return rc;
655 ** Return the value of a system call. Return NULL if zName is not a
656 ** recognized system call name. NULL is also returned if the system call
657 ** is currently undefined.
659 static sqlite3_syscall_ptr unixGetSystemCall(
660 sqlite3_vfs *pNotUsed,
661 const char *zName
663 unsigned int i;
665 UNUSED_PARAMETER(pNotUsed);
666 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
667 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
669 return 0;
673 ** Return the name of the first system call after zName. If zName==NULL
674 ** then return the name of the first system call. Return NULL if zName
675 ** is the last system call or if zName is not the name of a valid
676 ** system call.
678 static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
679 int i = -1;
681 UNUSED_PARAMETER(p);
682 if( zName ){
683 for(i=0; i<ArraySize(aSyscall)-1; i++){
684 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
687 for(i++; i<ArraySize(aSyscall); i++){
688 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
690 return 0;
694 ** Do not accept any file descriptor less than this value, in order to avoid
695 ** opening database file using file descriptors that are commonly used for
696 ** standard input, output, and error.
698 #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
699 # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
700 #endif
703 ** Invoke open(). Do so multiple times, until it either succeeds or
704 ** fails for some reason other than EINTR.
706 ** If the file creation mode "m" is 0 then set it to the default for
707 ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
708 ** 0644) as modified by the system umask. If m is not 0, then
709 ** make the file creation mode be exactly m ignoring the umask.
711 ** The m parameter will be non-zero only when creating -wal, -journal,
712 ** and -shm files. We want those files to have *exactly* the same
713 ** permissions as their original database, unadulterated by the umask.
714 ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
715 ** transaction crashes and leaves behind hot journals, then any
716 ** process that is able to write to the database will also be able to
717 ** recover the hot journals.
719 static int robust_open(const char *z, int f, mode_t m){
720 int fd;
721 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
722 while(1){
723 #if defined(O_CLOEXEC)
724 fd = osOpen(z,f|O_CLOEXEC,m2);
725 #else
726 fd = osOpen(z,f,m2);
727 #endif
728 if( fd<0 ){
729 if( errno==EINTR ) continue;
730 break;
732 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
733 if( (f & (O_EXCL|O_CREAT))==(O_EXCL|O_CREAT) ){
734 (void)osUnlink(z);
736 osClose(fd);
737 sqlite3_log(SQLITE_WARNING,
738 "attempt to open \"%s\" as file descriptor %d", z, fd);
739 fd = -1;
740 if( osOpen("/dev/null", O_RDONLY, m)<0 ) break;
742 if( fd>=0 ){
743 if( m!=0 ){
744 struct stat statbuf;
745 if( osFstat(fd, &statbuf)==0
746 && statbuf.st_size==0
747 && (statbuf.st_mode&0777)!=m
749 osFchmod(fd, m);
752 #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
753 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
754 #endif
756 return fd;
760 ** Helper functions to obtain and relinquish the global mutex. The
761 ** global mutex is used to protect the unixInodeInfo and
762 ** vxworksFileId objects used by this file, all of which may be
763 ** shared by multiple threads.
765 ** Function unixMutexHeld() is used to assert() that the global mutex
766 ** is held when required. This function is only used as part of assert()
767 ** statements. e.g.
769 ** unixEnterMutex()
770 ** assert( unixMutexHeld() );
771 ** unixEnterLeave()
773 ** To prevent deadlock, the global unixBigLock must must be acquired
774 ** before the unixInodeInfo.pLockMutex mutex, if both are held. It is
775 ** OK to get the pLockMutex without holding unixBigLock first, but if
776 ** that happens, the unixBigLock mutex must not be acquired until after
777 ** pLockMutex is released.
779 ** OK: enter(unixBigLock), enter(pLockInfo)
780 ** OK: enter(unixBigLock)
781 ** OK: enter(pLockInfo)
782 ** ERROR: enter(pLockInfo), enter(unixBigLock)
784 static sqlite3_mutex *unixBigLock = 0;
785 static void unixEnterMutex(void){
786 assert( sqlite3_mutex_notheld(unixBigLock) ); /* Not a recursive mutex */
787 sqlite3_mutex_enter(unixBigLock);
789 static void unixLeaveMutex(void){
790 assert( sqlite3_mutex_held(unixBigLock) );
791 sqlite3_mutex_leave(unixBigLock);
793 #ifdef SQLITE_DEBUG
794 static int unixMutexHeld(void) {
795 return sqlite3_mutex_held(unixBigLock);
797 #endif
800 #ifdef SQLITE_HAVE_OS_TRACE
802 ** Helper function for printing out trace information from debugging
803 ** binaries. This returns the string representation of the supplied
804 ** integer lock-type.
806 static const char *azFileLock(int eFileLock){
807 switch( eFileLock ){
808 case NO_LOCK: return "NONE";
809 case SHARED_LOCK: return "SHARED";
810 case RESERVED_LOCK: return "RESERVED";
811 case PENDING_LOCK: return "PENDING";
812 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
814 return "ERROR";
816 #endif
818 #ifdef SQLITE_LOCK_TRACE
820 ** Print out information about all locking operations.
822 ** This routine is used for troubleshooting locks on multithreaded
823 ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
824 ** command-line option on the compiler. This code is normally
825 ** turned off.
827 static int lockTrace(int fd, int op, struct flock *p){
828 char *zOpName, *zType;
829 int s;
830 int savedErrno;
831 if( op==F_GETLK ){
832 zOpName = "GETLK";
833 }else if( op==F_SETLK ){
834 zOpName = "SETLK";
835 }else{
836 s = osFcntl(fd, op, p);
837 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
838 return s;
840 if( p->l_type==F_RDLCK ){
841 zType = "RDLCK";
842 }else if( p->l_type==F_WRLCK ){
843 zType = "WRLCK";
844 }else if( p->l_type==F_UNLCK ){
845 zType = "UNLCK";
846 }else{
847 assert( 0 );
849 assert( p->l_whence==SEEK_SET );
850 s = osFcntl(fd, op, p);
851 savedErrno = errno;
852 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
853 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
854 (int)p->l_pid, s);
855 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
856 struct flock l2;
857 l2 = *p;
858 osFcntl(fd, F_GETLK, &l2);
859 if( l2.l_type==F_RDLCK ){
860 zType = "RDLCK";
861 }else if( l2.l_type==F_WRLCK ){
862 zType = "WRLCK";
863 }else if( l2.l_type==F_UNLCK ){
864 zType = "UNLCK";
865 }else{
866 assert( 0 );
868 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
869 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
871 errno = savedErrno;
872 return s;
874 #undef osFcntl
875 #define osFcntl lockTrace
876 #endif /* SQLITE_LOCK_TRACE */
879 ** Retry ftruncate() calls that fail due to EINTR
881 ** All calls to ftruncate() within this file should be made through
882 ** this wrapper. On the Android platform, bypassing the logic below
883 ** could lead to a corrupt database.
885 static int robust_ftruncate(int h, sqlite3_int64 sz){
886 int rc;
887 #ifdef __ANDROID__
888 /* On Android, ftruncate() always uses 32-bit offsets, even if
889 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
890 ** truncate a file to any size larger than 2GiB. Silently ignore any
891 ** such attempts. */
892 if( sz>(sqlite3_int64)0x7FFFFFFF ){
893 rc = SQLITE_OK;
894 }else
895 #endif
896 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
897 return rc;
901 ** This routine translates a standard POSIX errno code into something
902 ** useful to the clients of the sqlite3 functions. Specifically, it is
903 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
904 ** and a variety of "please close the file descriptor NOW" errors into
905 ** SQLITE_IOERR
907 ** Errors during initialization of locks, or file system support for locks,
908 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
910 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
911 assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
912 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
913 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
914 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
915 switch (posixError) {
916 case EACCES:
917 case EAGAIN:
918 case ETIMEDOUT:
919 case EBUSY:
920 case EINTR:
921 case ENOLCK:
922 /* random NFS retry error, unless during file system support
923 * introspection, in which it actually means what it says */
924 return SQLITE_BUSY;
926 case EPERM:
927 return SQLITE_PERM;
929 default:
930 return sqliteIOErr;
935 /******************************************************************************
936 ****************** Begin Unique File ID Utility Used By VxWorks ***************
938 ** On most versions of unix, we can get a unique ID for a file by concatenating
939 ** the device number and the inode number. But this does not work on VxWorks.
940 ** On VxWorks, a unique file id must be based on the canonical filename.
942 ** A pointer to an instance of the following structure can be used as a
943 ** unique file ID in VxWorks. Each instance of this structure contains
944 ** a copy of the canonical filename. There is also a reference count.
945 ** The structure is reclaimed when the number of pointers to it drops to
946 ** zero.
948 ** There are never very many files open at one time and lookups are not
949 ** a performance-critical path, so it is sufficient to put these
950 ** structures on a linked list.
952 struct vxworksFileId {
953 struct vxworksFileId *pNext; /* Next in a list of them all */
954 int nRef; /* Number of references to this one */
955 int nName; /* Length of the zCanonicalName[] string */
956 char *zCanonicalName; /* Canonical filename */
959 #if OS_VXWORKS
961 ** All unique filenames are held on a linked list headed by this
962 ** variable:
964 static struct vxworksFileId *vxworksFileList = 0;
967 ** Simplify a filename into its canonical form
968 ** by making the following changes:
970 ** * removing any trailing and duplicate /
971 ** * convert /./ into just /
972 ** * convert /A/../ where A is any simple name into just /
974 ** Changes are made in-place. Return the new name length.
976 ** The original filename is in z[0..n-1]. Return the number of
977 ** characters in the simplified name.
979 static int vxworksSimplifyName(char *z, int n){
980 int i, j;
981 while( n>1 && z[n-1]=='/' ){ n--; }
982 for(i=j=0; i<n; i++){
983 if( z[i]=='/' ){
984 if( z[i+1]=='/' ) continue;
985 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
986 i += 1;
987 continue;
989 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
990 while( j>0 && z[j-1]!='/' ){ j--; }
991 if( j>0 ){ j--; }
992 i += 2;
993 continue;
996 z[j++] = z[i];
998 z[j] = 0;
999 return j;
1003 ** Find a unique file ID for the given absolute pathname. Return
1004 ** a pointer to the vxworksFileId object. This pointer is the unique
1005 ** file ID.
1007 ** The nRef field of the vxworksFileId object is incremented before
1008 ** the object is returned. A new vxworksFileId object is created
1009 ** and added to the global list if necessary.
1011 ** If a memory allocation error occurs, return NULL.
1013 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
1014 struct vxworksFileId *pNew; /* search key and new file ID */
1015 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
1016 int n; /* Length of zAbsoluteName string */
1018 assert( zAbsoluteName[0]=='/' );
1019 n = (int)strlen(zAbsoluteName);
1020 pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
1021 if( pNew==0 ) return 0;
1022 pNew->zCanonicalName = (char*)&pNew[1];
1023 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
1024 n = vxworksSimplifyName(pNew->zCanonicalName, n);
1026 /* Search for an existing entry that matching the canonical name.
1027 ** If found, increment the reference count and return a pointer to
1028 ** the existing file ID.
1030 unixEnterMutex();
1031 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
1032 if( pCandidate->nName==n
1033 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
1035 sqlite3_free(pNew);
1036 pCandidate->nRef++;
1037 unixLeaveMutex();
1038 return pCandidate;
1042 /* No match was found. We will make a new file ID */
1043 pNew->nRef = 1;
1044 pNew->nName = n;
1045 pNew->pNext = vxworksFileList;
1046 vxworksFileList = pNew;
1047 unixLeaveMutex();
1048 return pNew;
1052 ** Decrement the reference count on a vxworksFileId object. Free
1053 ** the object when the reference count reaches zero.
1055 static void vxworksReleaseFileId(struct vxworksFileId *pId){
1056 unixEnterMutex();
1057 assert( pId->nRef>0 );
1058 pId->nRef--;
1059 if( pId->nRef==0 ){
1060 struct vxworksFileId **pp;
1061 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
1062 assert( *pp==pId );
1063 *pp = pId->pNext;
1064 sqlite3_free(pId);
1066 unixLeaveMutex();
1068 #endif /* OS_VXWORKS */
1069 /*************** End of Unique File ID Utility Used By VxWorks ****************
1070 ******************************************************************************/
1073 /******************************************************************************
1074 *************************** Posix Advisory Locking ****************************
1076 ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
1077 ** section 6.5.2.2 lines 483 through 490 specify that when a process
1078 ** sets or clears a lock, that operation overrides any prior locks set
1079 ** by the same process. It does not explicitly say so, but this implies
1080 ** that it overrides locks set by the same process using a different
1081 ** file descriptor. Consider this test case:
1083 ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
1084 ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
1086 ** Suppose ./file1 and ./file2 are really the same file (because
1087 ** one is a hard or symbolic link to the other) then if you set
1088 ** an exclusive lock on fd1, then try to get an exclusive lock
1089 ** on fd2, it works. I would have expected the second lock to
1090 ** fail since there was already a lock on the file due to fd1.
1091 ** But not so. Since both locks came from the same process, the
1092 ** second overrides the first, even though they were on different
1093 ** file descriptors opened on different file names.
1095 ** This means that we cannot use POSIX locks to synchronize file access
1096 ** among competing threads of the same process. POSIX locks will work fine
1097 ** to synchronize access for threads in separate processes, but not
1098 ** threads within the same process.
1100 ** To work around the problem, SQLite has to manage file locks internally
1101 ** on its own. Whenever a new database is opened, we have to find the
1102 ** specific inode of the database file (the inode is determined by the
1103 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
1104 ** and check for locks already existing on that inode. When locks are
1105 ** created or removed, we have to look at our own internal record of the
1106 ** locks to see if another thread has previously set a lock on that same
1107 ** inode.
1109 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
1110 ** For VxWorks, we have to use the alternative unique ID system based on
1111 ** canonical filename and implemented in the previous division.)
1113 ** The sqlite3_file structure for POSIX is no longer just an integer file
1114 ** descriptor. It is now a structure that holds the integer file
1115 ** descriptor and a pointer to a structure that describes the internal
1116 ** locks on the corresponding inode. There is one locking structure
1117 ** per inode, so if the same inode is opened twice, both unixFile structures
1118 ** point to the same locking structure. The locking structure keeps
1119 ** a reference count (so we will know when to delete it) and a "cnt"
1120 ** field that tells us its internal lock status. cnt==0 means the
1121 ** file is unlocked. cnt==-1 means the file has an exclusive lock.
1122 ** cnt>0 means there are cnt shared locks on the file.
1124 ** Any attempt to lock or unlock a file first checks the locking
1125 ** structure. The fcntl() system call is only invoked to set a
1126 ** POSIX lock if the internal lock structure transitions between
1127 ** a locked and an unlocked state.
1129 ** But wait: there are yet more problems with POSIX advisory locks.
1131 ** If you close a file descriptor that points to a file that has locks,
1132 ** all locks on that file that are owned by the current process are
1133 ** released. To work around this problem, each unixInodeInfo object
1134 ** maintains a count of the number of pending locks on the inode.
1135 ** When an attempt is made to close an unixFile, if there are
1136 ** other unixFile open on the same inode that are holding locks, the call
1137 ** to close() the file descriptor is deferred until all of the locks clear.
1138 ** The unixInodeInfo structure keeps a list of file descriptors that need to
1139 ** be closed and that list is walked (and cleared) when the last lock
1140 ** clears.
1142 ** Yet another problem: LinuxThreads do not play well with posix locks.
1144 ** Many older versions of linux use the LinuxThreads library which is
1145 ** not posix compliant. Under LinuxThreads, a lock created by thread
1146 ** A cannot be modified or overridden by a different thread B.
1147 ** Only thread A can modify the lock. Locking behavior is correct
1148 ** if the application uses the newer Native Posix Thread Library (NPTL)
1149 ** on linux - with NPTL a lock created by thread A can override locks
1150 ** in thread B. But there is no way to know at compile-time which
1151 ** threading library is being used. So there is no way to know at
1152 ** compile-time whether or not thread A can override locks on thread B.
1153 ** One has to do a run-time check to discover the behavior of the
1154 ** current process.
1156 ** SQLite used to support LinuxThreads. But support for LinuxThreads
1157 ** was dropped beginning with version 3.7.0. SQLite will still work with
1158 ** LinuxThreads provided that (1) there is no more than one connection
1159 ** per database file in the same process and (2) database connections
1160 ** do not move across threads.
1164 ** An instance of the following structure serves as the key used
1165 ** to locate a particular unixInodeInfo object.
1167 struct unixFileId {
1168 dev_t dev; /* Device number */
1169 #if OS_VXWORKS
1170 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
1171 #else
1172 /* We are told that some versions of Android contain a bug that
1173 ** sizes ino_t at only 32-bits instead of 64-bits. (See
1174 ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
1175 ** To work around this, always allocate 64-bits for the inode number.
1176 ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
1177 ** but that should not be a big deal. */
1178 /* WAS: ino_t ino; */
1179 u64 ino; /* Inode number */
1180 #endif
1184 ** An instance of the following structure is allocated for each open
1185 ** inode.
1187 ** A single inode can have multiple file descriptors, so each unixFile
1188 ** structure contains a pointer to an instance of this object and this
1189 ** object keeps a count of the number of unixFile pointing to it.
1191 ** Mutex rules:
1193 ** (1) Only the pLockMutex mutex must be held in order to read or write
1194 ** any of the locking fields:
1195 ** nShared, nLock, eFileLock, bProcessLock, pUnused
1197 ** (2) When nRef>0, then the following fields are unchanging and can
1198 ** be read (but not written) without holding any mutex:
1199 ** fileId, pLockMutex
1201 ** (3) With the exceptions above, all the fields may only be read
1202 ** or written while holding the global unixBigLock mutex.
1204 ** Deadlock prevention: The global unixBigLock mutex may not
1205 ** be acquired while holding the pLockMutex mutex. If both unixBigLock
1206 ** and pLockMutex are needed, then unixBigLock must be acquired first.
1208 struct unixInodeInfo {
1209 struct unixFileId fileId; /* The lookup key */
1210 sqlite3_mutex *pLockMutex; /* Hold this mutex for... */
1211 int nShared; /* Number of SHARED locks held */
1212 int nLock; /* Number of outstanding file locks */
1213 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1214 unsigned char bProcessLock; /* An exclusive process lock is held */
1215 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1216 int nRef; /* Number of pointers to this structure */
1217 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1218 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1219 unixInodeInfo *pPrev; /* .... doubly linked */
1220 #if SQLITE_ENABLE_LOCKING_STYLE
1221 unsigned long long sharedByte; /* for AFP simulated shared lock */
1222 #endif
1223 #if OS_VXWORKS
1224 sem_t *pSem; /* Named POSIX semaphore */
1225 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
1226 #endif
1230 ** A lists of all unixInodeInfo objects.
1232 ** Must hold unixBigLock in order to read or write this variable.
1234 static unixInodeInfo *inodeList = 0; /* All unixInodeInfo objects */
1236 #ifdef SQLITE_DEBUG
1238 ** True if the inode mutex (on the unixFile.pFileMutex field) is held, or not.
1239 ** This routine is used only within assert() to help verify correct mutex
1240 ** usage.
1242 int unixFileMutexHeld(unixFile *pFile){
1243 assert( pFile->pInode );
1244 return sqlite3_mutex_held(pFile->pInode->pLockMutex);
1246 int unixFileMutexNotheld(unixFile *pFile){
1247 assert( pFile->pInode );
1248 return sqlite3_mutex_notheld(pFile->pInode->pLockMutex);
1250 #endif
1254 ** This function - unixLogErrorAtLine(), is only ever called via the macro
1255 ** unixLogError().
1257 ** It is invoked after an error occurs in an OS function and errno has been
1258 ** set. It logs a message using sqlite3_log() containing the current value of
1259 ** errno and, if possible, the human-readable equivalent from strerror() or
1260 ** strerror_r().
1262 ** The first argument passed to the macro should be the error code that
1263 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1264 ** The two subsequent arguments should be the name of the OS function that
1265 ** failed (e.g. "unlink", "open") and the associated file-system path,
1266 ** if any.
1268 #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1269 static int unixLogErrorAtLine(
1270 int errcode, /* SQLite error code */
1271 const char *zFunc, /* Name of OS function that failed */
1272 const char *zPath, /* File path associated with error */
1273 int iLine /* Source line number where error occurred */
1275 char *zErr; /* Message from strerror() or equivalent */
1276 int iErrno = errno; /* Saved syscall error number */
1278 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1279 ** the strerror() function to obtain the human-readable error message
1280 ** equivalent to errno. Otherwise, use strerror_r().
1282 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1283 char aErr[80];
1284 memset(aErr, 0, sizeof(aErr));
1285 zErr = aErr;
1287 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
1288 ** assume that the system provides the GNU version of strerror_r() that
1289 ** returns a pointer to a buffer containing the error message. That pointer
1290 ** may point to aErr[], or it may point to some static storage somewhere.
1291 ** Otherwise, assume that the system provides the POSIX version of
1292 ** strerror_r(), which always writes an error message into aErr[].
1294 ** If the code incorrectly assumes that it is the POSIX version that is
1295 ** available, the error message will often be an empty string. Not a
1296 ** huge problem. Incorrectly concluding that the GNU version is available
1297 ** could lead to a segfault though.
1299 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1300 zErr =
1301 # endif
1302 strerror_r(iErrno, aErr, sizeof(aErr)-1);
1304 #elif SQLITE_THREADSAFE
1305 /* This is a threadsafe build, but strerror_r() is not available. */
1306 zErr = "";
1307 #else
1308 /* Non-threadsafe build, use strerror(). */
1309 zErr = strerror(iErrno);
1310 #endif
1312 if( zPath==0 ) zPath = "";
1313 sqlite3_log(errcode,
1314 "os_unix.c:%d: (%d) %s(%s) - %s",
1315 iLine, iErrno, zFunc, zPath, zErr
1318 return errcode;
1322 ** Close a file descriptor.
1324 ** We assume that close() almost always works, since it is only in a
1325 ** very sick application or on a very sick platform that it might fail.
1326 ** If it does fail, simply leak the file descriptor, but do log the
1327 ** error.
1329 ** Note that it is not safe to retry close() after EINTR since the
1330 ** file descriptor might have already been reused by another thread.
1331 ** So we don't even try to recover from an EINTR. Just log the error
1332 ** and move on.
1334 static void robust_close(unixFile *pFile, int h, int lineno){
1335 if( osClose(h) ){
1336 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1337 pFile ? pFile->zPath : 0, lineno);
1342 ** Set the pFile->lastErrno. Do this in a subroutine as that provides
1343 ** a convenient place to set a breakpoint.
1345 static void storeLastErrno(unixFile *pFile, int error){
1346 pFile->lastErrno = error;
1350 ** Close all file descriptors accumulated in the unixInodeInfo->pUnused list.
1352 static void closePendingFds(unixFile *pFile){
1353 unixInodeInfo *pInode = pFile->pInode;
1354 UnixUnusedFd *p;
1355 UnixUnusedFd *pNext;
1356 assert( unixFileMutexHeld(pFile) );
1357 for(p=pInode->pUnused; p; p=pNext){
1358 pNext = p->pNext;
1359 robust_close(pFile, p->fd, __LINE__);
1360 sqlite3_free(p);
1362 pInode->pUnused = 0;
1366 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
1368 ** The global mutex must be held when this routine is called, but the mutex
1369 ** on the inode being deleted must NOT be held.
1371 static void releaseInodeInfo(unixFile *pFile){
1372 unixInodeInfo *pInode = pFile->pInode;
1373 assert( unixMutexHeld() );
1374 assert( unixFileMutexNotheld(pFile) );
1375 if( ALWAYS(pInode) ){
1376 pInode->nRef--;
1377 if( pInode->nRef==0 ){
1378 assert( pInode->pShmNode==0 );
1379 sqlite3_mutex_enter(pInode->pLockMutex);
1380 closePendingFds(pFile);
1381 sqlite3_mutex_leave(pInode->pLockMutex);
1382 if( pInode->pPrev ){
1383 assert( pInode->pPrev->pNext==pInode );
1384 pInode->pPrev->pNext = pInode->pNext;
1385 }else{
1386 assert( inodeList==pInode );
1387 inodeList = pInode->pNext;
1389 if( pInode->pNext ){
1390 assert( pInode->pNext->pPrev==pInode );
1391 pInode->pNext->pPrev = pInode->pPrev;
1393 sqlite3_mutex_free(pInode->pLockMutex);
1394 sqlite3_free(pInode);
1400 ** Given a file descriptor, locate the unixInodeInfo object that
1401 ** describes that file descriptor. Create a new one if necessary. The
1402 ** return value might be uninitialized if an error occurs.
1404 ** The global mutex must held when calling this routine.
1406 ** Return an appropriate error code.
1408 static int findInodeInfo(
1409 unixFile *pFile, /* Unix file with file desc used in the key */
1410 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
1412 int rc; /* System call return code */
1413 int fd; /* The file descriptor for pFile */
1414 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1415 struct stat statbuf; /* Low-level file information */
1416 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
1418 assert( unixMutexHeld() );
1420 /* Get low-level information about the file that we can used to
1421 ** create a unique name for the file.
1423 fd = pFile->h;
1424 rc = osFstat(fd, &statbuf);
1425 if( rc!=0 ){
1426 storeLastErrno(pFile, errno);
1427 #if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
1428 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1429 #endif
1430 return SQLITE_IOERR;
1433 #ifdef __APPLE__
1434 /* On OS X on an msdos filesystem, the inode number is reported
1435 ** incorrectly for zero-size files. See ticket #3260. To work
1436 ** around this problem (we consider it a bug in OS X, not SQLite)
1437 ** we always increase the file size to 1 by writing a single byte
1438 ** prior to accessing the inode number. The one byte written is
1439 ** an ASCII 'S' character which also happens to be the first byte
1440 ** in the header of every SQLite database. In this way, if there
1441 ** is a race condition such that another thread has already populated
1442 ** the first page of the database, no damage is done.
1444 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
1445 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
1446 if( rc!=1 ){
1447 storeLastErrno(pFile, errno);
1448 return SQLITE_IOERR;
1450 rc = osFstat(fd, &statbuf);
1451 if( rc!=0 ){
1452 storeLastErrno(pFile, errno);
1453 return SQLITE_IOERR;
1456 #endif
1458 memset(&fileId, 0, sizeof(fileId));
1459 fileId.dev = statbuf.st_dev;
1460 #if OS_VXWORKS
1461 fileId.pId = pFile->pId;
1462 #else
1463 fileId.ino = (u64)statbuf.st_ino;
1464 #endif
1465 assert( unixMutexHeld() );
1466 pInode = inodeList;
1467 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1468 pInode = pInode->pNext;
1470 if( pInode==0 ){
1471 pInode = sqlite3_malloc64( sizeof(*pInode) );
1472 if( pInode==0 ){
1473 return SQLITE_NOMEM_BKPT;
1475 memset(pInode, 0, sizeof(*pInode));
1476 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1477 if( sqlite3GlobalConfig.bCoreMutex ){
1478 pInode->pLockMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
1479 if( pInode->pLockMutex==0 ){
1480 sqlite3_free(pInode);
1481 return SQLITE_NOMEM_BKPT;
1484 pInode->nRef = 1;
1485 assert( unixMutexHeld() );
1486 pInode->pNext = inodeList;
1487 pInode->pPrev = 0;
1488 if( inodeList ) inodeList->pPrev = pInode;
1489 inodeList = pInode;
1490 }else{
1491 pInode->nRef++;
1493 *ppInode = pInode;
1494 return SQLITE_OK;
1498 ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1500 static int fileHasMoved(unixFile *pFile){
1501 #if OS_VXWORKS
1502 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1503 #else
1504 struct stat buf;
1505 return pFile->pInode!=0 &&
1506 (osStat(pFile->zPath, &buf)!=0
1507 || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
1508 #endif
1513 ** Check a unixFile that is a database. Verify the following:
1515 ** (1) There is exactly one hard link on the file
1516 ** (2) The file is not a symbolic link
1517 ** (3) The file has not been renamed or unlinked
1519 ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1521 static void verifyDbFile(unixFile *pFile){
1522 struct stat buf;
1523 int rc;
1525 /* These verifications occurs for the main database only */
1526 if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
1528 rc = osFstat(pFile->h, &buf);
1529 if( rc!=0 ){
1530 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
1531 return;
1533 if( buf.st_nlink==0 ){
1534 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
1535 return;
1537 if( buf.st_nlink>1 ){
1538 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
1539 return;
1541 if( fileHasMoved(pFile) ){
1542 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
1543 return;
1549 ** This routine checks if there is a RESERVED lock held on the specified
1550 ** file by this or any other process. If such a lock is held, set *pResOut
1551 ** to a non-zero value otherwise *pResOut is set to zero. The return value
1552 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1554 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
1555 int rc = SQLITE_OK;
1556 int reserved = 0;
1557 unixFile *pFile = (unixFile*)id;
1559 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1561 assert( pFile );
1562 assert( pFile->eFileLock<=SHARED_LOCK );
1563 sqlite3_mutex_enter(pFile->pInode->pLockMutex);
1565 /* Check if a thread in this process holds such a lock */
1566 if( pFile->pInode->eFileLock>SHARED_LOCK ){
1567 reserved = 1;
1570 /* Otherwise see if some other process holds it.
1572 #ifndef __DJGPP__
1573 if( !reserved && !pFile->pInode->bProcessLock ){
1574 struct flock lock;
1575 lock.l_whence = SEEK_SET;
1576 lock.l_start = RESERVED_BYTE;
1577 lock.l_len = 1;
1578 lock.l_type = F_WRLCK;
1579 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1580 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1581 storeLastErrno(pFile, errno);
1582 } else if( lock.l_type!=F_UNLCK ){
1583 reserved = 1;
1586 #endif
1588 sqlite3_mutex_leave(pFile->pInode->pLockMutex);
1589 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
1591 *pResOut = reserved;
1592 return rc;
1595 /* Forward declaration*/
1596 static int unixSleep(sqlite3_vfs*,int);
1599 ** Set a posix-advisory-lock.
1601 ** There are two versions of this routine. If compiled with
1602 ** SQLITE_ENABLE_SETLK_TIMEOUT then the routine has an extra parameter
1603 ** which is a pointer to a unixFile. If the unixFile->iBusyTimeout
1604 ** value is set, then it is the number of milliseconds to wait before
1605 ** failing the lock. The iBusyTimeout value is always reset back to
1606 ** zero on each call.
1608 ** If SQLITE_ENABLE_SETLK_TIMEOUT is not defined, then do a non-blocking
1609 ** attempt to set the lock.
1611 #ifndef SQLITE_ENABLE_SETLK_TIMEOUT
1612 # define osSetPosixAdvisoryLock(h,x,t) osFcntl(h,F_SETLK,x)
1613 #else
1614 static int osSetPosixAdvisoryLock(
1615 int h, /* The file descriptor on which to take the lock */
1616 struct flock *pLock, /* The description of the lock */
1617 unixFile *pFile /* Structure holding timeout value */
1619 int tm = pFile->iBusyTimeout;
1620 int rc = osFcntl(h,F_SETLK,pLock);
1621 while( rc<0 && tm>0 ){
1622 /* On systems that support some kind of blocking file lock with a timeout,
1623 ** make appropriate changes here to invoke that blocking file lock. On
1624 ** generic posix, however, there is no such API. So we simply try the
1625 ** lock once every millisecond until either the timeout expires, or until
1626 ** the lock is obtained. */
1627 unixSleep(0,1000);
1628 rc = osFcntl(h,F_SETLK,pLock);
1629 tm--;
1631 return rc;
1633 #endif /* SQLITE_ENABLE_SETLK_TIMEOUT */
1637 ** Attempt to set a system-lock on the file pFile. The lock is
1638 ** described by pLock.
1640 ** If the pFile was opened read/write from unix-excl, then the only lock
1641 ** ever obtained is an exclusive lock, and it is obtained exactly once
1642 ** the first time any lock is attempted. All subsequent system locking
1643 ** operations become no-ops. Locking operations still happen internally,
1644 ** in order to coordinate access between separate database connections
1645 ** within this process, but all of that is handled in memory and the
1646 ** operating system does not participate.
1648 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1649 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1650 ** and is read-only.
1652 ** Zero is returned if the call completes successfully, or -1 if a call
1653 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
1655 static int unixFileLock(unixFile *pFile, struct flock *pLock){
1656 int rc;
1657 unixInodeInfo *pInode = pFile->pInode;
1658 assert( pInode!=0 );
1659 assert( sqlite3_mutex_held(pInode->pLockMutex) );
1660 if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
1661 if( pInode->bProcessLock==0 ){
1662 struct flock lock;
1663 assert( pInode->nLock==0 );
1664 lock.l_whence = SEEK_SET;
1665 lock.l_start = SHARED_FIRST;
1666 lock.l_len = SHARED_SIZE;
1667 lock.l_type = F_WRLCK;
1668 rc = osSetPosixAdvisoryLock(pFile->h, &lock, pFile);
1669 if( rc<0 ) return rc;
1670 pInode->bProcessLock = 1;
1671 pInode->nLock++;
1672 }else{
1673 rc = 0;
1675 }else{
1676 rc = osSetPosixAdvisoryLock(pFile->h, pLock, pFile);
1678 return rc;
1682 ** Lock the file with the lock specified by parameter eFileLock - one
1683 ** of the following:
1685 ** (1) SHARED_LOCK
1686 ** (2) RESERVED_LOCK
1687 ** (3) PENDING_LOCK
1688 ** (4) EXCLUSIVE_LOCK
1690 ** Sometimes when requesting one lock state, additional lock states
1691 ** are inserted in between. The locking might fail on one of the later
1692 ** transitions leaving the lock state different from what it started but
1693 ** still short of its goal. The following chart shows the allowed
1694 ** transitions and the inserted intermediate states:
1696 ** UNLOCKED -> SHARED
1697 ** SHARED -> RESERVED
1698 ** SHARED -> EXCLUSIVE
1699 ** RESERVED -> (PENDING) -> EXCLUSIVE
1700 ** PENDING -> EXCLUSIVE
1702 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
1703 ** routine to lower a locking level.
1705 static int unixLock(sqlite3_file *id, int eFileLock){
1706 /* The following describes the implementation of the various locks and
1707 ** lock transitions in terms of the POSIX advisory shared and exclusive
1708 ** lock primitives (called read-locks and write-locks below, to avoid
1709 ** confusion with SQLite lock names). The algorithms are complicated
1710 ** slightly in order to be compatible with Windows95 systems simultaneously
1711 ** accessing the same database file, in case that is ever required.
1713 ** Symbols defined in os.h identify the 'pending byte' and the 'reserved
1714 ** byte', each single bytes at well known offsets, and the 'shared byte
1715 ** range', a range of 510 bytes at a well known offset.
1717 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1718 ** byte'. If this is successful, 'shared byte range' is read-locked
1719 ** and the lock on the 'pending byte' released. (Legacy note: When
1720 ** SQLite was first developed, Windows95 systems were still very common,
1721 ** and Windows95 lacks a shared-lock capability. So on Windows95, a
1722 ** single randomly selected by from the 'shared byte range' is locked.
1723 ** Windows95 is now pretty much extinct, but this work-around for the
1724 ** lack of shared-locks on Windows95 lives on, for backwards
1725 ** compatibility.)
1727 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1728 ** A RESERVED lock is implemented by grabbing a write-lock on the
1729 ** 'reserved byte'.
1731 ** An EXCLUSIVE lock may only be requested after either a SHARED or
1732 ** RESERVED lock is held. An EXCLUSIVE lock is implemented by obtaining
1733 ** a write-lock on the entire 'shared byte range'. Since all other locks
1734 ** require a read-lock on one of the bytes within this range, this ensures
1735 ** that no other locks are held on the database.
1737 ** If a process that holds a RESERVED lock requests an EXCLUSIVE, then
1738 ** a PENDING lock is obtained first. A PENDING lock is implemented by
1739 ** obtaining a write-lock on the 'pending byte'. This ensures that no new
1740 ** SHARED locks can be obtained, but existing SHARED locks are allowed to
1741 ** persist. If the call to this function fails to obtain the EXCLUSIVE
1742 ** lock in this case, it holds the PENDING lock instead. The client may
1743 ** then re-attempt the EXCLUSIVE lock later on, after existing SHARED
1744 ** locks have cleared.
1746 int rc = SQLITE_OK;
1747 unixFile *pFile = (unixFile*)id;
1748 unixInodeInfo *pInode;
1749 struct flock lock;
1750 int tErrno = 0;
1752 assert( pFile );
1753 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1754 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
1755 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
1756 osGetpid(0)));
1758 /* If there is already a lock of this type or more restrictive on the
1759 ** unixFile, do nothing. Don't use the end_lock: exit path, as
1760 ** unixEnterMutex() hasn't been called yet.
1762 if( pFile->eFileLock>=eFileLock ){
1763 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1764 azFileLock(eFileLock)));
1765 return SQLITE_OK;
1768 /* Make sure the locking sequence is correct.
1769 ** (1) We never move from unlocked to anything higher than shared lock.
1770 ** (2) SQLite never explicitly requests a pending lock.
1771 ** (3) A shared lock is always held when a reserve lock is requested.
1773 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1774 assert( eFileLock!=PENDING_LOCK );
1775 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
1777 /* This mutex is needed because pFile->pInode is shared across threads
1779 pInode = pFile->pInode;
1780 sqlite3_mutex_enter(pInode->pLockMutex);
1782 /* If some thread using this PID has a lock via a different unixFile*
1783 ** handle that precludes the requested lock, return BUSY.
1785 if( (pFile->eFileLock!=pInode->eFileLock &&
1786 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
1788 rc = SQLITE_BUSY;
1789 goto end_lock;
1792 /* If a SHARED lock is requested, and some thread using this PID already
1793 ** has a SHARED or RESERVED lock, then increment reference counts and
1794 ** return SQLITE_OK.
1796 if( eFileLock==SHARED_LOCK &&
1797 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
1798 assert( eFileLock==SHARED_LOCK );
1799 assert( pFile->eFileLock==0 );
1800 assert( pInode->nShared>0 );
1801 pFile->eFileLock = SHARED_LOCK;
1802 pInode->nShared++;
1803 pInode->nLock++;
1804 goto end_lock;
1808 /* A PENDING lock is needed before acquiring a SHARED lock and before
1809 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1810 ** be released.
1812 lock.l_len = 1L;
1813 lock.l_whence = SEEK_SET;
1814 if( eFileLock==SHARED_LOCK
1815 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock==RESERVED_LOCK)
1817 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
1818 lock.l_start = PENDING_BYTE;
1819 if( unixFileLock(pFile, &lock) ){
1820 tErrno = errno;
1821 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1822 if( rc!=SQLITE_BUSY ){
1823 storeLastErrno(pFile, tErrno);
1825 goto end_lock;
1826 }else if( eFileLock==EXCLUSIVE_LOCK ){
1827 pFile->eFileLock = PENDING_LOCK;
1828 pInode->eFileLock = PENDING_LOCK;
1833 /* If control gets to this point, then actually go ahead and make
1834 ** operating system calls for the specified lock.
1836 if( eFileLock==SHARED_LOCK ){
1837 assert( pInode->nShared==0 );
1838 assert( pInode->eFileLock==0 );
1839 assert( rc==SQLITE_OK );
1841 /* Now get the read-lock */
1842 lock.l_start = SHARED_FIRST;
1843 lock.l_len = SHARED_SIZE;
1844 if( unixFileLock(pFile, &lock) ){
1845 tErrno = errno;
1846 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1849 /* Drop the temporary PENDING lock */
1850 lock.l_start = PENDING_BYTE;
1851 lock.l_len = 1L;
1852 lock.l_type = F_UNLCK;
1853 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1854 /* This could happen with a network mount */
1855 tErrno = errno;
1856 rc = SQLITE_IOERR_UNLOCK;
1859 if( rc ){
1860 if( rc!=SQLITE_BUSY ){
1861 storeLastErrno(pFile, tErrno);
1863 goto end_lock;
1864 }else{
1865 pFile->eFileLock = SHARED_LOCK;
1866 pInode->nLock++;
1867 pInode->nShared = 1;
1869 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
1870 /* We are trying for an exclusive lock but another thread in this
1871 ** same process is still holding a shared lock. */
1872 rc = SQLITE_BUSY;
1873 }else{
1874 /* The request was for a RESERVED or EXCLUSIVE lock. It is
1875 ** assumed that there is a SHARED or greater lock on the file
1876 ** already.
1878 assert( 0!=pFile->eFileLock );
1879 lock.l_type = F_WRLCK;
1881 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1882 if( eFileLock==RESERVED_LOCK ){
1883 lock.l_start = RESERVED_BYTE;
1884 lock.l_len = 1L;
1885 }else{
1886 lock.l_start = SHARED_FIRST;
1887 lock.l_len = SHARED_SIZE;
1890 if( unixFileLock(pFile, &lock) ){
1891 tErrno = errno;
1892 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1893 if( rc!=SQLITE_BUSY ){
1894 storeLastErrno(pFile, tErrno);
1900 #ifdef SQLITE_DEBUG
1901 /* Set up the transaction-counter change checking flags when
1902 ** transitioning from a SHARED to a RESERVED lock. The change
1903 ** from SHARED to RESERVED marks the beginning of a normal
1904 ** write operation (not a hot journal rollback).
1906 if( rc==SQLITE_OK
1907 && pFile->eFileLock<=SHARED_LOCK
1908 && eFileLock==RESERVED_LOCK
1910 pFile->transCntrChng = 0;
1911 pFile->dbUpdate = 0;
1912 pFile->inNormalWrite = 1;
1914 #endif
1916 if( rc==SQLITE_OK ){
1917 pFile->eFileLock = eFileLock;
1918 pInode->eFileLock = eFileLock;
1921 end_lock:
1922 sqlite3_mutex_leave(pInode->pLockMutex);
1923 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1924 rc==SQLITE_OK ? "ok" : "failed"));
1925 return rc;
1929 ** Add the file descriptor used by file handle pFile to the corresponding
1930 ** pUnused list.
1932 static void setPendingFd(unixFile *pFile){
1933 unixInodeInfo *pInode = pFile->pInode;
1934 UnixUnusedFd *p = pFile->pPreallocatedUnused;
1935 assert( unixFileMutexHeld(pFile) );
1936 p->pNext = pInode->pUnused;
1937 pInode->pUnused = p;
1938 pFile->h = -1;
1939 pFile->pPreallocatedUnused = 0;
1943 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
1944 ** must be either NO_LOCK or SHARED_LOCK.
1946 ** If the locking level of the file descriptor is already at or below
1947 ** the requested locking level, this routine is a no-op.
1949 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1950 ** the byte range is divided into 2 parts and the first part is unlocked then
1951 ** set to a read lock, then the other part is simply unlocked. This works
1952 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1953 ** remove the write lock on a region when a read lock is set.
1955 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
1956 unixFile *pFile = (unixFile*)id;
1957 unixInodeInfo *pInode;
1958 struct flock lock;
1959 int rc = SQLITE_OK;
1961 assert( pFile );
1962 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
1963 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
1964 osGetpid(0)));
1966 assert( eFileLock<=SHARED_LOCK );
1967 if( pFile->eFileLock<=eFileLock ){
1968 return SQLITE_OK;
1970 pInode = pFile->pInode;
1971 sqlite3_mutex_enter(pInode->pLockMutex);
1972 assert( pInode->nShared!=0 );
1973 if( pFile->eFileLock>SHARED_LOCK ){
1974 assert( pInode->eFileLock==pFile->eFileLock );
1976 #ifdef SQLITE_DEBUG
1977 /* When reducing a lock such that other processes can start
1978 ** reading the database file again, make sure that the
1979 ** transaction counter was updated if any part of the database
1980 ** file changed. If the transaction counter is not updated,
1981 ** other connections to the same file might not realize that
1982 ** the file has changed and hence might not know to flush their
1983 ** cache. The use of a stale cache can lead to database corruption.
1985 pFile->inNormalWrite = 0;
1986 #endif
1988 /* downgrading to a shared lock on NFS involves clearing the write lock
1989 ** before establishing the readlock - to avoid a race condition we downgrade
1990 ** the lock in 2 blocks, so that part of the range will be covered by a
1991 ** write lock until the rest is covered by a read lock:
1992 ** 1: [WWWWW]
1993 ** 2: [....W]
1994 ** 3: [RRRRW]
1995 ** 4: [RRRR.]
1997 if( eFileLock==SHARED_LOCK ){
1998 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
1999 (void)handleNFSUnlock;
2000 assert( handleNFSUnlock==0 );
2001 #endif
2002 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2003 if( handleNFSUnlock ){
2004 int tErrno; /* Error code from system call errors */
2005 off_t divSize = SHARED_SIZE - 1;
2007 lock.l_type = F_UNLCK;
2008 lock.l_whence = SEEK_SET;
2009 lock.l_start = SHARED_FIRST;
2010 lock.l_len = divSize;
2011 if( unixFileLock(pFile, &lock)==(-1) ){
2012 tErrno = errno;
2013 rc = SQLITE_IOERR_UNLOCK;
2014 storeLastErrno(pFile, tErrno);
2015 goto end_unlock;
2017 lock.l_type = F_RDLCK;
2018 lock.l_whence = SEEK_SET;
2019 lock.l_start = SHARED_FIRST;
2020 lock.l_len = divSize;
2021 if( unixFileLock(pFile, &lock)==(-1) ){
2022 tErrno = errno;
2023 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
2024 if( IS_LOCK_ERROR(rc) ){
2025 storeLastErrno(pFile, tErrno);
2027 goto end_unlock;
2029 lock.l_type = F_UNLCK;
2030 lock.l_whence = SEEK_SET;
2031 lock.l_start = SHARED_FIRST+divSize;
2032 lock.l_len = SHARED_SIZE-divSize;
2033 if( unixFileLock(pFile, &lock)==(-1) ){
2034 tErrno = errno;
2035 rc = SQLITE_IOERR_UNLOCK;
2036 storeLastErrno(pFile, tErrno);
2037 goto end_unlock;
2039 }else
2040 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2042 lock.l_type = F_RDLCK;
2043 lock.l_whence = SEEK_SET;
2044 lock.l_start = SHARED_FIRST;
2045 lock.l_len = SHARED_SIZE;
2046 if( unixFileLock(pFile, &lock) ){
2047 /* In theory, the call to unixFileLock() cannot fail because another
2048 ** process is holding an incompatible lock. If it does, this
2049 ** indicates that the other process is not following the locking
2050 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
2051 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
2052 ** an assert to fail). */
2053 rc = SQLITE_IOERR_RDLOCK;
2054 storeLastErrno(pFile, errno);
2055 goto end_unlock;
2059 lock.l_type = F_UNLCK;
2060 lock.l_whence = SEEK_SET;
2061 lock.l_start = PENDING_BYTE;
2062 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
2063 if( unixFileLock(pFile, &lock)==0 ){
2064 pInode->eFileLock = SHARED_LOCK;
2065 }else{
2066 rc = SQLITE_IOERR_UNLOCK;
2067 storeLastErrno(pFile, errno);
2068 goto end_unlock;
2071 if( eFileLock==NO_LOCK ){
2072 /* Decrement the shared lock counter. Release the lock using an
2073 ** OS call only when all threads in this same process have released
2074 ** the lock.
2076 pInode->nShared--;
2077 if( pInode->nShared==0 ){
2078 lock.l_type = F_UNLCK;
2079 lock.l_whence = SEEK_SET;
2080 lock.l_start = lock.l_len = 0L;
2081 if( unixFileLock(pFile, &lock)==0 ){
2082 pInode->eFileLock = NO_LOCK;
2083 }else{
2084 rc = SQLITE_IOERR_UNLOCK;
2085 storeLastErrno(pFile, errno);
2086 pInode->eFileLock = NO_LOCK;
2087 pFile->eFileLock = NO_LOCK;
2091 /* Decrement the count of locks against this same file. When the
2092 ** count reaches zero, close any other file descriptors whose close
2093 ** was deferred because of outstanding locks.
2095 pInode->nLock--;
2096 assert( pInode->nLock>=0 );
2097 if( pInode->nLock==0 ) closePendingFds(pFile);
2100 end_unlock:
2101 sqlite3_mutex_leave(pInode->pLockMutex);
2102 if( rc==SQLITE_OK ){
2103 pFile->eFileLock = eFileLock;
2105 return rc;
2109 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
2110 ** must be either NO_LOCK or SHARED_LOCK.
2112 ** If the locking level of the file descriptor is already at or below
2113 ** the requested locking level, this routine is a no-op.
2115 static int unixUnlock(sqlite3_file *id, int eFileLock){
2116 #if SQLITE_MAX_MMAP_SIZE>0
2117 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
2118 #endif
2119 return posixUnlock(id, eFileLock, 0);
2122 #if SQLITE_MAX_MMAP_SIZE>0
2123 static int unixMapfile(unixFile *pFd, i64 nByte);
2124 static void unixUnmapfile(unixFile *pFd);
2125 #endif
2128 ** This function performs the parts of the "close file" operation
2129 ** common to all locking schemes. It closes the directory and file
2130 ** handles, if they are valid, and sets all fields of the unixFile
2131 ** structure to 0.
2133 ** It is *not* necessary to hold the mutex when this routine is called,
2134 ** even on VxWorks. A mutex will be acquired on VxWorks by the
2135 ** vxworksReleaseFileId() routine.
2137 static int closeUnixFile(sqlite3_file *id){
2138 unixFile *pFile = (unixFile*)id;
2139 #if SQLITE_MAX_MMAP_SIZE>0
2140 unixUnmapfile(pFile);
2141 #endif
2142 if( pFile->h>=0 ){
2143 robust_close(pFile, pFile->h, __LINE__);
2144 pFile->h = -1;
2146 #if OS_VXWORKS
2147 if( pFile->pId ){
2148 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
2149 osUnlink(pFile->pId->zCanonicalName);
2151 vxworksReleaseFileId(pFile->pId);
2152 pFile->pId = 0;
2154 #endif
2155 #ifdef SQLITE_UNLINK_AFTER_CLOSE
2156 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
2157 osUnlink(pFile->zPath);
2158 sqlite3_free(*(char**)&pFile->zPath);
2159 pFile->zPath = 0;
2161 #endif
2162 OSTRACE(("CLOSE %-3d\n", pFile->h));
2163 OpenCounter(-1);
2164 sqlite3_free(pFile->pPreallocatedUnused);
2165 memset(pFile, 0, sizeof(unixFile));
2166 return SQLITE_OK;
2170 ** Close a file.
2172 static int unixClose(sqlite3_file *id){
2173 int rc = SQLITE_OK;
2174 unixFile *pFile = (unixFile *)id;
2175 unixInodeInfo *pInode = pFile->pInode;
2177 assert( pInode!=0 );
2178 verifyDbFile(pFile);
2179 unixUnlock(id, NO_LOCK);
2180 assert( unixFileMutexNotheld(pFile) );
2181 unixEnterMutex();
2183 /* unixFile.pInode is always valid here. Otherwise, a different close
2184 ** routine (e.g. nolockClose()) would be called instead.
2186 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
2187 sqlite3_mutex_enter(pInode->pLockMutex);
2188 if( pInode->nLock ){
2189 /* If there are outstanding locks, do not actually close the file just
2190 ** yet because that would clear those locks. Instead, add the file
2191 ** descriptor to pInode->pUnused list. It will be automatically closed
2192 ** when the last lock is cleared.
2194 setPendingFd(pFile);
2196 sqlite3_mutex_leave(pInode->pLockMutex);
2197 releaseInodeInfo(pFile);
2198 assert( pFile->pShm==0 );
2199 rc = closeUnixFile(id);
2200 unixLeaveMutex();
2201 return rc;
2204 /************** End of the posix advisory lock implementation *****************
2205 ******************************************************************************/
2207 /******************************************************************************
2208 ****************************** No-op Locking **********************************
2210 ** Of the various locking implementations available, this is by far the
2211 ** simplest: locking is ignored. No attempt is made to lock the database
2212 ** file for reading or writing.
2214 ** This locking mode is appropriate for use on read-only databases
2215 ** (ex: databases that are burned into CD-ROM, for example.) It can
2216 ** also be used if the application employs some external mechanism to
2217 ** prevent simultaneous access of the same database by two or more
2218 ** database connections. But there is a serious risk of database
2219 ** corruption if this locking mode is used in situations where multiple
2220 ** database connections are accessing the same database file at the same
2221 ** time and one or more of those connections are writing.
2224 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
2225 UNUSED_PARAMETER(NotUsed);
2226 *pResOut = 0;
2227 return SQLITE_OK;
2229 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
2230 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2231 return SQLITE_OK;
2233 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
2234 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2235 return SQLITE_OK;
2239 ** Close the file.
2241 static int nolockClose(sqlite3_file *id) {
2242 return closeUnixFile(id);
2245 /******************* End of the no-op lock implementation *********************
2246 ******************************************************************************/
2248 /******************************************************************************
2249 ************************* Begin dot-file Locking ******************************
2251 ** The dotfile locking implementation uses the existence of separate lock
2252 ** files (really a directory) to control access to the database. This works
2253 ** on just about every filesystem imaginable. But there are serious downsides:
2255 ** (1) There is zero concurrency. A single reader blocks all other
2256 ** connections from reading or writing the database.
2258 ** (2) An application crash or power loss can leave stale lock files
2259 ** sitting around that need to be cleared manually.
2261 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
2262 ** other locking strategy is available.
2264 ** Dotfile locking works by creating a subdirectory in the same directory as
2265 ** the database and with the same name but with a ".lock" extension added.
2266 ** The existence of a lock directory implies an EXCLUSIVE lock. All other
2267 ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
2271 ** The file suffix added to the data base filename in order to create the
2272 ** lock directory.
2274 #define DOTLOCK_SUFFIX ".lock"
2277 ** This routine checks if there is a RESERVED lock held on the specified
2278 ** file by this or any other process. If such a lock is held, set *pResOut
2279 ** to a non-zero value otherwise *pResOut is set to zero. The return value
2280 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2282 ** In dotfile locking, either a lock exists or it does not. So in this
2283 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
2284 ** is held on the file and false if the file is unlocked.
2286 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2287 int rc = SQLITE_OK;
2288 int reserved = 0;
2289 unixFile *pFile = (unixFile*)id;
2291 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2293 assert( pFile );
2294 reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
2295 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
2296 *pResOut = reserved;
2297 return rc;
2301 ** Lock the file with the lock specified by parameter eFileLock - one
2302 ** of the following:
2304 ** (1) SHARED_LOCK
2305 ** (2) RESERVED_LOCK
2306 ** (3) PENDING_LOCK
2307 ** (4) EXCLUSIVE_LOCK
2309 ** Sometimes when requesting one lock state, additional lock states
2310 ** are inserted in between. The locking might fail on one of the later
2311 ** transitions leaving the lock state different from what it started but
2312 ** still short of its goal. The following chart shows the allowed
2313 ** transitions and the inserted intermediate states:
2315 ** UNLOCKED -> SHARED
2316 ** SHARED -> RESERVED
2317 ** SHARED -> (PENDING) -> EXCLUSIVE
2318 ** RESERVED -> (PENDING) -> EXCLUSIVE
2319 ** PENDING -> EXCLUSIVE
2321 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
2322 ** routine to lower a locking level.
2324 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
2325 ** But we track the other locking levels internally.
2327 static int dotlockLock(sqlite3_file *id, int eFileLock) {
2328 unixFile *pFile = (unixFile*)id;
2329 char *zLockFile = (char *)pFile->lockingContext;
2330 int rc = SQLITE_OK;
2333 /* If we have any lock, then the lock file already exists. All we have
2334 ** to do is adjust our internal record of the lock level.
2336 if( pFile->eFileLock > NO_LOCK ){
2337 pFile->eFileLock = eFileLock;
2338 /* Always update the timestamp on the old file */
2339 #ifdef HAVE_UTIME
2340 utime(zLockFile, NULL);
2341 #else
2342 utimes(zLockFile, NULL);
2343 #endif
2344 return SQLITE_OK;
2347 /* grab an exclusive lock */
2348 rc = osMkdir(zLockFile, 0777);
2349 if( rc<0 ){
2350 /* failed to open/create the lock directory */
2351 int tErrno = errno;
2352 if( EEXIST == tErrno ){
2353 rc = SQLITE_BUSY;
2354 } else {
2355 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2356 if( rc!=SQLITE_BUSY ){
2357 storeLastErrno(pFile, tErrno);
2360 return rc;
2363 /* got it, set the type and return ok */
2364 pFile->eFileLock = eFileLock;
2365 return rc;
2369 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
2370 ** must be either NO_LOCK or SHARED_LOCK.
2372 ** If the locking level of the file descriptor is already at or below
2373 ** the requested locking level, this routine is a no-op.
2375 ** When the locking level reaches NO_LOCK, delete the lock file.
2377 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
2378 unixFile *pFile = (unixFile*)id;
2379 char *zLockFile = (char *)pFile->lockingContext;
2380 int rc;
2382 assert( pFile );
2383 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
2384 pFile->eFileLock, osGetpid(0)));
2385 assert( eFileLock<=SHARED_LOCK );
2387 /* no-op if possible */
2388 if( pFile->eFileLock==eFileLock ){
2389 return SQLITE_OK;
2392 /* To downgrade to shared, simply update our internal notion of the
2393 ** lock state. No need to mess with the file on disk.
2395 if( eFileLock==SHARED_LOCK ){
2396 pFile->eFileLock = SHARED_LOCK;
2397 return SQLITE_OK;
2400 /* To fully unlock the database, delete the lock file */
2401 assert( eFileLock==NO_LOCK );
2402 rc = osRmdir(zLockFile);
2403 if( rc<0 ){
2404 int tErrno = errno;
2405 if( tErrno==ENOENT ){
2406 rc = SQLITE_OK;
2407 }else{
2408 rc = SQLITE_IOERR_UNLOCK;
2409 storeLastErrno(pFile, tErrno);
2411 return rc;
2413 pFile->eFileLock = NO_LOCK;
2414 return SQLITE_OK;
2418 ** Close a file. Make sure the lock has been released before closing.
2420 static int dotlockClose(sqlite3_file *id) {
2421 unixFile *pFile = (unixFile*)id;
2422 assert( id!=0 );
2423 dotlockUnlock(id, NO_LOCK);
2424 sqlite3_free(pFile->lockingContext);
2425 return closeUnixFile(id);
2427 /****************** End of the dot-file lock implementation *******************
2428 ******************************************************************************/
2430 /******************************************************************************
2431 ************************** Begin flock Locking ********************************
2433 ** Use the flock() system call to do file locking.
2435 ** flock() locking is like dot-file locking in that the various
2436 ** fine-grain locking levels supported by SQLite are collapsed into
2437 ** a single exclusive lock. In other words, SHARED, RESERVED, and
2438 ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2439 ** still works when you do this, but concurrency is reduced since
2440 ** only a single process can be reading the database at a time.
2442 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
2444 #if SQLITE_ENABLE_LOCKING_STYLE
2447 ** Retry flock() calls that fail with EINTR
2449 #ifdef EINTR
2450 static int robust_flock(int fd, int op){
2451 int rc;
2452 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2453 return rc;
2455 #else
2456 # define robust_flock(a,b) flock(a,b)
2457 #endif
2461 ** This routine checks if there is a RESERVED lock held on the specified
2462 ** file by this or any other process. If such a lock is held, set *pResOut
2463 ** to a non-zero value otherwise *pResOut is set to zero. The return value
2464 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2466 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2467 int rc = SQLITE_OK;
2468 int reserved = 0;
2469 unixFile *pFile = (unixFile*)id;
2471 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2473 assert( pFile );
2475 /* Check if a thread in this process holds such a lock */
2476 if( pFile->eFileLock>SHARED_LOCK ){
2477 reserved = 1;
2480 /* Otherwise see if some other process holds it. */
2481 if( !reserved ){
2482 /* attempt to get the lock */
2483 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
2484 if( !lrc ){
2485 /* got the lock, unlock it */
2486 lrc = robust_flock(pFile->h, LOCK_UN);
2487 if ( lrc ) {
2488 int tErrno = errno;
2489 /* unlock failed with an error */
2490 lrc = SQLITE_IOERR_UNLOCK;
2491 storeLastErrno(pFile, tErrno);
2492 rc = lrc;
2494 } else {
2495 int tErrno = errno;
2496 reserved = 1;
2497 /* someone else might have it reserved */
2498 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2499 if( IS_LOCK_ERROR(lrc) ){
2500 storeLastErrno(pFile, tErrno);
2501 rc = lrc;
2505 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
2507 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2508 if( (rc & 0xff) == SQLITE_IOERR ){
2509 rc = SQLITE_OK;
2510 reserved=1;
2512 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2513 *pResOut = reserved;
2514 return rc;
2518 ** Lock the file with the lock specified by parameter eFileLock - one
2519 ** of the following:
2521 ** (1) SHARED_LOCK
2522 ** (2) RESERVED_LOCK
2523 ** (3) PENDING_LOCK
2524 ** (4) EXCLUSIVE_LOCK
2526 ** Sometimes when requesting one lock state, additional lock states
2527 ** are inserted in between. The locking might fail on one of the later
2528 ** transitions leaving the lock state different from what it started but
2529 ** still short of its goal. The following chart shows the allowed
2530 ** transitions and the inserted intermediate states:
2532 ** UNLOCKED -> SHARED
2533 ** SHARED -> RESERVED
2534 ** SHARED -> (PENDING) -> EXCLUSIVE
2535 ** RESERVED -> (PENDING) -> EXCLUSIVE
2536 ** PENDING -> EXCLUSIVE
2538 ** flock() only really support EXCLUSIVE locks. We track intermediate
2539 ** lock states in the sqlite3_file structure, but all locks SHARED or
2540 ** above are really EXCLUSIVE locks and exclude all other processes from
2541 ** access the file.
2543 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
2544 ** routine to lower a locking level.
2546 static int flockLock(sqlite3_file *id, int eFileLock) {
2547 int rc = SQLITE_OK;
2548 unixFile *pFile = (unixFile*)id;
2550 assert( pFile );
2552 /* if we already have a lock, it is exclusive.
2553 ** Just adjust level and punt on outta here. */
2554 if (pFile->eFileLock > NO_LOCK) {
2555 pFile->eFileLock = eFileLock;
2556 return SQLITE_OK;
2559 /* grab an exclusive lock */
2561 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
2562 int tErrno = errno;
2563 /* didn't get, must be busy */
2564 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2565 if( IS_LOCK_ERROR(rc) ){
2566 storeLastErrno(pFile, tErrno);
2568 } else {
2569 /* got it, set the type and return ok */
2570 pFile->eFileLock = eFileLock;
2572 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2573 rc==SQLITE_OK ? "ok" : "failed"));
2574 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2575 if( (rc & 0xff) == SQLITE_IOERR ){
2576 rc = SQLITE_BUSY;
2578 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2579 return rc;
2584 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
2585 ** must be either NO_LOCK or SHARED_LOCK.
2587 ** If the locking level of the file descriptor is already at or below
2588 ** the requested locking level, this routine is a no-op.
2590 static int flockUnlock(sqlite3_file *id, int eFileLock) {
2591 unixFile *pFile = (unixFile*)id;
2593 assert( pFile );
2594 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2595 pFile->eFileLock, osGetpid(0)));
2596 assert( eFileLock<=SHARED_LOCK );
2598 /* no-op if possible */
2599 if( pFile->eFileLock==eFileLock ){
2600 return SQLITE_OK;
2603 /* shared can just be set because we always have an exclusive */
2604 if (eFileLock==SHARED_LOCK) {
2605 pFile->eFileLock = eFileLock;
2606 return SQLITE_OK;
2609 /* no, really, unlock. */
2610 if( robust_flock(pFile->h, LOCK_UN) ){
2611 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2612 return SQLITE_OK;
2613 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2614 return SQLITE_IOERR_UNLOCK;
2615 }else{
2616 pFile->eFileLock = NO_LOCK;
2617 return SQLITE_OK;
2622 ** Close a file.
2624 static int flockClose(sqlite3_file *id) {
2625 assert( id!=0 );
2626 flockUnlock(id, NO_LOCK);
2627 return closeUnixFile(id);
2630 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2632 /******************* End of the flock lock implementation *********************
2633 ******************************************************************************/
2635 /******************************************************************************
2636 ************************ Begin Named Semaphore Locking ************************
2638 ** Named semaphore locking is only supported on VxWorks.
2640 ** Semaphore locking is like dot-lock and flock in that it really only
2641 ** supports EXCLUSIVE locking. Only a single process can read or write
2642 ** the database file at a time. This reduces potential concurrency, but
2643 ** makes the lock implementation much easier.
2645 #if OS_VXWORKS
2648 ** This routine checks if there is a RESERVED lock held on the specified
2649 ** file by this or any other process. If such a lock is held, set *pResOut
2650 ** to a non-zero value otherwise *pResOut is set to zero. The return value
2651 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2653 static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
2654 int rc = SQLITE_OK;
2655 int reserved = 0;
2656 unixFile *pFile = (unixFile*)id;
2658 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2660 assert( pFile );
2662 /* Check if a thread in this process holds such a lock */
2663 if( pFile->eFileLock>SHARED_LOCK ){
2664 reserved = 1;
2667 /* Otherwise see if some other process holds it. */
2668 if( !reserved ){
2669 sem_t *pSem = pFile->pInode->pSem;
2671 if( sem_trywait(pSem)==-1 ){
2672 int tErrno = errno;
2673 if( EAGAIN != tErrno ){
2674 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2675 storeLastErrno(pFile, tErrno);
2676 } else {
2677 /* someone else has the lock when we are in NO_LOCK */
2678 reserved = (pFile->eFileLock < SHARED_LOCK);
2680 }else{
2681 /* we could have it if we want it */
2682 sem_post(pSem);
2685 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
2687 *pResOut = reserved;
2688 return rc;
2692 ** Lock the file with the lock specified by parameter eFileLock - one
2693 ** of the following:
2695 ** (1) SHARED_LOCK
2696 ** (2) RESERVED_LOCK
2697 ** (3) PENDING_LOCK
2698 ** (4) EXCLUSIVE_LOCK
2700 ** Sometimes when requesting one lock state, additional lock states
2701 ** are inserted in between. The locking might fail on one of the later
2702 ** transitions leaving the lock state different from what it started but
2703 ** still short of its goal. The following chart shows the allowed
2704 ** transitions and the inserted intermediate states:
2706 ** UNLOCKED -> SHARED
2707 ** SHARED -> RESERVED
2708 ** SHARED -> (PENDING) -> EXCLUSIVE
2709 ** RESERVED -> (PENDING) -> EXCLUSIVE
2710 ** PENDING -> EXCLUSIVE
2712 ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2713 ** lock states in the sqlite3_file structure, but all locks SHARED or
2714 ** above are really EXCLUSIVE locks and exclude all other processes from
2715 ** access the file.
2717 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
2718 ** routine to lower a locking level.
2720 static int semXLock(sqlite3_file *id, int eFileLock) {
2721 unixFile *pFile = (unixFile*)id;
2722 sem_t *pSem = pFile->pInode->pSem;
2723 int rc = SQLITE_OK;
2725 /* if we already have a lock, it is exclusive.
2726 ** Just adjust level and punt on outta here. */
2727 if (pFile->eFileLock > NO_LOCK) {
2728 pFile->eFileLock = eFileLock;
2729 rc = SQLITE_OK;
2730 goto sem_end_lock;
2733 /* lock semaphore now but bail out when already locked. */
2734 if( sem_trywait(pSem)==-1 ){
2735 rc = SQLITE_BUSY;
2736 goto sem_end_lock;
2739 /* got it, set the type and return ok */
2740 pFile->eFileLock = eFileLock;
2742 sem_end_lock:
2743 return rc;
2747 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
2748 ** must be either NO_LOCK or SHARED_LOCK.
2750 ** If the locking level of the file descriptor is already at or below
2751 ** the requested locking level, this routine is a no-op.
2753 static int semXUnlock(sqlite3_file *id, int eFileLock) {
2754 unixFile *pFile = (unixFile*)id;
2755 sem_t *pSem = pFile->pInode->pSem;
2757 assert( pFile );
2758 assert( pSem );
2759 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2760 pFile->eFileLock, osGetpid(0)));
2761 assert( eFileLock<=SHARED_LOCK );
2763 /* no-op if possible */
2764 if( pFile->eFileLock==eFileLock ){
2765 return SQLITE_OK;
2768 /* shared can just be set because we always have an exclusive */
2769 if (eFileLock==SHARED_LOCK) {
2770 pFile->eFileLock = eFileLock;
2771 return SQLITE_OK;
2774 /* no, really unlock. */
2775 if ( sem_post(pSem)==-1 ) {
2776 int rc, tErrno = errno;
2777 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2778 if( IS_LOCK_ERROR(rc) ){
2779 storeLastErrno(pFile, tErrno);
2781 return rc;
2783 pFile->eFileLock = NO_LOCK;
2784 return SQLITE_OK;
2788 ** Close a file.
2790 static int semXClose(sqlite3_file *id) {
2791 if( id ){
2792 unixFile *pFile = (unixFile*)id;
2793 semXUnlock(id, NO_LOCK);
2794 assert( pFile );
2795 assert( unixFileMutexNotheld(pFile) );
2796 unixEnterMutex();
2797 releaseInodeInfo(pFile);
2798 unixLeaveMutex();
2799 closeUnixFile(id);
2801 return SQLITE_OK;
2804 #endif /* OS_VXWORKS */
2806 ** Named semaphore locking is only available on VxWorks.
2808 *************** End of the named semaphore lock implementation ****************
2809 ******************************************************************************/
2812 /******************************************************************************
2813 *************************** Begin AFP Locking *********************************
2815 ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2816 ** on Apple Macintosh computers - both OS9 and OSX.
2818 ** Third-party implementations of AFP are available. But this code here
2819 ** only works on OSX.
2822 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2824 ** The afpLockingContext structure contains all afp lock specific state
2826 typedef struct afpLockingContext afpLockingContext;
2827 struct afpLockingContext {
2828 int reserved;
2829 const char *dbPath; /* Name of the open file */
2832 struct ByteRangeLockPB2
2834 unsigned long long offset; /* offset to first byte to lock */
2835 unsigned long long length; /* nbr of bytes to lock */
2836 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2837 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2838 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2839 int fd; /* file desc to assoc this lock with */
2842 #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
2845 ** This is a utility for setting or clearing a bit-range lock on an
2846 ** AFP filesystem.
2848 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2850 static int afpSetLock(
2851 const char *path, /* Name of the file to be locked or unlocked */
2852 unixFile *pFile, /* Open file descriptor on path */
2853 unsigned long long offset, /* First byte to be locked */
2854 unsigned long long length, /* Number of bytes to lock */
2855 int setLockFlag /* True to set lock. False to clear lock */
2857 struct ByteRangeLockPB2 pb;
2858 int err;
2860 pb.unLockFlag = setLockFlag ? 0 : 1;
2861 pb.startEndFlag = 0;
2862 pb.offset = offset;
2863 pb.length = length;
2864 pb.fd = pFile->h;
2866 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
2867 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
2868 offset, length));
2869 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2870 if ( err==-1 ) {
2871 int rc;
2872 int tErrno = errno;
2873 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2874 path, tErrno, strerror(tErrno)));
2875 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2876 rc = SQLITE_BUSY;
2877 #else
2878 rc = sqliteErrorFromPosixError(tErrno,
2879 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
2880 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
2881 if( IS_LOCK_ERROR(rc) ){
2882 storeLastErrno(pFile, tErrno);
2884 return rc;
2885 } else {
2886 return SQLITE_OK;
2891 ** This routine checks if there is a RESERVED lock held on the specified
2892 ** file by this or any other process. If such a lock is held, set *pResOut
2893 ** to a non-zero value otherwise *pResOut is set to zero. The return value
2894 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2896 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
2897 int rc = SQLITE_OK;
2898 int reserved = 0;
2899 unixFile *pFile = (unixFile*)id;
2900 afpLockingContext *context;
2902 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2904 assert( pFile );
2905 context = (afpLockingContext *) pFile->lockingContext;
2906 if( context->reserved ){
2907 *pResOut = 1;
2908 return SQLITE_OK;
2910 sqlite3_mutex_enter(pFile->pInode->pLockMutex);
2911 /* Check if a thread in this process holds such a lock */
2912 if( pFile->pInode->eFileLock>SHARED_LOCK ){
2913 reserved = 1;
2916 /* Otherwise see if some other process holds it.
2918 if( !reserved ){
2919 /* lock the RESERVED byte */
2920 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
2921 if( SQLITE_OK==lrc ){
2922 /* if we succeeded in taking the reserved lock, unlock it to restore
2923 ** the original state */
2924 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2925 } else {
2926 /* if we failed to get the lock then someone else must have it */
2927 reserved = 1;
2929 if( IS_LOCK_ERROR(lrc) ){
2930 rc=lrc;
2934 sqlite3_mutex_leave(pFile->pInode->pLockMutex);
2935 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
2937 *pResOut = reserved;
2938 return rc;
2942 ** Lock the file with the lock specified by parameter eFileLock - one
2943 ** of the following:
2945 ** (1) SHARED_LOCK
2946 ** (2) RESERVED_LOCK
2947 ** (3) PENDING_LOCK
2948 ** (4) EXCLUSIVE_LOCK
2950 ** Sometimes when requesting one lock state, additional lock states
2951 ** are inserted in between. The locking might fail on one of the later
2952 ** transitions leaving the lock state different from what it started but
2953 ** still short of its goal. The following chart shows the allowed
2954 ** transitions and the inserted intermediate states:
2956 ** UNLOCKED -> SHARED
2957 ** SHARED -> RESERVED
2958 ** SHARED -> (PENDING) -> EXCLUSIVE
2959 ** RESERVED -> (PENDING) -> EXCLUSIVE
2960 ** PENDING -> EXCLUSIVE
2962 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
2963 ** routine to lower a locking level.
2965 static int afpLock(sqlite3_file *id, int eFileLock){
2966 int rc = SQLITE_OK;
2967 unixFile *pFile = (unixFile*)id;
2968 unixInodeInfo *pInode = pFile->pInode;
2969 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2971 assert( pFile );
2972 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2973 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
2974 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
2976 /* If there is already a lock of this type or more restrictive on the
2977 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
2978 ** unixEnterMutex() hasn't been called yet.
2980 if( pFile->eFileLock>=eFileLock ){
2981 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2982 azFileLock(eFileLock)));
2983 return SQLITE_OK;
2986 /* Make sure the locking sequence is correct
2987 ** (1) We never move from unlocked to anything higher than shared lock.
2988 ** (2) SQLite never explicitly requests a pending lock.
2989 ** (3) A shared lock is always held when a reserve lock is requested.
2991 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2992 assert( eFileLock!=PENDING_LOCK );
2993 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
2995 /* This mutex is needed because pFile->pInode is shared across threads
2997 pInode = pFile->pInode;
2998 sqlite3_mutex_enter(pInode->pLockMutex);
3000 /* If some thread using this PID has a lock via a different unixFile*
3001 ** handle that precludes the requested lock, return BUSY.
3003 if( (pFile->eFileLock!=pInode->eFileLock &&
3004 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
3006 rc = SQLITE_BUSY;
3007 goto afp_end_lock;
3010 /* If a SHARED lock is requested, and some thread using this PID already
3011 ** has a SHARED or RESERVED lock, then increment reference counts and
3012 ** return SQLITE_OK.
3014 if( eFileLock==SHARED_LOCK &&
3015 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
3016 assert( eFileLock==SHARED_LOCK );
3017 assert( pFile->eFileLock==0 );
3018 assert( pInode->nShared>0 );
3019 pFile->eFileLock = SHARED_LOCK;
3020 pInode->nShared++;
3021 pInode->nLock++;
3022 goto afp_end_lock;
3025 /* A PENDING lock is needed before acquiring a SHARED lock and before
3026 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
3027 ** be released.
3029 if( eFileLock==SHARED_LOCK
3030 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
3032 int failed;
3033 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
3034 if (failed) {
3035 rc = failed;
3036 goto afp_end_lock;
3040 /* If control gets to this point, then actually go ahead and make
3041 ** operating system calls for the specified lock.
3043 if( eFileLock==SHARED_LOCK ){
3044 int lrc1, lrc2, lrc1Errno = 0;
3045 long lk, mask;
3047 assert( pInode->nShared==0 );
3048 assert( pInode->eFileLock==0 );
3050 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
3051 /* Now get the read-lock SHARED_LOCK */
3052 /* note that the quality of the randomness doesn't matter that much */
3053 lk = random();
3054 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
3055 lrc1 = afpSetLock(context->dbPath, pFile,
3056 SHARED_FIRST+pInode->sharedByte, 1, 1);
3057 if( IS_LOCK_ERROR(lrc1) ){
3058 lrc1Errno = pFile->lastErrno;
3060 /* Drop the temporary PENDING lock */
3061 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
3063 if( IS_LOCK_ERROR(lrc1) ) {
3064 storeLastErrno(pFile, lrc1Errno);
3065 rc = lrc1;
3066 goto afp_end_lock;
3067 } else if( IS_LOCK_ERROR(lrc2) ){
3068 rc = lrc2;
3069 goto afp_end_lock;
3070 } else if( lrc1 != SQLITE_OK ) {
3071 rc = lrc1;
3072 } else {
3073 pFile->eFileLock = SHARED_LOCK;
3074 pInode->nLock++;
3075 pInode->nShared = 1;
3077 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
3078 /* We are trying for an exclusive lock but another thread in this
3079 ** same process is still holding a shared lock. */
3080 rc = SQLITE_BUSY;
3081 }else{
3082 /* The request was for a RESERVED or EXCLUSIVE lock. It is
3083 ** assumed that there is a SHARED or greater lock on the file
3084 ** already.
3086 int failed = 0;
3087 assert( 0!=pFile->eFileLock );
3088 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
3089 /* Acquire a RESERVED lock */
3090 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
3091 if( !failed ){
3092 context->reserved = 1;
3095 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
3096 /* Acquire an EXCLUSIVE lock */
3098 /* Remove the shared lock before trying the range. we'll need to
3099 ** reestablish the shared lock if we can't get the afpUnlock
3101 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
3102 pInode->sharedByte, 1, 0)) ){
3103 int failed2 = SQLITE_OK;
3104 /* now attempt to get the exclusive lock range */
3105 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
3106 SHARED_SIZE, 1);
3107 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
3108 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
3109 /* Can't reestablish the shared lock. Sqlite can't deal, this is
3110 ** a critical I/O error
3112 rc = ((failed & 0xff) == SQLITE_IOERR) ? failed2 :
3113 SQLITE_IOERR_LOCK;
3114 goto afp_end_lock;
3116 }else{
3117 rc = failed;
3120 if( failed ){
3121 rc = failed;
3125 if( rc==SQLITE_OK ){
3126 pFile->eFileLock = eFileLock;
3127 pInode->eFileLock = eFileLock;
3128 }else if( eFileLock==EXCLUSIVE_LOCK ){
3129 pFile->eFileLock = PENDING_LOCK;
3130 pInode->eFileLock = PENDING_LOCK;
3133 afp_end_lock:
3134 sqlite3_mutex_leave(pInode->pLockMutex);
3135 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
3136 rc==SQLITE_OK ? "ok" : "failed"));
3137 return rc;
3141 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
3142 ** must be either NO_LOCK or SHARED_LOCK.
3144 ** If the locking level of the file descriptor is already at or below
3145 ** the requested locking level, this routine is a no-op.
3147 static int afpUnlock(sqlite3_file *id, int eFileLock) {
3148 int rc = SQLITE_OK;
3149 unixFile *pFile = (unixFile*)id;
3150 unixInodeInfo *pInode;
3151 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
3152 int skipShared = 0;
3154 assert( pFile );
3155 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
3156 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
3157 osGetpid(0)));
3159 assert( eFileLock<=SHARED_LOCK );
3160 if( pFile->eFileLock<=eFileLock ){
3161 return SQLITE_OK;
3163 pInode = pFile->pInode;
3164 sqlite3_mutex_enter(pInode->pLockMutex);
3165 assert( pInode->nShared!=0 );
3166 if( pFile->eFileLock>SHARED_LOCK ){
3167 assert( pInode->eFileLock==pFile->eFileLock );
3169 #ifdef SQLITE_DEBUG
3170 /* When reducing a lock such that other processes can start
3171 ** reading the database file again, make sure that the
3172 ** transaction counter was updated if any part of the database
3173 ** file changed. If the transaction counter is not updated,
3174 ** other connections to the same file might not realize that
3175 ** the file has changed and hence might not know to flush their
3176 ** cache. The use of a stale cache can lead to database corruption.
3178 assert( pFile->inNormalWrite==0
3179 || pFile->dbUpdate==0
3180 || pFile->transCntrChng==1 );
3181 pFile->inNormalWrite = 0;
3182 #endif
3184 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
3185 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
3186 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
3187 /* only re-establish the shared lock if necessary */
3188 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3189 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
3190 } else {
3191 skipShared = 1;
3194 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
3195 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
3197 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
3198 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
3199 if( !rc ){
3200 context->reserved = 0;
3203 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
3204 pInode->eFileLock = SHARED_LOCK;
3207 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
3209 /* Decrement the shared lock counter. Release the lock using an
3210 ** OS call only when all threads in this same process have released
3211 ** the lock.
3213 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3214 pInode->nShared--;
3215 if( pInode->nShared==0 ){
3216 if( !skipShared ){
3217 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
3219 if( !rc ){
3220 pInode->eFileLock = NO_LOCK;
3221 pFile->eFileLock = NO_LOCK;
3224 if( rc==SQLITE_OK ){
3225 pInode->nLock--;
3226 assert( pInode->nLock>=0 );
3227 if( pInode->nLock==0 ) closePendingFds(pFile);
3231 sqlite3_mutex_leave(pInode->pLockMutex);
3232 if( rc==SQLITE_OK ){
3233 pFile->eFileLock = eFileLock;
3235 return rc;
3239 ** Close a file & cleanup AFP specific locking context
3241 static int afpClose(sqlite3_file *id) {
3242 int rc = SQLITE_OK;
3243 unixFile *pFile = (unixFile*)id;
3244 assert( id!=0 );
3245 afpUnlock(id, NO_LOCK);
3246 assert( unixFileMutexNotheld(pFile) );
3247 unixEnterMutex();
3248 if( pFile->pInode ){
3249 unixInodeInfo *pInode = pFile->pInode;
3250 sqlite3_mutex_enter(pInode->pLockMutex);
3251 if( pInode->nLock ){
3252 /* If there are outstanding locks, do not actually close the file just
3253 ** yet because that would clear those locks. Instead, add the file
3254 ** descriptor to pInode->aPending. It will be automatically closed when
3255 ** the last lock is cleared.
3257 setPendingFd(pFile);
3259 sqlite3_mutex_leave(pInode->pLockMutex);
3261 releaseInodeInfo(pFile);
3262 sqlite3_free(pFile->lockingContext);
3263 rc = closeUnixFile(id);
3264 unixLeaveMutex();
3265 return rc;
3268 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3270 ** The code above is the AFP lock implementation. The code is specific
3271 ** to MacOSX and does not work on other unix platforms. No alternative
3272 ** is available. If you don't compile for a mac, then the "unix-afp"
3273 ** VFS is not available.
3275 ********************* End of the AFP lock implementation **********************
3276 ******************************************************************************/
3278 /******************************************************************************
3279 *************************** Begin NFS Locking ********************************/
3281 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3283 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
3284 ** must be either NO_LOCK or SHARED_LOCK.
3286 ** If the locking level of the file descriptor is already at or below
3287 ** the requested locking level, this routine is a no-op.
3289 static int nfsUnlock(sqlite3_file *id, int eFileLock){
3290 return posixUnlock(id, eFileLock, 1);
3293 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3295 ** The code above is the NFS lock implementation. The code is specific
3296 ** to MacOSX and does not work on other unix platforms. No alternative
3297 ** is available.
3299 ********************* End of the NFS lock implementation **********************
3300 ******************************************************************************/
3302 /******************************************************************************
3303 **************** Non-locking sqlite3_file methods *****************************
3305 ** The next division contains implementations for all methods of the
3306 ** sqlite3_file object other than the locking methods. The locking
3307 ** methods were defined in divisions above (one locking method per
3308 ** division). Those methods that are common to all locking modes
3309 ** are gather together into this division.
3313 ** Seek to the offset passed as the second argument, then read cnt
3314 ** bytes into pBuf. Return the number of bytes actually read.
3316 ** To avoid stomping the errno value on a failed read the lastErrno value
3317 ** is set before returning.
3319 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3320 int got;
3321 int prior = 0;
3322 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
3323 i64 newOffset;
3324 #endif
3325 TIMER_START;
3326 assert( cnt==(cnt&0x1ffff) );
3327 assert( id->h>2 );
3329 #if defined(USE_PREAD)
3330 got = osPread(id->h, pBuf, cnt, offset);
3331 SimulateIOError( got = -1 );
3332 #elif defined(USE_PREAD64)
3333 got = osPread64(id->h, pBuf, cnt, offset);
3334 SimulateIOError( got = -1 );
3335 #else
3336 newOffset = lseek(id->h, offset, SEEK_SET);
3337 SimulateIOError( newOffset = -1 );
3338 if( newOffset<0 ){
3339 storeLastErrno((unixFile*)id, errno);
3340 return -1;
3342 got = osRead(id->h, pBuf, cnt);
3343 #endif
3344 if( got==cnt ) break;
3345 if( got<0 ){
3346 if( errno==EINTR ){ got = 1; continue; }
3347 prior = 0;
3348 storeLastErrno((unixFile*)id, errno);
3349 break;
3350 }else if( got>0 ){
3351 cnt -= got;
3352 offset += got;
3353 prior += got;
3354 pBuf = (void*)(got + (char*)pBuf);
3356 }while( got>0 );
3357 TIMER_END;
3358 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3359 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3360 return got+prior;
3364 ** Read data from a file into a buffer. Return SQLITE_OK if all
3365 ** bytes were read successfully and SQLITE_IOERR if anything goes
3366 ** wrong.
3368 static int unixRead(
3369 sqlite3_file *id,
3370 void *pBuf,
3371 int amt,
3372 sqlite3_int64 offset
3374 unixFile *pFile = (unixFile *)id;
3375 int got;
3376 assert( id );
3377 assert( offset>=0 );
3378 assert( amt>0 );
3380 /* If this is a database file (not a journal, super-journal or temp
3381 ** file), the bytes in the locking range should never be read or written. */
3382 #if 0
3383 assert( pFile->pPreallocatedUnused==0
3384 || offset>=PENDING_BYTE+512
3385 || offset+amt<=PENDING_BYTE
3387 #endif
3389 #if SQLITE_MAX_MMAP_SIZE>0
3390 /* Deal with as much of this read request as possible by transferring
3391 ** data from the memory mapping using memcpy(). */
3392 if( offset<pFile->mmapSize ){
3393 if( offset+amt <= pFile->mmapSize ){
3394 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3395 return SQLITE_OK;
3396 }else{
3397 int nCopy = pFile->mmapSize - offset;
3398 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3399 pBuf = &((u8 *)pBuf)[nCopy];
3400 amt -= nCopy;
3401 offset += nCopy;
3404 #endif
3406 got = seekAndRead(pFile, offset, pBuf, amt);
3407 if( got==amt ){
3408 return SQLITE_OK;
3409 }else if( got<0 ){
3410 /* pFile->lastErrno has been set by seekAndRead().
3411 ** Usually we return SQLITE_IOERR_READ here, though for some
3412 ** kinds of errors we return SQLITE_IOERR_CORRUPTFS. The
3413 ** SQLITE_IOERR_CORRUPTFS will be converted into SQLITE_CORRUPT
3414 ** prior to returning to the application by the sqlite3ApiExit()
3415 ** routine.
3417 switch( pFile->lastErrno ){
3418 case ERANGE:
3419 case EIO:
3420 #ifdef ENXIO
3421 case ENXIO:
3422 #endif
3423 #ifdef EDEVERR
3424 case EDEVERR:
3425 #endif
3426 return SQLITE_IOERR_CORRUPTFS;
3428 return SQLITE_IOERR_READ;
3429 }else{
3430 storeLastErrno(pFile, 0); /* not a system error */
3431 /* Unread parts of the buffer must be zero-filled */
3432 memset(&((char*)pBuf)[got], 0, amt-got);
3433 return SQLITE_IOERR_SHORT_READ;
3438 ** Attempt to seek the file-descriptor passed as the first argument to
3439 ** absolute offset iOff, then attempt to write nBuf bytes of data from
3440 ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3441 ** return the actual number of bytes written (which may be less than
3442 ** nBuf).
3444 static int seekAndWriteFd(
3445 int fd, /* File descriptor to write to */
3446 i64 iOff, /* File offset to begin writing at */
3447 const void *pBuf, /* Copy data from this buffer to the file */
3448 int nBuf, /* Size of buffer pBuf in bytes */
3449 int *piErrno /* OUT: Error number if error occurs */
3451 int rc = 0; /* Value returned by system call */
3453 assert( nBuf==(nBuf&0x1ffff) );
3454 assert( fd>2 );
3455 assert( piErrno!=0 );
3456 nBuf &= 0x1ffff;
3457 TIMER_START;
3459 #if defined(USE_PREAD)
3460 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
3461 #elif defined(USE_PREAD64)
3462 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
3463 #else
3465 i64 iSeek = lseek(fd, iOff, SEEK_SET);
3466 SimulateIOError( iSeek = -1 );
3467 if( iSeek<0 ){
3468 rc = -1;
3469 break;
3471 rc = osWrite(fd, pBuf, nBuf);
3472 }while( rc<0 && errno==EINTR );
3473 #endif
3475 TIMER_END;
3476 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3478 if( rc<0 ) *piErrno = errno;
3479 return rc;
3484 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
3485 ** Return the number of bytes actually read. Update the offset.
3487 ** To avoid stomping the errno value on a failed write the lastErrno value
3488 ** is set before returning.
3490 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
3491 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
3496 ** Write data from a buffer into a file. Return SQLITE_OK on success
3497 ** or some other error code on failure.
3499 static int unixWrite(
3500 sqlite3_file *id,
3501 const void *pBuf,
3502 int amt,
3503 sqlite3_int64 offset
3505 unixFile *pFile = (unixFile*)id;
3506 int wrote = 0;
3507 assert( id );
3508 assert( amt>0 );
3510 /* If this is a database file (not a journal, super-journal or temp
3511 ** file), the bytes in the locking range should never be read or written. */
3512 #if 0
3513 assert( pFile->pPreallocatedUnused==0
3514 || offset>=PENDING_BYTE+512
3515 || offset+amt<=PENDING_BYTE
3517 #endif
3519 #ifdef SQLITE_DEBUG
3520 /* If we are doing a normal write to a database file (as opposed to
3521 ** doing a hot-journal rollback or a write to some file other than a
3522 ** normal database file) then record the fact that the database
3523 ** has changed. If the transaction counter is modified, record that
3524 ** fact too.
3526 if( pFile->inNormalWrite ){
3527 pFile->dbUpdate = 1; /* The database has been modified */
3528 if( offset<=24 && offset+amt>=27 ){
3529 int rc;
3530 char oldCntr[4];
3531 SimulateIOErrorBenign(1);
3532 rc = seekAndRead(pFile, 24, oldCntr, 4);
3533 SimulateIOErrorBenign(0);
3534 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
3535 pFile->transCntrChng = 1; /* The transaction counter has changed */
3539 #endif
3541 #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
3542 /* Deal with as much of this write request as possible by transferring
3543 ** data from the memory mapping using memcpy(). */
3544 if( offset<pFile->mmapSize ){
3545 if( offset+amt <= pFile->mmapSize ){
3546 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3547 return SQLITE_OK;
3548 }else{
3549 int nCopy = pFile->mmapSize - offset;
3550 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3551 pBuf = &((u8 *)pBuf)[nCopy];
3552 amt -= nCopy;
3553 offset += nCopy;
3556 #endif
3558 while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
3559 amt -= wrote;
3560 offset += wrote;
3561 pBuf = &((char*)pBuf)[wrote];
3563 SimulateIOError(( wrote=(-1), amt=1 ));
3564 SimulateDiskfullError(( wrote=0, amt=1 ));
3566 if( amt>wrote ){
3567 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
3568 /* lastErrno set by seekAndWrite */
3569 return SQLITE_IOERR_WRITE;
3570 }else{
3571 storeLastErrno(pFile, 0); /* not a system error */
3572 return SQLITE_FULL;
3576 return SQLITE_OK;
3579 #ifdef SQLITE_TEST
3581 ** Count the number of fullsyncs and normal syncs. This is used to test
3582 ** that syncs and fullsyncs are occurring at the right times.
3584 int sqlite3_sync_count = 0;
3585 int sqlite3_fullsync_count = 0;
3586 #endif
3589 ** We do not trust systems to provide a working fdatasync(). Some do.
3590 ** Others do no. To be safe, we will stick with the (slightly slower)
3591 ** fsync(). If you know that your system does support fdatasync() correctly,
3592 ** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
3594 #if !defined(fdatasync) && !HAVE_FDATASYNC
3595 # define fdatasync fsync
3596 #endif
3599 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3600 ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3601 ** only available on Mac OS X. But that could change.
3603 #ifdef F_FULLFSYNC
3604 # define HAVE_FULLFSYNC 1
3605 #else
3606 # define HAVE_FULLFSYNC 0
3607 #endif
3611 ** The fsync() system call does not work as advertised on many
3612 ** unix systems. The following procedure is an attempt to make
3613 ** it work better.
3615 ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3616 ** for testing when we want to run through the test suite quickly.
3617 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3618 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3619 ** or power failure will likely corrupt the database file.
3621 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
3622 ** The idea behind dataOnly is that it should only write the file content
3623 ** to disk, not the inode. We only set dataOnly if the file size is
3624 ** unchanged since the file size is part of the inode. However,
3625 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
3626 ** file size has changed. The only real difference between fdatasync()
3627 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
3628 ** inode if the mtime or owner or other inode attributes have changed.
3629 ** We only care about the file size, not the other file attributes, so
3630 ** as far as SQLite is concerned, an fdatasync() is always adequate.
3631 ** So, we always use fdatasync() if it is available, regardless of
3632 ** the value of the dataOnly flag.
3634 static int full_fsync(int fd, int fullSync, int dataOnly){
3635 int rc;
3637 /* The following "ifdef/elif/else/" block has the same structure as
3638 ** the one below. It is replicated here solely to avoid cluttering
3639 ** up the real code with the UNUSED_PARAMETER() macros.
3641 #ifdef SQLITE_NO_SYNC
3642 UNUSED_PARAMETER(fd);
3643 UNUSED_PARAMETER(fullSync);
3644 UNUSED_PARAMETER(dataOnly);
3645 #elif HAVE_FULLFSYNC
3646 UNUSED_PARAMETER(dataOnly);
3647 #else
3648 UNUSED_PARAMETER(fullSync);
3649 UNUSED_PARAMETER(dataOnly);
3650 #endif
3652 /* Record the number of times that we do a normal fsync() and
3653 ** FULLSYNC. This is used during testing to verify that this procedure
3654 ** gets called with the correct arguments.
3656 #ifdef SQLITE_TEST
3657 if( fullSync ) sqlite3_fullsync_count++;
3658 sqlite3_sync_count++;
3659 #endif
3661 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3662 ** no-op. But go ahead and call fstat() to validate the file
3663 ** descriptor as we need a method to provoke a failure during
3664 ** coverage testing.
3666 #ifdef SQLITE_NO_SYNC
3668 struct stat buf;
3669 rc = osFstat(fd, &buf);
3671 #elif HAVE_FULLFSYNC
3672 if( fullSync ){
3673 rc = osFcntl(fd, F_FULLFSYNC, 0);
3674 }else{
3675 rc = 1;
3677 /* If the FULLFSYNC failed, fall back to attempting an fsync().
3678 ** It shouldn't be possible for fullfsync to fail on the local
3679 ** file system (on OSX), so failure indicates that FULLFSYNC
3680 ** isn't supported for this file system. So, attempt an fsync
3681 ** and (for now) ignore the overhead of a superfluous fcntl call.
3682 ** It'd be better to detect fullfsync support once and avoid
3683 ** the fcntl call every time sync is called.
3685 if( rc ) rc = fsync(fd);
3687 #elif defined(__APPLE__)
3688 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3689 ** so currently we default to the macro that redefines fdatasync to fsync
3691 rc = fsync(fd);
3692 #else
3693 rc = fdatasync(fd);
3694 #if OS_VXWORKS
3695 if( rc==-1 && errno==ENOTSUP ){
3696 rc = fsync(fd);
3698 #endif /* OS_VXWORKS */
3699 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3701 if( OS_VXWORKS && rc!= -1 ){
3702 rc = 0;
3704 return rc;
3708 ** Open a file descriptor to the directory containing file zFilename.
3709 ** If successful, *pFd is set to the opened file descriptor and
3710 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3711 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3712 ** value.
3714 ** The directory file descriptor is used for only one thing - to
3715 ** fsync() a directory to make sure file creation and deletion events
3716 ** are flushed to disk. Such fsyncs are not needed on newer
3717 ** journaling filesystems, but are required on older filesystems.
3719 ** This routine can be overridden using the xSetSysCall interface.
3720 ** The ability to override this routine was added in support of the
3721 ** chromium sandbox. Opening a directory is a security risk (we are
3722 ** told) so making it overrideable allows the chromium sandbox to
3723 ** replace this routine with a harmless no-op. To make this routine
3724 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3725 ** *pFd set to a negative number.
3727 ** If SQLITE_OK is returned, the caller is responsible for closing
3728 ** the file descriptor *pFd using close().
3730 static int openDirectory(const char *zFilename, int *pFd){
3731 int ii;
3732 int fd = -1;
3733 char zDirname[MAX_PATHNAME+1];
3735 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3736 for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
3737 if( ii>0 ){
3738 zDirname[ii] = '\0';
3739 }else{
3740 if( zDirname[0]!='/' ) zDirname[0] = '.';
3741 zDirname[1] = 0;
3743 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3744 if( fd>=0 ){
3745 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3747 *pFd = fd;
3748 if( fd>=0 ) return SQLITE_OK;
3749 return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
3753 ** Make sure all writes to a particular file are committed to disk.
3755 ** If dataOnly==0 then both the file itself and its metadata (file
3756 ** size, access time, etc) are synced. If dataOnly!=0 then only the
3757 ** file data is synced.
3759 ** Under Unix, also make sure that the directory entry for the file
3760 ** has been created by fsync-ing the directory that contains the file.
3761 ** If we do not do this and we encounter a power failure, the directory
3762 ** entry for the journal might not exist after we reboot. The next
3763 ** SQLite to access the file will not know that the journal exists (because
3764 ** the directory entry for the journal was never created) and the transaction
3765 ** will not roll back - possibly leading to database corruption.
3767 static int unixSync(sqlite3_file *id, int flags){
3768 int rc;
3769 unixFile *pFile = (unixFile*)id;
3771 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3772 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3774 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3775 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3776 || (flags&0x0F)==SQLITE_SYNC_FULL
3779 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3780 ** line is to test that doing so does not cause any problems.
3782 SimulateDiskfullError( return SQLITE_FULL );
3784 assert( pFile );
3785 OSTRACE(("SYNC %-3d\n", pFile->h));
3786 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3787 SimulateIOError( rc=1 );
3788 if( rc ){
3789 storeLastErrno(pFile, errno);
3790 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
3793 /* Also fsync the directory containing the file if the DIRSYNC flag
3794 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
3795 ** are unable to fsync a directory, so ignore errors on the fsync.
3797 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3798 int dirfd;
3799 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
3800 HAVE_FULLFSYNC, isFullsync));
3801 rc = osOpenDirectory(pFile->zPath, &dirfd);
3802 if( rc==SQLITE_OK ){
3803 full_fsync(dirfd, 0, 0);
3804 robust_close(pFile, dirfd, __LINE__);
3805 }else{
3806 assert( rc==SQLITE_CANTOPEN );
3807 rc = SQLITE_OK;
3809 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
3811 return rc;
3815 ** Truncate an open file to a specified size
3817 static int unixTruncate(sqlite3_file *id, i64 nByte){
3818 unixFile *pFile = (unixFile *)id;
3819 int rc;
3820 assert( pFile );
3821 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
3823 /* If the user has configured a chunk-size for this file, truncate the
3824 ** file so that it consists of an integer number of chunks (i.e. the
3825 ** actual file size after the operation may be larger than the requested
3826 ** size).
3828 if( pFile->szChunk>0 ){
3829 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3832 rc = robust_ftruncate(pFile->h, nByte);
3833 if( rc ){
3834 storeLastErrno(pFile, errno);
3835 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3836 }else{
3837 #ifdef SQLITE_DEBUG
3838 /* If we are doing a normal write to a database file (as opposed to
3839 ** doing a hot-journal rollback or a write to some file other than a
3840 ** normal database file) and we truncate the file to zero length,
3841 ** that effectively updates the change counter. This might happen
3842 ** when restoring a database using the backup API from a zero-length
3843 ** source.
3845 if( pFile->inNormalWrite && nByte==0 ){
3846 pFile->transCntrChng = 1;
3848 #endif
3850 #if SQLITE_MAX_MMAP_SIZE>0
3851 /* If the file was just truncated to a size smaller than the currently
3852 ** mapped region, reduce the effective mapping size as well. SQLite will
3853 ** use read() and write() to access data beyond this point from now on.
3855 if( nByte<pFile->mmapSize ){
3856 pFile->mmapSize = nByte;
3858 #endif
3860 return SQLITE_OK;
3865 ** Determine the current size of a file in bytes
3867 static int unixFileSize(sqlite3_file *id, i64 *pSize){
3868 int rc;
3869 struct stat buf;
3870 assert( id );
3871 rc = osFstat(((unixFile*)id)->h, &buf);
3872 SimulateIOError( rc=1 );
3873 if( rc!=0 ){
3874 storeLastErrno((unixFile*)id, errno);
3875 return SQLITE_IOERR_FSTAT;
3877 *pSize = buf.st_size;
3879 /* When opening a zero-size database, the findInodeInfo() procedure
3880 ** writes a single byte into that file in order to work around a bug
3881 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3882 ** layers, we need to report this file size as zero even though it is
3883 ** really 1. Ticket #3260.
3885 if( *pSize==1 ) *pSize = 0;
3888 return SQLITE_OK;
3891 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
3893 ** Handler for proxy-locking file-control verbs. Defined below in the
3894 ** proxying locking division.
3896 static int proxyFileControl(sqlite3_file*,int,void*);
3897 #endif
3900 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
3901 ** file-control operation. Enlarge the database to nBytes in size
3902 ** (rounded up to the next chunk-size). If the database is already
3903 ** nBytes or larger, this routine is a no-op.
3905 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
3906 if( pFile->szChunk>0 ){
3907 i64 nSize; /* Required file size */
3908 struct stat buf; /* Used to hold return values of fstat() */
3910 if( osFstat(pFile->h, &buf) ){
3911 return SQLITE_IOERR_FSTAT;
3914 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3915 if( nSize>(i64)buf.st_size ){
3917 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
3918 /* The code below is handling the return value of osFallocate()
3919 ** correctly. posix_fallocate() is defined to "returns zero on success,
3920 ** or an error number on failure". See the manpage for details. */
3921 int err;
3923 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3924 }while( err==EINTR );
3925 if( err && err!=EINVAL ) return SQLITE_IOERR_WRITE;
3926 #else
3927 /* If the OS does not have posix_fallocate(), fake it. Write a
3928 ** single byte to the last byte in each block that falls entirely
3929 ** within the extended region. Then, if required, a single byte
3930 ** at offset (nSize-1), to set the size of the file correctly.
3931 ** This is a similar technique to that used by glibc on systems
3932 ** that do not have a real fallocate() call.
3934 int nBlk = buf.st_blksize; /* File-system block size */
3935 int nWrite = 0; /* Number of bytes written by seekAndWrite */
3936 i64 iWrite; /* Next offset to write to */
3938 iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
3939 assert( iWrite>=buf.st_size );
3940 assert( ((iWrite+1)%nBlk)==0 );
3941 for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
3942 if( iWrite>=nSize ) iWrite = nSize - 1;
3943 nWrite = seekAndWrite(pFile, iWrite, "", 1);
3944 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
3946 #endif
3950 #if SQLITE_MAX_MMAP_SIZE>0
3951 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
3952 int rc;
3953 if( pFile->szChunk<=0 ){
3954 if( robust_ftruncate(pFile->h, nByte) ){
3955 storeLastErrno(pFile, errno);
3956 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3960 rc = unixMapfile(pFile, nByte);
3961 return rc;
3963 #endif
3965 return SQLITE_OK;
3969 ** If *pArg is initially negative then this is a query. Set *pArg to
3970 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3972 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3974 static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3975 if( *pArg<0 ){
3976 *pArg = (pFile->ctrlFlags & mask)!=0;
3977 }else if( (*pArg)==0 ){
3978 pFile->ctrlFlags &= ~mask;
3979 }else{
3980 pFile->ctrlFlags |= mask;
3984 /* Forward declaration */
3985 static int unixGetTempname(int nBuf, char *zBuf);
3986 #ifndef SQLITE_OMIT_WAL
3987 static int unixFcntlExternalReader(unixFile*, int*);
3988 #endif
3991 ** Information and control of an open file handle.
3993 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
3994 unixFile *pFile = (unixFile*)id;
3995 switch( op ){
3996 #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
3997 case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: {
3998 int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE);
3999 return rc ? SQLITE_IOERR_BEGIN_ATOMIC : SQLITE_OK;
4001 case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: {
4002 int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE);
4003 return rc ? SQLITE_IOERR_COMMIT_ATOMIC : SQLITE_OK;
4005 case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: {
4006 int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE);
4007 return rc ? SQLITE_IOERR_ROLLBACK_ATOMIC : SQLITE_OK;
4009 #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
4011 case SQLITE_FCNTL_LOCKSTATE: {
4012 *(int*)pArg = pFile->eFileLock;
4013 return SQLITE_OK;
4015 case SQLITE_FCNTL_LAST_ERRNO: {
4016 *(int*)pArg = pFile->lastErrno;
4017 return SQLITE_OK;
4019 case SQLITE_FCNTL_CHUNK_SIZE: {
4020 pFile->szChunk = *(int *)pArg;
4021 return SQLITE_OK;
4023 case SQLITE_FCNTL_SIZE_HINT: {
4024 int rc;
4025 SimulateIOErrorBenign(1);
4026 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
4027 SimulateIOErrorBenign(0);
4028 return rc;
4030 case SQLITE_FCNTL_PERSIST_WAL: {
4031 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
4032 return SQLITE_OK;
4034 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
4035 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
4036 return SQLITE_OK;
4038 case SQLITE_FCNTL_VFSNAME: {
4039 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
4040 return SQLITE_OK;
4042 case SQLITE_FCNTL_TEMPFILENAME: {
4043 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
4044 if( zTFile ){
4045 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
4046 *(char**)pArg = zTFile;
4048 return SQLITE_OK;
4050 case SQLITE_FCNTL_HAS_MOVED: {
4051 *(int*)pArg = fileHasMoved(pFile);
4052 return SQLITE_OK;
4054 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
4055 case SQLITE_FCNTL_LOCK_TIMEOUT: {
4056 int iOld = pFile->iBusyTimeout;
4057 pFile->iBusyTimeout = *(int*)pArg;
4058 *(int*)pArg = iOld;
4059 return SQLITE_OK;
4061 #endif
4062 #if SQLITE_MAX_MMAP_SIZE>0
4063 case SQLITE_FCNTL_MMAP_SIZE: {
4064 i64 newLimit = *(i64*)pArg;
4065 int rc = SQLITE_OK;
4066 if( newLimit>sqlite3GlobalConfig.mxMmap ){
4067 newLimit = sqlite3GlobalConfig.mxMmap;
4070 /* The value of newLimit may be eventually cast to (size_t) and passed
4071 ** to mmap(). Restrict its value to 2GB if (size_t) is not at least a
4072 ** 64-bit type. */
4073 if( newLimit>0 && sizeof(size_t)<8 ){
4074 newLimit = (newLimit & 0x7FFFFFFF);
4077 *(i64*)pArg = pFile->mmapSizeMax;
4078 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
4079 pFile->mmapSizeMax = newLimit;
4080 if( pFile->mmapSize>0 ){
4081 unixUnmapfile(pFile);
4082 rc = unixMapfile(pFile, -1);
4085 return rc;
4087 #endif
4088 #ifdef SQLITE_DEBUG
4089 /* The pager calls this method to signal that it has done
4090 ** a rollback and that the database is therefore unchanged and
4091 ** it hence it is OK for the transaction change counter to be
4092 ** unchanged.
4094 case SQLITE_FCNTL_DB_UNCHANGED: {
4095 ((unixFile*)id)->dbUpdate = 0;
4096 return SQLITE_OK;
4098 #endif
4099 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
4100 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
4101 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
4102 return proxyFileControl(id,op,pArg);
4104 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
4106 case SQLITE_FCNTL_EXTERNAL_READER: {
4107 #ifndef SQLITE_OMIT_WAL
4108 return unixFcntlExternalReader((unixFile*)id, (int*)pArg);
4109 #else
4110 *(int*)pArg = 0;
4111 return SQLITE_OK;
4112 #endif
4115 return SQLITE_NOTFOUND;
4119 ** If pFd->sectorSize is non-zero when this function is called, it is a
4120 ** no-op. Otherwise, the values of pFd->sectorSize and
4121 ** pFd->deviceCharacteristics are set according to the file-system
4122 ** characteristics.
4124 ** There are two versions of this function. One for QNX and one for all
4125 ** other systems.
4127 #ifndef __QNXNTO__
4128 static void setDeviceCharacteristics(unixFile *pFd){
4129 assert( pFd->deviceCharacteristics==0 || pFd->sectorSize!=0 );
4130 if( pFd->sectorSize==0 ){
4131 #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
4132 int res;
4133 u32 f = 0;
4135 /* Check for support for F2FS atomic batch writes. */
4136 res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES, &f);
4137 if( res==0 && (f & F2FS_FEATURE_ATOMIC_WRITE) ){
4138 pFd->deviceCharacteristics = SQLITE_IOCAP_BATCH_ATOMIC;
4140 #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
4142 /* Set the POWERSAFE_OVERWRITE flag if requested. */
4143 if( pFd->ctrlFlags & UNIXFILE_PSOW ){
4144 pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
4147 pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4150 #else
4151 #include <sys/dcmd_blk.h>
4152 #include <sys/statvfs.h>
4153 static void setDeviceCharacteristics(unixFile *pFile){
4154 if( pFile->sectorSize == 0 ){
4155 struct statvfs fsInfo;
4157 /* Set defaults for non-supported filesystems */
4158 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4159 pFile->deviceCharacteristics = 0;
4160 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
4161 return;
4164 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
4165 pFile->sectorSize = fsInfo.f_bsize;
4166 pFile->deviceCharacteristics =
4167 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
4168 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4169 ** the write succeeds */
4170 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4171 ** so it is ordered */
4173 }else if( strstr(fsInfo.f_basetype, "etfs") ){
4174 pFile->sectorSize = fsInfo.f_bsize;
4175 pFile->deviceCharacteristics =
4176 /* etfs cluster size writes are atomic */
4177 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
4178 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4179 ** the write succeeds */
4180 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4181 ** so it is ordered */
4183 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
4184 pFile->sectorSize = fsInfo.f_bsize;
4185 pFile->deviceCharacteristics =
4186 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
4187 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4188 ** the write succeeds */
4189 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4190 ** so it is ordered */
4192 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
4193 pFile->sectorSize = fsInfo.f_bsize;
4194 pFile->deviceCharacteristics =
4195 /* full bitset of atomics from max sector size and smaller */
4196 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
4197 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4198 ** so it is ordered */
4200 }else if( strstr(fsInfo.f_basetype, "dos") ){
4201 pFile->sectorSize = fsInfo.f_bsize;
4202 pFile->deviceCharacteristics =
4203 /* full bitset of atomics from max sector size and smaller */
4204 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
4205 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4206 ** so it is ordered */
4208 }else{
4209 pFile->deviceCharacteristics =
4210 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
4211 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4212 ** the write succeeds */
4216 /* Last chance verification. If the sector size isn't a multiple of 512
4217 ** then it isn't valid.*/
4218 if( pFile->sectorSize % 512 != 0 ){
4219 pFile->deviceCharacteristics = 0;
4220 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4223 #endif
4226 ** Return the sector size in bytes of the underlying block device for
4227 ** the specified file. This is almost always 512 bytes, but may be
4228 ** larger for some devices.
4230 ** SQLite code assumes this function cannot fail. It also assumes that
4231 ** if two files are created in the same file-system directory (i.e.
4232 ** a database and its journal file) that the sector size will be the
4233 ** same for both.
4235 static int unixSectorSize(sqlite3_file *id){
4236 unixFile *pFd = (unixFile*)id;
4237 setDeviceCharacteristics(pFd);
4238 return pFd->sectorSize;
4242 ** Return the device characteristics for the file.
4244 ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
4245 ** However, that choice is controversial since technically the underlying
4246 ** file system does not always provide powersafe overwrites. (In other
4247 ** words, after a power-loss event, parts of the file that were never
4248 ** written might end up being altered.) However, non-PSOW behavior is very,
4249 ** very rare. And asserting PSOW makes a large reduction in the amount
4250 ** of required I/O for journaling, since a lot of padding is eliminated.
4251 ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
4252 ** available to turn it off and URI query parameter available to turn it off.
4254 static int unixDeviceCharacteristics(sqlite3_file *id){
4255 unixFile *pFd = (unixFile*)id;
4256 setDeviceCharacteristics(pFd);
4257 return pFd->deviceCharacteristics;
4260 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
4263 ** Return the system page size.
4265 ** This function should not be called directly by other code in this file.
4266 ** Instead, it should be called via macro osGetpagesize().
4268 static int unixGetpagesize(void){
4269 #if OS_VXWORKS
4270 return 1024;
4271 #elif defined(_BSD_SOURCE)
4272 return getpagesize();
4273 #else
4274 return (int)sysconf(_SC_PAGESIZE);
4275 #endif
4278 #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
4280 #ifndef SQLITE_OMIT_WAL
4283 ** Object used to represent an shared memory buffer.
4285 ** When multiple threads all reference the same wal-index, each thread
4286 ** has its own unixShm object, but they all point to a single instance
4287 ** of this unixShmNode object. In other words, each wal-index is opened
4288 ** only once per process.
4290 ** Each unixShmNode object is connected to a single unixInodeInfo object.
4291 ** We could coalesce this object into unixInodeInfo, but that would mean
4292 ** every open file that does not use shared memory (in other words, most
4293 ** open files) would have to carry around this extra information. So
4294 ** the unixInodeInfo object contains a pointer to this unixShmNode object
4295 ** and the unixShmNode object is created only when needed.
4297 ** unixMutexHeld() must be true when creating or destroying
4298 ** this object or while reading or writing the following fields:
4300 ** nRef
4302 ** The following fields are read-only after the object is created:
4304 ** hShm
4305 ** zFilename
4307 ** Either unixShmNode.pShmMutex must be held or unixShmNode.nRef==0 and
4308 ** unixMutexHeld() is true when reading or writing any other field
4309 ** in this structure.
4311 struct unixShmNode {
4312 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
4313 sqlite3_mutex *pShmMutex; /* Mutex to access this object */
4314 char *zFilename; /* Name of the mmapped file */
4315 int hShm; /* Open file descriptor */
4316 int szRegion; /* Size of shared-memory regions */
4317 u16 nRegion; /* Size of array apRegion */
4318 u8 isReadonly; /* True if read-only */
4319 u8 isUnlocked; /* True if no DMS lock held */
4320 char **apRegion; /* Array of mapped shared-memory regions */
4321 int nRef; /* Number of unixShm objects pointing to this */
4322 unixShm *pFirst; /* All unixShm objects pointing to this */
4323 int aLock[SQLITE_SHM_NLOCK]; /* # shared locks on slot, -1==excl lock */
4324 #ifdef SQLITE_DEBUG
4325 u8 exclMask; /* Mask of exclusive locks held */
4326 u8 sharedMask; /* Mask of shared locks held */
4327 u8 nextShmId; /* Next available unixShm.id value */
4328 #endif
4332 ** Structure used internally by this VFS to record the state of an
4333 ** open shared memory connection.
4335 ** The following fields are initialized when this object is created and
4336 ** are read-only thereafter:
4338 ** unixShm.pShmNode
4339 ** unixShm.id
4341 ** All other fields are read/write. The unixShm.pShmNode->pShmMutex must
4342 ** be held while accessing any read/write fields.
4344 struct unixShm {
4345 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4346 unixShm *pNext; /* Next unixShm with the same unixShmNode */
4347 u8 hasMutex; /* True if holding the unixShmNode->pShmMutex */
4348 u8 id; /* Id of this connection within its unixShmNode */
4349 u16 sharedMask; /* Mask of shared locks held */
4350 u16 exclMask; /* Mask of exclusive locks held */
4354 ** Constants used for locking
4356 #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
4357 #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
4360 ** Use F_GETLK to check whether or not there are any readers with open
4361 ** wal-mode transactions in other processes on database file pFile. If
4362 ** no error occurs, return SQLITE_OK and set (*piOut) to 1 if there are
4363 ** such transactions, or 0 otherwise. If an error occurs, return an
4364 ** SQLite error code. The final value of *piOut is undefined in this
4365 ** case.
4367 static int unixFcntlExternalReader(unixFile *pFile, int *piOut){
4368 int rc = SQLITE_OK;
4369 *piOut = 0;
4370 if( pFile->pShm){
4371 unixShmNode *pShmNode = pFile->pShm->pShmNode;
4372 struct flock f;
4374 memset(&f, 0, sizeof(f));
4375 f.l_type = F_WRLCK;
4376 f.l_whence = SEEK_SET;
4377 f.l_start = UNIX_SHM_BASE + 3;
4378 f.l_len = SQLITE_SHM_NLOCK - 3;
4380 sqlite3_mutex_enter(pShmNode->pShmMutex);
4381 if( osFcntl(pShmNode->hShm, F_GETLK, &f)<0 ){
4382 rc = SQLITE_IOERR_LOCK;
4383 }else{
4384 *piOut = (f.l_type!=F_UNLCK);
4386 sqlite3_mutex_leave(pShmNode->pShmMutex);
4389 return rc;
4394 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
4396 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4397 ** otherwise.
4399 static int unixShmSystemLock(
4400 unixFile *pFile, /* Open connection to the WAL file */
4401 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
4402 int ofst, /* First byte of the locking range */
4403 int n /* Number of bytes to lock */
4405 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4406 struct flock f; /* The posix advisory locking structure */
4407 int rc = SQLITE_OK; /* Result code form fcntl() */
4409 /* Access to the unixShmNode object is serialized by the caller */
4410 pShmNode = pFile->pInode->pShmNode;
4411 assert( pShmNode->nRef==0 || sqlite3_mutex_held(pShmNode->pShmMutex) );
4412 assert( pShmNode->nRef>0 || unixMutexHeld() );
4414 /* Shared locks never span more than one byte */
4415 assert( n==1 || lockType!=F_RDLCK );
4417 /* Locks are within range */
4418 assert( n>=1 && n<=SQLITE_SHM_NLOCK );
4420 if( pShmNode->hShm>=0 ){
4421 int res;
4422 /* Initialize the locking parameters */
4423 f.l_type = lockType;
4424 f.l_whence = SEEK_SET;
4425 f.l_start = ofst;
4426 f.l_len = n;
4427 res = osSetPosixAdvisoryLock(pShmNode->hShm, &f, pFile);
4428 if( res==-1 ){
4429 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
4430 rc = (pFile->iBusyTimeout ? SQLITE_BUSY_TIMEOUT : SQLITE_BUSY);
4431 #else
4432 rc = SQLITE_BUSY;
4433 #endif
4437 /* Update the global lock state and do debug tracing */
4438 #ifdef SQLITE_DEBUG
4439 { u16 mask;
4440 OSTRACE(("SHM-LOCK "));
4441 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
4442 if( rc==SQLITE_OK ){
4443 if( lockType==F_UNLCK ){
4444 OSTRACE(("unlock %d ok", ofst));
4445 pShmNode->exclMask &= ~mask;
4446 pShmNode->sharedMask &= ~mask;
4447 }else if( lockType==F_RDLCK ){
4448 OSTRACE(("read-lock %d ok", ofst));
4449 pShmNode->exclMask &= ~mask;
4450 pShmNode->sharedMask |= mask;
4451 }else{
4452 assert( lockType==F_WRLCK );
4453 OSTRACE(("write-lock %d ok", ofst));
4454 pShmNode->exclMask |= mask;
4455 pShmNode->sharedMask &= ~mask;
4457 }else{
4458 if( lockType==F_UNLCK ){
4459 OSTRACE(("unlock %d failed", ofst));
4460 }else if( lockType==F_RDLCK ){
4461 OSTRACE(("read-lock failed"));
4462 }else{
4463 assert( lockType==F_WRLCK );
4464 OSTRACE(("write-lock %d failed", ofst));
4467 OSTRACE((" - afterwards %03x,%03x\n",
4468 pShmNode->sharedMask, pShmNode->exclMask));
4470 #endif
4472 return rc;
4476 ** Return the minimum number of 32KB shm regions that should be mapped at
4477 ** a time, assuming that each mapping must be an integer multiple of the
4478 ** current system page-size.
4480 ** Usually, this is 1. The exception seems to be systems that are configured
4481 ** to use 64KB pages - in this case each mapping must cover at least two
4482 ** shm regions.
4484 static int unixShmRegionPerMap(void){
4485 int shmsz = 32*1024; /* SHM region size */
4486 int pgsz = osGetpagesize(); /* System page size */
4487 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4488 if( pgsz<shmsz ) return 1;
4489 return pgsz/shmsz;
4493 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
4495 ** This is not a VFS shared-memory method; it is a utility function called
4496 ** by VFS shared-memory methods.
4498 static void unixShmPurge(unixFile *pFd){
4499 unixShmNode *p = pFd->pInode->pShmNode;
4500 assert( unixMutexHeld() );
4501 if( p && ALWAYS(p->nRef==0) ){
4502 int nShmPerMap = unixShmRegionPerMap();
4503 int i;
4504 assert( p->pInode==pFd->pInode );
4505 sqlite3_mutex_free(p->pShmMutex);
4506 for(i=0; i<p->nRegion; i+=nShmPerMap){
4507 if( p->hShm>=0 ){
4508 osMunmap(p->apRegion[i], p->szRegion);
4509 }else{
4510 sqlite3_free(p->apRegion[i]);
4513 sqlite3_free(p->apRegion);
4514 if( p->hShm>=0 ){
4515 robust_close(pFd, p->hShm, __LINE__);
4516 p->hShm = -1;
4518 p->pInode->pShmNode = 0;
4519 sqlite3_free(p);
4524 ** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
4525 ** take it now. Return SQLITE_OK if successful, or an SQLite error
4526 ** code otherwise.
4528 ** If the DMS cannot be locked because this is a readonly_shm=1
4529 ** connection and no other process already holds a lock, return
4530 ** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
4532 static int unixLockSharedMemory(unixFile *pDbFd, unixShmNode *pShmNode){
4533 struct flock lock;
4534 int rc = SQLITE_OK;
4536 /* Use F_GETLK to determine the locks other processes are holding
4537 ** on the DMS byte. If it indicates that another process is holding
4538 ** a SHARED lock, then this process may also take a SHARED lock
4539 ** and proceed with opening the *-shm file.
4541 ** Or, if no other process is holding any lock, then this process
4542 ** is the first to open it. In this case take an EXCLUSIVE lock on the
4543 ** DMS byte and truncate the *-shm file to zero bytes in size. Then
4544 ** downgrade to a SHARED lock on the DMS byte.
4546 ** If another process is holding an EXCLUSIVE lock on the DMS byte,
4547 ** return SQLITE_BUSY to the caller (it will try again). An earlier
4548 ** version of this code attempted the SHARED lock at this point. But
4549 ** this introduced a subtle race condition: if the process holding
4550 ** EXCLUSIVE failed just before truncating the *-shm file, then this
4551 ** process might open and use the *-shm file without truncating it.
4552 ** And if the *-shm file has been corrupted by a power failure or
4553 ** system crash, the database itself may also become corrupt. */
4554 lock.l_whence = SEEK_SET;
4555 lock.l_start = UNIX_SHM_DMS;
4556 lock.l_len = 1;
4557 lock.l_type = F_WRLCK;
4558 if( osFcntl(pShmNode->hShm, F_GETLK, &lock)!=0 ) {
4559 rc = SQLITE_IOERR_LOCK;
4560 }else if( lock.l_type==F_UNLCK ){
4561 if( pShmNode->isReadonly ){
4562 pShmNode->isUnlocked = 1;
4563 rc = SQLITE_READONLY_CANTINIT;
4564 }else{
4565 rc = unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1);
4566 /* The first connection to attach must truncate the -shm file. We
4567 ** truncate to 3 bytes (an arbitrary small number, less than the
4568 ** -shm header size) rather than 0 as a system debugging aid, to
4569 ** help detect if a -shm file truncation is legitimate or is the work
4570 ** or a rogue process. */
4571 if( rc==SQLITE_OK && robust_ftruncate(pShmNode->hShm, 3) ){
4572 rc = unixLogError(SQLITE_IOERR_SHMOPEN,"ftruncate",pShmNode->zFilename);
4575 }else if( lock.l_type==F_WRLCK ){
4576 rc = SQLITE_BUSY;
4579 if( rc==SQLITE_OK ){
4580 assert( lock.l_type==F_UNLCK || lock.l_type==F_RDLCK );
4581 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
4583 return rc;
4587 ** Open a shared-memory area associated with open database file pDbFd.
4588 ** This particular implementation uses mmapped files.
4590 ** The file used to implement shared-memory is in the same directory
4591 ** as the open database file and has the same name as the open database
4592 ** file with the "-shm" suffix added. For example, if the database file
4593 ** is "/home/user1/config.db" then the file that is created and mmapped
4594 ** for shared memory will be called "/home/user1/config.db-shm".
4596 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
4597 ** some other tmpfs mount. But if a file in a different directory
4598 ** from the database file is used, then differing access permissions
4599 ** or a chroot() might cause two different processes on the same
4600 ** database to end up using different files for shared memory -
4601 ** meaning that their memory would not really be shared - resulting
4602 ** in database corruption. Nevertheless, this tmpfs file usage
4603 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4604 ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4605 ** option results in an incompatible build of SQLite; builds of SQLite
4606 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4607 ** same database file at the same time, database corruption will likely
4608 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4609 ** "unsupported" and may go away in a future SQLite release.
4611 ** When opening a new shared-memory file, if no other instances of that
4612 ** file are currently open, in this process or in other processes, then
4613 ** the file must be truncated to zero length or have its header cleared.
4615 ** If the original database file (pDbFd) is using the "unix-excl" VFS
4616 ** that means that an exclusive lock is held on the database file and
4617 ** that no other processes are able to read or write the database. In
4618 ** that case, we do not really need shared memory. No shared memory
4619 ** file is created. The shared memory will be simulated with heap memory.
4621 static int unixOpenSharedMemory(unixFile *pDbFd){
4622 struct unixShm *p = 0; /* The connection to be opened */
4623 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4624 int rc = SQLITE_OK; /* Result code */
4625 unixInodeInfo *pInode; /* The inode of fd */
4626 char *zShm; /* Name of the file used for SHM */
4627 int nShmFilename; /* Size of the SHM filename in bytes */
4629 /* Allocate space for the new unixShm object. */
4630 p = sqlite3_malloc64( sizeof(*p) );
4631 if( p==0 ) return SQLITE_NOMEM_BKPT;
4632 memset(p, 0, sizeof(*p));
4633 assert( pDbFd->pShm==0 );
4635 /* Check to see if a unixShmNode object already exists. Reuse an existing
4636 ** one if present. Create a new one if necessary.
4638 assert( unixFileMutexNotheld(pDbFd) );
4639 unixEnterMutex();
4640 pInode = pDbFd->pInode;
4641 pShmNode = pInode->pShmNode;
4642 if( pShmNode==0 ){
4643 struct stat sStat; /* fstat() info for database file */
4644 #ifndef SQLITE_SHM_DIRECTORY
4645 const char *zBasePath = pDbFd->zPath;
4646 #endif
4648 /* Call fstat() to figure out the permissions on the database file. If
4649 ** a new *-shm file is created, an attempt will be made to create it
4650 ** with the same permissions.
4652 if( osFstat(pDbFd->h, &sStat) ){
4653 rc = SQLITE_IOERR_FSTAT;
4654 goto shm_open_err;
4657 #ifdef SQLITE_SHM_DIRECTORY
4658 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
4659 #else
4660 nShmFilename = 6 + (int)strlen(zBasePath);
4661 #endif
4662 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
4663 if( pShmNode==0 ){
4664 rc = SQLITE_NOMEM_BKPT;
4665 goto shm_open_err;
4667 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
4668 zShm = pShmNode->zFilename = (char*)&pShmNode[1];
4669 #ifdef SQLITE_SHM_DIRECTORY
4670 sqlite3_snprintf(nShmFilename, zShm,
4671 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4672 (u32)sStat.st_ino, (u32)sStat.st_dev);
4673 #else
4674 sqlite3_snprintf(nShmFilename, zShm, "%s-shm", zBasePath);
4675 sqlite3FileSuffix3(pDbFd->zPath, zShm);
4676 #endif
4677 pShmNode->hShm = -1;
4678 pDbFd->pInode->pShmNode = pShmNode;
4679 pShmNode->pInode = pDbFd->pInode;
4680 if( sqlite3GlobalConfig.bCoreMutex ){
4681 pShmNode->pShmMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4682 if( pShmNode->pShmMutex==0 ){
4683 rc = SQLITE_NOMEM_BKPT;
4684 goto shm_open_err;
4688 if( pInode->bProcessLock==0 ){
4689 if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
4690 pShmNode->hShm = robust_open(zShm, O_RDWR|O_CREAT|O_NOFOLLOW,
4691 (sStat.st_mode&0777));
4693 if( pShmNode->hShm<0 ){
4694 pShmNode->hShm = robust_open(zShm, O_RDONLY|O_NOFOLLOW,
4695 (sStat.st_mode&0777));
4696 if( pShmNode->hShm<0 ){
4697 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShm);
4698 goto shm_open_err;
4700 pShmNode->isReadonly = 1;
4703 /* If this process is running as root, make sure that the SHM file
4704 ** is owned by the same user that owns the original database. Otherwise,
4705 ** the original owner will not be able to connect.
4707 robustFchown(pShmNode->hShm, sStat.st_uid, sStat.st_gid);
4709 rc = unixLockSharedMemory(pDbFd, pShmNode);
4710 if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
4714 /* Make the new connection a child of the unixShmNode */
4715 p->pShmNode = pShmNode;
4716 #ifdef SQLITE_DEBUG
4717 p->id = pShmNode->nextShmId++;
4718 #endif
4719 pShmNode->nRef++;
4720 pDbFd->pShm = p;
4721 unixLeaveMutex();
4723 /* The reference count on pShmNode has already been incremented under
4724 ** the cover of the unixEnterMutex() mutex and the pointer from the
4725 ** new (struct unixShm) object to the pShmNode has been set. All that is
4726 ** left to do is to link the new object into the linked list starting
4727 ** at pShmNode->pFirst. This must be done while holding the
4728 ** pShmNode->pShmMutex.
4730 sqlite3_mutex_enter(pShmNode->pShmMutex);
4731 p->pNext = pShmNode->pFirst;
4732 pShmNode->pFirst = p;
4733 sqlite3_mutex_leave(pShmNode->pShmMutex);
4734 return rc;
4736 /* Jump here on any error */
4737 shm_open_err:
4738 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
4739 sqlite3_free(p);
4740 unixLeaveMutex();
4741 return rc;
4745 ** This function is called to obtain a pointer to region iRegion of the
4746 ** shared-memory associated with the database file fd. Shared-memory regions
4747 ** are numbered starting from zero. Each shared-memory region is szRegion
4748 ** bytes in size.
4750 ** If an error occurs, an error code is returned and *pp is set to NULL.
4752 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4753 ** region has not been allocated (by any client, including one running in a
4754 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4755 ** bExtend is non-zero and the requested shared-memory region has not yet
4756 ** been allocated, it is allocated by this function.
4758 ** If the shared-memory region has already been allocated or is allocated by
4759 ** this call as described above, then it is mapped into this processes
4760 ** address space (if it is not already), *pp is set to point to the mapped
4761 ** memory and SQLITE_OK returned.
4763 static int unixShmMap(
4764 sqlite3_file *fd, /* Handle open on database file */
4765 int iRegion, /* Region to retrieve */
4766 int szRegion, /* Size of regions */
4767 int bExtend, /* True to extend file if necessary */
4768 void volatile **pp /* OUT: Mapped memory */
4770 unixFile *pDbFd = (unixFile*)fd;
4771 unixShm *p;
4772 unixShmNode *pShmNode;
4773 int rc = SQLITE_OK;
4774 int nShmPerMap = unixShmRegionPerMap();
4775 int nReqRegion;
4777 /* If the shared-memory file has not yet been opened, open it now. */
4778 if( pDbFd->pShm==0 ){
4779 rc = unixOpenSharedMemory(pDbFd);
4780 if( rc!=SQLITE_OK ) return rc;
4783 p = pDbFd->pShm;
4784 pShmNode = p->pShmNode;
4785 sqlite3_mutex_enter(pShmNode->pShmMutex);
4786 if( pShmNode->isUnlocked ){
4787 rc = unixLockSharedMemory(pDbFd, pShmNode);
4788 if( rc!=SQLITE_OK ) goto shmpage_out;
4789 pShmNode->isUnlocked = 0;
4791 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
4792 assert( pShmNode->pInode==pDbFd->pInode );
4793 assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );
4794 assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );
4796 /* Minimum number of regions required to be mapped. */
4797 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4799 if( pShmNode->nRegion<nReqRegion ){
4800 char **apNew; /* New apRegion[] array */
4801 int nByte = nReqRegion*szRegion; /* Minimum required file size */
4802 struct stat sStat; /* Used by fstat() */
4804 pShmNode->szRegion = szRegion;
4806 if( pShmNode->hShm>=0 ){
4807 /* The requested region is not mapped into this processes address space.
4808 ** Check to see if it has been allocated (i.e. if the wal-index file is
4809 ** large enough to contain the requested region).
4811 if( osFstat(pShmNode->hShm, &sStat) ){
4812 rc = SQLITE_IOERR_SHMSIZE;
4813 goto shmpage_out;
4816 if( sStat.st_size<nByte ){
4817 /* The requested memory region does not exist. If bExtend is set to
4818 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
4820 if( !bExtend ){
4821 goto shmpage_out;
4824 /* Alternatively, if bExtend is true, extend the file. Do this by
4825 ** writing a single byte to the end of each (OS) page being
4826 ** allocated or extended. Technically, we need only write to the
4827 ** last page in order to extend the file. But writing to all new
4828 ** pages forces the OS to allocate them immediately, which reduces
4829 ** the chances of SIGBUS while accessing the mapped region later on.
4831 else{
4832 static const int pgsz = 4096;
4833 int iPg;
4835 /* Write to the last byte of each newly allocated or extended page */
4836 assert( (nByte % pgsz)==0 );
4837 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
4838 int x = 0;
4839 if( seekAndWriteFd(pShmNode->hShm, iPg*pgsz + pgsz-1,"",1,&x)!=1 ){
4840 const char *zFile = pShmNode->zFilename;
4841 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4842 goto shmpage_out;
4849 /* Map the requested memory region into this processes address space. */
4850 apNew = (char **)sqlite3_realloc(
4851 pShmNode->apRegion, nReqRegion*sizeof(char *)
4853 if( !apNew ){
4854 rc = SQLITE_IOERR_NOMEM_BKPT;
4855 goto shmpage_out;
4857 pShmNode->apRegion = apNew;
4858 while( pShmNode->nRegion<nReqRegion ){
4859 int nMap = szRegion*nShmPerMap;
4860 int i;
4861 void *pMem;
4862 if( pShmNode->hShm>=0 ){
4863 pMem = osMmap(0, nMap,
4864 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
4865 MAP_SHARED, pShmNode->hShm, szRegion*(i64)pShmNode->nRegion
4867 if( pMem==MAP_FAILED ){
4868 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
4869 goto shmpage_out;
4871 }else{
4872 pMem = sqlite3_malloc64(nMap);
4873 if( pMem==0 ){
4874 rc = SQLITE_NOMEM_BKPT;
4875 goto shmpage_out;
4877 memset(pMem, 0, nMap);
4880 for(i=0; i<nShmPerMap; i++){
4881 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4883 pShmNode->nRegion += nShmPerMap;
4887 shmpage_out:
4888 if( pShmNode->nRegion>iRegion ){
4889 *pp = pShmNode->apRegion[iRegion];
4890 }else{
4891 *pp = 0;
4893 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
4894 sqlite3_mutex_leave(pShmNode->pShmMutex);
4895 return rc;
4899 ** Check that the pShmNode->aLock[] array comports with the locking bitmasks
4900 ** held by each client. Return true if it does, or false otherwise. This
4901 ** is to be used in an assert(). e.g.
4903 ** assert( assertLockingArrayOk(pShmNode) );
4905 #ifdef SQLITE_DEBUG
4906 static int assertLockingArrayOk(unixShmNode *pShmNode){
4907 unixShm *pX;
4908 int aLock[SQLITE_SHM_NLOCK];
4909 assert( sqlite3_mutex_held(pShmNode->pShmMutex) );
4911 memset(aLock, 0, sizeof(aLock));
4912 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4913 int i;
4914 for(i=0; i<SQLITE_SHM_NLOCK; i++){
4915 if( pX->exclMask & (1<<i) ){
4916 assert( aLock[i]==0 );
4917 aLock[i] = -1;
4918 }else if( pX->sharedMask & (1<<i) ){
4919 assert( aLock[i]>=0 );
4920 aLock[i]++;
4925 assert( 0==memcmp(pShmNode->aLock, aLock, sizeof(aLock)) );
4926 return (memcmp(pShmNode->aLock, aLock, sizeof(aLock))==0);
4928 #endif
4931 ** Change the lock state for a shared-memory segment.
4933 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4934 ** different here than in posix. In xShmLock(), one can go from unlocked
4935 ** to shared and back or from unlocked to exclusive and back. But one may
4936 ** not go from shared to exclusive or from exclusive to shared.
4938 static int unixShmLock(
4939 sqlite3_file *fd, /* Database file holding the shared memory */
4940 int ofst, /* First lock to acquire or release */
4941 int n, /* Number of locks to acquire or release */
4942 int flags /* What to do with the lock */
4944 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4945 unixShm *p; /* The shared memory being locked */
4946 unixShmNode *pShmNode; /* The underlying file iNode */
4947 int rc = SQLITE_OK; /* Result code */
4948 u16 mask; /* Mask of locks to take or release */
4949 int *aLock;
4951 p = pDbFd->pShm;
4952 if( p==0 ) return SQLITE_IOERR_SHMLOCK;
4953 pShmNode = p->pShmNode;
4954 if( NEVER(pShmNode==0) ) return SQLITE_IOERR_SHMLOCK;
4955 aLock = pShmNode->aLock;
4957 assert( pShmNode==pDbFd->pInode->pShmNode );
4958 assert( pShmNode->pInode==pDbFd->pInode );
4959 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
4960 assert( n>=1 );
4961 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4962 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4963 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4964 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4965 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
4966 assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );
4967 assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );
4969 /* Check that, if this to be a blocking lock, no locks that occur later
4970 ** in the following list than the lock being obtained are already held:
4972 ** 1. Checkpointer lock (ofst==1).
4973 ** 2. Write lock (ofst==0).
4974 ** 3. Read locks (ofst>=3 && ofst<SQLITE_SHM_NLOCK).
4976 ** In other words, if this is a blocking lock, none of the locks that
4977 ** occur later in the above list than the lock being obtained may be
4978 ** held.
4980 ** It is not permitted to block on the RECOVER lock.
4982 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
4983 assert( (flags & SQLITE_SHM_UNLOCK) || pDbFd->iBusyTimeout==0 || (
4984 (ofst!=2) /* not RECOVER */
4985 && (ofst!=1 || (p->exclMask|p->sharedMask)==0)
4986 && (ofst!=0 || (p->exclMask|p->sharedMask)<3)
4987 && (ofst<3 || (p->exclMask|p->sharedMask)<(1<<ofst))
4989 #endif
4991 mask = (1<<(ofst+n)) - (1<<ofst);
4992 assert( n>1 || mask==(1<<ofst) );
4993 sqlite3_mutex_enter(pShmNode->pShmMutex);
4994 assert( assertLockingArrayOk(pShmNode) );
4995 if( flags & SQLITE_SHM_UNLOCK ){
4996 if( (p->exclMask|p->sharedMask) & mask ){
4997 int ii;
4998 int bUnlock = 1;
5000 for(ii=ofst; ii<ofst+n; ii++){
5001 if( aLock[ii]>((p->sharedMask & (1<<ii)) ? 1 : 0) ){
5002 bUnlock = 0;
5006 if( bUnlock ){
5007 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
5008 if( rc==SQLITE_OK ){
5009 memset(&aLock[ofst], 0, sizeof(int)*n);
5011 }else if( ALWAYS(p->sharedMask & (1<<ofst)) ){
5012 assert( n==1 && aLock[ofst]>1 );
5013 aLock[ofst]--;
5016 /* Undo the local locks */
5017 if( rc==SQLITE_OK ){
5018 p->exclMask &= ~mask;
5019 p->sharedMask &= ~mask;
5022 }else if( flags & SQLITE_SHM_SHARED ){
5023 assert( n==1 );
5024 assert( (p->exclMask & (1<<ofst))==0 );
5025 if( (p->sharedMask & mask)==0 ){
5026 if( aLock[ofst]<0 ){
5027 rc = SQLITE_BUSY;
5028 }else if( aLock[ofst]==0 ){
5029 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
5032 /* Get the local shared locks */
5033 if( rc==SQLITE_OK ){
5034 p->sharedMask |= mask;
5035 aLock[ofst]++;
5038 }else{
5039 /* Make sure no sibling connections hold locks that will block this
5040 ** lock. If any do, return SQLITE_BUSY right away. */
5041 int ii;
5042 for(ii=ofst; ii<ofst+n; ii++){
5043 assert( (p->sharedMask & mask)==0 );
5044 if( ALWAYS((p->exclMask & (1<<ii))==0) && aLock[ii] ){
5045 rc = SQLITE_BUSY;
5046 break;
5050 /* Get the exclusive locks at the system level. Then if successful
5051 ** also update the in-memory values. */
5052 if( rc==SQLITE_OK ){
5053 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
5054 if( rc==SQLITE_OK ){
5055 assert( (p->sharedMask & mask)==0 );
5056 p->exclMask |= mask;
5057 for(ii=ofst; ii<ofst+n; ii++){
5058 aLock[ii] = -1;
5063 assert( assertLockingArrayOk(pShmNode) );
5064 sqlite3_mutex_leave(pShmNode->pShmMutex);
5065 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
5066 p->id, osGetpid(0), p->sharedMask, p->exclMask));
5067 return rc;
5071 ** Implement a memory barrier or memory fence on shared memory.
5073 ** All loads and stores begun before the barrier must complete before
5074 ** any load or store begun after the barrier.
5076 static void unixShmBarrier(
5077 sqlite3_file *fd /* Database file holding the shared memory */
5079 UNUSED_PARAMETER(fd);
5080 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
5081 assert( fd->pMethods->xLock==nolockLock
5082 || unixFileMutexNotheld((unixFile*)fd)
5084 unixEnterMutex(); /* Also mutex, for redundancy */
5085 unixLeaveMutex();
5089 ** Close a connection to shared-memory. Delete the underlying
5090 ** storage if deleteFlag is true.
5092 ** If there is no shared memory associated with the connection then this
5093 ** routine is a harmless no-op.
5095 static int unixShmUnmap(
5096 sqlite3_file *fd, /* The underlying database file */
5097 int deleteFlag /* Delete shared-memory if true */
5099 unixShm *p; /* The connection to be closed */
5100 unixShmNode *pShmNode; /* The underlying shared-memory file */
5101 unixShm **pp; /* For looping over sibling connections */
5102 unixFile *pDbFd; /* The underlying database file */
5104 pDbFd = (unixFile*)fd;
5105 p = pDbFd->pShm;
5106 if( p==0 ) return SQLITE_OK;
5107 pShmNode = p->pShmNode;
5109 assert( pShmNode==pDbFd->pInode->pShmNode );
5110 assert( pShmNode->pInode==pDbFd->pInode );
5112 /* Remove connection p from the set of connections associated
5113 ** with pShmNode */
5114 sqlite3_mutex_enter(pShmNode->pShmMutex);
5115 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
5116 *pp = p->pNext;
5118 /* Free the connection p */
5119 sqlite3_free(p);
5120 pDbFd->pShm = 0;
5121 sqlite3_mutex_leave(pShmNode->pShmMutex);
5123 /* If pShmNode->nRef has reached 0, then close the underlying
5124 ** shared-memory file, too */
5125 assert( unixFileMutexNotheld(pDbFd) );
5126 unixEnterMutex();
5127 assert( pShmNode->nRef>0 );
5128 pShmNode->nRef--;
5129 if( pShmNode->nRef==0 ){
5130 if( deleteFlag && pShmNode->hShm>=0 ){
5131 osUnlink(pShmNode->zFilename);
5133 unixShmPurge(pDbFd);
5135 unixLeaveMutex();
5137 return SQLITE_OK;
5141 #else
5142 # define unixShmMap 0
5143 # define unixShmLock 0
5144 # define unixShmBarrier 0
5145 # define unixShmUnmap 0
5146 #endif /* #ifndef SQLITE_OMIT_WAL */
5148 #if SQLITE_MAX_MMAP_SIZE>0
5150 ** If it is currently memory mapped, unmap file pFd.
5152 static void unixUnmapfile(unixFile *pFd){
5153 assert( pFd->nFetchOut==0 );
5154 if( pFd->pMapRegion ){
5155 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
5156 pFd->pMapRegion = 0;
5157 pFd->mmapSize = 0;
5158 pFd->mmapSizeActual = 0;
5163 ** Attempt to set the size of the memory mapping maintained by file
5164 ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
5166 ** If successful, this function sets the following variables:
5168 ** unixFile.pMapRegion
5169 ** unixFile.mmapSize
5170 ** unixFile.mmapSizeActual
5172 ** If unsuccessful, an error message is logged via sqlite3_log() and
5173 ** the three variables above are zeroed. In this case SQLite should
5174 ** continue accessing the database using the xRead() and xWrite()
5175 ** methods.
5177 static void unixRemapfile(
5178 unixFile *pFd, /* File descriptor object */
5179 i64 nNew /* Required mapping size */
5181 const char *zErr = "mmap";
5182 int h = pFd->h; /* File descriptor open on db file */
5183 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
5184 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
5185 u8 *pNew = 0; /* Location of new mapping */
5186 int flags = PROT_READ; /* Flags to pass to mmap() */
5188 assert( pFd->nFetchOut==0 );
5189 assert( nNew>pFd->mmapSize );
5190 assert( nNew<=pFd->mmapSizeMax );
5191 assert( nNew>0 );
5192 assert( pFd->mmapSizeActual>=pFd->mmapSize );
5193 assert( MAP_FAILED!=0 );
5195 #ifdef SQLITE_MMAP_READWRITE
5196 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
5197 #endif
5199 if( pOrig ){
5200 #if HAVE_MREMAP
5201 i64 nReuse = pFd->mmapSize;
5202 #else
5203 const int szSyspage = osGetpagesize();
5204 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
5205 #endif
5206 u8 *pReq = &pOrig[nReuse];
5208 /* Unmap any pages of the existing mapping that cannot be reused. */
5209 if( nReuse!=nOrig ){
5210 osMunmap(pReq, nOrig-nReuse);
5213 #if HAVE_MREMAP
5214 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
5215 zErr = "mremap";
5216 #else
5217 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
5218 if( pNew!=MAP_FAILED ){
5219 if( pNew!=pReq ){
5220 osMunmap(pNew, nNew - nReuse);
5221 pNew = 0;
5222 }else{
5223 pNew = pOrig;
5226 #endif
5228 /* The attempt to extend the existing mapping failed. Free it. */
5229 if( pNew==MAP_FAILED || pNew==0 ){
5230 osMunmap(pOrig, nReuse);
5234 /* If pNew is still NULL, try to create an entirely new mapping. */
5235 if( pNew==0 ){
5236 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
5239 if( pNew==MAP_FAILED ){
5240 pNew = 0;
5241 nNew = 0;
5242 unixLogError(SQLITE_OK, zErr, pFd->zPath);
5244 /* If the mmap() above failed, assume that all subsequent mmap() calls
5245 ** will probably fail too. Fall back to using xRead/xWrite exclusively
5246 ** in this case. */
5247 pFd->mmapSizeMax = 0;
5249 pFd->pMapRegion = (void *)pNew;
5250 pFd->mmapSize = pFd->mmapSizeActual = nNew;
5254 ** Memory map or remap the file opened by file-descriptor pFd (if the file
5255 ** is already mapped, the existing mapping is replaced by the new). Or, if
5256 ** there already exists a mapping for this file, and there are still
5257 ** outstanding xFetch() references to it, this function is a no-op.
5259 ** If parameter nByte is non-negative, then it is the requested size of
5260 ** the mapping to create. Otherwise, if nByte is less than zero, then the
5261 ** requested size is the size of the file on disk. The actual size of the
5262 ** created mapping is either the requested size or the value configured
5263 ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
5265 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
5266 ** recreated as a result of outstanding references) or an SQLite error
5267 ** code otherwise.
5269 static int unixMapfile(unixFile *pFd, i64 nMap){
5270 assert( nMap>=0 || pFd->nFetchOut==0 );
5271 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
5272 if( pFd->nFetchOut>0 ) return SQLITE_OK;
5274 if( nMap<0 ){
5275 struct stat statbuf; /* Low-level file information */
5276 if( osFstat(pFd->h, &statbuf) ){
5277 return SQLITE_IOERR_FSTAT;
5279 nMap = statbuf.st_size;
5281 if( nMap>pFd->mmapSizeMax ){
5282 nMap = pFd->mmapSizeMax;
5285 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
5286 if( nMap!=pFd->mmapSize ){
5287 unixRemapfile(pFd, nMap);
5290 return SQLITE_OK;
5292 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
5295 ** If possible, return a pointer to a mapping of file fd starting at offset
5296 ** iOff. The mapping must be valid for at least nAmt bytes.
5298 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
5299 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
5300 ** Finally, if an error does occur, return an SQLite error code. The final
5301 ** value of *pp is undefined in this case.
5303 ** If this function does return a pointer, the caller must eventually
5304 ** release the reference by calling unixUnfetch().
5306 static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
5307 #if SQLITE_MAX_MMAP_SIZE>0
5308 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
5309 #endif
5310 *pp = 0;
5312 #if SQLITE_MAX_MMAP_SIZE>0
5313 if( pFd->mmapSizeMax>0 ){
5314 if( pFd->pMapRegion==0 ){
5315 int rc = unixMapfile(pFd, -1);
5316 if( rc!=SQLITE_OK ) return rc;
5318 if( pFd->mmapSize >= iOff+nAmt ){
5319 *pp = &((u8 *)pFd->pMapRegion)[iOff];
5320 pFd->nFetchOut++;
5323 #endif
5324 return SQLITE_OK;
5328 ** If the third argument is non-NULL, then this function releases a
5329 ** reference obtained by an earlier call to unixFetch(). The second
5330 ** argument passed to this function must be the same as the corresponding
5331 ** argument that was passed to the unixFetch() invocation.
5333 ** Or, if the third argument is NULL, then this function is being called
5334 ** to inform the VFS layer that, according to POSIX, any existing mapping
5335 ** may now be invalid and should be unmapped.
5337 static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
5338 #if SQLITE_MAX_MMAP_SIZE>0
5339 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
5340 UNUSED_PARAMETER(iOff);
5342 /* If p==0 (unmap the entire file) then there must be no outstanding
5343 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
5344 ** then there must be at least one outstanding. */
5345 assert( (p==0)==(pFd->nFetchOut==0) );
5347 /* If p!=0, it must match the iOff value. */
5348 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
5350 if( p ){
5351 pFd->nFetchOut--;
5352 }else{
5353 unixUnmapfile(pFd);
5356 assert( pFd->nFetchOut>=0 );
5357 #else
5358 UNUSED_PARAMETER(fd);
5359 UNUSED_PARAMETER(p);
5360 UNUSED_PARAMETER(iOff);
5361 #endif
5362 return SQLITE_OK;
5366 ** Here ends the implementation of all sqlite3_file methods.
5368 ********************** End sqlite3_file Methods *******************************
5369 ******************************************************************************/
5372 ** This division contains definitions of sqlite3_io_methods objects that
5373 ** implement various file locking strategies. It also contains definitions
5374 ** of "finder" functions. A finder-function is used to locate the appropriate
5375 ** sqlite3_io_methods object for a particular database file. The pAppData
5376 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
5377 ** the correct finder-function for that VFS.
5379 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
5380 ** object. The only interesting finder-function is autolockIoFinder, which
5381 ** looks at the filesystem type and tries to guess the best locking
5382 ** strategy from that.
5384 ** For finder-function F, two objects are created:
5386 ** (1) The real finder-function named "FImpt()".
5388 ** (2) A constant pointer to this function named just "F".
5391 ** A pointer to the F pointer is used as the pAppData value for VFS
5392 ** objects. We have to do this instead of letting pAppData point
5393 ** directly at the finder-function since C90 rules prevent a void*
5394 ** from be cast into a function pointer.
5397 ** Each instance of this macro generates two objects:
5399 ** * A constant sqlite3_io_methods object call METHOD that has locking
5400 ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
5402 ** * An I/O method finder function called FINDER that returns a pointer
5403 ** to the METHOD object in the previous bullet.
5405 #define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
5406 static const sqlite3_io_methods METHOD = { \
5407 VERSION, /* iVersion */ \
5408 CLOSE, /* xClose */ \
5409 unixRead, /* xRead */ \
5410 unixWrite, /* xWrite */ \
5411 unixTruncate, /* xTruncate */ \
5412 unixSync, /* xSync */ \
5413 unixFileSize, /* xFileSize */ \
5414 LOCK, /* xLock */ \
5415 UNLOCK, /* xUnlock */ \
5416 CKLOCK, /* xCheckReservedLock */ \
5417 unixFileControl, /* xFileControl */ \
5418 unixSectorSize, /* xSectorSize */ \
5419 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
5420 SHMMAP, /* xShmMap */ \
5421 unixShmLock, /* xShmLock */ \
5422 unixShmBarrier, /* xShmBarrier */ \
5423 unixShmUnmap, /* xShmUnmap */ \
5424 unixFetch, /* xFetch */ \
5425 unixUnfetch, /* xUnfetch */ \
5426 }; \
5427 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
5428 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
5429 return &METHOD; \
5431 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
5432 = FINDER##Impl;
5435 ** Here are all of the sqlite3_io_methods objects for each of the
5436 ** locking strategies. Functions that return pointers to these methods
5437 ** are also created.
5439 IOMETHODS(
5440 posixIoFinder, /* Finder function name */
5441 posixIoMethods, /* sqlite3_io_methods object name */
5442 3, /* shared memory and mmap are enabled */
5443 unixClose, /* xClose method */
5444 unixLock, /* xLock method */
5445 unixUnlock, /* xUnlock method */
5446 unixCheckReservedLock, /* xCheckReservedLock method */
5447 unixShmMap /* xShmMap method */
5449 IOMETHODS(
5450 nolockIoFinder, /* Finder function name */
5451 nolockIoMethods, /* sqlite3_io_methods object name */
5452 3, /* shared memory and mmap are enabled */
5453 nolockClose, /* xClose method */
5454 nolockLock, /* xLock method */
5455 nolockUnlock, /* xUnlock method */
5456 nolockCheckReservedLock, /* xCheckReservedLock method */
5457 0 /* xShmMap method */
5459 IOMETHODS(
5460 dotlockIoFinder, /* Finder function name */
5461 dotlockIoMethods, /* sqlite3_io_methods object name */
5462 1, /* shared memory is disabled */
5463 dotlockClose, /* xClose method */
5464 dotlockLock, /* xLock method */
5465 dotlockUnlock, /* xUnlock method */
5466 dotlockCheckReservedLock, /* xCheckReservedLock method */
5467 0 /* xShmMap method */
5470 #if SQLITE_ENABLE_LOCKING_STYLE
5471 IOMETHODS(
5472 flockIoFinder, /* Finder function name */
5473 flockIoMethods, /* sqlite3_io_methods object name */
5474 1, /* shared memory is disabled */
5475 flockClose, /* xClose method */
5476 flockLock, /* xLock method */
5477 flockUnlock, /* xUnlock method */
5478 flockCheckReservedLock, /* xCheckReservedLock method */
5479 0 /* xShmMap method */
5481 #endif
5483 #if OS_VXWORKS
5484 IOMETHODS(
5485 semIoFinder, /* Finder function name */
5486 semIoMethods, /* sqlite3_io_methods object name */
5487 1, /* shared memory is disabled */
5488 semXClose, /* xClose method */
5489 semXLock, /* xLock method */
5490 semXUnlock, /* xUnlock method */
5491 semXCheckReservedLock, /* xCheckReservedLock method */
5492 0 /* xShmMap method */
5494 #endif
5496 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5497 IOMETHODS(
5498 afpIoFinder, /* Finder function name */
5499 afpIoMethods, /* sqlite3_io_methods object name */
5500 1, /* shared memory is disabled */
5501 afpClose, /* xClose method */
5502 afpLock, /* xLock method */
5503 afpUnlock, /* xUnlock method */
5504 afpCheckReservedLock, /* xCheckReservedLock method */
5505 0 /* xShmMap method */
5507 #endif
5510 ** The proxy locking method is a "super-method" in the sense that it
5511 ** opens secondary file descriptors for the conch and lock files and
5512 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
5513 ** secondary files. For this reason, the division that implements
5514 ** proxy locking is located much further down in the file. But we need
5515 ** to go ahead and define the sqlite3_io_methods and finder function
5516 ** for proxy locking here. So we forward declare the I/O methods.
5518 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5519 static int proxyClose(sqlite3_file*);
5520 static int proxyLock(sqlite3_file*, int);
5521 static int proxyUnlock(sqlite3_file*, int);
5522 static int proxyCheckReservedLock(sqlite3_file*, int*);
5523 IOMETHODS(
5524 proxyIoFinder, /* Finder function name */
5525 proxyIoMethods, /* sqlite3_io_methods object name */
5526 1, /* shared memory is disabled */
5527 proxyClose, /* xClose method */
5528 proxyLock, /* xLock method */
5529 proxyUnlock, /* xUnlock method */
5530 proxyCheckReservedLock, /* xCheckReservedLock method */
5531 0 /* xShmMap method */
5533 #endif
5535 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5536 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5537 IOMETHODS(
5538 nfsIoFinder, /* Finder function name */
5539 nfsIoMethods, /* sqlite3_io_methods object name */
5540 1, /* shared memory is disabled */
5541 unixClose, /* xClose method */
5542 unixLock, /* xLock method */
5543 nfsUnlock, /* xUnlock method */
5544 unixCheckReservedLock, /* xCheckReservedLock method */
5545 0 /* xShmMap method */
5547 #endif
5549 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5551 ** This "finder" function attempts to determine the best locking strategy
5552 ** for the database file "filePath". It then returns the sqlite3_io_methods
5553 ** object that implements that strategy.
5555 ** This is for MacOSX only.
5557 static const sqlite3_io_methods *autolockIoFinderImpl(
5558 const char *filePath, /* name of the database file */
5559 unixFile *pNew /* open file object for the database file */
5561 static const struct Mapping {
5562 const char *zFilesystem; /* Filesystem type name */
5563 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
5564 } aMap[] = {
5565 { "hfs", &posixIoMethods },
5566 { "ufs", &posixIoMethods },
5567 { "afpfs", &afpIoMethods },
5568 { "smbfs", &afpIoMethods },
5569 { "webdav", &nolockIoMethods },
5570 { 0, 0 }
5572 int i;
5573 struct statfs fsInfo;
5574 struct flock lockInfo;
5576 if( !filePath ){
5577 /* If filePath==NULL that means we are dealing with a transient file
5578 ** that does not need to be locked. */
5579 return &nolockIoMethods;
5581 if( statfs(filePath, &fsInfo) != -1 ){
5582 if( fsInfo.f_flags & MNT_RDONLY ){
5583 return &nolockIoMethods;
5585 for(i=0; aMap[i].zFilesystem; i++){
5586 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5587 return aMap[i].pMethods;
5592 /* Default case. Handles, amongst others, "nfs".
5593 ** Test byte-range lock using fcntl(). If the call succeeds,
5594 ** assume that the file-system supports POSIX style locks.
5596 lockInfo.l_len = 1;
5597 lockInfo.l_start = 0;
5598 lockInfo.l_whence = SEEK_SET;
5599 lockInfo.l_type = F_RDLCK;
5600 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
5601 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5602 return &nfsIoMethods;
5603 } else {
5604 return &posixIoMethods;
5606 }else{
5607 return &dotlockIoMethods;
5610 static const sqlite3_io_methods
5611 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
5613 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
5615 #if OS_VXWORKS
5617 ** This "finder" function for VxWorks checks to see if posix advisory
5618 ** locking works. If it does, then that is what is used. If it does not
5619 ** work, then fallback to named semaphore locking.
5621 static const sqlite3_io_methods *vxworksIoFinderImpl(
5622 const char *filePath, /* name of the database file */
5623 unixFile *pNew /* the open file object */
5625 struct flock lockInfo;
5627 if( !filePath ){
5628 /* If filePath==NULL that means we are dealing with a transient file
5629 ** that does not need to be locked. */
5630 return &nolockIoMethods;
5633 /* Test if fcntl() is supported and use POSIX style locks.
5634 ** Otherwise fall back to the named semaphore method.
5636 lockInfo.l_len = 1;
5637 lockInfo.l_start = 0;
5638 lockInfo.l_whence = SEEK_SET;
5639 lockInfo.l_type = F_RDLCK;
5640 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
5641 return &posixIoMethods;
5642 }else{
5643 return &semIoMethods;
5646 static const sqlite3_io_methods
5647 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
5649 #endif /* OS_VXWORKS */
5652 ** An abstract type for a pointer to an IO method finder function:
5654 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
5657 /****************************************************************************
5658 **************************** sqlite3_vfs methods ****************************
5660 ** This division contains the implementation of methods on the
5661 ** sqlite3_vfs object.
5665 ** Initialize the contents of the unixFile structure pointed to by pId.
5667 static int fillInUnixFile(
5668 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5669 int h, /* Open file descriptor of file being opened */
5670 sqlite3_file *pId, /* Write to the unixFile structure here */
5671 const char *zFilename, /* Name of the file being opened */
5672 int ctrlFlags /* Zero or more UNIXFILE_* values */
5674 const sqlite3_io_methods *pLockingStyle;
5675 unixFile *pNew = (unixFile *)pId;
5676 int rc = SQLITE_OK;
5678 assert( pNew->pInode==NULL );
5680 /* No locking occurs in temporary files */
5681 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
5683 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
5684 pNew->h = h;
5685 pNew->pVfs = pVfs;
5686 pNew->zPath = zFilename;
5687 pNew->ctrlFlags = (u8)ctrlFlags;
5688 #if SQLITE_MAX_MMAP_SIZE>0
5689 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
5690 #endif
5691 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5692 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
5693 pNew->ctrlFlags |= UNIXFILE_PSOW;
5695 if( strcmp(pVfs->zName,"unix-excl")==0 ){
5696 pNew->ctrlFlags |= UNIXFILE_EXCL;
5699 #if OS_VXWORKS
5700 pNew->pId = vxworksFindFileId(zFilename);
5701 if( pNew->pId==0 ){
5702 ctrlFlags |= UNIXFILE_NOLOCK;
5703 rc = SQLITE_NOMEM_BKPT;
5705 #endif
5707 if( ctrlFlags & UNIXFILE_NOLOCK ){
5708 pLockingStyle = &nolockIoMethods;
5709 }else{
5710 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
5711 #if SQLITE_ENABLE_LOCKING_STYLE
5712 /* Cache zFilename in the locking context (AFP and dotlock override) for
5713 ** proxyLock activation is possible (remote proxy is based on db name)
5714 ** zFilename remains valid until file is closed, to support */
5715 pNew->lockingContext = (void*)zFilename;
5716 #endif
5719 if( pLockingStyle == &posixIoMethods
5720 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5721 || pLockingStyle == &nfsIoMethods
5722 #endif
5724 unixEnterMutex();
5725 rc = findInodeInfo(pNew, &pNew->pInode);
5726 if( rc!=SQLITE_OK ){
5727 /* If an error occurred in findInodeInfo(), close the file descriptor
5728 ** immediately, before releasing the mutex. findInodeInfo() may fail
5729 ** in two scenarios:
5731 ** (a) A call to fstat() failed.
5732 ** (b) A malloc failed.
5734 ** Scenario (b) may only occur if the process is holding no other
5735 ** file descriptors open on the same file. If there were other file
5736 ** descriptors on this file, then no malloc would be required by
5737 ** findInodeInfo(). If this is the case, it is quite safe to close
5738 ** handle h - as it is guaranteed that no posix locks will be released
5739 ** by doing so.
5741 ** If scenario (a) caused the error then things are not so safe. The
5742 ** implicit assumption here is that if fstat() fails, things are in
5743 ** such bad shape that dropping a lock or two doesn't matter much.
5745 robust_close(pNew, h, __LINE__);
5746 h = -1;
5748 unixLeaveMutex();
5751 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
5752 else if( pLockingStyle == &afpIoMethods ){
5753 /* AFP locking uses the file path so it needs to be included in
5754 ** the afpLockingContext.
5756 afpLockingContext *pCtx;
5757 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
5758 if( pCtx==0 ){
5759 rc = SQLITE_NOMEM_BKPT;
5760 }else{
5761 /* NB: zFilename exists and remains valid until the file is closed
5762 ** according to requirement F11141. So we do not need to make a
5763 ** copy of the filename. */
5764 pCtx->dbPath = zFilename;
5765 pCtx->reserved = 0;
5766 srandomdev();
5767 unixEnterMutex();
5768 rc = findInodeInfo(pNew, &pNew->pInode);
5769 if( rc!=SQLITE_OK ){
5770 sqlite3_free(pNew->lockingContext);
5771 robust_close(pNew, h, __LINE__);
5772 h = -1;
5774 unixLeaveMutex();
5777 #endif
5779 else if( pLockingStyle == &dotlockIoMethods ){
5780 /* Dotfile locking uses the file path so it needs to be included in
5781 ** the dotlockLockingContext
5783 char *zLockFile;
5784 int nFilename;
5785 assert( zFilename!=0 );
5786 nFilename = (int)strlen(zFilename) + 6;
5787 zLockFile = (char *)sqlite3_malloc64(nFilename);
5788 if( zLockFile==0 ){
5789 rc = SQLITE_NOMEM_BKPT;
5790 }else{
5791 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
5793 pNew->lockingContext = zLockFile;
5796 #if OS_VXWORKS
5797 else if( pLockingStyle == &semIoMethods ){
5798 /* Named semaphore locking uses the file path so it needs to be
5799 ** included in the semLockingContext
5801 unixEnterMutex();
5802 rc = findInodeInfo(pNew, &pNew->pInode);
5803 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5804 char *zSemName = pNew->pInode->aSemName;
5805 int n;
5806 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
5807 pNew->pId->zCanonicalName);
5808 for( n=1; zSemName[n]; n++ )
5809 if( zSemName[n]=='/' ) zSemName[n] = '_';
5810 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5811 if( pNew->pInode->pSem == SEM_FAILED ){
5812 rc = SQLITE_NOMEM_BKPT;
5813 pNew->pInode->aSemName[0] = '\0';
5816 unixLeaveMutex();
5818 #endif
5820 storeLastErrno(pNew, 0);
5821 #if OS_VXWORKS
5822 if( rc!=SQLITE_OK ){
5823 if( h>=0 ) robust_close(pNew, h, __LINE__);
5824 h = -1;
5825 osUnlink(zFilename);
5826 pNew->ctrlFlags |= UNIXFILE_DELETE;
5828 #endif
5829 if( rc!=SQLITE_OK ){
5830 if( h>=0 ) robust_close(pNew, h, __LINE__);
5831 }else{
5832 pId->pMethods = pLockingStyle;
5833 OpenCounter(+1);
5834 verifyDbFile(pNew);
5836 return rc;
5840 ** Directories to consider for temp files.
5842 static const char *azTempDirs[] = {
5845 "/var/tmp",
5846 "/usr/tmp",
5847 "/tmp",
5852 ** Initialize first two members of azTempDirs[] array.
5854 static void unixTempFileInit(void){
5855 azTempDirs[0] = getenv("SQLITE_TMPDIR");
5856 azTempDirs[1] = getenv("TMPDIR");
5860 ** Return the name of a directory in which to put temporary files.
5861 ** If no suitable temporary file directory can be found, return NULL.
5863 static const char *unixTempFileDir(void){
5864 unsigned int i = 0;
5865 struct stat buf;
5866 const char *zDir = sqlite3_temp_directory;
5868 while(1){
5869 if( zDir!=0
5870 && osStat(zDir, &buf)==0
5871 && S_ISDIR(buf.st_mode)
5872 && osAccess(zDir, 03)==0
5874 return zDir;
5876 if( i>=sizeof(azTempDirs)/sizeof(azTempDirs[0]) ) break;
5877 zDir = azTempDirs[i++];
5879 return 0;
5883 ** Create a temporary file name in zBuf. zBuf must be allocated
5884 ** by the calling process and must be big enough to hold at least
5885 ** pVfs->mxPathname bytes.
5887 static int unixGetTempname(int nBuf, char *zBuf){
5888 const char *zDir;
5889 int iLimit = 0;
5890 int rc = SQLITE_OK;
5892 /* It's odd to simulate an io-error here, but really this is just
5893 ** using the io-error infrastructure to test that SQLite handles this
5894 ** function failing.
5896 zBuf[0] = 0;
5897 SimulateIOError( return SQLITE_IOERR );
5899 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
5900 zDir = unixTempFileDir();
5901 if( zDir==0 ){
5902 rc = SQLITE_IOERR_GETTEMPPATH;
5903 }else{
5905 u64 r;
5906 sqlite3_randomness(sizeof(r), &r);
5907 assert( nBuf>2 );
5908 zBuf[nBuf-2] = 0;
5909 sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
5910 zDir, r, 0);
5911 if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ){
5912 rc = SQLITE_ERROR;
5913 break;
5915 }while( osAccess(zBuf,0)==0 );
5917 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
5918 return rc;
5921 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
5923 ** Routine to transform a unixFile into a proxy-locking unixFile.
5924 ** Implementation in the proxy-lock division, but used by unixOpen()
5925 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
5927 static int proxyTransformUnixFile(unixFile*, const char*);
5928 #endif
5931 ** Search for an unused file descriptor that was opened on the database
5932 ** file (not a journal or super-journal file) identified by pathname
5933 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5934 ** argument to this function.
5936 ** Such a file descriptor may exist if a database connection was closed
5937 ** but the associated file descriptor could not be closed because some
5938 ** other file descriptor open on the same file is holding a file-lock.
5939 ** Refer to comments in the unixClose() function and the lengthy comment
5940 ** describing "Posix Advisory Locking" at the start of this file for
5941 ** further details. Also, ticket #4018.
5943 ** If a suitable file descriptor is found, then it is returned. If no
5944 ** such file descriptor is located, -1 is returned.
5946 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5947 UnixUnusedFd *pUnused = 0;
5949 /* Do not search for an unused file descriptor on vxworks. Not because
5950 ** vxworks would not benefit from the change (it might, we're not sure),
5951 ** but because no way to test it is currently available. It is better
5952 ** not to risk breaking vxworks support for the sake of such an obscure
5953 ** feature. */
5954 #if !OS_VXWORKS
5955 struct stat sStat; /* Results of stat() call */
5957 unixEnterMutex();
5959 /* A stat() call may fail for various reasons. If this happens, it is
5960 ** almost certain that an open() call on the same path will also fail.
5961 ** For this reason, if an error occurs in the stat() call here, it is
5962 ** ignored and -1 is returned. The caller will try to open a new file
5963 ** descriptor on the same path, fail, and return an error to SQLite.
5965 ** Even if a subsequent open() call does succeed, the consequences of
5966 ** not searching for a reusable file descriptor are not dire. */
5967 if( inodeList!=0 && 0==osStat(zPath, &sStat) ){
5968 unixInodeInfo *pInode;
5970 pInode = inodeList;
5971 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5972 || pInode->fileId.ino!=(u64)sStat.st_ino) ){
5973 pInode = pInode->pNext;
5975 if( pInode ){
5976 UnixUnusedFd **pp;
5977 assert( sqlite3_mutex_notheld(pInode->pLockMutex) );
5978 sqlite3_mutex_enter(pInode->pLockMutex);
5979 flags &= (SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE);
5980 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
5981 pUnused = *pp;
5982 if( pUnused ){
5983 *pp = pUnused->pNext;
5985 sqlite3_mutex_leave(pInode->pLockMutex);
5988 unixLeaveMutex();
5989 #endif /* if !OS_VXWORKS */
5990 return pUnused;
5994 ** Find the mode, uid and gid of file zFile.
5996 static int getFileMode(
5997 const char *zFile, /* File name */
5998 mode_t *pMode, /* OUT: Permissions of zFile */
5999 uid_t *pUid, /* OUT: uid of zFile. */
6000 gid_t *pGid /* OUT: gid of zFile. */
6002 struct stat sStat; /* Output of stat() on database file */
6003 int rc = SQLITE_OK;
6004 if( 0==osStat(zFile, &sStat) ){
6005 *pMode = sStat.st_mode & 0777;
6006 *pUid = sStat.st_uid;
6007 *pGid = sStat.st_gid;
6008 }else{
6009 rc = SQLITE_IOERR_FSTAT;
6011 return rc;
6015 ** This function is called by unixOpen() to determine the unix permissions
6016 ** to create new files with. If no error occurs, then SQLITE_OK is returned
6017 ** and a value suitable for passing as the third argument to open(2) is
6018 ** written to *pMode. If an IO error occurs, an SQLite error code is
6019 ** returned and the value of *pMode is not modified.
6021 ** In most cases, this routine sets *pMode to 0, which will become
6022 ** an indication to robust_open() to create the file using
6023 ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
6024 ** But if the file being opened is a WAL or regular journal file, then
6025 ** this function queries the file-system for the permissions on the
6026 ** corresponding database file and sets *pMode to this value. Whenever
6027 ** possible, WAL and journal files are created using the same permissions
6028 ** as the associated database file.
6030 ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
6031 ** original filename is unavailable. But 8_3_NAMES is only used for
6032 ** FAT filesystems and permissions do not matter there, so just use
6033 ** the default permissions. In 8_3_NAMES mode, leave *pMode set to zero.
6035 static int findCreateFileMode(
6036 const char *zPath, /* Path of file (possibly) being created */
6037 int flags, /* Flags passed as 4th argument to xOpen() */
6038 mode_t *pMode, /* OUT: Permissions to open file with */
6039 uid_t *pUid, /* OUT: uid to set on the file */
6040 gid_t *pGid /* OUT: gid to set on the file */
6042 int rc = SQLITE_OK; /* Return Code */
6043 *pMode = 0;
6044 *pUid = 0;
6045 *pGid = 0;
6046 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
6047 char zDb[MAX_PATHNAME+1]; /* Database file path */
6048 int nDb; /* Number of valid bytes in zDb */
6050 /* zPath is a path to a WAL or journal file. The following block derives
6051 ** the path to the associated database file from zPath. This block handles
6052 ** the following naming conventions:
6054 ** "<path to db>-journal"
6055 ** "<path to db>-wal"
6056 ** "<path to db>-journalNN"
6057 ** "<path to db>-walNN"
6059 ** where NN is a decimal number. The NN naming schemes are
6060 ** used by the test_multiplex.c module.
6062 ** In normal operation, the journal file name will always contain
6063 ** a '-' character. However in 8+3 filename mode, or if a corrupt
6064 ** rollback journal specifies a super-journal with a goofy name, then
6065 ** the '-' might be missing or the '-' might be the first character in
6066 ** the filename. In that case, just return SQLITE_OK with *pMode==0.
6068 nDb = sqlite3Strlen30(zPath) - 1;
6069 while( nDb>0 && zPath[nDb]!='.' ){
6070 if( zPath[nDb]=='-' ){
6071 memcpy(zDb, zPath, nDb);
6072 zDb[nDb] = '\0';
6073 rc = getFileMode(zDb, pMode, pUid, pGid);
6074 break;
6076 nDb--;
6078 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
6079 *pMode = 0600;
6080 }else if( flags & SQLITE_OPEN_URI ){
6081 /* If this is a main database file and the file was opened using a URI
6082 ** filename, check for the "modeof" parameter. If present, interpret
6083 ** its value as a filename and try to copy the mode, uid and gid from
6084 ** that file. */
6085 const char *z = sqlite3_uri_parameter(zPath, "modeof");
6086 if( z ){
6087 rc = getFileMode(z, pMode, pUid, pGid);
6090 return rc;
6094 ** Open the file zPath.
6096 ** Previously, the SQLite OS layer used three functions in place of this
6097 ** one:
6099 ** sqlite3OsOpenReadWrite();
6100 ** sqlite3OsOpenReadOnly();
6101 ** sqlite3OsOpenExclusive();
6103 ** These calls correspond to the following combinations of flags:
6105 ** ReadWrite() -> (READWRITE | CREATE)
6106 ** ReadOnly() -> (READONLY)
6107 ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
6109 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
6110 ** true, the file was configured to be automatically deleted when the
6111 ** file handle closed. To achieve the same effect using this new
6112 ** interface, add the DELETEONCLOSE flag to those specified above for
6113 ** OpenExclusive().
6115 static int unixOpen(
6116 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
6117 const char *zPath, /* Pathname of file to be opened */
6118 sqlite3_file *pFile, /* The file descriptor to be filled in */
6119 int flags, /* Input flags to control the opening */
6120 int *pOutFlags /* Output flags returned to SQLite core */
6122 unixFile *p = (unixFile *)pFile;
6123 int fd = -1; /* File descriptor returned by open() */
6124 int openFlags = 0; /* Flags to pass to open() */
6125 int eType = flags&0x0FFF00; /* Type of file to open */
6126 int noLock; /* True to omit locking primitives */
6127 int rc = SQLITE_OK; /* Function Return Code */
6128 int ctrlFlags = 0; /* UNIXFILE_* flags */
6130 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
6131 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
6132 int isCreate = (flags & SQLITE_OPEN_CREATE);
6133 int isReadonly = (flags & SQLITE_OPEN_READONLY);
6134 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
6135 #if SQLITE_ENABLE_LOCKING_STYLE
6136 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
6137 #endif
6138 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
6139 struct statfs fsInfo;
6140 #endif
6142 /* If creating a super- or main-file journal, this function will open
6143 ** a file-descriptor on the directory too. The first time unixSync()
6144 ** is called the directory file descriptor will be fsync()ed and close()d.
6146 int isNewJrnl = (isCreate && (
6147 eType==SQLITE_OPEN_SUPER_JOURNAL
6148 || eType==SQLITE_OPEN_MAIN_JOURNAL
6149 || eType==SQLITE_OPEN_WAL
6152 /* If argument zPath is a NULL pointer, this function is required to open
6153 ** a temporary file. Use this buffer to store the file name in.
6155 char zTmpname[MAX_PATHNAME+2];
6156 const char *zName = zPath;
6158 /* Check the following statements are true:
6160 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
6161 ** (b) if CREATE is set, then READWRITE must also be set, and
6162 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
6163 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
6165 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
6166 assert(isCreate==0 || isReadWrite);
6167 assert(isExclusive==0 || isCreate);
6168 assert(isDelete==0 || isCreate);
6170 /* The main DB, main journal, WAL file and super-journal are never
6171 ** automatically deleted. Nor are they ever temporary files. */
6172 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
6173 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
6174 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_SUPER_JOURNAL );
6175 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
6177 /* Assert that the upper layer has set one of the "file-type" flags. */
6178 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
6179 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
6180 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_SUPER_JOURNAL
6181 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
6184 /* Detect a pid change and reset the PRNG. There is a race condition
6185 ** here such that two or more threads all trying to open databases at
6186 ** the same instant might all reset the PRNG. But multiple resets
6187 ** are harmless.
6189 if( randomnessPid!=osGetpid(0) ){
6190 randomnessPid = osGetpid(0);
6191 sqlite3_randomness(0,0);
6193 memset(p, 0, sizeof(unixFile));
6195 #ifdef SQLITE_ASSERT_NO_FILES
6196 /* Applications that never read or write a persistent disk files */
6197 assert( zName==0 );
6198 #endif
6200 if( eType==SQLITE_OPEN_MAIN_DB ){
6201 UnixUnusedFd *pUnused;
6202 pUnused = findReusableFd(zName, flags);
6203 if( pUnused ){
6204 fd = pUnused->fd;
6205 }else{
6206 pUnused = sqlite3_malloc64(sizeof(*pUnused));
6207 if( !pUnused ){
6208 return SQLITE_NOMEM_BKPT;
6211 p->pPreallocatedUnused = pUnused;
6213 /* Database filenames are double-zero terminated if they are not
6214 ** URIs with parameters. Hence, they can always be passed into
6215 ** sqlite3_uri_parameter(). */
6216 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
6218 }else if( !zName ){
6219 /* If zName is NULL, the upper layer is requesting a temp file. */
6220 assert(isDelete && !isNewJrnl);
6221 rc = unixGetTempname(pVfs->mxPathname, zTmpname);
6222 if( rc!=SQLITE_OK ){
6223 return rc;
6225 zName = zTmpname;
6227 /* Generated temporary filenames are always double-zero terminated
6228 ** for use by sqlite3_uri_parameter(). */
6229 assert( zName[strlen(zName)+1]==0 );
6232 /* Determine the value of the flags parameter passed to POSIX function
6233 ** open(). These must be calculated even if open() is not called, as
6234 ** they may be stored as part of the file handle and used by the
6235 ** 'conch file' locking functions later on. */
6236 if( isReadonly ) openFlags |= O_RDONLY;
6237 if( isReadWrite ) openFlags |= O_RDWR;
6238 if( isCreate ) openFlags |= O_CREAT;
6239 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
6240 openFlags |= (O_LARGEFILE|O_BINARY|O_NOFOLLOW);
6242 if( fd<0 ){
6243 mode_t openMode; /* Permissions to create file with */
6244 uid_t uid; /* Userid for the file */
6245 gid_t gid; /* Groupid for the file */
6246 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
6247 if( rc!=SQLITE_OK ){
6248 assert( !p->pPreallocatedUnused );
6249 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
6250 return rc;
6252 fd = robust_open(zName, openFlags, openMode);
6253 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
6254 assert( !isExclusive || (openFlags & O_CREAT)!=0 );
6255 if( fd<0 ){
6256 if( isNewJrnl && errno==EACCES && osAccess(zName, F_OK) ){
6257 /* If unable to create a journal because the directory is not
6258 ** writable, change the error code to indicate that. */
6259 rc = SQLITE_READONLY_DIRECTORY;
6260 }else if( errno!=EISDIR && isReadWrite ){
6261 /* Failed to open the file for read/write access. Try read-only. */
6262 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
6263 openFlags &= ~(O_RDWR|O_CREAT);
6264 flags |= SQLITE_OPEN_READONLY;
6265 openFlags |= O_RDONLY;
6266 isReadonly = 1;
6267 fd = robust_open(zName, openFlags, openMode);
6270 if( fd<0 ){
6271 int rc2 = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
6272 if( rc==SQLITE_OK ) rc = rc2;
6273 goto open_finished;
6276 /* The owner of the rollback journal or WAL file should always be the
6277 ** same as the owner of the database file. Try to ensure that this is
6278 ** the case. The chown() system call will be a no-op if the current
6279 ** process lacks root privileges, be we should at least try. Without
6280 ** this step, if a root process opens a database file, it can leave
6281 ** behinds a journal/WAL that is owned by root and hence make the
6282 ** database inaccessible to unprivileged processes.
6284 ** If openMode==0, then that means uid and gid are not set correctly
6285 ** (probably because SQLite is configured to use 8+3 filename mode) and
6286 ** in that case we do not want to attempt the chown().
6288 if( openMode && (flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL))!=0 ){
6289 robustFchown(fd, uid, gid);
6292 assert( fd>=0 );
6293 if( pOutFlags ){
6294 *pOutFlags = flags;
6297 if( p->pPreallocatedUnused ){
6298 p->pPreallocatedUnused->fd = fd;
6299 p->pPreallocatedUnused->flags =
6300 flags & (SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE);
6303 if( isDelete ){
6304 #if OS_VXWORKS
6305 zPath = zName;
6306 #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
6307 zPath = sqlite3_mprintf("%s", zName);
6308 if( zPath==0 ){
6309 robust_close(p, fd, __LINE__);
6310 return SQLITE_NOMEM_BKPT;
6312 #else
6313 osUnlink(zName);
6314 #endif
6316 #if SQLITE_ENABLE_LOCKING_STYLE
6317 else{
6318 p->openFlags = openFlags;
6320 #endif
6322 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
6323 if( fstatfs(fd, &fsInfo) == -1 ){
6324 storeLastErrno(p, errno);
6325 robust_close(p, fd, __LINE__);
6326 return SQLITE_IOERR_ACCESS;
6328 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
6329 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
6331 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
6332 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
6334 #endif
6336 /* Set up appropriate ctrlFlags */
6337 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
6338 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
6339 noLock = eType!=SQLITE_OPEN_MAIN_DB;
6340 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
6341 if( isNewJrnl ) ctrlFlags |= UNIXFILE_DIRSYNC;
6342 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
6344 #if SQLITE_ENABLE_LOCKING_STYLE
6345 #if SQLITE_PREFER_PROXY_LOCKING
6346 isAutoProxy = 1;
6347 #endif
6348 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
6349 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
6350 int useProxy = 0;
6352 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
6353 ** never use proxy, NULL means use proxy for non-local files only. */
6354 if( envforce!=NULL ){
6355 useProxy = atoi(envforce)>0;
6356 }else{
6357 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
6359 if( useProxy ){
6360 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
6361 if( rc==SQLITE_OK ){
6362 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
6363 if( rc!=SQLITE_OK ){
6364 /* Use unixClose to clean up the resources added in fillInUnixFile
6365 ** and clear all the structure's references. Specifically,
6366 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
6368 unixClose(pFile);
6369 return rc;
6372 goto open_finished;
6375 #endif
6377 assert( zPath==0 || zPath[0]=='/'
6378 || eType==SQLITE_OPEN_SUPER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL
6380 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
6382 open_finished:
6383 if( rc!=SQLITE_OK ){
6384 sqlite3_free(p->pPreallocatedUnused);
6386 return rc;
6391 ** Delete the file at zPath. If the dirSync argument is true, fsync()
6392 ** the directory after deleting the file.
6394 static int unixDelete(
6395 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
6396 const char *zPath, /* Name of file to be deleted */
6397 int dirSync /* If true, fsync() directory after deleting file */
6399 int rc = SQLITE_OK;
6400 UNUSED_PARAMETER(NotUsed);
6401 SimulateIOError(return SQLITE_IOERR_DELETE);
6402 if( osUnlink(zPath)==(-1) ){
6403 if( errno==ENOENT
6404 #if OS_VXWORKS
6405 || osAccess(zPath,0)!=0
6406 #endif
6408 rc = SQLITE_IOERR_DELETE_NOENT;
6409 }else{
6410 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
6412 return rc;
6414 #ifndef SQLITE_DISABLE_DIRSYNC
6415 if( (dirSync & 1)!=0 ){
6416 int fd;
6417 rc = osOpenDirectory(zPath, &fd);
6418 if( rc==SQLITE_OK ){
6419 if( full_fsync(fd,0,0) ){
6420 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
6422 robust_close(0, fd, __LINE__);
6423 }else{
6424 assert( rc==SQLITE_CANTOPEN );
6425 rc = SQLITE_OK;
6428 #endif
6429 return rc;
6433 ** Test the existence of or access permissions of file zPath. The
6434 ** test performed depends on the value of flags:
6436 ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
6437 ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
6438 ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
6440 ** Otherwise return 0.
6442 static int unixAccess(
6443 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
6444 const char *zPath, /* Path of the file to examine */
6445 int flags, /* What do we want to learn about the zPath file? */
6446 int *pResOut /* Write result boolean here */
6448 UNUSED_PARAMETER(NotUsed);
6449 SimulateIOError( return SQLITE_IOERR_ACCESS; );
6450 assert( pResOut!=0 );
6452 /* The spec says there are three possible values for flags. But only
6453 ** two of them are actually used */
6454 assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
6456 if( flags==SQLITE_ACCESS_EXISTS ){
6457 struct stat buf;
6458 *pResOut = 0==osStat(zPath, &buf) &&
6459 (!S_ISREG(buf.st_mode) || buf.st_size>0);
6460 }else{
6461 *pResOut = osAccess(zPath, W_OK|R_OK)==0;
6463 return SQLITE_OK;
6467 ** A pathname under construction
6469 typedef struct DbPath DbPath;
6470 struct DbPath {
6471 int rc; /* Non-zero following any error */
6472 int nSymlink; /* Number of symlinks resolved */
6473 char *zOut; /* Write the pathname here */
6474 int nOut; /* Bytes of space available to zOut[] */
6475 int nUsed; /* Bytes of zOut[] currently being used */
6478 /* Forward reference */
6479 static void appendAllPathElements(DbPath*,const char*);
6482 ** Append a single path element to the DbPath under construction
6484 static void appendOnePathElement(
6485 DbPath *pPath, /* Path under construction, to which to append zName */
6486 const char *zName, /* Name to append to pPath. Not zero-terminated */
6487 int nName /* Number of significant bytes in zName */
6489 assert( nName>0 );
6490 assert( zName!=0 );
6491 if( zName[0]=='.' ){
6492 if( nName==1 ) return;
6493 if( zName[1]=='.' && nName==2 ){
6494 if( pPath->nUsed>1 ){
6495 assert( pPath->zOut[0]=='/' );
6496 while( pPath->zOut[--pPath->nUsed]!='/' ){}
6498 return;
6501 if( pPath->nUsed + nName + 2 >= pPath->nOut ){
6502 pPath->rc = SQLITE_ERROR;
6503 return;
6505 pPath->zOut[pPath->nUsed++] = '/';
6506 memcpy(&pPath->zOut[pPath->nUsed], zName, nName);
6507 pPath->nUsed += nName;
6508 #if defined(HAVE_READLINK) && defined(HAVE_LSTAT)
6509 if( pPath->rc==SQLITE_OK ){
6510 const char *zIn;
6511 struct stat buf;
6512 pPath->zOut[pPath->nUsed] = 0;
6513 zIn = pPath->zOut;
6514 if( osLstat(zIn, &buf)!=0 ){
6515 if( errno!=ENOENT ){
6516 pPath->rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
6518 }else if( S_ISLNK(buf.st_mode) ){
6519 ssize_t got;
6520 char zLnk[SQLITE_MAX_PATHLEN+2];
6521 if( pPath->nSymlink++ > SQLITE_MAX_SYMLINK ){
6522 pPath->rc = SQLITE_CANTOPEN_BKPT;
6523 return;
6525 got = osReadlink(zIn, zLnk, sizeof(zLnk)-2);
6526 if( got<=0 || got>=(ssize_t)sizeof(zLnk)-2 ){
6527 pPath->rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
6528 return;
6530 zLnk[got] = 0;
6531 if( zLnk[0]=='/' ){
6532 pPath->nUsed = 0;
6533 }else{
6534 pPath->nUsed -= nName + 1;
6536 appendAllPathElements(pPath, zLnk);
6539 #endif
6543 ** Append all path elements in zPath to the DbPath under construction.
6545 static void appendAllPathElements(
6546 DbPath *pPath, /* Path under construction, to which to append zName */
6547 const char *zPath /* Path to append to pPath. Is zero-terminated */
6549 int i = 0;
6550 int j = 0;
6552 while( zPath[i] && zPath[i]!='/' ){ i++; }
6553 if( i>j ){
6554 appendOnePathElement(pPath, &zPath[j], i-j);
6556 j = i+1;
6557 }while( zPath[i++] );
6561 ** Turn a relative pathname into a full pathname. The relative path
6562 ** is stored as a nul-terminated string in the buffer pointed to by
6563 ** zPath.
6565 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
6566 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
6567 ** this buffer before returning.
6569 static int unixFullPathname(
6570 sqlite3_vfs *pVfs, /* Pointer to vfs object */
6571 const char *zPath, /* Possibly relative input path */
6572 int nOut, /* Size of output buffer in bytes */
6573 char *zOut /* Output buffer */
6575 DbPath path;
6576 UNUSED_PARAMETER(pVfs);
6577 path.rc = 0;
6578 path.nUsed = 0;
6579 path.nSymlink = 0;
6580 path.nOut = nOut;
6581 path.zOut = zOut;
6582 if( zPath[0]!='/' ){
6583 char zPwd[SQLITE_MAX_PATHLEN+2];
6584 if( osGetcwd(zPwd, sizeof(zPwd)-2)==0 ){
6585 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
6587 appendAllPathElements(&path, zPwd);
6589 appendAllPathElements(&path, zPath);
6590 zOut[path.nUsed] = 0;
6591 if( path.rc || path.nUsed<2 ) return SQLITE_CANTOPEN_BKPT;
6592 if( path.nSymlink ) return SQLITE_OK_SYMLINK;
6593 return SQLITE_OK;
6596 #ifndef SQLITE_OMIT_LOAD_EXTENSION
6598 ** Interfaces for opening a shared library, finding entry points
6599 ** within the shared library, and closing the shared library.
6601 #include <dlfcn.h>
6602 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6603 UNUSED_PARAMETER(NotUsed);
6604 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6608 ** SQLite calls this function immediately after a call to unixDlSym() or
6609 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
6610 ** message is available, it is written to zBufOut. If no error message
6611 ** is available, zBufOut is left unmodified and SQLite uses a default
6612 ** error message.
6614 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
6615 const char *zErr;
6616 UNUSED_PARAMETER(NotUsed);
6617 unixEnterMutex();
6618 zErr = dlerror();
6619 if( zErr ){
6620 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
6622 unixLeaveMutex();
6624 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6626 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6627 ** cast into a pointer to a function. And yet the library dlsym() routine
6628 ** returns a void* which is really a pointer to a function. So how do we
6629 ** use dlsym() with -pedantic-errors?
6631 ** Variable x below is defined to be a pointer to a function taking
6632 ** parameters void* and const char* and returning a pointer to a function.
6633 ** We initialize x by assigning it a pointer to the dlsym() function.
6634 ** (That assignment requires a cast.) Then we call the function that
6635 ** x points to.
6637 ** This work-around is unlikely to work correctly on any system where
6638 ** you really cannot cast a function pointer into void*. But then, on the
6639 ** other hand, dlsym() will not work on such a system either, so we have
6640 ** not really lost anything.
6642 void (*(*x)(void*,const char*))(void);
6643 UNUSED_PARAMETER(NotUsed);
6644 x = (void(*(*)(void*,const char*))(void))dlsym;
6645 return (*x)(p, zSym);
6647 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6648 UNUSED_PARAMETER(NotUsed);
6649 dlclose(pHandle);
6651 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6652 #define unixDlOpen 0
6653 #define unixDlError 0
6654 #define unixDlSym 0
6655 #define unixDlClose 0
6656 #endif
6659 ** Write nBuf bytes of random data to the supplied buffer zBuf.
6661 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6662 UNUSED_PARAMETER(NotUsed);
6663 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
6665 /* We have to initialize zBuf to prevent valgrind from reporting
6666 ** errors. The reports issued by valgrind are incorrect - we would
6667 ** prefer that the randomness be increased by making use of the
6668 ** uninitialized space in zBuf - but valgrind errors tend to worry
6669 ** some users. Rather than argue, it seems easier just to initialize
6670 ** the whole array and silence valgrind, even if that means less randomness
6671 ** in the random seed.
6673 ** When testing, initializing zBuf[] to zero is all we do. That means
6674 ** that we always use the same random number sequence. This makes the
6675 ** tests repeatable.
6677 memset(zBuf, 0, nBuf);
6678 randomnessPid = osGetpid(0);
6679 #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
6681 int fd, got;
6682 fd = robust_open("/dev/urandom", O_RDONLY, 0);
6683 if( fd<0 ){
6684 time_t t;
6685 time(&t);
6686 memcpy(zBuf, &t, sizeof(t));
6687 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6688 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6689 nBuf = sizeof(t) + sizeof(randomnessPid);
6690 }else{
6691 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
6692 robust_close(0, fd, __LINE__);
6695 #endif
6696 return nBuf;
6701 ** Sleep for a little while. Return the amount of time slept.
6702 ** The argument is the number of microseconds we want to sleep.
6703 ** The return value is the number of microseconds of sleep actually
6704 ** requested from the underlying operating system, a number which
6705 ** might be greater than or equal to the argument, but not less
6706 ** than the argument.
6708 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
6709 #if !defined(HAVE_NANOSLEEP) || HAVE_NANOSLEEP+0
6710 struct timespec sp;
6711 sp.tv_sec = microseconds / 1000000;
6712 sp.tv_nsec = (microseconds % 1000000) * 1000;
6714 /* Almost all modern unix systems support nanosleep(). But if you are
6715 ** compiling for one of the rare exceptions, you can use
6716 ** -DHAVE_NANOSLEEP=0 (perhaps in conjuction with -DHAVE_USLEEP if
6717 ** usleep() is available) in order to bypass the use of nanosleep() */
6718 nanosleep(&sp, NULL);
6720 UNUSED_PARAMETER(NotUsed);
6721 return microseconds;
6722 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
6723 if( microseconds>=1000000 ) sleep(microseconds/1000000);
6724 if( microseconds%1000000 ) usleep(microseconds%1000000);
6725 UNUSED_PARAMETER(NotUsed);
6726 return microseconds;
6727 #else
6728 int seconds = (microseconds+999999)/1000000;
6729 sleep(seconds);
6730 UNUSED_PARAMETER(NotUsed);
6731 return seconds*1000000;
6732 #endif
6736 ** The following variable, if set to a non-zero value, is interpreted as
6737 ** the number of seconds since 1970 and is used to set the result of
6738 ** sqlite3OsCurrentTime() during testing.
6740 #ifdef SQLITE_TEST
6741 int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
6742 #endif
6745 ** Find the current time (in Universal Coordinated Time). Write into *piNow
6746 ** the current time and date as a Julian Day number times 86_400_000. In
6747 ** other words, write into *piNow the number of milliseconds since the Julian
6748 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6749 ** proleptic Gregorian calendar.
6751 ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6752 ** cannot be found.
6754 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6755 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
6756 int rc = SQLITE_OK;
6757 #if defined(NO_GETTOD)
6758 time_t t;
6759 time(&t);
6760 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
6761 #elif OS_VXWORKS
6762 struct timespec sNow;
6763 clock_gettime(CLOCK_REALTIME, &sNow);
6764 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6765 #else
6766 struct timeval sNow;
6767 (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
6768 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
6769 #endif
6771 #ifdef SQLITE_TEST
6772 if( sqlite3_current_time ){
6773 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6775 #endif
6776 UNUSED_PARAMETER(NotUsed);
6777 return rc;
6780 #ifndef SQLITE_OMIT_DEPRECATED
6782 ** Find the current time (in Universal Coordinated Time). Write the
6783 ** current time and date as a Julian Day number into *prNow and
6784 ** return 0. Return 1 if the time and date cannot be found.
6786 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
6787 sqlite3_int64 i = 0;
6788 int rc;
6789 UNUSED_PARAMETER(NotUsed);
6790 rc = unixCurrentTimeInt64(0, &i);
6791 *prNow = i/86400000.0;
6792 return rc;
6794 #else
6795 # define unixCurrentTime 0
6796 #endif
6799 ** The xGetLastError() method is designed to return a better
6800 ** low-level error message when operating-system problems come up
6801 ** during SQLite operation. Only the integer return code is currently
6802 ** used.
6804 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6805 UNUSED_PARAMETER(NotUsed);
6806 UNUSED_PARAMETER(NotUsed2);
6807 UNUSED_PARAMETER(NotUsed3);
6808 return errno;
6813 ************************ End of sqlite3_vfs methods ***************************
6814 ******************************************************************************/
6816 /******************************************************************************
6817 ************************** Begin Proxy Locking ********************************
6819 ** Proxy locking is a "uber-locking-method" in this sense: It uses the
6820 ** other locking methods on secondary lock files. Proxy locking is a
6821 ** meta-layer over top of the primitive locking implemented above. For
6822 ** this reason, the division that implements of proxy locking is deferred
6823 ** until late in the file (here) after all of the other I/O methods have
6824 ** been defined - so that the primitive locking methods are available
6825 ** as services to help with the implementation of proxy locking.
6827 ****
6829 ** The default locking schemes in SQLite use byte-range locks on the
6830 ** database file to coordinate safe, concurrent access by multiple readers
6831 ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6832 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6833 ** as POSIX read & write locks over fixed set of locations (via fsctl),
6834 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
6835 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6836 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6837 ** address in the shared range is taken for a SHARED lock, the entire
6838 ** shared range is taken for an EXCLUSIVE lock):
6840 ** PENDING_BYTE 0x40000000
6841 ** RESERVED_BYTE 0x40000001
6842 ** SHARED_RANGE 0x40000002 -> 0x40000200
6844 ** This works well on the local file system, but shows a nearly 100x
6845 ** slowdown in read performance on AFP because the AFP client disables
6846 ** the read cache when byte-range locks are present. Enabling the read
6847 ** cache exposes a cache coherency problem that is present on all OS X
6848 ** supported network file systems. NFS and AFP both observe the
6849 ** close-to-open semantics for ensuring cache coherency
6850 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6851 ** address the requirements for concurrent database access by multiple
6852 ** readers and writers
6853 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6855 ** To address the performance and cache coherency issues, proxy file locking
6856 ** changes the way database access is controlled by limiting access to a
6857 ** single host at a time and moving file locks off of the database file
6858 ** and onto a proxy file on the local file system.
6861 ** Using proxy locks
6862 ** -----------------
6864 ** C APIs
6866 ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
6867 ** <proxy_path> | ":auto:");
6868 ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6869 ** &<proxy_path>);
6872 ** SQL pragmas
6874 ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6875 ** PRAGMA [database.]lock_proxy_file
6877 ** Specifying ":auto:" means that if there is a conch file with a matching
6878 ** host ID in it, the proxy path in the conch file will be used, otherwise
6879 ** a proxy path based on the user's temp dir
6880 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6881 ** actual proxy file name is generated from the name and path of the
6882 ** database file. For example:
6884 ** For database path "/Users/me/foo.db"
6885 ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6887 ** Once a lock proxy is configured for a database connection, it can not
6888 ** be removed, however it may be switched to a different proxy path via
6889 ** the above APIs (assuming the conch file is not being held by another
6890 ** connection or process).
6893 ** How proxy locking works
6894 ** -----------------------
6896 ** Proxy file locking relies primarily on two new supporting files:
6898 ** * conch file to limit access to the database file to a single host
6899 ** at a time
6901 ** * proxy file to act as a proxy for the advisory locks normally
6902 ** taken on the database
6904 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
6905 ** by taking an sqlite-style shared lock on the conch file, reading the
6906 ** contents and comparing the host's unique host ID (see below) and lock
6907 ** proxy path against the values stored in the conch. The conch file is
6908 ** stored in the same directory as the database file and the file name
6909 ** is patterned after the database file name as ".<databasename>-conch".
6910 ** If the conch file does not exist, or its contents do not match the
6911 ** host ID and/or proxy path, then the lock is escalated to an exclusive
6912 ** lock and the conch file contents is updated with the host ID and proxy
6913 ** path and the lock is downgraded to a shared lock again. If the conch
6914 ** is held by another process (with a shared lock), the exclusive lock
6915 ** will fail and SQLITE_BUSY is returned.
6917 ** The proxy file - a single-byte file used for all advisory file locks
6918 ** normally taken on the database file. This allows for safe sharing
6919 ** of the database file for multiple readers and writers on the same
6920 ** host (the conch ensures that they all use the same local lock file).
6922 ** Requesting the lock proxy does not immediately take the conch, it is
6923 ** only taken when the first request to lock database file is made.
6924 ** This matches the semantics of the traditional locking behavior, where
6925 ** opening a connection to a database file does not take a lock on it.
6926 ** The shared lock and an open file descriptor are maintained until
6927 ** the connection to the database is closed.
6929 ** The proxy file and the lock file are never deleted so they only need
6930 ** to be created the first time they are used.
6932 ** Configuration options
6933 ** ---------------------
6935 ** SQLITE_PREFER_PROXY_LOCKING
6937 ** Database files accessed on non-local file systems are
6938 ** automatically configured for proxy locking, lock files are
6939 ** named automatically using the same logic as
6940 ** PRAGMA lock_proxy_file=":auto:"
6942 ** SQLITE_PROXY_DEBUG
6944 ** Enables the logging of error messages during host id file
6945 ** retrieval and creation
6947 ** LOCKPROXYDIR
6949 ** Overrides the default directory used for lock proxy files that
6950 ** are named automatically via the ":auto:" setting
6952 ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6954 ** Permissions to use when creating a directory for storing the
6955 ** lock proxy files, only used when LOCKPROXYDIR is not set.
6958 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6959 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6960 ** force proxy locking to be used for every database file opened, and 0
6961 ** will force automatic proxy locking to be disabled for all database
6962 ** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
6963 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6967 ** Proxy locking is only available on MacOSX
6969 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
6972 ** The proxyLockingContext has the path and file structures for the remote
6973 ** and local proxy files in it
6975 typedef struct proxyLockingContext proxyLockingContext;
6976 struct proxyLockingContext {
6977 unixFile *conchFile; /* Open conch file */
6978 char *conchFilePath; /* Name of the conch file */
6979 unixFile *lockProxy; /* Open proxy lock file */
6980 char *lockProxyPath; /* Name of the proxy lock file */
6981 char *dbPath; /* Name of the open file */
6982 int conchHeld; /* 1 if the conch is held, -1 if lockless */
6983 int nFails; /* Number of conch taking failures */
6984 void *oldLockingContext; /* Original lockingcontext to restore on close */
6985 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6989 ** The proxy lock file path for the database at dbPath is written into lPath,
6990 ** which must point to valid, writable memory large enough for a maxLen length
6991 ** file path.
6993 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6994 int len;
6995 int dbLen;
6996 int i;
6998 #ifdef LOCKPROXYDIR
6999 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
7000 #else
7001 # ifdef _CS_DARWIN_USER_TEMP_DIR
7003 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
7004 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
7005 lPath, errno, osGetpid(0)));
7006 return SQLITE_IOERR_LOCK;
7008 len = strlcat(lPath, "sqliteplocks", maxLen);
7010 # else
7011 len = strlcpy(lPath, "/tmp/", maxLen);
7012 # endif
7013 #endif
7015 if( lPath[len-1]!='/' ){
7016 len = strlcat(lPath, "/", maxLen);
7019 /* transform the db path to a unique cache name */
7020 dbLen = (int)strlen(dbPath);
7021 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
7022 char c = dbPath[i];
7023 lPath[i+len] = (c=='/')?'_':c;
7025 lPath[i+len]='\0';
7026 strlcat(lPath, ":auto:", maxLen);
7027 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
7028 return SQLITE_OK;
7032 ** Creates the lock file and any missing directories in lockPath
7034 static int proxyCreateLockPath(const char *lockPath){
7035 int i, len;
7036 char buf[MAXPATHLEN];
7037 int start = 0;
7039 assert(lockPath!=NULL);
7040 /* try to create all the intermediate directories */
7041 len = (int)strlen(lockPath);
7042 buf[0] = lockPath[0];
7043 for( i=1; i<len; i++ ){
7044 if( lockPath[i] == '/' && (i - start > 0) ){
7045 /* only mkdir if leaf dir != "." or "/" or ".." */
7046 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
7047 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
7048 buf[i]='\0';
7049 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
7050 int err=errno;
7051 if( err!=EEXIST ) {
7052 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
7053 "'%s' proxy lock path=%s pid=%d\n",
7054 buf, strerror(err), lockPath, osGetpid(0)));
7055 return err;
7059 start=i+1;
7061 buf[i] = lockPath[i];
7063 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
7064 return 0;
7068 ** Create a new VFS file descriptor (stored in memory obtained from
7069 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
7071 ** The caller is responsible not only for closing the file descriptor
7072 ** but also for freeing the memory associated with the file descriptor.
7074 static int proxyCreateUnixFile(
7075 const char *path, /* path for the new unixFile */
7076 unixFile **ppFile, /* unixFile created and returned by ref */
7077 int islockfile /* if non zero missing dirs will be created */
7079 int fd = -1;
7080 unixFile *pNew;
7081 int rc = SQLITE_OK;
7082 int openFlags = O_RDWR | O_CREAT | O_NOFOLLOW;
7083 sqlite3_vfs dummyVfs;
7084 int terrno = 0;
7085 UnixUnusedFd *pUnused = NULL;
7087 /* 1. first try to open/create the file
7088 ** 2. if that fails, and this is a lock file (not-conch), try creating
7089 ** the parent directories and then try again.
7090 ** 3. if that fails, try to open the file read-only
7091 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
7093 pUnused = findReusableFd(path, openFlags);
7094 if( pUnused ){
7095 fd = pUnused->fd;
7096 }else{
7097 pUnused = sqlite3_malloc64(sizeof(*pUnused));
7098 if( !pUnused ){
7099 return SQLITE_NOMEM_BKPT;
7102 if( fd<0 ){
7103 fd = robust_open(path, openFlags, 0);
7104 terrno = errno;
7105 if( fd<0 && errno==ENOENT && islockfile ){
7106 if( proxyCreateLockPath(path) == SQLITE_OK ){
7107 fd = robust_open(path, openFlags, 0);
7111 if( fd<0 ){
7112 openFlags = O_RDONLY | O_NOFOLLOW;
7113 fd = robust_open(path, openFlags, 0);
7114 terrno = errno;
7116 if( fd<0 ){
7117 if( islockfile ){
7118 return SQLITE_BUSY;
7120 switch (terrno) {
7121 case EACCES:
7122 return SQLITE_PERM;
7123 case EIO:
7124 return SQLITE_IOERR_LOCK; /* even though it is the conch */
7125 default:
7126 return SQLITE_CANTOPEN_BKPT;
7130 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
7131 if( pNew==NULL ){
7132 rc = SQLITE_NOMEM_BKPT;
7133 goto end_create_proxy;
7135 memset(pNew, 0, sizeof(unixFile));
7136 pNew->openFlags = openFlags;
7137 memset(&dummyVfs, 0, sizeof(dummyVfs));
7138 dummyVfs.pAppData = (void*)&autolockIoFinder;
7139 dummyVfs.zName = "dummy";
7140 pUnused->fd = fd;
7141 pUnused->flags = openFlags;
7142 pNew->pPreallocatedUnused = pUnused;
7144 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
7145 if( rc==SQLITE_OK ){
7146 *ppFile = pNew;
7147 return SQLITE_OK;
7149 end_create_proxy:
7150 robust_close(pNew, fd, __LINE__);
7151 sqlite3_free(pNew);
7152 sqlite3_free(pUnused);
7153 return rc;
7156 #ifdef SQLITE_TEST
7157 /* simulate multiple hosts by creating unique hostid file paths */
7158 int sqlite3_hostid_num = 0;
7159 #endif
7161 #define PROXY_HOSTIDLEN 16 /* conch file host id length */
7163 #if HAVE_GETHOSTUUID
7164 /* Not always defined in the headers as it ought to be */
7165 extern int gethostuuid(uuid_t id, const struct timespec *wait);
7166 #endif
7168 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
7169 ** bytes of writable memory.
7171 static int proxyGetHostID(unsigned char *pHostID, int *pError){
7172 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
7173 memset(pHostID, 0, PROXY_HOSTIDLEN);
7174 #if HAVE_GETHOSTUUID
7176 struct timespec timeout = {1, 0}; /* 1 sec timeout */
7177 if( gethostuuid(pHostID, &timeout) ){
7178 int err = errno;
7179 if( pError ){
7180 *pError = err;
7182 return SQLITE_IOERR;
7185 #else
7186 UNUSED_PARAMETER(pError);
7187 #endif
7188 #ifdef SQLITE_TEST
7189 /* simulate multiple hosts by creating unique hostid file paths */
7190 if( sqlite3_hostid_num != 0){
7191 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
7193 #endif
7195 return SQLITE_OK;
7198 /* The conch file contains the header, host id and lock file path
7200 #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
7201 #define PROXY_HEADERLEN 1 /* conch file header length */
7202 #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
7203 #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
7206 ** Takes an open conch file, copies the contents to a new path and then moves
7207 ** it back. The newly created file's file descriptor is assigned to the
7208 ** conch file structure and finally the original conch file descriptor is
7209 ** closed. Returns zero if successful.
7211 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
7212 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7213 unixFile *conchFile = pCtx->conchFile;
7214 char tPath[MAXPATHLEN];
7215 char buf[PROXY_MAXCONCHLEN];
7216 char *cPath = pCtx->conchFilePath;
7217 size_t readLen = 0;
7218 size_t pathLen = 0;
7219 char errmsg[64] = "";
7220 int fd = -1;
7221 int rc = -1;
7222 UNUSED_PARAMETER(myHostID);
7224 /* create a new path by replace the trailing '-conch' with '-break' */
7225 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
7226 if( pathLen>MAXPATHLEN || pathLen<6 ||
7227 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
7228 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
7229 goto end_breaklock;
7231 /* read the conch content */
7232 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
7233 if( readLen<PROXY_PATHINDEX ){
7234 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
7235 goto end_breaklock;
7237 /* write it out to the temporary break file */
7238 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW), 0);
7239 if( fd<0 ){
7240 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
7241 goto end_breaklock;
7243 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
7244 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
7245 goto end_breaklock;
7247 if( rename(tPath, cPath) ){
7248 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
7249 goto end_breaklock;
7251 rc = 0;
7252 fprintf(stderr, "broke stale lock on %s\n", cPath);
7253 robust_close(pFile, conchFile->h, __LINE__);
7254 conchFile->h = fd;
7255 conchFile->openFlags = O_RDWR | O_CREAT;
7257 end_breaklock:
7258 if( rc ){
7259 if( fd>=0 ){
7260 osUnlink(tPath);
7261 robust_close(pFile, fd, __LINE__);
7263 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
7265 return rc;
7268 /* Take the requested lock on the conch file and break a stale lock if the
7269 ** host id matches.
7271 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
7272 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7273 unixFile *conchFile = pCtx->conchFile;
7274 int rc = SQLITE_OK;
7275 int nTries = 0;
7276 struct timespec conchModTime;
7278 memset(&conchModTime, 0, sizeof(conchModTime));
7279 do {
7280 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
7281 nTries ++;
7282 if( rc==SQLITE_BUSY ){
7283 /* If the lock failed (busy):
7284 * 1st try: get the mod time of the conch, wait 0.5s and try again.
7285 * 2nd try: fail if the mod time changed or host id is different, wait
7286 * 10 sec and try again
7287 * 3rd try: break the lock unless the mod time has changed.
7289 struct stat buf;
7290 if( osFstat(conchFile->h, &buf) ){
7291 storeLastErrno(pFile, errno);
7292 return SQLITE_IOERR_LOCK;
7295 if( nTries==1 ){
7296 conchModTime = buf.st_mtimespec;
7297 unixSleep(0,500000); /* wait 0.5 sec and try the lock again*/
7298 continue;
7301 assert( nTries>1 );
7302 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
7303 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
7304 return SQLITE_BUSY;
7307 if( nTries==2 ){
7308 char tBuf[PROXY_MAXCONCHLEN];
7309 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
7310 if( len<0 ){
7311 storeLastErrno(pFile, errno);
7312 return SQLITE_IOERR_LOCK;
7314 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
7315 /* don't break the lock if the host id doesn't match */
7316 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
7317 return SQLITE_BUSY;
7319 }else{
7320 /* don't break the lock on short read or a version mismatch */
7321 return SQLITE_BUSY;
7323 unixSleep(0,10000000); /* wait 10 sec and try the lock again */
7324 continue;
7327 assert( nTries==3 );
7328 if( 0==proxyBreakConchLock(pFile, myHostID) ){
7329 rc = SQLITE_OK;
7330 if( lockType==EXCLUSIVE_LOCK ){
7331 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
7333 if( !rc ){
7334 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
7338 } while( rc==SQLITE_BUSY && nTries<3 );
7340 return rc;
7343 /* Takes the conch by taking a shared lock and read the contents conch, if
7344 ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
7345 ** lockPath means that the lockPath in the conch file will be used if the
7346 ** host IDs match, or a new lock path will be generated automatically
7347 ** and written to the conch file.
7349 static int proxyTakeConch(unixFile *pFile){
7350 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7352 if( pCtx->conchHeld!=0 ){
7353 return SQLITE_OK;
7354 }else{
7355 unixFile *conchFile = pCtx->conchFile;
7356 uuid_t myHostID;
7357 int pError = 0;
7358 char readBuf[PROXY_MAXCONCHLEN];
7359 char lockPath[MAXPATHLEN];
7360 char *tempLockPath = NULL;
7361 int rc = SQLITE_OK;
7362 int createConch = 0;
7363 int hostIdMatch = 0;
7364 int readLen = 0;
7365 int tryOldLockPath = 0;
7366 int forceNewLockPath = 0;
7368 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
7369 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
7370 osGetpid(0)));
7372 rc = proxyGetHostID(myHostID, &pError);
7373 if( (rc&0xff)==SQLITE_IOERR ){
7374 storeLastErrno(pFile, pError);
7375 goto end_takeconch;
7377 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
7378 if( rc!=SQLITE_OK ){
7379 goto end_takeconch;
7381 /* read the existing conch file */
7382 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
7383 if( readLen<0 ){
7384 /* I/O error: lastErrno set by seekAndRead */
7385 storeLastErrno(pFile, conchFile->lastErrno);
7386 rc = SQLITE_IOERR_READ;
7387 goto end_takeconch;
7388 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
7389 readBuf[0]!=(char)PROXY_CONCHVERSION ){
7390 /* a short read or version format mismatch means we need to create a new
7391 ** conch file.
7393 createConch = 1;
7395 /* if the host id matches and the lock path already exists in the conch
7396 ** we'll try to use the path there, if we can't open that path, we'll
7397 ** retry with a new auto-generated path
7399 do { /* in case we need to try again for an :auto: named lock file */
7401 if( !createConch && !forceNewLockPath ){
7402 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
7403 PROXY_HOSTIDLEN);
7404 /* if the conch has data compare the contents */
7405 if( !pCtx->lockProxyPath ){
7406 /* for auto-named local lock file, just check the host ID and we'll
7407 ** use the local lock file path that's already in there
7409 if( hostIdMatch ){
7410 size_t pathLen = (readLen - PROXY_PATHINDEX);
7412 if( pathLen>=MAXPATHLEN ){
7413 pathLen=MAXPATHLEN-1;
7415 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
7416 lockPath[pathLen] = 0;
7417 tempLockPath = lockPath;
7418 tryOldLockPath = 1;
7419 /* create a copy of the lock path if the conch is taken */
7420 goto end_takeconch;
7422 }else if( hostIdMatch
7423 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
7424 readLen-PROXY_PATHINDEX)
7426 /* conch host and lock path match */
7427 goto end_takeconch;
7431 /* if the conch isn't writable and doesn't match, we can't take it */
7432 if( (conchFile->openFlags&O_RDWR) == 0 ){
7433 rc = SQLITE_BUSY;
7434 goto end_takeconch;
7437 /* either the conch didn't match or we need to create a new one */
7438 if( !pCtx->lockProxyPath ){
7439 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
7440 tempLockPath = lockPath;
7441 /* create a copy of the lock path _only_ if the conch is taken */
7444 /* update conch with host and path (this will fail if other process
7445 ** has a shared lock already), if the host id matches, use the big
7446 ** stick.
7448 futimes(conchFile->h, NULL);
7449 if( hostIdMatch && !createConch ){
7450 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
7451 /* We are trying for an exclusive lock but another thread in this
7452 ** same process is still holding a shared lock. */
7453 rc = SQLITE_BUSY;
7454 } else {
7455 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
7457 }else{
7458 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
7460 if( rc==SQLITE_OK ){
7461 char writeBuffer[PROXY_MAXCONCHLEN];
7462 int writeSize = 0;
7464 writeBuffer[0] = (char)PROXY_CONCHVERSION;
7465 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
7466 if( pCtx->lockProxyPath!=NULL ){
7467 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
7468 MAXPATHLEN);
7469 }else{
7470 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
7472 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
7473 robust_ftruncate(conchFile->h, writeSize);
7474 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
7475 full_fsync(conchFile->h,0,0);
7476 /* If we created a new conch file (not just updated the contents of a
7477 ** valid conch file), try to match the permissions of the database
7479 if( rc==SQLITE_OK && createConch ){
7480 struct stat buf;
7481 int err = osFstat(pFile->h, &buf);
7482 if( err==0 ){
7483 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
7484 S_IROTH|S_IWOTH);
7485 /* try to match the database file R/W permissions, ignore failure */
7486 #ifndef SQLITE_PROXY_DEBUG
7487 osFchmod(conchFile->h, cmode);
7488 #else
7490 rc = osFchmod(conchFile->h, cmode);
7491 }while( rc==(-1) && errno==EINTR );
7492 if( rc!=0 ){
7493 int code = errno;
7494 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
7495 cmode, code, strerror(code));
7496 } else {
7497 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
7499 }else{
7500 int code = errno;
7501 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
7502 err, code, strerror(code));
7503 #endif
7507 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
7509 end_takeconch:
7510 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
7511 if( rc==SQLITE_OK && pFile->openFlags ){
7512 int fd;
7513 if( pFile->h>=0 ){
7514 robust_close(pFile, pFile->h, __LINE__);
7516 pFile->h = -1;
7517 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
7518 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
7519 if( fd>=0 ){
7520 pFile->h = fd;
7521 }else{
7522 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
7523 during locking */
7526 if( rc==SQLITE_OK && !pCtx->lockProxy ){
7527 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
7528 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
7529 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
7530 /* we couldn't create the proxy lock file with the old lock file path
7531 ** so try again via auto-naming
7533 forceNewLockPath = 1;
7534 tryOldLockPath = 0;
7535 continue; /* go back to the do {} while start point, try again */
7538 if( rc==SQLITE_OK ){
7539 /* Need to make a copy of path if we extracted the value
7540 ** from the conch file or the path was allocated on the stack
7542 if( tempLockPath ){
7543 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
7544 if( !pCtx->lockProxyPath ){
7545 rc = SQLITE_NOMEM_BKPT;
7549 if( rc==SQLITE_OK ){
7550 pCtx->conchHeld = 1;
7552 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
7553 afpLockingContext *afpCtx;
7554 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
7555 afpCtx->dbPath = pCtx->lockProxyPath;
7557 } else {
7558 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7560 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
7561 rc==SQLITE_OK?"ok":"failed"));
7562 return rc;
7563 } while (1); /* in case we need to retry the :auto: lock file -
7564 ** we should never get here except via the 'continue' call. */
7569 ** If pFile holds a lock on a conch file, then release that lock.
7571 static int proxyReleaseConch(unixFile *pFile){
7572 int rc = SQLITE_OK; /* Subroutine return code */
7573 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
7574 unixFile *conchFile; /* Name of the conch file */
7576 pCtx = (proxyLockingContext *)pFile->lockingContext;
7577 conchFile = pCtx->conchFile;
7578 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
7579 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
7580 osGetpid(0)));
7581 if( pCtx->conchHeld>0 ){
7582 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7584 pCtx->conchHeld = 0;
7585 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
7586 (rc==SQLITE_OK ? "ok" : "failed")));
7587 return rc;
7591 ** Given the name of a database file, compute the name of its conch file.
7592 ** Store the conch filename in memory obtained from sqlite3_malloc64().
7593 ** Make *pConchPath point to the new name. Return SQLITE_OK on success
7594 ** or SQLITE_NOMEM if unable to obtain memory.
7596 ** The caller is responsible for ensuring that the allocated memory
7597 ** space is eventually freed.
7599 ** *pConchPath is set to NULL if a memory allocation error occurs.
7601 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7602 int i; /* Loop counter */
7603 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
7604 char *conchPath; /* buffer in which to construct conch name */
7606 /* Allocate space for the conch filename and initialize the name to
7607 ** the name of the original database file. */
7608 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
7609 if( conchPath==0 ){
7610 return SQLITE_NOMEM_BKPT;
7612 memcpy(conchPath, dbPath, len+1);
7614 /* now insert a "." before the last / character */
7615 for( i=(len-1); i>=0; i-- ){
7616 if( conchPath[i]=='/' ){
7617 i++;
7618 break;
7621 conchPath[i]='.';
7622 while ( i<len ){
7623 conchPath[i+1]=dbPath[i];
7624 i++;
7627 /* append the "-conch" suffix to the file */
7628 memcpy(&conchPath[i+1], "-conch", 7);
7629 assert( (int)strlen(conchPath) == len+7 );
7631 return SQLITE_OK;
7635 /* Takes a fully configured proxy locking-style unix file and switches
7636 ** the local lock file path
7638 static int switchLockProxyPath(unixFile *pFile, const char *path) {
7639 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7640 char *oldPath = pCtx->lockProxyPath;
7641 int rc = SQLITE_OK;
7643 if( pFile->eFileLock!=NO_LOCK ){
7644 return SQLITE_BUSY;
7647 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7648 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7649 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7650 return SQLITE_OK;
7651 }else{
7652 unixFile *lockProxy = pCtx->lockProxy;
7653 pCtx->lockProxy=NULL;
7654 pCtx->conchHeld = 0;
7655 if( lockProxy!=NULL ){
7656 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7657 if( rc ) return rc;
7658 sqlite3_free(lockProxy);
7660 sqlite3_free(oldPath);
7661 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7664 return rc;
7668 ** pFile is a file that has been opened by a prior xOpen call. dbPath
7669 ** is a string buffer at least MAXPATHLEN+1 characters in size.
7671 ** This routine find the filename associated with pFile and writes it
7672 ** int dbPath.
7674 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
7675 #if defined(__APPLE__)
7676 if( pFile->pMethod == &afpIoMethods ){
7677 /* afp style keeps a reference to the db path in the filePath field
7678 ** of the struct */
7679 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
7680 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7681 MAXPATHLEN);
7682 } else
7683 #endif
7684 if( pFile->pMethod == &dotlockIoMethods ){
7685 /* dot lock style uses the locking context to store the dot lock
7686 ** file path */
7687 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7688 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7689 }else{
7690 /* all other styles use the locking context to store the db file path */
7691 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
7692 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
7694 return SQLITE_OK;
7698 ** Takes an already filled in unix file and alters it so all file locking
7699 ** will be performed on the local proxy lock file. The following fields
7700 ** are preserved in the locking context so that they can be restored and
7701 ** the unix structure properly cleaned up at close time:
7702 ** ->lockingContext
7703 ** ->pMethod
7705 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7706 proxyLockingContext *pCtx;
7707 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7708 char *lockPath=NULL;
7709 int rc = SQLITE_OK;
7711 if( pFile->eFileLock!=NO_LOCK ){
7712 return SQLITE_BUSY;
7714 proxyGetDbPathForUnixFile(pFile, dbPath);
7715 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7716 lockPath=NULL;
7717 }else{
7718 lockPath=(char *)path;
7721 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
7722 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
7724 pCtx = sqlite3_malloc64( sizeof(*pCtx) );
7725 if( pCtx==0 ){
7726 return SQLITE_NOMEM_BKPT;
7728 memset(pCtx, 0, sizeof(*pCtx));
7730 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7731 if( rc==SQLITE_OK ){
7732 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7733 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7734 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7735 ** (c) the file system is read-only, then enable no-locking access.
7736 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7737 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7739 struct statfs fsInfo;
7740 struct stat conchInfo;
7741 int goLockless = 0;
7743 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
7744 int err = errno;
7745 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7746 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7749 if( goLockless ){
7750 pCtx->conchHeld = -1; /* read only FS/ lockless */
7751 rc = SQLITE_OK;
7755 if( rc==SQLITE_OK && lockPath ){
7756 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7759 if( rc==SQLITE_OK ){
7760 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7761 if( pCtx->dbPath==NULL ){
7762 rc = SQLITE_NOMEM_BKPT;
7765 if( rc==SQLITE_OK ){
7766 /* all memory is allocated, proxys are created and assigned,
7767 ** switch the locking context and pMethod then return.
7769 pCtx->oldLockingContext = pFile->lockingContext;
7770 pFile->lockingContext = pCtx;
7771 pCtx->pOldMethod = pFile->pMethod;
7772 pFile->pMethod = &proxyIoMethods;
7773 }else{
7774 if( pCtx->conchFile ){
7775 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
7776 sqlite3_free(pCtx->conchFile);
7778 sqlite3DbFree(0, pCtx->lockProxyPath);
7779 sqlite3_free(pCtx->conchFilePath);
7780 sqlite3_free(pCtx);
7782 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7783 (rc==SQLITE_OK ? "ok" : "failed")));
7784 return rc;
7789 ** This routine handles sqlite3_file_control() calls that are specific
7790 ** to proxy locking.
7792 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7793 switch( op ){
7794 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
7795 unixFile *pFile = (unixFile*)id;
7796 if( pFile->pMethod == &proxyIoMethods ){
7797 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7798 proxyTakeConch(pFile);
7799 if( pCtx->lockProxyPath ){
7800 *(const char **)pArg = pCtx->lockProxyPath;
7801 }else{
7802 *(const char **)pArg = ":auto: (not held)";
7804 } else {
7805 *(const char **)pArg = NULL;
7807 return SQLITE_OK;
7809 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
7810 unixFile *pFile = (unixFile*)id;
7811 int rc = SQLITE_OK;
7812 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7813 if( pArg==NULL || (const char *)pArg==0 ){
7814 if( isProxyStyle ){
7815 /* turn off proxy locking - not supported. If support is added for
7816 ** switching proxy locking mode off then it will need to fail if
7817 ** the journal mode is WAL mode.
7819 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7820 }else{
7821 /* turn off proxy locking - already off - NOOP */
7822 rc = SQLITE_OK;
7824 }else{
7825 const char *proxyPath = (const char *)pArg;
7826 if( isProxyStyle ){
7827 proxyLockingContext *pCtx =
7828 (proxyLockingContext*)pFile->lockingContext;
7829 if( !strcmp(pArg, ":auto:")
7830 || (pCtx->lockProxyPath &&
7831 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7833 rc = SQLITE_OK;
7834 }else{
7835 rc = switchLockProxyPath(pFile, proxyPath);
7837 }else{
7838 /* turn on proxy file locking */
7839 rc = proxyTransformUnixFile(pFile, proxyPath);
7842 return rc;
7844 default: {
7845 assert( 0 ); /* The call assures that only valid opcodes are sent */
7848 /*NOTREACHED*/ assert(0);
7849 return SQLITE_ERROR;
7853 ** Within this division (the proxying locking implementation) the procedures
7854 ** above this point are all utilities. The lock-related methods of the
7855 ** proxy-locking sqlite3_io_method object follow.
7860 ** This routine checks if there is a RESERVED lock held on the specified
7861 ** file by this or any other process. If such a lock is held, set *pResOut
7862 ** to a non-zero value otherwise *pResOut is set to zero. The return value
7863 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7865 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7866 unixFile *pFile = (unixFile*)id;
7867 int rc = proxyTakeConch(pFile);
7868 if( rc==SQLITE_OK ){
7869 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7870 if( pCtx->conchHeld>0 ){
7871 unixFile *proxy = pCtx->lockProxy;
7872 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7873 }else{ /* conchHeld < 0 is lockless */
7874 pResOut=0;
7877 return rc;
7881 ** Lock the file with the lock specified by parameter eFileLock - one
7882 ** of the following:
7884 ** (1) SHARED_LOCK
7885 ** (2) RESERVED_LOCK
7886 ** (3) PENDING_LOCK
7887 ** (4) EXCLUSIVE_LOCK
7889 ** Sometimes when requesting one lock state, additional lock states
7890 ** are inserted in between. The locking might fail on one of the later
7891 ** transitions leaving the lock state different from what it started but
7892 ** still short of its goal. The following chart shows the allowed
7893 ** transitions and the inserted intermediate states:
7895 ** UNLOCKED -> SHARED
7896 ** SHARED -> RESERVED
7897 ** SHARED -> (PENDING) -> EXCLUSIVE
7898 ** RESERVED -> (PENDING) -> EXCLUSIVE
7899 ** PENDING -> EXCLUSIVE
7901 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
7902 ** routine to lower a locking level.
7904 static int proxyLock(sqlite3_file *id, int eFileLock) {
7905 unixFile *pFile = (unixFile*)id;
7906 int rc = proxyTakeConch(pFile);
7907 if( rc==SQLITE_OK ){
7908 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7909 if( pCtx->conchHeld>0 ){
7910 unixFile *proxy = pCtx->lockProxy;
7911 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7912 pFile->eFileLock = proxy->eFileLock;
7913 }else{
7914 /* conchHeld < 0 is lockless */
7917 return rc;
7922 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
7923 ** must be either NO_LOCK or SHARED_LOCK.
7925 ** If the locking level of the file descriptor is already at or below
7926 ** the requested locking level, this routine is a no-op.
7928 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
7929 unixFile *pFile = (unixFile*)id;
7930 int rc = proxyTakeConch(pFile);
7931 if( rc==SQLITE_OK ){
7932 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7933 if( pCtx->conchHeld>0 ){
7934 unixFile *proxy = pCtx->lockProxy;
7935 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7936 pFile->eFileLock = proxy->eFileLock;
7937 }else{
7938 /* conchHeld < 0 is lockless */
7941 return rc;
7945 ** Close a file that uses proxy locks.
7947 static int proxyClose(sqlite3_file *id) {
7948 if( ALWAYS(id) ){
7949 unixFile *pFile = (unixFile*)id;
7950 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7951 unixFile *lockProxy = pCtx->lockProxy;
7952 unixFile *conchFile = pCtx->conchFile;
7953 int rc = SQLITE_OK;
7955 if( lockProxy ){
7956 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7957 if( rc ) return rc;
7958 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7959 if( rc ) return rc;
7960 sqlite3_free(lockProxy);
7961 pCtx->lockProxy = 0;
7963 if( conchFile ){
7964 if( pCtx->conchHeld ){
7965 rc = proxyReleaseConch(pFile);
7966 if( rc ) return rc;
7968 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7969 if( rc ) return rc;
7970 sqlite3_free(conchFile);
7972 sqlite3DbFree(0, pCtx->lockProxyPath);
7973 sqlite3_free(pCtx->conchFilePath);
7974 sqlite3DbFree(0, pCtx->dbPath);
7975 /* restore the original locking context and pMethod then close it */
7976 pFile->lockingContext = pCtx->oldLockingContext;
7977 pFile->pMethod = pCtx->pOldMethod;
7978 sqlite3_free(pCtx);
7979 return pFile->pMethod->xClose(id);
7981 return SQLITE_OK;
7986 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
7988 ** The proxy locking style is intended for use with AFP filesystems.
7989 ** And since AFP is only supported on MacOSX, the proxy locking is also
7990 ** restricted to MacOSX.
7993 ******************* End of the proxy lock implementation **********************
7994 ******************************************************************************/
7997 ** Initialize the operating system interface.
7999 ** This routine registers all VFS implementations for unix-like operating
8000 ** systems. This routine, and the sqlite3_os_end() routine that follows,
8001 ** should be the only routines in this file that are visible from other
8002 ** files.
8004 ** This routine is called once during SQLite initialization and by a
8005 ** single thread. The memory allocation and mutex subsystems have not
8006 ** necessarily been initialized when this routine is called, and so they
8007 ** should not be used.
8009 int sqlite3_os_init(void){
8011 ** The following macro defines an initializer for an sqlite3_vfs object.
8012 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
8013 ** to the "finder" function. (pAppData is a pointer to a pointer because
8014 ** silly C90 rules prohibit a void* from being cast to a function pointer
8015 ** and so we have to go through the intermediate pointer to avoid problems
8016 ** when compiling with -pedantic-errors on GCC.)
8018 ** The FINDER parameter to this macro is the name of the pointer to the
8019 ** finder-function. The finder-function returns a pointer to the
8020 ** sqlite_io_methods object that implements the desired locking
8021 ** behaviors. See the division above that contains the IOMETHODS
8022 ** macro for addition information on finder-functions.
8024 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
8025 ** object. But the "autolockIoFinder" available on MacOSX does a little
8026 ** more than that; it looks at the filesystem type that hosts the
8027 ** database file and tries to choose an locking method appropriate for
8028 ** that filesystem time.
8030 #define UNIXVFS(VFSNAME, FINDER) { \
8031 3, /* iVersion */ \
8032 sizeof(unixFile), /* szOsFile */ \
8033 MAX_PATHNAME, /* mxPathname */ \
8034 0, /* pNext */ \
8035 VFSNAME, /* zName */ \
8036 (void*)&FINDER, /* pAppData */ \
8037 unixOpen, /* xOpen */ \
8038 unixDelete, /* xDelete */ \
8039 unixAccess, /* xAccess */ \
8040 unixFullPathname, /* xFullPathname */ \
8041 unixDlOpen, /* xDlOpen */ \
8042 unixDlError, /* xDlError */ \
8043 unixDlSym, /* xDlSym */ \
8044 unixDlClose, /* xDlClose */ \
8045 unixRandomness, /* xRandomness */ \
8046 unixSleep, /* xSleep */ \
8047 unixCurrentTime, /* xCurrentTime */ \
8048 unixGetLastError, /* xGetLastError */ \
8049 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
8050 unixSetSystemCall, /* xSetSystemCall */ \
8051 unixGetSystemCall, /* xGetSystemCall */ \
8052 unixNextSystemCall, /* xNextSystemCall */ \
8056 ** All default VFSes for unix are contained in the following array.
8058 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
8059 ** by the SQLite core when the VFS is registered. So the following
8060 ** array cannot be const.
8062 static sqlite3_vfs aVfs[] = {
8063 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
8064 UNIXVFS("unix", autolockIoFinder ),
8065 #elif OS_VXWORKS
8066 UNIXVFS("unix", vxworksIoFinder ),
8067 #else
8068 UNIXVFS("unix", posixIoFinder ),
8069 #endif
8070 UNIXVFS("unix-none", nolockIoFinder ),
8071 UNIXVFS("unix-dotfile", dotlockIoFinder ),
8072 UNIXVFS("unix-excl", posixIoFinder ),
8073 #if OS_VXWORKS
8074 UNIXVFS("unix-namedsem", semIoFinder ),
8075 #endif
8076 #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
8077 UNIXVFS("unix-posix", posixIoFinder ),
8078 #endif
8079 #if SQLITE_ENABLE_LOCKING_STYLE
8080 UNIXVFS("unix-flock", flockIoFinder ),
8081 #endif
8082 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
8083 UNIXVFS("unix-afp", afpIoFinder ),
8084 UNIXVFS("unix-nfs", nfsIoFinder ),
8085 UNIXVFS("unix-proxy", proxyIoFinder ),
8086 #endif
8088 unsigned int i; /* Loop counter */
8090 /* Double-check that the aSyscall[] array has been constructed
8091 ** correctly. See ticket [bb3a86e890c8e96ab] */
8092 assert( ArraySize(aSyscall)==29 );
8094 /* Register all VFSes defined in the aVfs[] array */
8095 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
8096 #ifdef SQLITE_DEFAULT_UNIX_VFS
8097 sqlite3_vfs_register(&aVfs[i],
8098 0==strcmp(aVfs[i].zName,SQLITE_DEFAULT_UNIX_VFS));
8099 #else
8100 sqlite3_vfs_register(&aVfs[i], i==0);
8101 #endif
8103 #ifdef SQLITE_OS_KV_OPTIONAL
8104 sqlite3KvvfsInit();
8105 #endif
8106 unixBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
8108 #ifndef SQLITE_OMIT_WAL
8109 /* Validate lock assumptions */
8110 assert( SQLITE_SHM_NLOCK==8 ); /* Number of available locks */
8111 assert( UNIX_SHM_BASE==120 ); /* Start of locking area */
8112 /* Locks:
8113 ** WRITE UNIX_SHM_BASE 120
8114 ** CKPT UNIX_SHM_BASE+1 121
8115 ** RECOVER UNIX_SHM_BASE+2 122
8116 ** READ-0 UNIX_SHM_BASE+3 123
8117 ** READ-1 UNIX_SHM_BASE+4 124
8118 ** READ-2 UNIX_SHM_BASE+5 125
8119 ** READ-3 UNIX_SHM_BASE+6 126
8120 ** READ-4 UNIX_SHM_BASE+7 127
8121 ** DMS UNIX_SHM_BASE+8 128
8123 assert( UNIX_SHM_DMS==128 ); /* Byte offset of the deadman-switch */
8124 #endif
8126 /* Initialize temp file dir array. */
8127 unixTempFileInit();
8129 return SQLITE_OK;
8133 ** Shutdown the operating system interface.
8135 ** Some operating systems might need to do some cleanup in this routine,
8136 ** to release dynamically allocated objects. But not on unix.
8137 ** This routine is a no-op for unix.
8139 int sqlite3_os_end(void){
8140 unixBigLock = 0;
8141 return SQLITE_OK;
8144 #endif /* SQLITE_OS_UNIX */