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 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1302 strerror_r(iErrno
, aErr
, sizeof(aErr
)-1);
1304 #elif SQLITE_THREADSAFE
1305 /* This is a threadsafe build, but strerror_r() is not available. */
1308 /* Non-threadsafe build, use strerror(). */
1309 zErr
= strerror(iErrno
);
1312 if( zPath
==0 ) zPath
= "";
1313 sqlite3_log(errcode
,
1314 "os_unix.c:%d: (%d) %s(%s) - %s",
1315 iLine
, iErrno
, zFunc
, zPath
, zErr
1322 ** Close a file descriptor.
1324 ** We assume that close() almost always works, since it is only in a
1325 ** very sick application or on a very sick platform that it might fail.
1326 ** If it does fail, simply leak the file descriptor, but do log the
1329 ** Note that it is not safe to retry close() after EINTR since the
1330 ** file descriptor might have already been reused by another thread.
1331 ** So we don't even try to recover from an EINTR. Just log the error
1334 static void robust_close(unixFile
*pFile
, int h
, int lineno
){
1336 unixLogErrorAtLine(SQLITE_IOERR_CLOSE
, "close",
1337 pFile
? pFile
->zPath
: 0, lineno
);
1342 ** Set the pFile->lastErrno. Do this in a subroutine as that provides
1343 ** a convenient place to set a breakpoint.
1345 static void storeLastErrno(unixFile
*pFile
, int error
){
1346 pFile
->lastErrno
= error
;
1350 ** Close all file descriptors accumulated in the unixInodeInfo->pUnused list.
1352 static void closePendingFds(unixFile
*pFile
){
1353 unixInodeInfo
*pInode
= pFile
->pInode
;
1355 UnixUnusedFd
*pNext
;
1356 assert( unixFileMutexHeld(pFile
) );
1357 for(p
=pInode
->pUnused
; p
; p
=pNext
){
1359 robust_close(pFile
, p
->fd
, __LINE__
);
1362 pInode
->pUnused
= 0;
1366 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
1368 ** The global mutex must be held when this routine is called, but the mutex
1369 ** on the inode being deleted must NOT be held.
1371 static void releaseInodeInfo(unixFile
*pFile
){
1372 unixInodeInfo
*pInode
= pFile
->pInode
;
1373 assert( unixMutexHeld() );
1374 assert( unixFileMutexNotheld(pFile
) );
1375 if( ALWAYS(pInode
) ){
1377 if( pInode
->nRef
==0 ){
1378 assert( pInode
->pShmNode
==0 );
1379 sqlite3_mutex_enter(pInode
->pLockMutex
);
1380 closePendingFds(pFile
);
1381 sqlite3_mutex_leave(pInode
->pLockMutex
);
1382 if( pInode
->pPrev
){
1383 assert( pInode
->pPrev
->pNext
==pInode
);
1384 pInode
->pPrev
->pNext
= pInode
->pNext
;
1386 assert( inodeList
==pInode
);
1387 inodeList
= pInode
->pNext
;
1389 if( pInode
->pNext
){
1390 assert( pInode
->pNext
->pPrev
==pInode
);
1391 pInode
->pNext
->pPrev
= pInode
->pPrev
;
1393 sqlite3_mutex_free(pInode
->pLockMutex
);
1394 sqlite3_free(pInode
);
1400 ** Given a file descriptor, locate the unixInodeInfo object that
1401 ** describes that file descriptor. Create a new one if necessary. The
1402 ** return value might be uninitialized if an error occurs.
1404 ** The global mutex must held when calling this routine.
1406 ** Return an appropriate error code.
1408 static int findInodeInfo(
1409 unixFile
*pFile
, /* Unix file with file desc used in the key */
1410 unixInodeInfo
**ppInode
/* Return the unixInodeInfo object here */
1412 int rc
; /* System call return code */
1413 int fd
; /* The file descriptor for pFile */
1414 struct unixFileId fileId
; /* Lookup key for the unixInodeInfo */
1415 struct stat statbuf
; /* Low-level file information */
1416 unixInodeInfo
*pInode
= 0; /* Candidate unixInodeInfo object */
1418 assert( unixMutexHeld() );
1420 /* Get low-level information about the file that we can used to
1421 ** create a unique name for the file.
1424 rc
= osFstat(fd
, &statbuf
);
1426 storeLastErrno(pFile
, errno
);
1427 #if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
1428 if( pFile
->lastErrno
==EOVERFLOW
) return SQLITE_NOLFS
;
1430 return SQLITE_IOERR
;
1434 /* On OS X on an msdos filesystem, the inode number is reported
1435 ** incorrectly for zero-size files. See ticket #3260. To work
1436 ** around this problem (we consider it a bug in OS X, not SQLite)
1437 ** we always increase the file size to 1 by writing a single byte
1438 ** prior to accessing the inode number. The one byte written is
1439 ** an ASCII 'S' character which also happens to be the first byte
1440 ** in the header of every SQLite database. In this way, if there
1441 ** is a race condition such that another thread has already populated
1442 ** the first page of the database, no damage is done.
1444 if( statbuf
.st_size
==0 && (pFile
->fsFlags
& SQLITE_FSFLAGS_IS_MSDOS
)!=0 ){
1445 do{ rc
= osWrite(fd
, "S", 1); }while( rc
<0 && errno
==EINTR
);
1447 storeLastErrno(pFile
, errno
);
1448 return SQLITE_IOERR
;
1450 rc
= osFstat(fd
, &statbuf
);
1452 storeLastErrno(pFile
, errno
);
1453 return SQLITE_IOERR
;
1458 memset(&fileId
, 0, sizeof(fileId
));
1459 fileId
.dev
= statbuf
.st_dev
;
1461 fileId
.pId
= pFile
->pId
;
1463 fileId
.ino
= (u64
)statbuf
.st_ino
;
1465 assert( unixMutexHeld() );
1467 while( pInode
&& memcmp(&fileId
, &pInode
->fileId
, sizeof(fileId
)) ){
1468 pInode
= pInode
->pNext
;
1471 pInode
= sqlite3_malloc64( sizeof(*pInode
) );
1473 return SQLITE_NOMEM_BKPT
;
1475 memset(pInode
, 0, sizeof(*pInode
));
1476 memcpy(&pInode
->fileId
, &fileId
, sizeof(fileId
));
1477 if( sqlite3GlobalConfig
.bCoreMutex
){
1478 pInode
->pLockMutex
= sqlite3_mutex_alloc(SQLITE_MUTEX_FAST
);
1479 if( pInode
->pLockMutex
==0 ){
1480 sqlite3_free(pInode
);
1481 return SQLITE_NOMEM_BKPT
;
1485 assert( unixMutexHeld() );
1486 pInode
->pNext
= inodeList
;
1488 if( inodeList
) inodeList
->pPrev
= pInode
;
1498 ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1500 static int fileHasMoved(unixFile
*pFile
){
1502 return pFile
->pInode
!=0 && pFile
->pId
!=pFile
->pInode
->fileId
.pId
;
1505 return pFile
->pInode
!=0 &&
1506 (osStat(pFile
->zPath
, &buf
)!=0
1507 || (u64
)buf
.st_ino
!=pFile
->pInode
->fileId
.ino
);
1513 ** Check a unixFile that is a database. Verify the following:
1515 ** (1) There is exactly one hard link on the file
1516 ** (2) The file is not a symbolic link
1517 ** (3) The file has not been renamed or unlinked
1519 ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1521 static void verifyDbFile(unixFile
*pFile
){
1525 /* These verifications occurs for the main database only */
1526 if( pFile
->ctrlFlags
& UNIXFILE_NOLOCK
) return;
1528 rc
= osFstat(pFile
->h
, &buf
);
1530 sqlite3_log(SQLITE_WARNING
, "cannot fstat db file %s", pFile
->zPath
);
1533 if( buf
.st_nlink
==0 ){
1534 sqlite3_log(SQLITE_WARNING
, "file unlinked while open: %s", pFile
->zPath
);
1537 if( buf
.st_nlink
>1 ){
1538 sqlite3_log(SQLITE_WARNING
, "multiple links to file: %s", pFile
->zPath
);
1541 if( fileHasMoved(pFile
) ){
1542 sqlite3_log(SQLITE_WARNING
, "file renamed while open: %s", pFile
->zPath
);
1549 ** This routine checks if there is a RESERVED lock held on the specified
1550 ** file by this or any other process. If such a lock is held, set *pResOut
1551 ** to a non-zero value otherwise *pResOut is set to zero. The return value
1552 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1554 static int unixCheckReservedLock(sqlite3_file
*id
, int *pResOut
){
1557 unixFile
*pFile
= (unixFile
*)id
;
1559 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK
; );
1562 assert( pFile
->eFileLock
<=SHARED_LOCK
);
1563 sqlite3_mutex_enter(pFile
->pInode
->pLockMutex
);
1565 /* Check if a thread in this process holds such a lock */
1566 if( pFile
->pInode
->eFileLock
>SHARED_LOCK
){
1570 /* Otherwise see if some other process holds it.
1573 if( !reserved
&& !pFile
->pInode
->bProcessLock
){
1575 lock
.l_whence
= SEEK_SET
;
1576 lock
.l_start
= RESERVED_BYTE
;
1578 lock
.l_type
= F_WRLCK
;
1579 if( osFcntl(pFile
->h
, F_GETLK
, &lock
) ){
1580 rc
= SQLITE_IOERR_CHECKRESERVEDLOCK
;
1581 storeLastErrno(pFile
, errno
);
1582 } else if( lock
.l_type
!=F_UNLCK
){
1588 sqlite3_mutex_leave(pFile
->pInode
->pLockMutex
);
1589 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile
->h
, rc
, reserved
));
1591 *pResOut
= reserved
;
1595 /* Forward declaration*/
1596 static int unixSleep(sqlite3_vfs
*,int);
1599 ** Set a posix-advisory-lock.
1601 ** There are two versions of this routine. If compiled with
1602 ** SQLITE_ENABLE_SETLK_TIMEOUT then the routine has an extra parameter
1603 ** which is a pointer to a unixFile. If the unixFile->iBusyTimeout
1604 ** value is set, then it is the number of milliseconds to wait before
1605 ** failing the lock. The iBusyTimeout value is always reset back to
1606 ** zero on each call.
1608 ** If SQLITE_ENABLE_SETLK_TIMEOUT is not defined, then do a non-blocking
1609 ** attempt to set the lock.
1611 #ifndef SQLITE_ENABLE_SETLK_TIMEOUT
1612 # define osSetPosixAdvisoryLock(h,x,t) osFcntl(h,F_SETLK,x)
1614 static int osSetPosixAdvisoryLock(
1615 int h
, /* The file descriptor on which to take the lock */
1616 struct flock
*pLock
, /* The description of the lock */
1617 unixFile
*pFile
/* Structure holding timeout value */
1619 int tm
= pFile
->iBusyTimeout
;
1620 int rc
= osFcntl(h
,F_SETLK
,pLock
);
1621 while( rc
<0 && tm
>0 ){
1622 /* On systems that support some kind of blocking file lock with a timeout,
1623 ** make appropriate changes here to invoke that blocking file lock. On
1624 ** generic posix, however, there is no such API. So we simply try the
1625 ** lock once every millisecond until either the timeout expires, or until
1626 ** the lock is obtained. */
1628 rc
= osFcntl(h
,F_SETLK
,pLock
);
1633 #endif /* SQLITE_ENABLE_SETLK_TIMEOUT */
1637 ** Attempt to set a system-lock on the file pFile. The lock is
1638 ** described by pLock.
1640 ** If the pFile was opened read/write from unix-excl, then the only lock
1641 ** ever obtained is an exclusive lock, and it is obtained exactly once
1642 ** the first time any lock is attempted. All subsequent system locking
1643 ** operations become no-ops. Locking operations still happen internally,
1644 ** in order to coordinate access between separate database connections
1645 ** within this process, but all of that is handled in memory and the
1646 ** operating system does not participate.
1648 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1649 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1650 ** and is read-only.
1652 ** Zero is returned if the call completes successfully, or -1 if a call
1653 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
1655 static int unixFileLock(unixFile
*pFile
, struct flock
*pLock
){
1657 unixInodeInfo
*pInode
= pFile
->pInode
;
1658 assert( pInode
!=0 );
1659 assert( sqlite3_mutex_held(pInode
->pLockMutex
) );
1660 if( (pFile
->ctrlFlags
& (UNIXFILE_EXCL
|UNIXFILE_RDONLY
))==UNIXFILE_EXCL
){
1661 if( pInode
->bProcessLock
==0 ){
1663 assert( pInode
->nLock
==0 );
1664 lock
.l_whence
= SEEK_SET
;
1665 lock
.l_start
= SHARED_FIRST
;
1666 lock
.l_len
= SHARED_SIZE
;
1667 lock
.l_type
= F_WRLCK
;
1668 rc
= osSetPosixAdvisoryLock(pFile
->h
, &lock
, pFile
);
1669 if( rc
<0 ) return rc
;
1670 pInode
->bProcessLock
= 1;
1676 rc
= osSetPosixAdvisoryLock(pFile
->h
, pLock
, pFile
);
1682 ** Lock the file with the lock specified by parameter eFileLock - one
1683 ** of the following:
1686 ** (2) RESERVED_LOCK
1688 ** (4) EXCLUSIVE_LOCK
1690 ** Sometimes when requesting one lock state, additional lock states
1691 ** are inserted in between. The locking might fail on one of the later
1692 ** transitions leaving the lock state different from what it started but
1693 ** still short of its goal. The following chart shows the allowed
1694 ** transitions and the inserted intermediate states:
1696 ** UNLOCKED -> SHARED
1697 ** SHARED -> RESERVED
1698 ** SHARED -> EXCLUSIVE
1699 ** RESERVED -> (PENDING) -> EXCLUSIVE
1700 ** PENDING -> EXCLUSIVE
1702 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
1703 ** routine to lower a locking level.
1705 static int unixLock(sqlite3_file
*id
, int eFileLock
){
1706 /* The following describes the implementation of the various locks and
1707 ** lock transitions in terms of the POSIX advisory shared and exclusive
1708 ** lock primitives (called read-locks and write-locks below, to avoid
1709 ** confusion with SQLite lock names). The algorithms are complicated
1710 ** slightly in order to be compatible with Windows95 systems simultaneously
1711 ** accessing the same database file, in case that is ever required.
1713 ** Symbols defined in os.h identify the 'pending byte' and the 'reserved
1714 ** byte', each single bytes at well known offsets, and the 'shared byte
1715 ** range', a range of 510 bytes at a well known offset.
1717 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1718 ** byte'. If this is successful, 'shared byte range' is read-locked
1719 ** and the lock on the 'pending byte' released. (Legacy note: When
1720 ** SQLite was first developed, Windows95 systems were still very common,
1721 ** and Windows95 lacks a shared-lock capability. So on Windows95, a
1722 ** single randomly selected by from the 'shared byte range' is locked.
1723 ** Windows95 is now pretty much extinct, but this work-around for the
1724 ** lack of shared-locks on Windows95 lives on, for backwards
1727 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1728 ** A RESERVED lock is implemented by grabbing a write-lock on the
1731 ** An EXCLUSIVE lock may only be requested after either a SHARED or
1732 ** RESERVED lock is held. An EXCLUSIVE lock is implemented by obtaining
1733 ** a write-lock on the entire 'shared byte range'. Since all other locks
1734 ** require a read-lock on one of the bytes within this range, this ensures
1735 ** that no other locks are held on the database.
1737 ** If a process that holds a RESERVED lock requests an EXCLUSIVE, then
1738 ** a PENDING lock is obtained first. A PENDING lock is implemented by
1739 ** obtaining a write-lock on the 'pending byte'. This ensures that no new
1740 ** SHARED locks can be obtained, but existing SHARED locks are allowed to
1741 ** persist. If the call to this function fails to obtain the EXCLUSIVE
1742 ** lock in this case, it holds the PENDING lock instead. The client may
1743 ** then re-attempt the EXCLUSIVE lock later on, after existing SHARED
1744 ** locks have cleared.
1747 unixFile
*pFile
= (unixFile
*)id
;
1748 unixInodeInfo
*pInode
;
1753 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile
->h
,
1754 azFileLock(eFileLock
), azFileLock(pFile
->eFileLock
),
1755 azFileLock(pFile
->pInode
->eFileLock
), pFile
->pInode
->nShared
,
1758 /* If there is already a lock of this type or more restrictive on the
1759 ** unixFile, do nothing. Don't use the end_lock: exit path, as
1760 ** unixEnterMutex() hasn't been called yet.
1762 if( pFile
->eFileLock
>=eFileLock
){
1763 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile
->h
,
1764 azFileLock(eFileLock
)));
1768 /* Make sure the locking sequence is correct.
1769 ** (1) We never move from unlocked to anything higher than shared lock.
1770 ** (2) SQLite never explicitly requests a pending lock.
1771 ** (3) A shared lock is always held when a reserve lock is requested.
1773 assert( pFile
->eFileLock
!=NO_LOCK
|| eFileLock
==SHARED_LOCK
);
1774 assert( eFileLock
!=PENDING_LOCK
);
1775 assert( eFileLock
!=RESERVED_LOCK
|| pFile
->eFileLock
==SHARED_LOCK
);
1777 /* This mutex is needed because pFile->pInode is shared across threads
1779 pInode
= pFile
->pInode
;
1780 sqlite3_mutex_enter(pInode
->pLockMutex
);
1782 /* If some thread using this PID has a lock via a different unixFile*
1783 ** handle that precludes the requested lock, return BUSY.
1785 if( (pFile
->eFileLock
!=pInode
->eFileLock
&&
1786 (pInode
->eFileLock
>=PENDING_LOCK
|| eFileLock
>SHARED_LOCK
))
1792 /* If a SHARED lock is requested, and some thread using this PID already
1793 ** has a SHARED or RESERVED lock, then increment reference counts and
1794 ** return SQLITE_OK.
1796 if( eFileLock
==SHARED_LOCK
&&
1797 (pInode
->eFileLock
==SHARED_LOCK
|| pInode
->eFileLock
==RESERVED_LOCK
) ){
1798 assert( eFileLock
==SHARED_LOCK
);
1799 assert( pFile
->eFileLock
==0 );
1800 assert( pInode
->nShared
>0 );
1801 pFile
->eFileLock
= SHARED_LOCK
;
1808 /* A PENDING lock is needed before acquiring a SHARED lock and before
1809 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1813 lock
.l_whence
= SEEK_SET
;
1814 if( eFileLock
==SHARED_LOCK
1815 || (eFileLock
==EXCLUSIVE_LOCK
&& pFile
->eFileLock
==RESERVED_LOCK
)
1817 lock
.l_type
= (eFileLock
==SHARED_LOCK
?F_RDLCK
:F_WRLCK
);
1818 lock
.l_start
= PENDING_BYTE
;
1819 if( unixFileLock(pFile
, &lock
) ){
1821 rc
= sqliteErrorFromPosixError(tErrno
, SQLITE_IOERR_LOCK
);
1822 if( rc
!=SQLITE_BUSY
){
1823 storeLastErrno(pFile
, tErrno
);
1826 }else if( eFileLock
==EXCLUSIVE_LOCK
){
1827 pFile
->eFileLock
= PENDING_LOCK
;
1828 pInode
->eFileLock
= PENDING_LOCK
;
1833 /* If control gets to this point, then actually go ahead and make
1834 ** operating system calls for the specified lock.
1836 if( eFileLock
==SHARED_LOCK
){
1837 assert( pInode
->nShared
==0 );
1838 assert( pInode
->eFileLock
==0 );
1839 assert( rc
==SQLITE_OK
);
1841 /* Now get the read-lock */
1842 lock
.l_start
= SHARED_FIRST
;
1843 lock
.l_len
= SHARED_SIZE
;
1844 if( unixFileLock(pFile
, &lock
) ){
1846 rc
= sqliteErrorFromPosixError(tErrno
, SQLITE_IOERR_LOCK
);
1849 /* Drop the temporary PENDING lock */
1850 lock
.l_start
= PENDING_BYTE
;
1852 lock
.l_type
= F_UNLCK
;
1853 if( unixFileLock(pFile
, &lock
) && rc
==SQLITE_OK
){
1854 /* This could happen with a network mount */
1856 rc
= SQLITE_IOERR_UNLOCK
;
1860 if( rc
!=SQLITE_BUSY
){
1861 storeLastErrno(pFile
, tErrno
);
1865 pFile
->eFileLock
= SHARED_LOCK
;
1867 pInode
->nShared
= 1;
1869 }else if( eFileLock
==EXCLUSIVE_LOCK
&& pInode
->nShared
>1 ){
1870 /* We are trying for an exclusive lock but another thread in this
1871 ** same process is still holding a shared lock. */
1874 /* The request was for a RESERVED or EXCLUSIVE lock. It is
1875 ** assumed that there is a SHARED or greater lock on the file
1878 assert( 0!=pFile
->eFileLock
);
1879 lock
.l_type
= F_WRLCK
;
1881 assert( eFileLock
==RESERVED_LOCK
|| eFileLock
==EXCLUSIVE_LOCK
);
1882 if( eFileLock
==RESERVED_LOCK
){
1883 lock
.l_start
= RESERVED_BYTE
;
1886 lock
.l_start
= SHARED_FIRST
;
1887 lock
.l_len
= SHARED_SIZE
;
1890 if( unixFileLock(pFile
, &lock
) ){
1892 rc
= sqliteErrorFromPosixError(tErrno
, SQLITE_IOERR_LOCK
);
1893 if( rc
!=SQLITE_BUSY
){
1894 storeLastErrno(pFile
, tErrno
);
1901 /* Set up the transaction-counter change checking flags when
1902 ** transitioning from a SHARED to a RESERVED lock. The change
1903 ** from SHARED to RESERVED marks the beginning of a normal
1904 ** write operation (not a hot journal rollback).
1907 && pFile
->eFileLock
<=SHARED_LOCK
1908 && eFileLock
==RESERVED_LOCK
1910 pFile
->transCntrChng
= 0;
1911 pFile
->dbUpdate
= 0;
1912 pFile
->inNormalWrite
= 1;
1916 if( rc
==SQLITE_OK
){
1917 pFile
->eFileLock
= eFileLock
;
1918 pInode
->eFileLock
= eFileLock
;
1922 sqlite3_mutex_leave(pInode
->pLockMutex
);
1923 OSTRACE(("LOCK %d %s %s (unix)\n", pFile
->h
, azFileLock(eFileLock
),
1924 rc
==SQLITE_OK
? "ok" : "failed"));
1929 ** Add the file descriptor used by file handle pFile to the corresponding
1932 static void setPendingFd(unixFile
*pFile
){
1933 unixInodeInfo
*pInode
= pFile
->pInode
;
1934 UnixUnusedFd
*p
= pFile
->pPreallocatedUnused
;
1935 assert( unixFileMutexHeld(pFile
) );
1936 p
->pNext
= pInode
->pUnused
;
1937 pInode
->pUnused
= p
;
1939 pFile
->pPreallocatedUnused
= 0;
1943 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
1944 ** must be either NO_LOCK or SHARED_LOCK.
1946 ** If the locking level of the file descriptor is already at or below
1947 ** the requested locking level, this routine is a no-op.
1949 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1950 ** the byte range is divided into 2 parts and the first part is unlocked then
1951 ** set to a read lock, then the other part is simply unlocked. This works
1952 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1953 ** remove the write lock on a region when a read lock is set.
1955 static int posixUnlock(sqlite3_file
*id
, int eFileLock
, int handleNFSUnlock
){
1956 unixFile
*pFile
= (unixFile
*)id
;
1957 unixInodeInfo
*pInode
;
1962 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile
->h
, eFileLock
,
1963 pFile
->eFileLock
, pFile
->pInode
->eFileLock
, pFile
->pInode
->nShared
,
1966 assert( eFileLock
<=SHARED_LOCK
);
1967 if( pFile
->eFileLock
<=eFileLock
){
1970 pInode
= pFile
->pInode
;
1971 sqlite3_mutex_enter(pInode
->pLockMutex
);
1972 assert( pInode
->nShared
!=0 );
1973 if( pFile
->eFileLock
>SHARED_LOCK
){
1974 assert( pInode
->eFileLock
==pFile
->eFileLock
);
1977 /* When reducing a lock such that other processes can start
1978 ** reading the database file again, make sure that the
1979 ** transaction counter was updated if any part of the database
1980 ** file changed. If the transaction counter is not updated,
1981 ** other connections to the same file might not realize that
1982 ** the file has changed and hence might not know to flush their
1983 ** cache. The use of a stale cache can lead to database corruption.
1985 pFile
->inNormalWrite
= 0;
1988 /* downgrading to a shared lock on NFS involves clearing the write lock
1989 ** before establishing the readlock - to avoid a race condition we downgrade
1990 ** the lock in 2 blocks, so that part of the range will be covered by a
1991 ** write lock until the rest is covered by a read lock:
1997 if( eFileLock
==SHARED_LOCK
){
1998 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
1999 (void)handleNFSUnlock
;
2000 assert( handleNFSUnlock
==0 );
2002 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2003 if( handleNFSUnlock
){
2004 int tErrno
; /* Error code from system call errors */
2005 off_t divSize
= SHARED_SIZE
- 1;
2007 lock
.l_type
= F_UNLCK
;
2008 lock
.l_whence
= SEEK_SET
;
2009 lock
.l_start
= SHARED_FIRST
;
2010 lock
.l_len
= divSize
;
2011 if( unixFileLock(pFile
, &lock
)==(-1) ){
2013 rc
= SQLITE_IOERR_UNLOCK
;
2014 storeLastErrno(pFile
, tErrno
);
2017 lock
.l_type
= F_RDLCK
;
2018 lock
.l_whence
= SEEK_SET
;
2019 lock
.l_start
= SHARED_FIRST
;
2020 lock
.l_len
= divSize
;
2021 if( unixFileLock(pFile
, &lock
)==(-1) ){
2023 rc
= sqliteErrorFromPosixError(tErrno
, SQLITE_IOERR_RDLOCK
);
2024 if( IS_LOCK_ERROR(rc
) ){
2025 storeLastErrno(pFile
, tErrno
);
2029 lock
.l_type
= F_UNLCK
;
2030 lock
.l_whence
= SEEK_SET
;
2031 lock
.l_start
= SHARED_FIRST
+divSize
;
2032 lock
.l_len
= SHARED_SIZE
-divSize
;
2033 if( unixFileLock(pFile
, &lock
)==(-1) ){
2035 rc
= SQLITE_IOERR_UNLOCK
;
2036 storeLastErrno(pFile
, tErrno
);
2040 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2042 lock
.l_type
= F_RDLCK
;
2043 lock
.l_whence
= SEEK_SET
;
2044 lock
.l_start
= SHARED_FIRST
;
2045 lock
.l_len
= SHARED_SIZE
;
2046 if( unixFileLock(pFile
, &lock
) ){
2047 /* In theory, the call to unixFileLock() cannot fail because another
2048 ** process is holding an incompatible lock. If it does, this
2049 ** indicates that the other process is not following the locking
2050 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
2051 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
2052 ** an assert to fail). */
2053 rc
= SQLITE_IOERR_RDLOCK
;
2054 storeLastErrno(pFile
, errno
);
2059 lock
.l_type
= F_UNLCK
;
2060 lock
.l_whence
= SEEK_SET
;
2061 lock
.l_start
= PENDING_BYTE
;
2062 lock
.l_len
= 2L; assert( PENDING_BYTE
+1==RESERVED_BYTE
);
2063 if( unixFileLock(pFile
, &lock
)==0 ){
2064 pInode
->eFileLock
= SHARED_LOCK
;
2066 rc
= SQLITE_IOERR_UNLOCK
;
2067 storeLastErrno(pFile
, errno
);
2071 if( eFileLock
==NO_LOCK
){
2072 /* Decrement the shared lock counter. Release the lock using an
2073 ** OS call only when all threads in this same process have released
2077 if( pInode
->nShared
==0 ){
2078 lock
.l_type
= F_UNLCK
;
2079 lock
.l_whence
= SEEK_SET
;
2080 lock
.l_start
= lock
.l_len
= 0L;
2081 if( unixFileLock(pFile
, &lock
)==0 ){
2082 pInode
->eFileLock
= NO_LOCK
;
2084 rc
= SQLITE_IOERR_UNLOCK
;
2085 storeLastErrno(pFile
, errno
);
2086 pInode
->eFileLock
= NO_LOCK
;
2087 pFile
->eFileLock
= NO_LOCK
;
2091 /* Decrement the count of locks against this same file. When the
2092 ** count reaches zero, close any other file descriptors whose close
2093 ** was deferred because of outstanding locks.
2096 assert( pInode
->nLock
>=0 );
2097 if( pInode
->nLock
==0 ) closePendingFds(pFile
);
2101 sqlite3_mutex_leave(pInode
->pLockMutex
);
2102 if( rc
==SQLITE_OK
){
2103 pFile
->eFileLock
= eFileLock
;
2109 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
2110 ** must be either NO_LOCK or SHARED_LOCK.
2112 ** If the locking level of the file descriptor is already at or below
2113 ** the requested locking level, this routine is a no-op.
2115 static int unixUnlock(sqlite3_file
*id
, int eFileLock
){
2116 #if SQLITE_MAX_MMAP_SIZE>0
2117 assert( eFileLock
==SHARED_LOCK
|| ((unixFile
*)id
)->nFetchOut
==0 );
2119 return posixUnlock(id
, eFileLock
, 0);
2122 #if SQLITE_MAX_MMAP_SIZE>0
2123 static int unixMapfile(unixFile
*pFd
, i64 nByte
);
2124 static void unixUnmapfile(unixFile
*pFd
);
2128 ** This function performs the parts of the "close file" operation
2129 ** common to all locking schemes. It closes the directory and file
2130 ** handles, if they are valid, and sets all fields of the unixFile
2133 ** It is *not* necessary to hold the mutex when this routine is called,
2134 ** even on VxWorks. A mutex will be acquired on VxWorks by the
2135 ** vxworksReleaseFileId() routine.
2137 static int closeUnixFile(sqlite3_file
*id
){
2138 unixFile
*pFile
= (unixFile
*)id
;
2139 #if SQLITE_MAX_MMAP_SIZE>0
2140 unixUnmapfile(pFile
);
2143 robust_close(pFile
, pFile
->h
, __LINE__
);
2148 if( pFile
->ctrlFlags
& UNIXFILE_DELETE
){
2149 osUnlink(pFile
->pId
->zCanonicalName
);
2151 vxworksReleaseFileId(pFile
->pId
);
2155 #ifdef SQLITE_UNLINK_AFTER_CLOSE
2156 if( pFile
->ctrlFlags
& UNIXFILE_DELETE
){
2157 osUnlink(pFile
->zPath
);
2158 sqlite3_free(*(char**)&pFile
->zPath
);
2162 OSTRACE(("CLOSE %-3d\n", pFile
->h
));
2164 sqlite3_free(pFile
->pPreallocatedUnused
);
2165 memset(pFile
, 0, sizeof(unixFile
));
2172 static int unixClose(sqlite3_file
*id
){
2174 unixFile
*pFile
= (unixFile
*)id
;
2175 unixInodeInfo
*pInode
= pFile
->pInode
;
2177 assert( pInode
!=0 );
2178 verifyDbFile(pFile
);
2179 unixUnlock(id
, NO_LOCK
);
2180 assert( unixFileMutexNotheld(pFile
) );
2183 /* unixFile.pInode is always valid here. Otherwise, a different close
2184 ** routine (e.g. nolockClose()) would be called instead.
2186 assert( pFile
->pInode
->nLock
>0 || pFile
->pInode
->bProcessLock
==0 );
2187 sqlite3_mutex_enter(pInode
->pLockMutex
);
2188 if( pInode
->nLock
){
2189 /* If there are outstanding locks, do not actually close the file just
2190 ** yet because that would clear those locks. Instead, add the file
2191 ** descriptor to pInode->pUnused list. It will be automatically closed
2192 ** when the last lock is cleared.
2194 setPendingFd(pFile
);
2196 sqlite3_mutex_leave(pInode
->pLockMutex
);
2197 releaseInodeInfo(pFile
);
2198 assert( pFile
->pShm
==0 );
2199 rc
= closeUnixFile(id
);
2204 /************** End of the posix advisory lock implementation *****************
2205 ******************************************************************************/
2207 /******************************************************************************
2208 ****************************** No-op Locking **********************************
2210 ** Of the various locking implementations available, this is by far the
2211 ** simplest: locking is ignored. No attempt is made to lock the database
2212 ** file for reading or writing.
2214 ** This locking mode is appropriate for use on read-only databases
2215 ** (ex: databases that are burned into CD-ROM, for example.) It can
2216 ** also be used if the application employs some external mechanism to
2217 ** prevent simultaneous access of the same database by two or more
2218 ** database connections. But there is a serious risk of database
2219 ** corruption if this locking mode is used in situations where multiple
2220 ** database connections are accessing the same database file at the same
2221 ** time and one or more of those connections are writing.
2224 static int nolockCheckReservedLock(sqlite3_file
*NotUsed
, int *pResOut
){
2225 UNUSED_PARAMETER(NotUsed
);
2229 static int nolockLock(sqlite3_file
*NotUsed
, int NotUsed2
){
2230 UNUSED_PARAMETER2(NotUsed
, NotUsed2
);
2233 static int nolockUnlock(sqlite3_file
*NotUsed
, int NotUsed2
){
2234 UNUSED_PARAMETER2(NotUsed
, NotUsed2
);
2241 static int nolockClose(sqlite3_file
*id
) {
2242 return closeUnixFile(id
);
2245 /******************* End of the no-op lock implementation *********************
2246 ******************************************************************************/
2248 /******************************************************************************
2249 ************************* Begin dot-file Locking ******************************
2251 ** The dotfile locking implementation uses the existence of separate lock
2252 ** files (really a directory) to control access to the database. This works
2253 ** on just about every filesystem imaginable. But there are serious downsides:
2255 ** (1) There is zero concurrency. A single reader blocks all other
2256 ** connections from reading or writing the database.
2258 ** (2) An application crash or power loss can leave stale lock files
2259 ** sitting around that need to be cleared manually.
2261 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
2262 ** other locking strategy is available.
2264 ** Dotfile locking works by creating a subdirectory in the same directory as
2265 ** the database and with the same name but with a ".lock" extension added.
2266 ** The existence of a lock directory implies an EXCLUSIVE lock. All other
2267 ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
2271 ** The file suffix added to the data base filename in order to create the
2274 #define DOTLOCK_SUFFIX ".lock"
2277 ** This routine checks if there is a RESERVED lock held on the specified
2278 ** file by this or any other process. If such a lock is held, set *pResOut
2279 ** to a non-zero value otherwise *pResOut is set to zero. The return value
2280 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2282 ** In dotfile locking, either a lock exists or it does not. So in this
2283 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
2284 ** is held on the file and false if the file is unlocked.
2286 static int dotlockCheckReservedLock(sqlite3_file
*id
, int *pResOut
) {
2289 unixFile
*pFile
= (unixFile
*)id
;
2291 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK
; );
2294 reserved
= osAccess((const char*)pFile
->lockingContext
, 0)==0;
2295 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile
->h
, rc
, reserved
));
2296 *pResOut
= reserved
;
2301 ** Lock the file with the lock specified by parameter eFileLock - one
2302 ** of the following:
2305 ** (2) RESERVED_LOCK
2307 ** (4) EXCLUSIVE_LOCK
2309 ** Sometimes when requesting one lock state, additional lock states
2310 ** are inserted in between. The locking might fail on one of the later
2311 ** transitions leaving the lock state different from what it started but
2312 ** still short of its goal. The following chart shows the allowed
2313 ** transitions and the inserted intermediate states:
2315 ** UNLOCKED -> SHARED
2316 ** SHARED -> RESERVED
2317 ** SHARED -> (PENDING) -> EXCLUSIVE
2318 ** RESERVED -> (PENDING) -> EXCLUSIVE
2319 ** PENDING -> EXCLUSIVE
2321 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
2322 ** routine to lower a locking level.
2324 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
2325 ** But we track the other locking levels internally.
2327 static int dotlockLock(sqlite3_file
*id
, int eFileLock
) {
2328 unixFile
*pFile
= (unixFile
*)id
;
2329 char *zLockFile
= (char *)pFile
->lockingContext
;
2333 /* If we have any lock, then the lock file already exists. All we have
2334 ** to do is adjust our internal record of the lock level.
2336 if( pFile
->eFileLock
> NO_LOCK
){
2337 pFile
->eFileLock
= eFileLock
;
2338 /* Always update the timestamp on the old file */
2340 utime(zLockFile
, NULL
);
2342 utimes(zLockFile
, NULL
);
2347 /* grab an exclusive lock */
2348 rc
= osMkdir(zLockFile
, 0777);
2350 /* failed to open/create the lock directory */
2352 if( EEXIST
== tErrno
){
2355 rc
= sqliteErrorFromPosixError(tErrno
, SQLITE_IOERR_LOCK
);
2356 if( rc
!=SQLITE_BUSY
){
2357 storeLastErrno(pFile
, tErrno
);
2363 /* got it, set the type and return ok */
2364 pFile
->eFileLock
= eFileLock
;
2369 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
2370 ** must be either NO_LOCK or SHARED_LOCK.
2372 ** If the locking level of the file descriptor is already at or below
2373 ** the requested locking level, this routine is a no-op.
2375 ** When the locking level reaches NO_LOCK, delete the lock file.
2377 static int dotlockUnlock(sqlite3_file
*id
, int eFileLock
) {
2378 unixFile
*pFile
= (unixFile
*)id
;
2379 char *zLockFile
= (char *)pFile
->lockingContext
;
2383 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile
->h
, eFileLock
,
2384 pFile
->eFileLock
, osGetpid(0)));
2385 assert( eFileLock
<=SHARED_LOCK
);
2387 /* no-op if possible */
2388 if( pFile
->eFileLock
==eFileLock
){
2392 /* To downgrade to shared, simply update our internal notion of the
2393 ** lock state. No need to mess with the file on disk.
2395 if( eFileLock
==SHARED_LOCK
){
2396 pFile
->eFileLock
= SHARED_LOCK
;
2400 /* To fully unlock the database, delete the lock file */
2401 assert( eFileLock
==NO_LOCK
);
2402 rc
= osRmdir(zLockFile
);
2405 if( tErrno
==ENOENT
){
2408 rc
= SQLITE_IOERR_UNLOCK
;
2409 storeLastErrno(pFile
, tErrno
);
2413 pFile
->eFileLock
= NO_LOCK
;
2418 ** Close a file. Make sure the lock has been released before closing.
2420 static int dotlockClose(sqlite3_file
*id
) {
2421 unixFile
*pFile
= (unixFile
*)id
;
2423 dotlockUnlock(id
, NO_LOCK
);
2424 sqlite3_free(pFile
->lockingContext
);
2425 return closeUnixFile(id
);
2427 /****************** End of the dot-file lock implementation *******************
2428 ******************************************************************************/
2430 /******************************************************************************
2431 ************************** Begin flock Locking ********************************
2433 ** Use the flock() system call to do file locking.
2435 ** flock() locking is like dot-file locking in that the various
2436 ** fine-grain locking levels supported by SQLite are collapsed into
2437 ** a single exclusive lock. In other words, SHARED, RESERVED, and
2438 ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2439 ** still works when you do this, but concurrency is reduced since
2440 ** only a single process can be reading the database at a time.
2442 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
2444 #if SQLITE_ENABLE_LOCKING_STYLE
2447 ** Retry flock() calls that fail with EINTR
2450 static int robust_flock(int fd
, int op
){
2452 do{ rc
= flock(fd
,op
); }while( rc
<0 && errno
==EINTR
);
2456 # define robust_flock(a,b) flock(a,b)
2461 ** This routine checks if there is a RESERVED lock held on the specified
2462 ** file by this or any other process. If such a lock is held, set *pResOut
2463 ** to a non-zero value otherwise *pResOut is set to zero. The return value
2464 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2466 static int flockCheckReservedLock(sqlite3_file
*id
, int *pResOut
){
2469 unixFile
*pFile
= (unixFile
*)id
;
2471 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK
; );
2475 /* Check if a thread in this process holds such a lock */
2476 if( pFile
->eFileLock
>SHARED_LOCK
){
2480 /* Otherwise see if some other process holds it. */
2482 /* attempt to get the lock */
2483 int lrc
= robust_flock(pFile
->h
, LOCK_EX
| LOCK_NB
);
2485 /* got the lock, unlock it */
2486 lrc
= robust_flock(pFile
->h
, LOCK_UN
);
2489 /* unlock failed with an error */
2490 lrc
= SQLITE_IOERR_UNLOCK
;
2491 storeLastErrno(pFile
, tErrno
);
2497 /* someone else might have it reserved */
2498 lrc
= sqliteErrorFromPosixError(tErrno
, SQLITE_IOERR_LOCK
);
2499 if( IS_LOCK_ERROR(lrc
) ){
2500 storeLastErrno(pFile
, tErrno
);
2505 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile
->h
, rc
, reserved
));
2507 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2508 if( (rc
& 0xff) == SQLITE_IOERR
){
2512 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2513 *pResOut
= reserved
;
2518 ** Lock the file with the lock specified by parameter eFileLock - one
2519 ** of the following:
2522 ** (2) RESERVED_LOCK
2524 ** (4) EXCLUSIVE_LOCK
2526 ** Sometimes when requesting one lock state, additional lock states
2527 ** are inserted in between. The locking might fail on one of the later
2528 ** transitions leaving the lock state different from what it started but
2529 ** still short of its goal. The following chart shows the allowed
2530 ** transitions and the inserted intermediate states:
2532 ** UNLOCKED -> SHARED
2533 ** SHARED -> RESERVED
2534 ** SHARED -> (PENDING) -> EXCLUSIVE
2535 ** RESERVED -> (PENDING) -> EXCLUSIVE
2536 ** PENDING -> EXCLUSIVE
2538 ** flock() only really support EXCLUSIVE locks. We track intermediate
2539 ** lock states in the sqlite3_file structure, but all locks SHARED or
2540 ** above are really EXCLUSIVE locks and exclude all other processes from
2543 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
2544 ** routine to lower a locking level.
2546 static int flockLock(sqlite3_file
*id
, int eFileLock
) {
2548 unixFile
*pFile
= (unixFile
*)id
;
2552 /* if we already have a lock, it is exclusive.
2553 ** Just adjust level and punt on outta here. */
2554 if (pFile
->eFileLock
> NO_LOCK
) {
2555 pFile
->eFileLock
= eFileLock
;
2559 /* grab an exclusive lock */
2561 if (robust_flock(pFile
->h
, LOCK_EX
| LOCK_NB
)) {
2563 /* didn't get, must be busy */
2564 rc
= sqliteErrorFromPosixError(tErrno
, SQLITE_IOERR_LOCK
);
2565 if( IS_LOCK_ERROR(rc
) ){
2566 storeLastErrno(pFile
, tErrno
);
2569 /* got it, set the type and return ok */
2570 pFile
->eFileLock
= eFileLock
;
2572 OSTRACE(("LOCK %d %s %s (flock)\n", pFile
->h
, azFileLock(eFileLock
),
2573 rc
==SQLITE_OK
? "ok" : "failed"));
2574 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2575 if( (rc
& 0xff) == SQLITE_IOERR
){
2578 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2584 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
2585 ** must be either NO_LOCK or SHARED_LOCK.
2587 ** If the locking level of the file descriptor is already at or below
2588 ** the requested locking level, this routine is a no-op.
2590 static int flockUnlock(sqlite3_file
*id
, int eFileLock
) {
2591 unixFile
*pFile
= (unixFile
*)id
;
2594 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile
->h
, eFileLock
,
2595 pFile
->eFileLock
, osGetpid(0)));
2596 assert( eFileLock
<=SHARED_LOCK
);
2598 /* no-op if possible */
2599 if( pFile
->eFileLock
==eFileLock
){
2603 /* shared can just be set because we always have an exclusive */
2604 if (eFileLock
==SHARED_LOCK
) {
2605 pFile
->eFileLock
= eFileLock
;
2609 /* no, really, unlock. */
2610 if( robust_flock(pFile
->h
, LOCK_UN
) ){
2611 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2613 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2614 return SQLITE_IOERR_UNLOCK
;
2616 pFile
->eFileLock
= NO_LOCK
;
2624 static int flockClose(sqlite3_file
*id
) {
2626 flockUnlock(id
, NO_LOCK
);
2627 return closeUnixFile(id
);
2630 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2632 /******************* End of the flock lock implementation *********************
2633 ******************************************************************************/
2635 /******************************************************************************
2636 ************************ Begin Named Semaphore Locking ************************
2638 ** Named semaphore locking is only supported on VxWorks.
2640 ** Semaphore locking is like dot-lock and flock in that it really only
2641 ** supports EXCLUSIVE locking. Only a single process can read or write
2642 ** the database file at a time. This reduces potential concurrency, but
2643 ** makes the lock implementation much easier.
2648 ** This routine checks if there is a RESERVED lock held on the specified
2649 ** file by this or any other process. If such a lock is held, set *pResOut
2650 ** to a non-zero value otherwise *pResOut is set to zero. The return value
2651 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2653 static int semXCheckReservedLock(sqlite3_file
*id
, int *pResOut
) {
2656 unixFile
*pFile
= (unixFile
*)id
;
2658 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK
; );
2662 /* Check if a thread in this process holds such a lock */
2663 if( pFile
->eFileLock
>SHARED_LOCK
){
2667 /* Otherwise see if some other process holds it. */
2669 sem_t
*pSem
= pFile
->pInode
->pSem
;
2671 if( sem_trywait(pSem
)==-1 ){
2673 if( EAGAIN
!= tErrno
){
2674 rc
= sqliteErrorFromPosixError(tErrno
, SQLITE_IOERR_CHECKRESERVEDLOCK
);
2675 storeLastErrno(pFile
, tErrno
);
2677 /* someone else has the lock when we are in NO_LOCK */
2678 reserved
= (pFile
->eFileLock
< SHARED_LOCK
);
2681 /* we could have it if we want it */
2685 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile
->h
, rc
, reserved
));
2687 *pResOut
= reserved
;
2692 ** Lock the file with the lock specified by parameter eFileLock - one
2693 ** of the following:
2696 ** (2) RESERVED_LOCK
2698 ** (4) EXCLUSIVE_LOCK
2700 ** Sometimes when requesting one lock state, additional lock states
2701 ** are inserted in between. The locking might fail on one of the later
2702 ** transitions leaving the lock state different from what it started but
2703 ** still short of its goal. The following chart shows the allowed
2704 ** transitions and the inserted intermediate states:
2706 ** UNLOCKED -> SHARED
2707 ** SHARED -> RESERVED
2708 ** SHARED -> (PENDING) -> EXCLUSIVE
2709 ** RESERVED -> (PENDING) -> EXCLUSIVE
2710 ** PENDING -> EXCLUSIVE
2712 ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2713 ** lock states in the sqlite3_file structure, but all locks SHARED or
2714 ** above are really EXCLUSIVE locks and exclude all other processes from
2717 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
2718 ** routine to lower a locking level.
2720 static int semXLock(sqlite3_file
*id
, int eFileLock
) {
2721 unixFile
*pFile
= (unixFile
*)id
;
2722 sem_t
*pSem
= pFile
->pInode
->pSem
;
2725 /* if we already have a lock, it is exclusive.
2726 ** Just adjust level and punt on outta here. */
2727 if (pFile
->eFileLock
> NO_LOCK
) {
2728 pFile
->eFileLock
= eFileLock
;
2733 /* lock semaphore now but bail out when already locked. */
2734 if( sem_trywait(pSem
)==-1 ){
2739 /* got it, set the type and return ok */
2740 pFile
->eFileLock
= eFileLock
;
2747 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
2748 ** must be either NO_LOCK or SHARED_LOCK.
2750 ** If the locking level of the file descriptor is already at or below
2751 ** the requested locking level, this routine is a no-op.
2753 static int semXUnlock(sqlite3_file
*id
, int eFileLock
) {
2754 unixFile
*pFile
= (unixFile
*)id
;
2755 sem_t
*pSem
= pFile
->pInode
->pSem
;
2759 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile
->h
, eFileLock
,
2760 pFile
->eFileLock
, osGetpid(0)));
2761 assert( eFileLock
<=SHARED_LOCK
);
2763 /* no-op if possible */
2764 if( pFile
->eFileLock
==eFileLock
){
2768 /* shared can just be set because we always have an exclusive */
2769 if (eFileLock
==SHARED_LOCK
) {
2770 pFile
->eFileLock
= eFileLock
;
2774 /* no, really unlock. */
2775 if ( sem_post(pSem
)==-1 ) {
2776 int rc
, tErrno
= errno
;
2777 rc
= sqliteErrorFromPosixError(tErrno
, SQLITE_IOERR_UNLOCK
);
2778 if( IS_LOCK_ERROR(rc
) ){
2779 storeLastErrno(pFile
, tErrno
);
2783 pFile
->eFileLock
= NO_LOCK
;
2790 static int semXClose(sqlite3_file
*id
) {
2792 unixFile
*pFile
= (unixFile
*)id
;
2793 semXUnlock(id
, NO_LOCK
);
2795 assert( unixFileMutexNotheld(pFile
) );
2797 releaseInodeInfo(pFile
);
2804 #endif /* OS_VXWORKS */
2806 ** Named semaphore locking is only available on VxWorks.
2808 *************** End of the named semaphore lock implementation ****************
2809 ******************************************************************************/
2812 /******************************************************************************
2813 *************************** Begin AFP Locking *********************************
2815 ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2816 ** on Apple Macintosh computers - both OS9 and OSX.
2818 ** Third-party implementations of AFP are available. But this code here
2819 ** only works on OSX.
2822 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2824 ** The afpLockingContext structure contains all afp lock specific state
2826 typedef struct afpLockingContext afpLockingContext
;
2827 struct afpLockingContext
{
2829 const char *dbPath
; /* Name of the open file */
2832 struct ByteRangeLockPB2
2834 unsigned long long offset
; /* offset to first byte to lock */
2835 unsigned long long length
; /* nbr of bytes to lock */
2836 unsigned long long retRangeStart
; /* nbr of 1st byte locked if successful */
2837 unsigned char unLockFlag
; /* 1 = unlock, 0 = lock */
2838 unsigned char startEndFlag
; /* 1=rel to end of fork, 0=rel to start */
2839 int fd
; /* file desc to assoc this lock with */
2842 #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
2845 ** This is a utility for setting or clearing a bit-range lock on an
2848 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2850 static int afpSetLock(
2851 const char *path
, /* Name of the file to be locked or unlocked */
2852 unixFile
*pFile
, /* Open file descriptor on path */
2853 unsigned long long offset
, /* First byte to be locked */
2854 unsigned long long length
, /* Number of bytes to lock */
2855 int setLockFlag
/* True to set lock. False to clear lock */
2857 struct ByteRangeLockPB2 pb
;
2860 pb
.unLockFlag
= setLockFlag
? 0 : 1;
2861 pb
.startEndFlag
= 0;
2866 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
2867 (setLockFlag
?"ON":"OFF"), pFile
->h
, (pb
.fd
==-1?"[testval-1]":""),
2869 err
= fsctl(path
, afpfsByteRangeLock2FSCTL
, &pb
, 0);
2873 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2874 path
, tErrno
, strerror(tErrno
)));
2875 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2878 rc
= sqliteErrorFromPosixError(tErrno
,
2879 setLockFlag
? SQLITE_IOERR_LOCK
: SQLITE_IOERR_UNLOCK
);
2880 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
2881 if( IS_LOCK_ERROR(rc
) ){
2882 storeLastErrno(pFile
, tErrno
);
2891 ** This routine checks if there is a RESERVED lock held on the specified
2892 ** file by this or any other process. If such a lock is held, set *pResOut
2893 ** to a non-zero value otherwise *pResOut is set to zero. The return value
2894 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2896 static int afpCheckReservedLock(sqlite3_file
*id
, int *pResOut
){
2899 unixFile
*pFile
= (unixFile
*)id
;
2900 afpLockingContext
*context
;
2902 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK
; );
2905 context
= (afpLockingContext
*) pFile
->lockingContext
;
2906 if( context
->reserved
){
2910 sqlite3_mutex_enter(pFile
->pInode
->pLockMutex
);
2911 /* Check if a thread in this process holds such a lock */
2912 if( pFile
->pInode
->eFileLock
>SHARED_LOCK
){
2916 /* Otherwise see if some other process holds it.
2919 /* lock the RESERVED byte */
2920 int lrc
= afpSetLock(context
->dbPath
, pFile
, RESERVED_BYTE
, 1,1);
2921 if( SQLITE_OK
==lrc
){
2922 /* if we succeeded in taking the reserved lock, unlock it to restore
2923 ** the original state */
2924 lrc
= afpSetLock(context
->dbPath
, pFile
, RESERVED_BYTE
, 1, 0);
2926 /* if we failed to get the lock then someone else must have it */
2929 if( IS_LOCK_ERROR(lrc
) ){
2934 sqlite3_mutex_leave(pFile
->pInode
->pLockMutex
);
2935 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile
->h
, rc
, reserved
));
2937 *pResOut
= reserved
;
2942 ** Lock the file with the lock specified by parameter eFileLock - one
2943 ** of the following:
2946 ** (2) RESERVED_LOCK
2948 ** (4) EXCLUSIVE_LOCK
2950 ** Sometimes when requesting one lock state, additional lock states
2951 ** are inserted in between. The locking might fail on one of the later
2952 ** transitions leaving the lock state different from what it started but
2953 ** still short of its goal. The following chart shows the allowed
2954 ** transitions and the inserted intermediate states:
2956 ** UNLOCKED -> SHARED
2957 ** SHARED -> RESERVED
2958 ** SHARED -> (PENDING) -> EXCLUSIVE
2959 ** RESERVED -> (PENDING) -> EXCLUSIVE
2960 ** PENDING -> EXCLUSIVE
2962 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
2963 ** routine to lower a locking level.
2965 static int afpLock(sqlite3_file
*id
, int eFileLock
){
2967 unixFile
*pFile
= (unixFile
*)id
;
2968 unixInodeInfo
*pInode
= pFile
->pInode
;
2969 afpLockingContext
*context
= (afpLockingContext
*) pFile
->lockingContext
;
2972 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile
->h
,
2973 azFileLock(eFileLock
), azFileLock(pFile
->eFileLock
),
2974 azFileLock(pInode
->eFileLock
), pInode
->nShared
, osGetpid(0)));
2976 /* If there is already a lock of this type or more restrictive on the
2977 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
2978 ** unixEnterMutex() hasn't been called yet.
2980 if( pFile
->eFileLock
>=eFileLock
){
2981 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile
->h
,
2982 azFileLock(eFileLock
)));
2986 /* Make sure the locking sequence is correct
2987 ** (1) We never move from unlocked to anything higher than shared lock.
2988 ** (2) SQLite never explicitly requests a pending lock.
2989 ** (3) A shared lock is always held when a reserve lock is requested.
2991 assert( pFile
->eFileLock
!=NO_LOCK
|| eFileLock
==SHARED_LOCK
);
2992 assert( eFileLock
!=PENDING_LOCK
);
2993 assert( eFileLock
!=RESERVED_LOCK
|| pFile
->eFileLock
==SHARED_LOCK
);
2995 /* This mutex is needed because pFile->pInode is shared across threads
2997 pInode
= pFile
->pInode
;
2998 sqlite3_mutex_enter(pInode
->pLockMutex
);
3000 /* If some thread using this PID has a lock via a different unixFile*
3001 ** handle that precludes the requested lock, return BUSY.
3003 if( (pFile
->eFileLock
!=pInode
->eFileLock
&&
3004 (pInode
->eFileLock
>=PENDING_LOCK
|| eFileLock
>SHARED_LOCK
))
3010 /* If a SHARED lock is requested, and some thread using this PID already
3011 ** has a SHARED or RESERVED lock, then increment reference counts and
3012 ** return SQLITE_OK.
3014 if( eFileLock
==SHARED_LOCK
&&
3015 (pInode
->eFileLock
==SHARED_LOCK
|| pInode
->eFileLock
==RESERVED_LOCK
) ){
3016 assert( eFileLock
==SHARED_LOCK
);
3017 assert( pFile
->eFileLock
==0 );
3018 assert( pInode
->nShared
>0 );
3019 pFile
->eFileLock
= SHARED_LOCK
;
3025 /* A PENDING lock is needed before acquiring a SHARED lock and before
3026 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
3029 if( eFileLock
==SHARED_LOCK
3030 || (eFileLock
==EXCLUSIVE_LOCK
&& pFile
->eFileLock
<PENDING_LOCK
)
3033 failed
= afpSetLock(context
->dbPath
, pFile
, PENDING_BYTE
, 1, 1);
3040 /* If control gets to this point, then actually go ahead and make
3041 ** operating system calls for the specified lock.
3043 if( eFileLock
==SHARED_LOCK
){
3044 int lrc1
, lrc2
, lrc1Errno
= 0;
3047 assert( pInode
->nShared
==0 );
3048 assert( pInode
->eFileLock
==0 );
3050 mask
= (sizeof(long)==8) ? LARGEST_INT64
: 0x7fffffff;
3051 /* Now get the read-lock SHARED_LOCK */
3052 /* note that the quality of the randomness doesn't matter that much */
3054 pInode
->sharedByte
= (lk
& mask
)%(SHARED_SIZE
- 1);
3055 lrc1
= afpSetLock(context
->dbPath
, pFile
,
3056 SHARED_FIRST
+pInode
->sharedByte
, 1, 1);
3057 if( IS_LOCK_ERROR(lrc1
) ){
3058 lrc1Errno
= pFile
->lastErrno
;
3060 /* Drop the temporary PENDING lock */
3061 lrc2
= afpSetLock(context
->dbPath
, pFile
, PENDING_BYTE
, 1, 0);
3063 if( IS_LOCK_ERROR(lrc1
) ) {
3064 storeLastErrno(pFile
, lrc1Errno
);
3067 } else if( IS_LOCK_ERROR(lrc2
) ){
3070 } else if( lrc1
!= SQLITE_OK
) {
3073 pFile
->eFileLock
= SHARED_LOCK
;
3075 pInode
->nShared
= 1;
3077 }else if( eFileLock
==EXCLUSIVE_LOCK
&& pInode
->nShared
>1 ){
3078 /* We are trying for an exclusive lock but another thread in this
3079 ** same process is still holding a shared lock. */
3082 /* The request was for a RESERVED or EXCLUSIVE lock. It is
3083 ** assumed that there is a SHARED or greater lock on the file
3087 assert( 0!=pFile
->eFileLock
);
3088 if (eFileLock
>= RESERVED_LOCK
&& pFile
->eFileLock
< RESERVED_LOCK
) {
3089 /* Acquire a RESERVED lock */
3090 failed
= afpSetLock(context
->dbPath
, pFile
, RESERVED_BYTE
, 1,1);
3092 context
->reserved
= 1;
3095 if (!failed
&& eFileLock
== EXCLUSIVE_LOCK
) {
3096 /* Acquire an EXCLUSIVE lock */
3098 /* Remove the shared lock before trying the range. we'll need to
3099 ** reestablish the shared lock if we can't get the afpUnlock
3101 if( !(failed
= afpSetLock(context
->dbPath
, pFile
, SHARED_FIRST
+
3102 pInode
->sharedByte
, 1, 0)) ){
3103 int failed2
= SQLITE_OK
;
3104 /* now attempt to get the exclusive lock range */
3105 failed
= afpSetLock(context
->dbPath
, pFile
, SHARED_FIRST
,
3107 if( failed
&& (failed2
= afpSetLock(context
->dbPath
, pFile
,
3108 SHARED_FIRST
+ pInode
->sharedByte
, 1, 1)) ){
3109 /* Can't reestablish the shared lock. Sqlite can't deal, this is
3110 ** a critical I/O error
3112 rc
= ((failed
& 0xff) == SQLITE_IOERR
) ? failed2
:
3125 if( rc
==SQLITE_OK
){
3126 pFile
->eFileLock
= eFileLock
;
3127 pInode
->eFileLock
= eFileLock
;
3128 }else if( eFileLock
==EXCLUSIVE_LOCK
){
3129 pFile
->eFileLock
= PENDING_LOCK
;
3130 pInode
->eFileLock
= PENDING_LOCK
;
3134 sqlite3_mutex_leave(pInode
->pLockMutex
);
3135 OSTRACE(("LOCK %d %s %s (afp)\n", pFile
->h
, azFileLock(eFileLock
),
3136 rc
==SQLITE_OK
? "ok" : "failed"));
3141 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
3142 ** must be either NO_LOCK or SHARED_LOCK.
3144 ** If the locking level of the file descriptor is already at or below
3145 ** the requested locking level, this routine is a no-op.
3147 static int afpUnlock(sqlite3_file
*id
, int eFileLock
) {
3149 unixFile
*pFile
= (unixFile
*)id
;
3150 unixInodeInfo
*pInode
;
3151 afpLockingContext
*context
= (afpLockingContext
*) pFile
->lockingContext
;
3158 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile
->h
, eFileLock
,
3159 pFile
->eFileLock
, pFile
->pInode
->eFileLock
, pFile
->pInode
->nShared
,
3162 assert( eFileLock
<=SHARED_LOCK
);
3163 if( pFile
->eFileLock
<=eFileLock
){
3166 pInode
= pFile
->pInode
;
3167 sqlite3_mutex_enter(pInode
->pLockMutex
);
3168 assert( pInode
->nShared
!=0 );
3169 if( pFile
->eFileLock
>SHARED_LOCK
){
3170 assert( pInode
->eFileLock
==pFile
->eFileLock
);
3171 SimulateIOErrorBenign(1);
3172 SimulateIOError( h
=(-1) )
3173 SimulateIOErrorBenign(0);
3176 /* When reducing a lock such that other processes can start
3177 ** reading the database file again, make sure that the
3178 ** transaction counter was updated if any part of the database
3179 ** file changed. If the transaction counter is not updated,
3180 ** other connections to the same file might not realize that
3181 ** the file has changed and hence might not know to flush their
3182 ** cache. The use of a stale cache can lead to database corruption.
3184 assert( pFile
->inNormalWrite
==0
3185 || pFile
->dbUpdate
==0
3186 || pFile
->transCntrChng
==1 );
3187 pFile
->inNormalWrite
= 0;
3190 if( pFile
->eFileLock
==EXCLUSIVE_LOCK
){
3191 rc
= afpSetLock(context
->dbPath
, pFile
, SHARED_FIRST
, SHARED_SIZE
, 0);
3192 if( rc
==SQLITE_OK
&& (eFileLock
==SHARED_LOCK
|| pInode
->nShared
>1) ){
3193 /* only re-establish the shared lock if necessary */
3194 int sharedLockByte
= SHARED_FIRST
+pInode
->sharedByte
;
3195 rc
= afpSetLock(context
->dbPath
, pFile
, sharedLockByte
, 1, 1);
3200 if( rc
==SQLITE_OK
&& pFile
->eFileLock
>=PENDING_LOCK
){
3201 rc
= afpSetLock(context
->dbPath
, pFile
, PENDING_BYTE
, 1, 0);
3203 if( rc
==SQLITE_OK
&& pFile
->eFileLock
>=RESERVED_LOCK
&& context
->reserved
){
3204 rc
= afpSetLock(context
->dbPath
, pFile
, RESERVED_BYTE
, 1, 0);
3206 context
->reserved
= 0;
3209 if( rc
==SQLITE_OK
&& (eFileLock
==SHARED_LOCK
|| pInode
->nShared
>1)){
3210 pInode
->eFileLock
= SHARED_LOCK
;
3213 if( rc
==SQLITE_OK
&& eFileLock
==NO_LOCK
){
3215 /* Decrement the shared lock counter. Release the lock using an
3216 ** OS call only when all threads in this same process have released
3219 unsigned long long sharedLockByte
= SHARED_FIRST
+pInode
->sharedByte
;
3221 if( pInode
->nShared
==0 ){
3222 SimulateIOErrorBenign(1);
3223 SimulateIOError( h
=(-1) )
3224 SimulateIOErrorBenign(0);
3226 rc
= afpSetLock(context
->dbPath
, pFile
, sharedLockByte
, 1, 0);
3229 pInode
->eFileLock
= NO_LOCK
;
3230 pFile
->eFileLock
= NO_LOCK
;
3233 if( rc
==SQLITE_OK
){
3235 assert( pInode
->nLock
>=0 );
3236 if( pInode
->nLock
==0 ) closePendingFds(pFile
);
3240 sqlite3_mutex_leave(pInode
->pLockMutex
);
3241 if( rc
==SQLITE_OK
){
3242 pFile
->eFileLock
= eFileLock
;
3248 ** Close a file & cleanup AFP specific locking context
3250 static int afpClose(sqlite3_file
*id
) {
3252 unixFile
*pFile
= (unixFile
*)id
;
3254 afpUnlock(id
, NO_LOCK
);
3255 assert( unixFileMutexNotheld(pFile
) );
3257 if( pFile
->pInode
){
3258 unixInodeInfo
*pInode
= pFile
->pInode
;
3259 sqlite3_mutex_enter(pInode
->pLockMutex
);
3260 if( pInode
->nLock
){
3261 /* If there are outstanding locks, do not actually close the file just
3262 ** yet because that would clear those locks. Instead, add the file
3263 ** descriptor to pInode->aPending. It will be automatically closed when
3264 ** the last lock is cleared.
3266 setPendingFd(pFile
);
3268 sqlite3_mutex_leave(pInode
->pLockMutex
);
3270 releaseInodeInfo(pFile
);
3271 sqlite3_free(pFile
->lockingContext
);
3272 rc
= closeUnixFile(id
);
3277 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3279 ** The code above is the AFP lock implementation. The code is specific
3280 ** to MacOSX and does not work on other unix platforms. No alternative
3281 ** is available. If you don't compile for a mac, then the "unix-afp"
3282 ** VFS is not available.
3284 ********************* End of the AFP lock implementation **********************
3285 ******************************************************************************/
3287 /******************************************************************************
3288 *************************** Begin NFS Locking ********************************/
3290 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3292 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
3293 ** must be either NO_LOCK or SHARED_LOCK.
3295 ** If the locking level of the file descriptor is already at or below
3296 ** the requested locking level, this routine is a no-op.
3298 static int nfsUnlock(sqlite3_file
*id
, int eFileLock
){
3299 return posixUnlock(id
, eFileLock
, 1);
3302 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3304 ** The code above is the NFS lock implementation. The code is specific
3305 ** to MacOSX and does not work on other unix platforms. No alternative
3308 ********************* End of the NFS lock implementation **********************
3309 ******************************************************************************/
3311 /******************************************************************************
3312 **************** Non-locking sqlite3_file methods *****************************
3314 ** The next division contains implementations for all methods of the
3315 ** sqlite3_file object other than the locking methods. The locking
3316 ** methods were defined in divisions above (one locking method per
3317 ** division). Those methods that are common to all locking modes
3318 ** are gather together into this division.
3322 ** Seek to the offset passed as the second argument, then read cnt
3323 ** bytes into pBuf. Return the number of bytes actually read.
3325 ** To avoid stomping the errno value on a failed read the lastErrno value
3326 ** is set before returning.
3328 static int seekAndRead(unixFile
*id
, sqlite3_int64 offset
, void *pBuf
, int cnt
){
3331 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
3335 assert( cnt
==(cnt
&0x1ffff) );
3338 #if defined(USE_PREAD)
3339 got
= osPread(id
->h
, pBuf
, cnt
, offset
);
3340 SimulateIOError( got
= -1 );
3341 #elif defined(USE_PREAD64)
3342 got
= osPread64(id
->h
, pBuf
, cnt
, offset
);
3343 SimulateIOError( got
= -1 );
3345 newOffset
= lseek(id
->h
, offset
, SEEK_SET
);
3346 SimulateIOError( newOffset
= -1 );
3348 storeLastErrno((unixFile
*)id
, errno
);
3351 got
= osRead(id
->h
, pBuf
, cnt
);
3353 if( got
==cnt
) break;
3355 if( errno
==EINTR
){ got
= 1; continue; }
3357 storeLastErrno((unixFile
*)id
, errno
);
3363 pBuf
= (void*)(got
+ (char*)pBuf
);
3367 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3368 id
->h
, got
+prior
, offset
-prior
, TIMER_ELAPSED
));
3373 ** Read data from a file into a buffer. Return SQLITE_OK if all
3374 ** bytes were read successfully and SQLITE_IOERR if anything goes
3377 static int unixRead(
3381 sqlite3_int64 offset
3383 unixFile
*pFile
= (unixFile
*)id
;
3386 assert( offset
>=0 );
3389 /* If this is a database file (not a journal, super-journal or temp
3390 ** file), the bytes in the locking range should never be read or written. */
3392 assert( pFile
->pPreallocatedUnused
==0
3393 || offset
>=PENDING_BYTE
+512
3394 || offset
+amt
<=PENDING_BYTE
3398 #if SQLITE_MAX_MMAP_SIZE>0
3399 /* Deal with as much of this read request as possible by transferring
3400 ** data from the memory mapping using memcpy(). */
3401 if( offset
<pFile
->mmapSize
){
3402 if( offset
+amt
<= pFile
->mmapSize
){
3403 memcpy(pBuf
, &((u8
*)(pFile
->pMapRegion
))[offset
], amt
);
3406 int nCopy
= pFile
->mmapSize
- offset
;
3407 memcpy(pBuf
, &((u8
*)(pFile
->pMapRegion
))[offset
], nCopy
);
3408 pBuf
= &((u8
*)pBuf
)[nCopy
];
3415 got
= seekAndRead(pFile
, offset
, pBuf
, amt
);
3419 /* pFile->lastErrno has been set by seekAndRead().
3420 ** Usually we return SQLITE_IOERR_READ here, though for some
3421 ** kinds of errors we return SQLITE_IOERR_CORRUPTFS. The
3422 ** SQLITE_IOERR_CORRUPTFS will be converted into SQLITE_CORRUPT
3423 ** prior to returning to the application by the sqlite3ApiExit()
3426 switch( pFile
->lastErrno
){
3435 return SQLITE_IOERR_CORRUPTFS
;
3437 return SQLITE_IOERR_READ
;
3439 storeLastErrno(pFile
, 0); /* not a system error */
3440 /* Unread parts of the buffer must be zero-filled */
3441 memset(&((char*)pBuf
)[got
], 0, amt
-got
);
3442 return SQLITE_IOERR_SHORT_READ
;
3447 ** Attempt to seek the file-descriptor passed as the first argument to
3448 ** absolute offset iOff, then attempt to write nBuf bytes of data from
3449 ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3450 ** return the actual number of bytes written (which may be less than
3453 static int seekAndWriteFd(
3454 int fd
, /* File descriptor to write to */
3455 i64 iOff
, /* File offset to begin writing at */
3456 const void *pBuf
, /* Copy data from this buffer to the file */
3457 int nBuf
, /* Size of buffer pBuf in bytes */
3458 int *piErrno
/* OUT: Error number if error occurs */
3460 int rc
= 0; /* Value returned by system call */
3462 assert( nBuf
==(nBuf
&0x1ffff) );
3464 assert( piErrno
!=0 );
3468 #if defined(USE_PREAD)
3469 do{ rc
= (int)osPwrite(fd
, pBuf
, nBuf
, iOff
); }while( rc
<0 && errno
==EINTR
);
3470 #elif defined(USE_PREAD64)
3471 do{ rc
= (int)osPwrite64(fd
, pBuf
, nBuf
, iOff
);}while( rc
<0 && errno
==EINTR
);
3474 i64 iSeek
= lseek(fd
, iOff
, SEEK_SET
);
3475 SimulateIOError( iSeek
= -1 );
3480 rc
= osWrite(fd
, pBuf
, nBuf
);
3481 }while( rc
<0 && errno
==EINTR
);
3485 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd
, rc
, iOff
, TIMER_ELAPSED
));
3487 if( rc
<0 ) *piErrno
= errno
;
3493 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
3494 ** Return the number of bytes actually read. Update the offset.
3496 ** To avoid stomping the errno value on a failed write the lastErrno value
3497 ** is set before returning.
3499 static int seekAndWrite(unixFile
*id
, i64 offset
, const void *pBuf
, int cnt
){
3500 return seekAndWriteFd(id
->h
, offset
, pBuf
, cnt
, &id
->lastErrno
);
3505 ** Write data from a buffer into a file. Return SQLITE_OK on success
3506 ** or some other error code on failure.
3508 static int unixWrite(
3512 sqlite3_int64 offset
3514 unixFile
*pFile
= (unixFile
*)id
;
3519 /* If this is a database file (not a journal, super-journal or temp
3520 ** file), the bytes in the locking range should never be read or written. */
3522 assert( pFile
->pPreallocatedUnused
==0
3523 || offset
>=PENDING_BYTE
+512
3524 || offset
+amt
<=PENDING_BYTE
3529 /* If we are doing a normal write to a database file (as opposed to
3530 ** doing a hot-journal rollback or a write to some file other than a
3531 ** normal database file) then record the fact that the database
3532 ** has changed. If the transaction counter is modified, record that
3535 if( pFile
->inNormalWrite
){
3536 pFile
->dbUpdate
= 1; /* The database has been modified */
3537 if( offset
<=24 && offset
+amt
>=27 ){
3540 SimulateIOErrorBenign(1);
3541 rc
= seekAndRead(pFile
, 24, oldCntr
, 4);
3542 SimulateIOErrorBenign(0);
3543 if( rc
!=4 || memcmp(oldCntr
, &((char*)pBuf
)[24-offset
], 4)!=0 ){
3544 pFile
->transCntrChng
= 1; /* The transaction counter has changed */
3550 #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
3551 /* Deal with as much of this write request as possible by transferring
3552 ** data from the memory mapping using memcpy(). */
3553 if( offset
<pFile
->mmapSize
){
3554 if( offset
+amt
<= pFile
->mmapSize
){
3555 memcpy(&((u8
*)(pFile
->pMapRegion
))[offset
], pBuf
, amt
);
3558 int nCopy
= pFile
->mmapSize
- offset
;
3559 memcpy(&((u8
*)(pFile
->pMapRegion
))[offset
], pBuf
, nCopy
);
3560 pBuf
= &((u8
*)pBuf
)[nCopy
];
3567 while( (wrote
= seekAndWrite(pFile
, offset
, pBuf
, amt
))<amt
&& wrote
>0 ){
3570 pBuf
= &((char*)pBuf
)[wrote
];
3572 SimulateIOError(( wrote
=(-1), amt
=1 ));
3573 SimulateDiskfullError(( wrote
=0, amt
=1 ));
3576 if( wrote
<0 && pFile
->lastErrno
!=ENOSPC
){
3577 /* lastErrno set by seekAndWrite */
3578 return SQLITE_IOERR_WRITE
;
3580 storeLastErrno(pFile
, 0); /* not a system error */
3590 ** Count the number of fullsyncs and normal syncs. This is used to test
3591 ** that syncs and fullsyncs are occurring at the right times.
3593 int sqlite3_sync_count
= 0;
3594 int sqlite3_fullsync_count
= 0;
3598 ** We do not trust systems to provide a working fdatasync(). Some do.
3599 ** Others do no. To be safe, we will stick with the (slightly slower)
3600 ** fsync(). If you know that your system does support fdatasync() correctly,
3601 ** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
3603 #if !defined(fdatasync) && !HAVE_FDATASYNC
3604 # define fdatasync fsync
3608 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3609 ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3610 ** only available on Mac OS X. But that could change.
3613 # define HAVE_FULLFSYNC 1
3615 # define HAVE_FULLFSYNC 0
3620 ** The fsync() system call does not work as advertised on many
3621 ** unix systems. The following procedure is an attempt to make
3624 ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3625 ** for testing when we want to run through the test suite quickly.
3626 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3627 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3628 ** or power failure will likely corrupt the database file.
3630 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
3631 ** The idea behind dataOnly is that it should only write the file content
3632 ** to disk, not the inode. We only set dataOnly if the file size is
3633 ** unchanged since the file size is part of the inode. However,
3634 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
3635 ** file size has changed. The only real difference between fdatasync()
3636 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
3637 ** inode if the mtime or owner or other inode attributes have changed.
3638 ** We only care about the file size, not the other file attributes, so
3639 ** as far as SQLite is concerned, an fdatasync() is always adequate.
3640 ** So, we always use fdatasync() if it is available, regardless of
3641 ** the value of the dataOnly flag.
3643 static int full_fsync(int fd
, int fullSync
, int dataOnly
){
3646 /* The following "ifdef/elif/else/" block has the same structure as
3647 ** the one below. It is replicated here solely to avoid cluttering
3648 ** up the real code with the UNUSED_PARAMETER() macros.
3650 #ifdef SQLITE_NO_SYNC
3651 UNUSED_PARAMETER(fd
);
3652 UNUSED_PARAMETER(fullSync
);
3653 UNUSED_PARAMETER(dataOnly
);
3654 #elif HAVE_FULLFSYNC
3655 UNUSED_PARAMETER(dataOnly
);
3657 UNUSED_PARAMETER(fullSync
);
3658 UNUSED_PARAMETER(dataOnly
);
3661 /* Record the number of times that we do a normal fsync() and
3662 ** FULLSYNC. This is used during testing to verify that this procedure
3663 ** gets called with the correct arguments.
3666 if( fullSync
) sqlite3_fullsync_count
++;
3667 sqlite3_sync_count
++;
3670 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3671 ** no-op. But go ahead and call fstat() to validate the file
3672 ** descriptor as we need a method to provoke a failure during
3673 ** coverage testing.
3675 #ifdef SQLITE_NO_SYNC
3678 rc
= osFstat(fd
, &buf
);
3680 #elif HAVE_FULLFSYNC
3682 rc
= osFcntl(fd
, F_FULLFSYNC
, 0);
3686 /* If the FULLFSYNC failed, fall back to attempting an fsync().
3687 ** It shouldn't be possible for fullfsync to fail on the local
3688 ** file system (on OSX), so failure indicates that FULLFSYNC
3689 ** isn't supported for this file system. So, attempt an fsync
3690 ** and (for now) ignore the overhead of a superfluous fcntl call.
3691 ** It'd be better to detect fullfsync support once and avoid
3692 ** the fcntl call every time sync is called.
3694 if( rc
) rc
= fsync(fd
);
3696 #elif defined(__APPLE__)
3697 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3698 ** so currently we default to the macro that redefines fdatasync to fsync
3704 if( rc
==-1 && errno
==ENOTSUP
){
3707 #endif /* OS_VXWORKS */
3708 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3710 if( OS_VXWORKS
&& rc
!= -1 ){
3717 ** Open a file descriptor to the directory containing file zFilename.
3718 ** If successful, *pFd is set to the opened file descriptor and
3719 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3720 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3723 ** The directory file descriptor is used for only one thing - to
3724 ** fsync() a directory to make sure file creation and deletion events
3725 ** are flushed to disk. Such fsyncs are not needed on newer
3726 ** journaling filesystems, but are required on older filesystems.
3728 ** This routine can be overridden using the xSetSysCall interface.
3729 ** The ability to override this routine was added in support of the
3730 ** chromium sandbox. Opening a directory is a security risk (we are
3731 ** told) so making it overrideable allows the chromium sandbox to
3732 ** replace this routine with a harmless no-op. To make this routine
3733 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3734 ** *pFd set to a negative number.
3736 ** If SQLITE_OK is returned, the caller is responsible for closing
3737 ** the file descriptor *pFd using close().
3739 static int openDirectory(const char *zFilename
, int *pFd
){
3742 char zDirname
[MAX_PATHNAME
+1];
3744 sqlite3_snprintf(MAX_PATHNAME
, zDirname
, "%s", zFilename
);
3745 for(ii
=(int)strlen(zDirname
); ii
>0 && zDirname
[ii
]!='/'; ii
--);
3747 zDirname
[ii
] = '\0';
3749 if( zDirname
[0]!='/' ) zDirname
[0] = '.';
3752 fd
= robust_open(zDirname
, O_RDONLY
|O_BINARY
, 0);
3754 OSTRACE(("OPENDIR %-3d %s\n", fd
, zDirname
));
3757 if( fd
>=0 ) return SQLITE_OK
;
3758 return unixLogError(SQLITE_CANTOPEN_BKPT
, "openDirectory", zDirname
);
3762 ** Make sure all writes to a particular file are committed to disk.
3764 ** If dataOnly==0 then both the file itself and its metadata (file
3765 ** size, access time, etc) are synced. If dataOnly!=0 then only the
3766 ** file data is synced.
3768 ** Under Unix, also make sure that the directory entry for the file
3769 ** has been created by fsync-ing the directory that contains the file.
3770 ** If we do not do this and we encounter a power failure, the directory
3771 ** entry for the journal might not exist after we reboot. The next
3772 ** SQLite to access the file will not know that the journal exists (because
3773 ** the directory entry for the journal was never created) and the transaction
3774 ** will not roll back - possibly leading to database corruption.
3776 static int unixSync(sqlite3_file
*id
, int flags
){
3778 unixFile
*pFile
= (unixFile
*)id
;
3780 int isDataOnly
= (flags
&SQLITE_SYNC_DATAONLY
);
3781 int isFullsync
= (flags
&0x0F)==SQLITE_SYNC_FULL
;
3783 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3784 assert((flags
&0x0F)==SQLITE_SYNC_NORMAL
3785 || (flags
&0x0F)==SQLITE_SYNC_FULL
3788 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3789 ** line is to test that doing so does not cause any problems.
3791 SimulateDiskfullError( return SQLITE_FULL
);
3794 OSTRACE(("SYNC %-3d\n", pFile
->h
));
3795 rc
= full_fsync(pFile
->h
, isFullsync
, isDataOnly
);
3796 SimulateIOError( rc
=1 );
3798 storeLastErrno(pFile
, errno
);
3799 return unixLogError(SQLITE_IOERR_FSYNC
, "full_fsync", pFile
->zPath
);
3802 /* Also fsync the directory containing the file if the DIRSYNC flag
3803 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
3804 ** are unable to fsync a directory, so ignore errors on the fsync.
3806 if( pFile
->ctrlFlags
& UNIXFILE_DIRSYNC
){
3808 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile
->zPath
,
3809 HAVE_FULLFSYNC
, isFullsync
));
3810 rc
= osOpenDirectory(pFile
->zPath
, &dirfd
);
3811 if( rc
==SQLITE_OK
){
3812 full_fsync(dirfd
, 0, 0);
3813 robust_close(pFile
, dirfd
, __LINE__
);
3815 assert( rc
==SQLITE_CANTOPEN
);
3818 pFile
->ctrlFlags
&= ~UNIXFILE_DIRSYNC
;
3824 ** Truncate an open file to a specified size
3826 static int unixTruncate(sqlite3_file
*id
, i64 nByte
){
3827 unixFile
*pFile
= (unixFile
*)id
;
3830 SimulateIOError( return SQLITE_IOERR_TRUNCATE
);
3832 /* If the user has configured a chunk-size for this file, truncate the
3833 ** file so that it consists of an integer number of chunks (i.e. the
3834 ** actual file size after the operation may be larger than the requested
3837 if( pFile
->szChunk
>0 ){
3838 nByte
= ((nByte
+ pFile
->szChunk
- 1)/pFile
->szChunk
) * pFile
->szChunk
;
3841 rc
= robust_ftruncate(pFile
->h
, nByte
);
3843 storeLastErrno(pFile
, errno
);
3844 return unixLogError(SQLITE_IOERR_TRUNCATE
, "ftruncate", pFile
->zPath
);
3847 /* If we are doing a normal write to a database file (as opposed to
3848 ** doing a hot-journal rollback or a write to some file other than a
3849 ** normal database file) and we truncate the file to zero length,
3850 ** that effectively updates the change counter. This might happen
3851 ** when restoring a database using the backup API from a zero-length
3854 if( pFile
->inNormalWrite
&& nByte
==0 ){
3855 pFile
->transCntrChng
= 1;
3859 #if SQLITE_MAX_MMAP_SIZE>0
3860 /* If the file was just truncated to a size smaller than the currently
3861 ** mapped region, reduce the effective mapping size as well. SQLite will
3862 ** use read() and write() to access data beyond this point from now on.
3864 if( nByte
<pFile
->mmapSize
){
3865 pFile
->mmapSize
= nByte
;
3874 ** Determine the current size of a file in bytes
3876 static int unixFileSize(sqlite3_file
*id
, i64
*pSize
){
3880 rc
= osFstat(((unixFile
*)id
)->h
, &buf
);
3881 SimulateIOError( rc
=1 );
3883 storeLastErrno((unixFile
*)id
, errno
);
3884 return SQLITE_IOERR_FSTAT
;
3886 *pSize
= buf
.st_size
;
3888 /* When opening a zero-size database, the findInodeInfo() procedure
3889 ** writes a single byte into that file in order to work around a bug
3890 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3891 ** layers, we need to report this file size as zero even though it is
3892 ** really 1. Ticket #3260.
3894 if( *pSize
==1 ) *pSize
= 0;
3900 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
3902 ** Handler for proxy-locking file-control verbs. Defined below in the
3903 ** proxying locking division.
3905 static int proxyFileControl(sqlite3_file
*,int,void*);
3909 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
3910 ** file-control operation. Enlarge the database to nBytes in size
3911 ** (rounded up to the next chunk-size). If the database is already
3912 ** nBytes or larger, this routine is a no-op.
3914 static int fcntlSizeHint(unixFile
*pFile
, i64 nByte
){
3915 if( pFile
->szChunk
>0 ){
3916 i64 nSize
; /* Required file size */
3917 struct stat buf
; /* Used to hold return values of fstat() */
3919 if( osFstat(pFile
->h
, &buf
) ){
3920 return SQLITE_IOERR_FSTAT
;
3923 nSize
= ((nByte
+pFile
->szChunk
-1) / pFile
->szChunk
) * pFile
->szChunk
;
3924 if( nSize
>(i64
)buf
.st_size
){
3926 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
3927 /* The code below is handling the return value of osFallocate()
3928 ** correctly. posix_fallocate() is defined to "returns zero on success,
3929 ** or an error number on failure". See the manpage for details. */
3932 err
= osFallocate(pFile
->h
, buf
.st_size
, nSize
-buf
.st_size
);
3933 }while( err
==EINTR
);
3934 if( err
&& err
!=EINVAL
) return SQLITE_IOERR_WRITE
;
3936 /* If the OS does not have posix_fallocate(), fake it. Write a
3937 ** single byte to the last byte in each block that falls entirely
3938 ** within the extended region. Then, if required, a single byte
3939 ** at offset (nSize-1), to set the size of the file correctly.
3940 ** This is a similar technique to that used by glibc on systems
3941 ** that do not have a real fallocate() call.
3943 int nBlk
= buf
.st_blksize
; /* File-system block size */
3944 int nWrite
= 0; /* Number of bytes written by seekAndWrite */
3945 i64 iWrite
; /* Next offset to write to */
3947 iWrite
= (buf
.st_size
/nBlk
)*nBlk
+ nBlk
- 1;
3948 assert( iWrite
>=buf
.st_size
);
3949 assert( ((iWrite
+1)%nBlk
)==0 );
3950 for(/*no-op*/; iWrite
<nSize
+nBlk
-1; iWrite
+=nBlk
){
3951 if( iWrite
>=nSize
) iWrite
= nSize
- 1;
3952 nWrite
= seekAndWrite(pFile
, iWrite
, "", 1);
3953 if( nWrite
!=1 ) return SQLITE_IOERR_WRITE
;
3959 #if SQLITE_MAX_MMAP_SIZE>0
3960 if( pFile
->mmapSizeMax
>0 && nByte
>pFile
->mmapSize
){
3962 if( pFile
->szChunk
<=0 ){
3963 if( robust_ftruncate(pFile
->h
, nByte
) ){
3964 storeLastErrno(pFile
, errno
);
3965 return unixLogError(SQLITE_IOERR_TRUNCATE
, "ftruncate", pFile
->zPath
);
3969 rc
= unixMapfile(pFile
, nByte
);
3978 ** If *pArg is initially negative then this is a query. Set *pArg to
3979 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3981 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3983 static void unixModeBit(unixFile
*pFile
, unsigned char mask
, int *pArg
){
3985 *pArg
= (pFile
->ctrlFlags
& mask
)!=0;
3986 }else if( (*pArg
)==0 ){
3987 pFile
->ctrlFlags
&= ~mask
;
3989 pFile
->ctrlFlags
|= mask
;
3993 /* Forward declaration */
3994 static int unixGetTempname(int nBuf
, char *zBuf
);
3995 #ifndef SQLITE_OMIT_WAL
3996 static int unixFcntlExternalReader(unixFile
*, int*);
4000 ** Information and control of an open file handle.
4002 static int unixFileControl(sqlite3_file
*id
, int op
, void *pArg
){
4003 unixFile
*pFile
= (unixFile
*)id
;
4005 #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
4006 case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE
: {
4007 int rc
= osIoctl(pFile
->h
, F2FS_IOC_START_ATOMIC_WRITE
);
4008 return rc
? SQLITE_IOERR_BEGIN_ATOMIC
: SQLITE_OK
;
4010 case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE
: {
4011 int rc
= osIoctl(pFile
->h
, F2FS_IOC_COMMIT_ATOMIC_WRITE
);
4012 return rc
? SQLITE_IOERR_COMMIT_ATOMIC
: SQLITE_OK
;
4014 case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE
: {
4015 int rc
= osIoctl(pFile
->h
, F2FS_IOC_ABORT_VOLATILE_WRITE
);
4016 return rc
? SQLITE_IOERR_ROLLBACK_ATOMIC
: SQLITE_OK
;
4018 #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
4020 case SQLITE_FCNTL_LOCKSTATE
: {
4021 *(int*)pArg
= pFile
->eFileLock
;
4024 case SQLITE_FCNTL_LAST_ERRNO
: {
4025 *(int*)pArg
= pFile
->lastErrno
;
4028 case SQLITE_FCNTL_CHUNK_SIZE
: {
4029 pFile
->szChunk
= *(int *)pArg
;
4032 case SQLITE_FCNTL_SIZE_HINT
: {
4034 SimulateIOErrorBenign(1);
4035 rc
= fcntlSizeHint(pFile
, *(i64
*)pArg
);
4036 SimulateIOErrorBenign(0);
4039 case SQLITE_FCNTL_PERSIST_WAL
: {
4040 unixModeBit(pFile
, UNIXFILE_PERSIST_WAL
, (int*)pArg
);
4043 case SQLITE_FCNTL_POWERSAFE_OVERWRITE
: {
4044 unixModeBit(pFile
, UNIXFILE_PSOW
, (int*)pArg
);
4047 case SQLITE_FCNTL_VFSNAME
: {
4048 *(char**)pArg
= sqlite3_mprintf("%s", pFile
->pVfs
->zName
);
4051 case SQLITE_FCNTL_TEMPFILENAME
: {
4052 char *zTFile
= sqlite3_malloc64( pFile
->pVfs
->mxPathname
);
4054 unixGetTempname(pFile
->pVfs
->mxPathname
, zTFile
);
4055 *(char**)pArg
= zTFile
;
4059 case SQLITE_FCNTL_HAS_MOVED
: {
4060 *(int*)pArg
= fileHasMoved(pFile
);
4063 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
4064 case SQLITE_FCNTL_LOCK_TIMEOUT
: {
4065 int iOld
= pFile
->iBusyTimeout
;
4066 pFile
->iBusyTimeout
= *(int*)pArg
;
4071 #if SQLITE_MAX_MMAP_SIZE>0
4072 case SQLITE_FCNTL_MMAP_SIZE
: {
4073 i64 newLimit
= *(i64
*)pArg
;
4075 if( newLimit
>sqlite3GlobalConfig
.mxMmap
){
4076 newLimit
= sqlite3GlobalConfig
.mxMmap
;
4079 /* The value of newLimit may be eventually cast to (size_t) and passed
4080 ** to mmap(). Restrict its value to 2GB if (size_t) is not at least a
4082 if( newLimit
>0 && sizeof(size_t)<8 ){
4083 newLimit
= (newLimit
& 0x7FFFFFFF);
4086 *(i64
*)pArg
= pFile
->mmapSizeMax
;
4087 if( newLimit
>=0 && newLimit
!=pFile
->mmapSizeMax
&& pFile
->nFetchOut
==0 ){
4088 pFile
->mmapSizeMax
= newLimit
;
4089 if( pFile
->mmapSize
>0 ){
4090 unixUnmapfile(pFile
);
4091 rc
= unixMapfile(pFile
, -1);
4098 /* The pager calls this method to signal that it has done
4099 ** a rollback and that the database is therefore unchanged and
4100 ** it hence it is OK for the transaction change counter to be
4103 case SQLITE_FCNTL_DB_UNCHANGED
: {
4104 ((unixFile
*)id
)->dbUpdate
= 0;
4108 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
4109 case SQLITE_FCNTL_SET_LOCKPROXYFILE
:
4110 case SQLITE_FCNTL_GET_LOCKPROXYFILE
: {
4111 return proxyFileControl(id
,op
,pArg
);
4113 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
4115 case SQLITE_FCNTL_EXTERNAL_READER
: {
4116 #ifndef SQLITE_OMIT_WAL
4117 return unixFcntlExternalReader((unixFile
*)id
, (int*)pArg
);
4124 return SQLITE_NOTFOUND
;
4128 ** If pFd->sectorSize is non-zero when this function is called, it is a
4129 ** no-op. Otherwise, the values of pFd->sectorSize and
4130 ** pFd->deviceCharacteristics are set according to the file-system
4133 ** There are two versions of this function. One for QNX and one for all
4137 static void setDeviceCharacteristics(unixFile
*pFd
){
4138 assert( pFd
->deviceCharacteristics
==0 || pFd
->sectorSize
!=0 );
4139 if( pFd
->sectorSize
==0 ){
4140 #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
4144 /* Check for support for F2FS atomic batch writes. */
4145 res
= osIoctl(pFd
->h
, F2FS_IOC_GET_FEATURES
, &f
);
4146 if( res
==0 && (f
& F2FS_FEATURE_ATOMIC_WRITE
) ){
4147 pFd
->deviceCharacteristics
= SQLITE_IOCAP_BATCH_ATOMIC
;
4149 #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
4151 /* Set the POWERSAFE_OVERWRITE flag if requested. */
4152 if( pFd
->ctrlFlags
& UNIXFILE_PSOW
){
4153 pFd
->deviceCharacteristics
|= SQLITE_IOCAP_POWERSAFE_OVERWRITE
;
4156 pFd
->sectorSize
= SQLITE_DEFAULT_SECTOR_SIZE
;
4160 #include <sys/dcmd_blk.h>
4161 #include <sys/statvfs.h>
4162 static void setDeviceCharacteristics(unixFile
*pFile
){
4163 if( pFile
->sectorSize
== 0 ){
4164 struct statvfs fsInfo
;
4166 /* Set defaults for non-supported filesystems */
4167 pFile
->sectorSize
= SQLITE_DEFAULT_SECTOR_SIZE
;
4168 pFile
->deviceCharacteristics
= 0;
4169 if( fstatvfs(pFile
->h
, &fsInfo
) == -1 ) {
4173 if( !strcmp(fsInfo
.f_basetype
, "tmp") ) {
4174 pFile
->sectorSize
= fsInfo
.f_bsize
;
4175 pFile
->deviceCharacteristics
=
4176 SQLITE_IOCAP_ATOMIC4K
| /* All ram filesystem writes are atomic */
4177 SQLITE_IOCAP_SAFE_APPEND
| /* growing the file does not occur until
4178 ** the write succeeds */
4179 SQLITE_IOCAP_SEQUENTIAL
| /* The ram filesystem has no write behind
4180 ** so it is ordered */
4182 }else if( strstr(fsInfo
.f_basetype
, "etfs") ){
4183 pFile
->sectorSize
= fsInfo
.f_bsize
;
4184 pFile
->deviceCharacteristics
=
4185 /* etfs cluster size writes are atomic */
4186 (pFile
->sectorSize
/ 512 * SQLITE_IOCAP_ATOMIC512
) |
4187 SQLITE_IOCAP_SAFE_APPEND
| /* growing the file does not occur until
4188 ** the write succeeds */
4189 SQLITE_IOCAP_SEQUENTIAL
| /* The ram filesystem has no write behind
4190 ** so it is ordered */
4192 }else if( !strcmp(fsInfo
.f_basetype
, "qnx6") ){
4193 pFile
->sectorSize
= fsInfo
.f_bsize
;
4194 pFile
->deviceCharacteristics
=
4195 SQLITE_IOCAP_ATOMIC
| /* All filesystem writes are atomic */
4196 SQLITE_IOCAP_SAFE_APPEND
| /* growing the file does not occur until
4197 ** the write succeeds */
4198 SQLITE_IOCAP_SEQUENTIAL
| /* The ram filesystem has no write behind
4199 ** so it is ordered */
4201 }else if( !strcmp(fsInfo
.f_basetype
, "qnx4") ){
4202 pFile
->sectorSize
= fsInfo
.f_bsize
;
4203 pFile
->deviceCharacteristics
=
4204 /* full bitset of atomics from max sector size and smaller */
4205 ((pFile
->sectorSize
/ 512 * SQLITE_IOCAP_ATOMIC512
) << 1) - 2 |
4206 SQLITE_IOCAP_SEQUENTIAL
| /* The ram filesystem has no write behind
4207 ** so it is ordered */
4209 }else if( strstr(fsInfo
.f_basetype
, "dos") ){
4210 pFile
->sectorSize
= fsInfo
.f_bsize
;
4211 pFile
->deviceCharacteristics
=
4212 /* full bitset of atomics from max sector size and smaller */
4213 ((pFile
->sectorSize
/ 512 * SQLITE_IOCAP_ATOMIC512
) << 1) - 2 |
4214 SQLITE_IOCAP_SEQUENTIAL
| /* The ram filesystem has no write behind
4215 ** so it is ordered */
4218 pFile
->deviceCharacteristics
=
4219 SQLITE_IOCAP_ATOMIC512
| /* blocks are atomic */
4220 SQLITE_IOCAP_SAFE_APPEND
| /* growing the file does not occur until
4221 ** the write succeeds */
4225 /* Last chance verification. If the sector size isn't a multiple of 512
4226 ** then it isn't valid.*/
4227 if( pFile
->sectorSize
% 512 != 0 ){
4228 pFile
->deviceCharacteristics
= 0;
4229 pFile
->sectorSize
= SQLITE_DEFAULT_SECTOR_SIZE
;
4235 ** Return the sector size in bytes of the underlying block device for
4236 ** the specified file. This is almost always 512 bytes, but may be
4237 ** larger for some devices.
4239 ** SQLite code assumes this function cannot fail. It also assumes that
4240 ** if two files are created in the same file-system directory (i.e.
4241 ** a database and its journal file) that the sector size will be the
4244 static int unixSectorSize(sqlite3_file
*id
){
4245 unixFile
*pFd
= (unixFile
*)id
;
4246 setDeviceCharacteristics(pFd
);
4247 return pFd
->sectorSize
;
4251 ** Return the device characteristics for the file.
4253 ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
4254 ** However, that choice is controversial since technically the underlying
4255 ** file system does not always provide powersafe overwrites. (In other
4256 ** words, after a power-loss event, parts of the file that were never
4257 ** written might end up being altered.) However, non-PSOW behavior is very,
4258 ** very rare. And asserting PSOW makes a large reduction in the amount
4259 ** of required I/O for journaling, since a lot of padding is eliminated.
4260 ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
4261 ** available to turn it off and URI query parameter available to turn it off.
4263 static int unixDeviceCharacteristics(sqlite3_file
*id
){
4264 unixFile
*pFd
= (unixFile
*)id
;
4265 setDeviceCharacteristics(pFd
);
4266 return pFd
->deviceCharacteristics
;
4269 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
4272 ** Return the system page size.
4274 ** This function should not be called directly by other code in this file.
4275 ** Instead, it should be called via macro osGetpagesize().
4277 static int unixGetpagesize(void){
4280 #elif defined(_BSD_SOURCE)
4281 return getpagesize();
4283 return (int)sysconf(_SC_PAGESIZE
);
4287 #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
4289 #ifndef SQLITE_OMIT_WAL
4292 ** Object used to represent an shared memory buffer.
4294 ** When multiple threads all reference the same wal-index, each thread
4295 ** has its own unixShm object, but they all point to a single instance
4296 ** of this unixShmNode object. In other words, each wal-index is opened
4297 ** only once per process.
4299 ** Each unixShmNode object is connected to a single unixInodeInfo object.
4300 ** We could coalesce this object into unixInodeInfo, but that would mean
4301 ** every open file that does not use shared memory (in other words, most
4302 ** open files) would have to carry around this extra information. So
4303 ** the unixInodeInfo object contains a pointer to this unixShmNode object
4304 ** and the unixShmNode object is created only when needed.
4306 ** unixMutexHeld() must be true when creating or destroying
4307 ** this object or while reading or writing the following fields:
4311 ** The following fields are read-only after the object is created:
4316 ** Either unixShmNode.pShmMutex must be held or unixShmNode.nRef==0 and
4317 ** unixMutexHeld() is true when reading or writing any other field
4318 ** in this structure.
4320 struct unixShmNode
{
4321 unixInodeInfo
*pInode
; /* unixInodeInfo that owns this SHM node */
4322 sqlite3_mutex
*pShmMutex
; /* Mutex to access this object */
4323 char *zFilename
; /* Name of the mmapped file */
4324 int hShm
; /* Open file descriptor */
4325 int szRegion
; /* Size of shared-memory regions */
4326 u16 nRegion
; /* Size of array apRegion */
4327 u8 isReadonly
; /* True if read-only */
4328 u8 isUnlocked
; /* True if no DMS lock held */
4329 char **apRegion
; /* Array of mapped shared-memory regions */
4330 int nRef
; /* Number of unixShm objects pointing to this */
4331 unixShm
*pFirst
; /* All unixShm objects pointing to this */
4332 int aLock
[SQLITE_SHM_NLOCK
]; /* # shared locks on slot, -1==excl lock */
4334 u8 exclMask
; /* Mask of exclusive locks held */
4335 u8 sharedMask
; /* Mask of shared locks held */
4336 u8 nextShmId
; /* Next available unixShm.id value */
4341 ** Structure used internally by this VFS to record the state of an
4342 ** open shared memory connection.
4344 ** The following fields are initialized when this object is created and
4345 ** are read-only thereafter:
4350 ** All other fields are read/write. The unixShm.pShmNode->pShmMutex must
4351 ** be held while accessing any read/write fields.
4354 unixShmNode
*pShmNode
; /* The underlying unixShmNode object */
4355 unixShm
*pNext
; /* Next unixShm with the same unixShmNode */
4356 u8 hasMutex
; /* True if holding the unixShmNode->pShmMutex */
4357 u8 id
; /* Id of this connection within its unixShmNode */
4358 u16 sharedMask
; /* Mask of shared locks held */
4359 u16 exclMask
; /* Mask of exclusive locks held */
4363 ** Constants used for locking
4365 #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
4366 #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
4369 ** Use F_GETLK to check whether or not there are any readers with open
4370 ** wal-mode transactions in other processes on database file pFile. If
4371 ** no error occurs, return SQLITE_OK and set (*piOut) to 1 if there are
4372 ** such transactions, or 0 otherwise. If an error occurs, return an
4373 ** SQLite error code. The final value of *piOut is undefined in this
4376 static int unixFcntlExternalReader(unixFile
*pFile
, int *piOut
){
4380 unixShmNode
*pShmNode
= pFile
->pShm
->pShmNode
;
4383 memset(&f
, 0, sizeof(f
));
4385 f
.l_whence
= SEEK_SET
;
4386 f
.l_start
= UNIX_SHM_BASE
+ 3;
4387 f
.l_len
= SQLITE_SHM_NLOCK
- 3;
4389 sqlite3_mutex_enter(pShmNode
->pShmMutex
);
4390 if( osFcntl(pShmNode
->hShm
, F_GETLK
, &f
)<0 ){
4391 rc
= SQLITE_IOERR_LOCK
;
4393 *piOut
= (f
.l_type
!=F_UNLCK
);
4395 sqlite3_mutex_leave(pShmNode
->pShmMutex
);
4403 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
4405 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4408 static int unixShmSystemLock(
4409 unixFile
*pFile
, /* Open connection to the WAL file */
4410 int lockType
, /* F_UNLCK, F_RDLCK, or F_WRLCK */
4411 int ofst
, /* First byte of the locking range */
4412 int n
/* Number of bytes to lock */
4414 unixShmNode
*pShmNode
; /* Apply locks to this open shared-memory segment */
4415 struct flock f
; /* The posix advisory locking structure */
4416 int rc
= SQLITE_OK
; /* Result code form fcntl() */
4418 /* Access to the unixShmNode object is serialized by the caller */
4419 pShmNode
= pFile
->pInode
->pShmNode
;
4420 assert( pShmNode
->nRef
==0 || sqlite3_mutex_held(pShmNode
->pShmMutex
) );
4421 assert( pShmNode
->nRef
>0 || unixMutexHeld() );
4423 /* Shared locks never span more than one byte */
4424 assert( n
==1 || lockType
!=F_RDLCK
);
4426 /* Locks are within range */
4427 assert( n
>=1 && n
<=SQLITE_SHM_NLOCK
);
4429 if( pShmNode
->hShm
>=0 ){
4431 /* Initialize the locking parameters */
4432 f
.l_type
= lockType
;
4433 f
.l_whence
= SEEK_SET
;
4436 res
= osSetPosixAdvisoryLock(pShmNode
->hShm
, &f
, pFile
);
4438 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
4439 rc
= (pFile
->iBusyTimeout
? SQLITE_BUSY_TIMEOUT
: SQLITE_BUSY
);
4446 /* Update the global lock state and do debug tracing */
4449 OSTRACE(("SHM-LOCK "));
4450 mask
= ofst
>31 ? 0xffff : (1<<(ofst
+n
)) - (1<<ofst
);
4451 if( rc
==SQLITE_OK
){
4452 if( lockType
==F_UNLCK
){
4453 OSTRACE(("unlock %d ok", ofst
));
4454 pShmNode
->exclMask
&= ~mask
;
4455 pShmNode
->sharedMask
&= ~mask
;
4456 }else if( lockType
==F_RDLCK
){
4457 OSTRACE(("read-lock %d ok", ofst
));
4458 pShmNode
->exclMask
&= ~mask
;
4459 pShmNode
->sharedMask
|= mask
;
4461 assert( lockType
==F_WRLCK
);
4462 OSTRACE(("write-lock %d ok", ofst
));
4463 pShmNode
->exclMask
|= mask
;
4464 pShmNode
->sharedMask
&= ~mask
;
4467 if( lockType
==F_UNLCK
){
4468 OSTRACE(("unlock %d failed", ofst
));
4469 }else if( lockType
==F_RDLCK
){
4470 OSTRACE(("read-lock failed"));
4472 assert( lockType
==F_WRLCK
);
4473 OSTRACE(("write-lock %d failed", ofst
));
4476 OSTRACE((" - afterwards %03x,%03x\n",
4477 pShmNode
->sharedMask
, pShmNode
->exclMask
));
4485 ** Return the minimum number of 32KB shm regions that should be mapped at
4486 ** a time, assuming that each mapping must be an integer multiple of the
4487 ** current system page-size.
4489 ** Usually, this is 1. The exception seems to be systems that are configured
4490 ** to use 64KB pages - in this case each mapping must cover at least two
4493 static int unixShmRegionPerMap(void){
4494 int shmsz
= 32*1024; /* SHM region size */
4495 int pgsz
= osGetpagesize(); /* System page size */
4496 assert( ((pgsz
-1)&pgsz
)==0 ); /* Page size must be a power of 2 */
4497 if( pgsz
<shmsz
) return 1;
4502 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
4504 ** This is not a VFS shared-memory method; it is a utility function called
4505 ** by VFS shared-memory methods.
4507 static void unixShmPurge(unixFile
*pFd
){
4508 unixShmNode
*p
= pFd
->pInode
->pShmNode
;
4509 assert( unixMutexHeld() );
4510 if( p
&& ALWAYS(p
->nRef
==0) ){
4511 int nShmPerMap
= unixShmRegionPerMap();
4513 assert( p
->pInode
==pFd
->pInode
);
4514 sqlite3_mutex_free(p
->pShmMutex
);
4515 for(i
=0; i
<p
->nRegion
; i
+=nShmPerMap
){
4517 osMunmap(p
->apRegion
[i
], p
->szRegion
);
4519 sqlite3_free(p
->apRegion
[i
]);
4522 sqlite3_free(p
->apRegion
);
4524 robust_close(pFd
, p
->hShm
, __LINE__
);
4527 p
->pInode
->pShmNode
= 0;
4533 ** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
4534 ** take it now. Return SQLITE_OK if successful, or an SQLite error
4537 ** If the DMS cannot be locked because this is a readonly_shm=1
4538 ** connection and no other process already holds a lock, return
4539 ** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
4541 static int unixLockSharedMemory(unixFile
*pDbFd
, unixShmNode
*pShmNode
){
4545 /* Use F_GETLK to determine the locks other processes are holding
4546 ** on the DMS byte. If it indicates that another process is holding
4547 ** a SHARED lock, then this process may also take a SHARED lock
4548 ** and proceed with opening the *-shm file.
4550 ** Or, if no other process is holding any lock, then this process
4551 ** is the first to open it. In this case take an EXCLUSIVE lock on the
4552 ** DMS byte and truncate the *-shm file to zero bytes in size. Then
4553 ** downgrade to a SHARED lock on the DMS byte.
4555 ** If another process is holding an EXCLUSIVE lock on the DMS byte,
4556 ** return SQLITE_BUSY to the caller (it will try again). An earlier
4557 ** version of this code attempted the SHARED lock at this point. But
4558 ** this introduced a subtle race condition: if the process holding
4559 ** EXCLUSIVE failed just before truncating the *-shm file, then this
4560 ** process might open and use the *-shm file without truncating it.
4561 ** And if the *-shm file has been corrupted by a power failure or
4562 ** system crash, the database itself may also become corrupt. */
4563 lock
.l_whence
= SEEK_SET
;
4564 lock
.l_start
= UNIX_SHM_DMS
;
4566 lock
.l_type
= F_WRLCK
;
4567 if( osFcntl(pShmNode
->hShm
, F_GETLK
, &lock
)!=0 ) {
4568 rc
= SQLITE_IOERR_LOCK
;
4569 }else if( lock
.l_type
==F_UNLCK
){
4570 if( pShmNode
->isReadonly
){
4571 pShmNode
->isUnlocked
= 1;
4572 rc
= SQLITE_READONLY_CANTINIT
;
4574 rc
= unixShmSystemLock(pDbFd
, F_WRLCK
, UNIX_SHM_DMS
, 1);
4575 /* The first connection to attach must truncate the -shm file. We
4576 ** truncate to 3 bytes (an arbitrary small number, less than the
4577 ** -shm header size) rather than 0 as a system debugging aid, to
4578 ** help detect if a -shm file truncation is legitimate or is the work
4579 ** or a rogue process. */
4580 if( rc
==SQLITE_OK
&& robust_ftruncate(pShmNode
->hShm
, 3) ){
4581 rc
= unixLogError(SQLITE_IOERR_SHMOPEN
,"ftruncate",pShmNode
->zFilename
);
4584 }else if( lock
.l_type
==F_WRLCK
){
4588 if( rc
==SQLITE_OK
){
4589 assert( lock
.l_type
==F_UNLCK
|| lock
.l_type
==F_RDLCK
);
4590 rc
= unixShmSystemLock(pDbFd
, F_RDLCK
, UNIX_SHM_DMS
, 1);
4596 ** Open a shared-memory area associated with open database file pDbFd.
4597 ** This particular implementation uses mmapped files.
4599 ** The file used to implement shared-memory is in the same directory
4600 ** as the open database file and has the same name as the open database
4601 ** file with the "-shm" suffix added. For example, if the database file
4602 ** is "/home/user1/config.db" then the file that is created and mmapped
4603 ** for shared memory will be called "/home/user1/config.db-shm".
4605 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
4606 ** some other tmpfs mount. But if a file in a different directory
4607 ** from the database file is used, then differing access permissions
4608 ** or a chroot() might cause two different processes on the same
4609 ** database to end up using different files for shared memory -
4610 ** meaning that their memory would not really be shared - resulting
4611 ** in database corruption. Nevertheless, this tmpfs file usage
4612 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4613 ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4614 ** option results in an incompatible build of SQLite; builds of SQLite
4615 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4616 ** same database file at the same time, database corruption will likely
4617 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4618 ** "unsupported" and may go away in a future SQLite release.
4620 ** When opening a new shared-memory file, if no other instances of that
4621 ** file are currently open, in this process or in other processes, then
4622 ** the file must be truncated to zero length or have its header cleared.
4624 ** If the original database file (pDbFd) is using the "unix-excl" VFS
4625 ** that means that an exclusive lock is held on the database file and
4626 ** that no other processes are able to read or write the database. In
4627 ** that case, we do not really need shared memory. No shared memory
4628 ** file is created. The shared memory will be simulated with heap memory.
4630 static int unixOpenSharedMemory(unixFile
*pDbFd
){
4631 struct unixShm
*p
= 0; /* The connection to be opened */
4632 struct unixShmNode
*pShmNode
; /* The underlying mmapped file */
4633 int rc
= SQLITE_OK
; /* Result code */
4634 unixInodeInfo
*pInode
; /* The inode of fd */
4635 char *zShm
; /* Name of the file used for SHM */
4636 int nShmFilename
; /* Size of the SHM filename in bytes */
4638 /* Allocate space for the new unixShm object. */
4639 p
= sqlite3_malloc64( sizeof(*p
) );
4640 if( p
==0 ) return SQLITE_NOMEM_BKPT
;
4641 memset(p
, 0, sizeof(*p
));
4642 assert( pDbFd
->pShm
==0 );
4644 /* Check to see if a unixShmNode object already exists. Reuse an existing
4645 ** one if present. Create a new one if necessary.
4647 assert( unixFileMutexNotheld(pDbFd
) );
4649 pInode
= pDbFd
->pInode
;
4650 pShmNode
= pInode
->pShmNode
;
4652 struct stat sStat
; /* fstat() info for database file */
4653 #ifndef SQLITE_SHM_DIRECTORY
4654 const char *zBasePath
= pDbFd
->zPath
;
4657 /* Call fstat() to figure out the permissions on the database file. If
4658 ** a new *-shm file is created, an attempt will be made to create it
4659 ** with the same permissions.
4661 if( osFstat(pDbFd
->h
, &sStat
) ){
4662 rc
= SQLITE_IOERR_FSTAT
;
4666 #ifdef SQLITE_SHM_DIRECTORY
4667 nShmFilename
= sizeof(SQLITE_SHM_DIRECTORY
) + 31;
4669 nShmFilename
= 6 + (int)strlen(zBasePath
);
4671 pShmNode
= sqlite3_malloc64( sizeof(*pShmNode
) + nShmFilename
);
4673 rc
= SQLITE_NOMEM_BKPT
;
4676 memset(pShmNode
, 0, sizeof(*pShmNode
)+nShmFilename
);
4677 zShm
= pShmNode
->zFilename
= (char*)&pShmNode
[1];
4678 #ifdef SQLITE_SHM_DIRECTORY
4679 sqlite3_snprintf(nShmFilename
, zShm
,
4680 SQLITE_SHM_DIRECTORY
"/sqlite-shm-%x-%x",
4681 (u32
)sStat
.st_ino
, (u32
)sStat
.st_dev
);
4683 sqlite3_snprintf(nShmFilename
, zShm
, "%s-shm", zBasePath
);
4684 sqlite3FileSuffix3(pDbFd
->zPath
, zShm
);
4686 pShmNode
->hShm
= -1;
4687 pDbFd
->pInode
->pShmNode
= pShmNode
;
4688 pShmNode
->pInode
= pDbFd
->pInode
;
4689 if( sqlite3GlobalConfig
.bCoreMutex
){
4690 pShmNode
->pShmMutex
= sqlite3_mutex_alloc(SQLITE_MUTEX_FAST
);
4691 if( pShmNode
->pShmMutex
==0 ){
4692 rc
= SQLITE_NOMEM_BKPT
;
4697 if( pInode
->bProcessLock
==0 ){
4698 if( 0==sqlite3_uri_boolean(pDbFd
->zPath
, "readonly_shm", 0) ){
4699 pShmNode
->hShm
= robust_open(zShm
, O_RDWR
|O_CREAT
|O_NOFOLLOW
,
4700 (sStat
.st_mode
&0777));
4702 if( pShmNode
->hShm
<0 ){
4703 pShmNode
->hShm
= robust_open(zShm
, O_RDONLY
|O_NOFOLLOW
,
4704 (sStat
.st_mode
&0777));
4705 if( pShmNode
->hShm
<0 ){
4706 rc
= unixLogError(SQLITE_CANTOPEN_BKPT
, "open", zShm
);
4709 pShmNode
->isReadonly
= 1;
4712 /* If this process is running as root, make sure that the SHM file
4713 ** is owned by the same user that owns the original database. Otherwise,
4714 ** the original owner will not be able to connect.
4716 robustFchown(pShmNode
->hShm
, sStat
.st_uid
, sStat
.st_gid
);
4718 rc
= unixLockSharedMemory(pDbFd
, pShmNode
);
4719 if( rc
!=SQLITE_OK
&& rc
!=SQLITE_READONLY_CANTINIT
) goto shm_open_err
;
4723 /* Make the new connection a child of the unixShmNode */
4724 p
->pShmNode
= pShmNode
;
4726 p
->id
= pShmNode
->nextShmId
++;
4732 /* The reference count on pShmNode has already been incremented under
4733 ** the cover of the unixEnterMutex() mutex and the pointer from the
4734 ** new (struct unixShm) object to the pShmNode has been set. All that is
4735 ** left to do is to link the new object into the linked list starting
4736 ** at pShmNode->pFirst. This must be done while holding the
4737 ** pShmNode->pShmMutex.
4739 sqlite3_mutex_enter(pShmNode
->pShmMutex
);
4740 p
->pNext
= pShmNode
->pFirst
;
4741 pShmNode
->pFirst
= p
;
4742 sqlite3_mutex_leave(pShmNode
->pShmMutex
);
4745 /* Jump here on any error */
4747 unixShmPurge(pDbFd
); /* This call frees pShmNode if required */
4754 ** This function is called to obtain a pointer to region iRegion of the
4755 ** shared-memory associated with the database file fd. Shared-memory regions
4756 ** are numbered starting from zero. Each shared-memory region is szRegion
4759 ** If an error occurs, an error code is returned and *pp is set to NULL.
4761 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4762 ** region has not been allocated (by any client, including one running in a
4763 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4764 ** bExtend is non-zero and the requested shared-memory region has not yet
4765 ** been allocated, it is allocated by this function.
4767 ** If the shared-memory region has already been allocated or is allocated by
4768 ** this call as described above, then it is mapped into this processes
4769 ** address space (if it is not already), *pp is set to point to the mapped
4770 ** memory and SQLITE_OK returned.
4772 static int unixShmMap(
4773 sqlite3_file
*fd
, /* Handle open on database file */
4774 int iRegion
, /* Region to retrieve */
4775 int szRegion
, /* Size of regions */
4776 int bExtend
, /* True to extend file if necessary */
4777 void volatile **pp
/* OUT: Mapped memory */
4779 unixFile
*pDbFd
= (unixFile
*)fd
;
4781 unixShmNode
*pShmNode
;
4783 int nShmPerMap
= unixShmRegionPerMap();
4786 /* If the shared-memory file has not yet been opened, open it now. */
4787 if( pDbFd
->pShm
==0 ){
4788 rc
= unixOpenSharedMemory(pDbFd
);
4789 if( rc
!=SQLITE_OK
) return rc
;
4793 pShmNode
= p
->pShmNode
;
4794 sqlite3_mutex_enter(pShmNode
->pShmMutex
);
4795 if( pShmNode
->isUnlocked
){
4796 rc
= unixLockSharedMemory(pDbFd
, pShmNode
);
4797 if( rc
!=SQLITE_OK
) goto shmpage_out
;
4798 pShmNode
->isUnlocked
= 0;
4800 assert( szRegion
==pShmNode
->szRegion
|| pShmNode
->nRegion
==0 );
4801 assert( pShmNode
->pInode
==pDbFd
->pInode
);
4802 assert( pShmNode
->hShm
>=0 || pDbFd
->pInode
->bProcessLock
==1 );
4803 assert( pShmNode
->hShm
<0 || pDbFd
->pInode
->bProcessLock
==0 );
4805 /* Minimum number of regions required to be mapped. */
4806 nReqRegion
= ((iRegion
+nShmPerMap
) / nShmPerMap
) * nShmPerMap
;
4808 if( pShmNode
->nRegion
<nReqRegion
){
4809 char **apNew
; /* New apRegion[] array */
4810 int nByte
= nReqRegion
*szRegion
; /* Minimum required file size */
4811 struct stat sStat
; /* Used by fstat() */
4813 pShmNode
->szRegion
= szRegion
;
4815 if( pShmNode
->hShm
>=0 ){
4816 /* The requested region is not mapped into this processes address space.
4817 ** Check to see if it has been allocated (i.e. if the wal-index file is
4818 ** large enough to contain the requested region).
4820 if( osFstat(pShmNode
->hShm
, &sStat
) ){
4821 rc
= SQLITE_IOERR_SHMSIZE
;
4825 if( sStat
.st_size
<nByte
){
4826 /* The requested memory region does not exist. If bExtend is set to
4827 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
4833 /* Alternatively, if bExtend is true, extend the file. Do this by
4834 ** writing a single byte to the end of each (OS) page being
4835 ** allocated or extended. Technically, we need only write to the
4836 ** last page in order to extend the file. But writing to all new
4837 ** pages forces the OS to allocate them immediately, which reduces
4838 ** the chances of SIGBUS while accessing the mapped region later on.
4841 static const int pgsz
= 4096;
4844 /* Write to the last byte of each newly allocated or extended page */
4845 assert( (nByte
% pgsz
)==0 );
4846 for(iPg
=(sStat
.st_size
/pgsz
); iPg
<(nByte
/pgsz
); iPg
++){
4848 if( seekAndWriteFd(pShmNode
->hShm
, iPg
*pgsz
+ pgsz
-1,"",1,&x
)!=1 ){
4849 const char *zFile
= pShmNode
->zFilename
;
4850 rc
= unixLogError(SQLITE_IOERR_SHMSIZE
, "write", zFile
);
4858 /* Map the requested memory region into this processes address space. */
4859 apNew
= (char **)sqlite3_realloc(
4860 pShmNode
->apRegion
, nReqRegion
*sizeof(char *)
4863 rc
= SQLITE_IOERR_NOMEM_BKPT
;
4866 pShmNode
->apRegion
= apNew
;
4867 while( pShmNode
->nRegion
<nReqRegion
){
4868 int nMap
= szRegion
*nShmPerMap
;
4871 if( pShmNode
->hShm
>=0 ){
4872 pMem
= osMmap(0, nMap
,
4873 pShmNode
->isReadonly
? PROT_READ
: PROT_READ
|PROT_WRITE
,
4874 MAP_SHARED
, pShmNode
->hShm
, szRegion
*(i64
)pShmNode
->nRegion
4876 if( pMem
==MAP_FAILED
){
4877 rc
= unixLogError(SQLITE_IOERR_SHMMAP
, "mmap", pShmNode
->zFilename
);
4881 pMem
= sqlite3_malloc64(nMap
);
4883 rc
= SQLITE_NOMEM_BKPT
;
4886 memset(pMem
, 0, nMap
);
4889 for(i
=0; i
<nShmPerMap
; i
++){
4890 pShmNode
->apRegion
[pShmNode
->nRegion
+i
] = &((char*)pMem
)[szRegion
*i
];
4892 pShmNode
->nRegion
+= nShmPerMap
;
4897 if( pShmNode
->nRegion
>iRegion
){
4898 *pp
= pShmNode
->apRegion
[iRegion
];
4902 if( pShmNode
->isReadonly
&& rc
==SQLITE_OK
) rc
= SQLITE_READONLY
;
4903 sqlite3_mutex_leave(pShmNode
->pShmMutex
);
4908 ** Check that the pShmNode->aLock[] array comports with the locking bitmasks
4909 ** held by each client. Return true if it does, or false otherwise. This
4910 ** is to be used in an assert(). e.g.
4912 ** assert( assertLockingArrayOk(pShmNode) );
4915 static int assertLockingArrayOk(unixShmNode
*pShmNode
){
4917 int aLock
[SQLITE_SHM_NLOCK
];
4918 assert( sqlite3_mutex_held(pShmNode
->pShmMutex
) );
4920 memset(aLock
, 0, sizeof(aLock
));
4921 for(pX
=pShmNode
->pFirst
; pX
; pX
=pX
->pNext
){
4923 for(i
=0; i
<SQLITE_SHM_NLOCK
; i
++){
4924 if( pX
->exclMask
& (1<<i
) ){
4925 assert( aLock
[i
]==0 );
4927 }else if( pX
->sharedMask
& (1<<i
) ){
4928 assert( aLock
[i
]>=0 );
4934 assert( 0==memcmp(pShmNode
->aLock
, aLock
, sizeof(aLock
)) );
4935 return (memcmp(pShmNode
->aLock
, aLock
, sizeof(aLock
))==0);
4940 ** Change the lock state for a shared-memory segment.
4942 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4943 ** different here than in posix. In xShmLock(), one can go from unlocked
4944 ** to shared and back or from unlocked to exclusive and back. But one may
4945 ** not go from shared to exclusive or from exclusive to shared.
4947 static int unixShmLock(
4948 sqlite3_file
*fd
, /* Database file holding the shared memory */
4949 int ofst
, /* First lock to acquire or release */
4950 int n
, /* Number of locks to acquire or release */
4951 int flags
/* What to do with the lock */
4953 unixFile
*pDbFd
= (unixFile
*)fd
; /* Connection holding shared memory */
4954 unixShm
*p
; /* The shared memory being locked */
4955 unixShmNode
*pShmNode
; /* The underlying file iNode */
4956 int rc
= SQLITE_OK
; /* Result code */
4957 u16 mask
; /* Mask of locks to take or release */
4961 if( p
==0 ) return SQLITE_IOERR_SHMLOCK
;
4962 pShmNode
= p
->pShmNode
;
4963 if( NEVER(pShmNode
==0) ) return SQLITE_IOERR_SHMLOCK
;
4964 aLock
= pShmNode
->aLock
;
4966 assert( pShmNode
==pDbFd
->pInode
->pShmNode
);
4967 assert( pShmNode
->pInode
==pDbFd
->pInode
);
4968 assert( ofst
>=0 && ofst
+n
<=SQLITE_SHM_NLOCK
);
4970 assert( flags
==(SQLITE_SHM_LOCK
| SQLITE_SHM_SHARED
)
4971 || flags
==(SQLITE_SHM_LOCK
| SQLITE_SHM_EXCLUSIVE
)
4972 || flags
==(SQLITE_SHM_UNLOCK
| SQLITE_SHM_SHARED
)
4973 || flags
==(SQLITE_SHM_UNLOCK
| SQLITE_SHM_EXCLUSIVE
) );
4974 assert( n
==1 || (flags
& SQLITE_SHM_EXCLUSIVE
)!=0 );
4975 assert( pShmNode
->hShm
>=0 || pDbFd
->pInode
->bProcessLock
==1 );
4976 assert( pShmNode
->hShm
<0 || pDbFd
->pInode
->bProcessLock
==0 );
4978 /* Check that, if this to be a blocking lock, no locks that occur later
4979 ** in the following list than the lock being obtained are already held:
4981 ** 1. Checkpointer lock (ofst==1).
4982 ** 2. Write lock (ofst==0).
4983 ** 3. Read locks (ofst>=3 && ofst<SQLITE_SHM_NLOCK).
4985 ** In other words, if this is a blocking lock, none of the locks that
4986 ** occur later in the above list than the lock being obtained may be
4989 ** It is not permitted to block on the RECOVER lock.
4991 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
4992 assert( (flags
& SQLITE_SHM_UNLOCK
) || pDbFd
->iBusyTimeout
==0 || (
4993 (ofst
!=2) /* not RECOVER */
4994 && (ofst
!=1 || (p
->exclMask
|p
->sharedMask
)==0)
4995 && (ofst
!=0 || (p
->exclMask
|p
->sharedMask
)<3)
4996 && (ofst
<3 || (p
->exclMask
|p
->sharedMask
)<(1<<ofst
))
5000 mask
= (1<<(ofst
+n
)) - (1<<ofst
);
5001 assert( n
>1 || mask
==(1<<ofst
) );
5002 sqlite3_mutex_enter(pShmNode
->pShmMutex
);
5003 assert( assertLockingArrayOk(pShmNode
) );
5004 if( flags
& SQLITE_SHM_UNLOCK
){
5005 if( (p
->exclMask
|p
->sharedMask
) & mask
){
5009 for(ii
=ofst
; ii
<ofst
+n
; ii
++){
5010 if( aLock
[ii
]>((p
->sharedMask
& (1<<ii
)) ? 1 : 0) ){
5016 rc
= unixShmSystemLock(pDbFd
, F_UNLCK
, ofst
+UNIX_SHM_BASE
, n
);
5017 if( rc
==SQLITE_OK
){
5018 memset(&aLock
[ofst
], 0, sizeof(int)*n
);
5020 }else if( ALWAYS(p
->sharedMask
& (1<<ofst
)) ){
5021 assert( n
==1 && aLock
[ofst
]>1 );
5025 /* Undo the local locks */
5026 if( rc
==SQLITE_OK
){
5027 p
->exclMask
&= ~mask
;
5028 p
->sharedMask
&= ~mask
;
5031 }else if( flags
& SQLITE_SHM_SHARED
){
5033 assert( (p
->exclMask
& (1<<ofst
))==0 );
5034 if( (p
->sharedMask
& mask
)==0 ){
5035 if( aLock
[ofst
]<0 ){
5037 }else if( aLock
[ofst
]==0 ){
5038 rc
= unixShmSystemLock(pDbFd
, F_RDLCK
, ofst
+UNIX_SHM_BASE
, n
);
5041 /* Get the local shared locks */
5042 if( rc
==SQLITE_OK
){
5043 p
->sharedMask
|= mask
;
5048 /* Make sure no sibling connections hold locks that will block this
5049 ** lock. If any do, return SQLITE_BUSY right away. */
5051 for(ii
=ofst
; ii
<ofst
+n
; ii
++){
5052 assert( (p
->sharedMask
& mask
)==0 );
5053 if( ALWAYS((p
->exclMask
& (1<<ii
))==0) && aLock
[ii
] ){
5059 /* Get the exclusive locks at the system level. Then if successful
5060 ** also update the in-memory values. */
5061 if( rc
==SQLITE_OK
){
5062 rc
= unixShmSystemLock(pDbFd
, F_WRLCK
, ofst
+UNIX_SHM_BASE
, n
);
5063 if( rc
==SQLITE_OK
){
5064 assert( (p
->sharedMask
& mask
)==0 );
5065 p
->exclMask
|= mask
;
5066 for(ii
=ofst
; ii
<ofst
+n
; ii
++){
5072 assert( assertLockingArrayOk(pShmNode
) );
5073 sqlite3_mutex_leave(pShmNode
->pShmMutex
);
5074 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
5075 p
->id
, osGetpid(0), p
->sharedMask
, p
->exclMask
));
5080 ** Implement a memory barrier or memory fence on shared memory.
5082 ** All loads and stores begun before the barrier must complete before
5083 ** any load or store begun after the barrier.
5085 static void unixShmBarrier(
5086 sqlite3_file
*fd
/* Database file holding the shared memory */
5088 UNUSED_PARAMETER(fd
);
5089 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
5090 assert( fd
->pMethods
->xLock
==nolockLock
5091 || unixFileMutexNotheld((unixFile
*)fd
)
5093 unixEnterMutex(); /* Also mutex, for redundancy */
5098 ** Close a connection to shared-memory. Delete the underlying
5099 ** storage if deleteFlag is true.
5101 ** If there is no shared memory associated with the connection then this
5102 ** routine is a harmless no-op.
5104 static int unixShmUnmap(
5105 sqlite3_file
*fd
, /* The underlying database file */
5106 int deleteFlag
/* Delete shared-memory if true */
5108 unixShm
*p
; /* The connection to be closed */
5109 unixShmNode
*pShmNode
; /* The underlying shared-memory file */
5110 unixShm
**pp
; /* For looping over sibling connections */
5111 unixFile
*pDbFd
; /* The underlying database file */
5113 pDbFd
= (unixFile
*)fd
;
5115 if( p
==0 ) return SQLITE_OK
;
5116 pShmNode
= p
->pShmNode
;
5118 assert( pShmNode
==pDbFd
->pInode
->pShmNode
);
5119 assert( pShmNode
->pInode
==pDbFd
->pInode
);
5121 /* Remove connection p from the set of connections associated
5123 sqlite3_mutex_enter(pShmNode
->pShmMutex
);
5124 for(pp
=&pShmNode
->pFirst
; (*pp
)!=p
; pp
= &(*pp
)->pNext
){}
5127 /* Free the connection p */
5130 sqlite3_mutex_leave(pShmNode
->pShmMutex
);
5132 /* If pShmNode->nRef has reached 0, then close the underlying
5133 ** shared-memory file, too */
5134 assert( unixFileMutexNotheld(pDbFd
) );
5136 assert( pShmNode
->nRef
>0 );
5138 if( pShmNode
->nRef
==0 ){
5139 if( deleteFlag
&& pShmNode
->hShm
>=0 ){
5140 osUnlink(pShmNode
->zFilename
);
5142 unixShmPurge(pDbFd
);
5151 # define unixShmMap 0
5152 # define unixShmLock 0
5153 # define unixShmBarrier 0
5154 # define unixShmUnmap 0
5155 #endif /* #ifndef SQLITE_OMIT_WAL */
5157 #if SQLITE_MAX_MMAP_SIZE>0
5159 ** If it is currently memory mapped, unmap file pFd.
5161 static void unixUnmapfile(unixFile
*pFd
){
5162 assert( pFd
->nFetchOut
==0 );
5163 if( pFd
->pMapRegion
){
5164 osMunmap(pFd
->pMapRegion
, pFd
->mmapSizeActual
);
5165 pFd
->pMapRegion
= 0;
5167 pFd
->mmapSizeActual
= 0;
5172 ** Attempt to set the size of the memory mapping maintained by file
5173 ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
5175 ** If successful, this function sets the following variables:
5177 ** unixFile.pMapRegion
5178 ** unixFile.mmapSize
5179 ** unixFile.mmapSizeActual
5181 ** If unsuccessful, an error message is logged via sqlite3_log() and
5182 ** the three variables above are zeroed. In this case SQLite should
5183 ** continue accessing the database using the xRead() and xWrite()
5186 static void unixRemapfile(
5187 unixFile
*pFd
, /* File descriptor object */
5188 i64 nNew
/* Required mapping size */
5190 const char *zErr
= "mmap";
5191 int h
= pFd
->h
; /* File descriptor open on db file */
5192 u8
*pOrig
= (u8
*)pFd
->pMapRegion
; /* Pointer to current file mapping */
5193 i64 nOrig
= pFd
->mmapSizeActual
; /* Size of pOrig region in bytes */
5194 u8
*pNew
= 0; /* Location of new mapping */
5195 int flags
= PROT_READ
; /* Flags to pass to mmap() */
5197 assert( pFd
->nFetchOut
==0 );
5198 assert( nNew
>pFd
->mmapSize
);
5199 assert( nNew
<=pFd
->mmapSizeMax
);
5201 assert( pFd
->mmapSizeActual
>=pFd
->mmapSize
);
5202 assert( MAP_FAILED
!=0 );
5204 #ifdef SQLITE_MMAP_READWRITE
5205 if( (pFd
->ctrlFlags
& UNIXFILE_RDONLY
)==0 ) flags
|= PROT_WRITE
;
5210 i64 nReuse
= pFd
->mmapSize
;
5212 const int szSyspage
= osGetpagesize();
5213 i64 nReuse
= (pFd
->mmapSize
& ~(szSyspage
-1));
5215 u8
*pReq
= &pOrig
[nReuse
];
5217 /* Unmap any pages of the existing mapping that cannot be reused. */
5218 if( nReuse
!=nOrig
){
5219 osMunmap(pReq
, nOrig
-nReuse
);
5223 pNew
= osMremap(pOrig
, nReuse
, nNew
, MREMAP_MAYMOVE
);
5226 pNew
= osMmap(pReq
, nNew
-nReuse
, flags
, MAP_SHARED
, h
, nReuse
);
5227 if( pNew
!=MAP_FAILED
){
5229 osMunmap(pNew
, nNew
- nReuse
);
5237 /* The attempt to extend the existing mapping failed. Free it. */
5238 if( pNew
==MAP_FAILED
|| pNew
==0 ){
5239 osMunmap(pOrig
, nReuse
);
5243 /* If pNew is still NULL, try to create an entirely new mapping. */
5245 pNew
= osMmap(0, nNew
, flags
, MAP_SHARED
, h
, 0);
5248 if( pNew
==MAP_FAILED
){
5251 unixLogError(SQLITE_OK
, zErr
, pFd
->zPath
);
5253 /* If the mmap() above failed, assume that all subsequent mmap() calls
5254 ** will probably fail too. Fall back to using xRead/xWrite exclusively
5256 pFd
->mmapSizeMax
= 0;
5258 pFd
->pMapRegion
= (void *)pNew
;
5259 pFd
->mmapSize
= pFd
->mmapSizeActual
= nNew
;
5263 ** Memory map or remap the file opened by file-descriptor pFd (if the file
5264 ** is already mapped, the existing mapping is replaced by the new). Or, if
5265 ** there already exists a mapping for this file, and there are still
5266 ** outstanding xFetch() references to it, this function is a no-op.
5268 ** If parameter nByte is non-negative, then it is the requested size of
5269 ** the mapping to create. Otherwise, if nByte is less than zero, then the
5270 ** requested size is the size of the file on disk. The actual size of the
5271 ** created mapping is either the requested size or the value configured
5272 ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
5274 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
5275 ** recreated as a result of outstanding references) or an SQLite error
5278 static int unixMapfile(unixFile
*pFd
, i64 nMap
){
5279 assert( nMap
>=0 || pFd
->nFetchOut
==0 );
5280 assert( nMap
>0 || (pFd
->mmapSize
==0 && pFd
->pMapRegion
==0) );
5281 if( pFd
->nFetchOut
>0 ) return SQLITE_OK
;
5284 struct stat statbuf
; /* Low-level file information */
5285 if( osFstat(pFd
->h
, &statbuf
) ){
5286 return SQLITE_IOERR_FSTAT
;
5288 nMap
= statbuf
.st_size
;
5290 if( nMap
>pFd
->mmapSizeMax
){
5291 nMap
= pFd
->mmapSizeMax
;
5294 assert( nMap
>0 || (pFd
->mmapSize
==0 && pFd
->pMapRegion
==0) );
5295 if( nMap
!=pFd
->mmapSize
){
5296 unixRemapfile(pFd
, nMap
);
5301 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
5304 ** If possible, return a pointer to a mapping of file fd starting at offset
5305 ** iOff. The mapping must be valid for at least nAmt bytes.
5307 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
5308 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
5309 ** Finally, if an error does occur, return an SQLite error code. The final
5310 ** value of *pp is undefined in this case.
5312 ** If this function does return a pointer, the caller must eventually
5313 ** release the reference by calling unixUnfetch().
5315 static int unixFetch(sqlite3_file
*fd
, i64 iOff
, int nAmt
, void **pp
){
5316 #if SQLITE_MAX_MMAP_SIZE>0
5317 unixFile
*pFd
= (unixFile
*)fd
; /* The underlying database file */
5321 #if SQLITE_MAX_MMAP_SIZE>0
5322 if( pFd
->mmapSizeMax
>0 ){
5323 if( pFd
->pMapRegion
==0 ){
5324 int rc
= unixMapfile(pFd
, -1);
5325 if( rc
!=SQLITE_OK
) return rc
;
5327 if( pFd
->mmapSize
>= iOff
+nAmt
){
5328 *pp
= &((u8
*)pFd
->pMapRegion
)[iOff
];
5337 ** If the third argument is non-NULL, then this function releases a
5338 ** reference obtained by an earlier call to unixFetch(). The second
5339 ** argument passed to this function must be the same as the corresponding
5340 ** argument that was passed to the unixFetch() invocation.
5342 ** Or, if the third argument is NULL, then this function is being called
5343 ** to inform the VFS layer that, according to POSIX, any existing mapping
5344 ** may now be invalid and should be unmapped.
5346 static int unixUnfetch(sqlite3_file
*fd
, i64 iOff
, void *p
){
5347 #if SQLITE_MAX_MMAP_SIZE>0
5348 unixFile
*pFd
= (unixFile
*)fd
; /* The underlying database file */
5349 UNUSED_PARAMETER(iOff
);
5351 /* If p==0 (unmap the entire file) then there must be no outstanding
5352 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
5353 ** then there must be at least one outstanding. */
5354 assert( (p
==0)==(pFd
->nFetchOut
==0) );
5356 /* If p!=0, it must match the iOff value. */
5357 assert( p
==0 || p
==&((u8
*)pFd
->pMapRegion
)[iOff
] );
5365 assert( pFd
->nFetchOut
>=0 );
5367 UNUSED_PARAMETER(fd
);
5368 UNUSED_PARAMETER(p
);
5369 UNUSED_PARAMETER(iOff
);
5375 ** Here ends the implementation of all sqlite3_file methods.
5377 ********************** End sqlite3_file Methods *******************************
5378 ******************************************************************************/
5381 ** This division contains definitions of sqlite3_io_methods objects that
5382 ** implement various file locking strategies. It also contains definitions
5383 ** of "finder" functions. A finder-function is used to locate the appropriate
5384 ** sqlite3_io_methods object for a particular database file. The pAppData
5385 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
5386 ** the correct finder-function for that VFS.
5388 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
5389 ** object. The only interesting finder-function is autolockIoFinder, which
5390 ** looks at the filesystem type and tries to guess the best locking
5391 ** strategy from that.
5393 ** For finder-function F, two objects are created:
5395 ** (1) The real finder-function named "FImpt()".
5397 ** (2) A constant pointer to this function named just "F".
5400 ** A pointer to the F pointer is used as the pAppData value for VFS
5401 ** objects. We have to do this instead of letting pAppData point
5402 ** directly at the finder-function since C90 rules prevent a void*
5403 ** from be cast into a function pointer.
5406 ** Each instance of this macro generates two objects:
5408 ** * A constant sqlite3_io_methods object call METHOD that has locking
5409 ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
5411 ** * An I/O method finder function called FINDER that returns a pointer
5412 ** to the METHOD object in the previous bullet.
5414 #define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
5415 static const sqlite3_io_methods METHOD = { \
5416 VERSION, /* iVersion */ \
5417 CLOSE, /* xClose */ \
5418 unixRead, /* xRead */ \
5419 unixWrite, /* xWrite */ \
5420 unixTruncate, /* xTruncate */ \
5421 unixSync, /* xSync */ \
5422 unixFileSize, /* xFileSize */ \
5424 UNLOCK, /* xUnlock */ \
5425 CKLOCK, /* xCheckReservedLock */ \
5426 unixFileControl, /* xFileControl */ \
5427 unixSectorSize, /* xSectorSize */ \
5428 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
5429 SHMMAP, /* xShmMap */ \
5430 unixShmLock, /* xShmLock */ \
5431 unixShmBarrier, /* xShmBarrier */ \
5432 unixShmUnmap, /* xShmUnmap */ \
5433 unixFetch, /* xFetch */ \
5434 unixUnfetch, /* xUnfetch */ \
5436 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
5437 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
5440 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
5444 ** Here are all of the sqlite3_io_methods objects for each of the
5445 ** locking strategies. Functions that return pointers to these methods
5446 ** are also created.
5449 posixIoFinder
, /* Finder function name */
5450 posixIoMethods
, /* sqlite3_io_methods object name */
5451 3, /* shared memory and mmap are enabled */
5452 unixClose
, /* xClose method */
5453 unixLock
, /* xLock method */
5454 unixUnlock
, /* xUnlock method */
5455 unixCheckReservedLock
, /* xCheckReservedLock method */
5456 unixShmMap
/* xShmMap method */
5459 nolockIoFinder
, /* Finder function name */
5460 nolockIoMethods
, /* sqlite3_io_methods object name */
5461 3, /* shared memory and mmap are enabled */
5462 nolockClose
, /* xClose method */
5463 nolockLock
, /* xLock method */
5464 nolockUnlock
, /* xUnlock method */
5465 nolockCheckReservedLock
, /* xCheckReservedLock method */
5466 0 /* xShmMap method */
5469 dotlockIoFinder
, /* Finder function name */
5470 dotlockIoMethods
, /* sqlite3_io_methods object name */
5471 1, /* shared memory is disabled */
5472 dotlockClose
, /* xClose method */
5473 dotlockLock
, /* xLock method */
5474 dotlockUnlock
, /* xUnlock method */
5475 dotlockCheckReservedLock
, /* xCheckReservedLock method */
5476 0 /* xShmMap method */
5479 #if SQLITE_ENABLE_LOCKING_STYLE
5481 flockIoFinder
, /* Finder function name */
5482 flockIoMethods
, /* sqlite3_io_methods object name */
5483 1, /* shared memory is disabled */
5484 flockClose
, /* xClose method */
5485 flockLock
, /* xLock method */
5486 flockUnlock
, /* xUnlock method */
5487 flockCheckReservedLock
, /* xCheckReservedLock method */
5488 0 /* xShmMap method */
5494 semIoFinder
, /* Finder function name */
5495 semIoMethods
, /* sqlite3_io_methods object name */
5496 1, /* shared memory is disabled */
5497 semXClose
, /* xClose method */
5498 semXLock
, /* xLock method */
5499 semXUnlock
, /* xUnlock method */
5500 semXCheckReservedLock
, /* xCheckReservedLock method */
5501 0 /* xShmMap method */
5505 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5507 afpIoFinder
, /* Finder function name */
5508 afpIoMethods
, /* sqlite3_io_methods object name */
5509 1, /* shared memory is disabled */
5510 afpClose
, /* xClose method */
5511 afpLock
, /* xLock method */
5512 afpUnlock
, /* xUnlock method */
5513 afpCheckReservedLock
, /* xCheckReservedLock method */
5514 0 /* xShmMap method */
5519 ** The proxy locking method is a "super-method" in the sense that it
5520 ** opens secondary file descriptors for the conch and lock files and
5521 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
5522 ** secondary files. For this reason, the division that implements
5523 ** proxy locking is located much further down in the file. But we need
5524 ** to go ahead and define the sqlite3_io_methods and finder function
5525 ** for proxy locking here. So we forward declare the I/O methods.
5527 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5528 static int proxyClose(sqlite3_file
*);
5529 static int proxyLock(sqlite3_file
*, int);
5530 static int proxyUnlock(sqlite3_file
*, int);
5531 static int proxyCheckReservedLock(sqlite3_file
*, int*);
5533 proxyIoFinder
, /* Finder function name */
5534 proxyIoMethods
, /* sqlite3_io_methods object name */
5535 1, /* shared memory is disabled */
5536 proxyClose
, /* xClose method */
5537 proxyLock
, /* xLock method */
5538 proxyUnlock
, /* xUnlock method */
5539 proxyCheckReservedLock
, /* xCheckReservedLock method */
5540 0 /* xShmMap method */
5544 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5545 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5547 nfsIoFinder
, /* Finder function name */
5548 nfsIoMethods
, /* sqlite3_io_methods object name */
5549 1, /* shared memory is disabled */
5550 unixClose
, /* xClose method */
5551 unixLock
, /* xLock method */
5552 nfsUnlock
, /* xUnlock method */
5553 unixCheckReservedLock
, /* xCheckReservedLock method */
5554 0 /* xShmMap method */
5558 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5560 ** This "finder" function attempts to determine the best locking strategy
5561 ** for the database file "filePath". It then returns the sqlite3_io_methods
5562 ** object that implements that strategy.
5564 ** This is for MacOSX only.
5566 static const sqlite3_io_methods
*autolockIoFinderImpl(
5567 const char *filePath
, /* name of the database file */
5568 unixFile
*pNew
/* open file object for the database file */
5570 static const struct Mapping
{
5571 const char *zFilesystem
; /* Filesystem type name */
5572 const sqlite3_io_methods
*pMethods
; /* Appropriate locking method */
5574 { "hfs", &posixIoMethods
},
5575 { "ufs", &posixIoMethods
},
5576 { "afpfs", &afpIoMethods
},
5577 { "smbfs", &afpIoMethods
},
5578 { "webdav", &nolockIoMethods
},
5582 struct statfs fsInfo
;
5583 struct flock lockInfo
;
5586 /* If filePath==NULL that means we are dealing with a transient file
5587 ** that does not need to be locked. */
5588 return &nolockIoMethods
;
5590 if( statfs(filePath
, &fsInfo
) != -1 ){
5591 if( fsInfo
.f_flags
& MNT_RDONLY
){
5592 return &nolockIoMethods
;
5594 for(i
=0; aMap
[i
].zFilesystem
; i
++){
5595 if( strcmp(fsInfo
.f_fstypename
, aMap
[i
].zFilesystem
)==0 ){
5596 return aMap
[i
].pMethods
;
5601 /* Default case. Handles, amongst others, "nfs".
5602 ** Test byte-range lock using fcntl(). If the call succeeds,
5603 ** assume that the file-system supports POSIX style locks.
5606 lockInfo
.l_start
= 0;
5607 lockInfo
.l_whence
= SEEK_SET
;
5608 lockInfo
.l_type
= F_RDLCK
;
5609 if( osFcntl(pNew
->h
, F_GETLK
, &lockInfo
)!=-1 ) {
5610 if( strcmp(fsInfo
.f_fstypename
, "nfs")==0 ){
5611 return &nfsIoMethods
;
5613 return &posixIoMethods
;
5616 return &dotlockIoMethods
;
5619 static const sqlite3_io_methods
5620 *(*const autolockIoFinder
)(const char*,unixFile
*) = autolockIoFinderImpl
;
5622 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
5626 ** This "finder" function for VxWorks checks to see if posix advisory
5627 ** locking works. If it does, then that is what is used. If it does not
5628 ** work, then fallback to named semaphore locking.
5630 static const sqlite3_io_methods
*vxworksIoFinderImpl(
5631 const char *filePath
, /* name of the database file */
5632 unixFile
*pNew
/* the open file object */
5634 struct flock lockInfo
;
5637 /* If filePath==NULL that means we are dealing with a transient file
5638 ** that does not need to be locked. */
5639 return &nolockIoMethods
;
5642 /* Test if fcntl() is supported and use POSIX style locks.
5643 ** Otherwise fall back to the named semaphore method.
5646 lockInfo
.l_start
= 0;
5647 lockInfo
.l_whence
= SEEK_SET
;
5648 lockInfo
.l_type
= F_RDLCK
;
5649 if( osFcntl(pNew
->h
, F_GETLK
, &lockInfo
)!=-1 ) {
5650 return &posixIoMethods
;
5652 return &semIoMethods
;
5655 static const sqlite3_io_methods
5656 *(*const vxworksIoFinder
)(const char*,unixFile
*) = vxworksIoFinderImpl
;
5658 #endif /* OS_VXWORKS */
5661 ** An abstract type for a pointer to an IO method finder function:
5663 typedef const sqlite3_io_methods
*(*finder_type
)(const char*,unixFile
*);
5666 /****************************************************************************
5667 **************************** sqlite3_vfs methods ****************************
5669 ** This division contains the implementation of methods on the
5670 ** sqlite3_vfs object.
5674 ** Initialize the contents of the unixFile structure pointed to by pId.
5676 static int fillInUnixFile(
5677 sqlite3_vfs
*pVfs
, /* Pointer to vfs object */
5678 int h
, /* Open file descriptor of file being opened */
5679 sqlite3_file
*pId
, /* Write to the unixFile structure here */
5680 const char *zFilename
, /* Name of the file being opened */
5681 int ctrlFlags
/* Zero or more UNIXFILE_* values */
5683 const sqlite3_io_methods
*pLockingStyle
;
5684 unixFile
*pNew
= (unixFile
*)pId
;
5687 assert( pNew
->pInode
==NULL
);
5689 /* No locking occurs in temporary files */
5690 assert( zFilename
!=0 || (ctrlFlags
& UNIXFILE_NOLOCK
)!=0 );
5692 OSTRACE(("OPEN %-3d %s\n", h
, zFilename
));
5695 pNew
->zPath
= zFilename
;
5696 pNew
->ctrlFlags
= (u8
)ctrlFlags
;
5697 #if SQLITE_MAX_MMAP_SIZE>0
5698 pNew
->mmapSizeMax
= sqlite3GlobalConfig
.szMmap
;
5700 if( sqlite3_uri_boolean(((ctrlFlags
& UNIXFILE_URI
) ? zFilename
: 0),
5701 "psow", SQLITE_POWERSAFE_OVERWRITE
) ){
5702 pNew
->ctrlFlags
|= UNIXFILE_PSOW
;
5704 if( strcmp(pVfs
->zName
,"unix-excl")==0 ){
5705 pNew
->ctrlFlags
|= UNIXFILE_EXCL
;
5709 pNew
->pId
= vxworksFindFileId(zFilename
);
5711 ctrlFlags
|= UNIXFILE_NOLOCK
;
5712 rc
= SQLITE_NOMEM_BKPT
;
5716 if( ctrlFlags
& UNIXFILE_NOLOCK
){
5717 pLockingStyle
= &nolockIoMethods
;
5719 pLockingStyle
= (**(finder_type
*)pVfs
->pAppData
)(zFilename
, pNew
);
5720 #if SQLITE_ENABLE_LOCKING_STYLE
5721 /* Cache zFilename in the locking context (AFP and dotlock override) for
5722 ** proxyLock activation is possible (remote proxy is based on db name)
5723 ** zFilename remains valid until file is closed, to support */
5724 pNew
->lockingContext
= (void*)zFilename
;
5728 if( pLockingStyle
== &posixIoMethods
5729 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5730 || pLockingStyle
== &nfsIoMethods
5734 rc
= findInodeInfo(pNew
, &pNew
->pInode
);
5735 if( rc
!=SQLITE_OK
){
5736 /* If an error occurred in findInodeInfo(), close the file descriptor
5737 ** immediately, before releasing the mutex. findInodeInfo() may fail
5738 ** in two scenarios:
5740 ** (a) A call to fstat() failed.
5741 ** (b) A malloc failed.
5743 ** Scenario (b) may only occur if the process is holding no other
5744 ** file descriptors open on the same file. If there were other file
5745 ** descriptors on this file, then no malloc would be required by
5746 ** findInodeInfo(). If this is the case, it is quite safe to close
5747 ** handle h - as it is guaranteed that no posix locks will be released
5750 ** If scenario (a) caused the error then things are not so safe. The
5751 ** implicit assumption here is that if fstat() fails, things are in
5752 ** such bad shape that dropping a lock or two doesn't matter much.
5754 robust_close(pNew
, h
, __LINE__
);
5760 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
5761 else if( pLockingStyle
== &afpIoMethods
){
5762 /* AFP locking uses the file path so it needs to be included in
5763 ** the afpLockingContext.
5765 afpLockingContext
*pCtx
;
5766 pNew
->lockingContext
= pCtx
= sqlite3_malloc64( sizeof(*pCtx
) );
5768 rc
= SQLITE_NOMEM_BKPT
;
5770 /* NB: zFilename exists and remains valid until the file is closed
5771 ** according to requirement F11141. So we do not need to make a
5772 ** copy of the filename. */
5773 pCtx
->dbPath
= zFilename
;
5777 rc
= findInodeInfo(pNew
, &pNew
->pInode
);
5778 if( rc
!=SQLITE_OK
){
5779 sqlite3_free(pNew
->lockingContext
);
5780 robust_close(pNew
, h
, __LINE__
);
5788 else if( pLockingStyle
== &dotlockIoMethods
){
5789 /* Dotfile locking uses the file path so it needs to be included in
5790 ** the dotlockLockingContext
5794 assert( zFilename
!=0 );
5795 nFilename
= (int)strlen(zFilename
) + 6;
5796 zLockFile
= (char *)sqlite3_malloc64(nFilename
);
5798 rc
= SQLITE_NOMEM_BKPT
;
5800 sqlite3_snprintf(nFilename
, zLockFile
, "%s" DOTLOCK_SUFFIX
, zFilename
);
5802 pNew
->lockingContext
= zLockFile
;
5806 else if( pLockingStyle
== &semIoMethods
){
5807 /* Named semaphore locking uses the file path so it needs to be
5808 ** included in the semLockingContext
5811 rc
= findInodeInfo(pNew
, &pNew
->pInode
);
5812 if( (rc
==SQLITE_OK
) && (pNew
->pInode
->pSem
==NULL
) ){
5813 char *zSemName
= pNew
->pInode
->aSemName
;
5815 sqlite3_snprintf(MAX_PATHNAME
, zSemName
, "/%s.sem",
5816 pNew
->pId
->zCanonicalName
);
5817 for( n
=1; zSemName
[n
]; n
++ )
5818 if( zSemName
[n
]=='/' ) zSemName
[n
] = '_';
5819 pNew
->pInode
->pSem
= sem_open(zSemName
, O_CREAT
, 0666, 1);
5820 if( pNew
->pInode
->pSem
== SEM_FAILED
){
5821 rc
= SQLITE_NOMEM_BKPT
;
5822 pNew
->pInode
->aSemName
[0] = '\0';
5829 storeLastErrno(pNew
, 0);
5831 if( rc
!=SQLITE_OK
){
5832 if( h
>=0 ) robust_close(pNew
, h
, __LINE__
);
5834 osUnlink(zFilename
);
5835 pNew
->ctrlFlags
|= UNIXFILE_DELETE
;
5838 if( rc
!=SQLITE_OK
){
5839 if( h
>=0 ) robust_close(pNew
, h
, __LINE__
);
5841 pId
->pMethods
= pLockingStyle
;
5849 ** Directories to consider for temp files.
5851 static const char *azTempDirs
[] = {
5861 ** Initialize first two members of azTempDirs[] array.
5863 static void unixTempFileInit(void){
5864 azTempDirs
[0] = getenv("SQLITE_TMPDIR");
5865 azTempDirs
[1] = getenv("TMPDIR");
5869 ** Return the name of a directory in which to put temporary files.
5870 ** If no suitable temporary file directory can be found, return NULL.
5872 static const char *unixTempFileDir(void){
5875 const char *zDir
= sqlite3_temp_directory
;
5879 && osStat(zDir
, &buf
)==0
5880 && S_ISDIR(buf
.st_mode
)
5881 && osAccess(zDir
, 03)==0
5885 if( i
>=sizeof(azTempDirs
)/sizeof(azTempDirs
[0]) ) break;
5886 zDir
= azTempDirs
[i
++];
5892 ** Create a temporary file name in zBuf. zBuf must be allocated
5893 ** by the calling process and must be big enough to hold at least
5894 ** pVfs->mxPathname bytes.
5896 static int unixGetTempname(int nBuf
, char *zBuf
){
5901 /* It's odd to simulate an io-error here, but really this is just
5902 ** using the io-error infrastructure to test that SQLite handles this
5903 ** function failing.
5906 SimulateIOError( return SQLITE_IOERR
);
5908 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR
));
5909 zDir
= unixTempFileDir();
5911 rc
= SQLITE_IOERR_GETTEMPPATH
;
5915 sqlite3_randomness(sizeof(r
), &r
);
5918 sqlite3_snprintf(nBuf
, zBuf
, "%s/"SQLITE_TEMP_FILE_PREFIX
"%llx%c",
5920 if( zBuf
[nBuf
-2]!=0 || (iLimit
++)>10 ){
5924 }while( osAccess(zBuf
,0)==0 );
5926 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR
));
5930 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
5932 ** Routine to transform a unixFile into a proxy-locking unixFile.
5933 ** Implementation in the proxy-lock division, but used by unixOpen()
5934 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
5936 static int proxyTransformUnixFile(unixFile
*, const char*);
5940 ** Search for an unused file descriptor that was opened on the database
5941 ** file (not a journal or super-journal file) identified by pathname
5942 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5943 ** argument to this function.
5945 ** Such a file descriptor may exist if a database connection was closed
5946 ** but the associated file descriptor could not be closed because some
5947 ** other file descriptor open on the same file is holding a file-lock.
5948 ** Refer to comments in the unixClose() function and the lengthy comment
5949 ** describing "Posix Advisory Locking" at the start of this file for
5950 ** further details. Also, ticket #4018.
5952 ** If a suitable file descriptor is found, then it is returned. If no
5953 ** such file descriptor is located, -1 is returned.
5955 static UnixUnusedFd
*findReusableFd(const char *zPath
, int flags
){
5956 UnixUnusedFd
*pUnused
= 0;
5958 /* Do not search for an unused file descriptor on vxworks. Not because
5959 ** vxworks would not benefit from the change (it might, we're not sure),
5960 ** but because no way to test it is currently available. It is better
5961 ** not to risk breaking vxworks support for the sake of such an obscure
5964 struct stat sStat
; /* Results of stat() call */
5968 /* A stat() call may fail for various reasons. If this happens, it is
5969 ** almost certain that an open() call on the same path will also fail.
5970 ** For this reason, if an error occurs in the stat() call here, it is
5971 ** ignored and -1 is returned. The caller will try to open a new file
5972 ** descriptor on the same path, fail, and return an error to SQLite.
5974 ** Even if a subsequent open() call does succeed, the consequences of
5975 ** not searching for a reusable file descriptor are not dire. */
5976 if( inodeList
!=0 && 0==osStat(zPath
, &sStat
) ){
5977 unixInodeInfo
*pInode
;
5980 while( pInode
&& (pInode
->fileId
.dev
!=sStat
.st_dev
5981 || pInode
->fileId
.ino
!=(u64
)sStat
.st_ino
) ){
5982 pInode
= pInode
->pNext
;
5986 assert( sqlite3_mutex_notheld(pInode
->pLockMutex
) );
5987 sqlite3_mutex_enter(pInode
->pLockMutex
);
5988 flags
&= (SQLITE_OPEN_READONLY
|SQLITE_OPEN_READWRITE
);
5989 for(pp
=&pInode
->pUnused
; *pp
&& (*pp
)->flags
!=flags
; pp
=&((*pp
)->pNext
));
5992 *pp
= pUnused
->pNext
;
5994 sqlite3_mutex_leave(pInode
->pLockMutex
);
5998 #endif /* if !OS_VXWORKS */
6003 ** Find the mode, uid and gid of file zFile.
6005 static int getFileMode(
6006 const char *zFile
, /* File name */
6007 mode_t
*pMode
, /* OUT: Permissions of zFile */
6008 uid_t
*pUid
, /* OUT: uid of zFile. */
6009 gid_t
*pGid
/* OUT: gid of zFile. */
6011 struct stat sStat
; /* Output of stat() on database file */
6013 if( 0==osStat(zFile
, &sStat
) ){
6014 *pMode
= sStat
.st_mode
& 0777;
6015 *pUid
= sStat
.st_uid
;
6016 *pGid
= sStat
.st_gid
;
6018 rc
= SQLITE_IOERR_FSTAT
;
6024 ** This function is called by unixOpen() to determine the unix permissions
6025 ** to create new files with. If no error occurs, then SQLITE_OK is returned
6026 ** and a value suitable for passing as the third argument to open(2) is
6027 ** written to *pMode. If an IO error occurs, an SQLite error code is
6028 ** returned and the value of *pMode is not modified.
6030 ** In most cases, this routine sets *pMode to 0, which will become
6031 ** an indication to robust_open() to create the file using
6032 ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
6033 ** But if the file being opened is a WAL or regular journal file, then
6034 ** this function queries the file-system for the permissions on the
6035 ** corresponding database file and sets *pMode to this value. Whenever
6036 ** possible, WAL and journal files are created using the same permissions
6037 ** as the associated database file.
6039 ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
6040 ** original filename is unavailable. But 8_3_NAMES is only used for
6041 ** FAT filesystems and permissions do not matter there, so just use
6042 ** the default permissions. In 8_3_NAMES mode, leave *pMode set to zero.
6044 static int findCreateFileMode(
6045 const char *zPath
, /* Path of file (possibly) being created */
6046 int flags
, /* Flags passed as 4th argument to xOpen() */
6047 mode_t
*pMode
, /* OUT: Permissions to open file with */
6048 uid_t
*pUid
, /* OUT: uid to set on the file */
6049 gid_t
*pGid
/* OUT: gid to set on the file */
6051 int rc
= SQLITE_OK
; /* Return Code */
6055 if( flags
& (SQLITE_OPEN_WAL
|SQLITE_OPEN_MAIN_JOURNAL
) ){
6056 char zDb
[MAX_PATHNAME
+1]; /* Database file path */
6057 int nDb
; /* Number of valid bytes in zDb */
6059 /* zPath is a path to a WAL or journal file. The following block derives
6060 ** the path to the associated database file from zPath. This block handles
6061 ** the following naming conventions:
6063 ** "<path to db>-journal"
6064 ** "<path to db>-wal"
6065 ** "<path to db>-journalNN"
6066 ** "<path to db>-walNN"
6068 ** where NN is a decimal number. The NN naming schemes are
6069 ** used by the test_multiplex.c module.
6071 ** In normal operation, the journal file name will always contain
6072 ** a '-' character. However in 8+3 filename mode, or if a corrupt
6073 ** rollback journal specifies a super-journal with a goofy name, then
6074 ** the '-' might be missing or the '-' might be the first character in
6075 ** the filename. In that case, just return SQLITE_OK with *pMode==0.
6077 nDb
= sqlite3Strlen30(zPath
) - 1;
6078 while( nDb
>0 && zPath
[nDb
]!='.' ){
6079 if( zPath
[nDb
]=='-' ){
6080 memcpy(zDb
, zPath
, nDb
);
6082 rc
= getFileMode(zDb
, pMode
, pUid
, pGid
);
6087 }else if( flags
& SQLITE_OPEN_DELETEONCLOSE
){
6089 }else if( flags
& SQLITE_OPEN_URI
){
6090 /* If this is a main database file and the file was opened using a URI
6091 ** filename, check for the "modeof" parameter. If present, interpret
6092 ** its value as a filename and try to copy the mode, uid and gid from
6094 const char *z
= sqlite3_uri_parameter(zPath
, "modeof");
6096 rc
= getFileMode(z
, pMode
, pUid
, pGid
);
6103 ** Open the file zPath.
6105 ** Previously, the SQLite OS layer used three functions in place of this
6108 ** sqlite3OsOpenReadWrite();
6109 ** sqlite3OsOpenReadOnly();
6110 ** sqlite3OsOpenExclusive();
6112 ** These calls correspond to the following combinations of flags:
6114 ** ReadWrite() -> (READWRITE | CREATE)
6115 ** ReadOnly() -> (READONLY)
6116 ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
6118 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
6119 ** true, the file was configured to be automatically deleted when the
6120 ** file handle closed. To achieve the same effect using this new
6121 ** interface, add the DELETEONCLOSE flag to those specified above for
6124 static int unixOpen(
6125 sqlite3_vfs
*pVfs
, /* The VFS for which this is the xOpen method */
6126 const char *zPath
, /* Pathname of file to be opened */
6127 sqlite3_file
*pFile
, /* The file descriptor to be filled in */
6128 int flags
, /* Input flags to control the opening */
6129 int *pOutFlags
/* Output flags returned to SQLite core */
6131 unixFile
*p
= (unixFile
*)pFile
;
6132 int fd
= -1; /* File descriptor returned by open() */
6133 int openFlags
= 0; /* Flags to pass to open() */
6134 int eType
= flags
&0x0FFF00; /* Type of file to open */
6135 int noLock
; /* True to omit locking primitives */
6136 int rc
= SQLITE_OK
; /* Function Return Code */
6137 int ctrlFlags
= 0; /* UNIXFILE_* flags */
6139 int isExclusive
= (flags
& SQLITE_OPEN_EXCLUSIVE
);
6140 int isDelete
= (flags
& SQLITE_OPEN_DELETEONCLOSE
);
6141 int isCreate
= (flags
& SQLITE_OPEN_CREATE
);
6142 int isReadonly
= (flags
& SQLITE_OPEN_READONLY
);
6143 int isReadWrite
= (flags
& SQLITE_OPEN_READWRITE
);
6144 #if SQLITE_ENABLE_LOCKING_STYLE
6145 int isAutoProxy
= (flags
& SQLITE_OPEN_AUTOPROXY
);
6147 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
6148 struct statfs fsInfo
;
6151 /* If creating a super- or main-file journal, this function will open
6152 ** a file-descriptor on the directory too. The first time unixSync()
6153 ** is called the directory file descriptor will be fsync()ed and close()d.
6155 int isNewJrnl
= (isCreate
&& (
6156 eType
==SQLITE_OPEN_SUPER_JOURNAL
6157 || eType
==SQLITE_OPEN_MAIN_JOURNAL
6158 || eType
==SQLITE_OPEN_WAL
6161 /* If argument zPath is a NULL pointer, this function is required to open
6162 ** a temporary file. Use this buffer to store the file name in.
6164 char zTmpname
[MAX_PATHNAME
+2];
6165 const char *zName
= zPath
;
6167 /* Check the following statements are true:
6169 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
6170 ** (b) if CREATE is set, then READWRITE must also be set, and
6171 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
6172 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
6174 assert((isReadonly
==0 || isReadWrite
==0) && (isReadWrite
|| isReadonly
));
6175 assert(isCreate
==0 || isReadWrite
);
6176 assert(isExclusive
==0 || isCreate
);
6177 assert(isDelete
==0 || isCreate
);
6179 /* The main DB, main journal, WAL file and super-journal are never
6180 ** automatically deleted. Nor are they ever temporary files. */
6181 assert( (!isDelete
&& zName
) || eType
!=SQLITE_OPEN_MAIN_DB
);
6182 assert( (!isDelete
&& zName
) || eType
!=SQLITE_OPEN_MAIN_JOURNAL
);
6183 assert( (!isDelete
&& zName
) || eType
!=SQLITE_OPEN_SUPER_JOURNAL
);
6184 assert( (!isDelete
&& zName
) || eType
!=SQLITE_OPEN_WAL
);
6186 /* Assert that the upper layer has set one of the "file-type" flags. */
6187 assert( eType
==SQLITE_OPEN_MAIN_DB
|| eType
==SQLITE_OPEN_TEMP_DB
6188 || eType
==SQLITE_OPEN_MAIN_JOURNAL
|| eType
==SQLITE_OPEN_TEMP_JOURNAL
6189 || eType
==SQLITE_OPEN_SUBJOURNAL
|| eType
==SQLITE_OPEN_SUPER_JOURNAL
6190 || eType
==SQLITE_OPEN_TRANSIENT_DB
|| eType
==SQLITE_OPEN_WAL
6193 /* Detect a pid change and reset the PRNG. There is a race condition
6194 ** here such that two or more threads all trying to open databases at
6195 ** the same instant might all reset the PRNG. But multiple resets
6198 if( randomnessPid
!=osGetpid(0) ){
6199 randomnessPid
= osGetpid(0);
6200 sqlite3_randomness(0,0);
6202 memset(p
, 0, sizeof(unixFile
));
6204 #ifdef SQLITE_ASSERT_NO_FILES
6205 /* Applications that never read or write a persistent disk files */
6209 if( eType
==SQLITE_OPEN_MAIN_DB
){
6210 UnixUnusedFd
*pUnused
;
6211 pUnused
= findReusableFd(zName
, flags
);
6215 pUnused
= sqlite3_malloc64(sizeof(*pUnused
));
6217 return SQLITE_NOMEM_BKPT
;
6220 p
->pPreallocatedUnused
= pUnused
;
6222 /* Database filenames are double-zero terminated if they are not
6223 ** URIs with parameters. Hence, they can always be passed into
6224 ** sqlite3_uri_parameter(). */
6225 assert( (flags
& SQLITE_OPEN_URI
) || zName
[strlen(zName
)+1]==0 );
6228 /* If zName is NULL, the upper layer is requesting a temp file. */
6229 assert(isDelete
&& !isNewJrnl
);
6230 rc
= unixGetTempname(pVfs
->mxPathname
, zTmpname
);
6231 if( rc
!=SQLITE_OK
){
6236 /* Generated temporary filenames are always double-zero terminated
6237 ** for use by sqlite3_uri_parameter(). */
6238 assert( zName
[strlen(zName
)+1]==0 );
6241 /* Determine the value of the flags parameter passed to POSIX function
6242 ** open(). These must be calculated even if open() is not called, as
6243 ** they may be stored as part of the file handle and used by the
6244 ** 'conch file' locking functions later on. */
6245 if( isReadonly
) openFlags
|= O_RDONLY
;
6246 if( isReadWrite
) openFlags
|= O_RDWR
;
6247 if( isCreate
) openFlags
|= O_CREAT
;
6248 if( isExclusive
) openFlags
|= (O_EXCL
|O_NOFOLLOW
);
6249 openFlags
|= (O_LARGEFILE
|O_BINARY
|O_NOFOLLOW
);
6252 mode_t openMode
; /* Permissions to create file with */
6253 uid_t uid
; /* Userid for the file */
6254 gid_t gid
; /* Groupid for the file */
6255 rc
= findCreateFileMode(zName
, flags
, &openMode
, &uid
, &gid
);
6256 if( rc
!=SQLITE_OK
){
6257 assert( !p
->pPreallocatedUnused
);
6258 assert( eType
==SQLITE_OPEN_WAL
|| eType
==SQLITE_OPEN_MAIN_JOURNAL
);
6261 fd
= robust_open(zName
, openFlags
, openMode
);
6262 OSTRACE(("OPENX %-3d %s 0%o\n", fd
, zName
, openFlags
));
6263 assert( !isExclusive
|| (openFlags
& O_CREAT
)!=0 );
6265 if( isNewJrnl
&& errno
==EACCES
&& osAccess(zName
, F_OK
) ){
6266 /* If unable to create a journal because the directory is not
6267 ** writable, change the error code to indicate that. */
6268 rc
= SQLITE_READONLY_DIRECTORY
;
6269 }else if( errno
!=EISDIR
&& isReadWrite
){
6270 /* Failed to open the file for read/write access. Try read-only. */
6271 flags
&= ~(SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
);
6272 openFlags
&= ~(O_RDWR
|O_CREAT
);
6273 flags
|= SQLITE_OPEN_READONLY
;
6274 openFlags
|= O_RDONLY
;
6276 fd
= robust_open(zName
, openFlags
, openMode
);
6280 int rc2
= unixLogError(SQLITE_CANTOPEN_BKPT
, "open", zName
);
6281 if( rc
==SQLITE_OK
) rc
= rc2
;
6285 /* The owner of the rollback journal or WAL file should always be the
6286 ** same as the owner of the database file. Try to ensure that this is
6287 ** the case. The chown() system call will be a no-op if the current
6288 ** process lacks root privileges, be we should at least try. Without
6289 ** this step, if a root process opens a database file, it can leave
6290 ** behinds a journal/WAL that is owned by root and hence make the
6291 ** database inaccessible to unprivileged processes.
6293 ** If openMode==0, then that means uid and gid are not set correctly
6294 ** (probably because SQLite is configured to use 8+3 filename mode) and
6295 ** in that case we do not want to attempt the chown().
6297 if( openMode
&& (flags
& (SQLITE_OPEN_WAL
|SQLITE_OPEN_MAIN_JOURNAL
))!=0 ){
6298 robustFchown(fd
, uid
, gid
);
6306 if( p
->pPreallocatedUnused
){
6307 p
->pPreallocatedUnused
->fd
= fd
;
6308 p
->pPreallocatedUnused
->flags
=
6309 flags
& (SQLITE_OPEN_READONLY
|SQLITE_OPEN_READWRITE
);
6315 #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
6316 zPath
= sqlite3_mprintf("%s", zName
);
6318 robust_close(p
, fd
, __LINE__
);
6319 return SQLITE_NOMEM_BKPT
;
6325 #if SQLITE_ENABLE_LOCKING_STYLE
6327 p
->openFlags
= openFlags
;
6331 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
6332 if( fstatfs(fd
, &fsInfo
) == -1 ){
6333 storeLastErrno(p
, errno
);
6334 robust_close(p
, fd
, __LINE__
);
6335 return SQLITE_IOERR_ACCESS
;
6337 if (0 == strncmp("msdos", fsInfo
.f_fstypename
, 5)) {
6338 ((unixFile
*)pFile
)->fsFlags
|= SQLITE_FSFLAGS_IS_MSDOS
;
6340 if (0 == strncmp("exfat", fsInfo
.f_fstypename
, 5)) {
6341 ((unixFile
*)pFile
)->fsFlags
|= SQLITE_FSFLAGS_IS_MSDOS
;
6345 /* Set up appropriate ctrlFlags */
6346 if( isDelete
) ctrlFlags
|= UNIXFILE_DELETE
;
6347 if( isReadonly
) ctrlFlags
|= UNIXFILE_RDONLY
;
6348 noLock
= eType
!=SQLITE_OPEN_MAIN_DB
;
6349 if( noLock
) ctrlFlags
|= UNIXFILE_NOLOCK
;
6350 if( isNewJrnl
) ctrlFlags
|= UNIXFILE_DIRSYNC
;
6351 if( flags
& SQLITE_OPEN_URI
) ctrlFlags
|= UNIXFILE_URI
;
6353 #if SQLITE_ENABLE_LOCKING_STYLE
6354 #if SQLITE_PREFER_PROXY_LOCKING
6357 if( isAutoProxy
&& (zPath
!=NULL
) && (!noLock
) && pVfs
->xOpen
){
6358 char *envforce
= getenv("SQLITE_FORCE_PROXY_LOCKING");
6361 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
6362 ** never use proxy, NULL means use proxy for non-local files only. */
6363 if( envforce
!=NULL
){
6364 useProxy
= atoi(envforce
)>0;
6366 useProxy
= !(fsInfo
.f_flags
&MNT_LOCAL
);
6369 rc
= fillInUnixFile(pVfs
, fd
, pFile
, zPath
, ctrlFlags
);
6370 if( rc
==SQLITE_OK
){
6371 rc
= proxyTransformUnixFile((unixFile
*)pFile
, ":auto:");
6372 if( rc
!=SQLITE_OK
){
6373 /* Use unixClose to clean up the resources added in fillInUnixFile
6374 ** and clear all the structure's references. Specifically,
6375 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
6386 assert( zPath
==0 || zPath
[0]=='/'
6387 || eType
==SQLITE_OPEN_SUPER_JOURNAL
|| eType
==SQLITE_OPEN_MAIN_JOURNAL
6389 rc
= fillInUnixFile(pVfs
, fd
, pFile
, zPath
, ctrlFlags
);
6392 if( rc
!=SQLITE_OK
){
6393 sqlite3_free(p
->pPreallocatedUnused
);
6400 ** Delete the file at zPath. If the dirSync argument is true, fsync()
6401 ** the directory after deleting the file.
6403 static int unixDelete(
6404 sqlite3_vfs
*NotUsed
, /* VFS containing this as the xDelete method */
6405 const char *zPath
, /* Name of file to be deleted */
6406 int dirSync
/* If true, fsync() directory after deleting file */
6409 UNUSED_PARAMETER(NotUsed
);
6410 SimulateIOError(return SQLITE_IOERR_DELETE
);
6411 if( osUnlink(zPath
)==(-1) ){
6414 || osAccess(zPath
,0)!=0
6417 rc
= SQLITE_IOERR_DELETE_NOENT
;
6419 rc
= unixLogError(SQLITE_IOERR_DELETE
, "unlink", zPath
);
6423 #ifndef SQLITE_DISABLE_DIRSYNC
6424 if( (dirSync
& 1)!=0 ){
6426 rc
= osOpenDirectory(zPath
, &fd
);
6427 if( rc
==SQLITE_OK
){
6428 if( full_fsync(fd
,0,0) ){
6429 rc
= unixLogError(SQLITE_IOERR_DIR_FSYNC
, "fsync", zPath
);
6431 robust_close(0, fd
, __LINE__
);
6433 assert( rc
==SQLITE_CANTOPEN
);
6442 ** Test the existence of or access permissions of file zPath. The
6443 ** test performed depends on the value of flags:
6445 ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
6446 ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
6447 ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
6449 ** Otherwise return 0.
6451 static int unixAccess(
6452 sqlite3_vfs
*NotUsed
, /* The VFS containing this xAccess method */
6453 const char *zPath
, /* Path of the file to examine */
6454 int flags
, /* What do we want to learn about the zPath file? */
6455 int *pResOut
/* Write result boolean here */
6457 UNUSED_PARAMETER(NotUsed
);
6458 SimulateIOError( return SQLITE_IOERR_ACCESS
; );
6459 assert( pResOut
!=0 );
6461 /* The spec says there are three possible values for flags. But only
6462 ** two of them are actually used */
6463 assert( flags
==SQLITE_ACCESS_EXISTS
|| flags
==SQLITE_ACCESS_READWRITE
);
6465 if( flags
==SQLITE_ACCESS_EXISTS
){
6467 *pResOut
= 0==osStat(zPath
, &buf
) &&
6468 (!S_ISREG(buf
.st_mode
) || buf
.st_size
>0);
6470 *pResOut
= osAccess(zPath
, W_OK
|R_OK
)==0;
6476 ** A pathname under construction
6478 typedef struct DbPath DbPath
;
6480 int rc
; /* Non-zero following any error */
6481 int nSymlink
; /* Number of symlinks resolved */
6482 char *zOut
; /* Write the pathname here */
6483 int nOut
; /* Bytes of space available to zOut[] */
6484 int nUsed
; /* Bytes of zOut[] currently being used */
6487 /* Forward reference */
6488 static void appendAllPathElements(DbPath
*,const char*);
6491 ** Append a single path element to the DbPath under construction
6493 static void appendOnePathElement(
6494 DbPath
*pPath
, /* Path under construction, to which to append zName */
6495 const char *zName
, /* Name to append to pPath. Not zero-terminated */
6496 int nName
/* Number of significant bytes in zName */
6500 if( zName
[0]=='.' ){
6501 if( nName
==1 ) return;
6502 if( zName
[1]=='.' && nName
==2 ){
6503 if( pPath
->nUsed
>1 ){
6504 assert( pPath
->zOut
[0]=='/' );
6505 while( pPath
->zOut
[--pPath
->nUsed
]!='/' ){}
6510 if( pPath
->nUsed
+ nName
+ 2 >= pPath
->nOut
){
6511 pPath
->rc
= SQLITE_ERROR
;
6514 pPath
->zOut
[pPath
->nUsed
++] = '/';
6515 memcpy(&pPath
->zOut
[pPath
->nUsed
], zName
, nName
);
6516 pPath
->nUsed
+= nName
;
6517 #if defined(HAVE_READLINK) && defined(HAVE_LSTAT)
6518 if( pPath
->rc
==SQLITE_OK
){
6521 pPath
->zOut
[pPath
->nUsed
] = 0;
6523 if( osLstat(zIn
, &buf
)!=0 ){
6524 if( errno
!=ENOENT
){
6525 pPath
->rc
= unixLogError(SQLITE_CANTOPEN_BKPT
, "lstat", zIn
);
6527 }else if( S_ISLNK(buf
.st_mode
) ){
6529 char zLnk
[SQLITE_MAX_PATHLEN
+2];
6530 if( pPath
->nSymlink
++ > SQLITE_MAX_SYMLINK
){
6531 pPath
->rc
= SQLITE_CANTOPEN_BKPT
;
6534 got
= osReadlink(zIn
, zLnk
, sizeof(zLnk
)-2);
6535 if( got
<=0 || got
>=(ssize_t
)sizeof(zLnk
)-2 ){
6536 pPath
->rc
= unixLogError(SQLITE_CANTOPEN_BKPT
, "readlink", zIn
);
6543 pPath
->nUsed
-= nName
+ 1;
6545 appendAllPathElements(pPath
, zLnk
);
6552 ** Append all path elements in zPath to the DbPath under construction.
6554 static void appendAllPathElements(
6555 DbPath
*pPath
, /* Path under construction, to which to append zName */
6556 const char *zPath
/* Path to append to pPath. Is zero-terminated */
6561 while( zPath
[i
] && zPath
[i
]!='/' ){ i
++; }
6563 appendOnePathElement(pPath
, &zPath
[j
], i
-j
);
6566 }while( zPath
[i
++] );
6570 ** Turn a relative pathname into a full pathname. The relative path
6571 ** is stored as a nul-terminated string in the buffer pointed to by
6574 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
6575 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
6576 ** this buffer before returning.
6578 static int unixFullPathname(
6579 sqlite3_vfs
*pVfs
, /* Pointer to vfs object */
6580 const char *zPath
, /* Possibly relative input path */
6581 int nOut
, /* Size of output buffer in bytes */
6582 char *zOut
/* Output buffer */
6585 UNUSED_PARAMETER(pVfs
);
6591 if( zPath
[0]!='/' ){
6592 char zPwd
[SQLITE_MAX_PATHLEN
+2];
6593 if( osGetcwd(zPwd
, sizeof(zPwd
)-2)==0 ){
6594 return unixLogError(SQLITE_CANTOPEN_BKPT
, "getcwd", zPath
);
6596 appendAllPathElements(&path
, zPwd
);
6598 appendAllPathElements(&path
, zPath
);
6599 zOut
[path
.nUsed
] = 0;
6600 if( path
.rc
|| path
.nUsed
<2 ) return SQLITE_CANTOPEN_BKPT
;
6601 if( path
.nSymlink
) return SQLITE_OK_SYMLINK
;
6605 #ifndef SQLITE_OMIT_LOAD_EXTENSION
6607 ** Interfaces for opening a shared library, finding entry points
6608 ** within the shared library, and closing the shared library.
6611 static void *unixDlOpen(sqlite3_vfs
*NotUsed
, const char *zFilename
){
6612 UNUSED_PARAMETER(NotUsed
);
6613 return dlopen(zFilename
, RTLD_NOW
| RTLD_GLOBAL
);
6617 ** SQLite calls this function immediately after a call to unixDlSym() or
6618 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
6619 ** message is available, it is written to zBufOut. If no error message
6620 ** is available, zBufOut is left unmodified and SQLite uses a default
6623 static void unixDlError(sqlite3_vfs
*NotUsed
, int nBuf
, char *zBufOut
){
6625 UNUSED_PARAMETER(NotUsed
);
6629 sqlite3_snprintf(nBuf
, zBufOut
, "%s", zErr
);
6633 static void (*unixDlSym(sqlite3_vfs
*NotUsed
, void *p
, const char*zSym
))(void){
6635 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6636 ** cast into a pointer to a function. And yet the library dlsym() routine
6637 ** returns a void* which is really a pointer to a function. So how do we
6638 ** use dlsym() with -pedantic-errors?
6640 ** Variable x below is defined to be a pointer to a function taking
6641 ** parameters void* and const char* and returning a pointer to a function.
6642 ** We initialize x by assigning it a pointer to the dlsym() function.
6643 ** (That assignment requires a cast.) Then we call the function that
6646 ** This work-around is unlikely to work correctly on any system where
6647 ** you really cannot cast a function pointer into void*. But then, on the
6648 ** other hand, dlsym() will not work on such a system either, so we have
6649 ** not really lost anything.
6651 void (*(*x
)(void*,const char*))(void);
6652 UNUSED_PARAMETER(NotUsed
);
6653 x
= (void(*(*)(void*,const char*))(void))dlsym
;
6654 return (*x
)(p
, zSym
);
6656 static void unixDlClose(sqlite3_vfs
*NotUsed
, void *pHandle
){
6657 UNUSED_PARAMETER(NotUsed
);
6660 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6661 #define unixDlOpen 0
6662 #define unixDlError 0
6664 #define unixDlClose 0
6668 ** Write nBuf bytes of random data to the supplied buffer zBuf.
6670 static int unixRandomness(sqlite3_vfs
*NotUsed
, int nBuf
, char *zBuf
){
6671 UNUSED_PARAMETER(NotUsed
);
6672 assert((size_t)nBuf
>=(sizeof(time_t)+sizeof(int)));
6674 /* We have to initialize zBuf to prevent valgrind from reporting
6675 ** errors. The reports issued by valgrind are incorrect - we would
6676 ** prefer that the randomness be increased by making use of the
6677 ** uninitialized space in zBuf - but valgrind errors tend to worry
6678 ** some users. Rather than argue, it seems easier just to initialize
6679 ** the whole array and silence valgrind, even if that means less randomness
6680 ** in the random seed.
6682 ** When testing, initializing zBuf[] to zero is all we do. That means
6683 ** that we always use the same random number sequence. This makes the
6684 ** tests repeatable.
6686 memset(zBuf
, 0, nBuf
);
6687 randomnessPid
= osGetpid(0);
6688 #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
6691 fd
= robust_open("/dev/urandom", O_RDONLY
, 0);
6695 memcpy(zBuf
, &t
, sizeof(t
));
6696 memcpy(&zBuf
[sizeof(t
)], &randomnessPid
, sizeof(randomnessPid
));
6697 assert( sizeof(t
)+sizeof(randomnessPid
)<=(size_t)nBuf
);
6698 nBuf
= sizeof(t
) + sizeof(randomnessPid
);
6700 do{ got
= osRead(fd
, zBuf
, nBuf
); }while( got
<0 && errno
==EINTR
);
6701 robust_close(0, fd
, __LINE__
);
6710 ** Sleep for a little while. Return the amount of time slept.
6711 ** The argument is the number of microseconds we want to sleep.
6712 ** The return value is the number of microseconds of sleep actually
6713 ** requested from the underlying operating system, a number which
6714 ** might be greater than or equal to the argument, but not less
6715 ** than the argument.
6717 static int unixSleep(sqlite3_vfs
*NotUsed
, int microseconds
){
6718 #if !defined(HAVE_NANOSLEEP) || HAVE_NANOSLEEP+0
6720 sp
.tv_sec
= microseconds
/ 1000000;
6721 sp
.tv_nsec
= (microseconds
% 1000000) * 1000;
6723 /* Almost all modern unix systems support nanosleep(). But if you are
6724 ** compiling for one of the rare exceptions, you can use
6725 ** -DHAVE_NANOSLEEP=0 (perhaps in conjuction with -DHAVE_USLEEP if
6726 ** usleep() is available) in order to bypass the use of nanosleep() */
6727 nanosleep(&sp
, NULL
);
6729 UNUSED_PARAMETER(NotUsed
);
6730 return microseconds
;
6731 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
6732 if( microseconds
>=1000000 ) sleep(microseconds
/1000000);
6733 if( microseconds
%1000000 ) usleep(microseconds
%1000000);
6734 UNUSED_PARAMETER(NotUsed
);
6735 return microseconds
;
6737 int seconds
= (microseconds
+999999)/1000000;
6739 UNUSED_PARAMETER(NotUsed
);
6740 return seconds
*1000000;
6745 ** The following variable, if set to a non-zero value, is interpreted as
6746 ** the number of seconds since 1970 and is used to set the result of
6747 ** sqlite3OsCurrentTime() during testing.
6750 int sqlite3_current_time
= 0; /* Fake system time in seconds since 1970. */
6754 ** Find the current time (in Universal Coordinated Time). Write into *piNow
6755 ** the current time and date as a Julian Day number times 86_400_000. In
6756 ** other words, write into *piNow the number of milliseconds since the Julian
6757 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6758 ** proleptic Gregorian calendar.
6760 ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6763 static int unixCurrentTimeInt64(sqlite3_vfs
*NotUsed
, sqlite3_int64
*piNow
){
6764 static const sqlite3_int64 unixEpoch
= 24405875*(sqlite3_int64
)8640000;
6766 #if defined(NO_GETTOD)
6769 *piNow
= ((sqlite3_int64
)t
)*1000 + unixEpoch
;
6771 struct timespec sNow
;
6772 clock_gettime(CLOCK_REALTIME
, &sNow
);
6773 *piNow
= unixEpoch
+ 1000*(sqlite3_int64
)sNow
.tv_sec
+ sNow
.tv_nsec
/1000000;
6775 struct timeval sNow
;
6776 (void)gettimeofday(&sNow
, 0); /* Cannot fail given valid arguments */
6777 *piNow
= unixEpoch
+ 1000*(sqlite3_int64
)sNow
.tv_sec
+ sNow
.tv_usec
/1000;
6781 if( sqlite3_current_time
){
6782 *piNow
= 1000*(sqlite3_int64
)sqlite3_current_time
+ unixEpoch
;
6785 UNUSED_PARAMETER(NotUsed
);
6789 #ifndef SQLITE_OMIT_DEPRECATED
6791 ** Find the current time (in Universal Coordinated Time). Write the
6792 ** current time and date as a Julian Day number into *prNow and
6793 ** return 0. Return 1 if the time and date cannot be found.
6795 static int unixCurrentTime(sqlite3_vfs
*NotUsed
, double *prNow
){
6796 sqlite3_int64 i
= 0;
6798 UNUSED_PARAMETER(NotUsed
);
6799 rc
= unixCurrentTimeInt64(0, &i
);
6800 *prNow
= i
/86400000.0;
6804 # define unixCurrentTime 0
6808 ** The xGetLastError() method is designed to return a better
6809 ** low-level error message when operating-system problems come up
6810 ** during SQLite operation. Only the integer return code is currently
6813 static int unixGetLastError(sqlite3_vfs
*NotUsed
, int NotUsed2
, char *NotUsed3
){
6814 UNUSED_PARAMETER(NotUsed
);
6815 UNUSED_PARAMETER(NotUsed2
);
6816 UNUSED_PARAMETER(NotUsed3
);
6822 ************************ End of sqlite3_vfs methods ***************************
6823 ******************************************************************************/
6825 /******************************************************************************
6826 ************************** Begin Proxy Locking ********************************
6828 ** Proxy locking is a "uber-locking-method" in this sense: It uses the
6829 ** other locking methods on secondary lock files. Proxy locking is a
6830 ** meta-layer over top of the primitive locking implemented above. For
6831 ** this reason, the division that implements of proxy locking is deferred
6832 ** until late in the file (here) after all of the other I/O methods have
6833 ** been defined - so that the primitive locking methods are available
6834 ** as services to help with the implementation of proxy locking.
6838 ** The default locking schemes in SQLite use byte-range locks on the
6839 ** database file to coordinate safe, concurrent access by multiple readers
6840 ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6841 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6842 ** as POSIX read & write locks over fixed set of locations (via fsctl),
6843 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
6844 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6845 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6846 ** address in the shared range is taken for a SHARED lock, the entire
6847 ** shared range is taken for an EXCLUSIVE lock):
6849 ** PENDING_BYTE 0x40000000
6850 ** RESERVED_BYTE 0x40000001
6851 ** SHARED_RANGE 0x40000002 -> 0x40000200
6853 ** This works well on the local file system, but shows a nearly 100x
6854 ** slowdown in read performance on AFP because the AFP client disables
6855 ** the read cache when byte-range locks are present. Enabling the read
6856 ** cache exposes a cache coherency problem that is present on all OS X
6857 ** supported network file systems. NFS and AFP both observe the
6858 ** close-to-open semantics for ensuring cache coherency
6859 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6860 ** address the requirements for concurrent database access by multiple
6861 ** readers and writers
6862 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6864 ** To address the performance and cache coherency issues, proxy file locking
6865 ** changes the way database access is controlled by limiting access to a
6866 ** single host at a time and moving file locks off of the database file
6867 ** and onto a proxy file on the local file system.
6870 ** Using proxy locks
6871 ** -----------------
6875 ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
6876 ** <proxy_path> | ":auto:");
6877 ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6883 ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6884 ** PRAGMA [database.]lock_proxy_file
6886 ** Specifying ":auto:" means that if there is a conch file with a matching
6887 ** host ID in it, the proxy path in the conch file will be used, otherwise
6888 ** a proxy path based on the user's temp dir
6889 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6890 ** actual proxy file name is generated from the name and path of the
6891 ** database file. For example:
6893 ** For database path "/Users/me/foo.db"
6894 ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6896 ** Once a lock proxy is configured for a database connection, it can not
6897 ** be removed, however it may be switched to a different proxy path via
6898 ** the above APIs (assuming the conch file is not being held by another
6899 ** connection or process).
6902 ** How proxy locking works
6903 ** -----------------------
6905 ** Proxy file locking relies primarily on two new supporting files:
6907 ** * conch file to limit access to the database file to a single host
6910 ** * proxy file to act as a proxy for the advisory locks normally
6911 ** taken on the database
6913 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
6914 ** by taking an sqlite-style shared lock on the conch file, reading the
6915 ** contents and comparing the host's unique host ID (see below) and lock
6916 ** proxy path against the values stored in the conch. The conch file is
6917 ** stored in the same directory as the database file and the file name
6918 ** is patterned after the database file name as ".<databasename>-conch".
6919 ** If the conch file does not exist, or its contents do not match the
6920 ** host ID and/or proxy path, then the lock is escalated to an exclusive
6921 ** lock and the conch file contents is updated with the host ID and proxy
6922 ** path and the lock is downgraded to a shared lock again. If the conch
6923 ** is held by another process (with a shared lock), the exclusive lock
6924 ** will fail and SQLITE_BUSY is returned.
6926 ** The proxy file - a single-byte file used for all advisory file locks
6927 ** normally taken on the database file. This allows for safe sharing
6928 ** of the database file for multiple readers and writers on the same
6929 ** host (the conch ensures that they all use the same local lock file).
6931 ** Requesting the lock proxy does not immediately take the conch, it is
6932 ** only taken when the first request to lock database file is made.
6933 ** This matches the semantics of the traditional locking behavior, where
6934 ** opening a connection to a database file does not take a lock on it.
6935 ** The shared lock and an open file descriptor are maintained until
6936 ** the connection to the database is closed.
6938 ** The proxy file and the lock file are never deleted so they only need
6939 ** to be created the first time they are used.
6941 ** Configuration options
6942 ** ---------------------
6944 ** SQLITE_PREFER_PROXY_LOCKING
6946 ** Database files accessed on non-local file systems are
6947 ** automatically configured for proxy locking, lock files are
6948 ** named automatically using the same logic as
6949 ** PRAGMA lock_proxy_file=":auto:"
6951 ** SQLITE_PROXY_DEBUG
6953 ** Enables the logging of error messages during host id file
6954 ** retrieval and creation
6958 ** Overrides the default directory used for lock proxy files that
6959 ** are named automatically via the ":auto:" setting
6961 ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6963 ** Permissions to use when creating a directory for storing the
6964 ** lock proxy files, only used when LOCKPROXYDIR is not set.
6967 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6968 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6969 ** force proxy locking to be used for every database file opened, and 0
6970 ** will force automatic proxy locking to be disabled for all database
6971 ** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
6972 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6976 ** Proxy locking is only available on MacOSX
6978 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
6981 ** The proxyLockingContext has the path and file structures for the remote
6982 ** and local proxy files in it
6984 typedef struct proxyLockingContext proxyLockingContext
;
6985 struct proxyLockingContext
{
6986 unixFile
*conchFile
; /* Open conch file */
6987 char *conchFilePath
; /* Name of the conch file */
6988 unixFile
*lockProxy
; /* Open proxy lock file */
6989 char *lockProxyPath
; /* Name of the proxy lock file */
6990 char *dbPath
; /* Name of the open file */
6991 int conchHeld
; /* 1 if the conch is held, -1 if lockless */
6992 int nFails
; /* Number of conch taking failures */
6993 void *oldLockingContext
; /* Original lockingcontext to restore on close */
6994 sqlite3_io_methods
const *pOldMethod
; /* Original I/O methods for close */
6998 ** The proxy lock file path for the database at dbPath is written into lPath,
6999 ** which must point to valid, writable memory large enough for a maxLen length
7002 static int proxyGetLockPath(const char *dbPath
, char *lPath
, size_t maxLen
){
7008 len
= strlcpy(lPath
, LOCKPROXYDIR
, maxLen
);
7010 # ifdef _CS_DARWIN_USER_TEMP_DIR
7012 if( !confstr(_CS_DARWIN_USER_TEMP_DIR
, lPath
, maxLen
) ){
7013 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
7014 lPath
, errno
, osGetpid(0)));
7015 return SQLITE_IOERR_LOCK
;
7017 len
= strlcat(lPath
, "sqliteplocks", maxLen
);
7020 len
= strlcpy(lPath
, "/tmp/", maxLen
);
7024 if( lPath
[len
-1]!='/' ){
7025 len
= strlcat(lPath
, "/", maxLen
);
7028 /* transform the db path to a unique cache name */
7029 dbLen
= (int)strlen(dbPath
);
7030 for( i
=0; i
<dbLen
&& (i
+len
+7)<(int)maxLen
; i
++){
7032 lPath
[i
+len
] = (c
=='/')?'_':c
;
7035 strlcat(lPath
, ":auto:", maxLen
);
7036 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath
, osGetpid(0)));
7041 ** Creates the lock file and any missing directories in lockPath
7043 static int proxyCreateLockPath(const char *lockPath
){
7045 char buf
[MAXPATHLEN
];
7048 assert(lockPath
!=NULL
);
7049 /* try to create all the intermediate directories */
7050 len
= (int)strlen(lockPath
);
7051 buf
[0] = lockPath
[0];
7052 for( i
=1; i
<len
; i
++ ){
7053 if( lockPath
[i
] == '/' && (i
- start
> 0) ){
7054 /* only mkdir if leaf dir != "." or "/" or ".." */
7055 if( i
-start
>2 || (i
-start
==1 && buf
[start
] != '.' && buf
[start
] != '/')
7056 || (i
-start
==2 && buf
[start
] != '.' && buf
[start
+1] != '.') ){
7058 if( osMkdir(buf
, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
) ){
7061 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
7062 "'%s' proxy lock path=%s pid=%d\n",
7063 buf
, strerror(err
), lockPath
, osGetpid(0)));
7070 buf
[i
] = lockPath
[i
];
7072 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath
,osGetpid(0)));
7077 ** Create a new VFS file descriptor (stored in memory obtained from
7078 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
7080 ** The caller is responsible not only for closing the file descriptor
7081 ** but also for freeing the memory associated with the file descriptor.
7083 static int proxyCreateUnixFile(
7084 const char *path
, /* path for the new unixFile */
7085 unixFile
**ppFile
, /* unixFile created and returned by ref */
7086 int islockfile
/* if non zero missing dirs will be created */
7091 int openFlags
= O_RDWR
| O_CREAT
| O_NOFOLLOW
;
7092 sqlite3_vfs dummyVfs
;
7094 UnixUnusedFd
*pUnused
= NULL
;
7096 /* 1. first try to open/create the file
7097 ** 2. if that fails, and this is a lock file (not-conch), try creating
7098 ** the parent directories and then try again.
7099 ** 3. if that fails, try to open the file read-only
7100 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
7102 pUnused
= findReusableFd(path
, openFlags
);
7106 pUnused
= sqlite3_malloc64(sizeof(*pUnused
));
7108 return SQLITE_NOMEM_BKPT
;
7112 fd
= robust_open(path
, openFlags
, 0);
7114 if( fd
<0 && errno
==ENOENT
&& islockfile
){
7115 if( proxyCreateLockPath(path
) == SQLITE_OK
){
7116 fd
= robust_open(path
, openFlags
, 0);
7121 openFlags
= O_RDONLY
| O_NOFOLLOW
;
7122 fd
= robust_open(path
, openFlags
, 0);
7133 return SQLITE_IOERR_LOCK
; /* even though it is the conch */
7135 return SQLITE_CANTOPEN_BKPT
;
7139 pNew
= (unixFile
*)sqlite3_malloc64(sizeof(*pNew
));
7141 rc
= SQLITE_NOMEM_BKPT
;
7142 goto end_create_proxy
;
7144 memset(pNew
, 0, sizeof(unixFile
));
7145 pNew
->openFlags
= openFlags
;
7146 memset(&dummyVfs
, 0, sizeof(dummyVfs
));
7147 dummyVfs
.pAppData
= (void*)&autolockIoFinder
;
7148 dummyVfs
.zName
= "dummy";
7150 pUnused
->flags
= openFlags
;
7151 pNew
->pPreallocatedUnused
= pUnused
;
7153 rc
= fillInUnixFile(&dummyVfs
, fd
, (sqlite3_file
*)pNew
, path
, 0);
7154 if( rc
==SQLITE_OK
){
7159 robust_close(pNew
, fd
, __LINE__
);
7161 sqlite3_free(pUnused
);
7166 /* simulate multiple hosts by creating unique hostid file paths */
7167 int sqlite3_hostid_num
= 0;
7170 #define PROXY_HOSTIDLEN 16 /* conch file host id length */
7172 #if HAVE_GETHOSTUUID
7173 /* Not always defined in the headers as it ought to be */
7174 extern int gethostuuid(uuid_t id
, const struct timespec
*wait
);
7177 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
7178 ** bytes of writable memory.
7180 static int proxyGetHostID(unsigned char *pHostID
, int *pError
){
7181 assert(PROXY_HOSTIDLEN
== sizeof(uuid_t
));
7182 memset(pHostID
, 0, PROXY_HOSTIDLEN
);
7183 #if HAVE_GETHOSTUUID
7185 struct timespec timeout
= {1, 0}; /* 1 sec timeout */
7186 if( gethostuuid(pHostID
, &timeout
) ){
7191 return SQLITE_IOERR
;
7195 UNUSED_PARAMETER(pError
);
7198 /* simulate multiple hosts by creating unique hostid file paths */
7199 if( sqlite3_hostid_num
!= 0){
7200 pHostID
[0] = (char)(pHostID
[0] + (char)(sqlite3_hostid_num
& 0xFF));
7207 /* The conch file contains the header, host id and lock file path
7209 #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
7210 #define PROXY_HEADERLEN 1 /* conch file header length */
7211 #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
7212 #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
7215 ** Takes an open conch file, copies the contents to a new path and then moves
7216 ** it back. The newly created file's file descriptor is assigned to the
7217 ** conch file structure and finally the original conch file descriptor is
7218 ** closed. Returns zero if successful.
7220 static int proxyBreakConchLock(unixFile
*pFile
, uuid_t myHostID
){
7221 proxyLockingContext
*pCtx
= (proxyLockingContext
*)pFile
->lockingContext
;
7222 unixFile
*conchFile
= pCtx
->conchFile
;
7223 char tPath
[MAXPATHLEN
];
7224 char buf
[PROXY_MAXCONCHLEN
];
7225 char *cPath
= pCtx
->conchFilePath
;
7228 char errmsg
[64] = "";
7231 UNUSED_PARAMETER(myHostID
);
7233 /* create a new path by replace the trailing '-conch' with '-break' */
7234 pathLen
= strlcpy(tPath
, cPath
, MAXPATHLEN
);
7235 if( pathLen
>MAXPATHLEN
|| pathLen
<6 ||
7236 (strlcpy(&tPath
[pathLen
-5], "break", 6) != 5) ){
7237 sqlite3_snprintf(sizeof(errmsg
),errmsg
,"path error (len %d)",(int)pathLen
);
7240 /* read the conch content */
7241 readLen
= osPread(conchFile
->h
, buf
, PROXY_MAXCONCHLEN
, 0);
7242 if( readLen
<PROXY_PATHINDEX
){
7243 sqlite3_snprintf(sizeof(errmsg
),errmsg
,"read error (len %d)",(int)readLen
);
7246 /* write it out to the temporary break file */
7247 fd
= robust_open(tPath
, (O_RDWR
|O_CREAT
|O_EXCL
|O_NOFOLLOW
), 0);
7249 sqlite3_snprintf(sizeof(errmsg
), errmsg
, "create failed (%d)", errno
);
7252 if( osPwrite(fd
, buf
, readLen
, 0) != (ssize_t
)readLen
){
7253 sqlite3_snprintf(sizeof(errmsg
), errmsg
, "write failed (%d)", errno
);
7256 if( rename(tPath
, cPath
) ){
7257 sqlite3_snprintf(sizeof(errmsg
), errmsg
, "rename failed (%d)", errno
);
7261 fprintf(stderr
, "broke stale lock on %s\n", cPath
);
7262 robust_close(pFile
, conchFile
->h
, __LINE__
);
7264 conchFile
->openFlags
= O_RDWR
| O_CREAT
;
7270 robust_close(pFile
, fd
, __LINE__
);
7272 fprintf(stderr
, "failed to break stale lock on %s, %s\n", cPath
, errmsg
);
7277 /* Take the requested lock on the conch file and break a stale lock if the
7280 static int proxyConchLock(unixFile
*pFile
, uuid_t myHostID
, int lockType
){
7281 proxyLockingContext
*pCtx
= (proxyLockingContext
*)pFile
->lockingContext
;
7282 unixFile
*conchFile
= pCtx
->conchFile
;
7285 struct timespec conchModTime
;
7287 memset(&conchModTime
, 0, sizeof(conchModTime
));
7289 rc
= conchFile
->pMethod
->xLock((sqlite3_file
*)conchFile
, lockType
);
7291 if( rc
==SQLITE_BUSY
){
7292 /* If the lock failed (busy):
7293 * 1st try: get the mod time of the conch, wait 0.5s and try again.
7294 * 2nd try: fail if the mod time changed or host id is different, wait
7295 * 10 sec and try again
7296 * 3rd try: break the lock unless the mod time has changed.
7299 if( osFstat(conchFile
->h
, &buf
) ){
7300 storeLastErrno(pFile
, errno
);
7301 return SQLITE_IOERR_LOCK
;
7305 conchModTime
= buf
.st_mtimespec
;
7306 unixSleep(0,500000); /* wait 0.5 sec and try the lock again*/
7311 if( conchModTime
.tv_sec
!= buf
.st_mtimespec
.tv_sec
||
7312 conchModTime
.tv_nsec
!= buf
.st_mtimespec
.tv_nsec
){
7317 char tBuf
[PROXY_MAXCONCHLEN
];
7318 int len
= osPread(conchFile
->h
, tBuf
, PROXY_MAXCONCHLEN
, 0);
7320 storeLastErrno(pFile
, errno
);
7321 return SQLITE_IOERR_LOCK
;
7323 if( len
>PROXY_PATHINDEX
&& tBuf
[0]==(char)PROXY_CONCHVERSION
){
7324 /* don't break the lock if the host id doesn't match */
7325 if( 0!=memcmp(&tBuf
[PROXY_HEADERLEN
], myHostID
, PROXY_HOSTIDLEN
) ){
7329 /* don't break the lock on short read or a version mismatch */
7332 unixSleep(0,10000000); /* wait 10 sec and try the lock again */
7336 assert( nTries
==3 );
7337 if( 0==proxyBreakConchLock(pFile
, myHostID
) ){
7339 if( lockType
==EXCLUSIVE_LOCK
){
7340 rc
= conchFile
->pMethod
->xLock((sqlite3_file
*)conchFile
, SHARED_LOCK
);
7343 rc
= conchFile
->pMethod
->xLock((sqlite3_file
*)conchFile
, lockType
);
7347 } while( rc
==SQLITE_BUSY
&& nTries
<3 );
7352 /* Takes the conch by taking a shared lock and read the contents conch, if
7353 ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
7354 ** lockPath means that the lockPath in the conch file will be used if the
7355 ** host IDs match, or a new lock path will be generated automatically
7356 ** and written to the conch file.
7358 static int proxyTakeConch(unixFile
*pFile
){
7359 proxyLockingContext
*pCtx
= (proxyLockingContext
*)pFile
->lockingContext
;
7361 if( pCtx
->conchHeld
!=0 ){
7364 unixFile
*conchFile
= pCtx
->conchFile
;
7367 char readBuf
[PROXY_MAXCONCHLEN
];
7368 char lockPath
[MAXPATHLEN
];
7369 char *tempLockPath
= NULL
;
7371 int createConch
= 0;
7372 int hostIdMatch
= 0;
7374 int tryOldLockPath
= 0;
7375 int forceNewLockPath
= 0;
7377 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile
->h
,
7378 (pCtx
->lockProxyPath
? pCtx
->lockProxyPath
: ":auto:"),
7381 rc
= proxyGetHostID(myHostID
, &pError
);
7382 if( (rc
&0xff)==SQLITE_IOERR
){
7383 storeLastErrno(pFile
, pError
);
7386 rc
= proxyConchLock(pFile
, myHostID
, SHARED_LOCK
);
7387 if( rc
!=SQLITE_OK
){
7390 /* read the existing conch file */
7391 readLen
= seekAndRead((unixFile
*)conchFile
, 0, readBuf
, PROXY_MAXCONCHLEN
);
7393 /* I/O error: lastErrno set by seekAndRead */
7394 storeLastErrno(pFile
, conchFile
->lastErrno
);
7395 rc
= SQLITE_IOERR_READ
;
7397 }else if( readLen
<=(PROXY_HEADERLEN
+PROXY_HOSTIDLEN
) ||
7398 readBuf
[0]!=(char)PROXY_CONCHVERSION
){
7399 /* a short read or version format mismatch means we need to create a new
7404 /* if the host id matches and the lock path already exists in the conch
7405 ** we'll try to use the path there, if we can't open that path, we'll
7406 ** retry with a new auto-generated path
7408 do { /* in case we need to try again for an :auto: named lock file */
7410 if( !createConch
&& !forceNewLockPath
){
7411 hostIdMatch
= !memcmp(&readBuf
[PROXY_HEADERLEN
], myHostID
,
7413 /* if the conch has data compare the contents */
7414 if( !pCtx
->lockProxyPath
){
7415 /* for auto-named local lock file, just check the host ID and we'll
7416 ** use the local lock file path that's already in there
7419 size_t pathLen
= (readLen
- PROXY_PATHINDEX
);
7421 if( pathLen
>=MAXPATHLEN
){
7422 pathLen
=MAXPATHLEN
-1;
7424 memcpy(lockPath
, &readBuf
[PROXY_PATHINDEX
], pathLen
);
7425 lockPath
[pathLen
] = 0;
7426 tempLockPath
= lockPath
;
7428 /* create a copy of the lock path if the conch is taken */
7431 }else if( hostIdMatch
7432 && !strncmp(pCtx
->lockProxyPath
, &readBuf
[PROXY_PATHINDEX
],
7433 readLen
-PROXY_PATHINDEX
)
7435 /* conch host and lock path match */
7440 /* if the conch isn't writable and doesn't match, we can't take it */
7441 if( (conchFile
->openFlags
&O_RDWR
) == 0 ){
7446 /* either the conch didn't match or we need to create a new one */
7447 if( !pCtx
->lockProxyPath
){
7448 proxyGetLockPath(pCtx
->dbPath
, lockPath
, MAXPATHLEN
);
7449 tempLockPath
= lockPath
;
7450 /* create a copy of the lock path _only_ if the conch is taken */
7453 /* update conch with host and path (this will fail if other process
7454 ** has a shared lock already), if the host id matches, use the big
7457 futimes(conchFile
->h
, NULL
);
7458 if( hostIdMatch
&& !createConch
){
7459 if( conchFile
->pInode
&& conchFile
->pInode
->nShared
>1 ){
7460 /* We are trying for an exclusive lock but another thread in this
7461 ** same process is still holding a shared lock. */
7464 rc
= proxyConchLock(pFile
, myHostID
, EXCLUSIVE_LOCK
);
7467 rc
= proxyConchLock(pFile
, myHostID
, EXCLUSIVE_LOCK
);
7469 if( rc
==SQLITE_OK
){
7470 char writeBuffer
[PROXY_MAXCONCHLEN
];
7473 writeBuffer
[0] = (char)PROXY_CONCHVERSION
;
7474 memcpy(&writeBuffer
[PROXY_HEADERLEN
], myHostID
, PROXY_HOSTIDLEN
);
7475 if( pCtx
->lockProxyPath
!=NULL
){
7476 strlcpy(&writeBuffer
[PROXY_PATHINDEX
], pCtx
->lockProxyPath
,
7479 strlcpy(&writeBuffer
[PROXY_PATHINDEX
], tempLockPath
, MAXPATHLEN
);
7481 writeSize
= PROXY_PATHINDEX
+ strlen(&writeBuffer
[PROXY_PATHINDEX
]);
7482 robust_ftruncate(conchFile
->h
, writeSize
);
7483 rc
= unixWrite((sqlite3_file
*)conchFile
, writeBuffer
, writeSize
, 0);
7484 full_fsync(conchFile
->h
,0,0);
7485 /* If we created a new conch file (not just updated the contents of a
7486 ** valid conch file), try to match the permissions of the database
7488 if( rc
==SQLITE_OK
&& createConch
){
7490 int err
= osFstat(pFile
->h
, &buf
);
7492 mode_t cmode
= buf
.st_mode
&(S_IRUSR
|S_IWUSR
| S_IRGRP
|S_IWGRP
|
7494 /* try to match the database file R/W permissions, ignore failure */
7495 #ifndef SQLITE_PROXY_DEBUG
7496 osFchmod(conchFile
->h
, cmode
);
7499 rc
= osFchmod(conchFile
->h
, cmode
);
7500 }while( rc
==(-1) && errno
==EINTR
);
7503 fprintf(stderr
, "fchmod %o FAILED with %d %s\n",
7504 cmode
, code
, strerror(code
));
7506 fprintf(stderr
, "fchmod %o SUCCEDED\n",cmode
);
7510 fprintf(stderr
, "STAT FAILED[%d] with %d %s\n",
7511 err
, code
, strerror(code
));
7516 conchFile
->pMethod
->xUnlock((sqlite3_file
*)conchFile
, SHARED_LOCK
);
7519 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile
->h
));
7520 if( rc
==SQLITE_OK
&& pFile
->openFlags
){
7523 robust_close(pFile
, pFile
->h
, __LINE__
);
7526 fd
= robust_open(pCtx
->dbPath
, pFile
->openFlags
, 0);
7527 OSTRACE(("TRANSPROXY: OPEN %d\n", fd
));
7531 rc
=SQLITE_CANTOPEN_BKPT
; /* SQLITE_BUSY? proxyTakeConch called
7535 if( rc
==SQLITE_OK
&& !pCtx
->lockProxy
){
7536 char *path
= tempLockPath
? tempLockPath
: pCtx
->lockProxyPath
;
7537 rc
= proxyCreateUnixFile(path
, &pCtx
->lockProxy
, 1);
7538 if( rc
!=SQLITE_OK
&& rc
!=SQLITE_NOMEM
&& tryOldLockPath
){
7539 /* we couldn't create the proxy lock file with the old lock file path
7540 ** so try again via auto-naming
7542 forceNewLockPath
= 1;
7544 continue; /* go back to the do {} while start point, try again */
7547 if( rc
==SQLITE_OK
){
7548 /* Need to make a copy of path if we extracted the value
7549 ** from the conch file or the path was allocated on the stack
7552 pCtx
->lockProxyPath
= sqlite3DbStrDup(0, tempLockPath
);
7553 if( !pCtx
->lockProxyPath
){
7554 rc
= SQLITE_NOMEM_BKPT
;
7558 if( rc
==SQLITE_OK
){
7559 pCtx
->conchHeld
= 1;
7561 if( pCtx
->lockProxy
->pMethod
== &afpIoMethods
){
7562 afpLockingContext
*afpCtx
;
7563 afpCtx
= (afpLockingContext
*)pCtx
->lockProxy
->lockingContext
;
7564 afpCtx
->dbPath
= pCtx
->lockProxyPath
;
7567 conchFile
->pMethod
->xUnlock((sqlite3_file
*)conchFile
, NO_LOCK
);
7569 OSTRACE(("TAKECONCH %d %s\n", conchFile
->h
,
7570 rc
==SQLITE_OK
?"ok":"failed"));
7572 } while (1); /* in case we need to retry the :auto: lock file -
7573 ** we should never get here except via the 'continue' call. */
7578 ** If pFile holds a lock on a conch file, then release that lock.
7580 static int proxyReleaseConch(unixFile
*pFile
){
7581 int rc
= SQLITE_OK
; /* Subroutine return code */
7582 proxyLockingContext
*pCtx
; /* The locking context for the proxy lock */
7583 unixFile
*conchFile
; /* Name of the conch file */
7585 pCtx
= (proxyLockingContext
*)pFile
->lockingContext
;
7586 conchFile
= pCtx
->conchFile
;
7587 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile
->h
,
7588 (pCtx
->lockProxyPath
? pCtx
->lockProxyPath
: ":auto:"),
7590 if( pCtx
->conchHeld
>0 ){
7591 rc
= conchFile
->pMethod
->xUnlock((sqlite3_file
*)conchFile
, NO_LOCK
);
7593 pCtx
->conchHeld
= 0;
7594 OSTRACE(("RELEASECONCH %d %s\n", conchFile
->h
,
7595 (rc
==SQLITE_OK
? "ok" : "failed")));
7600 ** Given the name of a database file, compute the name of its conch file.
7601 ** Store the conch filename in memory obtained from sqlite3_malloc64().
7602 ** Make *pConchPath point to the new name. Return SQLITE_OK on success
7603 ** or SQLITE_NOMEM if unable to obtain memory.
7605 ** The caller is responsible for ensuring that the allocated memory
7606 ** space is eventually freed.
7608 ** *pConchPath is set to NULL if a memory allocation error occurs.
7610 static int proxyCreateConchPathname(char *dbPath
, char **pConchPath
){
7611 int i
; /* Loop counter */
7612 int len
= (int)strlen(dbPath
); /* Length of database filename - dbPath */
7613 char *conchPath
; /* buffer in which to construct conch name */
7615 /* Allocate space for the conch filename and initialize the name to
7616 ** the name of the original database file. */
7617 *pConchPath
= conchPath
= (char *)sqlite3_malloc64(len
+ 8);
7619 return SQLITE_NOMEM_BKPT
;
7621 memcpy(conchPath
, dbPath
, len
+1);
7623 /* now insert a "." before the last / character */
7624 for( i
=(len
-1); i
>=0; i
-- ){
7625 if( conchPath
[i
]=='/' ){
7632 conchPath
[i
+1]=dbPath
[i
];
7636 /* append the "-conch" suffix to the file */
7637 memcpy(&conchPath
[i
+1], "-conch", 7);
7638 assert( (int)strlen(conchPath
) == len
+7 );
7644 /* Takes a fully configured proxy locking-style unix file and switches
7645 ** the local lock file path
7647 static int switchLockProxyPath(unixFile
*pFile
, const char *path
) {
7648 proxyLockingContext
*pCtx
= (proxyLockingContext
*)pFile
->lockingContext
;
7649 char *oldPath
= pCtx
->lockProxyPath
;
7652 if( pFile
->eFileLock
!=NO_LOCK
){
7656 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7657 if( !path
|| path
[0]=='\0' || !strcmp(path
, ":auto:") ||
7658 (oldPath
&& !strncmp(oldPath
, path
, MAXPATHLEN
)) ){
7661 unixFile
*lockProxy
= pCtx
->lockProxy
;
7662 pCtx
->lockProxy
=NULL
;
7663 pCtx
->conchHeld
= 0;
7664 if( lockProxy
!=NULL
){
7665 rc
=lockProxy
->pMethod
->xClose((sqlite3_file
*)lockProxy
);
7667 sqlite3_free(lockProxy
);
7669 sqlite3_free(oldPath
);
7670 pCtx
->lockProxyPath
= sqlite3DbStrDup(0, path
);
7677 ** pFile is a file that has been opened by a prior xOpen call. dbPath
7678 ** is a string buffer at least MAXPATHLEN+1 characters in size.
7680 ** This routine find the filename associated with pFile and writes it
7683 static int proxyGetDbPathForUnixFile(unixFile
*pFile
, char *dbPath
){
7684 #if defined(__APPLE__)
7685 if( pFile
->pMethod
== &afpIoMethods
){
7686 /* afp style keeps a reference to the db path in the filePath field
7688 assert( (int)strlen((char*)pFile
->lockingContext
)<=MAXPATHLEN
);
7689 strlcpy(dbPath
, ((afpLockingContext
*)pFile
->lockingContext
)->dbPath
,
7693 if( pFile
->pMethod
== &dotlockIoMethods
){
7694 /* dot lock style uses the locking context to store the dot lock
7696 int len
= strlen((char *)pFile
->lockingContext
) - strlen(DOTLOCK_SUFFIX
);
7697 memcpy(dbPath
, (char *)pFile
->lockingContext
, len
+ 1);
7699 /* all other styles use the locking context to store the db file path */
7700 assert( strlen((char*)pFile
->lockingContext
)<=MAXPATHLEN
);
7701 strlcpy(dbPath
, (char *)pFile
->lockingContext
, MAXPATHLEN
);
7707 ** Takes an already filled in unix file and alters it so all file locking
7708 ** will be performed on the local proxy lock file. The following fields
7709 ** are preserved in the locking context so that they can be restored and
7710 ** the unix structure properly cleaned up at close time:
7714 static int proxyTransformUnixFile(unixFile
*pFile
, const char *path
) {
7715 proxyLockingContext
*pCtx
;
7716 char dbPath
[MAXPATHLEN
+1]; /* Name of the database file */
7717 char *lockPath
=NULL
;
7720 if( pFile
->eFileLock
!=NO_LOCK
){
7723 proxyGetDbPathForUnixFile(pFile
, dbPath
);
7724 if( !path
|| path
[0]=='\0' || !strcmp(path
, ":auto:") ){
7727 lockPath
=(char *)path
;
7730 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile
->h
,
7731 (lockPath
? lockPath
: ":auto:"), osGetpid(0)));
7733 pCtx
= sqlite3_malloc64( sizeof(*pCtx
) );
7735 return SQLITE_NOMEM_BKPT
;
7737 memset(pCtx
, 0, sizeof(*pCtx
));
7739 rc
= proxyCreateConchPathname(dbPath
, &pCtx
->conchFilePath
);
7740 if( rc
==SQLITE_OK
){
7741 rc
= proxyCreateUnixFile(pCtx
->conchFilePath
, &pCtx
->conchFile
, 0);
7742 if( rc
==SQLITE_CANTOPEN
&& ((pFile
->openFlags
&O_RDWR
) == 0) ){
7743 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7744 ** (c) the file system is read-only, then enable no-locking access.
7745 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7746 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7748 struct statfs fsInfo
;
7749 struct stat conchInfo
;
7752 if( osStat(pCtx
->conchFilePath
, &conchInfo
) == -1 ) {
7754 if( (err
==ENOENT
) && (statfs(dbPath
, &fsInfo
) != -1) ){
7755 goLockless
= (fsInfo
.f_flags
&MNT_RDONLY
) == MNT_RDONLY
;
7759 pCtx
->conchHeld
= -1; /* read only FS/ lockless */
7764 if( rc
==SQLITE_OK
&& lockPath
){
7765 pCtx
->lockProxyPath
= sqlite3DbStrDup(0, lockPath
);
7768 if( rc
==SQLITE_OK
){
7769 pCtx
->dbPath
= sqlite3DbStrDup(0, dbPath
);
7770 if( pCtx
->dbPath
==NULL
){
7771 rc
= SQLITE_NOMEM_BKPT
;
7774 if( rc
==SQLITE_OK
){
7775 /* all memory is allocated, proxys are created and assigned,
7776 ** switch the locking context and pMethod then return.
7778 pCtx
->oldLockingContext
= pFile
->lockingContext
;
7779 pFile
->lockingContext
= pCtx
;
7780 pCtx
->pOldMethod
= pFile
->pMethod
;
7781 pFile
->pMethod
= &proxyIoMethods
;
7783 if( pCtx
->conchFile
){
7784 pCtx
->conchFile
->pMethod
->xClose((sqlite3_file
*)pCtx
->conchFile
);
7785 sqlite3_free(pCtx
->conchFile
);
7787 sqlite3DbFree(0, pCtx
->lockProxyPath
);
7788 sqlite3_free(pCtx
->conchFilePath
);
7791 OSTRACE(("TRANSPROXY %d %s\n", pFile
->h
,
7792 (rc
==SQLITE_OK
? "ok" : "failed")));
7798 ** This routine handles sqlite3_file_control() calls that are specific
7799 ** to proxy locking.
7801 static int proxyFileControl(sqlite3_file
*id
, int op
, void *pArg
){
7803 case SQLITE_FCNTL_GET_LOCKPROXYFILE
: {
7804 unixFile
*pFile
= (unixFile
*)id
;
7805 if( pFile
->pMethod
== &proxyIoMethods
){
7806 proxyLockingContext
*pCtx
= (proxyLockingContext
*)pFile
->lockingContext
;
7807 proxyTakeConch(pFile
);
7808 if( pCtx
->lockProxyPath
){
7809 *(const char **)pArg
= pCtx
->lockProxyPath
;
7811 *(const char **)pArg
= ":auto: (not held)";
7814 *(const char **)pArg
= NULL
;
7818 case SQLITE_FCNTL_SET_LOCKPROXYFILE
: {
7819 unixFile
*pFile
= (unixFile
*)id
;
7821 int isProxyStyle
= (pFile
->pMethod
== &proxyIoMethods
);
7822 if( pArg
==NULL
|| (const char *)pArg
==0 ){
7824 /* turn off proxy locking - not supported. If support is added for
7825 ** switching proxy locking mode off then it will need to fail if
7826 ** the journal mode is WAL mode.
7828 rc
= SQLITE_ERROR
/*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7830 /* turn off proxy locking - already off - NOOP */
7834 const char *proxyPath
= (const char *)pArg
;
7836 proxyLockingContext
*pCtx
=
7837 (proxyLockingContext
*)pFile
->lockingContext
;
7838 if( !strcmp(pArg
, ":auto:")
7839 || (pCtx
->lockProxyPath
&&
7840 !strncmp(pCtx
->lockProxyPath
, proxyPath
, MAXPATHLEN
))
7844 rc
= switchLockProxyPath(pFile
, proxyPath
);
7847 /* turn on proxy file locking */
7848 rc
= proxyTransformUnixFile(pFile
, proxyPath
);
7854 assert( 0 ); /* The call assures that only valid opcodes are sent */
7857 /*NOTREACHED*/ assert(0);
7858 return SQLITE_ERROR
;
7862 ** Within this division (the proxying locking implementation) the procedures
7863 ** above this point are all utilities. The lock-related methods of the
7864 ** proxy-locking sqlite3_io_method object follow.
7869 ** This routine checks if there is a RESERVED lock held on the specified
7870 ** file by this or any other process. If such a lock is held, set *pResOut
7871 ** to a non-zero value otherwise *pResOut is set to zero. The return value
7872 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7874 static int proxyCheckReservedLock(sqlite3_file
*id
, int *pResOut
) {
7875 unixFile
*pFile
= (unixFile
*)id
;
7876 int rc
= proxyTakeConch(pFile
);
7877 if( rc
==SQLITE_OK
){
7878 proxyLockingContext
*pCtx
= (proxyLockingContext
*)pFile
->lockingContext
;
7879 if( pCtx
->conchHeld
>0 ){
7880 unixFile
*proxy
= pCtx
->lockProxy
;
7881 return proxy
->pMethod
->xCheckReservedLock((sqlite3_file
*)proxy
, pResOut
);
7882 }else{ /* conchHeld < 0 is lockless */
7890 ** Lock the file with the lock specified by parameter eFileLock - one
7891 ** of the following:
7894 ** (2) RESERVED_LOCK
7896 ** (4) EXCLUSIVE_LOCK
7898 ** Sometimes when requesting one lock state, additional lock states
7899 ** are inserted in between. The locking might fail on one of the later
7900 ** transitions leaving the lock state different from what it started but
7901 ** still short of its goal. The following chart shows the allowed
7902 ** transitions and the inserted intermediate states:
7904 ** UNLOCKED -> SHARED
7905 ** SHARED -> RESERVED
7906 ** SHARED -> (PENDING) -> EXCLUSIVE
7907 ** RESERVED -> (PENDING) -> EXCLUSIVE
7908 ** PENDING -> EXCLUSIVE
7910 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
7911 ** routine to lower a locking level.
7913 static int proxyLock(sqlite3_file
*id
, int eFileLock
) {
7914 unixFile
*pFile
= (unixFile
*)id
;
7915 int rc
= proxyTakeConch(pFile
);
7916 if( rc
==SQLITE_OK
){
7917 proxyLockingContext
*pCtx
= (proxyLockingContext
*)pFile
->lockingContext
;
7918 if( pCtx
->conchHeld
>0 ){
7919 unixFile
*proxy
= pCtx
->lockProxy
;
7920 rc
= proxy
->pMethod
->xLock((sqlite3_file
*)proxy
, eFileLock
);
7921 pFile
->eFileLock
= proxy
->eFileLock
;
7923 /* conchHeld < 0 is lockless */
7931 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
7932 ** must be either NO_LOCK or SHARED_LOCK.
7934 ** If the locking level of the file descriptor is already at or below
7935 ** the requested locking level, this routine is a no-op.
7937 static int proxyUnlock(sqlite3_file
*id
, int eFileLock
) {
7938 unixFile
*pFile
= (unixFile
*)id
;
7939 int rc
= proxyTakeConch(pFile
);
7940 if( rc
==SQLITE_OK
){
7941 proxyLockingContext
*pCtx
= (proxyLockingContext
*)pFile
->lockingContext
;
7942 if( pCtx
->conchHeld
>0 ){
7943 unixFile
*proxy
= pCtx
->lockProxy
;
7944 rc
= proxy
->pMethod
->xUnlock((sqlite3_file
*)proxy
, eFileLock
);
7945 pFile
->eFileLock
= proxy
->eFileLock
;
7947 /* conchHeld < 0 is lockless */
7954 ** Close a file that uses proxy locks.
7956 static int proxyClose(sqlite3_file
*id
) {
7958 unixFile
*pFile
= (unixFile
*)id
;
7959 proxyLockingContext
*pCtx
= (proxyLockingContext
*)pFile
->lockingContext
;
7960 unixFile
*lockProxy
= pCtx
->lockProxy
;
7961 unixFile
*conchFile
= pCtx
->conchFile
;
7965 rc
= lockProxy
->pMethod
->xUnlock((sqlite3_file
*)lockProxy
, NO_LOCK
);
7967 rc
= lockProxy
->pMethod
->xClose((sqlite3_file
*)lockProxy
);
7969 sqlite3_free(lockProxy
);
7970 pCtx
->lockProxy
= 0;
7973 if( pCtx
->conchHeld
){
7974 rc
= proxyReleaseConch(pFile
);
7977 rc
= conchFile
->pMethod
->xClose((sqlite3_file
*)conchFile
);
7979 sqlite3_free(conchFile
);
7981 sqlite3DbFree(0, pCtx
->lockProxyPath
);
7982 sqlite3_free(pCtx
->conchFilePath
);
7983 sqlite3DbFree(0, pCtx
->dbPath
);
7984 /* restore the original locking context and pMethod then close it */
7985 pFile
->lockingContext
= pCtx
->oldLockingContext
;
7986 pFile
->pMethod
= pCtx
->pOldMethod
;
7988 return pFile
->pMethod
->xClose(id
);
7995 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
7997 ** The proxy locking style is intended for use with AFP filesystems.
7998 ** And since AFP is only supported on MacOSX, the proxy locking is also
7999 ** restricted to MacOSX.
8002 ******************* End of the proxy lock implementation **********************
8003 ******************************************************************************/
8006 ** Initialize the operating system interface.
8008 ** This routine registers all VFS implementations for unix-like operating
8009 ** systems. This routine, and the sqlite3_os_end() routine that follows,
8010 ** should be the only routines in this file that are visible from other
8013 ** This routine is called once during SQLite initialization and by a
8014 ** single thread. The memory allocation and mutex subsystems have not
8015 ** necessarily been initialized when this routine is called, and so they
8016 ** should not be used.
8018 int sqlite3_os_init(void){
8020 ** The following macro defines an initializer for an sqlite3_vfs object.
8021 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
8022 ** to the "finder" function. (pAppData is a pointer to a pointer because
8023 ** silly C90 rules prohibit a void* from being cast to a function pointer
8024 ** and so we have to go through the intermediate pointer to avoid problems
8025 ** when compiling with -pedantic-errors on GCC.)
8027 ** The FINDER parameter to this macro is the name of the pointer to the
8028 ** finder-function. The finder-function returns a pointer to the
8029 ** sqlite_io_methods object that implements the desired locking
8030 ** behaviors. See the division above that contains the IOMETHODS
8031 ** macro for addition information on finder-functions.
8033 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
8034 ** object. But the "autolockIoFinder" available on MacOSX does a little
8035 ** more than that; it looks at the filesystem type that hosts the
8036 ** database file and tries to choose an locking method appropriate for
8037 ** that filesystem time.
8039 #define UNIXVFS(VFSNAME, FINDER) { \
8041 sizeof(unixFile), /* szOsFile */ \
8042 MAX_PATHNAME, /* mxPathname */ \
8044 VFSNAME, /* zName */ \
8045 (void*)&FINDER, /* pAppData */ \
8046 unixOpen, /* xOpen */ \
8047 unixDelete, /* xDelete */ \
8048 unixAccess, /* xAccess */ \
8049 unixFullPathname, /* xFullPathname */ \
8050 unixDlOpen, /* xDlOpen */ \
8051 unixDlError, /* xDlError */ \
8052 unixDlSym, /* xDlSym */ \
8053 unixDlClose, /* xDlClose */ \
8054 unixRandomness, /* xRandomness */ \
8055 unixSleep, /* xSleep */ \
8056 unixCurrentTime, /* xCurrentTime */ \
8057 unixGetLastError, /* xGetLastError */ \
8058 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
8059 unixSetSystemCall, /* xSetSystemCall */ \
8060 unixGetSystemCall, /* xGetSystemCall */ \
8061 unixNextSystemCall, /* xNextSystemCall */ \
8065 ** All default VFSes for unix are contained in the following array.
8067 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
8068 ** by the SQLite core when the VFS is registered. So the following
8069 ** array cannot be const.
8071 static sqlite3_vfs aVfs
[] = {
8072 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
8073 UNIXVFS("unix", autolockIoFinder
),
8075 UNIXVFS("unix", vxworksIoFinder
),
8077 UNIXVFS("unix", posixIoFinder
),
8079 UNIXVFS("unix-none", nolockIoFinder
),
8080 UNIXVFS("unix-dotfile", dotlockIoFinder
),
8081 UNIXVFS("unix-excl", posixIoFinder
),
8083 UNIXVFS("unix-namedsem", semIoFinder
),
8085 #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
8086 UNIXVFS("unix-posix", posixIoFinder
),
8088 #if SQLITE_ENABLE_LOCKING_STYLE
8089 UNIXVFS("unix-flock", flockIoFinder
),
8091 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
8092 UNIXVFS("unix-afp", afpIoFinder
),
8093 UNIXVFS("unix-nfs", nfsIoFinder
),
8094 UNIXVFS("unix-proxy", proxyIoFinder
),
8097 unsigned int i
; /* Loop counter */
8099 /* Double-check that the aSyscall[] array has been constructed
8100 ** correctly. See ticket [bb3a86e890c8e96ab] */
8101 assert( ArraySize(aSyscall
)==29 );
8103 /* Register all VFSes defined in the aVfs[] array */
8104 for(i
=0; i
<(sizeof(aVfs
)/sizeof(sqlite3_vfs
)); i
++){
8105 #ifdef SQLITE_DEFAULT_UNIX_VFS
8106 sqlite3_vfs_register(&aVfs
[i
],
8107 0==strcmp(aVfs
[i
].zName
,SQLITE_DEFAULT_UNIX_VFS
));
8109 sqlite3_vfs_register(&aVfs
[i
], i
==0);
8112 #ifdef SQLITE_OS_KV_OPTIONAL
8115 unixBigLock
= sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1
);
8117 #ifndef SQLITE_OMIT_WAL
8118 /* Validate lock assumptions */
8119 assert( SQLITE_SHM_NLOCK
==8 ); /* Number of available locks */
8120 assert( UNIX_SHM_BASE
==120 ); /* Start of locking area */
8122 ** WRITE UNIX_SHM_BASE 120
8123 ** CKPT UNIX_SHM_BASE+1 121
8124 ** RECOVER UNIX_SHM_BASE+2 122
8125 ** READ-0 UNIX_SHM_BASE+3 123
8126 ** READ-1 UNIX_SHM_BASE+4 124
8127 ** READ-2 UNIX_SHM_BASE+5 125
8128 ** READ-3 UNIX_SHM_BASE+6 126
8129 ** READ-4 UNIX_SHM_BASE+7 127
8130 ** DMS UNIX_SHM_BASE+8 128
8132 assert( UNIX_SHM_DMS
==128 ); /* Byte offset of the deadman-switch */
8135 /* Initialize temp file dir array. */
8142 ** Shutdown the operating system interface.
8144 ** Some operating systems might need to do some cleanup in this routine,
8145 ** to release dynamically allocated objects. But not on unix.
8146 ** This routine is a no-op for unix.
8148 int sqlite3_os_end(void){
8153 #endif /* SQLITE_OS_UNIX */