4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
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
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
53 ** 1. POSIX locking (the default),
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
70 # define SQLITE_ENABLE_LOCKING_STYLE 0
74 /* Use pread() and pwrite() if they are available */
75 #if defined(__APPLE__) || defined(__linux__)
77 # define HAVE_PWRITE 1
79 #if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
81 # define USE_PREAD64 1
82 #elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)
88 ** standard include files.
90 #include <sys/types.h> /* amalgamator: keep */
91 #include <sys/stat.h> /* amalgamator: keep */
93 #include <sys/ioctl.h>
94 #include <unistd.h> /* amalgamator: keep */
96 #include <sys/time.h> /* amalgamator: keep */
98 #if (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) \
99 && !defined(SQLITE_WASI)
100 # include <sys/mman.h>
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
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
131 # warning "gethostuuid() is disabled."
138 # include <sys/ioctl.h>
139 # include <semaphore.h>
141 #endif /* OS_VXWORKS */
143 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
144 # include <sys/mount.h>
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>
164 ** Default permissions when creating a new file
166 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
167 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
171 ** Default permissions when creating auto proxy dir
173 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
174 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
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.
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"? */
204 # if __LONG_MAX == 0x7fffffffL
214 #else /* !SQLITE_WASI */
218 #endif /* SQLITE_WASI */
221 # define osGetpid(X) (pid_t)1
223 /* Always cast the getpid() return type for compatibility with
224 ** kernel modules in VxWorks. */
225 # define osGetpid(X) (pid_t)getpid()
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
;
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 */
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() */
282 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
283 unsigned fsFlags
; /* cached details from statfs() */
285 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
286 unsigned iBusyTimeout
; /* Wait this many millisec on locks */
289 struct vxworksFileId
*pId
; /* Unique file ID */
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 */
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.
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 */
328 # define UNIXFILE_DIRSYNC 0x00
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.
344 # define O_LARGEFILE 0
346 #ifdef SQLITE_DISABLE_LFS
348 # define O_LARGEFILE 0
351 # define O_NOFOLLOW 0
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()
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
374 # define HAVE_MREMAP 0
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.
383 # define lseek lseek64
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 */
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?
450 #define osFstat(a,b,c) 0
452 { "fstat", (sqlite3_syscall_ptr
)fstat
, 0 },
453 #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
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 },
468 { "pread", (sqlite3_syscall_ptr
)0, 0 },
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 },
475 { "pread64", (sqlite3_syscall_ptr
)0, 0 },
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 },
485 { "pwrite", (sqlite3_syscall_ptr
)0, 0 },
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 },
493 { "pwrite64", (sqlite3_syscall_ptr
)0, 0 },
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 },
501 { "fchmod", (sqlite3_syscall_ptr
)0, 0 },
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 },
508 { "fallocate", (sqlite3_syscall_ptr
)0, 0 },
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 },
527 { "fchown", (sqlite3_syscall_ptr
)0, 0 },
529 #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
531 #if defined(HAVE_FCHOWN)
532 { "geteuid", (sqlite3_syscall_ptr
)geteuid
, 0 },
534 { "geteuid", (sqlite3_syscall_ptr
)0, 0 },
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 },
542 { "mmap", (sqlite3_syscall_ptr
)0, 0 },
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 },
550 { "munmap", (sqlite3_syscall_ptr
)0, 0 },
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 },
557 { "mremap", (sqlite3_syscall_ptr
)0, 0 },
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 },
564 { "getpagesize", (sqlite3_syscall_ptr
)0, 0 },
566 #define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
568 #if defined(HAVE_READLINK)
569 { "readlink", (sqlite3_syscall_ptr
)readlink
, 0 },
571 { "readlink", (sqlite3_syscall_ptr
)0, 0 },
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 },
578 { "lstat", (sqlite3_syscall_ptr
)0, 0 },
580 #define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
582 #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
584 { "ioctl", (sqlite3_syscall_ptr
)(int(*)(int, int, ...))ioctl
, 0 },
585 #define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent)
587 { "ioctl", (sqlite3_syscall_ptr
)ioctl
, 0 },
588 #define osIoctl ((int(*)(int,unsigned long,...))aSyscall[28].pCurrent)
591 { "ioctl", (sqlite3_syscall_ptr
)0, 0 },
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
);
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 */
622 int rc
= SQLITE_NOTFOUND
;
624 UNUSED_PARAMETER(pNotUsed
);
626 /* If no zName is given, restore all system calls to their default
627 ** settings and return NULL
630 for(i
=0; i
<sizeof(aSyscall
)/sizeof(aSyscall
[0]); i
++){
631 if( aSyscall
[i
].pDefault
){
632 aSyscall
[i
].pCurrent
= aSyscall
[i
].pDefault
;
636 /* If zName is specified, operate on only the one system call
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
;
645 if( pNewFunc
==0 ) pNewFunc
= aSyscall
[i
].pDefault
;
646 aSyscall
[i
].pCurrent
= pNewFunc
;
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
,
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
;
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
678 static const char *unixNextSystemCall(sqlite3_vfs
*p
, const char *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
;
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
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
){
721 mode_t m2
= m
? m
: SQLITE_DEFAULT_FILE_PERMISSIONS
;
723 #if defined(O_CLOEXEC)
724 fd
= osOpen(z
,f
|O_CLOEXEC
,m2
);
729 if( errno
==EINTR
) continue;
732 if( fd
>=SQLITE_MINIMUM_FILE_DESCRIPTOR
) break;
733 if( (f
& (O_EXCL
|O_CREAT
))==(O_EXCL
|O_CREAT
) ){
737 sqlite3_log(SQLITE_WARNING
,
738 "attempt to open \"%s\" as file descriptor %d", z
, fd
);
740 if( osOpen("/dev/null", O_RDONLY
, m
)<0 ) break;
745 if( osFstat(fd
, &statbuf
)==0
746 && statbuf
.st_size
==0
747 && (statbuf
.st_mode
&0777)!=m
752 #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
753 osFcntl(fd
, F_SETFD
, osFcntl(fd
, F_GETFD
, 0) | FD_CLOEXEC
);
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()
770 ** assert( unixMutexHeld() );
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
);
794 static int unixMutexHeld(void) {
795 return sqlite3_mutex_held(unixBigLock
);
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
){
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";
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
827 static int lockTrace(int fd
, int op
, struct flock
*p
){
828 char *zOpName
, *zType
;
833 }else if( op
==F_SETLK
){
836 s
= osFcntl(fd
, op
, p
);
837 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd
, op
, s
);
840 if( p
->l_type
==F_RDLCK
){
842 }else if( p
->l_type
==F_WRLCK
){
844 }else if( p
->l_type
==F_UNLCK
){
849 assert( p
->l_whence
==SEEK_SET
);
850 s
= osFcntl(fd
, op
, p
);
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
,
855 if( s
==(-1) && op
==F_SETLK
&& (p
->l_type
==F_RDLCK
|| p
->l_type
==F_WRLCK
) ){
858 osFcntl(fd
, F_GETLK
, &l2
);
859 if( l2
.l_type
==F_RDLCK
){
861 }else if( l2
.l_type
==F_WRLCK
){
863 }else if( l2
.l_type
==F_UNLCK
){
868 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
869 zType
, (int)l2
.l_start
, (int)l2
.l_len
, (int)l2
.l_pid
);
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
){
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
892 if( sz
>(sqlite3_int64
)0x7FFFFFFF ){
896 do{ rc
= osFtruncate(h
,sz
); }while( rc
<0 && errno
==EINTR
);
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
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
) {
922 /* random NFS retry error, unless during file system support
923 * introspection, in which it actually means what it says */
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
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 */
961 ** All unique filenames are held on a linked list headed by this
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
){
981 while( n
>1 && z
[n
-1]=='/' ){ n
--; }
982 for(i
=j
=0; i
<n
; i
++){
984 if( z
[i
+1]=='/' ) continue;
985 if( z
[i
+1]=='.' && i
+2<n
&& z
[i
+2]=='/' ){
989 if( z
[i
+1]=='.' && i
+3<n
&& z
[i
+2]=='.' && z
[i
+3]=='/' ){
990 while( j
>0 && z
[j
-1]!='/' ){ 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
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.
1031 for(pCandidate
=vxworksFileList
; pCandidate
; pCandidate
=pCandidate
->pNext
){
1032 if( pCandidate
->nName
==n
1033 && memcmp(pCandidate
->zCanonicalName
, pNew
->zCanonicalName
, n
)==0
1042 /* No match was found. We will make a new file ID */
1045 pNew
->pNext
= vxworksFileList
;
1046 vxworksFileList
= 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
){
1057 assert( pId
->nRef
>0 );
1060 struct vxworksFileId
**pp
;
1061 for(pp
=&vxworksFileList
; *pp
&& *pp
!=pId
; pp
= &((*pp
)->pNext
)){}
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
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
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
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.
1168 dev_t dev
; /* Device number */
1170 struct vxworksFileId
*pId
; /* Unique file ID for vxworks. */
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 */
1184 ** An instance of the following structure is allocated for each open
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.
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 */
1224 sem_t
*pSem
; /* Named POSIX semaphore */
1225 char aSemName
[MAX_PATHNAME
+2]; /* Name of that semaphore */
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 */
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
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
);
1254 ** This function - unixLogErrorAtLine(), is only ever called via the macro
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
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,
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)
1284 memset(aErr
, 0, sizeof(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 ** Forum post 3f13857fa4062301 reports that the Android SDK may use
1300 ** int-type return, depending on its version.
1302 #if (defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)) \
1303 && !defined(ANDROID) && !defined(__ANDROID__)
1306 strerror_r(iErrno
, aErr
, sizeof(aErr
)-1);
1308 #elif SQLITE_THREADSAFE
1309 /* This is a threadsafe build, but strerror_r() is not available. */
1312 /* Non-threadsafe build, use strerror(). */
1313 zErr
= strerror(iErrno
);
1316 if( zPath
==0 ) zPath
= "";
1317 sqlite3_log(errcode
,
1318 "os_unix.c:%d: (%d) %s(%s) - %s",
1319 iLine
, iErrno
, zFunc
, zPath
, zErr
1326 ** Close a file descriptor.
1328 ** We assume that close() almost always works, since it is only in a
1329 ** very sick application or on a very sick platform that it might fail.
1330 ** If it does fail, simply leak the file descriptor, but do log the
1333 ** Note that it is not safe to retry close() after EINTR since the
1334 ** file descriptor might have already been reused by another thread.
1335 ** So we don't even try to recover from an EINTR. Just log the error
1338 static void robust_close(unixFile
*pFile
, int h
, int lineno
){
1340 unixLogErrorAtLine(SQLITE_IOERR_CLOSE
, "close",
1341 pFile
? pFile
->zPath
: 0, lineno
);
1346 ** Set the pFile->lastErrno. Do this in a subroutine as that provides
1347 ** a convenient place to set a breakpoint.
1349 static void storeLastErrno(unixFile
*pFile
, int error
){
1350 pFile
->lastErrno
= error
;
1354 ** Close all file descriptors accumulated in the unixInodeInfo->pUnused list.
1356 static void closePendingFds(unixFile
*pFile
){
1357 unixInodeInfo
*pInode
= pFile
->pInode
;
1359 UnixUnusedFd
*pNext
;
1360 assert( unixFileMutexHeld(pFile
) );
1361 for(p
=pInode
->pUnused
; p
; p
=pNext
){
1363 robust_close(pFile
, p
->fd
, __LINE__
);
1366 pInode
->pUnused
= 0;
1370 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
1372 ** The global mutex must be held when this routine is called, but the mutex
1373 ** on the inode being deleted must NOT be held.
1375 static void releaseInodeInfo(unixFile
*pFile
){
1376 unixInodeInfo
*pInode
= pFile
->pInode
;
1377 assert( unixMutexHeld() );
1378 assert( unixFileMutexNotheld(pFile
) );
1379 if( ALWAYS(pInode
) ){
1381 if( pInode
->nRef
==0 ){
1382 assert( pInode
->pShmNode
==0 );
1383 sqlite3_mutex_enter(pInode
->pLockMutex
);
1384 closePendingFds(pFile
);
1385 sqlite3_mutex_leave(pInode
->pLockMutex
);
1386 if( pInode
->pPrev
){
1387 assert( pInode
->pPrev
->pNext
==pInode
);
1388 pInode
->pPrev
->pNext
= pInode
->pNext
;
1390 assert( inodeList
==pInode
);
1391 inodeList
= pInode
->pNext
;
1393 if( pInode
->pNext
){
1394 assert( pInode
->pNext
->pPrev
==pInode
);
1395 pInode
->pNext
->pPrev
= pInode
->pPrev
;
1397 sqlite3_mutex_free(pInode
->pLockMutex
);
1398 sqlite3_free(pInode
);
1404 ** Given a file descriptor, locate the unixInodeInfo object that
1405 ** describes that file descriptor. Create a new one if necessary. The
1406 ** return value might be uninitialized if an error occurs.
1408 ** The global mutex must held when calling this routine.
1410 ** Return an appropriate error code.
1412 static int findInodeInfo(
1413 unixFile
*pFile
, /* Unix file with file desc used in the key */
1414 unixInodeInfo
**ppInode
/* Return the unixInodeInfo object here */
1416 int rc
; /* System call return code */
1417 int fd
; /* The file descriptor for pFile */
1418 struct unixFileId fileId
; /* Lookup key for the unixInodeInfo */
1419 struct stat statbuf
; /* Low-level file information */
1420 unixInodeInfo
*pInode
= 0; /* Candidate unixInodeInfo object */
1422 assert( unixMutexHeld() );
1424 /* Get low-level information about the file that we can used to
1425 ** create a unique name for the file.
1428 rc
= osFstat(fd
, &statbuf
);
1430 storeLastErrno(pFile
, errno
);
1431 #if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
1432 if( pFile
->lastErrno
==EOVERFLOW
) return SQLITE_NOLFS
;
1434 return SQLITE_IOERR
;
1438 /* On OS X on an msdos filesystem, the inode number is reported
1439 ** incorrectly for zero-size files. See ticket #3260. To work
1440 ** around this problem (we consider it a bug in OS X, not SQLite)
1441 ** we always increase the file size to 1 by writing a single byte
1442 ** prior to accessing the inode number. The one byte written is
1443 ** an ASCII 'S' character which also happens to be the first byte
1444 ** in the header of every SQLite database. In this way, if there
1445 ** is a race condition such that another thread has already populated
1446 ** the first page of the database, no damage is done.
1448 if( statbuf
.st_size
==0 && (pFile
->fsFlags
& SQLITE_FSFLAGS_IS_MSDOS
)!=0 ){
1449 do{ rc
= osWrite(fd
, "S", 1); }while( rc
<0 && errno
==EINTR
);
1451 storeLastErrno(pFile
, errno
);
1452 return SQLITE_IOERR
;
1454 rc
= osFstat(fd
, &statbuf
);
1456 storeLastErrno(pFile
, errno
);
1457 return SQLITE_IOERR
;
1462 memset(&fileId
, 0, sizeof(fileId
));
1463 fileId
.dev
= statbuf
.st_dev
;
1465 fileId
.pId
= pFile
->pId
;
1467 fileId
.ino
= (u64
)statbuf
.st_ino
;
1469 assert( unixMutexHeld() );
1471 while( pInode
&& memcmp(&fileId
, &pInode
->fileId
, sizeof(fileId
)) ){
1472 pInode
= pInode
->pNext
;
1475 pInode
= sqlite3_malloc64( sizeof(*pInode
) );
1477 return SQLITE_NOMEM_BKPT
;
1479 memset(pInode
, 0, sizeof(*pInode
));
1480 memcpy(&pInode
->fileId
, &fileId
, sizeof(fileId
));
1481 if( sqlite3GlobalConfig
.bCoreMutex
){
1482 pInode
->pLockMutex
= sqlite3_mutex_alloc(SQLITE_MUTEX_FAST
);
1483 if( pInode
->pLockMutex
==0 ){
1484 sqlite3_free(pInode
);
1485 return SQLITE_NOMEM_BKPT
;
1489 assert( unixMutexHeld() );
1490 pInode
->pNext
= inodeList
;
1492 if( inodeList
) inodeList
->pPrev
= pInode
;
1502 ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1504 static int fileHasMoved(unixFile
*pFile
){
1506 return pFile
->pInode
!=0 && pFile
->pId
!=pFile
->pInode
->fileId
.pId
;
1509 return pFile
->pInode
!=0 &&
1510 (osStat(pFile
->zPath
, &buf
)!=0
1511 || (u64
)buf
.st_ino
!=pFile
->pInode
->fileId
.ino
);
1517 ** Check a unixFile that is a database. Verify the following:
1519 ** (1) There is exactly one hard link on the file
1520 ** (2) The file is not a symbolic link
1521 ** (3) The file has not been renamed or unlinked
1523 ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1525 static void verifyDbFile(unixFile
*pFile
){
1529 /* These verifications occurs for the main database only */
1530 if( pFile
->ctrlFlags
& UNIXFILE_NOLOCK
) return;
1532 rc
= osFstat(pFile
->h
, &buf
);
1534 sqlite3_log(SQLITE_WARNING
, "cannot fstat db file %s", pFile
->zPath
);
1537 if( buf
.st_nlink
==0 ){
1538 sqlite3_log(SQLITE_WARNING
, "file unlinked while open: %s", pFile
->zPath
);
1541 if( buf
.st_nlink
>1 ){
1542 sqlite3_log(SQLITE_WARNING
, "multiple links to file: %s", pFile
->zPath
);
1545 if( fileHasMoved(pFile
) ){
1546 sqlite3_log(SQLITE_WARNING
, "file renamed while open: %s", pFile
->zPath
);
1553 ** This routine checks if there is a RESERVED lock held on the specified
1554 ** file by this or any other process. If such a lock is held, set *pResOut
1555 ** to a non-zero value otherwise *pResOut is set to zero. The return value
1556 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1558 static int unixCheckReservedLock(sqlite3_file
*id
, int *pResOut
){
1561 unixFile
*pFile
= (unixFile
*)id
;
1563 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK
; );
1566 assert( pFile
->eFileLock
<=SHARED_LOCK
);
1567 sqlite3_mutex_enter(pFile
->pInode
->pLockMutex
);
1569 /* Check if a thread in this process holds such a lock */
1570 if( pFile
->pInode
->eFileLock
>SHARED_LOCK
){
1574 /* Otherwise see if some other process holds it.
1577 if( !reserved
&& !pFile
->pInode
->bProcessLock
){
1579 lock
.l_whence
= SEEK_SET
;
1580 lock
.l_start
= RESERVED_BYTE
;
1582 lock
.l_type
= F_WRLCK
;
1583 if( osFcntl(pFile
->h
, F_GETLK
, &lock
) ){
1584 rc
= SQLITE_IOERR_CHECKRESERVEDLOCK
;
1585 storeLastErrno(pFile
, errno
);
1586 } else if( lock
.l_type
!=F_UNLCK
){
1592 sqlite3_mutex_leave(pFile
->pInode
->pLockMutex
);
1593 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile
->h
, rc
, reserved
));
1595 *pResOut
= reserved
;
1599 /* Forward declaration*/
1600 static int unixSleep(sqlite3_vfs
*,int);
1603 ** Set a posix-advisory-lock.
1605 ** There are two versions of this routine. If compiled with
1606 ** SQLITE_ENABLE_SETLK_TIMEOUT then the routine has an extra parameter
1607 ** which is a pointer to a unixFile. If the unixFile->iBusyTimeout
1608 ** value is set, then it is the number of milliseconds to wait before
1609 ** failing the lock. The iBusyTimeout value is always reset back to
1610 ** zero on each call.
1612 ** If SQLITE_ENABLE_SETLK_TIMEOUT is not defined, then do a non-blocking
1613 ** attempt to set the lock.
1615 #ifndef SQLITE_ENABLE_SETLK_TIMEOUT
1616 # define osSetPosixAdvisoryLock(h,x,t) osFcntl(h,F_SETLK,x)
1618 static int osSetPosixAdvisoryLock(
1619 int h
, /* The file descriptor on which to take the lock */
1620 struct flock
*pLock
, /* The description of the lock */
1621 unixFile
*pFile
/* Structure holding timeout value */
1623 int tm
= pFile
->iBusyTimeout
;
1624 int rc
= osFcntl(h
,F_SETLK
,pLock
);
1625 while( rc
<0 && tm
>0 ){
1626 /* On systems that support some kind of blocking file lock with a timeout,
1627 ** make appropriate changes here to invoke that blocking file lock. On
1628 ** generic posix, however, there is no such API. So we simply try the
1629 ** lock once every millisecond until either the timeout expires, or until
1630 ** the lock is obtained. */
1632 rc
= osFcntl(h
,F_SETLK
,pLock
);
1637 #endif /* SQLITE_ENABLE_SETLK_TIMEOUT */
1641 ** Attempt to set a system-lock on the file pFile. The lock is
1642 ** described by pLock.
1644 ** If the pFile was opened read/write from unix-excl, then the only lock
1645 ** ever obtained is an exclusive lock, and it is obtained exactly once
1646 ** the first time any lock is attempted. All subsequent system locking
1647 ** operations become no-ops. Locking operations still happen internally,
1648 ** in order to coordinate access between separate database connections
1649 ** within this process, but all of that is handled in memory and the
1650 ** operating system does not participate.
1652 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1653 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1654 ** and is read-only.
1656 ** Zero is returned if the call completes successfully, or -1 if a call
1657 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
1659 static int unixFileLock(unixFile
*pFile
, struct flock
*pLock
){
1661 unixInodeInfo
*pInode
= pFile
->pInode
;
1662 assert( pInode
!=0 );
1663 assert( sqlite3_mutex_held(pInode
->pLockMutex
) );
1664 if( (pFile
->ctrlFlags
& (UNIXFILE_EXCL
|UNIXFILE_RDONLY
))==UNIXFILE_EXCL
){
1665 if( pInode
->bProcessLock
==0 ){
1667 assert( pInode
->nLock
==0 );
1668 lock
.l_whence
= SEEK_SET
;
1669 lock
.l_start
= SHARED_FIRST
;
1670 lock
.l_len
= SHARED_SIZE
;
1671 lock
.l_type
= F_WRLCK
;
1672 rc
= osSetPosixAdvisoryLock(pFile
->h
, &lock
, pFile
);
1673 if( rc
<0 ) return rc
;
1674 pInode
->bProcessLock
= 1;
1680 rc
= osSetPosixAdvisoryLock(pFile
->h
, pLock
, pFile
);
1686 ** Lock the file with the lock specified by parameter eFileLock - one
1687 ** of the following:
1690 ** (2) RESERVED_LOCK
1692 ** (4) EXCLUSIVE_LOCK
1694 ** Sometimes when requesting one lock state, additional lock states
1695 ** are inserted in between. The locking might fail on one of the later
1696 ** transitions leaving the lock state different from what it started but
1697 ** still short of its goal. The following chart shows the allowed
1698 ** transitions and the inserted intermediate states:
1700 ** UNLOCKED -> SHARED
1701 ** SHARED -> RESERVED
1702 ** SHARED -> EXCLUSIVE
1703 ** RESERVED -> (PENDING) -> EXCLUSIVE
1704 ** PENDING -> EXCLUSIVE
1706 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
1707 ** routine to lower a locking level.
1709 static int unixLock(sqlite3_file
*id
, int eFileLock
){
1710 /* The following describes the implementation of the various locks and
1711 ** lock transitions in terms of the POSIX advisory shared and exclusive
1712 ** lock primitives (called read-locks and write-locks below, to avoid
1713 ** confusion with SQLite lock names). The algorithms are complicated
1714 ** slightly in order to be compatible with Windows95 systems simultaneously
1715 ** accessing the same database file, in case that is ever required.
1717 ** Symbols defined in os.h identify the 'pending byte' and the 'reserved
1718 ** byte', each single bytes at well known offsets, and the 'shared byte
1719 ** range', a range of 510 bytes at a well known offset.
1721 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1722 ** byte'. If this is successful, 'shared byte range' is read-locked
1723 ** and the lock on the 'pending byte' released. (Legacy note: When
1724 ** SQLite was first developed, Windows95 systems were still very common,
1725 ** and Windows95 lacks a shared-lock capability. So on Windows95, a
1726 ** single randomly selected by from the 'shared byte range' is locked.
1727 ** Windows95 is now pretty much extinct, but this work-around for the
1728 ** lack of shared-locks on Windows95 lives on, for backwards
1731 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1732 ** A RESERVED lock is implemented by grabbing a write-lock on the
1735 ** An EXCLUSIVE lock may only be requested after either a SHARED or
1736 ** RESERVED lock is held. An EXCLUSIVE lock is implemented by obtaining
1737 ** a write-lock on the entire 'shared byte range'. Since all other locks
1738 ** require a read-lock on one of the bytes within this range, this ensures
1739 ** that no other locks are held on the database.
1741 ** If a process that holds a RESERVED lock requests an EXCLUSIVE, then
1742 ** a PENDING lock is obtained first. A PENDING lock is implemented by
1743 ** obtaining a write-lock on the 'pending byte'. This ensures that no new
1744 ** SHARED locks can be obtained, but existing SHARED locks are allowed to
1745 ** persist. If the call to this function fails to obtain the EXCLUSIVE
1746 ** lock in this case, it holds the PENDING lock instead. The client may
1747 ** then re-attempt the EXCLUSIVE lock later on, after existing SHARED
1748 ** locks have cleared.
1751 unixFile
*pFile
= (unixFile
*)id
;
1752 unixInodeInfo
*pInode
;
1757 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile
->h
,
1758 azFileLock(eFileLock
), azFileLock(pFile
->eFileLock
),
1759 azFileLock(pFile
->pInode
->eFileLock
), pFile
->pInode
->nShared
,
1762 /* If there is already a lock of this type or more restrictive on the
1763 ** unixFile, do nothing. Don't use the end_lock: exit path, as
1764 ** unixEnterMutex() hasn't been called yet.
1766 if( pFile
->eFileLock
>=eFileLock
){
1767 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile
->h
,
1768 azFileLock(eFileLock
)));
1772 /* Make sure the locking sequence is correct.
1773 ** (1) We never move from unlocked to anything higher than shared lock.
1774 ** (2) SQLite never explicitly requests a pending lock.
1775 ** (3) A shared lock is always held when a reserve lock is requested.
1777 assert( pFile
->eFileLock
!=NO_LOCK
|| eFileLock
==SHARED_LOCK
);
1778 assert( eFileLock
!=PENDING_LOCK
);
1779 assert( eFileLock
!=RESERVED_LOCK
|| pFile
->eFileLock
==SHARED_LOCK
);
1781 /* This mutex is needed because pFile->pInode is shared across threads
1783 pInode
= pFile
->pInode
;
1784 sqlite3_mutex_enter(pInode
->pLockMutex
);
1786 /* If some thread using this PID has a lock via a different unixFile*
1787 ** handle that precludes the requested lock, return BUSY.
1789 if( (pFile
->eFileLock
!=pInode
->eFileLock
&&
1790 (pInode
->eFileLock
>=PENDING_LOCK
|| eFileLock
>SHARED_LOCK
))
1796 /* If a SHARED lock is requested, and some thread using this PID already
1797 ** has a SHARED or RESERVED lock, then increment reference counts and
1798 ** return SQLITE_OK.
1800 if( eFileLock
==SHARED_LOCK
&&
1801 (pInode
->eFileLock
==SHARED_LOCK
|| pInode
->eFileLock
==RESERVED_LOCK
) ){
1802 assert( eFileLock
==SHARED_LOCK
);
1803 assert( pFile
->eFileLock
==0 );
1804 assert( pInode
->nShared
>0 );
1805 pFile
->eFileLock
= SHARED_LOCK
;
1812 /* A PENDING lock is needed before acquiring a SHARED lock and before
1813 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1817 lock
.l_whence
= SEEK_SET
;
1818 if( eFileLock
==SHARED_LOCK
1819 || (eFileLock
==EXCLUSIVE_LOCK
&& pFile
->eFileLock
==RESERVED_LOCK
)
1821 lock
.l_type
= (eFileLock
==SHARED_LOCK
?F_RDLCK
:F_WRLCK
);
1822 lock
.l_start
= PENDING_BYTE
;
1823 if( unixFileLock(pFile
, &lock
) ){
1825 rc
= sqliteErrorFromPosixError(tErrno
, SQLITE_IOERR_LOCK
);
1826 if( rc
!=SQLITE_BUSY
){
1827 storeLastErrno(pFile
, tErrno
);
1830 }else if( eFileLock
==EXCLUSIVE_LOCK
){
1831 pFile
->eFileLock
= PENDING_LOCK
;
1832 pInode
->eFileLock
= PENDING_LOCK
;
1837 /* If control gets to this point, then actually go ahead and make
1838 ** operating system calls for the specified lock.
1840 if( eFileLock
==SHARED_LOCK
){
1841 assert( pInode
->nShared
==0 );
1842 assert( pInode
->eFileLock
==0 );
1843 assert( rc
==SQLITE_OK
);
1845 /* Now get the read-lock */
1846 lock
.l_start
= SHARED_FIRST
;
1847 lock
.l_len
= SHARED_SIZE
;
1848 if( unixFileLock(pFile
, &lock
) ){
1850 rc
= sqliteErrorFromPosixError(tErrno
, SQLITE_IOERR_LOCK
);
1853 /* Drop the temporary PENDING lock */
1854 lock
.l_start
= PENDING_BYTE
;
1856 lock
.l_type
= F_UNLCK
;
1857 if( unixFileLock(pFile
, &lock
) && rc
==SQLITE_OK
){
1858 /* This could happen with a network mount */
1860 rc
= SQLITE_IOERR_UNLOCK
;
1864 if( rc
!=SQLITE_BUSY
){
1865 storeLastErrno(pFile
, tErrno
);
1869 pFile
->eFileLock
= SHARED_LOCK
;
1871 pInode
->nShared
= 1;
1873 }else if( eFileLock
==EXCLUSIVE_LOCK
&& pInode
->nShared
>1 ){
1874 /* We are trying for an exclusive lock but another thread in this
1875 ** same process is still holding a shared lock. */
1878 /* The request was for a RESERVED or EXCLUSIVE lock. It is
1879 ** assumed that there is a SHARED or greater lock on the file
1882 assert( 0!=pFile
->eFileLock
);
1883 lock
.l_type
= F_WRLCK
;
1885 assert( eFileLock
==RESERVED_LOCK
|| eFileLock
==EXCLUSIVE_LOCK
);
1886 if( eFileLock
==RESERVED_LOCK
){
1887 lock
.l_start
= RESERVED_BYTE
;
1890 lock
.l_start
= SHARED_FIRST
;
1891 lock
.l_len
= SHARED_SIZE
;
1894 if( unixFileLock(pFile
, &lock
) ){
1896 rc
= sqliteErrorFromPosixError(tErrno
, SQLITE_IOERR_LOCK
);
1897 if( rc
!=SQLITE_BUSY
){
1898 storeLastErrno(pFile
, tErrno
);
1905 /* Set up the transaction-counter change checking flags when
1906 ** transitioning from a SHARED to a RESERVED lock. The change
1907 ** from SHARED to RESERVED marks the beginning of a normal
1908 ** write operation (not a hot journal rollback).
1911 && pFile
->eFileLock
<=SHARED_LOCK
1912 && eFileLock
==RESERVED_LOCK
1914 pFile
->transCntrChng
= 0;
1915 pFile
->dbUpdate
= 0;
1916 pFile
->inNormalWrite
= 1;
1920 if( rc
==SQLITE_OK
){
1921 pFile
->eFileLock
= eFileLock
;
1922 pInode
->eFileLock
= eFileLock
;
1926 sqlite3_mutex_leave(pInode
->pLockMutex
);
1927 OSTRACE(("LOCK %d %s %s (unix)\n", pFile
->h
, azFileLock(eFileLock
),
1928 rc
==SQLITE_OK
? "ok" : "failed"));
1933 ** Add the file descriptor used by file handle pFile to the corresponding
1936 static void setPendingFd(unixFile
*pFile
){
1937 unixInodeInfo
*pInode
= pFile
->pInode
;
1938 UnixUnusedFd
*p
= pFile
->pPreallocatedUnused
;
1939 assert( unixFileMutexHeld(pFile
) );
1940 p
->pNext
= pInode
->pUnused
;
1941 pInode
->pUnused
= p
;
1943 pFile
->pPreallocatedUnused
= 0;
1947 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
1948 ** must be either NO_LOCK or SHARED_LOCK.
1950 ** If the locking level of the file descriptor is already at or below
1951 ** the requested locking level, this routine is a no-op.
1953 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1954 ** the byte range is divided into 2 parts and the first part is unlocked then
1955 ** set to a read lock, then the other part is simply unlocked. This works
1956 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1957 ** remove the write lock on a region when a read lock is set.
1959 static int posixUnlock(sqlite3_file
*id
, int eFileLock
, int handleNFSUnlock
){
1960 unixFile
*pFile
= (unixFile
*)id
;
1961 unixInodeInfo
*pInode
;
1966 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile
->h
, eFileLock
,
1967 pFile
->eFileLock
, pFile
->pInode
->eFileLock
, pFile
->pInode
->nShared
,
1970 assert( eFileLock
<=SHARED_LOCK
);
1971 if( pFile
->eFileLock
<=eFileLock
){
1974 pInode
= pFile
->pInode
;
1975 sqlite3_mutex_enter(pInode
->pLockMutex
);
1976 assert( pInode
->nShared
!=0 );
1977 if( pFile
->eFileLock
>SHARED_LOCK
){
1978 assert( pInode
->eFileLock
==pFile
->eFileLock
);
1981 /* When reducing a lock such that other processes can start
1982 ** reading the database file again, make sure that the
1983 ** transaction counter was updated if any part of the database
1984 ** file changed. If the transaction counter is not updated,
1985 ** other connections to the same file might not realize that
1986 ** the file has changed and hence might not know to flush their
1987 ** cache. The use of a stale cache can lead to database corruption.
1989 pFile
->inNormalWrite
= 0;
1992 /* downgrading to a shared lock on NFS involves clearing the write lock
1993 ** before establishing the readlock - to avoid a race condition we downgrade
1994 ** the lock in 2 blocks, so that part of the range will be covered by a
1995 ** write lock until the rest is covered by a read lock:
2001 if( eFileLock
==SHARED_LOCK
){
2002 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
2003 (void)handleNFSUnlock
;
2004 assert( handleNFSUnlock
==0 );
2006 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2007 if( handleNFSUnlock
){
2008 int tErrno
; /* Error code from system call errors */
2009 off_t divSize
= SHARED_SIZE
- 1;
2011 lock
.l_type
= F_UNLCK
;
2012 lock
.l_whence
= SEEK_SET
;
2013 lock
.l_start
= SHARED_FIRST
;
2014 lock
.l_len
= divSize
;
2015 if( unixFileLock(pFile
, &lock
)==(-1) ){
2017 rc
= SQLITE_IOERR_UNLOCK
;
2018 storeLastErrno(pFile
, tErrno
);
2021 lock
.l_type
= F_RDLCK
;
2022 lock
.l_whence
= SEEK_SET
;
2023 lock
.l_start
= SHARED_FIRST
;
2024 lock
.l_len
= divSize
;
2025 if( unixFileLock(pFile
, &lock
)==(-1) ){
2027 rc
= sqliteErrorFromPosixError(tErrno
, SQLITE_IOERR_RDLOCK
);
2028 if( IS_LOCK_ERROR(rc
) ){
2029 storeLastErrno(pFile
, tErrno
);
2033 lock
.l_type
= F_UNLCK
;
2034 lock
.l_whence
= SEEK_SET
;
2035 lock
.l_start
= SHARED_FIRST
+divSize
;
2036 lock
.l_len
= SHARED_SIZE
-divSize
;
2037 if( unixFileLock(pFile
, &lock
)==(-1) ){
2039 rc
= SQLITE_IOERR_UNLOCK
;
2040 storeLastErrno(pFile
, tErrno
);
2044 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2046 lock
.l_type
= F_RDLCK
;
2047 lock
.l_whence
= SEEK_SET
;
2048 lock
.l_start
= SHARED_FIRST
;
2049 lock
.l_len
= SHARED_SIZE
;
2050 if( unixFileLock(pFile
, &lock
) ){
2051 /* In theory, the call to unixFileLock() cannot fail because another
2052 ** process is holding an incompatible lock. If it does, this
2053 ** indicates that the other process is not following the locking
2054 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
2055 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
2056 ** an assert to fail). */
2057 rc
= SQLITE_IOERR_RDLOCK
;
2058 storeLastErrno(pFile
, errno
);
2063 lock
.l_type
= F_UNLCK
;
2064 lock
.l_whence
= SEEK_SET
;
2065 lock
.l_start
= PENDING_BYTE
;
2066 lock
.l_len
= 2L; assert( PENDING_BYTE
+1==RESERVED_BYTE
);
2067 if( unixFileLock(pFile
, &lock
)==0 ){
2068 pInode
->eFileLock
= SHARED_LOCK
;
2070 rc
= SQLITE_IOERR_UNLOCK
;
2071 storeLastErrno(pFile
, errno
);
2075 if( eFileLock
==NO_LOCK
){
2076 /* Decrement the shared lock counter. Release the lock using an
2077 ** OS call only when all threads in this same process have released
2081 if( pInode
->nShared
==0 ){
2082 lock
.l_type
= F_UNLCK
;
2083 lock
.l_whence
= SEEK_SET
;
2084 lock
.l_start
= lock
.l_len
= 0L;
2085 if( unixFileLock(pFile
, &lock
)==0 ){
2086 pInode
->eFileLock
= NO_LOCK
;
2088 rc
= SQLITE_IOERR_UNLOCK
;
2089 storeLastErrno(pFile
, errno
);
2090 pInode
->eFileLock
= NO_LOCK
;
2091 pFile
->eFileLock
= NO_LOCK
;
2095 /* Decrement the count of locks against this same file. When the
2096 ** count reaches zero, close any other file descriptors whose close
2097 ** was deferred because of outstanding locks.
2100 assert( pInode
->nLock
>=0 );
2101 if( pInode
->nLock
==0 ) closePendingFds(pFile
);
2105 sqlite3_mutex_leave(pInode
->pLockMutex
);
2106 if( rc
==SQLITE_OK
){
2107 pFile
->eFileLock
= eFileLock
;
2113 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
2114 ** must be either NO_LOCK or SHARED_LOCK.
2116 ** If the locking level of the file descriptor is already at or below
2117 ** the requested locking level, this routine is a no-op.
2119 static int unixUnlock(sqlite3_file
*id
, int eFileLock
){
2120 #if SQLITE_MAX_MMAP_SIZE>0
2121 assert( eFileLock
==SHARED_LOCK
|| ((unixFile
*)id
)->nFetchOut
==0 );
2123 return posixUnlock(id
, eFileLock
, 0);
2126 #if SQLITE_MAX_MMAP_SIZE>0
2127 static int unixMapfile(unixFile
*pFd
, i64 nByte
);
2128 static void unixUnmapfile(unixFile
*pFd
);
2132 ** This function performs the parts of the "close file" operation
2133 ** common to all locking schemes. It closes the directory and file
2134 ** handles, if they are valid, and sets all fields of the unixFile
2137 ** It is *not* necessary to hold the mutex when this routine is called,
2138 ** even on VxWorks. A mutex will be acquired on VxWorks by the
2139 ** vxworksReleaseFileId() routine.
2141 static int closeUnixFile(sqlite3_file
*id
){
2142 unixFile
*pFile
= (unixFile
*)id
;
2143 #if SQLITE_MAX_MMAP_SIZE>0
2144 unixUnmapfile(pFile
);
2147 robust_close(pFile
, pFile
->h
, __LINE__
);
2152 if( pFile
->ctrlFlags
& UNIXFILE_DELETE
){
2153 osUnlink(pFile
->pId
->zCanonicalName
);
2155 vxworksReleaseFileId(pFile
->pId
);
2159 #ifdef SQLITE_UNLINK_AFTER_CLOSE
2160 if( pFile
->ctrlFlags
& UNIXFILE_DELETE
){
2161 osUnlink(pFile
->zPath
);
2162 sqlite3_free(*(char**)&pFile
->zPath
);
2166 OSTRACE(("CLOSE %-3d\n", pFile
->h
));
2168 sqlite3_free(pFile
->pPreallocatedUnused
);
2169 memset(pFile
, 0, sizeof(unixFile
));
2176 static int unixClose(sqlite3_file
*id
){
2178 unixFile
*pFile
= (unixFile
*)id
;
2179 unixInodeInfo
*pInode
= pFile
->pInode
;
2181 assert( pInode
!=0 );
2182 verifyDbFile(pFile
);
2183 unixUnlock(id
, NO_LOCK
);
2184 assert( unixFileMutexNotheld(pFile
) );
2187 /* unixFile.pInode is always valid here. Otherwise, a different close
2188 ** routine (e.g. nolockClose()) would be called instead.
2190 assert( pFile
->pInode
->nLock
>0 || pFile
->pInode
->bProcessLock
==0 );
2191 sqlite3_mutex_enter(pInode
->pLockMutex
);
2192 if( pInode
->nLock
){
2193 /* If there are outstanding locks, do not actually close the file just
2194 ** yet because that would clear those locks. Instead, add the file
2195 ** descriptor to pInode->pUnused list. It will be automatically closed
2196 ** when the last lock is cleared.
2198 setPendingFd(pFile
);
2200 sqlite3_mutex_leave(pInode
->pLockMutex
);
2201 releaseInodeInfo(pFile
);
2202 assert( pFile
->pShm
==0 );
2203 rc
= closeUnixFile(id
);
2208 /************** End of the posix advisory lock implementation *****************
2209 ******************************************************************************/
2211 /******************************************************************************
2212 ****************************** No-op Locking **********************************
2214 ** Of the various locking implementations available, this is by far the
2215 ** simplest: locking is ignored. No attempt is made to lock the database
2216 ** file for reading or writing.
2218 ** This locking mode is appropriate for use on read-only databases
2219 ** (ex: databases that are burned into CD-ROM, for example.) It can
2220 ** also be used if the application employs some external mechanism to
2221 ** prevent simultaneous access of the same database by two or more
2222 ** database connections. But there is a serious risk of database
2223 ** corruption if this locking mode is used in situations where multiple
2224 ** database connections are accessing the same database file at the same
2225 ** time and one or more of those connections are writing.
2228 static int nolockCheckReservedLock(sqlite3_file
*NotUsed
, int *pResOut
){
2229 UNUSED_PARAMETER(NotUsed
);
2233 static int nolockLock(sqlite3_file
*NotUsed
, int NotUsed2
){
2234 UNUSED_PARAMETER2(NotUsed
, NotUsed2
);
2237 static int nolockUnlock(sqlite3_file
*NotUsed
, int NotUsed2
){
2238 UNUSED_PARAMETER2(NotUsed
, NotUsed2
);
2245 static int nolockClose(sqlite3_file
*id
) {
2246 return closeUnixFile(id
);
2249 /******************* End of the no-op lock implementation *********************
2250 ******************************************************************************/
2252 /******************************************************************************
2253 ************************* Begin dot-file Locking ******************************
2255 ** The dotfile locking implementation uses the existence of separate lock
2256 ** files (really a directory) to control access to the database. This works
2257 ** on just about every filesystem imaginable. But there are serious downsides:
2259 ** (1) There is zero concurrency. A single reader blocks all other
2260 ** connections from reading or writing the database.
2262 ** (2) An application crash or power loss can leave stale lock files
2263 ** sitting around that need to be cleared manually.
2265 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
2266 ** other locking strategy is available.
2268 ** Dotfile locking works by creating a subdirectory in the same directory as
2269 ** the database and with the same name but with a ".lock" extension added.
2270 ** The existence of a lock directory implies an EXCLUSIVE lock. All other
2271 ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
2275 ** The file suffix added to the data base filename in order to create the
2278 #define DOTLOCK_SUFFIX ".lock"
2281 ** This routine checks if there is a RESERVED lock held on the specified
2282 ** file by this or any other process. If such a lock is held, set *pResOut
2283 ** to a non-zero value otherwise *pResOut is set to zero. The return value
2284 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2286 ** In dotfile locking, either a lock exists or it does not. So in this
2287 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
2288 ** is held on the file and false if the file is unlocked.
2290 static int dotlockCheckReservedLock(sqlite3_file
*id
, int *pResOut
) {
2293 unixFile
*pFile
= (unixFile
*)id
;
2295 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK
; );
2298 reserved
= osAccess((const char*)pFile
->lockingContext
, 0)==0;
2299 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile
->h
, rc
, reserved
));
2300 *pResOut
= reserved
;
2305 ** Lock the file with the lock specified by parameter eFileLock - one
2306 ** of the following:
2309 ** (2) RESERVED_LOCK
2311 ** (4) EXCLUSIVE_LOCK
2313 ** Sometimes when requesting one lock state, additional lock states
2314 ** are inserted in between. The locking might fail on one of the later
2315 ** transitions leaving the lock state different from what it started but
2316 ** still short of its goal. The following chart shows the allowed
2317 ** transitions and the inserted intermediate states:
2319 ** UNLOCKED -> SHARED
2320 ** SHARED -> RESERVED
2321 ** SHARED -> (PENDING) -> EXCLUSIVE
2322 ** RESERVED -> (PENDING) -> EXCLUSIVE
2323 ** PENDING -> EXCLUSIVE
2325 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
2326 ** routine to lower a locking level.
2328 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
2329 ** But we track the other locking levels internally.
2331 static int dotlockLock(sqlite3_file
*id
, int eFileLock
) {
2332 unixFile
*pFile
= (unixFile
*)id
;
2333 char *zLockFile
= (char *)pFile
->lockingContext
;
2337 /* If we have any lock, then the lock file already exists. All we have
2338 ** to do is adjust our internal record of the lock level.
2340 if( pFile
->eFileLock
> NO_LOCK
){
2341 pFile
->eFileLock
= eFileLock
;
2342 /* Always update the timestamp on the old file */
2344 utime(zLockFile
, NULL
);
2346 utimes(zLockFile
, NULL
);
2351 /* grab an exclusive lock */
2352 rc
= osMkdir(zLockFile
, 0777);
2354 /* failed to open/create the lock directory */
2356 if( EEXIST
== tErrno
){
2359 rc
= sqliteErrorFromPosixError(tErrno
, SQLITE_IOERR_LOCK
);
2360 if( rc
!=SQLITE_BUSY
){
2361 storeLastErrno(pFile
, tErrno
);
2367 /* got it, set the type and return ok */
2368 pFile
->eFileLock
= eFileLock
;
2373 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
2374 ** must be either NO_LOCK or SHARED_LOCK.
2376 ** If the locking level of the file descriptor is already at or below
2377 ** the requested locking level, this routine is a no-op.
2379 ** When the locking level reaches NO_LOCK, delete the lock file.
2381 static int dotlockUnlock(sqlite3_file
*id
, int eFileLock
) {
2382 unixFile
*pFile
= (unixFile
*)id
;
2383 char *zLockFile
= (char *)pFile
->lockingContext
;
2387 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile
->h
, eFileLock
,
2388 pFile
->eFileLock
, osGetpid(0)));
2389 assert( eFileLock
<=SHARED_LOCK
);
2391 /* no-op if possible */
2392 if( pFile
->eFileLock
==eFileLock
){
2396 /* To downgrade to shared, simply update our internal notion of the
2397 ** lock state. No need to mess with the file on disk.
2399 if( eFileLock
==SHARED_LOCK
){
2400 pFile
->eFileLock
= SHARED_LOCK
;
2404 /* To fully unlock the database, delete the lock file */
2405 assert( eFileLock
==NO_LOCK
);
2406 rc
= osRmdir(zLockFile
);
2409 if( tErrno
==ENOENT
){
2412 rc
= SQLITE_IOERR_UNLOCK
;
2413 storeLastErrno(pFile
, tErrno
);
2417 pFile
->eFileLock
= NO_LOCK
;
2422 ** Close a file. Make sure the lock has been released before closing.
2424 static int dotlockClose(sqlite3_file
*id
) {
2425 unixFile
*pFile
= (unixFile
*)id
;
2427 dotlockUnlock(id
, NO_LOCK
);
2428 sqlite3_free(pFile
->lockingContext
);
2429 return closeUnixFile(id
);
2431 /****************** End of the dot-file lock implementation *******************
2432 ******************************************************************************/
2434 /******************************************************************************
2435 ************************** Begin flock Locking ********************************
2437 ** Use the flock() system call to do file locking.
2439 ** flock() locking is like dot-file locking in that the various
2440 ** fine-grain locking levels supported by SQLite are collapsed into
2441 ** a single exclusive lock. In other words, SHARED, RESERVED, and
2442 ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2443 ** still works when you do this, but concurrency is reduced since
2444 ** only a single process can be reading the database at a time.
2446 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
2448 #if SQLITE_ENABLE_LOCKING_STYLE
2451 ** Retry flock() calls that fail with EINTR
2454 static int robust_flock(int fd
, int op
){
2456 do{ rc
= flock(fd
,op
); }while( rc
<0 && errno
==EINTR
);
2460 # define robust_flock(a,b) flock(a,b)
2465 ** This routine checks if there is a RESERVED lock held on the specified
2466 ** file by this or any other process. If such a lock is held, set *pResOut
2467 ** to a non-zero value otherwise *pResOut is set to zero. The return value
2468 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2470 static int flockCheckReservedLock(sqlite3_file
*id
, int *pResOut
){
2473 unixFile
*pFile
= (unixFile
*)id
;
2475 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK
; );
2479 /* Check if a thread in this process holds such a lock */
2480 if( pFile
->eFileLock
>SHARED_LOCK
){
2484 /* Otherwise see if some other process holds it. */
2486 /* attempt to get the lock */
2487 int lrc
= robust_flock(pFile
->h
, LOCK_EX
| LOCK_NB
);
2489 /* got the lock, unlock it */
2490 lrc
= robust_flock(pFile
->h
, LOCK_UN
);
2493 /* unlock failed with an error */
2494 lrc
= SQLITE_IOERR_UNLOCK
;
2495 storeLastErrno(pFile
, tErrno
);
2501 /* someone else might have it reserved */
2502 lrc
= sqliteErrorFromPosixError(tErrno
, SQLITE_IOERR_LOCK
);
2503 if( IS_LOCK_ERROR(lrc
) ){
2504 storeLastErrno(pFile
, tErrno
);
2509 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile
->h
, rc
, reserved
));
2511 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2512 if( (rc
& 0xff) == SQLITE_IOERR
){
2516 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2517 *pResOut
= reserved
;
2522 ** Lock the file with the lock specified by parameter eFileLock - one
2523 ** of the following:
2526 ** (2) RESERVED_LOCK
2528 ** (4) EXCLUSIVE_LOCK
2530 ** Sometimes when requesting one lock state, additional lock states
2531 ** are inserted in between. The locking might fail on one of the later
2532 ** transitions leaving the lock state different from what it started but
2533 ** still short of its goal. The following chart shows the allowed
2534 ** transitions and the inserted intermediate states:
2536 ** UNLOCKED -> SHARED
2537 ** SHARED -> RESERVED
2538 ** SHARED -> (PENDING) -> EXCLUSIVE
2539 ** RESERVED -> (PENDING) -> EXCLUSIVE
2540 ** PENDING -> EXCLUSIVE
2542 ** flock() only really support EXCLUSIVE locks. We track intermediate
2543 ** lock states in the sqlite3_file structure, but all locks SHARED or
2544 ** above are really EXCLUSIVE locks and exclude all other processes from
2547 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
2548 ** routine to lower a locking level.
2550 static int flockLock(sqlite3_file
*id
, int eFileLock
) {
2552 unixFile
*pFile
= (unixFile
*)id
;
2556 /* if we already have a lock, it is exclusive.
2557 ** Just adjust level and punt on outta here. */
2558 if (pFile
->eFileLock
> NO_LOCK
) {
2559 pFile
->eFileLock
= eFileLock
;
2563 /* grab an exclusive lock */
2565 if (robust_flock(pFile
->h
, LOCK_EX
| LOCK_NB
)) {
2567 /* didn't get, must be busy */
2568 rc
= sqliteErrorFromPosixError(tErrno
, SQLITE_IOERR_LOCK
);
2569 if( IS_LOCK_ERROR(rc
) ){
2570 storeLastErrno(pFile
, tErrno
);
2573 /* got it, set the type and return ok */
2574 pFile
->eFileLock
= eFileLock
;
2576 OSTRACE(("LOCK %d %s %s (flock)\n", pFile
->h
, azFileLock(eFileLock
),
2577 rc
==SQLITE_OK
? "ok" : "failed"));
2578 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2579 if( (rc
& 0xff) == SQLITE_IOERR
){
2582 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2588 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
2589 ** must be either NO_LOCK or SHARED_LOCK.
2591 ** If the locking level of the file descriptor is already at or below
2592 ** the requested locking level, this routine is a no-op.
2594 static int flockUnlock(sqlite3_file
*id
, int eFileLock
) {
2595 unixFile
*pFile
= (unixFile
*)id
;
2598 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile
->h
, eFileLock
,
2599 pFile
->eFileLock
, osGetpid(0)));
2600 assert( eFileLock
<=SHARED_LOCK
);
2602 /* no-op if possible */
2603 if( pFile
->eFileLock
==eFileLock
){
2607 /* shared can just be set because we always have an exclusive */
2608 if (eFileLock
==SHARED_LOCK
) {
2609 pFile
->eFileLock
= eFileLock
;
2613 /* no, really, unlock. */
2614 if( robust_flock(pFile
->h
, LOCK_UN
) ){
2615 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2617 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2618 return SQLITE_IOERR_UNLOCK
;
2620 pFile
->eFileLock
= NO_LOCK
;
2628 static int flockClose(sqlite3_file
*id
) {
2630 flockUnlock(id
, NO_LOCK
);
2631 return closeUnixFile(id
);
2634 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2636 /******************* End of the flock lock implementation *********************
2637 ******************************************************************************/
2639 /******************************************************************************
2640 ************************ Begin Named Semaphore Locking ************************
2642 ** Named semaphore locking is only supported on VxWorks.
2644 ** Semaphore locking is like dot-lock and flock in that it really only
2645 ** supports EXCLUSIVE locking. Only a single process can read or write
2646 ** the database file at a time. This reduces potential concurrency, but
2647 ** makes the lock implementation much easier.
2652 ** This routine checks if there is a RESERVED lock held on the specified
2653 ** file by this or any other process. If such a lock is held, set *pResOut
2654 ** to a non-zero value otherwise *pResOut is set to zero. The return value
2655 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2657 static int semXCheckReservedLock(sqlite3_file
*id
, int *pResOut
) {
2660 unixFile
*pFile
= (unixFile
*)id
;
2662 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK
; );
2666 /* Check if a thread in this process holds such a lock */
2667 if( pFile
->eFileLock
>SHARED_LOCK
){
2671 /* Otherwise see if some other process holds it. */
2673 sem_t
*pSem
= pFile
->pInode
->pSem
;
2675 if( sem_trywait(pSem
)==-1 ){
2677 if( EAGAIN
!= tErrno
){
2678 rc
= sqliteErrorFromPosixError(tErrno
, SQLITE_IOERR_CHECKRESERVEDLOCK
);
2679 storeLastErrno(pFile
, tErrno
);
2681 /* someone else has the lock when we are in NO_LOCK */
2682 reserved
= (pFile
->eFileLock
< SHARED_LOCK
);
2685 /* we could have it if we want it */
2689 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile
->h
, rc
, reserved
));
2691 *pResOut
= reserved
;
2696 ** Lock the file with the lock specified by parameter eFileLock - one
2697 ** of the following:
2700 ** (2) RESERVED_LOCK
2702 ** (4) EXCLUSIVE_LOCK
2704 ** Sometimes when requesting one lock state, additional lock states
2705 ** are inserted in between. The locking might fail on one of the later
2706 ** transitions leaving the lock state different from what it started but
2707 ** still short of its goal. The following chart shows the allowed
2708 ** transitions and the inserted intermediate states:
2710 ** UNLOCKED -> SHARED
2711 ** SHARED -> RESERVED
2712 ** SHARED -> (PENDING) -> EXCLUSIVE
2713 ** RESERVED -> (PENDING) -> EXCLUSIVE
2714 ** PENDING -> EXCLUSIVE
2716 ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2717 ** lock states in the sqlite3_file structure, but all locks SHARED or
2718 ** above are really EXCLUSIVE locks and exclude all other processes from
2721 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
2722 ** routine to lower a locking level.
2724 static int semXLock(sqlite3_file
*id
, int eFileLock
) {
2725 unixFile
*pFile
= (unixFile
*)id
;
2726 sem_t
*pSem
= pFile
->pInode
->pSem
;
2729 /* if we already have a lock, it is exclusive.
2730 ** Just adjust level and punt on outta here. */
2731 if (pFile
->eFileLock
> NO_LOCK
) {
2732 pFile
->eFileLock
= eFileLock
;
2737 /* lock semaphore now but bail out when already locked. */
2738 if( sem_trywait(pSem
)==-1 ){
2743 /* got it, set the type and return ok */
2744 pFile
->eFileLock
= eFileLock
;
2751 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
2752 ** must be either NO_LOCK or SHARED_LOCK.
2754 ** If the locking level of the file descriptor is already at or below
2755 ** the requested locking level, this routine is a no-op.
2757 static int semXUnlock(sqlite3_file
*id
, int eFileLock
) {
2758 unixFile
*pFile
= (unixFile
*)id
;
2759 sem_t
*pSem
= pFile
->pInode
->pSem
;
2763 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile
->h
, eFileLock
,
2764 pFile
->eFileLock
, osGetpid(0)));
2765 assert( eFileLock
<=SHARED_LOCK
);
2767 /* no-op if possible */
2768 if( pFile
->eFileLock
==eFileLock
){
2772 /* shared can just be set because we always have an exclusive */
2773 if (eFileLock
==SHARED_LOCK
) {
2774 pFile
->eFileLock
= eFileLock
;
2778 /* no, really unlock. */
2779 if ( sem_post(pSem
)==-1 ) {
2780 int rc
, tErrno
= errno
;
2781 rc
= sqliteErrorFromPosixError(tErrno
, SQLITE_IOERR_UNLOCK
);
2782 if( IS_LOCK_ERROR(rc
) ){
2783 storeLastErrno(pFile
, tErrno
);
2787 pFile
->eFileLock
= NO_LOCK
;
2794 static int semXClose(sqlite3_file
*id
) {
2796 unixFile
*pFile
= (unixFile
*)id
;
2797 semXUnlock(id
, NO_LOCK
);
2799 assert( unixFileMutexNotheld(pFile
) );
2801 releaseInodeInfo(pFile
);
2808 #endif /* OS_VXWORKS */
2810 ** Named semaphore locking is only available on VxWorks.
2812 *************** End of the named semaphore lock implementation ****************
2813 ******************************************************************************/
2816 /******************************************************************************
2817 *************************** Begin AFP Locking *********************************
2819 ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2820 ** on Apple Macintosh computers - both OS9 and OSX.
2822 ** Third-party implementations of AFP are available. But this code here
2823 ** only works on OSX.
2826 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2828 ** The afpLockingContext structure contains all afp lock specific state
2830 typedef struct afpLockingContext afpLockingContext
;
2831 struct afpLockingContext
{
2833 const char *dbPath
; /* Name of the open file */
2836 struct ByteRangeLockPB2
2838 unsigned long long offset
; /* offset to first byte to lock */
2839 unsigned long long length
; /* nbr of bytes to lock */
2840 unsigned long long retRangeStart
; /* nbr of 1st byte locked if successful */
2841 unsigned char unLockFlag
; /* 1 = unlock, 0 = lock */
2842 unsigned char startEndFlag
; /* 1=rel to end of fork, 0=rel to start */
2843 int fd
; /* file desc to assoc this lock with */
2846 #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
2849 ** This is a utility for setting or clearing a bit-range lock on an
2852 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2854 static int afpSetLock(
2855 const char *path
, /* Name of the file to be locked or unlocked */
2856 unixFile
*pFile
, /* Open file descriptor on path */
2857 unsigned long long offset
, /* First byte to be locked */
2858 unsigned long long length
, /* Number of bytes to lock */
2859 int setLockFlag
/* True to set lock. False to clear lock */
2861 struct ByteRangeLockPB2 pb
;
2864 pb
.unLockFlag
= setLockFlag
? 0 : 1;
2865 pb
.startEndFlag
= 0;
2870 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
2871 (setLockFlag
?"ON":"OFF"), pFile
->h
, (pb
.fd
==-1?"[testval-1]":""),
2873 err
= fsctl(path
, afpfsByteRangeLock2FSCTL
, &pb
, 0);
2877 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2878 path
, tErrno
, strerror(tErrno
)));
2879 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2882 rc
= sqliteErrorFromPosixError(tErrno
,
2883 setLockFlag
? SQLITE_IOERR_LOCK
: SQLITE_IOERR_UNLOCK
);
2884 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
2885 if( IS_LOCK_ERROR(rc
) ){
2886 storeLastErrno(pFile
, tErrno
);
2895 ** This routine checks if there is a RESERVED lock held on the specified
2896 ** file by this or any other process. If such a lock is held, set *pResOut
2897 ** to a non-zero value otherwise *pResOut is set to zero. The return value
2898 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2900 static int afpCheckReservedLock(sqlite3_file
*id
, int *pResOut
){
2903 unixFile
*pFile
= (unixFile
*)id
;
2904 afpLockingContext
*context
;
2906 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK
; );
2909 context
= (afpLockingContext
*) pFile
->lockingContext
;
2910 if( context
->reserved
){
2914 sqlite3_mutex_enter(pFile
->pInode
->pLockMutex
);
2915 /* Check if a thread in this process holds such a lock */
2916 if( pFile
->pInode
->eFileLock
>SHARED_LOCK
){
2920 /* Otherwise see if some other process holds it.
2923 /* lock the RESERVED byte */
2924 int lrc
= afpSetLock(context
->dbPath
, pFile
, RESERVED_BYTE
, 1,1);
2925 if( SQLITE_OK
==lrc
){
2926 /* if we succeeded in taking the reserved lock, unlock it to restore
2927 ** the original state */
2928 lrc
= afpSetLock(context
->dbPath
, pFile
, RESERVED_BYTE
, 1, 0);
2930 /* if we failed to get the lock then someone else must have it */
2933 if( IS_LOCK_ERROR(lrc
) ){
2938 sqlite3_mutex_leave(pFile
->pInode
->pLockMutex
);
2939 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile
->h
, rc
, reserved
));
2941 *pResOut
= reserved
;
2946 ** Lock the file with the lock specified by parameter eFileLock - one
2947 ** of the following:
2950 ** (2) RESERVED_LOCK
2952 ** (4) EXCLUSIVE_LOCK
2954 ** Sometimes when requesting one lock state, additional lock states
2955 ** are inserted in between. The locking might fail on one of the later
2956 ** transitions leaving the lock state different from what it started but
2957 ** still short of its goal. The following chart shows the allowed
2958 ** transitions and the inserted intermediate states:
2960 ** UNLOCKED -> SHARED
2961 ** SHARED -> RESERVED
2962 ** SHARED -> (PENDING) -> EXCLUSIVE
2963 ** RESERVED -> (PENDING) -> EXCLUSIVE
2964 ** PENDING -> EXCLUSIVE
2966 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
2967 ** routine to lower a locking level.
2969 static int afpLock(sqlite3_file
*id
, int eFileLock
){
2971 unixFile
*pFile
= (unixFile
*)id
;
2972 unixInodeInfo
*pInode
= pFile
->pInode
;
2973 afpLockingContext
*context
= (afpLockingContext
*) pFile
->lockingContext
;
2976 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile
->h
,
2977 azFileLock(eFileLock
), azFileLock(pFile
->eFileLock
),
2978 azFileLock(pInode
->eFileLock
), pInode
->nShared
, osGetpid(0)));
2980 /* If there is already a lock of this type or more restrictive on the
2981 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
2982 ** unixEnterMutex() hasn't been called yet.
2984 if( pFile
->eFileLock
>=eFileLock
){
2985 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile
->h
,
2986 azFileLock(eFileLock
)));
2990 /* Make sure the locking sequence is correct
2991 ** (1) We never move from unlocked to anything higher than shared lock.
2992 ** (2) SQLite never explicitly requests a pending lock.
2993 ** (3) A shared lock is always held when a reserve lock is requested.
2995 assert( pFile
->eFileLock
!=NO_LOCK
|| eFileLock
==SHARED_LOCK
);
2996 assert( eFileLock
!=PENDING_LOCK
);
2997 assert( eFileLock
!=RESERVED_LOCK
|| pFile
->eFileLock
==SHARED_LOCK
);
2999 /* This mutex is needed because pFile->pInode is shared across threads
3001 pInode
= pFile
->pInode
;
3002 sqlite3_mutex_enter(pInode
->pLockMutex
);
3004 /* If some thread using this PID has a lock via a different unixFile*
3005 ** handle that precludes the requested lock, return BUSY.
3007 if( (pFile
->eFileLock
!=pInode
->eFileLock
&&
3008 (pInode
->eFileLock
>=PENDING_LOCK
|| eFileLock
>SHARED_LOCK
))
3014 /* If a SHARED lock is requested, and some thread using this PID already
3015 ** has a SHARED or RESERVED lock, then increment reference counts and
3016 ** return SQLITE_OK.
3018 if( eFileLock
==SHARED_LOCK
&&
3019 (pInode
->eFileLock
==SHARED_LOCK
|| pInode
->eFileLock
==RESERVED_LOCK
) ){
3020 assert( eFileLock
==SHARED_LOCK
);
3021 assert( pFile
->eFileLock
==0 );
3022 assert( pInode
->nShared
>0 );
3023 pFile
->eFileLock
= SHARED_LOCK
;
3029 /* A PENDING lock is needed before acquiring a SHARED lock and before
3030 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
3033 if( eFileLock
==SHARED_LOCK
3034 || (eFileLock
==EXCLUSIVE_LOCK
&& pFile
->eFileLock
<PENDING_LOCK
)
3037 failed
= afpSetLock(context
->dbPath
, pFile
, PENDING_BYTE
, 1, 1);
3044 /* If control gets to this point, then actually go ahead and make
3045 ** operating system calls for the specified lock.
3047 if( eFileLock
==SHARED_LOCK
){
3048 int lrc1
, lrc2
, lrc1Errno
= 0;
3051 assert( pInode
->nShared
==0 );
3052 assert( pInode
->eFileLock
==0 );
3054 mask
= (sizeof(long)==8) ? LARGEST_INT64
: 0x7fffffff;
3055 /* Now get the read-lock SHARED_LOCK */
3056 /* note that the quality of the randomness doesn't matter that much */
3058 pInode
->sharedByte
= (lk
& mask
)%(SHARED_SIZE
- 1);
3059 lrc1
= afpSetLock(context
->dbPath
, pFile
,
3060 SHARED_FIRST
+pInode
->sharedByte
, 1, 1);
3061 if( IS_LOCK_ERROR(lrc1
) ){
3062 lrc1Errno
= pFile
->lastErrno
;
3064 /* Drop the temporary PENDING lock */
3065 lrc2
= afpSetLock(context
->dbPath
, pFile
, PENDING_BYTE
, 1, 0);
3067 if( IS_LOCK_ERROR(lrc1
) ) {
3068 storeLastErrno(pFile
, lrc1Errno
);
3071 } else if( IS_LOCK_ERROR(lrc2
) ){
3074 } else if( lrc1
!= SQLITE_OK
) {
3077 pFile
->eFileLock
= SHARED_LOCK
;
3079 pInode
->nShared
= 1;
3081 }else if( eFileLock
==EXCLUSIVE_LOCK
&& pInode
->nShared
>1 ){
3082 /* We are trying for an exclusive lock but another thread in this
3083 ** same process is still holding a shared lock. */
3086 /* The request was for a RESERVED or EXCLUSIVE lock. It is
3087 ** assumed that there is a SHARED or greater lock on the file
3091 assert( 0!=pFile
->eFileLock
);
3092 if (eFileLock
>= RESERVED_LOCK
&& pFile
->eFileLock
< RESERVED_LOCK
) {
3093 /* Acquire a RESERVED lock */
3094 failed
= afpSetLock(context
->dbPath
, pFile
, RESERVED_BYTE
, 1,1);
3096 context
->reserved
= 1;
3099 if (!failed
&& eFileLock
== EXCLUSIVE_LOCK
) {
3100 /* Acquire an EXCLUSIVE lock */
3102 /* Remove the shared lock before trying the range. we'll need to
3103 ** reestablish the shared lock if we can't get the afpUnlock
3105 if( !(failed
= afpSetLock(context
->dbPath
, pFile
, SHARED_FIRST
+
3106 pInode
->sharedByte
, 1, 0)) ){
3107 int failed2
= SQLITE_OK
;
3108 /* now attempt to get the exclusive lock range */
3109 failed
= afpSetLock(context
->dbPath
, pFile
, SHARED_FIRST
,
3111 if( failed
&& (failed2
= afpSetLock(context
->dbPath
, pFile
,
3112 SHARED_FIRST
+ pInode
->sharedByte
, 1, 1)) ){
3113 /* Can't reestablish the shared lock. Sqlite can't deal, this is
3114 ** a critical I/O error
3116 rc
= ((failed
& 0xff) == SQLITE_IOERR
) ? failed2
:
3129 if( rc
==SQLITE_OK
){
3130 pFile
->eFileLock
= eFileLock
;
3131 pInode
->eFileLock
= eFileLock
;
3132 }else if( eFileLock
==EXCLUSIVE_LOCK
){
3133 pFile
->eFileLock
= PENDING_LOCK
;
3134 pInode
->eFileLock
= PENDING_LOCK
;
3138 sqlite3_mutex_leave(pInode
->pLockMutex
);
3139 OSTRACE(("LOCK %d %s %s (afp)\n", pFile
->h
, azFileLock(eFileLock
),
3140 rc
==SQLITE_OK
? "ok" : "failed"));
3145 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
3146 ** must be either NO_LOCK or SHARED_LOCK.
3148 ** If the locking level of the file descriptor is already at or below
3149 ** the requested locking level, this routine is a no-op.
3151 static int afpUnlock(sqlite3_file
*id
, int eFileLock
) {
3153 unixFile
*pFile
= (unixFile
*)id
;
3154 unixInodeInfo
*pInode
;
3155 afpLockingContext
*context
= (afpLockingContext
*) pFile
->lockingContext
;
3159 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile
->h
, eFileLock
,
3160 pFile
->eFileLock
, pFile
->pInode
->eFileLock
, pFile
->pInode
->nShared
,
3163 assert( eFileLock
<=SHARED_LOCK
);
3164 if( pFile
->eFileLock
<=eFileLock
){
3167 pInode
= pFile
->pInode
;
3168 sqlite3_mutex_enter(pInode
->pLockMutex
);
3169 assert( pInode
->nShared
!=0 );
3170 if( pFile
->eFileLock
>SHARED_LOCK
){
3171 assert( pInode
->eFileLock
==pFile
->eFileLock
);
3174 /* When reducing a lock such that other processes can start
3175 ** reading the database file again, make sure that the
3176 ** transaction counter was updated if any part of the database
3177 ** file changed. If the transaction counter is not updated,
3178 ** other connections to the same file might not realize that
3179 ** the file has changed and hence might not know to flush their
3180 ** cache. The use of a stale cache can lead to database corruption.
3182 assert( pFile
->inNormalWrite
==0
3183 || pFile
->dbUpdate
==0
3184 || pFile
->transCntrChng
==1 );
3185 pFile
->inNormalWrite
= 0;
3188 if( pFile
->eFileLock
==EXCLUSIVE_LOCK
){
3189 rc
= afpSetLock(context
->dbPath
, pFile
, SHARED_FIRST
, SHARED_SIZE
, 0);
3190 if( rc
==SQLITE_OK
&& (eFileLock
==SHARED_LOCK
|| pInode
->nShared
>1) ){
3191 /* only re-establish the shared lock if necessary */
3192 int sharedLockByte
= SHARED_FIRST
+pInode
->sharedByte
;
3193 rc
= afpSetLock(context
->dbPath
, pFile
, sharedLockByte
, 1, 1);
3198 if( rc
==SQLITE_OK
&& pFile
->eFileLock
>=PENDING_LOCK
){
3199 rc
= afpSetLock(context
->dbPath
, pFile
, PENDING_BYTE
, 1, 0);
3201 if( rc
==SQLITE_OK
&& pFile
->eFileLock
>=RESERVED_LOCK
&& context
->reserved
){
3202 rc
= afpSetLock(context
->dbPath
, pFile
, RESERVED_BYTE
, 1, 0);
3204 context
->reserved
= 0;
3207 if( rc
==SQLITE_OK
&& (eFileLock
==SHARED_LOCK
|| pInode
->nShared
>1)){
3208 pInode
->eFileLock
= SHARED_LOCK
;
3211 if( rc
==SQLITE_OK
&& eFileLock
==NO_LOCK
){
3213 /* Decrement the shared lock counter. Release the lock using an
3214 ** OS call only when all threads in this same process have released
3217 unsigned long long sharedLockByte
= SHARED_FIRST
+pInode
->sharedByte
;
3219 if( pInode
->nShared
==0 ){
3221 rc
= afpSetLock(context
->dbPath
, pFile
, sharedLockByte
, 1, 0);
3224 pInode
->eFileLock
= NO_LOCK
;
3225 pFile
->eFileLock
= NO_LOCK
;
3228 if( rc
==SQLITE_OK
){
3230 assert( pInode
->nLock
>=0 );
3231 if( pInode
->nLock
==0 ) closePendingFds(pFile
);
3235 sqlite3_mutex_leave(pInode
->pLockMutex
);
3236 if( rc
==SQLITE_OK
){
3237 pFile
->eFileLock
= eFileLock
;
3243 ** Close a file & cleanup AFP specific locking context
3245 static int afpClose(sqlite3_file
*id
) {
3247 unixFile
*pFile
= (unixFile
*)id
;
3249 afpUnlock(id
, NO_LOCK
);
3250 assert( unixFileMutexNotheld(pFile
) );
3252 if( pFile
->pInode
){
3253 unixInodeInfo
*pInode
= pFile
->pInode
;
3254 sqlite3_mutex_enter(pInode
->pLockMutex
);
3255 if( pInode
->nLock
){
3256 /* If there are outstanding locks, do not actually close the file just
3257 ** yet because that would clear those locks. Instead, add the file
3258 ** descriptor to pInode->aPending. It will be automatically closed when
3259 ** the last lock is cleared.
3261 setPendingFd(pFile
);
3263 sqlite3_mutex_leave(pInode
->pLockMutex
);
3265 releaseInodeInfo(pFile
);
3266 sqlite3_free(pFile
->lockingContext
);
3267 rc
= closeUnixFile(id
);
3272 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3274 ** The code above is the AFP lock implementation. The code is specific
3275 ** to MacOSX and does not work on other unix platforms. No alternative
3276 ** is available. If you don't compile for a mac, then the "unix-afp"
3277 ** VFS is not available.
3279 ********************* End of the AFP lock implementation **********************
3280 ******************************************************************************/
3282 /******************************************************************************
3283 *************************** Begin NFS Locking ********************************/
3285 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3287 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
3288 ** must be either NO_LOCK or SHARED_LOCK.
3290 ** If the locking level of the file descriptor is already at or below
3291 ** the requested locking level, this routine is a no-op.
3293 static int nfsUnlock(sqlite3_file
*id
, int eFileLock
){
3294 return posixUnlock(id
, eFileLock
, 1);
3297 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3299 ** The code above is the NFS lock implementation. The code is specific
3300 ** to MacOSX and does not work on other unix platforms. No alternative
3303 ********************* End of the NFS lock implementation **********************
3304 ******************************************************************************/
3306 /******************************************************************************
3307 **************** Non-locking sqlite3_file methods *****************************
3309 ** The next division contains implementations for all methods of the
3310 ** sqlite3_file object other than the locking methods. The locking
3311 ** methods were defined in divisions above (one locking method per
3312 ** division). Those methods that are common to all locking modes
3313 ** are gather together into this division.
3317 ** Seek to the offset passed as the second argument, then read cnt
3318 ** bytes into pBuf. Return the number of bytes actually read.
3320 ** To avoid stomping the errno value on a failed read the lastErrno value
3321 ** is set before returning.
3323 static int seekAndRead(unixFile
*id
, sqlite3_int64 offset
, void *pBuf
, int cnt
){
3326 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
3330 assert( cnt
==(cnt
&0x1ffff) );
3333 #if defined(USE_PREAD)
3334 got
= osPread(id
->h
, pBuf
, cnt
, offset
);
3335 SimulateIOError( got
= -1 );
3336 #elif defined(USE_PREAD64)
3337 got
= osPread64(id
->h
, pBuf
, cnt
, offset
);
3338 SimulateIOError( got
= -1 );
3340 newOffset
= lseek(id
->h
, offset
, SEEK_SET
);
3341 SimulateIOError( newOffset
= -1 );
3343 storeLastErrno((unixFile
*)id
, errno
);
3346 got
= osRead(id
->h
, pBuf
, cnt
);
3348 if( got
==cnt
) break;
3350 if( errno
==EINTR
){ got
= 1; continue; }
3352 storeLastErrno((unixFile
*)id
, errno
);
3358 pBuf
= (void*)(got
+ (char*)pBuf
);
3362 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3363 id
->h
, got
+prior
, offset
-prior
, TIMER_ELAPSED
));
3368 ** Read data from a file into a buffer. Return SQLITE_OK if all
3369 ** bytes were read successfully and SQLITE_IOERR if anything goes
3372 static int unixRead(
3376 sqlite3_int64 offset
3378 unixFile
*pFile
= (unixFile
*)id
;
3381 assert( offset
>=0 );
3384 /* If this is a database file (not a journal, super-journal or temp
3385 ** file), the bytes in the locking range should never be read or written. */
3387 assert( pFile
->pPreallocatedUnused
==0
3388 || offset
>=PENDING_BYTE
+512
3389 || offset
+amt
<=PENDING_BYTE
3393 #if SQLITE_MAX_MMAP_SIZE>0
3394 /* Deal with as much of this read request as possible by transferring
3395 ** data from the memory mapping using memcpy(). */
3396 if( offset
<pFile
->mmapSize
){
3397 if( offset
+amt
<= pFile
->mmapSize
){
3398 memcpy(pBuf
, &((u8
*)(pFile
->pMapRegion
))[offset
], amt
);
3401 int nCopy
= pFile
->mmapSize
- offset
;
3402 memcpy(pBuf
, &((u8
*)(pFile
->pMapRegion
))[offset
], nCopy
);
3403 pBuf
= &((u8
*)pBuf
)[nCopy
];
3410 got
= seekAndRead(pFile
, offset
, pBuf
, amt
);
3414 /* pFile->lastErrno has been set by seekAndRead().
3415 ** Usually we return SQLITE_IOERR_READ here, though for some
3416 ** kinds of errors we return SQLITE_IOERR_CORRUPTFS. The
3417 ** SQLITE_IOERR_CORRUPTFS will be converted into SQLITE_CORRUPT
3418 ** prior to returning to the application by the sqlite3ApiExit()
3421 switch( pFile
->lastErrno
){
3430 return SQLITE_IOERR_CORRUPTFS
;
3432 return SQLITE_IOERR_READ
;
3434 storeLastErrno(pFile
, 0); /* not a system error */
3435 /* Unread parts of the buffer must be zero-filled */
3436 memset(&((char*)pBuf
)[got
], 0, amt
-got
);
3437 return SQLITE_IOERR_SHORT_READ
;
3442 ** Attempt to seek the file-descriptor passed as the first argument to
3443 ** absolute offset iOff, then attempt to write nBuf bytes of data from
3444 ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3445 ** return the actual number of bytes written (which may be less than
3448 static int seekAndWriteFd(
3449 int fd
, /* File descriptor to write to */
3450 i64 iOff
, /* File offset to begin writing at */
3451 const void *pBuf
, /* Copy data from this buffer to the file */
3452 int nBuf
, /* Size of buffer pBuf in bytes */
3453 int *piErrno
/* OUT: Error number if error occurs */
3455 int rc
= 0; /* Value returned by system call */
3457 assert( nBuf
==(nBuf
&0x1ffff) );
3459 assert( piErrno
!=0 );
3463 #if defined(USE_PREAD)
3464 do{ rc
= (int)osPwrite(fd
, pBuf
, nBuf
, iOff
); }while( rc
<0 && errno
==EINTR
);
3465 #elif defined(USE_PREAD64)
3466 do{ rc
= (int)osPwrite64(fd
, pBuf
, nBuf
, iOff
);}while( rc
<0 && errno
==EINTR
);
3469 i64 iSeek
= lseek(fd
, iOff
, SEEK_SET
);
3470 SimulateIOError( iSeek
= -1 );
3475 rc
= osWrite(fd
, pBuf
, nBuf
);
3476 }while( rc
<0 && errno
==EINTR
);
3480 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd
, rc
, iOff
, TIMER_ELAPSED
));
3482 if( rc
<0 ) *piErrno
= errno
;
3488 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
3489 ** Return the number of bytes actually read. Update the offset.
3491 ** To avoid stomping the errno value on a failed write the lastErrno value
3492 ** is set before returning.
3494 static int seekAndWrite(unixFile
*id
, i64 offset
, const void *pBuf
, int cnt
){
3495 return seekAndWriteFd(id
->h
, offset
, pBuf
, cnt
, &id
->lastErrno
);
3500 ** Write data from a buffer into a file. Return SQLITE_OK on success
3501 ** or some other error code on failure.
3503 static int unixWrite(
3507 sqlite3_int64 offset
3509 unixFile
*pFile
= (unixFile
*)id
;
3514 /* If this is a database file (not a journal, super-journal or temp
3515 ** file), the bytes in the locking range should never be read or written. */
3517 assert( pFile
->pPreallocatedUnused
==0
3518 || offset
>=PENDING_BYTE
+512
3519 || offset
+amt
<=PENDING_BYTE
3524 /* If we are doing a normal write to a database file (as opposed to
3525 ** doing a hot-journal rollback or a write to some file other than a
3526 ** normal database file) then record the fact that the database
3527 ** has changed. If the transaction counter is modified, record that
3530 if( pFile
->inNormalWrite
){
3531 pFile
->dbUpdate
= 1; /* The database has been modified */
3532 if( offset
<=24 && offset
+amt
>=27 ){
3535 SimulateIOErrorBenign(1);
3536 rc
= seekAndRead(pFile
, 24, oldCntr
, 4);
3537 SimulateIOErrorBenign(0);
3538 if( rc
!=4 || memcmp(oldCntr
, &((char*)pBuf
)[24-offset
], 4)!=0 ){
3539 pFile
->transCntrChng
= 1; /* The transaction counter has changed */
3545 #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
3546 /* Deal with as much of this write request as possible by transferring
3547 ** data from the memory mapping using memcpy(). */
3548 if( offset
<pFile
->mmapSize
){
3549 if( offset
+amt
<= pFile
->mmapSize
){
3550 memcpy(&((u8
*)(pFile
->pMapRegion
))[offset
], pBuf
, amt
);
3553 int nCopy
= pFile
->mmapSize
- offset
;
3554 memcpy(&((u8
*)(pFile
->pMapRegion
))[offset
], pBuf
, nCopy
);
3555 pBuf
= &((u8
*)pBuf
)[nCopy
];
3562 while( (wrote
= seekAndWrite(pFile
, offset
, pBuf
, amt
))<amt
&& wrote
>0 ){
3565 pBuf
= &((char*)pBuf
)[wrote
];
3567 SimulateIOError(( wrote
=(-1), amt
=1 ));
3568 SimulateDiskfullError(( wrote
=0, amt
=1 ));
3571 if( wrote
<0 && pFile
->lastErrno
!=ENOSPC
){
3572 /* lastErrno set by seekAndWrite */
3573 return SQLITE_IOERR_WRITE
;
3575 storeLastErrno(pFile
, 0); /* not a system error */
3585 ** Count the number of fullsyncs and normal syncs. This is used to test
3586 ** that syncs and fullsyncs are occurring at the right times.
3588 int sqlite3_sync_count
= 0;
3589 int sqlite3_fullsync_count
= 0;
3593 ** We do not trust systems to provide a working fdatasync(). Some do.
3594 ** Others do no. To be safe, we will stick with the (slightly slower)
3595 ** fsync(). If you know that your system does support fdatasync() correctly,
3596 ** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
3598 #if !defined(fdatasync) && !HAVE_FDATASYNC
3599 # define fdatasync fsync
3603 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3604 ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3605 ** only available on Mac OS X. But that could change.
3608 # define HAVE_FULLFSYNC 1
3610 # define HAVE_FULLFSYNC 0
3615 ** The fsync() system call does not work as advertised on many
3616 ** unix systems. The following procedure is an attempt to make
3619 ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3620 ** for testing when we want to run through the test suite quickly.
3621 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3622 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3623 ** or power failure will likely corrupt the database file.
3625 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
3626 ** The idea behind dataOnly is that it should only write the file content
3627 ** to disk, not the inode. We only set dataOnly if the file size is
3628 ** unchanged since the file size is part of the inode. However,
3629 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
3630 ** file size has changed. The only real difference between fdatasync()
3631 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
3632 ** inode if the mtime or owner or other inode attributes have changed.
3633 ** We only care about the file size, not the other file attributes, so
3634 ** as far as SQLite is concerned, an fdatasync() is always adequate.
3635 ** So, we always use fdatasync() if it is available, regardless of
3636 ** the value of the dataOnly flag.
3638 static int full_fsync(int fd
, int fullSync
, int dataOnly
){
3641 /* The following "ifdef/elif/else/" block has the same structure as
3642 ** the one below. It is replicated here solely to avoid cluttering
3643 ** up the real code with the UNUSED_PARAMETER() macros.
3645 #ifdef SQLITE_NO_SYNC
3646 UNUSED_PARAMETER(fd
);
3647 UNUSED_PARAMETER(fullSync
);
3648 UNUSED_PARAMETER(dataOnly
);
3649 #elif HAVE_FULLFSYNC
3650 UNUSED_PARAMETER(dataOnly
);
3652 UNUSED_PARAMETER(fullSync
);
3653 UNUSED_PARAMETER(dataOnly
);
3656 /* Record the number of times that we do a normal fsync() and
3657 ** FULLSYNC. This is used during testing to verify that this procedure
3658 ** gets called with the correct arguments.
3661 if( fullSync
) sqlite3_fullsync_count
++;
3662 sqlite3_sync_count
++;
3665 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3666 ** no-op. But go ahead and call fstat() to validate the file
3667 ** descriptor as we need a method to provoke a failure during
3668 ** coverage testing.
3670 #ifdef SQLITE_NO_SYNC
3673 rc
= osFstat(fd
, &buf
);
3675 #elif HAVE_FULLFSYNC
3677 rc
= osFcntl(fd
, F_FULLFSYNC
, 0);
3681 /* If the FULLFSYNC failed, fall back to attempting an fsync().
3682 ** It shouldn't be possible for fullfsync to fail on the local
3683 ** file system (on OSX), so failure indicates that FULLFSYNC
3684 ** isn't supported for this file system. So, attempt an fsync
3685 ** and (for now) ignore the overhead of a superfluous fcntl call.
3686 ** It'd be better to detect fullfsync support once and avoid
3687 ** the fcntl call every time sync is called.
3689 if( rc
) rc
= fsync(fd
);
3691 #elif defined(__APPLE__)
3692 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3693 ** so currently we default to the macro that redefines fdatasync to fsync
3699 if( rc
==-1 && errno
==ENOTSUP
){
3702 #endif /* OS_VXWORKS */
3703 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3705 if( OS_VXWORKS
&& rc
!= -1 ){
3712 ** Open a file descriptor to the directory containing file zFilename.
3713 ** If successful, *pFd is set to the opened file descriptor and
3714 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3715 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3718 ** The directory file descriptor is used for only one thing - to
3719 ** fsync() a directory to make sure file creation and deletion events
3720 ** are flushed to disk. Such fsyncs are not needed on newer
3721 ** journaling filesystems, but are required on older filesystems.
3723 ** This routine can be overridden using the xSetSysCall interface.
3724 ** The ability to override this routine was added in support of the
3725 ** chromium sandbox. Opening a directory is a security risk (we are
3726 ** told) so making it overrideable allows the chromium sandbox to
3727 ** replace this routine with a harmless no-op. To make this routine
3728 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3729 ** *pFd set to a negative number.
3731 ** If SQLITE_OK is returned, the caller is responsible for closing
3732 ** the file descriptor *pFd using close().
3734 static int openDirectory(const char *zFilename
, int *pFd
){
3737 char zDirname
[MAX_PATHNAME
+1];
3739 sqlite3_snprintf(MAX_PATHNAME
, zDirname
, "%s", zFilename
);
3740 for(ii
=(int)strlen(zDirname
); ii
>0 && zDirname
[ii
]!='/'; ii
--);
3742 zDirname
[ii
] = '\0';
3744 if( zDirname
[0]!='/' ) zDirname
[0] = '.';
3747 fd
= robust_open(zDirname
, O_RDONLY
|O_BINARY
, 0);
3749 OSTRACE(("OPENDIR %-3d %s\n", fd
, zDirname
));
3752 if( fd
>=0 ) return SQLITE_OK
;
3753 return unixLogError(SQLITE_CANTOPEN_BKPT
, "openDirectory", zDirname
);
3757 ** Make sure all writes to a particular file are committed to disk.
3759 ** If dataOnly==0 then both the file itself and its metadata (file
3760 ** size, access time, etc) are synced. If dataOnly!=0 then only the
3761 ** file data is synced.
3763 ** Under Unix, also make sure that the directory entry for the file
3764 ** has been created by fsync-ing the directory that contains the file.
3765 ** If we do not do this and we encounter a power failure, the directory
3766 ** entry for the journal might not exist after we reboot. The next
3767 ** SQLite to access the file will not know that the journal exists (because
3768 ** the directory entry for the journal was never created) and the transaction
3769 ** will not roll back - possibly leading to database corruption.
3771 static int unixSync(sqlite3_file
*id
, int flags
){
3773 unixFile
*pFile
= (unixFile
*)id
;
3775 int isDataOnly
= (flags
&SQLITE_SYNC_DATAONLY
);
3776 int isFullsync
= (flags
&0x0F)==SQLITE_SYNC_FULL
;
3778 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3779 assert((flags
&0x0F)==SQLITE_SYNC_NORMAL
3780 || (flags
&0x0F)==SQLITE_SYNC_FULL
3783 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3784 ** line is to test that doing so does not cause any problems.
3786 SimulateDiskfullError( return SQLITE_FULL
);
3789 OSTRACE(("SYNC %-3d\n", pFile
->h
));
3790 rc
= full_fsync(pFile
->h
, isFullsync
, isDataOnly
);
3791 SimulateIOError( rc
=1 );
3793 storeLastErrno(pFile
, errno
);
3794 return unixLogError(SQLITE_IOERR_FSYNC
, "full_fsync", pFile
->zPath
);
3797 /* Also fsync the directory containing the file if the DIRSYNC flag
3798 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
3799 ** are unable to fsync a directory, so ignore errors on the fsync.
3801 if( pFile
->ctrlFlags
& UNIXFILE_DIRSYNC
){
3803 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile
->zPath
,
3804 HAVE_FULLFSYNC
, isFullsync
));
3805 rc
= osOpenDirectory(pFile
->zPath
, &dirfd
);
3806 if( rc
==SQLITE_OK
){
3807 full_fsync(dirfd
, 0, 0);
3808 robust_close(pFile
, dirfd
, __LINE__
);
3810 assert( rc
==SQLITE_CANTOPEN
);
3813 pFile
->ctrlFlags
&= ~UNIXFILE_DIRSYNC
;
3819 ** Truncate an open file to a specified size
3821 static int unixTruncate(sqlite3_file
*id
, i64 nByte
){
3822 unixFile
*pFile
= (unixFile
*)id
;
3825 SimulateIOError( return SQLITE_IOERR_TRUNCATE
);
3827 /* If the user has configured a chunk-size for this file, truncate the
3828 ** file so that it consists of an integer number of chunks (i.e. the
3829 ** actual file size after the operation may be larger than the requested
3832 if( pFile
->szChunk
>0 ){
3833 nByte
= ((nByte
+ pFile
->szChunk
- 1)/pFile
->szChunk
) * pFile
->szChunk
;
3836 rc
= robust_ftruncate(pFile
->h
, nByte
);
3838 storeLastErrno(pFile
, errno
);
3839 return unixLogError(SQLITE_IOERR_TRUNCATE
, "ftruncate", pFile
->zPath
);
3842 /* If we are doing a normal write to a database file (as opposed to
3843 ** doing a hot-journal rollback or a write to some file other than a
3844 ** normal database file) and we truncate the file to zero length,
3845 ** that effectively updates the change counter. This might happen
3846 ** when restoring a database using the backup API from a zero-length
3849 if( pFile
->inNormalWrite
&& nByte
==0 ){
3850 pFile
->transCntrChng
= 1;
3854 #if SQLITE_MAX_MMAP_SIZE>0
3855 /* If the file was just truncated to a size smaller than the currently
3856 ** mapped region, reduce the effective mapping size as well. SQLite will
3857 ** use read() and write() to access data beyond this point from now on.
3859 if( nByte
<pFile
->mmapSize
){
3860 pFile
->mmapSize
= nByte
;
3869 ** Determine the current size of a file in bytes
3871 static int unixFileSize(sqlite3_file
*id
, i64
*pSize
){
3875 rc
= osFstat(((unixFile
*)id
)->h
, &buf
);
3876 SimulateIOError( rc
=1 );
3878 storeLastErrno((unixFile
*)id
, errno
);
3879 return SQLITE_IOERR_FSTAT
;
3881 *pSize
= buf
.st_size
;
3883 /* When opening a zero-size database, the findInodeInfo() procedure
3884 ** writes a single byte into that file in order to work around a bug
3885 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3886 ** layers, we need to report this file size as zero even though it is
3887 ** really 1. Ticket #3260.
3889 if( *pSize
==1 ) *pSize
= 0;
3895 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
3897 ** Handler for proxy-locking file-control verbs. Defined below in the
3898 ** proxying locking division.
3900 static int proxyFileControl(sqlite3_file
*,int,void*);
3904 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
3905 ** file-control operation. Enlarge the database to nBytes in size
3906 ** (rounded up to the next chunk-size). If the database is already
3907 ** nBytes or larger, this routine is a no-op.
3909 static int fcntlSizeHint(unixFile
*pFile
, i64 nByte
){
3910 if( pFile
->szChunk
>0 ){
3911 i64 nSize
; /* Required file size */
3912 struct stat buf
; /* Used to hold return values of fstat() */
3914 if( osFstat(pFile
->h
, &buf
) ){
3915 return SQLITE_IOERR_FSTAT
;
3918 nSize
= ((nByte
+pFile
->szChunk
-1) / pFile
->szChunk
) * pFile
->szChunk
;
3919 if( nSize
>(i64
)buf
.st_size
){
3921 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
3922 /* The code below is handling the return value of osFallocate()
3923 ** correctly. posix_fallocate() is defined to "returns zero on success,
3924 ** or an error number on failure". See the manpage for details. */
3927 err
= osFallocate(pFile
->h
, buf
.st_size
, nSize
-buf
.st_size
);
3928 }while( err
==EINTR
);
3929 if( err
&& err
!=EINVAL
) return SQLITE_IOERR_WRITE
;
3931 /* If the OS does not have posix_fallocate(), fake it. Write a
3932 ** single byte to the last byte in each block that falls entirely
3933 ** within the extended region. Then, if required, a single byte
3934 ** at offset (nSize-1), to set the size of the file correctly.
3935 ** This is a similar technique to that used by glibc on systems
3936 ** that do not have a real fallocate() call.
3938 int nBlk
= buf
.st_blksize
; /* File-system block size */
3939 int nWrite
= 0; /* Number of bytes written by seekAndWrite */
3940 i64 iWrite
; /* Next offset to write to */
3942 iWrite
= (buf
.st_size
/nBlk
)*nBlk
+ nBlk
- 1;
3943 assert( iWrite
>=buf
.st_size
);
3944 assert( ((iWrite
+1)%nBlk
)==0 );
3945 for(/*no-op*/; iWrite
<nSize
+nBlk
-1; iWrite
+=nBlk
){
3946 if( iWrite
>=nSize
) iWrite
= nSize
- 1;
3947 nWrite
= seekAndWrite(pFile
, iWrite
, "", 1);
3948 if( nWrite
!=1 ) return SQLITE_IOERR_WRITE
;
3954 #if SQLITE_MAX_MMAP_SIZE>0
3955 if( pFile
->mmapSizeMax
>0 && nByte
>pFile
->mmapSize
){
3957 if( pFile
->szChunk
<=0 ){
3958 if( robust_ftruncate(pFile
->h
, nByte
) ){
3959 storeLastErrno(pFile
, errno
);
3960 return unixLogError(SQLITE_IOERR_TRUNCATE
, "ftruncate", pFile
->zPath
);
3964 rc
= unixMapfile(pFile
, nByte
);
3973 ** If *pArg is initially negative then this is a query. Set *pArg to
3974 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3976 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3978 static void unixModeBit(unixFile
*pFile
, unsigned char mask
, int *pArg
){
3980 *pArg
= (pFile
->ctrlFlags
& mask
)!=0;
3981 }else if( (*pArg
)==0 ){
3982 pFile
->ctrlFlags
&= ~mask
;
3984 pFile
->ctrlFlags
|= mask
;
3988 /* Forward declaration */
3989 static int unixGetTempname(int nBuf
, char *zBuf
);
3990 #ifndef SQLITE_OMIT_WAL
3991 static int unixFcntlExternalReader(unixFile
*, int*);
3995 ** Information and control of an open file handle.
3997 static int unixFileControl(sqlite3_file
*id
, int op
, void *pArg
){
3998 unixFile
*pFile
= (unixFile
*)id
;
4000 #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
4001 case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE
: {
4002 int rc
= osIoctl(pFile
->h
, F2FS_IOC_START_ATOMIC_WRITE
);
4003 return rc
? SQLITE_IOERR_BEGIN_ATOMIC
: SQLITE_OK
;
4005 case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE
: {
4006 int rc
= osIoctl(pFile
->h
, F2FS_IOC_COMMIT_ATOMIC_WRITE
);
4007 return rc
? SQLITE_IOERR_COMMIT_ATOMIC
: SQLITE_OK
;
4009 case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE
: {
4010 int rc
= osIoctl(pFile
->h
, F2FS_IOC_ABORT_VOLATILE_WRITE
);
4011 return rc
? SQLITE_IOERR_ROLLBACK_ATOMIC
: SQLITE_OK
;
4013 #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
4015 case SQLITE_FCNTL_LOCKSTATE
: {
4016 *(int*)pArg
= pFile
->eFileLock
;
4019 case SQLITE_FCNTL_LAST_ERRNO
: {
4020 *(int*)pArg
= pFile
->lastErrno
;
4023 case SQLITE_FCNTL_CHUNK_SIZE
: {
4024 pFile
->szChunk
= *(int *)pArg
;
4027 case SQLITE_FCNTL_SIZE_HINT
: {
4029 SimulateIOErrorBenign(1);
4030 rc
= fcntlSizeHint(pFile
, *(i64
*)pArg
);
4031 SimulateIOErrorBenign(0);
4034 case SQLITE_FCNTL_PERSIST_WAL
: {
4035 unixModeBit(pFile
, UNIXFILE_PERSIST_WAL
, (int*)pArg
);
4038 case SQLITE_FCNTL_POWERSAFE_OVERWRITE
: {
4039 unixModeBit(pFile
, UNIXFILE_PSOW
, (int*)pArg
);
4042 case SQLITE_FCNTL_VFSNAME
: {
4043 *(char**)pArg
= sqlite3_mprintf("%s", pFile
->pVfs
->zName
);
4046 case SQLITE_FCNTL_TEMPFILENAME
: {
4047 char *zTFile
= sqlite3_malloc64( pFile
->pVfs
->mxPathname
);
4049 unixGetTempname(pFile
->pVfs
->mxPathname
, zTFile
);
4050 *(char**)pArg
= zTFile
;
4054 case SQLITE_FCNTL_HAS_MOVED
: {
4055 *(int*)pArg
= fileHasMoved(pFile
);
4058 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
4059 case SQLITE_FCNTL_LOCK_TIMEOUT
: {
4060 int iOld
= pFile
->iBusyTimeout
;
4061 #if SQLITE_ENABLE_SETLK_TIMEOUT==1
4062 pFile
->iBusyTimeout
= *(int*)pArg
;
4063 #elif SQLITE_ENABLE_SETLK_TIMEOUT==2
4064 pFile
->iBusyTimeout
= !!(*(int*)pArg
);
4066 # error "SQLITE_ENABLE_SETLK_TIMEOUT must be set to 1 or 2"
4072 #if SQLITE_MAX_MMAP_SIZE>0
4073 case SQLITE_FCNTL_MMAP_SIZE
: {
4074 i64 newLimit
= *(i64
*)pArg
;
4076 if( newLimit
>sqlite3GlobalConfig
.mxMmap
){
4077 newLimit
= sqlite3GlobalConfig
.mxMmap
;
4080 /* The value of newLimit may be eventually cast to (size_t) and passed
4081 ** to mmap(). Restrict its value to 2GB if (size_t) is not at least a
4083 if( newLimit
>0 && sizeof(size_t)<8 ){
4084 newLimit
= (newLimit
& 0x7FFFFFFF);
4087 *(i64
*)pArg
= pFile
->mmapSizeMax
;
4088 if( newLimit
>=0 && newLimit
!=pFile
->mmapSizeMax
&& pFile
->nFetchOut
==0 ){
4089 pFile
->mmapSizeMax
= newLimit
;
4090 if( pFile
->mmapSize
>0 ){
4091 unixUnmapfile(pFile
);
4092 rc
= unixMapfile(pFile
, -1);
4099 /* The pager calls this method to signal that it has done
4100 ** a rollback and that the database is therefore unchanged and
4101 ** it hence it is OK for the transaction change counter to be
4104 case SQLITE_FCNTL_DB_UNCHANGED
: {
4105 ((unixFile
*)id
)->dbUpdate
= 0;
4109 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
4110 case SQLITE_FCNTL_SET_LOCKPROXYFILE
:
4111 case SQLITE_FCNTL_GET_LOCKPROXYFILE
: {
4112 return proxyFileControl(id
,op
,pArg
);
4114 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
4116 case SQLITE_FCNTL_EXTERNAL_READER
: {
4117 #ifndef SQLITE_OMIT_WAL
4118 return unixFcntlExternalReader((unixFile
*)id
, (int*)pArg
);
4125 return SQLITE_NOTFOUND
;
4129 ** If pFd->sectorSize is non-zero when this function is called, it is a
4130 ** no-op. Otherwise, the values of pFd->sectorSize and
4131 ** pFd->deviceCharacteristics are set according to the file-system
4134 ** There are two versions of this function. One for QNX and one for all
4138 static void setDeviceCharacteristics(unixFile
*pFd
){
4139 assert( pFd
->deviceCharacteristics
==0 || pFd
->sectorSize
!=0 );
4140 if( pFd
->sectorSize
==0 ){
4141 #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
4145 /* Check for support for F2FS atomic batch writes. */
4146 res
= osIoctl(pFd
->h
, F2FS_IOC_GET_FEATURES
, &f
);
4147 if( res
==0 && (f
& F2FS_FEATURE_ATOMIC_WRITE
) ){
4148 pFd
->deviceCharacteristics
= SQLITE_IOCAP_BATCH_ATOMIC
;
4150 #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
4152 /* Set the POWERSAFE_OVERWRITE flag if requested. */
4153 if( pFd
->ctrlFlags
& UNIXFILE_PSOW
){
4154 pFd
->deviceCharacteristics
|= SQLITE_IOCAP_POWERSAFE_OVERWRITE
;
4157 pFd
->sectorSize
= SQLITE_DEFAULT_SECTOR_SIZE
;
4161 #include <sys/dcmd_blk.h>
4162 #include <sys/statvfs.h>
4163 static void setDeviceCharacteristics(unixFile
*pFile
){
4164 if( pFile
->sectorSize
== 0 ){
4165 struct statvfs fsInfo
;
4167 /* Set defaults for non-supported filesystems */
4168 pFile
->sectorSize
= SQLITE_DEFAULT_SECTOR_SIZE
;
4169 pFile
->deviceCharacteristics
= 0;
4170 if( fstatvfs(pFile
->h
, &fsInfo
) == -1 ) {
4174 if( !strcmp(fsInfo
.f_basetype
, "tmp") ) {
4175 pFile
->sectorSize
= fsInfo
.f_bsize
;
4176 pFile
->deviceCharacteristics
=
4177 SQLITE_IOCAP_ATOMIC4K
| /* All ram filesystem writes are atomic */
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( strstr(fsInfo
.f_basetype
, "etfs") ){
4184 pFile
->sectorSize
= fsInfo
.f_bsize
;
4185 pFile
->deviceCharacteristics
=
4186 /* etfs cluster size writes are atomic */
4187 (pFile
->sectorSize
/ 512 * SQLITE_IOCAP_ATOMIC512
) |
4188 SQLITE_IOCAP_SAFE_APPEND
| /* growing the file does not occur until
4189 ** the write succeeds */
4190 SQLITE_IOCAP_SEQUENTIAL
| /* The ram filesystem has no write behind
4191 ** so it is ordered */
4193 }else if( !strcmp(fsInfo
.f_basetype
, "qnx6") ){
4194 pFile
->sectorSize
= fsInfo
.f_bsize
;
4195 pFile
->deviceCharacteristics
=
4196 SQLITE_IOCAP_ATOMIC
| /* All filesystem writes are atomic */
4197 SQLITE_IOCAP_SAFE_APPEND
| /* growing the file does not occur until
4198 ** the write succeeds */
4199 SQLITE_IOCAP_SEQUENTIAL
| /* The ram filesystem has no write behind
4200 ** so it is ordered */
4202 }else if( !strcmp(fsInfo
.f_basetype
, "qnx4") ){
4203 pFile
->sectorSize
= fsInfo
.f_bsize
;
4204 pFile
->deviceCharacteristics
=
4205 /* full bitset of atomics from max sector size and smaller */
4206 ((pFile
->sectorSize
/ 512 * SQLITE_IOCAP_ATOMIC512
) << 1) - 2 |
4207 SQLITE_IOCAP_SEQUENTIAL
| /* The ram filesystem has no write behind
4208 ** so it is ordered */
4210 }else if( strstr(fsInfo
.f_basetype
, "dos") ){
4211 pFile
->sectorSize
= fsInfo
.f_bsize
;
4212 pFile
->deviceCharacteristics
=
4213 /* full bitset of atomics from max sector size and smaller */
4214 ((pFile
->sectorSize
/ 512 * SQLITE_IOCAP_ATOMIC512
) << 1) - 2 |
4215 SQLITE_IOCAP_SEQUENTIAL
| /* The ram filesystem has no write behind
4216 ** so it is ordered */
4219 pFile
->deviceCharacteristics
=
4220 SQLITE_IOCAP_ATOMIC512
| /* blocks are atomic */
4221 SQLITE_IOCAP_SAFE_APPEND
| /* growing the file does not occur until
4222 ** the write succeeds */
4226 /* Last chance verification. If the sector size isn't a multiple of 512
4227 ** then it isn't valid.*/
4228 if( pFile
->sectorSize
% 512 != 0 ){
4229 pFile
->deviceCharacteristics
= 0;
4230 pFile
->sectorSize
= SQLITE_DEFAULT_SECTOR_SIZE
;
4236 ** Return the sector size in bytes of the underlying block device for
4237 ** the specified file. This is almost always 512 bytes, but may be
4238 ** larger for some devices.
4240 ** SQLite code assumes this function cannot fail. It also assumes that
4241 ** if two files are created in the same file-system directory (i.e.
4242 ** a database and its journal file) that the sector size will be the
4245 static int unixSectorSize(sqlite3_file
*id
){
4246 unixFile
*pFd
= (unixFile
*)id
;
4247 setDeviceCharacteristics(pFd
);
4248 return pFd
->sectorSize
;
4252 ** Return the device characteristics for the file.
4254 ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
4255 ** However, that choice is controversial since technically the underlying
4256 ** file system does not always provide powersafe overwrites. (In other
4257 ** words, after a power-loss event, parts of the file that were never
4258 ** written might end up being altered.) However, non-PSOW behavior is very,
4259 ** very rare. And asserting PSOW makes a large reduction in the amount
4260 ** of required I/O for journaling, since a lot of padding is eliminated.
4261 ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
4262 ** available to turn it off and URI query parameter available to turn it off.
4264 static int unixDeviceCharacteristics(sqlite3_file
*id
){
4265 unixFile
*pFd
= (unixFile
*)id
;
4266 setDeviceCharacteristics(pFd
);
4267 return pFd
->deviceCharacteristics
;
4270 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
4273 ** Return the system page size.
4275 ** This function should not be called directly by other code in this file.
4276 ** Instead, it should be called via macro osGetpagesize().
4278 static int unixGetpagesize(void){
4281 #elif defined(_BSD_SOURCE)
4282 return getpagesize();
4284 return (int)sysconf(_SC_PAGESIZE
);
4288 #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
4290 #ifndef SQLITE_OMIT_WAL
4293 ** Object used to represent an shared memory buffer.
4295 ** When multiple threads all reference the same wal-index, each thread
4296 ** has its own unixShm object, but they all point to a single instance
4297 ** of this unixShmNode object. In other words, each wal-index is opened
4298 ** only once per process.
4300 ** Each unixShmNode object is connected to a single unixInodeInfo object.
4301 ** We could coalesce this object into unixInodeInfo, but that would mean
4302 ** every open file that does not use shared memory (in other words, most
4303 ** open files) would have to carry around this extra information. So
4304 ** the unixInodeInfo object contains a pointer to this unixShmNode object
4305 ** and the unixShmNode object is created only when needed.
4307 ** unixMutexHeld() must be true when creating or destroying
4308 ** this object or while reading or writing the following fields:
4312 ** The following fields are read-only after the object is created:
4317 ** Either unixShmNode.pShmMutex must be held or unixShmNode.nRef==0 and
4318 ** unixMutexHeld() is true when reading or writing any other field
4319 ** in this structure.
4321 ** aLock[SQLITE_SHM_NLOCK]:
4322 ** This array records the various locks held by clients on each of the
4323 ** SQLITE_SHM_NLOCK slots. If the aLock[] entry is set to 0, then no
4324 ** locks are held by the process on this slot. If it is set to -1, then
4325 ** some client holds an EXCLUSIVE lock on the locking slot. If the aLock[]
4326 ** value is set to a positive value, then it is the number of shared
4327 ** locks currently held on the slot.
4329 ** aMutex[SQLITE_SHM_NLOCK]:
4330 ** Normally, when SQLITE_ENABLE_SETLK_TIMEOUT is not defined, mutex
4331 ** pShmMutex is used to protect the aLock[] array and the right to
4332 ** call fcntl() on unixShmNode.hShm to obtain or release locks.
4334 ** If SQLITE_ENABLE_SETLK_TIMEOUT is defined though, we use an array
4335 ** of mutexes - one for each locking slot. To read or write locking
4336 ** slot aLock[iSlot], the caller must hold the corresponding mutex
4337 ** aMutex[iSlot]. Similarly, to call fcntl() to obtain or release a
4338 ** lock corresponding to slot iSlot, mutex aMutex[iSlot] must be held.
4340 struct unixShmNode
{
4341 unixInodeInfo
*pInode
; /* unixInodeInfo that owns this SHM node */
4342 sqlite3_mutex
*pShmMutex
; /* Mutex to access this object */
4343 char *zFilename
; /* Name of the mmapped file */
4344 int hShm
; /* Open file descriptor */
4345 int szRegion
; /* Size of shared-memory regions */
4346 u16 nRegion
; /* Size of array apRegion */
4347 u8 isReadonly
; /* True if read-only */
4348 u8 isUnlocked
; /* True if no DMS lock held */
4349 char **apRegion
; /* Array of mapped shared-memory regions */
4350 int nRef
; /* Number of unixShm objects pointing to this */
4351 unixShm
*pFirst
; /* All unixShm objects pointing to this */
4352 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
4353 sqlite3_mutex
*aMutex
[SQLITE_SHM_NLOCK
];
4355 int aLock
[SQLITE_SHM_NLOCK
]; /* # shared locks on slot, -1==excl lock */
4357 u8 nextShmId
; /* Next available unixShm.id value */
4362 ** Structure used internally by this VFS to record the state of an
4363 ** open shared memory connection.
4365 ** The following fields are initialized when this object is created and
4366 ** are read-only thereafter:
4371 ** All other fields are read/write. The unixShm.pShmNode->pShmMutex must
4372 ** be held while accessing any read/write fields.
4375 unixShmNode
*pShmNode
; /* The underlying unixShmNode object */
4376 unixShm
*pNext
; /* Next unixShm with the same unixShmNode */
4377 u8 hasMutex
; /* True if holding the unixShmNode->pShmMutex */
4378 u8 id
; /* Id of this connection within its unixShmNode */
4379 u16 sharedMask
; /* Mask of shared locks held */
4380 u16 exclMask
; /* Mask of exclusive locks held */
4384 ** Constants used for locking
4386 #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
4387 #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
4390 ** Use F_GETLK to check whether or not there are any readers with open
4391 ** wal-mode transactions in other processes on database file pFile. If
4392 ** no error occurs, return SQLITE_OK and set (*piOut) to 1 if there are
4393 ** such transactions, or 0 otherwise. If an error occurs, return an
4394 ** SQLite error code. The final value of *piOut is undefined in this
4397 static int unixFcntlExternalReader(unixFile
*pFile
, int *piOut
){
4401 unixShmNode
*pShmNode
= pFile
->pShm
->pShmNode
;
4404 memset(&f
, 0, sizeof(f
));
4406 f
.l_whence
= SEEK_SET
;
4407 f
.l_start
= UNIX_SHM_BASE
+ 3;
4408 f
.l_len
= SQLITE_SHM_NLOCK
- 3;
4410 sqlite3_mutex_enter(pShmNode
->pShmMutex
);
4411 if( osFcntl(pShmNode
->hShm
, F_GETLK
, &f
)<0 ){
4412 rc
= SQLITE_IOERR_LOCK
;
4414 *piOut
= (f
.l_type
!=F_UNLCK
);
4416 sqlite3_mutex_leave(pShmNode
->pShmMutex
);
4424 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
4426 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4429 static int unixShmSystemLock(
4430 unixFile
*pFile
, /* Open connection to the WAL file */
4431 int lockType
, /* F_UNLCK, F_RDLCK, or F_WRLCK */
4432 int ofst
, /* First byte of the locking range */
4433 int n
/* Number of bytes to lock */
4435 unixShmNode
*pShmNode
; /* Apply locks to this open shared-memory segment */
4436 struct flock f
; /* The posix advisory locking structure */
4437 int rc
= SQLITE_OK
; /* Result code form fcntl() */
4439 pShmNode
= pFile
->pInode
->pShmNode
;
4441 /* Assert that the parameters are within expected range and that the
4442 ** correct mutex or mutexes are held. */
4443 assert( pShmNode
->nRef
>=0 );
4444 assert( (ofst
==UNIX_SHM_DMS
&& n
==1)
4445 || (ofst
>=UNIX_SHM_BASE
&& ofst
+n
<=(UNIX_SHM_BASE
+SQLITE_SHM_NLOCK
))
4447 if( ofst
==UNIX_SHM_DMS
){
4448 assert( pShmNode
->nRef
>0 || unixMutexHeld() );
4449 assert( pShmNode
->nRef
==0 || sqlite3_mutex_held(pShmNode
->pShmMutex
) );
4451 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
4453 for(ii
=ofst
-UNIX_SHM_BASE
; ii
<ofst
-UNIX_SHM_BASE
+n
; ii
++){
4454 assert( sqlite3_mutex_held(pShmNode
->aMutex
[ii
]) );
4457 assert( sqlite3_mutex_held(pShmNode
->pShmMutex
) );
4458 assert( pShmNode
->nRef
>0 );
4462 /* Shared locks never span more than one byte */
4463 assert( n
==1 || lockType
!=F_RDLCK
);
4465 /* Locks are within range */
4466 assert( n
>=1 && n
<=SQLITE_SHM_NLOCK
);
4467 assert( ofst
>=UNIX_SHM_BASE
&& ofst
<=(UNIX_SHM_DMS
+SQLITE_SHM_NLOCK
) );
4469 if( pShmNode
->hShm
>=0 ){
4471 /* Initialize the locking parameters */
4472 f
.l_type
= lockType
;
4473 f
.l_whence
= SEEK_SET
;
4476 res
= osSetPosixAdvisoryLock(pShmNode
->hShm
, &f
, pFile
);
4478 #if defined(SQLITE_ENABLE_SETLK_TIMEOUT) && SQLITE_ENABLE_SETLK_TIMEOUT==1
4479 rc
= (pFile
->iBusyTimeout
? SQLITE_BUSY_TIMEOUT
: SQLITE_BUSY
);
4486 /* Do debug tracing */
4488 OSTRACE(("SHM-LOCK "));
4489 if( rc
==SQLITE_OK
){
4490 if( lockType
==F_UNLCK
){
4491 OSTRACE(("unlock %d..%d ok\n", ofst
, ofst
+n
-1));
4492 }else if( lockType
==F_RDLCK
){
4493 OSTRACE(("read-lock %d..%d ok\n", ofst
, ofst
+n
-1));
4495 assert( lockType
==F_WRLCK
);
4496 OSTRACE(("write-lock %d..%d ok\n", ofst
, ofst
+n
-1));
4499 if( lockType
==F_UNLCK
){
4500 OSTRACE(("unlock %d..%d failed\n", ofst
, ofst
+n
-1));
4501 }else if( lockType
==F_RDLCK
){
4502 OSTRACE(("read-lock %d..%d failed\n", ofst
, ofst
+n
-1));
4504 assert( lockType
==F_WRLCK
);
4505 OSTRACE(("write-lock %d..%d failed\n", ofst
, ofst
+n
-1));
4514 ** Return the minimum number of 32KB shm regions that should be mapped at
4515 ** a time, assuming that each mapping must be an integer multiple of the
4516 ** current system page-size.
4518 ** Usually, this is 1. The exception seems to be systems that are configured
4519 ** to use 64KB pages - in this case each mapping must cover at least two
4522 static int unixShmRegionPerMap(void){
4523 int shmsz
= 32*1024; /* SHM region size */
4524 int pgsz
= osGetpagesize(); /* System page size */
4525 assert( ((pgsz
-1)&pgsz
)==0 ); /* Page size must be a power of 2 */
4526 if( pgsz
<shmsz
) return 1;
4531 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
4533 ** This is not a VFS shared-memory method; it is a utility function called
4534 ** by VFS shared-memory methods.
4536 static void unixShmPurge(unixFile
*pFd
){
4537 unixShmNode
*p
= pFd
->pInode
->pShmNode
;
4538 assert( unixMutexHeld() );
4539 if( p
&& ALWAYS(p
->nRef
==0) ){
4540 int nShmPerMap
= unixShmRegionPerMap();
4542 assert( p
->pInode
==pFd
->pInode
);
4543 sqlite3_mutex_free(p
->pShmMutex
);
4544 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
4545 for(i
=0; i
<SQLITE_SHM_NLOCK
; i
++){
4546 sqlite3_mutex_free(p
->aMutex
[i
]);
4549 for(i
=0; i
<p
->nRegion
; i
+=nShmPerMap
){
4551 osMunmap(p
->apRegion
[i
], p
->szRegion
);
4553 sqlite3_free(p
->apRegion
[i
]);
4556 sqlite3_free(p
->apRegion
);
4558 robust_close(pFd
, p
->hShm
, __LINE__
);
4561 p
->pInode
->pShmNode
= 0;
4567 ** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
4568 ** take it now. Return SQLITE_OK if successful, or an SQLite error
4571 ** If the DMS cannot be locked because this is a readonly_shm=1
4572 ** connection and no other process already holds a lock, return
4573 ** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
4575 static int unixLockSharedMemory(unixFile
*pDbFd
, unixShmNode
*pShmNode
){
4579 /* Use F_GETLK to determine the locks other processes are holding
4580 ** on the DMS byte. If it indicates that another process is holding
4581 ** a SHARED lock, then this process may also take a SHARED lock
4582 ** and proceed with opening the *-shm file.
4584 ** Or, if no other process is holding any lock, then this process
4585 ** is the first to open it. In this case take an EXCLUSIVE lock on the
4586 ** DMS byte and truncate the *-shm file to zero bytes in size. Then
4587 ** downgrade to a SHARED lock on the DMS byte.
4589 ** If another process is holding an EXCLUSIVE lock on the DMS byte,
4590 ** return SQLITE_BUSY to the caller (it will try again). An earlier
4591 ** version of this code attempted the SHARED lock at this point. But
4592 ** this introduced a subtle race condition: if the process holding
4593 ** EXCLUSIVE failed just before truncating the *-shm file, then this
4594 ** process might open and use the *-shm file without truncating it.
4595 ** And if the *-shm file has been corrupted by a power failure or
4596 ** system crash, the database itself may also become corrupt. */
4597 lock
.l_whence
= SEEK_SET
;
4598 lock
.l_start
= UNIX_SHM_DMS
;
4600 lock
.l_type
= F_WRLCK
;
4601 if( osFcntl(pShmNode
->hShm
, F_GETLK
, &lock
)!=0 ) {
4602 rc
= SQLITE_IOERR_LOCK
;
4603 }else if( lock
.l_type
==F_UNLCK
){
4604 if( pShmNode
->isReadonly
){
4605 pShmNode
->isUnlocked
= 1;
4606 rc
= SQLITE_READONLY_CANTINIT
;
4608 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
4609 /* Do not use a blocking lock here. If the lock cannot be obtained
4610 ** immediately, it means some other connection is truncating the
4611 ** *-shm file. And after it has done so, it will not release its
4612 ** lock, but only downgrade it to a shared lock. So no point in
4613 ** blocking here. The call below to obtain the shared DMS lock may
4614 ** use a blocking lock. */
4615 int iSaveTimeout
= pDbFd
->iBusyTimeout
;
4616 pDbFd
->iBusyTimeout
= 0;
4618 rc
= unixShmSystemLock(pDbFd
, F_WRLCK
, UNIX_SHM_DMS
, 1);
4619 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
4620 pDbFd
->iBusyTimeout
= iSaveTimeout
;
4622 /* The first connection to attach must truncate the -shm file. We
4623 ** truncate to 3 bytes (an arbitrary small number, less than the
4624 ** -shm header size) rather than 0 as a system debugging aid, to
4625 ** help detect if a -shm file truncation is legitimate or is the work
4626 ** or a rogue process. */
4627 if( rc
==SQLITE_OK
&& robust_ftruncate(pShmNode
->hShm
, 3) ){
4628 rc
= unixLogError(SQLITE_IOERR_SHMOPEN
,"ftruncate",pShmNode
->zFilename
);
4631 }else if( lock
.l_type
==F_WRLCK
){
4635 if( rc
==SQLITE_OK
){
4636 assert( lock
.l_type
==F_UNLCK
|| lock
.l_type
==F_RDLCK
);
4637 rc
= unixShmSystemLock(pDbFd
, F_RDLCK
, UNIX_SHM_DMS
, 1);
4643 ** Open a shared-memory area associated with open database file pDbFd.
4644 ** This particular implementation uses mmapped files.
4646 ** The file used to implement shared-memory is in the same directory
4647 ** as the open database file and has the same name as the open database
4648 ** file with the "-shm" suffix added. For example, if the database file
4649 ** is "/home/user1/config.db" then the file that is created and mmapped
4650 ** for shared memory will be called "/home/user1/config.db-shm".
4652 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
4653 ** some other tmpfs mount. But if a file in a different directory
4654 ** from the database file is used, then differing access permissions
4655 ** or a chroot() might cause two different processes on the same
4656 ** database to end up using different files for shared memory -
4657 ** meaning that their memory would not really be shared - resulting
4658 ** in database corruption. Nevertheless, this tmpfs file usage
4659 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4660 ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4661 ** option results in an incompatible build of SQLite; builds of SQLite
4662 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4663 ** same database file at the same time, database corruption will likely
4664 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4665 ** "unsupported" and may go away in a future SQLite release.
4667 ** When opening a new shared-memory file, if no other instances of that
4668 ** file are currently open, in this process or in other processes, then
4669 ** the file must be truncated to zero length or have its header cleared.
4671 ** If the original database file (pDbFd) is using the "unix-excl" VFS
4672 ** that means that an exclusive lock is held on the database file and
4673 ** that no other processes are able to read or write the database. In
4674 ** that case, we do not really need shared memory. No shared memory
4675 ** file is created. The shared memory will be simulated with heap memory.
4677 static int unixOpenSharedMemory(unixFile
*pDbFd
){
4678 struct unixShm
*p
= 0; /* The connection to be opened */
4679 struct unixShmNode
*pShmNode
; /* The underlying mmapped file */
4680 int rc
= SQLITE_OK
; /* Result code */
4681 unixInodeInfo
*pInode
; /* The inode of fd */
4682 char *zShm
; /* Name of the file used for SHM */
4683 int nShmFilename
; /* Size of the SHM filename in bytes */
4685 /* Allocate space for the new unixShm object. */
4686 p
= sqlite3_malloc64( sizeof(*p
) );
4687 if( p
==0 ) return SQLITE_NOMEM_BKPT
;
4688 memset(p
, 0, sizeof(*p
));
4689 assert( pDbFd
->pShm
==0 );
4691 /* Check to see if a unixShmNode object already exists. Reuse an existing
4692 ** one if present. Create a new one if necessary.
4694 assert( unixFileMutexNotheld(pDbFd
) );
4696 pInode
= pDbFd
->pInode
;
4697 pShmNode
= pInode
->pShmNode
;
4699 struct stat sStat
; /* fstat() info for database file */
4700 #ifndef SQLITE_SHM_DIRECTORY
4701 const char *zBasePath
= pDbFd
->zPath
;
4704 /* Call fstat() to figure out the permissions on the database file. If
4705 ** a new *-shm file is created, an attempt will be made to create it
4706 ** with the same permissions.
4708 if( osFstat(pDbFd
->h
, &sStat
) ){
4709 rc
= SQLITE_IOERR_FSTAT
;
4713 #ifdef SQLITE_SHM_DIRECTORY
4714 nShmFilename
= sizeof(SQLITE_SHM_DIRECTORY
) + 31;
4716 nShmFilename
= 6 + (int)strlen(zBasePath
);
4718 pShmNode
= sqlite3_malloc64( sizeof(*pShmNode
) + nShmFilename
);
4720 rc
= SQLITE_NOMEM_BKPT
;
4723 memset(pShmNode
, 0, sizeof(*pShmNode
)+nShmFilename
);
4724 zShm
= pShmNode
->zFilename
= (char*)&pShmNode
[1];
4725 #ifdef SQLITE_SHM_DIRECTORY
4726 sqlite3_snprintf(nShmFilename
, zShm
,
4727 SQLITE_SHM_DIRECTORY
"/sqlite-shm-%x-%x",
4728 (u32
)sStat
.st_ino
, (u32
)sStat
.st_dev
);
4730 sqlite3_snprintf(nShmFilename
, zShm
, "%s-shm", zBasePath
);
4731 sqlite3FileSuffix3(pDbFd
->zPath
, zShm
);
4733 pShmNode
->hShm
= -1;
4734 pDbFd
->pInode
->pShmNode
= pShmNode
;
4735 pShmNode
->pInode
= pDbFd
->pInode
;
4736 if( sqlite3GlobalConfig
.bCoreMutex
){
4737 pShmNode
->pShmMutex
= sqlite3_mutex_alloc(SQLITE_MUTEX_FAST
);
4738 if( pShmNode
->pShmMutex
==0 ){
4739 rc
= SQLITE_NOMEM_BKPT
;
4742 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
4745 for(ii
=0; ii
<SQLITE_SHM_NLOCK
; ii
++){
4746 pShmNode
->aMutex
[ii
] = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST
);
4747 if( pShmNode
->aMutex
[ii
]==0 ){
4748 rc
= SQLITE_NOMEM_BKPT
;
4756 if( pInode
->bProcessLock
==0 ){
4757 if( 0==sqlite3_uri_boolean(pDbFd
->zPath
, "readonly_shm", 0) ){
4758 pShmNode
->hShm
= robust_open(zShm
, O_RDWR
|O_CREAT
|O_NOFOLLOW
,
4759 (sStat
.st_mode
&0777));
4761 if( pShmNode
->hShm
<0 ){
4762 pShmNode
->hShm
= robust_open(zShm
, O_RDONLY
|O_NOFOLLOW
,
4763 (sStat
.st_mode
&0777));
4764 if( pShmNode
->hShm
<0 ){
4765 rc
= unixLogError(SQLITE_CANTOPEN_BKPT
, "open", zShm
);
4768 pShmNode
->isReadonly
= 1;
4771 /* If this process is running as root, make sure that the SHM file
4772 ** is owned by the same user that owns the original database. Otherwise,
4773 ** the original owner will not be able to connect.
4775 robustFchown(pShmNode
->hShm
, sStat
.st_uid
, sStat
.st_gid
);
4777 rc
= unixLockSharedMemory(pDbFd
, pShmNode
);
4778 if( rc
!=SQLITE_OK
&& rc
!=SQLITE_READONLY_CANTINIT
) goto shm_open_err
;
4782 /* Make the new connection a child of the unixShmNode */
4783 p
->pShmNode
= pShmNode
;
4785 p
->id
= pShmNode
->nextShmId
++;
4791 /* The reference count on pShmNode has already been incremented under
4792 ** the cover of the unixEnterMutex() mutex and the pointer from the
4793 ** new (struct unixShm) object to the pShmNode has been set. All that is
4794 ** left to do is to link the new object into the linked list starting
4795 ** at pShmNode->pFirst. This must be done while holding the
4796 ** pShmNode->pShmMutex.
4798 sqlite3_mutex_enter(pShmNode
->pShmMutex
);
4799 p
->pNext
= pShmNode
->pFirst
;
4800 pShmNode
->pFirst
= p
;
4801 sqlite3_mutex_leave(pShmNode
->pShmMutex
);
4804 /* Jump here on any error */
4806 unixShmPurge(pDbFd
); /* This call frees pShmNode if required */
4813 ** This function is called to obtain a pointer to region iRegion of the
4814 ** shared-memory associated with the database file fd. Shared-memory regions
4815 ** are numbered starting from zero. Each shared-memory region is szRegion
4818 ** If an error occurs, an error code is returned and *pp is set to NULL.
4820 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4821 ** region has not been allocated (by any client, including one running in a
4822 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4823 ** bExtend is non-zero and the requested shared-memory region has not yet
4824 ** been allocated, it is allocated by this function.
4826 ** If the shared-memory region has already been allocated or is allocated by
4827 ** this call as described above, then it is mapped into this processes
4828 ** address space (if it is not already), *pp is set to point to the mapped
4829 ** memory and SQLITE_OK returned.
4831 static int unixShmMap(
4832 sqlite3_file
*fd
, /* Handle open on database file */
4833 int iRegion
, /* Region to retrieve */
4834 int szRegion
, /* Size of regions */
4835 int bExtend
, /* True to extend file if necessary */
4836 void volatile **pp
/* OUT: Mapped memory */
4838 unixFile
*pDbFd
= (unixFile
*)fd
;
4840 unixShmNode
*pShmNode
;
4842 int nShmPerMap
= unixShmRegionPerMap();
4845 /* If the shared-memory file has not yet been opened, open it now. */
4846 if( pDbFd
->pShm
==0 ){
4847 rc
= unixOpenSharedMemory(pDbFd
);
4848 if( rc
!=SQLITE_OK
) return rc
;
4852 pShmNode
= p
->pShmNode
;
4853 sqlite3_mutex_enter(pShmNode
->pShmMutex
);
4854 if( pShmNode
->isUnlocked
){
4855 rc
= unixLockSharedMemory(pDbFd
, pShmNode
);
4856 if( rc
!=SQLITE_OK
) goto shmpage_out
;
4857 pShmNode
->isUnlocked
= 0;
4859 assert( szRegion
==pShmNode
->szRegion
|| pShmNode
->nRegion
==0 );
4860 assert( pShmNode
->pInode
==pDbFd
->pInode
);
4861 assert( pShmNode
->hShm
>=0 || pDbFd
->pInode
->bProcessLock
==1 );
4862 assert( pShmNode
->hShm
<0 || pDbFd
->pInode
->bProcessLock
==0 );
4864 /* Minimum number of regions required to be mapped. */
4865 nReqRegion
= ((iRegion
+nShmPerMap
) / nShmPerMap
) * nShmPerMap
;
4867 if( pShmNode
->nRegion
<nReqRegion
){
4868 char **apNew
; /* New apRegion[] array */
4869 int nByte
= nReqRegion
*szRegion
; /* Minimum required file size */
4870 struct stat sStat
; /* Used by fstat() */
4872 pShmNode
->szRegion
= szRegion
;
4874 if( pShmNode
->hShm
>=0 ){
4875 /* The requested region is not mapped into this processes address space.
4876 ** Check to see if it has been allocated (i.e. if the wal-index file is
4877 ** large enough to contain the requested region).
4879 if( osFstat(pShmNode
->hShm
, &sStat
) ){
4880 rc
= SQLITE_IOERR_SHMSIZE
;
4884 if( sStat
.st_size
<nByte
){
4885 /* The requested memory region does not exist. If bExtend is set to
4886 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
4892 /* Alternatively, if bExtend is true, extend the file. Do this by
4893 ** writing a single byte to the end of each (OS) page being
4894 ** allocated or extended. Technically, we need only write to the
4895 ** last page in order to extend the file. But writing to all new
4896 ** pages forces the OS to allocate them immediately, which reduces
4897 ** the chances of SIGBUS while accessing the mapped region later on.
4900 static const int pgsz
= 4096;
4903 /* Write to the last byte of each newly allocated or extended page */
4904 assert( (nByte
% pgsz
)==0 );
4905 for(iPg
=(sStat
.st_size
/pgsz
); iPg
<(nByte
/pgsz
); iPg
++){
4907 if( seekAndWriteFd(pShmNode
->hShm
, iPg
*pgsz
+ pgsz
-1,"",1,&x
)!=1 ){
4908 const char *zFile
= pShmNode
->zFilename
;
4909 rc
= unixLogError(SQLITE_IOERR_SHMSIZE
, "write", zFile
);
4917 /* Map the requested memory region into this processes address space. */
4918 apNew
= (char **)sqlite3_realloc(
4919 pShmNode
->apRegion
, nReqRegion
*sizeof(char *)
4922 rc
= SQLITE_IOERR_NOMEM_BKPT
;
4925 pShmNode
->apRegion
= apNew
;
4926 while( pShmNode
->nRegion
<nReqRegion
){
4927 int nMap
= szRegion
*nShmPerMap
;
4930 if( pShmNode
->hShm
>=0 ){
4931 pMem
= osMmap(0, nMap
,
4932 pShmNode
->isReadonly
? PROT_READ
: PROT_READ
|PROT_WRITE
,
4933 MAP_SHARED
, pShmNode
->hShm
, szRegion
*(i64
)pShmNode
->nRegion
4935 if( pMem
==MAP_FAILED
){
4936 rc
= unixLogError(SQLITE_IOERR_SHMMAP
, "mmap", pShmNode
->zFilename
);
4940 pMem
= sqlite3_malloc64(nMap
);
4942 rc
= SQLITE_NOMEM_BKPT
;
4945 memset(pMem
, 0, nMap
);
4948 for(i
=0; i
<nShmPerMap
; i
++){
4949 pShmNode
->apRegion
[pShmNode
->nRegion
+i
] = &((char*)pMem
)[szRegion
*i
];
4951 pShmNode
->nRegion
+= nShmPerMap
;
4956 if( pShmNode
->nRegion
>iRegion
){
4957 *pp
= pShmNode
->apRegion
[iRegion
];
4961 if( pShmNode
->isReadonly
&& rc
==SQLITE_OK
) rc
= SQLITE_READONLY
;
4962 sqlite3_mutex_leave(pShmNode
->pShmMutex
);
4967 ** Check that the pShmNode->aLock[] array comports with the locking bitmasks
4968 ** held by each client. Return true if it does, or false otherwise. This
4969 ** is to be used in an assert(). e.g.
4971 ** assert( assertLockingArrayOk(pShmNode) );
4974 static int assertLockingArrayOk(unixShmNode
*pShmNode
){
4975 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
4979 int aLock
[SQLITE_SHM_NLOCK
];
4981 memset(aLock
, 0, sizeof(aLock
));
4982 for(pX
=pShmNode
->pFirst
; pX
; pX
=pX
->pNext
){
4984 for(i
=0; i
<SQLITE_SHM_NLOCK
; i
++){
4985 if( pX
->exclMask
& (1<<i
) ){
4986 assert( aLock
[i
]==0 );
4988 }else if( pX
->sharedMask
& (1<<i
) ){
4989 assert( aLock
[i
]>=0 );
4995 assert( 0==memcmp(pShmNode
->aLock
, aLock
, sizeof(aLock
)) );
4996 return (memcmp(pShmNode
->aLock
, aLock
, sizeof(aLock
))==0);
5002 ** Change the lock state for a shared-memory segment.
5004 ** Note that the relationship between SHARED and EXCLUSIVE locks is a little
5005 ** different here than in posix. In xShmLock(), one can go from unlocked
5006 ** to shared and back or from unlocked to exclusive and back. But one may
5007 ** not go from shared to exclusive or from exclusive to shared.
5009 static int unixShmLock(
5010 sqlite3_file
*fd
, /* Database file holding the shared memory */
5011 int ofst
, /* First lock to acquire or release */
5012 int n
, /* Number of locks to acquire or release */
5013 int flags
/* What to do with the lock */
5015 unixFile
*pDbFd
= (unixFile
*)fd
; /* Connection holding shared memory */
5016 unixShm
*p
; /* The shared memory being locked */
5017 unixShmNode
*pShmNode
; /* The underlying file iNode */
5018 int rc
= SQLITE_OK
; /* Result code */
5019 u16 mask
= (1<<(ofst
+n
)) - (1<<ofst
); /* Mask of locks to take or release */
5023 if( p
==0 ) return SQLITE_IOERR_SHMLOCK
;
5024 pShmNode
= p
->pShmNode
;
5025 if( NEVER(pShmNode
==0) ) return SQLITE_IOERR_SHMLOCK
;
5026 aLock
= pShmNode
->aLock
;
5028 assert( pShmNode
==pDbFd
->pInode
->pShmNode
);
5029 assert( pShmNode
->pInode
==pDbFd
->pInode
);
5030 assert( ofst
>=0 && ofst
+n
<=SQLITE_SHM_NLOCK
);
5032 assert( flags
==(SQLITE_SHM_LOCK
| SQLITE_SHM_SHARED
)
5033 || flags
==(SQLITE_SHM_LOCK
| SQLITE_SHM_EXCLUSIVE
)
5034 || flags
==(SQLITE_SHM_UNLOCK
| SQLITE_SHM_SHARED
)
5035 || flags
==(SQLITE_SHM_UNLOCK
| SQLITE_SHM_EXCLUSIVE
) );
5036 assert( n
==1 || (flags
& SQLITE_SHM_EXCLUSIVE
)!=0 );
5037 assert( pShmNode
->hShm
>=0 || pDbFd
->pInode
->bProcessLock
==1 );
5038 assert( pShmNode
->hShm
<0 || pDbFd
->pInode
->bProcessLock
==0 );
5040 /* Check that, if this to be a blocking lock, no locks that occur later
5041 ** in the following list than the lock being obtained are already held:
5043 ** 1. Checkpointer lock (ofst==1).
5044 ** 2. Write lock (ofst==0).
5045 ** 3. Read locks (ofst>=3 && ofst<SQLITE_SHM_NLOCK).
5047 ** In other words, if this is a blocking lock, none of the locks that
5048 ** occur later in the above list than the lock being obtained may be
5051 ** It is not permitted to block on the RECOVER lock.
5053 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
5055 u16 lockMask
= (p
->exclMask
|p
->sharedMask
);
5056 assert( (flags
& SQLITE_SHM_UNLOCK
) || pDbFd
->iBusyTimeout
==0 || (
5057 (ofst
!=2) /* not RECOVER */
5058 && (ofst
!=1 || lockMask
==0 || lockMask
==2)
5059 && (ofst
!=0 || lockMask
<3)
5060 && (ofst
<3 || lockMask
<(1<<ofst
))
5065 /* Check if there is any work to do. There are three cases:
5067 ** a) An unlock operation where there are locks to unlock,
5068 ** b) An shared lock where the requested lock is not already held
5069 ** c) An exclusive lock where the requested lock is not already held
5071 ** The SQLite core never requests an exclusive lock that it already holds.
5072 ** This is assert()ed below.
5074 assert( flags
!=(SQLITE_SHM_EXCLUSIVE
|SQLITE_SHM_LOCK
)
5075 || 0==(p
->exclMask
& mask
)
5077 if( ((flags
& SQLITE_SHM_UNLOCK
) && ((p
->exclMask
|p
->sharedMask
) & mask
))
5078 || (flags
==(SQLITE_SHM_SHARED
|SQLITE_SHM_LOCK
) && 0==(p
->sharedMask
& mask
))
5079 || (flags
==(SQLITE_SHM_EXCLUSIVE
|SQLITE_SHM_LOCK
))
5082 /* Take the required mutexes. In SETLK_TIMEOUT mode (blocking locks), if
5083 ** this is an attempt on an exclusive lock use sqlite3_mutex_try(). If any
5084 ** other thread is holding this mutex, then it is either holding or about
5085 ** to hold a lock exclusive to the one being requested, and we may
5086 ** therefore return SQLITE_BUSY to the caller.
5088 ** Doing this prevents some deadlock scenarios. For example, thread 1 may
5089 ** be a checkpointer blocked waiting on the WRITER lock. And thread 2
5090 ** may be a normal SQL client upgrading to a write transaction. In this
5091 ** case thread 2 does a non-blocking request for the WRITER lock. But -
5092 ** if it were to use sqlite3_mutex_enter() then it would effectively
5093 ** become a (doomed) blocking request, as thread 2 would block until thread
5094 ** 1 obtained WRITER and released the mutex. Since thread 2 already holds
5095 ** a lock on a read-locking slot at this point, this breaks the
5096 ** anti-deadlock rules (see above). */
5097 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
5099 for(iMutex
=ofst
; iMutex
<ofst
+n
; iMutex
++){
5100 if( flags
==(SQLITE_SHM_LOCK
|SQLITE_SHM_EXCLUSIVE
) ){
5101 rc
= sqlite3_mutex_try(pShmNode
->aMutex
[iMutex
]);
5102 if( rc
!=SQLITE_OK
) goto leave_shmnode_mutexes
;
5104 sqlite3_mutex_enter(pShmNode
->aMutex
[iMutex
]);
5108 sqlite3_mutex_enter(pShmNode
->pShmMutex
);
5111 if( ALWAYS(rc
==SQLITE_OK
) ){
5112 if( flags
& SQLITE_SHM_UNLOCK
){
5113 /* Case (a) - unlock. */
5115 assert( (p
->exclMask
& p
->sharedMask
)==0 );
5116 assert( !(flags
& SQLITE_SHM_EXCLUSIVE
) || (p
->exclMask
& mask
)==mask
);
5117 assert( !(flags
& SQLITE_SHM_SHARED
) || (p
->sharedMask
& mask
)==mask
);
5119 /* If this is a SHARED lock being unlocked, it is possible that other
5120 ** clients within this process are holding the same SHARED lock. In
5121 ** this case, set bUnlock to 0 so that the posix lock is not removed
5122 ** from the file-descriptor below. */
5123 if( flags
& SQLITE_SHM_SHARED
){
5125 assert( aLock
[ofst
]>=1 );
5126 if( aLock
[ofst
]>1 ){
5129 p
->sharedMask
&= ~mask
;
5134 rc
= unixShmSystemLock(pDbFd
, F_UNLCK
, ofst
+UNIX_SHM_BASE
, n
);
5135 if( rc
==SQLITE_OK
){
5136 memset(&aLock
[ofst
], 0, sizeof(int)*n
);
5137 p
->sharedMask
&= ~mask
;
5138 p
->exclMask
&= ~mask
;
5141 }else if( flags
& SQLITE_SHM_SHARED
){
5142 /* Case (b) - a shared lock. */
5144 if( aLock
[ofst
]<0 ){
5145 /* An exclusive lock is held by some other connection. BUSY. */
5147 }else if( aLock
[ofst
]==0 ){
5148 rc
= unixShmSystemLock(pDbFd
, F_RDLCK
, ofst
+UNIX_SHM_BASE
, n
);
5151 /* Get the local shared locks */
5152 if( rc
==SQLITE_OK
){
5153 p
->sharedMask
|= mask
;
5157 /* Case (c) - an exclusive lock. */
5160 assert( flags
==(SQLITE_SHM_LOCK
|SQLITE_SHM_EXCLUSIVE
) );
5161 assert( (p
->sharedMask
& mask
)==0 );
5162 assert( (p
->exclMask
& mask
)==0 );
5164 /* Make sure no sibling connections hold locks that will block this
5165 ** lock. If any do, return SQLITE_BUSY right away. */
5166 for(ii
=ofst
; ii
<ofst
+n
; ii
++){
5173 /* Get the exclusive locks at the system level. Then if successful
5174 ** also update the in-memory values. */
5175 if( rc
==SQLITE_OK
){
5176 rc
= unixShmSystemLock(pDbFd
, F_WRLCK
, ofst
+UNIX_SHM_BASE
, n
);
5177 if( rc
==SQLITE_OK
){
5178 p
->exclMask
|= mask
;
5179 for(ii
=ofst
; ii
<ofst
+n
; ii
++){
5185 assert( assertLockingArrayOk(pShmNode
) );
5188 /* Drop the mutexes acquired above. */
5189 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
5190 leave_shmnode_mutexes
:
5191 for(iMutex
--; iMutex
>=ofst
; iMutex
--){
5192 sqlite3_mutex_leave(pShmNode
->aMutex
[iMutex
]);
5195 sqlite3_mutex_leave(pShmNode
->pShmMutex
);
5199 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
5200 p
->id
, osGetpid(0), p
->sharedMask
, p
->exclMask
));
5205 ** Implement a memory barrier or memory fence on shared memory.
5207 ** All loads and stores begun before the barrier must complete before
5208 ** any load or store begun after the barrier.
5210 static void unixShmBarrier(
5211 sqlite3_file
*fd
/* Database file holding the shared memory */
5213 UNUSED_PARAMETER(fd
);
5214 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
5215 assert( fd
->pMethods
->xLock
==nolockLock
5216 || unixFileMutexNotheld((unixFile
*)fd
)
5218 unixEnterMutex(); /* Also mutex, for redundancy */
5223 ** Close a connection to shared-memory. Delete the underlying
5224 ** storage if deleteFlag is true.
5226 ** If there is no shared memory associated with the connection then this
5227 ** routine is a harmless no-op.
5229 static int unixShmUnmap(
5230 sqlite3_file
*fd
, /* The underlying database file */
5231 int deleteFlag
/* Delete shared-memory if true */
5233 unixShm
*p
; /* The connection to be closed */
5234 unixShmNode
*pShmNode
; /* The underlying shared-memory file */
5235 unixShm
**pp
; /* For looping over sibling connections */
5236 unixFile
*pDbFd
; /* The underlying database file */
5238 pDbFd
= (unixFile
*)fd
;
5240 if( p
==0 ) return SQLITE_OK
;
5241 pShmNode
= p
->pShmNode
;
5243 assert( pShmNode
==pDbFd
->pInode
->pShmNode
);
5244 assert( pShmNode
->pInode
==pDbFd
->pInode
);
5246 /* Remove connection p from the set of connections associated
5248 sqlite3_mutex_enter(pShmNode
->pShmMutex
);
5249 for(pp
=&pShmNode
->pFirst
; (*pp
)!=p
; pp
= &(*pp
)->pNext
){}
5252 /* Free the connection p */
5255 sqlite3_mutex_leave(pShmNode
->pShmMutex
);
5257 /* If pShmNode->nRef has reached 0, then close the underlying
5258 ** shared-memory file, too */
5259 assert( unixFileMutexNotheld(pDbFd
) );
5261 assert( pShmNode
->nRef
>0 );
5263 if( pShmNode
->nRef
==0 ){
5264 if( deleteFlag
&& pShmNode
->hShm
>=0 ){
5265 osUnlink(pShmNode
->zFilename
);
5267 unixShmPurge(pDbFd
);
5276 # define unixShmMap 0
5277 # define unixShmLock 0
5278 # define unixShmBarrier 0
5279 # define unixShmUnmap 0
5280 #endif /* #ifndef SQLITE_OMIT_WAL */
5282 #if SQLITE_MAX_MMAP_SIZE>0
5284 ** If it is currently memory mapped, unmap file pFd.
5286 static void unixUnmapfile(unixFile
*pFd
){
5287 assert( pFd
->nFetchOut
==0 );
5288 if( pFd
->pMapRegion
){
5289 osMunmap(pFd
->pMapRegion
, pFd
->mmapSizeActual
);
5290 pFd
->pMapRegion
= 0;
5292 pFd
->mmapSizeActual
= 0;
5297 ** Attempt to set the size of the memory mapping maintained by file
5298 ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
5300 ** If successful, this function sets the following variables:
5302 ** unixFile.pMapRegion
5303 ** unixFile.mmapSize
5304 ** unixFile.mmapSizeActual
5306 ** If unsuccessful, an error message is logged via sqlite3_log() and
5307 ** the three variables above are zeroed. In this case SQLite should
5308 ** continue accessing the database using the xRead() and xWrite()
5311 static void unixRemapfile(
5312 unixFile
*pFd
, /* File descriptor object */
5313 i64 nNew
/* Required mapping size */
5315 const char *zErr
= "mmap";
5316 int h
= pFd
->h
; /* File descriptor open on db file */
5317 u8
*pOrig
= (u8
*)pFd
->pMapRegion
; /* Pointer to current file mapping */
5318 i64 nOrig
= pFd
->mmapSizeActual
; /* Size of pOrig region in bytes */
5319 u8
*pNew
= 0; /* Location of new mapping */
5320 int flags
= PROT_READ
; /* Flags to pass to mmap() */
5322 assert( pFd
->nFetchOut
==0 );
5323 assert( nNew
>pFd
->mmapSize
);
5324 assert( nNew
<=pFd
->mmapSizeMax
);
5326 assert( pFd
->mmapSizeActual
>=pFd
->mmapSize
);
5327 assert( MAP_FAILED
!=0 );
5329 #ifdef SQLITE_MMAP_READWRITE
5330 if( (pFd
->ctrlFlags
& UNIXFILE_RDONLY
)==0 ) flags
|= PROT_WRITE
;
5335 i64 nReuse
= pFd
->mmapSize
;
5337 const int szSyspage
= osGetpagesize();
5338 i64 nReuse
= (pFd
->mmapSize
& ~(szSyspage
-1));
5340 u8
*pReq
= &pOrig
[nReuse
];
5342 /* Unmap any pages of the existing mapping that cannot be reused. */
5343 if( nReuse
!=nOrig
){
5344 osMunmap(pReq
, nOrig
-nReuse
);
5348 pNew
= osMremap(pOrig
, nReuse
, nNew
, MREMAP_MAYMOVE
);
5351 pNew
= osMmap(pReq
, nNew
-nReuse
, flags
, MAP_SHARED
, h
, nReuse
);
5352 if( pNew
!=MAP_FAILED
){
5354 osMunmap(pNew
, nNew
- nReuse
);
5362 /* The attempt to extend the existing mapping failed. Free it. */
5363 if( pNew
==MAP_FAILED
|| pNew
==0 ){
5364 osMunmap(pOrig
, nReuse
);
5368 /* If pNew is still NULL, try to create an entirely new mapping. */
5370 pNew
= osMmap(0, nNew
, flags
, MAP_SHARED
, h
, 0);
5373 if( pNew
==MAP_FAILED
){
5376 unixLogError(SQLITE_OK
, zErr
, pFd
->zPath
);
5378 /* If the mmap() above failed, assume that all subsequent mmap() calls
5379 ** will probably fail too. Fall back to using xRead/xWrite exclusively
5381 pFd
->mmapSizeMax
= 0;
5383 pFd
->pMapRegion
= (void *)pNew
;
5384 pFd
->mmapSize
= pFd
->mmapSizeActual
= nNew
;
5388 ** Memory map or remap the file opened by file-descriptor pFd (if the file
5389 ** is already mapped, the existing mapping is replaced by the new). Or, if
5390 ** there already exists a mapping for this file, and there are still
5391 ** outstanding xFetch() references to it, this function is a no-op.
5393 ** If parameter nByte is non-negative, then it is the requested size of
5394 ** the mapping to create. Otherwise, if nByte is less than zero, then the
5395 ** requested size is the size of the file on disk. The actual size of the
5396 ** created mapping is either the requested size or the value configured
5397 ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
5399 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
5400 ** recreated as a result of outstanding references) or an SQLite error
5403 static int unixMapfile(unixFile
*pFd
, i64 nMap
){
5404 assert( nMap
>=0 || pFd
->nFetchOut
==0 );
5405 assert( nMap
>0 || (pFd
->mmapSize
==0 && pFd
->pMapRegion
==0) );
5406 if( pFd
->nFetchOut
>0 ) return SQLITE_OK
;
5409 struct stat statbuf
; /* Low-level file information */
5410 if( osFstat(pFd
->h
, &statbuf
) ){
5411 return SQLITE_IOERR_FSTAT
;
5413 nMap
= statbuf
.st_size
;
5415 if( nMap
>pFd
->mmapSizeMax
){
5416 nMap
= pFd
->mmapSizeMax
;
5419 assert( nMap
>0 || (pFd
->mmapSize
==0 && pFd
->pMapRegion
==0) );
5420 if( nMap
!=pFd
->mmapSize
){
5421 unixRemapfile(pFd
, nMap
);
5426 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
5429 ** If possible, return a pointer to a mapping of file fd starting at offset
5430 ** iOff. The mapping must be valid for at least nAmt bytes.
5432 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
5433 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
5434 ** Finally, if an error does occur, return an SQLite error code. The final
5435 ** value of *pp is undefined in this case.
5437 ** If this function does return a pointer, the caller must eventually
5438 ** release the reference by calling unixUnfetch().
5440 static int unixFetch(sqlite3_file
*fd
, i64 iOff
, int nAmt
, void **pp
){
5441 #if SQLITE_MAX_MMAP_SIZE>0
5442 unixFile
*pFd
= (unixFile
*)fd
; /* The underlying database file */
5446 #if SQLITE_MAX_MMAP_SIZE>0
5447 if( pFd
->mmapSizeMax
>0 ){
5448 /* Ensure that there is always at least a 256 byte buffer of addressable
5449 ** memory following the returned page. If the database is corrupt,
5450 ** SQLite may overread the page slightly (in practice only a few bytes,
5451 ** but 256 is safe, round, number). */
5452 const int nEofBuffer
= 256;
5453 if( pFd
->pMapRegion
==0 ){
5454 int rc
= unixMapfile(pFd
, -1);
5455 if( rc
!=SQLITE_OK
) return rc
;
5457 if( pFd
->mmapSize
>= (iOff
+nAmt
+nEofBuffer
) ){
5458 *pp
= &((u8
*)pFd
->pMapRegion
)[iOff
];
5467 ** If the third argument is non-NULL, then this function releases a
5468 ** reference obtained by an earlier call to unixFetch(). The second
5469 ** argument passed to this function must be the same as the corresponding
5470 ** argument that was passed to the unixFetch() invocation.
5472 ** Or, if the third argument is NULL, then this function is being called
5473 ** to inform the VFS layer that, according to POSIX, any existing mapping
5474 ** may now be invalid and should be unmapped.
5476 static int unixUnfetch(sqlite3_file
*fd
, i64 iOff
, void *p
){
5477 #if SQLITE_MAX_MMAP_SIZE>0
5478 unixFile
*pFd
= (unixFile
*)fd
; /* The underlying database file */
5479 UNUSED_PARAMETER(iOff
);
5481 /* If p==0 (unmap the entire file) then there must be no outstanding
5482 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
5483 ** then there must be at least one outstanding. */
5484 assert( (p
==0)==(pFd
->nFetchOut
==0) );
5486 /* If p!=0, it must match the iOff value. */
5487 assert( p
==0 || p
==&((u8
*)pFd
->pMapRegion
)[iOff
] );
5495 assert( pFd
->nFetchOut
>=0 );
5497 UNUSED_PARAMETER(fd
);
5498 UNUSED_PARAMETER(p
);
5499 UNUSED_PARAMETER(iOff
);
5505 ** Here ends the implementation of all sqlite3_file methods.
5507 ********************** End sqlite3_file Methods *******************************
5508 ******************************************************************************/
5511 ** This division contains definitions of sqlite3_io_methods objects that
5512 ** implement various file locking strategies. It also contains definitions
5513 ** of "finder" functions. A finder-function is used to locate the appropriate
5514 ** sqlite3_io_methods object for a particular database file. The pAppData
5515 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
5516 ** the correct finder-function for that VFS.
5518 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
5519 ** object. The only interesting finder-function is autolockIoFinder, which
5520 ** looks at the filesystem type and tries to guess the best locking
5521 ** strategy from that.
5523 ** For finder-function F, two objects are created:
5525 ** (1) The real finder-function named "FImpt()".
5527 ** (2) A constant pointer to this function named just "F".
5530 ** A pointer to the F pointer is used as the pAppData value for VFS
5531 ** objects. We have to do this instead of letting pAppData point
5532 ** directly at the finder-function since C90 rules prevent a void*
5533 ** from be cast into a function pointer.
5536 ** Each instance of this macro generates two objects:
5538 ** * A constant sqlite3_io_methods object call METHOD that has locking
5539 ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
5541 ** * An I/O method finder function called FINDER that returns a pointer
5542 ** to the METHOD object in the previous bullet.
5544 #define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
5545 static const sqlite3_io_methods METHOD = { \
5546 VERSION, /* iVersion */ \
5547 CLOSE, /* xClose */ \
5548 unixRead, /* xRead */ \
5549 unixWrite, /* xWrite */ \
5550 unixTruncate, /* xTruncate */ \
5551 unixSync, /* xSync */ \
5552 unixFileSize, /* xFileSize */ \
5554 UNLOCK, /* xUnlock */ \
5555 CKLOCK, /* xCheckReservedLock */ \
5556 unixFileControl, /* xFileControl */ \
5557 unixSectorSize, /* xSectorSize */ \
5558 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
5559 SHMMAP, /* xShmMap */ \
5560 unixShmLock, /* xShmLock */ \
5561 unixShmBarrier, /* xShmBarrier */ \
5562 unixShmUnmap, /* xShmUnmap */ \
5563 unixFetch, /* xFetch */ \
5564 unixUnfetch, /* xUnfetch */ \
5566 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
5567 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
5570 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
5574 ** Here are all of the sqlite3_io_methods objects for each of the
5575 ** locking strategies. Functions that return pointers to these methods
5576 ** are also created.
5579 posixIoFinder
, /* Finder function name */
5580 posixIoMethods
, /* sqlite3_io_methods object name */
5581 3, /* shared memory and mmap are enabled */
5582 unixClose
, /* xClose method */
5583 unixLock
, /* xLock method */
5584 unixUnlock
, /* xUnlock method */
5585 unixCheckReservedLock
, /* xCheckReservedLock method */
5586 unixShmMap
/* xShmMap method */
5589 nolockIoFinder
, /* Finder function name */
5590 nolockIoMethods
, /* sqlite3_io_methods object name */
5591 3, /* shared memory and mmap are enabled */
5592 nolockClose
, /* xClose method */
5593 nolockLock
, /* xLock method */
5594 nolockUnlock
, /* xUnlock method */
5595 nolockCheckReservedLock
, /* xCheckReservedLock method */
5596 0 /* xShmMap method */
5599 dotlockIoFinder
, /* Finder function name */
5600 dotlockIoMethods
, /* sqlite3_io_methods object name */
5601 1, /* shared memory is disabled */
5602 dotlockClose
, /* xClose method */
5603 dotlockLock
, /* xLock method */
5604 dotlockUnlock
, /* xUnlock method */
5605 dotlockCheckReservedLock
, /* xCheckReservedLock method */
5606 0 /* xShmMap method */
5609 #if SQLITE_ENABLE_LOCKING_STYLE
5611 flockIoFinder
, /* Finder function name */
5612 flockIoMethods
, /* sqlite3_io_methods object name */
5613 1, /* shared memory is disabled */
5614 flockClose
, /* xClose method */
5615 flockLock
, /* xLock method */
5616 flockUnlock
, /* xUnlock method */
5617 flockCheckReservedLock
, /* xCheckReservedLock method */
5618 0 /* xShmMap method */
5624 semIoFinder
, /* Finder function name */
5625 semIoMethods
, /* sqlite3_io_methods object name */
5626 1, /* shared memory is disabled */
5627 semXClose
, /* xClose method */
5628 semXLock
, /* xLock method */
5629 semXUnlock
, /* xUnlock method */
5630 semXCheckReservedLock
, /* xCheckReservedLock method */
5631 0 /* xShmMap method */
5635 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5637 afpIoFinder
, /* Finder function name */
5638 afpIoMethods
, /* sqlite3_io_methods object name */
5639 1, /* shared memory is disabled */
5640 afpClose
, /* xClose method */
5641 afpLock
, /* xLock method */
5642 afpUnlock
, /* xUnlock method */
5643 afpCheckReservedLock
, /* xCheckReservedLock method */
5644 0 /* xShmMap method */
5649 ** The proxy locking method is a "super-method" in the sense that it
5650 ** opens secondary file descriptors for the conch and lock files and
5651 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
5652 ** secondary files. For this reason, the division that implements
5653 ** proxy locking is located much further down in the file. But we need
5654 ** to go ahead and define the sqlite3_io_methods and finder function
5655 ** for proxy locking here. So we forward declare the I/O methods.
5657 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5658 static int proxyClose(sqlite3_file
*);
5659 static int proxyLock(sqlite3_file
*, int);
5660 static int proxyUnlock(sqlite3_file
*, int);
5661 static int proxyCheckReservedLock(sqlite3_file
*, int*);
5663 proxyIoFinder
, /* Finder function name */
5664 proxyIoMethods
, /* sqlite3_io_methods object name */
5665 1, /* shared memory is disabled */
5666 proxyClose
, /* xClose method */
5667 proxyLock
, /* xLock method */
5668 proxyUnlock
, /* xUnlock method */
5669 proxyCheckReservedLock
, /* xCheckReservedLock method */
5670 0 /* xShmMap method */
5674 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5675 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5677 nfsIoFinder
, /* Finder function name */
5678 nfsIoMethods
, /* sqlite3_io_methods object name */
5679 1, /* shared memory is disabled */
5680 unixClose
, /* xClose method */
5681 unixLock
, /* xLock method */
5682 nfsUnlock
, /* xUnlock method */
5683 unixCheckReservedLock
, /* xCheckReservedLock method */
5684 0 /* xShmMap method */
5688 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5690 ** This "finder" function attempts to determine the best locking strategy
5691 ** for the database file "filePath". It then returns the sqlite3_io_methods
5692 ** object that implements that strategy.
5694 ** This is for MacOSX only.
5696 static const sqlite3_io_methods
*autolockIoFinderImpl(
5697 const char *filePath
, /* name of the database file */
5698 unixFile
*pNew
/* open file object for the database file */
5700 static const struct Mapping
{
5701 const char *zFilesystem
; /* Filesystem type name */
5702 const sqlite3_io_methods
*pMethods
; /* Appropriate locking method */
5704 { "hfs", &posixIoMethods
},
5705 { "ufs", &posixIoMethods
},
5706 { "afpfs", &afpIoMethods
},
5707 { "smbfs", &afpIoMethods
},
5708 { "webdav", &nolockIoMethods
},
5712 struct statfs fsInfo
;
5713 struct flock lockInfo
;
5716 /* If filePath==NULL that means we are dealing with a transient file
5717 ** that does not need to be locked. */
5718 return &nolockIoMethods
;
5720 if( statfs(filePath
, &fsInfo
) != -1 ){
5721 if( fsInfo
.f_flags
& MNT_RDONLY
){
5722 return &nolockIoMethods
;
5724 for(i
=0; aMap
[i
].zFilesystem
; i
++){
5725 if( strcmp(fsInfo
.f_fstypename
, aMap
[i
].zFilesystem
)==0 ){
5726 return aMap
[i
].pMethods
;
5731 /* Default case. Handles, amongst others, "nfs".
5732 ** Test byte-range lock using fcntl(). If the call succeeds,
5733 ** assume that the file-system supports POSIX style locks.
5736 lockInfo
.l_start
= 0;
5737 lockInfo
.l_whence
= SEEK_SET
;
5738 lockInfo
.l_type
= F_RDLCK
;
5739 if( osFcntl(pNew
->h
, F_GETLK
, &lockInfo
)!=-1 ) {
5740 if( strcmp(fsInfo
.f_fstypename
, "nfs")==0 ){
5741 return &nfsIoMethods
;
5743 return &posixIoMethods
;
5746 return &dotlockIoMethods
;
5749 static const sqlite3_io_methods
5750 *(*const autolockIoFinder
)(const char*,unixFile
*) = autolockIoFinderImpl
;
5752 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
5756 ** This "finder" function for VxWorks checks to see if posix advisory
5757 ** locking works. If it does, then that is what is used. If it does not
5758 ** work, then fallback to named semaphore locking.
5760 static const sqlite3_io_methods
*vxworksIoFinderImpl(
5761 const char *filePath
, /* name of the database file */
5762 unixFile
*pNew
/* the open file object */
5764 struct flock lockInfo
;
5767 /* If filePath==NULL that means we are dealing with a transient file
5768 ** that does not need to be locked. */
5769 return &nolockIoMethods
;
5772 /* Test if fcntl() is supported and use POSIX style locks.
5773 ** Otherwise fall back to the named semaphore method.
5776 lockInfo
.l_start
= 0;
5777 lockInfo
.l_whence
= SEEK_SET
;
5778 lockInfo
.l_type
= F_RDLCK
;
5779 if( osFcntl(pNew
->h
, F_GETLK
, &lockInfo
)!=-1 ) {
5780 return &posixIoMethods
;
5782 return &semIoMethods
;
5785 static const sqlite3_io_methods
5786 *(*const vxworksIoFinder
)(const char*,unixFile
*) = vxworksIoFinderImpl
;
5788 #endif /* OS_VXWORKS */
5791 ** An abstract type for a pointer to an IO method finder function:
5793 typedef const sqlite3_io_methods
*(*finder_type
)(const char*,unixFile
*);
5796 /****************************************************************************
5797 **************************** sqlite3_vfs methods ****************************
5799 ** This division contains the implementation of methods on the
5800 ** sqlite3_vfs object.
5804 ** Initialize the contents of the unixFile structure pointed to by pId.
5806 static int fillInUnixFile(
5807 sqlite3_vfs
*pVfs
, /* Pointer to vfs object */
5808 int h
, /* Open file descriptor of file being opened */
5809 sqlite3_file
*pId
, /* Write to the unixFile structure here */
5810 const char *zFilename
, /* Name of the file being opened */
5811 int ctrlFlags
/* Zero or more UNIXFILE_* values */
5813 const sqlite3_io_methods
*pLockingStyle
;
5814 unixFile
*pNew
= (unixFile
*)pId
;
5817 assert( pNew
->pInode
==NULL
);
5819 /* No locking occurs in temporary files */
5820 assert( zFilename
!=0 || (ctrlFlags
& UNIXFILE_NOLOCK
)!=0 );
5822 OSTRACE(("OPEN %-3d %s\n", h
, zFilename
));
5825 pNew
->zPath
= zFilename
;
5826 pNew
->ctrlFlags
= (u8
)ctrlFlags
;
5827 #if SQLITE_MAX_MMAP_SIZE>0
5828 pNew
->mmapSizeMax
= sqlite3GlobalConfig
.szMmap
;
5830 if( sqlite3_uri_boolean(((ctrlFlags
& UNIXFILE_URI
) ? zFilename
: 0),
5831 "psow", SQLITE_POWERSAFE_OVERWRITE
) ){
5832 pNew
->ctrlFlags
|= UNIXFILE_PSOW
;
5834 if( strcmp(pVfs
->zName
,"unix-excl")==0 ){
5835 pNew
->ctrlFlags
|= UNIXFILE_EXCL
;
5839 pNew
->pId
= vxworksFindFileId(zFilename
);
5841 ctrlFlags
|= UNIXFILE_NOLOCK
;
5842 rc
= SQLITE_NOMEM_BKPT
;
5846 if( ctrlFlags
& UNIXFILE_NOLOCK
){
5847 pLockingStyle
= &nolockIoMethods
;
5849 pLockingStyle
= (**(finder_type
*)pVfs
->pAppData
)(zFilename
, pNew
);
5850 #if SQLITE_ENABLE_LOCKING_STYLE
5851 /* Cache zFilename in the locking context (AFP and dotlock override) for
5852 ** proxyLock activation is possible (remote proxy is based on db name)
5853 ** zFilename remains valid until file is closed, to support */
5854 pNew
->lockingContext
= (void*)zFilename
;
5858 if( pLockingStyle
== &posixIoMethods
5859 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5860 || pLockingStyle
== &nfsIoMethods
5864 rc
= findInodeInfo(pNew
, &pNew
->pInode
);
5865 if( rc
!=SQLITE_OK
){
5866 /* If an error occurred in findInodeInfo(), close the file descriptor
5867 ** immediately, before releasing the mutex. findInodeInfo() may fail
5868 ** in two scenarios:
5870 ** (a) A call to fstat() failed.
5871 ** (b) A malloc failed.
5873 ** Scenario (b) may only occur if the process is holding no other
5874 ** file descriptors open on the same file. If there were other file
5875 ** descriptors on this file, then no malloc would be required by
5876 ** findInodeInfo(). If this is the case, it is quite safe to close
5877 ** handle h - as it is guaranteed that no posix locks will be released
5880 ** If scenario (a) caused the error then things are not so safe. The
5881 ** implicit assumption here is that if fstat() fails, things are in
5882 ** such bad shape that dropping a lock or two doesn't matter much.
5884 robust_close(pNew
, h
, __LINE__
);
5890 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
5891 else if( pLockingStyle
== &afpIoMethods
){
5892 /* AFP locking uses the file path so it needs to be included in
5893 ** the afpLockingContext.
5895 afpLockingContext
*pCtx
;
5896 pNew
->lockingContext
= pCtx
= sqlite3_malloc64( sizeof(*pCtx
) );
5898 rc
= SQLITE_NOMEM_BKPT
;
5900 /* NB: zFilename exists and remains valid until the file is closed
5901 ** according to requirement F11141. So we do not need to make a
5902 ** copy of the filename. */
5903 pCtx
->dbPath
= zFilename
;
5907 rc
= findInodeInfo(pNew
, &pNew
->pInode
);
5908 if( rc
!=SQLITE_OK
){
5909 sqlite3_free(pNew
->lockingContext
);
5910 robust_close(pNew
, h
, __LINE__
);
5918 else if( pLockingStyle
== &dotlockIoMethods
){
5919 /* Dotfile locking uses the file path so it needs to be included in
5920 ** the dotlockLockingContext
5924 assert( zFilename
!=0 );
5925 nFilename
= (int)strlen(zFilename
) + 6;
5926 zLockFile
= (char *)sqlite3_malloc64(nFilename
);
5928 rc
= SQLITE_NOMEM_BKPT
;
5930 sqlite3_snprintf(nFilename
, zLockFile
, "%s" DOTLOCK_SUFFIX
, zFilename
);
5932 pNew
->lockingContext
= zLockFile
;
5936 else if( pLockingStyle
== &semIoMethods
){
5937 /* Named semaphore locking uses the file path so it needs to be
5938 ** included in the semLockingContext
5941 rc
= findInodeInfo(pNew
, &pNew
->pInode
);
5942 if( (rc
==SQLITE_OK
) && (pNew
->pInode
->pSem
==NULL
) ){
5943 char *zSemName
= pNew
->pInode
->aSemName
;
5945 sqlite3_snprintf(MAX_PATHNAME
, zSemName
, "/%s.sem",
5946 pNew
->pId
->zCanonicalName
);
5947 for( n
=1; zSemName
[n
]; n
++ )
5948 if( zSemName
[n
]=='/' ) zSemName
[n
] = '_';
5949 pNew
->pInode
->pSem
= sem_open(zSemName
, O_CREAT
, 0666, 1);
5950 if( pNew
->pInode
->pSem
== SEM_FAILED
){
5951 rc
= SQLITE_NOMEM_BKPT
;
5952 pNew
->pInode
->aSemName
[0] = '\0';
5959 storeLastErrno(pNew
, 0);
5961 if( rc
!=SQLITE_OK
){
5962 if( h
>=0 ) robust_close(pNew
, h
, __LINE__
);
5964 osUnlink(zFilename
);
5965 pNew
->ctrlFlags
|= UNIXFILE_DELETE
;
5968 if( rc
!=SQLITE_OK
){
5969 if( h
>=0 ) robust_close(pNew
, h
, __LINE__
);
5971 pId
->pMethods
= pLockingStyle
;
5979 ** Directories to consider for temp files.
5981 static const char *azTempDirs
[] = {
5991 ** Initialize first two members of azTempDirs[] array.
5993 static void unixTempFileInit(void){
5994 azTempDirs
[0] = getenv("SQLITE_TMPDIR");
5995 azTempDirs
[1] = getenv("TMPDIR");
5999 ** Return the name of a directory in which to put temporary files.
6000 ** If no suitable temporary file directory can be found, return NULL.
6002 static const char *unixTempFileDir(void){
6005 const char *zDir
= sqlite3_temp_directory
;
6009 && osStat(zDir
, &buf
)==0
6010 && S_ISDIR(buf
.st_mode
)
6011 && osAccess(zDir
, 03)==0
6015 if( i
>=sizeof(azTempDirs
)/sizeof(azTempDirs
[0]) ) break;
6016 zDir
= azTempDirs
[i
++];
6022 ** Create a temporary file name in zBuf. zBuf must be allocated
6023 ** by the calling process and must be big enough to hold at least
6024 ** pVfs->mxPathname bytes.
6026 static int unixGetTempname(int nBuf
, char *zBuf
){
6031 /* It's odd to simulate an io-error here, but really this is just
6032 ** using the io-error infrastructure to test that SQLite handles this
6033 ** function failing.
6036 SimulateIOError( return SQLITE_IOERR
);
6038 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR
));
6039 zDir
= unixTempFileDir();
6041 rc
= SQLITE_IOERR_GETTEMPPATH
;
6045 sqlite3_randomness(sizeof(r
), &r
);
6048 sqlite3_snprintf(nBuf
, zBuf
, "%s/"SQLITE_TEMP_FILE_PREFIX
"%llx%c",
6050 if( zBuf
[nBuf
-2]!=0 || (iLimit
++)>10 ){
6054 }while( osAccess(zBuf
,0)==0 );
6056 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR
));
6060 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
6062 ** Routine to transform a unixFile into a proxy-locking unixFile.
6063 ** Implementation in the proxy-lock division, but used by unixOpen()
6064 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
6066 static int proxyTransformUnixFile(unixFile
*, const char*);
6070 ** Search for an unused file descriptor that was opened on the database
6071 ** file (not a journal or super-journal file) identified by pathname
6072 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
6073 ** argument to this function.
6075 ** Such a file descriptor may exist if a database connection was closed
6076 ** but the associated file descriptor could not be closed because some
6077 ** other file descriptor open on the same file is holding a file-lock.
6078 ** Refer to comments in the unixClose() function and the lengthy comment
6079 ** describing "Posix Advisory Locking" at the start of this file for
6080 ** further details. Also, ticket #4018.
6082 ** If a suitable file descriptor is found, then it is returned. If no
6083 ** such file descriptor is located, -1 is returned.
6085 static UnixUnusedFd
*findReusableFd(const char *zPath
, int flags
){
6086 UnixUnusedFd
*pUnused
= 0;
6088 /* Do not search for an unused file descriptor on vxworks. Not because
6089 ** vxworks would not benefit from the change (it might, we're not sure),
6090 ** but because no way to test it is currently available. It is better
6091 ** not to risk breaking vxworks support for the sake of such an obscure
6094 struct stat sStat
; /* Results of stat() call */
6098 /* A stat() call may fail for various reasons. If this happens, it is
6099 ** almost certain that an open() call on the same path will also fail.
6100 ** For this reason, if an error occurs in the stat() call here, it is
6101 ** ignored and -1 is returned. The caller will try to open a new file
6102 ** descriptor on the same path, fail, and return an error to SQLite.
6104 ** Even if a subsequent open() call does succeed, the consequences of
6105 ** not searching for a reusable file descriptor are not dire. */
6106 if( inodeList
!=0 && 0==osStat(zPath
, &sStat
) ){
6107 unixInodeInfo
*pInode
;
6110 while( pInode
&& (pInode
->fileId
.dev
!=sStat
.st_dev
6111 || pInode
->fileId
.ino
!=(u64
)sStat
.st_ino
) ){
6112 pInode
= pInode
->pNext
;
6116 assert( sqlite3_mutex_notheld(pInode
->pLockMutex
) );
6117 sqlite3_mutex_enter(pInode
->pLockMutex
);
6118 flags
&= (SQLITE_OPEN_READONLY
|SQLITE_OPEN_READWRITE
);
6119 for(pp
=&pInode
->pUnused
; *pp
&& (*pp
)->flags
!=flags
; pp
=&((*pp
)->pNext
));
6122 *pp
= pUnused
->pNext
;
6124 sqlite3_mutex_leave(pInode
->pLockMutex
);
6128 #endif /* if !OS_VXWORKS */
6133 ** Find the mode, uid and gid of file zFile.
6135 static int getFileMode(
6136 const char *zFile
, /* File name */
6137 mode_t
*pMode
, /* OUT: Permissions of zFile */
6138 uid_t
*pUid
, /* OUT: uid of zFile. */
6139 gid_t
*pGid
/* OUT: gid of zFile. */
6141 struct stat sStat
; /* Output of stat() on database file */
6143 if( 0==osStat(zFile
, &sStat
) ){
6144 *pMode
= sStat
.st_mode
& 0777;
6145 *pUid
= sStat
.st_uid
;
6146 *pGid
= sStat
.st_gid
;
6148 rc
= SQLITE_IOERR_FSTAT
;
6154 ** This function is called by unixOpen() to determine the unix permissions
6155 ** to create new files with. If no error occurs, then SQLITE_OK is returned
6156 ** and a value suitable for passing as the third argument to open(2) is
6157 ** written to *pMode. If an IO error occurs, an SQLite error code is
6158 ** returned and the value of *pMode is not modified.
6160 ** In most cases, this routine sets *pMode to 0, which will become
6161 ** an indication to robust_open() to create the file using
6162 ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
6163 ** But if the file being opened is a WAL or regular journal file, then
6164 ** this function queries the file-system for the permissions on the
6165 ** corresponding database file and sets *pMode to this value. Whenever
6166 ** possible, WAL and journal files are created using the same permissions
6167 ** as the associated database file.
6169 ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
6170 ** original filename is unavailable. But 8_3_NAMES is only used for
6171 ** FAT filesystems and permissions do not matter there, so just use
6172 ** the default permissions. In 8_3_NAMES mode, leave *pMode set to zero.
6174 static int findCreateFileMode(
6175 const char *zPath
, /* Path of file (possibly) being created */
6176 int flags
, /* Flags passed as 4th argument to xOpen() */
6177 mode_t
*pMode
, /* OUT: Permissions to open file with */
6178 uid_t
*pUid
, /* OUT: uid to set on the file */
6179 gid_t
*pGid
/* OUT: gid to set on the file */
6181 int rc
= SQLITE_OK
; /* Return Code */
6185 if( flags
& (SQLITE_OPEN_WAL
|SQLITE_OPEN_MAIN_JOURNAL
) ){
6186 char zDb
[MAX_PATHNAME
+1]; /* Database file path */
6187 int nDb
; /* Number of valid bytes in zDb */
6189 /* zPath is a path to a WAL or journal file. The following block derives
6190 ** the path to the associated database file from zPath. This block handles
6191 ** the following naming conventions:
6193 ** "<path to db>-journal"
6194 ** "<path to db>-wal"
6195 ** "<path to db>-journalNN"
6196 ** "<path to db>-walNN"
6198 ** where NN is a decimal number. The NN naming schemes are
6199 ** used by the test_multiplex.c module.
6201 ** In normal operation, the journal file name will always contain
6202 ** a '-' character. However in 8+3 filename mode, or if a corrupt
6203 ** rollback journal specifies a super-journal with a goofy name, then
6204 ** the '-' might be missing or the '-' might be the first character in
6205 ** the filename. In that case, just return SQLITE_OK with *pMode==0.
6207 nDb
= sqlite3Strlen30(zPath
) - 1;
6208 while( nDb
>0 && zPath
[nDb
]!='.' ){
6209 if( zPath
[nDb
]=='-' ){
6210 memcpy(zDb
, zPath
, nDb
);
6212 rc
= getFileMode(zDb
, pMode
, pUid
, pGid
);
6217 }else if( flags
& SQLITE_OPEN_DELETEONCLOSE
){
6219 }else if( flags
& SQLITE_OPEN_URI
){
6220 /* If this is a main database file and the file was opened using a URI
6221 ** filename, check for the "modeof" parameter. If present, interpret
6222 ** its value as a filename and try to copy the mode, uid and gid from
6224 const char *z
= sqlite3_uri_parameter(zPath
, "modeof");
6226 rc
= getFileMode(z
, pMode
, pUid
, pGid
);
6233 ** Open the file zPath.
6235 ** Previously, the SQLite OS layer used three functions in place of this
6238 ** sqlite3OsOpenReadWrite();
6239 ** sqlite3OsOpenReadOnly();
6240 ** sqlite3OsOpenExclusive();
6242 ** These calls correspond to the following combinations of flags:
6244 ** ReadWrite() -> (READWRITE | CREATE)
6245 ** ReadOnly() -> (READONLY)
6246 ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
6248 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
6249 ** true, the file was configured to be automatically deleted when the
6250 ** file handle closed. To achieve the same effect using this new
6251 ** interface, add the DELETEONCLOSE flag to those specified above for
6254 static int unixOpen(
6255 sqlite3_vfs
*pVfs
, /* The VFS for which this is the xOpen method */
6256 const char *zPath
, /* Pathname of file to be opened */
6257 sqlite3_file
*pFile
, /* The file descriptor to be filled in */
6258 int flags
, /* Input flags to control the opening */
6259 int *pOutFlags
/* Output flags returned to SQLite core */
6261 unixFile
*p
= (unixFile
*)pFile
;
6262 int fd
= -1; /* File descriptor returned by open() */
6263 int openFlags
= 0; /* Flags to pass to open() */
6264 int eType
= flags
&0x0FFF00; /* Type of file to open */
6265 int noLock
; /* True to omit locking primitives */
6266 int rc
= SQLITE_OK
; /* Function Return Code */
6267 int ctrlFlags
= 0; /* UNIXFILE_* flags */
6269 int isExclusive
= (flags
& SQLITE_OPEN_EXCLUSIVE
);
6270 int isDelete
= (flags
& SQLITE_OPEN_DELETEONCLOSE
);
6271 int isCreate
= (flags
& SQLITE_OPEN_CREATE
);
6272 int isReadonly
= (flags
& SQLITE_OPEN_READONLY
);
6273 int isReadWrite
= (flags
& SQLITE_OPEN_READWRITE
);
6274 #if SQLITE_ENABLE_LOCKING_STYLE
6275 int isAutoProxy
= (flags
& SQLITE_OPEN_AUTOPROXY
);
6277 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
6278 struct statfs fsInfo
;
6281 /* If creating a super- or main-file journal, this function will open
6282 ** a file-descriptor on the directory too. The first time unixSync()
6283 ** is called the directory file descriptor will be fsync()ed and close()d.
6285 int isNewJrnl
= (isCreate
&& (
6286 eType
==SQLITE_OPEN_SUPER_JOURNAL
6287 || eType
==SQLITE_OPEN_MAIN_JOURNAL
6288 || eType
==SQLITE_OPEN_WAL
6291 /* If argument zPath is a NULL pointer, this function is required to open
6292 ** a temporary file. Use this buffer to store the file name in.
6294 char zTmpname
[MAX_PATHNAME
+2];
6295 const char *zName
= zPath
;
6297 /* Check the following statements are true:
6299 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
6300 ** (b) if CREATE is set, then READWRITE must also be set, and
6301 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
6302 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
6304 assert((isReadonly
==0 || isReadWrite
==0) && (isReadWrite
|| isReadonly
));
6305 assert(isCreate
==0 || isReadWrite
);
6306 assert(isExclusive
==0 || isCreate
);
6307 assert(isDelete
==0 || isCreate
);
6309 /* The main DB, main journal, WAL file and super-journal are never
6310 ** automatically deleted. Nor are they ever temporary files. */
6311 assert( (!isDelete
&& zName
) || eType
!=SQLITE_OPEN_MAIN_DB
);
6312 assert( (!isDelete
&& zName
) || eType
!=SQLITE_OPEN_MAIN_JOURNAL
);
6313 assert( (!isDelete
&& zName
) || eType
!=SQLITE_OPEN_SUPER_JOURNAL
);
6314 assert( (!isDelete
&& zName
) || eType
!=SQLITE_OPEN_WAL
);
6316 /* Assert that the upper layer has set one of the "file-type" flags. */
6317 assert( eType
==SQLITE_OPEN_MAIN_DB
|| eType
==SQLITE_OPEN_TEMP_DB
6318 || eType
==SQLITE_OPEN_MAIN_JOURNAL
|| eType
==SQLITE_OPEN_TEMP_JOURNAL
6319 || eType
==SQLITE_OPEN_SUBJOURNAL
|| eType
==SQLITE_OPEN_SUPER_JOURNAL
6320 || eType
==SQLITE_OPEN_TRANSIENT_DB
|| eType
==SQLITE_OPEN_WAL
6323 /* Detect a pid change and reset the PRNG. There is a race condition
6324 ** here such that two or more threads all trying to open databases at
6325 ** the same instant might all reset the PRNG. But multiple resets
6328 if( randomnessPid
!=osGetpid(0) ){
6329 randomnessPid
= osGetpid(0);
6330 sqlite3_randomness(0,0);
6332 memset(p
, 0, sizeof(unixFile
));
6334 #ifdef SQLITE_ASSERT_NO_FILES
6335 /* Applications that never read or write a persistent disk files */
6339 if( eType
==SQLITE_OPEN_MAIN_DB
){
6340 UnixUnusedFd
*pUnused
;
6341 pUnused
= findReusableFd(zName
, flags
);
6345 pUnused
= sqlite3_malloc64(sizeof(*pUnused
));
6347 return SQLITE_NOMEM_BKPT
;
6350 p
->pPreallocatedUnused
= pUnused
;
6352 /* Database filenames are double-zero terminated if they are not
6353 ** URIs with parameters. Hence, they can always be passed into
6354 ** sqlite3_uri_parameter(). */
6355 assert( (flags
& SQLITE_OPEN_URI
) || zName
[strlen(zName
)+1]==0 );
6358 /* If zName is NULL, the upper layer is requesting a temp file. */
6359 assert(isDelete
&& !isNewJrnl
);
6360 rc
= unixGetTempname(pVfs
->mxPathname
, zTmpname
);
6361 if( rc
!=SQLITE_OK
){
6366 /* Generated temporary filenames are always double-zero terminated
6367 ** for use by sqlite3_uri_parameter(). */
6368 assert( zName
[strlen(zName
)+1]==0 );
6371 /* Determine the value of the flags parameter passed to POSIX function
6372 ** open(). These must be calculated even if open() is not called, as
6373 ** they may be stored as part of the file handle and used by the
6374 ** 'conch file' locking functions later on. */
6375 if( isReadonly
) openFlags
|= O_RDONLY
;
6376 if( isReadWrite
) openFlags
|= O_RDWR
;
6377 if( isCreate
) openFlags
|= O_CREAT
;
6378 if( isExclusive
) openFlags
|= (O_EXCL
|O_NOFOLLOW
);
6379 openFlags
|= (O_LARGEFILE
|O_BINARY
|O_NOFOLLOW
);
6382 mode_t openMode
; /* Permissions to create file with */
6383 uid_t uid
; /* Userid for the file */
6384 gid_t gid
; /* Groupid for the file */
6385 rc
= findCreateFileMode(zName
, flags
, &openMode
, &uid
, &gid
);
6386 if( rc
!=SQLITE_OK
){
6387 assert( !p
->pPreallocatedUnused
);
6388 assert( eType
==SQLITE_OPEN_WAL
|| eType
==SQLITE_OPEN_MAIN_JOURNAL
);
6391 fd
= robust_open(zName
, openFlags
, openMode
);
6392 OSTRACE(("OPENX %-3d %s 0%o\n", fd
, zName
, openFlags
));
6393 assert( !isExclusive
|| (openFlags
& O_CREAT
)!=0 );
6395 if( isNewJrnl
&& errno
==EACCES
&& osAccess(zName
, F_OK
) ){
6396 /* If unable to create a journal because the directory is not
6397 ** writable, change the error code to indicate that. */
6398 rc
= SQLITE_READONLY_DIRECTORY
;
6399 }else if( errno
!=EISDIR
&& isReadWrite
){
6400 /* Failed to open the file for read/write access. Try read-only. */
6401 UnixUnusedFd
*pReadonly
= 0;
6402 flags
&= ~(SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
);
6403 openFlags
&= ~(O_RDWR
|O_CREAT
);
6404 flags
|= SQLITE_OPEN_READONLY
;
6405 openFlags
|= O_RDONLY
;
6407 pReadonly
= findReusableFd(zName
, flags
);
6410 sqlite3_free(pReadonly
);
6412 fd
= robust_open(zName
, openFlags
, openMode
);
6417 int rc2
= unixLogError(SQLITE_CANTOPEN_BKPT
, "open", zName
);
6418 if( rc
==SQLITE_OK
) rc
= rc2
;
6422 /* The owner of the rollback journal or WAL file should always be the
6423 ** same as the owner of the database file. Try to ensure that this is
6424 ** the case. The chown() system call will be a no-op if the current
6425 ** process lacks root privileges, be we should at least try. Without
6426 ** this step, if a root process opens a database file, it can leave
6427 ** behinds a journal/WAL that is owned by root and hence make the
6428 ** database inaccessible to unprivileged processes.
6430 ** If openMode==0, then that means uid and gid are not set correctly
6431 ** (probably because SQLite is configured to use 8+3 filename mode) and
6432 ** in that case we do not want to attempt the chown().
6434 if( openMode
&& (flags
& (SQLITE_OPEN_WAL
|SQLITE_OPEN_MAIN_JOURNAL
))!=0 ){
6435 robustFchown(fd
, uid
, gid
);
6443 if( p
->pPreallocatedUnused
){
6444 p
->pPreallocatedUnused
->fd
= fd
;
6445 p
->pPreallocatedUnused
->flags
=
6446 flags
& (SQLITE_OPEN_READONLY
|SQLITE_OPEN_READWRITE
);
6452 #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
6453 zPath
= sqlite3_mprintf("%s", zName
);
6455 robust_close(p
, fd
, __LINE__
);
6456 return SQLITE_NOMEM_BKPT
;
6462 #if SQLITE_ENABLE_LOCKING_STYLE
6464 p
->openFlags
= openFlags
;
6468 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
6469 if( fstatfs(fd
, &fsInfo
) == -1 ){
6470 storeLastErrno(p
, errno
);
6471 robust_close(p
, fd
, __LINE__
);
6472 return SQLITE_IOERR_ACCESS
;
6474 if (0 == strncmp("msdos", fsInfo
.f_fstypename
, 5)) {
6475 ((unixFile
*)pFile
)->fsFlags
|= SQLITE_FSFLAGS_IS_MSDOS
;
6477 if (0 == strncmp("exfat", fsInfo
.f_fstypename
, 5)) {
6478 ((unixFile
*)pFile
)->fsFlags
|= SQLITE_FSFLAGS_IS_MSDOS
;
6482 /* Set up appropriate ctrlFlags */
6483 if( isDelete
) ctrlFlags
|= UNIXFILE_DELETE
;
6484 if( isReadonly
) ctrlFlags
|= UNIXFILE_RDONLY
;
6485 noLock
= eType
!=SQLITE_OPEN_MAIN_DB
;
6486 if( noLock
) ctrlFlags
|= UNIXFILE_NOLOCK
;
6487 if( isNewJrnl
) ctrlFlags
|= UNIXFILE_DIRSYNC
;
6488 if( flags
& SQLITE_OPEN_URI
) ctrlFlags
|= UNIXFILE_URI
;
6490 #if SQLITE_ENABLE_LOCKING_STYLE
6491 #if SQLITE_PREFER_PROXY_LOCKING
6494 if( isAutoProxy
&& (zPath
!=NULL
) && (!noLock
) && pVfs
->xOpen
){
6495 char *envforce
= getenv("SQLITE_FORCE_PROXY_LOCKING");
6498 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
6499 ** never use proxy, NULL means use proxy for non-local files only. */
6500 if( envforce
!=NULL
){
6501 useProxy
= atoi(envforce
)>0;
6503 useProxy
= !(fsInfo
.f_flags
&MNT_LOCAL
);
6506 rc
= fillInUnixFile(pVfs
, fd
, pFile
, zPath
, ctrlFlags
);
6507 if( rc
==SQLITE_OK
){
6508 rc
= proxyTransformUnixFile((unixFile
*)pFile
, ":auto:");
6509 if( rc
!=SQLITE_OK
){
6510 /* Use unixClose to clean up the resources added in fillInUnixFile
6511 ** and clear all the structure's references. Specifically,
6512 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
6523 assert( zPath
==0 || zPath
[0]=='/'
6524 || eType
==SQLITE_OPEN_SUPER_JOURNAL
|| eType
==SQLITE_OPEN_MAIN_JOURNAL
6526 rc
= fillInUnixFile(pVfs
, fd
, pFile
, zPath
, ctrlFlags
);
6529 if( rc
!=SQLITE_OK
){
6530 sqlite3_free(p
->pPreallocatedUnused
);
6537 ** Delete the file at zPath. If the dirSync argument is true, fsync()
6538 ** the directory after deleting the file.
6540 static int unixDelete(
6541 sqlite3_vfs
*NotUsed
, /* VFS containing this as the xDelete method */
6542 const char *zPath
, /* Name of file to be deleted */
6543 int dirSync
/* If true, fsync() directory after deleting file */
6546 UNUSED_PARAMETER(NotUsed
);
6547 SimulateIOError(return SQLITE_IOERR_DELETE
);
6548 if( osUnlink(zPath
)==(-1) ){
6551 || osAccess(zPath
,0)!=0
6554 rc
= SQLITE_IOERR_DELETE_NOENT
;
6556 rc
= unixLogError(SQLITE_IOERR_DELETE
, "unlink", zPath
);
6560 #ifndef SQLITE_DISABLE_DIRSYNC
6561 if( (dirSync
& 1)!=0 ){
6563 rc
= osOpenDirectory(zPath
, &fd
);
6564 if( rc
==SQLITE_OK
){
6565 if( full_fsync(fd
,0,0) ){
6566 rc
= unixLogError(SQLITE_IOERR_DIR_FSYNC
, "fsync", zPath
);
6568 robust_close(0, fd
, __LINE__
);
6570 assert( rc
==SQLITE_CANTOPEN
);
6579 ** Test the existence of or access permissions of file zPath. The
6580 ** test performed depends on the value of flags:
6582 ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
6583 ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
6584 ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
6586 ** Otherwise return 0.
6588 static int unixAccess(
6589 sqlite3_vfs
*NotUsed
, /* The VFS containing this xAccess method */
6590 const char *zPath
, /* Path of the file to examine */
6591 int flags
, /* What do we want to learn about the zPath file? */
6592 int *pResOut
/* Write result boolean here */
6594 UNUSED_PARAMETER(NotUsed
);
6595 SimulateIOError( return SQLITE_IOERR_ACCESS
; );
6596 assert( pResOut
!=0 );
6598 /* The spec says there are three possible values for flags. But only
6599 ** two of them are actually used */
6600 assert( flags
==SQLITE_ACCESS_EXISTS
|| flags
==SQLITE_ACCESS_READWRITE
);
6602 if( flags
==SQLITE_ACCESS_EXISTS
){
6604 *pResOut
= 0==osStat(zPath
, &buf
) &&
6605 (!S_ISREG(buf
.st_mode
) || buf
.st_size
>0);
6607 *pResOut
= osAccess(zPath
, W_OK
|R_OK
)==0;
6613 ** A pathname under construction
6615 typedef struct DbPath DbPath
;
6617 int rc
; /* Non-zero following any error */
6618 int nSymlink
; /* Number of symlinks resolved */
6619 char *zOut
; /* Write the pathname here */
6620 int nOut
; /* Bytes of space available to zOut[] */
6621 int nUsed
; /* Bytes of zOut[] currently being used */
6624 /* Forward reference */
6625 static void appendAllPathElements(DbPath
*,const char*);
6628 ** Append a single path element to the DbPath under construction
6630 static void appendOnePathElement(
6631 DbPath
*pPath
, /* Path under construction, to which to append zName */
6632 const char *zName
, /* Name to append to pPath. Not zero-terminated */
6633 int nName
/* Number of significant bytes in zName */
6637 if( zName
[0]=='.' ){
6638 if( nName
==1 ) return;
6639 if( zName
[1]=='.' && nName
==2 ){
6640 if( pPath
->nUsed
>1 ){
6641 assert( pPath
->zOut
[0]=='/' );
6642 while( pPath
->zOut
[--pPath
->nUsed
]!='/' ){}
6647 if( pPath
->nUsed
+ nName
+ 2 >= pPath
->nOut
){
6648 pPath
->rc
= SQLITE_ERROR
;
6651 pPath
->zOut
[pPath
->nUsed
++] = '/';
6652 memcpy(&pPath
->zOut
[pPath
->nUsed
], zName
, nName
);
6653 pPath
->nUsed
+= nName
;
6654 #if defined(HAVE_READLINK) && defined(HAVE_LSTAT)
6655 if( pPath
->rc
==SQLITE_OK
){
6658 pPath
->zOut
[pPath
->nUsed
] = 0;
6660 if( osLstat(zIn
, &buf
)!=0 ){
6661 if( errno
!=ENOENT
){
6662 pPath
->rc
= unixLogError(SQLITE_CANTOPEN_BKPT
, "lstat", zIn
);
6664 }else if( S_ISLNK(buf
.st_mode
) ){
6666 char zLnk
[SQLITE_MAX_PATHLEN
+2];
6667 if( pPath
->nSymlink
++ > SQLITE_MAX_SYMLINK
){
6668 pPath
->rc
= SQLITE_CANTOPEN_BKPT
;
6671 got
= osReadlink(zIn
, zLnk
, sizeof(zLnk
)-2);
6672 if( got
<=0 || got
>=(ssize_t
)sizeof(zLnk
)-2 ){
6673 pPath
->rc
= unixLogError(SQLITE_CANTOPEN_BKPT
, "readlink", zIn
);
6680 pPath
->nUsed
-= nName
+ 1;
6682 appendAllPathElements(pPath
, zLnk
);
6689 ** Append all path elements in zPath to the DbPath under construction.
6691 static void appendAllPathElements(
6692 DbPath
*pPath
, /* Path under construction, to which to append zName */
6693 const char *zPath
/* Path to append to pPath. Is zero-terminated */
6698 while( zPath
[i
] && zPath
[i
]!='/' ){ i
++; }
6700 appendOnePathElement(pPath
, &zPath
[j
], i
-j
);
6703 }while( zPath
[i
++] );
6707 ** Turn a relative pathname into a full pathname. The relative path
6708 ** is stored as a nul-terminated string in the buffer pointed to by
6711 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
6712 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
6713 ** this buffer before returning.
6715 static int unixFullPathname(
6716 sqlite3_vfs
*pVfs
, /* Pointer to vfs object */
6717 const char *zPath
, /* Possibly relative input path */
6718 int nOut
, /* Size of output buffer in bytes */
6719 char *zOut
/* Output buffer */
6722 UNUSED_PARAMETER(pVfs
);
6728 if( zPath
[0]!='/' ){
6729 char zPwd
[SQLITE_MAX_PATHLEN
+2];
6730 if( osGetcwd(zPwd
, sizeof(zPwd
)-2)==0 ){
6731 return unixLogError(SQLITE_CANTOPEN_BKPT
, "getcwd", zPath
);
6733 appendAllPathElements(&path
, zPwd
);
6735 appendAllPathElements(&path
, zPath
);
6736 zOut
[path
.nUsed
] = 0;
6737 if( path
.rc
|| path
.nUsed
<2 ) return SQLITE_CANTOPEN_BKPT
;
6738 if( path
.nSymlink
) return SQLITE_OK_SYMLINK
;
6742 #ifndef SQLITE_OMIT_LOAD_EXTENSION
6744 ** Interfaces for opening a shared library, finding entry points
6745 ** within the shared library, and closing the shared library.
6748 static void *unixDlOpen(sqlite3_vfs
*NotUsed
, const char *zFilename
){
6749 UNUSED_PARAMETER(NotUsed
);
6750 return dlopen(zFilename
, RTLD_NOW
| RTLD_GLOBAL
);
6754 ** SQLite calls this function immediately after a call to unixDlSym() or
6755 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
6756 ** message is available, it is written to zBufOut. If no error message
6757 ** is available, zBufOut is left unmodified and SQLite uses a default
6760 static void unixDlError(sqlite3_vfs
*NotUsed
, int nBuf
, char *zBufOut
){
6762 UNUSED_PARAMETER(NotUsed
);
6766 sqlite3_snprintf(nBuf
, zBufOut
, "%s", zErr
);
6770 static void (*unixDlSym(sqlite3_vfs
*NotUsed
, void *p
, const char*zSym
))(void){
6772 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6773 ** cast into a pointer to a function. And yet the library dlsym() routine
6774 ** returns a void* which is really a pointer to a function. So how do we
6775 ** use dlsym() with -pedantic-errors?
6777 ** Variable x below is defined to be a pointer to a function taking
6778 ** parameters void* and const char* and returning a pointer to a function.
6779 ** We initialize x by assigning it a pointer to the dlsym() function.
6780 ** (That assignment requires a cast.) Then we call the function that
6783 ** This work-around is unlikely to work correctly on any system where
6784 ** you really cannot cast a function pointer into void*. But then, on the
6785 ** other hand, dlsym() will not work on such a system either, so we have
6786 ** not really lost anything.
6788 void (*(*x
)(void*,const char*))(void);
6789 UNUSED_PARAMETER(NotUsed
);
6790 x
= (void(*(*)(void*,const char*))(void))dlsym
;
6791 return (*x
)(p
, zSym
);
6793 static void unixDlClose(sqlite3_vfs
*NotUsed
, void *pHandle
){
6794 UNUSED_PARAMETER(NotUsed
);
6797 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6798 #define unixDlOpen 0
6799 #define unixDlError 0
6801 #define unixDlClose 0
6805 ** Write nBuf bytes of random data to the supplied buffer zBuf.
6807 static int unixRandomness(sqlite3_vfs
*NotUsed
, int nBuf
, char *zBuf
){
6808 UNUSED_PARAMETER(NotUsed
);
6809 assert((size_t)nBuf
>=(sizeof(time_t)+sizeof(int)));
6811 /* We have to initialize zBuf to prevent valgrind from reporting
6812 ** errors. The reports issued by valgrind are incorrect - we would
6813 ** prefer that the randomness be increased by making use of the
6814 ** uninitialized space in zBuf - but valgrind errors tend to worry
6815 ** some users. Rather than argue, it seems easier just to initialize
6816 ** the whole array and silence valgrind, even if that means less randomness
6817 ** in the random seed.
6819 ** When testing, initializing zBuf[] to zero is all we do. That means
6820 ** that we always use the same random number sequence. This makes the
6821 ** tests repeatable.
6823 memset(zBuf
, 0, nBuf
);
6824 randomnessPid
= osGetpid(0);
6825 #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
6828 fd
= robust_open("/dev/urandom", O_RDONLY
, 0);
6832 memcpy(zBuf
, &t
, sizeof(t
));
6833 memcpy(&zBuf
[sizeof(t
)], &randomnessPid
, sizeof(randomnessPid
));
6834 assert( sizeof(t
)+sizeof(randomnessPid
)<=(size_t)nBuf
);
6835 nBuf
= sizeof(t
) + sizeof(randomnessPid
);
6837 do{ got
= osRead(fd
, zBuf
, nBuf
); }while( got
<0 && errno
==EINTR
);
6838 robust_close(0, fd
, __LINE__
);
6847 ** Sleep for a little while. Return the amount of time slept.
6848 ** The argument is the number of microseconds we want to sleep.
6849 ** The return value is the number of microseconds of sleep actually
6850 ** requested from the underlying operating system, a number which
6851 ** might be greater than or equal to the argument, but not less
6852 ** than the argument.
6854 static int unixSleep(sqlite3_vfs
*NotUsed
, int microseconds
){
6855 #if !defined(HAVE_NANOSLEEP) || HAVE_NANOSLEEP+0
6857 sp
.tv_sec
= microseconds
/ 1000000;
6858 sp
.tv_nsec
= (microseconds
% 1000000) * 1000;
6860 /* Almost all modern unix systems support nanosleep(). But if you are
6861 ** compiling for one of the rare exceptions, you can use
6862 ** -DHAVE_NANOSLEEP=0 (perhaps in conjuction with -DHAVE_USLEEP if
6863 ** usleep() is available) in order to bypass the use of nanosleep() */
6864 nanosleep(&sp
, NULL
);
6866 UNUSED_PARAMETER(NotUsed
);
6867 return microseconds
;
6868 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
6869 if( microseconds
>=1000000 ) sleep(microseconds
/1000000);
6870 if( microseconds
%1000000 ) usleep(microseconds
%1000000);
6871 UNUSED_PARAMETER(NotUsed
);
6872 return microseconds
;
6874 int seconds
= (microseconds
+999999)/1000000;
6876 UNUSED_PARAMETER(NotUsed
);
6877 return seconds
*1000000;
6882 ** The following variable, if set to a non-zero value, is interpreted as
6883 ** the number of seconds since 1970 and is used to set the result of
6884 ** sqlite3OsCurrentTime() during testing.
6887 int sqlite3_current_time
= 0; /* Fake system time in seconds since 1970. */
6891 ** Find the current time (in Universal Coordinated Time). Write into *piNow
6892 ** the current time and date as a Julian Day number times 86_400_000. In
6893 ** other words, write into *piNow the number of milliseconds since the Julian
6894 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6895 ** proleptic Gregorian calendar.
6897 ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6900 static int unixCurrentTimeInt64(sqlite3_vfs
*NotUsed
, sqlite3_int64
*piNow
){
6901 static const sqlite3_int64 unixEpoch
= 24405875*(sqlite3_int64
)8640000;
6903 #if defined(NO_GETTOD)
6906 *piNow
= ((sqlite3_int64
)t
)*1000 + unixEpoch
;
6908 struct timespec sNow
;
6909 clock_gettime(CLOCK_REALTIME
, &sNow
);
6910 *piNow
= unixEpoch
+ 1000*(sqlite3_int64
)sNow
.tv_sec
+ sNow
.tv_nsec
/1000000;
6912 struct timeval sNow
;
6913 (void)gettimeofday(&sNow
, 0); /* Cannot fail given valid arguments */
6914 *piNow
= unixEpoch
+ 1000*(sqlite3_int64
)sNow
.tv_sec
+ sNow
.tv_usec
/1000;
6918 if( sqlite3_current_time
){
6919 *piNow
= 1000*(sqlite3_int64
)sqlite3_current_time
+ unixEpoch
;
6922 UNUSED_PARAMETER(NotUsed
);
6926 #ifndef SQLITE_OMIT_DEPRECATED
6928 ** Find the current time (in Universal Coordinated Time). Write the
6929 ** current time and date as a Julian Day number into *prNow and
6930 ** return 0. Return 1 if the time and date cannot be found.
6932 static int unixCurrentTime(sqlite3_vfs
*NotUsed
, double *prNow
){
6933 sqlite3_int64 i
= 0;
6935 UNUSED_PARAMETER(NotUsed
);
6936 rc
= unixCurrentTimeInt64(0, &i
);
6937 *prNow
= i
/86400000.0;
6941 # define unixCurrentTime 0
6945 ** The xGetLastError() method is designed to return a better
6946 ** low-level error message when operating-system problems come up
6947 ** during SQLite operation. Only the integer return code is currently
6950 static int unixGetLastError(sqlite3_vfs
*NotUsed
, int NotUsed2
, char *NotUsed3
){
6951 UNUSED_PARAMETER(NotUsed
);
6952 UNUSED_PARAMETER(NotUsed2
);
6953 UNUSED_PARAMETER(NotUsed3
);
6959 ************************ End of sqlite3_vfs methods ***************************
6960 ******************************************************************************/
6962 /******************************************************************************
6963 ************************** Begin Proxy Locking ********************************
6965 ** Proxy locking is a "uber-locking-method" in this sense: It uses the
6966 ** other locking methods on secondary lock files. Proxy locking is a
6967 ** meta-layer over top of the primitive locking implemented above. For
6968 ** this reason, the division that implements of proxy locking is deferred
6969 ** until late in the file (here) after all of the other I/O methods have
6970 ** been defined - so that the primitive locking methods are available
6971 ** as services to help with the implementation of proxy locking.
6975 ** The default locking schemes in SQLite use byte-range locks on the
6976 ** database file to coordinate safe, concurrent access by multiple readers
6977 ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6978 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6979 ** as POSIX read & write locks over fixed set of locations (via fsctl),
6980 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
6981 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6982 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6983 ** address in the shared range is taken for a SHARED lock, the entire
6984 ** shared range is taken for an EXCLUSIVE lock):
6986 ** PENDING_BYTE 0x40000000
6987 ** RESERVED_BYTE 0x40000001
6988 ** SHARED_RANGE 0x40000002 -> 0x40000200
6990 ** This works well on the local file system, but shows a nearly 100x
6991 ** slowdown in read performance on AFP because the AFP client disables
6992 ** the read cache when byte-range locks are present. Enabling the read
6993 ** cache exposes a cache coherency problem that is present on all OS X
6994 ** supported network file systems. NFS and AFP both observe the
6995 ** close-to-open semantics for ensuring cache coherency
6996 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6997 ** address the requirements for concurrent database access by multiple
6998 ** readers and writers
6999 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
7001 ** To address the performance and cache coherency issues, proxy file locking
7002 ** changes the way database access is controlled by limiting access to a
7003 ** single host at a time and moving file locks off of the database file
7004 ** and onto a proxy file on the local file system.
7007 ** Using proxy locks
7008 ** -----------------
7012 ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
7013 ** <proxy_path> | ":auto:");
7014 ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
7020 ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
7021 ** PRAGMA [database.]lock_proxy_file
7023 ** Specifying ":auto:" means that if there is a conch file with a matching
7024 ** host ID in it, the proxy path in the conch file will be used, otherwise
7025 ** a proxy path based on the user's temp dir
7026 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
7027 ** actual proxy file name is generated from the name and path of the
7028 ** database file. For example:
7030 ** For database path "/Users/me/foo.db"
7031 ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
7033 ** Once a lock proxy is configured for a database connection, it can not
7034 ** be removed, however it may be switched to a different proxy path via
7035 ** the above APIs (assuming the conch file is not being held by another
7036 ** connection or process).
7039 ** How proxy locking works
7040 ** -----------------------
7042 ** Proxy file locking relies primarily on two new supporting files:
7044 ** * conch file to limit access to the database file to a single host
7047 ** * proxy file to act as a proxy for the advisory locks normally
7048 ** taken on the database
7050 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
7051 ** by taking an sqlite-style shared lock on the conch file, reading the
7052 ** contents and comparing the host's unique host ID (see below) and lock
7053 ** proxy path against the values stored in the conch. The conch file is
7054 ** stored in the same directory as the database file and the file name
7055 ** is patterned after the database file name as ".<databasename>-conch".
7056 ** If the conch file does not exist, or its contents do not match the
7057 ** host ID and/or proxy path, then the lock is escalated to an exclusive
7058 ** lock and the conch file contents is updated with the host ID and proxy
7059 ** path and the lock is downgraded to a shared lock again. If the conch
7060 ** is held by another process (with a shared lock), the exclusive lock
7061 ** will fail and SQLITE_BUSY is returned.
7063 ** The proxy file - a single-byte file used for all advisory file locks
7064 ** normally taken on the database file. This allows for safe sharing
7065 ** of the database file for multiple readers and writers on the same
7066 ** host (the conch ensures that they all use the same local lock file).
7068 ** Requesting the lock proxy does not immediately take the conch, it is
7069 ** only taken when the first request to lock database file is made.
7070 ** This matches the semantics of the traditional locking behavior, where
7071 ** opening a connection to a database file does not take a lock on it.
7072 ** The shared lock and an open file descriptor are maintained until
7073 ** the connection to the database is closed.
7075 ** The proxy file and the lock file are never deleted so they only need
7076 ** to be created the first time they are used.
7078 ** Configuration options
7079 ** ---------------------
7081 ** SQLITE_PREFER_PROXY_LOCKING
7083 ** Database files accessed on non-local file systems are
7084 ** automatically configured for proxy locking, lock files are
7085 ** named automatically using the same logic as
7086 ** PRAGMA lock_proxy_file=":auto:"
7088 ** SQLITE_PROXY_DEBUG
7090 ** Enables the logging of error messages during host id file
7091 ** retrieval and creation
7095 ** Overrides the default directory used for lock proxy files that
7096 ** are named automatically via the ":auto:" setting
7098 ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
7100 ** Permissions to use when creating a directory for storing the
7101 ** lock proxy files, only used when LOCKPROXYDIR is not set.
7104 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
7105 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
7106 ** force proxy locking to be used for every database file opened, and 0
7107 ** will force automatic proxy locking to be disabled for all database
7108 ** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
7109 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
7113 ** Proxy locking is only available on MacOSX
7115 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
7118 ** The proxyLockingContext has the path and file structures for the remote
7119 ** and local proxy files in it
7121 typedef struct proxyLockingContext proxyLockingContext
;
7122 struct proxyLockingContext
{
7123 unixFile
*conchFile
; /* Open conch file */
7124 char *conchFilePath
; /* Name of the conch file */
7125 unixFile
*lockProxy
; /* Open proxy lock file */
7126 char *lockProxyPath
; /* Name of the proxy lock file */
7127 char *dbPath
; /* Name of the open file */
7128 int conchHeld
; /* 1 if the conch is held, -1 if lockless */
7129 int nFails
; /* Number of conch taking failures */
7130 void *oldLockingContext
; /* Original lockingcontext to restore on close */
7131 sqlite3_io_methods
const *pOldMethod
; /* Original I/O methods for close */
7135 ** The proxy lock file path for the database at dbPath is written into lPath,
7136 ** which must point to valid, writable memory large enough for a maxLen length
7139 static int proxyGetLockPath(const char *dbPath
, char *lPath
, size_t maxLen
){
7145 len
= strlcpy(lPath
, LOCKPROXYDIR
, maxLen
);
7147 # ifdef _CS_DARWIN_USER_TEMP_DIR
7149 if( !confstr(_CS_DARWIN_USER_TEMP_DIR
, lPath
, maxLen
) ){
7150 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
7151 lPath
, errno
, osGetpid(0)));
7152 return SQLITE_IOERR_LOCK
;
7154 len
= strlcat(lPath
, "sqliteplocks", maxLen
);
7157 len
= strlcpy(lPath
, "/tmp/", maxLen
);
7161 if( lPath
[len
-1]!='/' ){
7162 len
= strlcat(lPath
, "/", maxLen
);
7165 /* transform the db path to a unique cache name */
7166 dbLen
= (int)strlen(dbPath
);
7167 for( i
=0; i
<dbLen
&& (i
+len
+7)<(int)maxLen
; i
++){
7169 lPath
[i
+len
] = (c
=='/')?'_':c
;
7172 strlcat(lPath
, ":auto:", maxLen
);
7173 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath
, osGetpid(0)));
7178 ** Creates the lock file and any missing directories in lockPath
7180 static int proxyCreateLockPath(const char *lockPath
){
7182 char buf
[MAXPATHLEN
];
7185 assert(lockPath
!=NULL
);
7186 /* try to create all the intermediate directories */
7187 len
= (int)strlen(lockPath
);
7188 buf
[0] = lockPath
[0];
7189 for( i
=1; i
<len
; i
++ ){
7190 if( lockPath
[i
] == '/' && (i
- start
> 0) ){
7191 /* only mkdir if leaf dir != "." or "/" or ".." */
7192 if( i
-start
>2 || (i
-start
==1 && buf
[start
] != '.' && buf
[start
] != '/')
7193 || (i
-start
==2 && buf
[start
] != '.' && buf
[start
+1] != '.') ){
7195 if( osMkdir(buf
, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
) ){
7198 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
7199 "'%s' proxy lock path=%s pid=%d\n",
7200 buf
, strerror(err
), lockPath
, osGetpid(0)));
7207 buf
[i
] = lockPath
[i
];
7209 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath
,osGetpid(0)));
7214 ** Create a new VFS file descriptor (stored in memory obtained from
7215 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
7217 ** The caller is responsible not only for closing the file descriptor
7218 ** but also for freeing the memory associated with the file descriptor.
7220 static int proxyCreateUnixFile(
7221 const char *path
, /* path for the new unixFile */
7222 unixFile
**ppFile
, /* unixFile created and returned by ref */
7223 int islockfile
/* if non zero missing dirs will be created */
7228 int openFlags
= O_RDWR
| O_CREAT
| O_NOFOLLOW
;
7229 sqlite3_vfs dummyVfs
;
7231 UnixUnusedFd
*pUnused
= NULL
;
7233 /* 1. first try to open/create the file
7234 ** 2. if that fails, and this is a lock file (not-conch), try creating
7235 ** the parent directories and then try again.
7236 ** 3. if that fails, try to open the file read-only
7237 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
7239 pUnused
= findReusableFd(path
, openFlags
);
7243 pUnused
= sqlite3_malloc64(sizeof(*pUnused
));
7245 return SQLITE_NOMEM_BKPT
;
7249 fd
= robust_open(path
, openFlags
, 0);
7251 if( fd
<0 && errno
==ENOENT
&& islockfile
){
7252 if( proxyCreateLockPath(path
) == SQLITE_OK
){
7253 fd
= robust_open(path
, openFlags
, 0);
7258 openFlags
= O_RDONLY
| O_NOFOLLOW
;
7259 fd
= robust_open(path
, openFlags
, 0);
7270 return SQLITE_IOERR_LOCK
; /* even though it is the conch */
7272 return SQLITE_CANTOPEN_BKPT
;
7276 pNew
= (unixFile
*)sqlite3_malloc64(sizeof(*pNew
));
7278 rc
= SQLITE_NOMEM_BKPT
;
7279 goto end_create_proxy
;
7281 memset(pNew
, 0, sizeof(unixFile
));
7282 pNew
->openFlags
= openFlags
;
7283 memset(&dummyVfs
, 0, sizeof(dummyVfs
));
7284 dummyVfs
.pAppData
= (void*)&autolockIoFinder
;
7285 dummyVfs
.zName
= "dummy";
7287 pUnused
->flags
= openFlags
;
7288 pNew
->pPreallocatedUnused
= pUnused
;
7290 rc
= fillInUnixFile(&dummyVfs
, fd
, (sqlite3_file
*)pNew
, path
, 0);
7291 if( rc
==SQLITE_OK
){
7296 robust_close(pNew
, fd
, __LINE__
);
7298 sqlite3_free(pUnused
);
7303 /* simulate multiple hosts by creating unique hostid file paths */
7304 int sqlite3_hostid_num
= 0;
7307 #define PROXY_HOSTIDLEN 16 /* conch file host id length */
7309 #if HAVE_GETHOSTUUID
7310 /* Not always defined in the headers as it ought to be */
7311 extern int gethostuuid(uuid_t id
, const struct timespec
*wait
);
7314 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
7315 ** bytes of writable memory.
7317 static int proxyGetHostID(unsigned char *pHostID
, int *pError
){
7318 assert(PROXY_HOSTIDLEN
== sizeof(uuid_t
));
7319 memset(pHostID
, 0, PROXY_HOSTIDLEN
);
7320 #if HAVE_GETHOSTUUID
7322 struct timespec timeout
= {1, 0}; /* 1 sec timeout */
7323 if( gethostuuid(pHostID
, &timeout
) ){
7328 return SQLITE_IOERR
;
7332 UNUSED_PARAMETER(pError
);
7335 /* simulate multiple hosts by creating unique hostid file paths */
7336 if( sqlite3_hostid_num
!= 0){
7337 pHostID
[0] = (char)(pHostID
[0] + (char)(sqlite3_hostid_num
& 0xFF));
7344 /* The conch file contains the header, host id and lock file path
7346 #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
7347 #define PROXY_HEADERLEN 1 /* conch file header length */
7348 #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
7349 #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
7352 ** Takes an open conch file, copies the contents to a new path and then moves
7353 ** it back. The newly created file's file descriptor is assigned to the
7354 ** conch file structure and finally the original conch file descriptor is
7355 ** closed. Returns zero if successful.
7357 static int proxyBreakConchLock(unixFile
*pFile
, uuid_t myHostID
){
7358 proxyLockingContext
*pCtx
= (proxyLockingContext
*)pFile
->lockingContext
;
7359 unixFile
*conchFile
= pCtx
->conchFile
;
7360 char tPath
[MAXPATHLEN
];
7361 char buf
[PROXY_MAXCONCHLEN
];
7362 char *cPath
= pCtx
->conchFilePath
;
7365 char errmsg
[64] = "";
7368 UNUSED_PARAMETER(myHostID
);
7370 /* create a new path by replace the trailing '-conch' with '-break' */
7371 pathLen
= strlcpy(tPath
, cPath
, MAXPATHLEN
);
7372 if( pathLen
>MAXPATHLEN
|| pathLen
<6 ||
7373 (strlcpy(&tPath
[pathLen
-5], "break", 6) != 5) ){
7374 sqlite3_snprintf(sizeof(errmsg
),errmsg
,"path error (len %d)",(int)pathLen
);
7377 /* read the conch content */
7378 readLen
= osPread(conchFile
->h
, buf
, PROXY_MAXCONCHLEN
, 0);
7379 if( readLen
<PROXY_PATHINDEX
){
7380 sqlite3_snprintf(sizeof(errmsg
),errmsg
,"read error (len %d)",(int)readLen
);
7383 /* write it out to the temporary break file */
7384 fd
= robust_open(tPath
, (O_RDWR
|O_CREAT
|O_EXCL
|O_NOFOLLOW
), 0);
7386 sqlite3_snprintf(sizeof(errmsg
), errmsg
, "create failed (%d)", errno
);
7389 if( osPwrite(fd
, buf
, readLen
, 0) != (ssize_t
)readLen
){
7390 sqlite3_snprintf(sizeof(errmsg
), errmsg
, "write failed (%d)", errno
);
7393 if( rename(tPath
, cPath
) ){
7394 sqlite3_snprintf(sizeof(errmsg
), errmsg
, "rename failed (%d)", errno
);
7398 fprintf(stderr
, "broke stale lock on %s\n", cPath
);
7399 robust_close(pFile
, conchFile
->h
, __LINE__
);
7401 conchFile
->openFlags
= O_RDWR
| O_CREAT
;
7407 robust_close(pFile
, fd
, __LINE__
);
7409 fprintf(stderr
, "failed to break stale lock on %s, %s\n", cPath
, errmsg
);
7414 /* Take the requested lock on the conch file and break a stale lock if the
7417 static int proxyConchLock(unixFile
*pFile
, uuid_t myHostID
, int lockType
){
7418 proxyLockingContext
*pCtx
= (proxyLockingContext
*)pFile
->lockingContext
;
7419 unixFile
*conchFile
= pCtx
->conchFile
;
7422 struct timespec conchModTime
;
7424 memset(&conchModTime
, 0, sizeof(conchModTime
));
7426 rc
= conchFile
->pMethod
->xLock((sqlite3_file
*)conchFile
, lockType
);
7428 if( rc
==SQLITE_BUSY
){
7429 /* If the lock failed (busy):
7430 * 1st try: get the mod time of the conch, wait 0.5s and try again.
7431 * 2nd try: fail if the mod time changed or host id is different, wait
7432 * 10 sec and try again
7433 * 3rd try: break the lock unless the mod time has changed.
7436 if( osFstat(conchFile
->h
, &buf
) ){
7437 storeLastErrno(pFile
, errno
);
7438 return SQLITE_IOERR_LOCK
;
7442 conchModTime
= buf
.st_mtimespec
;
7443 unixSleep(0,500000); /* wait 0.5 sec and try the lock again*/
7448 if( conchModTime
.tv_sec
!= buf
.st_mtimespec
.tv_sec
||
7449 conchModTime
.tv_nsec
!= buf
.st_mtimespec
.tv_nsec
){
7454 char tBuf
[PROXY_MAXCONCHLEN
];
7455 int len
= osPread(conchFile
->h
, tBuf
, PROXY_MAXCONCHLEN
, 0);
7457 storeLastErrno(pFile
, errno
);
7458 return SQLITE_IOERR_LOCK
;
7460 if( len
>PROXY_PATHINDEX
&& tBuf
[0]==(char)PROXY_CONCHVERSION
){
7461 /* don't break the lock if the host id doesn't match */
7462 if( 0!=memcmp(&tBuf
[PROXY_HEADERLEN
], myHostID
, PROXY_HOSTIDLEN
) ){
7466 /* don't break the lock on short read or a version mismatch */
7469 unixSleep(0,10000000); /* wait 10 sec and try the lock again */
7473 assert( nTries
==3 );
7474 if( 0==proxyBreakConchLock(pFile
, myHostID
) ){
7476 if( lockType
==EXCLUSIVE_LOCK
){
7477 rc
= conchFile
->pMethod
->xLock((sqlite3_file
*)conchFile
, SHARED_LOCK
);
7480 rc
= conchFile
->pMethod
->xLock((sqlite3_file
*)conchFile
, lockType
);
7484 } while( rc
==SQLITE_BUSY
&& nTries
<3 );
7489 /* Takes the conch by taking a shared lock and read the contents conch, if
7490 ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
7491 ** lockPath means that the lockPath in the conch file will be used if the
7492 ** host IDs match, or a new lock path will be generated automatically
7493 ** and written to the conch file.
7495 static int proxyTakeConch(unixFile
*pFile
){
7496 proxyLockingContext
*pCtx
= (proxyLockingContext
*)pFile
->lockingContext
;
7498 if( pCtx
->conchHeld
!=0 ){
7501 unixFile
*conchFile
= pCtx
->conchFile
;
7504 char readBuf
[PROXY_MAXCONCHLEN
];
7505 char lockPath
[MAXPATHLEN
];
7506 char *tempLockPath
= NULL
;
7508 int createConch
= 0;
7509 int hostIdMatch
= 0;
7511 int tryOldLockPath
= 0;
7512 int forceNewLockPath
= 0;
7514 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile
->h
,
7515 (pCtx
->lockProxyPath
? pCtx
->lockProxyPath
: ":auto:"),
7518 rc
= proxyGetHostID(myHostID
, &pError
);
7519 if( (rc
&0xff)==SQLITE_IOERR
){
7520 storeLastErrno(pFile
, pError
);
7523 rc
= proxyConchLock(pFile
, myHostID
, SHARED_LOCK
);
7524 if( rc
!=SQLITE_OK
){
7527 /* read the existing conch file */
7528 readLen
= seekAndRead((unixFile
*)conchFile
, 0, readBuf
, PROXY_MAXCONCHLEN
);
7530 /* I/O error: lastErrno set by seekAndRead */
7531 storeLastErrno(pFile
, conchFile
->lastErrno
);
7532 rc
= SQLITE_IOERR_READ
;
7534 }else if( readLen
<=(PROXY_HEADERLEN
+PROXY_HOSTIDLEN
) ||
7535 readBuf
[0]!=(char)PROXY_CONCHVERSION
){
7536 /* a short read or version format mismatch means we need to create a new
7541 /* if the host id matches and the lock path already exists in the conch
7542 ** we'll try to use the path there, if we can't open that path, we'll
7543 ** retry with a new auto-generated path
7545 do { /* in case we need to try again for an :auto: named lock file */
7547 if( !createConch
&& !forceNewLockPath
){
7548 hostIdMatch
= !memcmp(&readBuf
[PROXY_HEADERLEN
], myHostID
,
7550 /* if the conch has data compare the contents */
7551 if( !pCtx
->lockProxyPath
){
7552 /* for auto-named local lock file, just check the host ID and we'll
7553 ** use the local lock file path that's already in there
7556 size_t pathLen
= (readLen
- PROXY_PATHINDEX
);
7558 if( pathLen
>=MAXPATHLEN
){
7559 pathLen
=MAXPATHLEN
-1;
7561 memcpy(lockPath
, &readBuf
[PROXY_PATHINDEX
], pathLen
);
7562 lockPath
[pathLen
] = 0;
7563 tempLockPath
= lockPath
;
7565 /* create a copy of the lock path if the conch is taken */
7568 }else if( hostIdMatch
7569 && !strncmp(pCtx
->lockProxyPath
, &readBuf
[PROXY_PATHINDEX
],
7570 readLen
-PROXY_PATHINDEX
)
7572 /* conch host and lock path match */
7577 /* if the conch isn't writable and doesn't match, we can't take it */
7578 if( (conchFile
->openFlags
&O_RDWR
) == 0 ){
7583 /* either the conch didn't match or we need to create a new one */
7584 if( !pCtx
->lockProxyPath
){
7585 proxyGetLockPath(pCtx
->dbPath
, lockPath
, MAXPATHLEN
);
7586 tempLockPath
= lockPath
;
7587 /* create a copy of the lock path _only_ if the conch is taken */
7590 /* update conch with host and path (this will fail if other process
7591 ** has a shared lock already), if the host id matches, use the big
7594 futimes(conchFile
->h
, NULL
);
7595 if( hostIdMatch
&& !createConch
){
7596 if( conchFile
->pInode
&& conchFile
->pInode
->nShared
>1 ){
7597 /* We are trying for an exclusive lock but another thread in this
7598 ** same process is still holding a shared lock. */
7601 rc
= proxyConchLock(pFile
, myHostID
, EXCLUSIVE_LOCK
);
7604 rc
= proxyConchLock(pFile
, myHostID
, EXCLUSIVE_LOCK
);
7606 if( rc
==SQLITE_OK
){
7607 char writeBuffer
[PROXY_MAXCONCHLEN
];
7610 writeBuffer
[0] = (char)PROXY_CONCHVERSION
;
7611 memcpy(&writeBuffer
[PROXY_HEADERLEN
], myHostID
, PROXY_HOSTIDLEN
);
7612 if( pCtx
->lockProxyPath
!=NULL
){
7613 strlcpy(&writeBuffer
[PROXY_PATHINDEX
], pCtx
->lockProxyPath
,
7616 strlcpy(&writeBuffer
[PROXY_PATHINDEX
], tempLockPath
, MAXPATHLEN
);
7618 writeSize
= PROXY_PATHINDEX
+ strlen(&writeBuffer
[PROXY_PATHINDEX
]);
7619 robust_ftruncate(conchFile
->h
, writeSize
);
7620 rc
= unixWrite((sqlite3_file
*)conchFile
, writeBuffer
, writeSize
, 0);
7621 full_fsync(conchFile
->h
,0,0);
7622 /* If we created a new conch file (not just updated the contents of a
7623 ** valid conch file), try to match the permissions of the database
7625 if( rc
==SQLITE_OK
&& createConch
){
7627 int err
= osFstat(pFile
->h
, &buf
);
7629 mode_t cmode
= buf
.st_mode
&(S_IRUSR
|S_IWUSR
| S_IRGRP
|S_IWGRP
|
7631 /* try to match the database file R/W permissions, ignore failure */
7632 #ifndef SQLITE_PROXY_DEBUG
7633 osFchmod(conchFile
->h
, cmode
);
7636 rc
= osFchmod(conchFile
->h
, cmode
);
7637 }while( rc
==(-1) && errno
==EINTR
);
7640 fprintf(stderr
, "fchmod %o FAILED with %d %s\n",
7641 cmode
, code
, strerror(code
));
7643 fprintf(stderr
, "fchmod %o SUCCEDED\n",cmode
);
7647 fprintf(stderr
, "STAT FAILED[%d] with %d %s\n",
7648 err
, code
, strerror(code
));
7653 conchFile
->pMethod
->xUnlock((sqlite3_file
*)conchFile
, SHARED_LOCK
);
7656 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile
->h
));
7657 if( rc
==SQLITE_OK
&& pFile
->openFlags
){
7660 robust_close(pFile
, pFile
->h
, __LINE__
);
7663 fd
= robust_open(pCtx
->dbPath
, pFile
->openFlags
, 0);
7664 OSTRACE(("TRANSPROXY: OPEN %d\n", fd
));
7668 rc
=SQLITE_CANTOPEN_BKPT
; /* SQLITE_BUSY? proxyTakeConch called
7672 if( rc
==SQLITE_OK
&& !pCtx
->lockProxy
){
7673 char *path
= tempLockPath
? tempLockPath
: pCtx
->lockProxyPath
;
7674 rc
= proxyCreateUnixFile(path
, &pCtx
->lockProxy
, 1);
7675 if( rc
!=SQLITE_OK
&& rc
!=SQLITE_NOMEM
&& tryOldLockPath
){
7676 /* we couldn't create the proxy lock file with the old lock file path
7677 ** so try again via auto-naming
7679 forceNewLockPath
= 1;
7681 continue; /* go back to the do {} while start point, try again */
7684 if( rc
==SQLITE_OK
){
7685 /* Need to make a copy of path if we extracted the value
7686 ** from the conch file or the path was allocated on the stack
7689 pCtx
->lockProxyPath
= sqlite3DbStrDup(0, tempLockPath
);
7690 if( !pCtx
->lockProxyPath
){
7691 rc
= SQLITE_NOMEM_BKPT
;
7695 if( rc
==SQLITE_OK
){
7696 pCtx
->conchHeld
= 1;
7698 if( pCtx
->lockProxy
->pMethod
== &afpIoMethods
){
7699 afpLockingContext
*afpCtx
;
7700 afpCtx
= (afpLockingContext
*)pCtx
->lockProxy
->lockingContext
;
7701 afpCtx
->dbPath
= pCtx
->lockProxyPath
;
7704 conchFile
->pMethod
->xUnlock((sqlite3_file
*)conchFile
, NO_LOCK
);
7706 OSTRACE(("TAKECONCH %d %s\n", conchFile
->h
,
7707 rc
==SQLITE_OK
?"ok":"failed"));
7709 } while (1); /* in case we need to retry the :auto: lock file -
7710 ** we should never get here except via the 'continue' call. */
7715 ** If pFile holds a lock on a conch file, then release that lock.
7717 static int proxyReleaseConch(unixFile
*pFile
){
7718 int rc
= SQLITE_OK
; /* Subroutine return code */
7719 proxyLockingContext
*pCtx
; /* The locking context for the proxy lock */
7720 unixFile
*conchFile
; /* Name of the conch file */
7722 pCtx
= (proxyLockingContext
*)pFile
->lockingContext
;
7723 conchFile
= pCtx
->conchFile
;
7724 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile
->h
,
7725 (pCtx
->lockProxyPath
? pCtx
->lockProxyPath
: ":auto:"),
7727 if( pCtx
->conchHeld
>0 ){
7728 rc
= conchFile
->pMethod
->xUnlock((sqlite3_file
*)conchFile
, NO_LOCK
);
7730 pCtx
->conchHeld
= 0;
7731 OSTRACE(("RELEASECONCH %d %s\n", conchFile
->h
,
7732 (rc
==SQLITE_OK
? "ok" : "failed")));
7737 ** Given the name of a database file, compute the name of its conch file.
7738 ** Store the conch filename in memory obtained from sqlite3_malloc64().
7739 ** Make *pConchPath point to the new name. Return SQLITE_OK on success
7740 ** or SQLITE_NOMEM if unable to obtain memory.
7742 ** The caller is responsible for ensuring that the allocated memory
7743 ** space is eventually freed.
7745 ** *pConchPath is set to NULL if a memory allocation error occurs.
7747 static int proxyCreateConchPathname(char *dbPath
, char **pConchPath
){
7748 int i
; /* Loop counter */
7749 int len
= (int)strlen(dbPath
); /* Length of database filename - dbPath */
7750 char *conchPath
; /* buffer in which to construct conch name */
7752 /* Allocate space for the conch filename and initialize the name to
7753 ** the name of the original database file. */
7754 *pConchPath
= conchPath
= (char *)sqlite3_malloc64(len
+ 8);
7756 return SQLITE_NOMEM_BKPT
;
7758 memcpy(conchPath
, dbPath
, len
+1);
7760 /* now insert a "." before the last / character */
7761 for( i
=(len
-1); i
>=0; i
-- ){
7762 if( conchPath
[i
]=='/' ){
7769 conchPath
[i
+1]=dbPath
[i
];
7773 /* append the "-conch" suffix to the file */
7774 memcpy(&conchPath
[i
+1], "-conch", 7);
7775 assert( (int)strlen(conchPath
) == len
+7 );
7781 /* Takes a fully configured proxy locking-style unix file and switches
7782 ** the local lock file path
7784 static int switchLockProxyPath(unixFile
*pFile
, const char *path
) {
7785 proxyLockingContext
*pCtx
= (proxyLockingContext
*)pFile
->lockingContext
;
7786 char *oldPath
= pCtx
->lockProxyPath
;
7789 if( pFile
->eFileLock
!=NO_LOCK
){
7793 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7794 if( !path
|| path
[0]=='\0' || !strcmp(path
, ":auto:") ||
7795 (oldPath
&& !strncmp(oldPath
, path
, MAXPATHLEN
)) ){
7798 unixFile
*lockProxy
= pCtx
->lockProxy
;
7799 pCtx
->lockProxy
=NULL
;
7800 pCtx
->conchHeld
= 0;
7801 if( lockProxy
!=NULL
){
7802 rc
=lockProxy
->pMethod
->xClose((sqlite3_file
*)lockProxy
);
7804 sqlite3_free(lockProxy
);
7806 sqlite3_free(oldPath
);
7807 pCtx
->lockProxyPath
= sqlite3DbStrDup(0, path
);
7814 ** pFile is a file that has been opened by a prior xOpen call. dbPath
7815 ** is a string buffer at least MAXPATHLEN+1 characters in size.
7817 ** This routine find the filename associated with pFile and writes it
7820 static int proxyGetDbPathForUnixFile(unixFile
*pFile
, char *dbPath
){
7821 #if defined(__APPLE__)
7822 if( pFile
->pMethod
== &afpIoMethods
){
7823 /* afp style keeps a reference to the db path in the filePath field
7825 assert( (int)strlen((char*)pFile
->lockingContext
)<=MAXPATHLEN
);
7826 strlcpy(dbPath
, ((afpLockingContext
*)pFile
->lockingContext
)->dbPath
,
7830 if( pFile
->pMethod
== &dotlockIoMethods
){
7831 /* dot lock style uses the locking context to store the dot lock
7833 int len
= strlen((char *)pFile
->lockingContext
) - strlen(DOTLOCK_SUFFIX
);
7834 memcpy(dbPath
, (char *)pFile
->lockingContext
, len
+ 1);
7836 /* all other styles use the locking context to store the db file path */
7837 assert( strlen((char*)pFile
->lockingContext
)<=MAXPATHLEN
);
7838 strlcpy(dbPath
, (char *)pFile
->lockingContext
, MAXPATHLEN
);
7844 ** Takes an already filled in unix file and alters it so all file locking
7845 ** will be performed on the local proxy lock file. The following fields
7846 ** are preserved in the locking context so that they can be restored and
7847 ** the unix structure properly cleaned up at close time:
7851 static int proxyTransformUnixFile(unixFile
*pFile
, const char *path
) {
7852 proxyLockingContext
*pCtx
;
7853 char dbPath
[MAXPATHLEN
+1]; /* Name of the database file */
7854 char *lockPath
=NULL
;
7857 if( pFile
->eFileLock
!=NO_LOCK
){
7860 proxyGetDbPathForUnixFile(pFile
, dbPath
);
7861 if( !path
|| path
[0]=='\0' || !strcmp(path
, ":auto:") ){
7864 lockPath
=(char *)path
;
7867 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile
->h
,
7868 (lockPath
? lockPath
: ":auto:"), osGetpid(0)));
7870 pCtx
= sqlite3_malloc64( sizeof(*pCtx
) );
7872 return SQLITE_NOMEM_BKPT
;
7874 memset(pCtx
, 0, sizeof(*pCtx
));
7876 rc
= proxyCreateConchPathname(dbPath
, &pCtx
->conchFilePath
);
7877 if( rc
==SQLITE_OK
){
7878 rc
= proxyCreateUnixFile(pCtx
->conchFilePath
, &pCtx
->conchFile
, 0);
7879 if( rc
==SQLITE_CANTOPEN
&& ((pFile
->openFlags
&O_RDWR
) == 0) ){
7880 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7881 ** (c) the file system is read-only, then enable no-locking access.
7882 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7883 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7885 struct statfs fsInfo
;
7886 struct stat conchInfo
;
7889 if( osStat(pCtx
->conchFilePath
, &conchInfo
) == -1 ) {
7891 if( (err
==ENOENT
) && (statfs(dbPath
, &fsInfo
) != -1) ){
7892 goLockless
= (fsInfo
.f_flags
&MNT_RDONLY
) == MNT_RDONLY
;
7896 pCtx
->conchHeld
= -1; /* read only FS/ lockless */
7901 if( rc
==SQLITE_OK
&& lockPath
){
7902 pCtx
->lockProxyPath
= sqlite3DbStrDup(0, lockPath
);
7905 if( rc
==SQLITE_OK
){
7906 pCtx
->dbPath
= sqlite3DbStrDup(0, dbPath
);
7907 if( pCtx
->dbPath
==NULL
){
7908 rc
= SQLITE_NOMEM_BKPT
;
7911 if( rc
==SQLITE_OK
){
7912 /* all memory is allocated, proxys are created and assigned,
7913 ** switch the locking context and pMethod then return.
7915 pCtx
->oldLockingContext
= pFile
->lockingContext
;
7916 pFile
->lockingContext
= pCtx
;
7917 pCtx
->pOldMethod
= pFile
->pMethod
;
7918 pFile
->pMethod
= &proxyIoMethods
;
7920 if( pCtx
->conchFile
){
7921 pCtx
->conchFile
->pMethod
->xClose((sqlite3_file
*)pCtx
->conchFile
);
7922 sqlite3_free(pCtx
->conchFile
);
7924 sqlite3DbFree(0, pCtx
->lockProxyPath
);
7925 sqlite3_free(pCtx
->conchFilePath
);
7928 OSTRACE(("TRANSPROXY %d %s\n", pFile
->h
,
7929 (rc
==SQLITE_OK
? "ok" : "failed")));
7935 ** This routine handles sqlite3_file_control() calls that are specific
7936 ** to proxy locking.
7938 static int proxyFileControl(sqlite3_file
*id
, int op
, void *pArg
){
7940 case SQLITE_FCNTL_GET_LOCKPROXYFILE
: {
7941 unixFile
*pFile
= (unixFile
*)id
;
7942 if( pFile
->pMethod
== &proxyIoMethods
){
7943 proxyLockingContext
*pCtx
= (proxyLockingContext
*)pFile
->lockingContext
;
7944 proxyTakeConch(pFile
);
7945 if( pCtx
->lockProxyPath
){
7946 *(const char **)pArg
= pCtx
->lockProxyPath
;
7948 *(const char **)pArg
= ":auto: (not held)";
7951 *(const char **)pArg
= NULL
;
7955 case SQLITE_FCNTL_SET_LOCKPROXYFILE
: {
7956 unixFile
*pFile
= (unixFile
*)id
;
7958 int isProxyStyle
= (pFile
->pMethod
== &proxyIoMethods
);
7959 if( pArg
==NULL
|| (const char *)pArg
==0 ){
7961 /* turn off proxy locking - not supported. If support is added for
7962 ** switching proxy locking mode off then it will need to fail if
7963 ** the journal mode is WAL mode.
7965 rc
= SQLITE_ERROR
/*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7967 /* turn off proxy locking - already off - NOOP */
7971 const char *proxyPath
= (const char *)pArg
;
7973 proxyLockingContext
*pCtx
=
7974 (proxyLockingContext
*)pFile
->lockingContext
;
7975 if( !strcmp(pArg
, ":auto:")
7976 || (pCtx
->lockProxyPath
&&
7977 !strncmp(pCtx
->lockProxyPath
, proxyPath
, MAXPATHLEN
))
7981 rc
= switchLockProxyPath(pFile
, proxyPath
);
7984 /* turn on proxy file locking */
7985 rc
= proxyTransformUnixFile(pFile
, proxyPath
);
7991 assert( 0 ); /* The call assures that only valid opcodes are sent */
7994 /*NOTREACHED*/ assert(0);
7995 return SQLITE_ERROR
;
7999 ** Within this division (the proxying locking implementation) the procedures
8000 ** above this point are all utilities. The lock-related methods of the
8001 ** proxy-locking sqlite3_io_method object follow.
8006 ** This routine checks if there is a RESERVED lock held on the specified
8007 ** file by this or any other process. If such a lock is held, set *pResOut
8008 ** to a non-zero value otherwise *pResOut is set to zero. The return value
8009 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
8011 static int proxyCheckReservedLock(sqlite3_file
*id
, int *pResOut
) {
8012 unixFile
*pFile
= (unixFile
*)id
;
8013 int rc
= proxyTakeConch(pFile
);
8014 if( rc
==SQLITE_OK
){
8015 proxyLockingContext
*pCtx
= (proxyLockingContext
*)pFile
->lockingContext
;
8016 if( pCtx
->conchHeld
>0 ){
8017 unixFile
*proxy
= pCtx
->lockProxy
;
8018 return proxy
->pMethod
->xCheckReservedLock((sqlite3_file
*)proxy
, pResOut
);
8019 }else{ /* conchHeld < 0 is lockless */
8027 ** Lock the file with the lock specified by parameter eFileLock - one
8028 ** of the following:
8031 ** (2) RESERVED_LOCK
8033 ** (4) EXCLUSIVE_LOCK
8035 ** Sometimes when requesting one lock state, additional lock states
8036 ** are inserted in between. The locking might fail on one of the later
8037 ** transitions leaving the lock state different from what it started but
8038 ** still short of its goal. The following chart shows the allowed
8039 ** transitions and the inserted intermediate states:
8041 ** UNLOCKED -> SHARED
8042 ** SHARED -> RESERVED
8043 ** SHARED -> (PENDING) -> EXCLUSIVE
8044 ** RESERVED -> (PENDING) -> EXCLUSIVE
8045 ** PENDING -> EXCLUSIVE
8047 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
8048 ** routine to lower a locking level.
8050 static int proxyLock(sqlite3_file
*id
, int eFileLock
) {
8051 unixFile
*pFile
= (unixFile
*)id
;
8052 int rc
= proxyTakeConch(pFile
);
8053 if( rc
==SQLITE_OK
){
8054 proxyLockingContext
*pCtx
= (proxyLockingContext
*)pFile
->lockingContext
;
8055 if( pCtx
->conchHeld
>0 ){
8056 unixFile
*proxy
= pCtx
->lockProxy
;
8057 rc
= proxy
->pMethod
->xLock((sqlite3_file
*)proxy
, eFileLock
);
8058 pFile
->eFileLock
= proxy
->eFileLock
;
8060 /* conchHeld < 0 is lockless */
8068 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
8069 ** must be either NO_LOCK or SHARED_LOCK.
8071 ** If the locking level of the file descriptor is already at or below
8072 ** the requested locking level, this routine is a no-op.
8074 static int proxyUnlock(sqlite3_file
*id
, int eFileLock
) {
8075 unixFile
*pFile
= (unixFile
*)id
;
8076 int rc
= proxyTakeConch(pFile
);
8077 if( rc
==SQLITE_OK
){
8078 proxyLockingContext
*pCtx
= (proxyLockingContext
*)pFile
->lockingContext
;
8079 if( pCtx
->conchHeld
>0 ){
8080 unixFile
*proxy
= pCtx
->lockProxy
;
8081 rc
= proxy
->pMethod
->xUnlock((sqlite3_file
*)proxy
, eFileLock
);
8082 pFile
->eFileLock
= proxy
->eFileLock
;
8084 /* conchHeld < 0 is lockless */
8091 ** Close a file that uses proxy locks.
8093 static int proxyClose(sqlite3_file
*id
) {
8095 unixFile
*pFile
= (unixFile
*)id
;
8096 proxyLockingContext
*pCtx
= (proxyLockingContext
*)pFile
->lockingContext
;
8097 unixFile
*lockProxy
= pCtx
->lockProxy
;
8098 unixFile
*conchFile
= pCtx
->conchFile
;
8102 rc
= lockProxy
->pMethod
->xUnlock((sqlite3_file
*)lockProxy
, NO_LOCK
);
8104 rc
= lockProxy
->pMethod
->xClose((sqlite3_file
*)lockProxy
);
8106 sqlite3_free(lockProxy
);
8107 pCtx
->lockProxy
= 0;
8110 if( pCtx
->conchHeld
){
8111 rc
= proxyReleaseConch(pFile
);
8114 rc
= conchFile
->pMethod
->xClose((sqlite3_file
*)conchFile
);
8116 sqlite3_free(conchFile
);
8118 sqlite3DbFree(0, pCtx
->lockProxyPath
);
8119 sqlite3_free(pCtx
->conchFilePath
);
8120 sqlite3DbFree(0, pCtx
->dbPath
);
8121 /* restore the original locking context and pMethod then close it */
8122 pFile
->lockingContext
= pCtx
->oldLockingContext
;
8123 pFile
->pMethod
= pCtx
->pOldMethod
;
8125 return pFile
->pMethod
->xClose(id
);
8132 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
8134 ** The proxy locking style is intended for use with AFP filesystems.
8135 ** And since AFP is only supported on MacOSX, the proxy locking is also
8136 ** restricted to MacOSX.
8139 ******************* End of the proxy lock implementation **********************
8140 ******************************************************************************/
8143 ** Initialize the operating system interface.
8145 ** This routine registers all VFS implementations for unix-like operating
8146 ** systems. This routine, and the sqlite3_os_end() routine that follows,
8147 ** should be the only routines in this file that are visible from other
8150 ** This routine is called once during SQLite initialization and by a
8151 ** single thread. The memory allocation and mutex subsystems have not
8152 ** necessarily been initialized when this routine is called, and so they
8153 ** should not be used.
8155 int sqlite3_os_init(void){
8157 ** The following macro defines an initializer for an sqlite3_vfs object.
8158 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
8159 ** to the "finder" function. (pAppData is a pointer to a pointer because
8160 ** silly C90 rules prohibit a void* from being cast to a function pointer
8161 ** and so we have to go through the intermediate pointer to avoid problems
8162 ** when compiling with -pedantic-errors on GCC.)
8164 ** The FINDER parameter to this macro is the name of the pointer to the
8165 ** finder-function. The finder-function returns a pointer to the
8166 ** sqlite_io_methods object that implements the desired locking
8167 ** behaviors. See the division above that contains the IOMETHODS
8168 ** macro for addition information on finder-functions.
8170 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
8171 ** object. But the "autolockIoFinder" available on MacOSX does a little
8172 ** more than that; it looks at the filesystem type that hosts the
8173 ** database file and tries to choose an locking method appropriate for
8174 ** that filesystem time.
8176 #define UNIXVFS(VFSNAME, FINDER) { \
8178 sizeof(unixFile), /* szOsFile */ \
8179 MAX_PATHNAME, /* mxPathname */ \
8181 VFSNAME, /* zName */ \
8182 (void*)&FINDER, /* pAppData */ \
8183 unixOpen, /* xOpen */ \
8184 unixDelete, /* xDelete */ \
8185 unixAccess, /* xAccess */ \
8186 unixFullPathname, /* xFullPathname */ \
8187 unixDlOpen, /* xDlOpen */ \
8188 unixDlError, /* xDlError */ \
8189 unixDlSym, /* xDlSym */ \
8190 unixDlClose, /* xDlClose */ \
8191 unixRandomness, /* xRandomness */ \
8192 unixSleep, /* xSleep */ \
8193 unixCurrentTime, /* xCurrentTime */ \
8194 unixGetLastError, /* xGetLastError */ \
8195 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
8196 unixSetSystemCall, /* xSetSystemCall */ \
8197 unixGetSystemCall, /* xGetSystemCall */ \
8198 unixNextSystemCall, /* xNextSystemCall */ \
8202 ** All default VFSes for unix are contained in the following array.
8204 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
8205 ** by the SQLite core when the VFS is registered. So the following
8206 ** array cannot be const.
8208 static sqlite3_vfs aVfs
[] = {
8209 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
8210 UNIXVFS("unix", autolockIoFinder
),
8212 UNIXVFS("unix", vxworksIoFinder
),
8214 UNIXVFS("unix", posixIoFinder
),
8216 UNIXVFS("unix-none", nolockIoFinder
),
8217 UNIXVFS("unix-dotfile", dotlockIoFinder
),
8218 UNIXVFS("unix-excl", posixIoFinder
),
8220 UNIXVFS("unix-namedsem", semIoFinder
),
8222 #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
8223 UNIXVFS("unix-posix", posixIoFinder
),
8225 #if SQLITE_ENABLE_LOCKING_STYLE
8226 UNIXVFS("unix-flock", flockIoFinder
),
8228 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
8229 UNIXVFS("unix-afp", afpIoFinder
),
8230 UNIXVFS("unix-nfs", nfsIoFinder
),
8231 UNIXVFS("unix-proxy", proxyIoFinder
),
8234 unsigned int i
; /* Loop counter */
8236 /* Double-check that the aSyscall[] array has been constructed
8237 ** correctly. See ticket [bb3a86e890c8e96ab] */
8238 assert( ArraySize(aSyscall
)==29 );
8240 /* Register all VFSes defined in the aVfs[] array */
8241 for(i
=0; i
<(sizeof(aVfs
)/sizeof(sqlite3_vfs
)); i
++){
8242 #ifdef SQLITE_DEFAULT_UNIX_VFS
8243 sqlite3_vfs_register(&aVfs
[i
],
8244 0==strcmp(aVfs
[i
].zName
,SQLITE_DEFAULT_UNIX_VFS
));
8246 sqlite3_vfs_register(&aVfs
[i
], i
==0);
8249 #ifdef SQLITE_OS_KV_OPTIONAL
8252 unixBigLock
= sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1
);
8254 #ifndef SQLITE_OMIT_WAL
8255 /* Validate lock assumptions */
8256 assert( SQLITE_SHM_NLOCK
==8 ); /* Number of available locks */
8257 assert( UNIX_SHM_BASE
==120 ); /* Start of locking area */
8259 ** WRITE UNIX_SHM_BASE 120
8260 ** CKPT UNIX_SHM_BASE+1 121
8261 ** RECOVER UNIX_SHM_BASE+2 122
8262 ** READ-0 UNIX_SHM_BASE+3 123
8263 ** READ-1 UNIX_SHM_BASE+4 124
8264 ** READ-2 UNIX_SHM_BASE+5 125
8265 ** READ-3 UNIX_SHM_BASE+6 126
8266 ** READ-4 UNIX_SHM_BASE+7 127
8267 ** DMS UNIX_SHM_BASE+8 128
8269 assert( UNIX_SHM_DMS
==128 ); /* Byte offset of the deadman-switch */
8272 /* Initialize temp file dir array. */
8279 ** Shutdown the operating system interface.
8281 ** Some operating systems might need to do some cleanup in this routine,
8282 ** to release dynamically allocated objects. But not on unix.
8283 ** This routine is a no-op for unix.
8285 int sqlite3_os_end(void){
8290 #endif /* SQLITE_OS_UNIX */