Updates to the sqlite3_file_control() documentation. No changes to code.
[sqlite.git] / src / os_unix.c
blob2d377ef56afe436efbe86f27286f9c143ca9c77b
1 /*
2 ** 2004 May 22
3 **
4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
6 **
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 ******************************************************************************
13 ** This file contains the VFS implementation for unix-like operating systems
14 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
16 ** There are actually several different VFS implementations in this file.
17 ** The differences are in the way that file locking is done. The default
18 ** implementation uses Posix Advisory Locks. Alternative implementations
19 ** use flock(), dot-files, various proprietary locking schemas, or simply
20 ** skip locking all together.
22 ** This source file is organized into divisions where the logic for various
23 ** subfunctions is contained within the appropriate division. PLEASE
24 ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
25 ** in the correct division and should be clearly labeled.
27 ** The layout of divisions is as follows:
29 ** * General-purpose declarations and utility functions.
30 ** * Unique file ID logic used by VxWorks.
31 ** * Various locking primitive implementations (all except proxy locking):
32 ** + for Posix Advisory Locks
33 ** + for no-op locks
34 ** + for dot-file locks
35 ** + for flock() locking
36 ** + for named semaphore locks (VxWorks only)
37 ** + for AFP filesystem locks (MacOSX only)
38 ** * sqlite3_file methods not associated with locking.
39 ** * Definitions of sqlite3_io_methods objects for all locking
40 ** methods plus "finder" functions for each locking method.
41 ** * sqlite3_vfs method implementations.
42 ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
43 ** * Definitions of sqlite3_vfs objects for all locking methods
44 ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
46 #include "sqliteInt.h"
47 #if SQLITE_OS_UNIX /* This file is used on unix only */
50 ** There are various methods for file locking used for concurrency
51 ** control:
53 ** 1. POSIX locking (the default),
54 ** 2. No locking,
55 ** 3. Dot-file locking,
56 ** 4. flock() locking,
57 ** 5. AFP locking (OSX only),
58 ** 6. Named POSIX semaphores (VXWorks only),
59 ** 7. proxy locking. (OSX only)
61 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
62 ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
63 ** selection of the appropriate locking style based on the filesystem
64 ** where the database is located.
66 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
67 # if defined(__APPLE__)
68 # define SQLITE_ENABLE_LOCKING_STYLE 1
69 # else
70 # define SQLITE_ENABLE_LOCKING_STYLE 0
71 # endif
72 #endif
74 /* Use pread() and pwrite() if they are available */
75 #if defined(__APPLE__)
76 # define HAVE_PREAD 1
77 # define HAVE_PWRITE 1
78 #endif
79 #if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
80 # undef USE_PREAD
81 # define USE_PREAD64 1
82 #elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)
83 # undef USE_PREAD64
84 # define USE_PREAD 1
85 #endif
88 ** standard include files.
90 #include <sys/types.h>
91 #include <sys/stat.h>
92 #include <fcntl.h>
93 #include <sys/ioctl.h>
94 #include <unistd.h>
95 #include <time.h>
96 #include <sys/time.h>
97 #include <errno.h>
98 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
99 # include <sys/mman.h>
100 #endif
102 #if SQLITE_ENABLE_LOCKING_STYLE
103 # include <sys/ioctl.h>
104 # include <sys/file.h>
105 # include <sys/param.h>
106 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
108 #if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
109 (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
110 # if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
111 && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
112 # define HAVE_GETHOSTUUID 1
113 # else
114 # warning "gethostuuid() is disabled."
115 # endif
116 #endif
119 #if OS_VXWORKS
120 # include <sys/ioctl.h>
121 # include <semaphore.h>
122 # include <limits.h>
123 #endif /* OS_VXWORKS */
125 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
126 # include <sys/mount.h>
127 #endif
129 #ifdef HAVE_UTIME
130 # include <utime.h>
131 #endif
134 ** Allowed values of unixFile.fsFlags
136 #define SQLITE_FSFLAGS_IS_MSDOS 0x1
139 ** If we are to be thread-safe, include the pthreads header and define
140 ** the SQLITE_UNIX_THREADS macro.
142 #if SQLITE_THREADSAFE
143 # include <pthread.h>
144 # define SQLITE_UNIX_THREADS 1
145 #endif
148 ** Default permissions when creating a new file
150 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
151 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
152 #endif
155 ** Default permissions when creating auto proxy dir
157 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
158 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
159 #endif
162 ** Maximum supported path-length.
164 #define MAX_PATHNAME 512
167 ** Maximum supported symbolic links
169 #define SQLITE_MAX_SYMLINKS 100
171 /* Always cast the getpid() return type for compatibility with
172 ** kernel modules in VxWorks. */
173 #define osGetpid(X) (pid_t)getpid()
176 ** Only set the lastErrno if the error code is a real error and not
177 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
179 #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
181 /* Forward references */
182 typedef struct unixShm unixShm; /* Connection shared memory */
183 typedef struct unixShmNode unixShmNode; /* Shared memory instance */
184 typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
185 typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
188 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
189 ** cannot be closed immediately. In these cases, instances of the following
190 ** structure are used to store the file descriptor while waiting for an
191 ** opportunity to either close or reuse it.
193 struct UnixUnusedFd {
194 int fd; /* File descriptor to close */
195 int flags; /* Flags this file descriptor was opened with */
196 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
200 ** The unixFile structure is subclass of sqlite3_file specific to the unix
201 ** VFS implementations.
203 typedef struct unixFile unixFile;
204 struct unixFile {
205 sqlite3_io_methods const *pMethod; /* Always the first entry */
206 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
207 unixInodeInfo *pInode; /* Info about locks on this inode */
208 int h; /* The file descriptor */
209 unsigned char eFileLock; /* The type of lock held on this fd */
210 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
211 int lastErrno; /* The unix errno from last I/O error */
212 void *lockingContext; /* Locking style specific state */
213 UnixUnusedFd *pPreallocatedUnused; /* Pre-allocated UnixUnusedFd */
214 const char *zPath; /* Name of the file */
215 unixShm *pShm; /* Shared memory segment information */
216 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
217 #if SQLITE_MAX_MMAP_SIZE>0
218 int nFetchOut; /* Number of outstanding xFetch refs */
219 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
220 sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
221 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
222 void *pMapRegion; /* Memory mapped region */
223 #endif
224 int sectorSize; /* Device sector size */
225 int deviceCharacteristics; /* Precomputed device characteristics */
226 #if SQLITE_ENABLE_LOCKING_STYLE
227 int openFlags; /* The flags specified at open() */
228 #endif
229 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
230 unsigned fsFlags; /* cached details from statfs() */
231 #endif
232 #if OS_VXWORKS
233 struct vxworksFileId *pId; /* Unique file ID */
234 #endif
235 #ifdef SQLITE_DEBUG
236 /* The next group of variables are used to track whether or not the
237 ** transaction counter in bytes 24-27 of database files are updated
238 ** whenever any part of the database changes. An assertion fault will
239 ** occur if a file is updated without also updating the transaction
240 ** counter. This test is made to avoid new problems similar to the
241 ** one described by ticket #3584.
243 unsigned char transCntrChng; /* True if the transaction counter changed */
244 unsigned char dbUpdate; /* True if any part of database file changed */
245 unsigned char inNormalWrite; /* True if in a normal write operation */
247 #endif
249 #ifdef SQLITE_TEST
250 /* In test mode, increase the size of this structure a bit so that
251 ** it is larger than the struct CrashFile defined in test6.c.
253 char aPadding[32];
254 #endif
257 /* This variable holds the process id (pid) from when the xRandomness()
258 ** method was called. If xOpen() is called from a different process id,
259 ** indicating that a fork() has occurred, the PRNG will be reset.
261 static pid_t randomnessPid = 0;
264 ** Allowed values for the unixFile.ctrlFlags bitmask:
266 #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
267 #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
268 #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
269 #ifndef SQLITE_DISABLE_DIRSYNC
270 # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
271 #else
272 # define UNIXFILE_DIRSYNC 0x00
273 #endif
274 #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
275 #define UNIXFILE_DELETE 0x20 /* Delete on close */
276 #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
277 #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
280 ** Include code that is common to all os_*.c files
282 #include "os_common.h"
285 ** Define various macros that are missing from some systems.
287 #ifndef O_LARGEFILE
288 # define O_LARGEFILE 0
289 #endif
290 #ifdef SQLITE_DISABLE_LFS
291 # undef O_LARGEFILE
292 # define O_LARGEFILE 0
293 #endif
294 #ifndef O_NOFOLLOW
295 # define O_NOFOLLOW 0
296 #endif
297 #ifndef O_BINARY
298 # define O_BINARY 0
299 #endif
302 ** The threadid macro resolves to the thread-id or to 0. Used for
303 ** testing and debugging only.
305 #if SQLITE_THREADSAFE
306 #define threadid pthread_self()
307 #else
308 #define threadid 0
309 #endif
312 ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
314 #if !defined(HAVE_MREMAP)
315 # if defined(__linux__) && defined(_GNU_SOURCE)
316 # define HAVE_MREMAP 1
317 # else
318 # define HAVE_MREMAP 0
319 # endif
320 #endif
323 ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
324 ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
326 #ifdef __ANDROID__
327 # define lseek lseek64
328 #endif
330 #ifdef __linux__
332 ** Linux-specific IOCTL magic numbers used for controlling F2FS
334 #define F2FS_IOCTL_MAGIC 0xf5
335 #define F2FS_IOC_START_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 1)
336 #define F2FS_IOC_COMMIT_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 2)
337 #define F2FS_IOC_START_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 3)
338 #define F2FS_IOC_ABORT_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 5)
339 #define F2FS_IOC_GET_FEATURES _IOR(F2FS_IOCTL_MAGIC, 12, u32)
340 #define F2FS_FEATURE_ATOMIC_WRITE 0x0004
341 #endif /* __linux__ */
345 ** Different Unix systems declare open() in different ways. Same use
346 ** open(const char*,int,mode_t). Others use open(const char*,int,...).
347 ** The difference is important when using a pointer to the function.
349 ** The safest way to deal with the problem is to always use this wrapper
350 ** which always has the same well-defined interface.
352 static int posixOpen(const char *zFile, int flags, int mode){
353 return open(zFile, flags, mode);
356 /* Forward reference */
357 static int openDirectory(const char*, int*);
358 static int unixGetpagesize(void);
361 ** Many system calls are accessed through pointer-to-functions so that
362 ** they may be overridden at runtime to facilitate fault injection during
363 ** testing and sandboxing. The following array holds the names and pointers
364 ** to all overrideable system calls.
366 static struct unix_syscall {
367 const char *zName; /* Name of the system call */
368 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
369 sqlite3_syscall_ptr pDefault; /* Default value */
370 } aSyscall[] = {
371 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
372 #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
374 { "close", (sqlite3_syscall_ptr)close, 0 },
375 #define osClose ((int(*)(int))aSyscall[1].pCurrent)
377 { "access", (sqlite3_syscall_ptr)access, 0 },
378 #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
380 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
381 #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
383 { "stat", (sqlite3_syscall_ptr)stat, 0 },
384 #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
387 ** The DJGPP compiler environment looks mostly like Unix, but it
388 ** lacks the fcntl() system call. So redefine fcntl() to be something
389 ** that always succeeds. This means that locking does not occur under
390 ** DJGPP. But it is DOS - what did you expect?
392 #ifdef __DJGPP__
393 { "fstat", 0, 0 },
394 #define osFstat(a,b,c) 0
395 #else
396 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
397 #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
398 #endif
400 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
401 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
403 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
404 #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
406 { "read", (sqlite3_syscall_ptr)read, 0 },
407 #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
409 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
410 { "pread", (sqlite3_syscall_ptr)pread, 0 },
411 #else
412 { "pread", (sqlite3_syscall_ptr)0, 0 },
413 #endif
414 #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
416 #if defined(USE_PREAD64)
417 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
418 #else
419 { "pread64", (sqlite3_syscall_ptr)0, 0 },
420 #endif
421 #define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
423 { "write", (sqlite3_syscall_ptr)write, 0 },
424 #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
426 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
427 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
428 #else
429 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
430 #endif
431 #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
432 aSyscall[12].pCurrent)
434 #if defined(USE_PREAD64)
435 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
436 #else
437 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
438 #endif
439 #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off64_t))\
440 aSyscall[13].pCurrent)
442 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
443 #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
445 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
446 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
447 #else
448 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
449 #endif
450 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
452 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
453 #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
455 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
456 #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
458 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
459 #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
461 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
462 #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
464 #if defined(HAVE_FCHOWN)
465 { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
466 #else
467 { "fchown", (sqlite3_syscall_ptr)0, 0 },
468 #endif
469 #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
471 { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
472 #define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
474 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
475 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
476 #else
477 { "mmap", (sqlite3_syscall_ptr)0, 0 },
478 #endif
479 #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
481 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
482 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
483 #else
484 { "munmap", (sqlite3_syscall_ptr)0, 0 },
485 #endif
486 #define osMunmap ((int(*)(void*,size_t))aSyscall[23].pCurrent)
488 #if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
489 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
490 #else
491 { "mremap", (sqlite3_syscall_ptr)0, 0 },
492 #endif
493 #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
495 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
496 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
497 #else
498 { "getpagesize", (sqlite3_syscall_ptr)0, 0 },
499 #endif
500 #define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
502 #if defined(HAVE_READLINK)
503 { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
504 #else
505 { "readlink", (sqlite3_syscall_ptr)0, 0 },
506 #endif
507 #define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
509 #if defined(HAVE_LSTAT)
510 { "lstat", (sqlite3_syscall_ptr)lstat, 0 },
511 #else
512 { "lstat", (sqlite3_syscall_ptr)0, 0 },
513 #endif
514 #define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
516 #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
517 { "ioctl", (sqlite3_syscall_ptr)ioctl, 0 },
518 #else
519 { "ioctl", (sqlite3_syscall_ptr)0, 0 },
520 #endif
521 #define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent)
523 }; /* End of the overrideable system calls */
527 ** On some systems, calls to fchown() will trigger a message in a security
528 ** log if they come from non-root processes. So avoid calling fchown() if
529 ** we are not running as root.
531 static int robustFchown(int fd, uid_t uid, gid_t gid){
532 #if defined(HAVE_FCHOWN)
533 return osGeteuid() ? 0 : osFchown(fd,uid,gid);
534 #else
535 return 0;
536 #endif
540 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
541 ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
542 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
543 ** system call named zName.
545 static int unixSetSystemCall(
546 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
547 const char *zName, /* Name of system call to override */
548 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
550 unsigned int i;
551 int rc = SQLITE_NOTFOUND;
553 UNUSED_PARAMETER(pNotUsed);
554 if( zName==0 ){
555 /* If no zName is given, restore all system calls to their default
556 ** settings and return NULL
558 rc = SQLITE_OK;
559 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
560 if( aSyscall[i].pDefault ){
561 aSyscall[i].pCurrent = aSyscall[i].pDefault;
564 }else{
565 /* If zName is specified, operate on only the one system call
566 ** specified.
568 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
569 if( strcmp(zName, aSyscall[i].zName)==0 ){
570 if( aSyscall[i].pDefault==0 ){
571 aSyscall[i].pDefault = aSyscall[i].pCurrent;
573 rc = SQLITE_OK;
574 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
575 aSyscall[i].pCurrent = pNewFunc;
576 break;
580 return rc;
584 ** Return the value of a system call. Return NULL if zName is not a
585 ** recognized system call name. NULL is also returned if the system call
586 ** is currently undefined.
588 static sqlite3_syscall_ptr unixGetSystemCall(
589 sqlite3_vfs *pNotUsed,
590 const char *zName
592 unsigned int i;
594 UNUSED_PARAMETER(pNotUsed);
595 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
596 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
598 return 0;
602 ** Return the name of the first system call after zName. If zName==NULL
603 ** then return the name of the first system call. Return NULL if zName
604 ** is the last system call or if zName is not the name of a valid
605 ** system call.
607 static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
608 int i = -1;
610 UNUSED_PARAMETER(p);
611 if( zName ){
612 for(i=0; i<ArraySize(aSyscall)-1; i++){
613 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
616 for(i++; i<ArraySize(aSyscall); i++){
617 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
619 return 0;
623 ** Do not accept any file descriptor less than this value, in order to avoid
624 ** opening database file using file descriptors that are commonly used for
625 ** standard input, output, and error.
627 #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
628 # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
629 #endif
632 ** Invoke open(). Do so multiple times, until it either succeeds or
633 ** fails for some reason other than EINTR.
635 ** If the file creation mode "m" is 0 then set it to the default for
636 ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
637 ** 0644) as modified by the system umask. If m is not 0, then
638 ** make the file creation mode be exactly m ignoring the umask.
640 ** The m parameter will be non-zero only when creating -wal, -journal,
641 ** and -shm files. We want those files to have *exactly* the same
642 ** permissions as their original database, unadulterated by the umask.
643 ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
644 ** transaction crashes and leaves behind hot journals, then any
645 ** process that is able to write to the database will also be able to
646 ** recover the hot journals.
648 static int robust_open(const char *z, int f, mode_t m){
649 int fd;
650 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
651 while(1){
652 #if defined(O_CLOEXEC)
653 fd = osOpen(z,f|O_CLOEXEC,m2);
654 #else
655 fd = osOpen(z,f,m2);
656 #endif
657 if( fd<0 ){
658 if( errno==EINTR ) continue;
659 break;
661 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
662 osClose(fd);
663 sqlite3_log(SQLITE_WARNING,
664 "attempt to open \"%s\" as file descriptor %d", z, fd);
665 fd = -1;
666 if( osOpen("/dev/null", f, m)<0 ) break;
668 if( fd>=0 ){
669 if( m!=0 ){
670 struct stat statbuf;
671 if( osFstat(fd, &statbuf)==0
672 && statbuf.st_size==0
673 && (statbuf.st_mode&0777)!=m
675 osFchmod(fd, m);
678 #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
679 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
680 #endif
682 return fd;
686 ** Helper functions to obtain and relinquish the global mutex. The
687 ** global mutex is used to protect the unixInodeInfo and
688 ** vxworksFileId objects used by this file, all of which may be
689 ** shared by multiple threads.
691 ** Function unixMutexHeld() is used to assert() that the global mutex
692 ** is held when required. This function is only used as part of assert()
693 ** statements. e.g.
695 ** unixEnterMutex()
696 ** assert( unixMutexHeld() );
697 ** unixEnterLeave()
699 static void unixEnterMutex(void){
700 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
702 static void unixLeaveMutex(void){
703 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
705 #ifdef SQLITE_DEBUG
706 static int unixMutexHeld(void) {
707 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
709 #endif
712 #ifdef SQLITE_HAVE_OS_TRACE
714 ** Helper function for printing out trace information from debugging
715 ** binaries. This returns the string representation of the supplied
716 ** integer lock-type.
718 static const char *azFileLock(int eFileLock){
719 switch( eFileLock ){
720 case NO_LOCK: return "NONE";
721 case SHARED_LOCK: return "SHARED";
722 case RESERVED_LOCK: return "RESERVED";
723 case PENDING_LOCK: return "PENDING";
724 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
726 return "ERROR";
728 #endif
730 #ifdef SQLITE_LOCK_TRACE
732 ** Print out information about all locking operations.
734 ** This routine is used for troubleshooting locks on multithreaded
735 ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
736 ** command-line option on the compiler. This code is normally
737 ** turned off.
739 static int lockTrace(int fd, int op, struct flock *p){
740 char *zOpName, *zType;
741 int s;
742 int savedErrno;
743 if( op==F_GETLK ){
744 zOpName = "GETLK";
745 }else if( op==F_SETLK ){
746 zOpName = "SETLK";
747 }else{
748 s = osFcntl(fd, op, p);
749 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
750 return s;
752 if( p->l_type==F_RDLCK ){
753 zType = "RDLCK";
754 }else if( p->l_type==F_WRLCK ){
755 zType = "WRLCK";
756 }else if( p->l_type==F_UNLCK ){
757 zType = "UNLCK";
758 }else{
759 assert( 0 );
761 assert( p->l_whence==SEEK_SET );
762 s = osFcntl(fd, op, p);
763 savedErrno = errno;
764 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
765 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
766 (int)p->l_pid, s);
767 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
768 struct flock l2;
769 l2 = *p;
770 osFcntl(fd, F_GETLK, &l2);
771 if( l2.l_type==F_RDLCK ){
772 zType = "RDLCK";
773 }else if( l2.l_type==F_WRLCK ){
774 zType = "WRLCK";
775 }else if( l2.l_type==F_UNLCK ){
776 zType = "UNLCK";
777 }else{
778 assert( 0 );
780 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
781 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
783 errno = savedErrno;
784 return s;
786 #undef osFcntl
787 #define osFcntl lockTrace
788 #endif /* SQLITE_LOCK_TRACE */
791 ** Retry ftruncate() calls that fail due to EINTR
793 ** All calls to ftruncate() within this file should be made through
794 ** this wrapper. On the Android platform, bypassing the logic below
795 ** could lead to a corrupt database.
797 static int robust_ftruncate(int h, sqlite3_int64 sz){
798 int rc;
799 #ifdef __ANDROID__
800 /* On Android, ftruncate() always uses 32-bit offsets, even if
801 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
802 ** truncate a file to any size larger than 2GiB. Silently ignore any
803 ** such attempts. */
804 if( sz>(sqlite3_int64)0x7FFFFFFF ){
805 rc = SQLITE_OK;
806 }else
807 #endif
808 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
809 return rc;
813 ** This routine translates a standard POSIX errno code into something
814 ** useful to the clients of the sqlite3 functions. Specifically, it is
815 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
816 ** and a variety of "please close the file descriptor NOW" errors into
817 ** SQLITE_IOERR
819 ** Errors during initialization of locks, or file system support for locks,
820 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
822 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
823 assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
824 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
825 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
826 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
827 switch (posixError) {
828 case EACCES:
829 case EAGAIN:
830 case ETIMEDOUT:
831 case EBUSY:
832 case EINTR:
833 case ENOLCK:
834 /* random NFS retry error, unless during file system support
835 * introspection, in which it actually means what it says */
836 return SQLITE_BUSY;
838 case EPERM:
839 return SQLITE_PERM;
841 default:
842 return sqliteIOErr;
847 /******************************************************************************
848 ****************** Begin Unique File ID Utility Used By VxWorks ***************
850 ** On most versions of unix, we can get a unique ID for a file by concatenating
851 ** the device number and the inode number. But this does not work on VxWorks.
852 ** On VxWorks, a unique file id must be based on the canonical filename.
854 ** A pointer to an instance of the following structure can be used as a
855 ** unique file ID in VxWorks. Each instance of this structure contains
856 ** a copy of the canonical filename. There is also a reference count.
857 ** The structure is reclaimed when the number of pointers to it drops to
858 ** zero.
860 ** There are never very many files open at one time and lookups are not
861 ** a performance-critical path, so it is sufficient to put these
862 ** structures on a linked list.
864 struct vxworksFileId {
865 struct vxworksFileId *pNext; /* Next in a list of them all */
866 int nRef; /* Number of references to this one */
867 int nName; /* Length of the zCanonicalName[] string */
868 char *zCanonicalName; /* Canonical filename */
871 #if OS_VXWORKS
873 ** All unique filenames are held on a linked list headed by this
874 ** variable:
876 static struct vxworksFileId *vxworksFileList = 0;
879 ** Simplify a filename into its canonical form
880 ** by making the following changes:
882 ** * removing any trailing and duplicate /
883 ** * convert /./ into just /
884 ** * convert /A/../ where A is any simple name into just /
886 ** Changes are made in-place. Return the new name length.
888 ** The original filename is in z[0..n-1]. Return the number of
889 ** characters in the simplified name.
891 static int vxworksSimplifyName(char *z, int n){
892 int i, j;
893 while( n>1 && z[n-1]=='/' ){ n--; }
894 for(i=j=0; i<n; i++){
895 if( z[i]=='/' ){
896 if( z[i+1]=='/' ) continue;
897 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
898 i += 1;
899 continue;
901 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
902 while( j>0 && z[j-1]!='/' ){ j--; }
903 if( j>0 ){ j--; }
904 i += 2;
905 continue;
908 z[j++] = z[i];
910 z[j] = 0;
911 return j;
915 ** Find a unique file ID for the given absolute pathname. Return
916 ** a pointer to the vxworksFileId object. This pointer is the unique
917 ** file ID.
919 ** The nRef field of the vxworksFileId object is incremented before
920 ** the object is returned. A new vxworksFileId object is created
921 ** and added to the global list if necessary.
923 ** If a memory allocation error occurs, return NULL.
925 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
926 struct vxworksFileId *pNew; /* search key and new file ID */
927 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
928 int n; /* Length of zAbsoluteName string */
930 assert( zAbsoluteName[0]=='/' );
931 n = (int)strlen(zAbsoluteName);
932 pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
933 if( pNew==0 ) return 0;
934 pNew->zCanonicalName = (char*)&pNew[1];
935 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
936 n = vxworksSimplifyName(pNew->zCanonicalName, n);
938 /* Search for an existing entry that matching the canonical name.
939 ** If found, increment the reference count and return a pointer to
940 ** the existing file ID.
942 unixEnterMutex();
943 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
944 if( pCandidate->nName==n
945 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
947 sqlite3_free(pNew);
948 pCandidate->nRef++;
949 unixLeaveMutex();
950 return pCandidate;
954 /* No match was found. We will make a new file ID */
955 pNew->nRef = 1;
956 pNew->nName = n;
957 pNew->pNext = vxworksFileList;
958 vxworksFileList = pNew;
959 unixLeaveMutex();
960 return pNew;
964 ** Decrement the reference count on a vxworksFileId object. Free
965 ** the object when the reference count reaches zero.
967 static void vxworksReleaseFileId(struct vxworksFileId *pId){
968 unixEnterMutex();
969 assert( pId->nRef>0 );
970 pId->nRef--;
971 if( pId->nRef==0 ){
972 struct vxworksFileId **pp;
973 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
974 assert( *pp==pId );
975 *pp = pId->pNext;
976 sqlite3_free(pId);
978 unixLeaveMutex();
980 #endif /* OS_VXWORKS */
981 /*************** End of Unique File ID Utility Used By VxWorks ****************
982 ******************************************************************************/
985 /******************************************************************************
986 *************************** Posix Advisory Locking ****************************
988 ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
989 ** section 6.5.2.2 lines 483 through 490 specify that when a process
990 ** sets or clears a lock, that operation overrides any prior locks set
991 ** by the same process. It does not explicitly say so, but this implies
992 ** that it overrides locks set by the same process using a different
993 ** file descriptor. Consider this test case:
995 ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
996 ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
998 ** Suppose ./file1 and ./file2 are really the same file (because
999 ** one is a hard or symbolic link to the other) then if you set
1000 ** an exclusive lock on fd1, then try to get an exclusive lock
1001 ** on fd2, it works. I would have expected the second lock to
1002 ** fail since there was already a lock on the file due to fd1.
1003 ** But not so. Since both locks came from the same process, the
1004 ** second overrides the first, even though they were on different
1005 ** file descriptors opened on different file names.
1007 ** This means that we cannot use POSIX locks to synchronize file access
1008 ** among competing threads of the same process. POSIX locks will work fine
1009 ** to synchronize access for threads in separate processes, but not
1010 ** threads within the same process.
1012 ** To work around the problem, SQLite has to manage file locks internally
1013 ** on its own. Whenever a new database is opened, we have to find the
1014 ** specific inode of the database file (the inode is determined by the
1015 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
1016 ** and check for locks already existing on that inode. When locks are
1017 ** created or removed, we have to look at our own internal record of the
1018 ** locks to see if another thread has previously set a lock on that same
1019 ** inode.
1021 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
1022 ** For VxWorks, we have to use the alternative unique ID system based on
1023 ** canonical filename and implemented in the previous division.)
1025 ** The sqlite3_file structure for POSIX is no longer just an integer file
1026 ** descriptor. It is now a structure that holds the integer file
1027 ** descriptor and a pointer to a structure that describes the internal
1028 ** locks on the corresponding inode. There is one locking structure
1029 ** per inode, so if the same inode is opened twice, both unixFile structures
1030 ** point to the same locking structure. The locking structure keeps
1031 ** a reference count (so we will know when to delete it) and a "cnt"
1032 ** field that tells us its internal lock status. cnt==0 means the
1033 ** file is unlocked. cnt==-1 means the file has an exclusive lock.
1034 ** cnt>0 means there are cnt shared locks on the file.
1036 ** Any attempt to lock or unlock a file first checks the locking
1037 ** structure. The fcntl() system call is only invoked to set a
1038 ** POSIX lock if the internal lock structure transitions between
1039 ** a locked and an unlocked state.
1041 ** But wait: there are yet more problems with POSIX advisory locks.
1043 ** If you close a file descriptor that points to a file that has locks,
1044 ** all locks on that file that are owned by the current process are
1045 ** released. To work around this problem, each unixInodeInfo object
1046 ** maintains a count of the number of pending locks on tha inode.
1047 ** When an attempt is made to close an unixFile, if there are
1048 ** other unixFile open on the same inode that are holding locks, the call
1049 ** to close() the file descriptor is deferred until all of the locks clear.
1050 ** The unixInodeInfo structure keeps a list of file descriptors that need to
1051 ** be closed and that list is walked (and cleared) when the last lock
1052 ** clears.
1054 ** Yet another problem: LinuxThreads do not play well with posix locks.
1056 ** Many older versions of linux use the LinuxThreads library which is
1057 ** not posix compliant. Under LinuxThreads, a lock created by thread
1058 ** A cannot be modified or overridden by a different thread B.
1059 ** Only thread A can modify the lock. Locking behavior is correct
1060 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
1061 ** on linux - with NPTL a lock created by thread A can override locks
1062 ** in thread B. But there is no way to know at compile-time which
1063 ** threading library is being used. So there is no way to know at
1064 ** compile-time whether or not thread A can override locks on thread B.
1065 ** One has to do a run-time check to discover the behavior of the
1066 ** current process.
1068 ** SQLite used to support LinuxThreads. But support for LinuxThreads
1069 ** was dropped beginning with version 3.7.0. SQLite will still work with
1070 ** LinuxThreads provided that (1) there is no more than one connection
1071 ** per database file in the same process and (2) database connections
1072 ** do not move across threads.
1076 ** An instance of the following structure serves as the key used
1077 ** to locate a particular unixInodeInfo object.
1079 struct unixFileId {
1080 dev_t dev; /* Device number */
1081 #if OS_VXWORKS
1082 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
1083 #else
1084 /* We are told that some versions of Android contain a bug that
1085 ** sizes ino_t at only 32-bits instead of 64-bits. (See
1086 ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
1087 ** To work around this, always allocate 64-bits for the inode number.
1088 ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
1089 ** but that should not be a big deal. */
1090 /* WAS: ino_t ino; */
1091 u64 ino; /* Inode number */
1092 #endif
1096 ** An instance of the following structure is allocated for each open
1097 ** inode. Or, on LinuxThreads, there is one of these structures for
1098 ** each inode opened by each thread.
1100 ** A single inode can have multiple file descriptors, so each unixFile
1101 ** structure contains a pointer to an instance of this object and this
1102 ** object keeps a count of the number of unixFile pointing to it.
1104 struct unixInodeInfo {
1105 struct unixFileId fileId; /* The lookup key */
1106 int nShared; /* Number of SHARED locks held */
1107 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1108 unsigned char bProcessLock; /* An exclusive process lock is held */
1109 int nRef; /* Number of pointers to this structure */
1110 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1111 int nLock; /* Number of outstanding file locks */
1112 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1113 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1114 unixInodeInfo *pPrev; /* .... doubly linked */
1115 #if SQLITE_ENABLE_LOCKING_STYLE
1116 unsigned long long sharedByte; /* for AFP simulated shared lock */
1117 #endif
1118 #if OS_VXWORKS
1119 sem_t *pSem; /* Named POSIX semaphore */
1120 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
1121 #endif
1125 ** A lists of all unixInodeInfo objects.
1127 static unixInodeInfo *inodeList = 0; /* All unixInodeInfo objects */
1128 static unsigned int nUnusedFd = 0; /* Total unused file descriptors */
1132 ** This function - unixLogErrorAtLine(), is only ever called via the macro
1133 ** unixLogError().
1135 ** It is invoked after an error occurs in an OS function and errno has been
1136 ** set. It logs a message using sqlite3_log() containing the current value of
1137 ** errno and, if possible, the human-readable equivalent from strerror() or
1138 ** strerror_r().
1140 ** The first argument passed to the macro should be the error code that
1141 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1142 ** The two subsequent arguments should be the name of the OS function that
1143 ** failed (e.g. "unlink", "open") and the associated file-system path,
1144 ** if any.
1146 #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1147 static int unixLogErrorAtLine(
1148 int errcode, /* SQLite error code */
1149 const char *zFunc, /* Name of OS function that failed */
1150 const char *zPath, /* File path associated with error */
1151 int iLine /* Source line number where error occurred */
1153 char *zErr; /* Message from strerror() or equivalent */
1154 int iErrno = errno; /* Saved syscall error number */
1156 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1157 ** the strerror() function to obtain the human-readable error message
1158 ** equivalent to errno. Otherwise, use strerror_r().
1160 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1161 char aErr[80];
1162 memset(aErr, 0, sizeof(aErr));
1163 zErr = aErr;
1165 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
1166 ** assume that the system provides the GNU version of strerror_r() that
1167 ** returns a pointer to a buffer containing the error message. That pointer
1168 ** may point to aErr[], or it may point to some static storage somewhere.
1169 ** Otherwise, assume that the system provides the POSIX version of
1170 ** strerror_r(), which always writes an error message into aErr[].
1172 ** If the code incorrectly assumes that it is the POSIX version that is
1173 ** available, the error message will often be an empty string. Not a
1174 ** huge problem. Incorrectly concluding that the GNU version is available
1175 ** could lead to a segfault though.
1177 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1178 zErr =
1179 # endif
1180 strerror_r(iErrno, aErr, sizeof(aErr)-1);
1182 #elif SQLITE_THREADSAFE
1183 /* This is a threadsafe build, but strerror_r() is not available. */
1184 zErr = "";
1185 #else
1186 /* Non-threadsafe build, use strerror(). */
1187 zErr = strerror(iErrno);
1188 #endif
1190 if( zPath==0 ) zPath = "";
1191 sqlite3_log(errcode,
1192 "os_unix.c:%d: (%d) %s(%s) - %s",
1193 iLine, iErrno, zFunc, zPath, zErr
1196 return errcode;
1200 ** Close a file descriptor.
1202 ** We assume that close() almost always works, since it is only in a
1203 ** very sick application or on a very sick platform that it might fail.
1204 ** If it does fail, simply leak the file descriptor, but do log the
1205 ** error.
1207 ** Note that it is not safe to retry close() after EINTR since the
1208 ** file descriptor might have already been reused by another thread.
1209 ** So we don't even try to recover from an EINTR. Just log the error
1210 ** and move on.
1212 static void robust_close(unixFile *pFile, int h, int lineno){
1213 if( osClose(h) ){
1214 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1215 pFile ? pFile->zPath : 0, lineno);
1220 ** Set the pFile->lastErrno. Do this in a subroutine as that provides
1221 ** a convenient place to set a breakpoint.
1223 static void storeLastErrno(unixFile *pFile, int error){
1224 pFile->lastErrno = error;
1228 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
1230 static void closePendingFds(unixFile *pFile){
1231 unixInodeInfo *pInode = pFile->pInode;
1232 UnixUnusedFd *p;
1233 UnixUnusedFd *pNext;
1234 for(p=pInode->pUnused; p; p=pNext){
1235 pNext = p->pNext;
1236 robust_close(pFile, p->fd, __LINE__);
1237 sqlite3_free(p);
1238 nUnusedFd--;
1240 pInode->pUnused = 0;
1244 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
1246 ** The mutex entered using the unixEnterMutex() function must be held
1247 ** when this function is called.
1249 static void releaseInodeInfo(unixFile *pFile){
1250 unixInodeInfo *pInode = pFile->pInode;
1251 assert( unixMutexHeld() );
1252 if( ALWAYS(pInode) ){
1253 pInode->nRef--;
1254 if( pInode->nRef==0 ){
1255 assert( pInode->pShmNode==0 );
1256 closePendingFds(pFile);
1257 if( pInode->pPrev ){
1258 assert( pInode->pPrev->pNext==pInode );
1259 pInode->pPrev->pNext = pInode->pNext;
1260 }else{
1261 assert( inodeList==pInode );
1262 inodeList = pInode->pNext;
1264 if( pInode->pNext ){
1265 assert( pInode->pNext->pPrev==pInode );
1266 pInode->pNext->pPrev = pInode->pPrev;
1268 sqlite3_free(pInode);
1271 assert( inodeList!=0 || nUnusedFd==0 );
1275 ** Given a file descriptor, locate the unixInodeInfo object that
1276 ** describes that file descriptor. Create a new one if necessary. The
1277 ** return value might be uninitialized if an error occurs.
1279 ** The mutex entered using the unixEnterMutex() function must be held
1280 ** when this function is called.
1282 ** Return an appropriate error code.
1284 static int findInodeInfo(
1285 unixFile *pFile, /* Unix file with file desc used in the key */
1286 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
1288 int rc; /* System call return code */
1289 int fd; /* The file descriptor for pFile */
1290 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1291 struct stat statbuf; /* Low-level file information */
1292 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
1294 assert( unixMutexHeld() );
1296 /* Get low-level information about the file that we can used to
1297 ** create a unique name for the file.
1299 fd = pFile->h;
1300 rc = osFstat(fd, &statbuf);
1301 if( rc!=0 ){
1302 storeLastErrno(pFile, errno);
1303 #if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
1304 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1305 #endif
1306 return SQLITE_IOERR;
1309 #ifdef __APPLE__
1310 /* On OS X on an msdos filesystem, the inode number is reported
1311 ** incorrectly for zero-size files. See ticket #3260. To work
1312 ** around this problem (we consider it a bug in OS X, not SQLite)
1313 ** we always increase the file size to 1 by writing a single byte
1314 ** prior to accessing the inode number. The one byte written is
1315 ** an ASCII 'S' character which also happens to be the first byte
1316 ** in the header of every SQLite database. In this way, if there
1317 ** is a race condition such that another thread has already populated
1318 ** the first page of the database, no damage is done.
1320 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
1321 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
1322 if( rc!=1 ){
1323 storeLastErrno(pFile, errno);
1324 return SQLITE_IOERR;
1326 rc = osFstat(fd, &statbuf);
1327 if( rc!=0 ){
1328 storeLastErrno(pFile, errno);
1329 return SQLITE_IOERR;
1332 #endif
1334 memset(&fileId, 0, sizeof(fileId));
1335 fileId.dev = statbuf.st_dev;
1336 #if OS_VXWORKS
1337 fileId.pId = pFile->pId;
1338 #else
1339 fileId.ino = (u64)statbuf.st_ino;
1340 #endif
1341 assert( inodeList!=0 || nUnusedFd==0 );
1342 pInode = inodeList;
1343 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1344 pInode = pInode->pNext;
1346 if( pInode==0 ){
1347 pInode = sqlite3_malloc64( sizeof(*pInode) );
1348 if( pInode==0 ){
1349 return SQLITE_NOMEM_BKPT;
1351 memset(pInode, 0, sizeof(*pInode));
1352 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1353 pInode->nRef = 1;
1354 pInode->pNext = inodeList;
1355 pInode->pPrev = 0;
1356 if( inodeList ) inodeList->pPrev = pInode;
1357 inodeList = pInode;
1358 }else{
1359 pInode->nRef++;
1361 *ppInode = pInode;
1362 return SQLITE_OK;
1366 ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1368 static int fileHasMoved(unixFile *pFile){
1369 #if OS_VXWORKS
1370 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1371 #else
1372 struct stat buf;
1373 return pFile->pInode!=0 &&
1374 (osStat(pFile->zPath, &buf)!=0
1375 || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
1376 #endif
1381 ** Check a unixFile that is a database. Verify the following:
1383 ** (1) There is exactly one hard link on the file
1384 ** (2) The file is not a symbolic link
1385 ** (3) The file has not been renamed or unlinked
1387 ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1389 static void verifyDbFile(unixFile *pFile){
1390 struct stat buf;
1391 int rc;
1393 /* These verifications occurs for the main database only */
1394 if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
1396 rc = osFstat(pFile->h, &buf);
1397 if( rc!=0 ){
1398 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
1399 return;
1401 if( buf.st_nlink==0 ){
1402 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
1403 return;
1405 if( buf.st_nlink>1 ){
1406 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
1407 return;
1409 if( fileHasMoved(pFile) ){
1410 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
1411 return;
1417 ** This routine checks if there is a RESERVED lock held on the specified
1418 ** file by this or any other process. If such a lock is held, set *pResOut
1419 ** to a non-zero value otherwise *pResOut is set to zero. The return value
1420 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1422 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
1423 int rc = SQLITE_OK;
1424 int reserved = 0;
1425 unixFile *pFile = (unixFile*)id;
1427 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1429 assert( pFile );
1430 assert( pFile->eFileLock<=SHARED_LOCK );
1431 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
1433 /* Check if a thread in this process holds such a lock */
1434 if( pFile->pInode->eFileLock>SHARED_LOCK ){
1435 reserved = 1;
1438 /* Otherwise see if some other process holds it.
1440 #ifndef __DJGPP__
1441 if( !reserved && !pFile->pInode->bProcessLock ){
1442 struct flock lock;
1443 lock.l_whence = SEEK_SET;
1444 lock.l_start = RESERVED_BYTE;
1445 lock.l_len = 1;
1446 lock.l_type = F_WRLCK;
1447 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1448 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1449 storeLastErrno(pFile, errno);
1450 } else if( lock.l_type!=F_UNLCK ){
1451 reserved = 1;
1454 #endif
1456 unixLeaveMutex();
1457 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
1459 *pResOut = reserved;
1460 return rc;
1464 ** Attempt to set a system-lock on the file pFile. The lock is
1465 ** described by pLock.
1467 ** If the pFile was opened read/write from unix-excl, then the only lock
1468 ** ever obtained is an exclusive lock, and it is obtained exactly once
1469 ** the first time any lock is attempted. All subsequent system locking
1470 ** operations become no-ops. Locking operations still happen internally,
1471 ** in order to coordinate access between separate database connections
1472 ** within this process, but all of that is handled in memory and the
1473 ** operating system does not participate.
1475 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1476 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1477 ** and is read-only.
1479 ** Zero is returned if the call completes successfully, or -1 if a call
1480 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
1482 static int unixFileLock(unixFile *pFile, struct flock *pLock){
1483 int rc;
1484 unixInodeInfo *pInode = pFile->pInode;
1485 assert( unixMutexHeld() );
1486 assert( pInode!=0 );
1487 if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
1488 if( pInode->bProcessLock==0 ){
1489 struct flock lock;
1490 assert( pInode->nLock==0 );
1491 lock.l_whence = SEEK_SET;
1492 lock.l_start = SHARED_FIRST;
1493 lock.l_len = SHARED_SIZE;
1494 lock.l_type = F_WRLCK;
1495 rc = osFcntl(pFile->h, F_SETLK, &lock);
1496 if( rc<0 ) return rc;
1497 pInode->bProcessLock = 1;
1498 pInode->nLock++;
1499 }else{
1500 rc = 0;
1502 }else{
1503 rc = osFcntl(pFile->h, F_SETLK, pLock);
1505 return rc;
1509 ** Lock the file with the lock specified by parameter eFileLock - one
1510 ** of the following:
1512 ** (1) SHARED_LOCK
1513 ** (2) RESERVED_LOCK
1514 ** (3) PENDING_LOCK
1515 ** (4) EXCLUSIVE_LOCK
1517 ** Sometimes when requesting one lock state, additional lock states
1518 ** are inserted in between. The locking might fail on one of the later
1519 ** transitions leaving the lock state different from what it started but
1520 ** still short of its goal. The following chart shows the allowed
1521 ** transitions and the inserted intermediate states:
1523 ** UNLOCKED -> SHARED
1524 ** SHARED -> RESERVED
1525 ** SHARED -> (PENDING) -> EXCLUSIVE
1526 ** RESERVED -> (PENDING) -> EXCLUSIVE
1527 ** PENDING -> EXCLUSIVE
1529 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
1530 ** routine to lower a locking level.
1532 static int unixLock(sqlite3_file *id, int eFileLock){
1533 /* The following describes the implementation of the various locks and
1534 ** lock transitions in terms of the POSIX advisory shared and exclusive
1535 ** lock primitives (called read-locks and write-locks below, to avoid
1536 ** confusion with SQLite lock names). The algorithms are complicated
1537 ** slightly in order to be compatible with Windows95 systems simultaneously
1538 ** accessing the same database file, in case that is ever required.
1540 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1541 ** byte', each single bytes at well known offsets, and the 'shared byte
1542 ** range', a range of 510 bytes at a well known offset.
1544 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1545 ** byte'. If this is successful, 'shared byte range' is read-locked
1546 ** and the lock on the 'pending byte' released. (Legacy note: When
1547 ** SQLite was first developed, Windows95 systems were still very common,
1548 ** and Widnows95 lacks a shared-lock capability. So on Windows95, a
1549 ** single randomly selected by from the 'shared byte range' is locked.
1550 ** Windows95 is now pretty much extinct, but this work-around for the
1551 ** lack of shared-locks on Windows95 lives on, for backwards
1552 ** compatibility.)
1554 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1555 ** A RESERVED lock is implemented by grabbing a write-lock on the
1556 ** 'reserved byte'.
1558 ** A process may only obtain a PENDING lock after it has obtained a
1559 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1560 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1561 ** obtained, but existing SHARED locks are allowed to persist. A process
1562 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1563 ** This property is used by the algorithm for rolling back a journal file
1564 ** after a crash.
1566 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1567 ** implemented by obtaining a write-lock on the entire 'shared byte
1568 ** range'. Since all other locks require a read-lock on one of the bytes
1569 ** within this range, this ensures that no other locks are held on the
1570 ** database.
1572 int rc = SQLITE_OK;
1573 unixFile *pFile = (unixFile*)id;
1574 unixInodeInfo *pInode;
1575 struct flock lock;
1576 int tErrno = 0;
1578 assert( pFile );
1579 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1580 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
1581 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
1582 osGetpid(0)));
1584 /* If there is already a lock of this type or more restrictive on the
1585 ** unixFile, do nothing. Don't use the end_lock: exit path, as
1586 ** unixEnterMutex() hasn't been called yet.
1588 if( pFile->eFileLock>=eFileLock ){
1589 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1590 azFileLock(eFileLock)));
1591 return SQLITE_OK;
1594 /* Make sure the locking sequence is correct.
1595 ** (1) We never move from unlocked to anything higher than shared lock.
1596 ** (2) SQLite never explicitly requests a pendig lock.
1597 ** (3) A shared lock is always held when a reserve lock is requested.
1599 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1600 assert( eFileLock!=PENDING_LOCK );
1601 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
1603 /* This mutex is needed because pFile->pInode is shared across threads
1605 unixEnterMutex();
1606 pInode = pFile->pInode;
1608 /* If some thread using this PID has a lock via a different unixFile*
1609 ** handle that precludes the requested lock, return BUSY.
1611 if( (pFile->eFileLock!=pInode->eFileLock &&
1612 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
1614 rc = SQLITE_BUSY;
1615 goto end_lock;
1618 /* If a SHARED lock is requested, and some thread using this PID already
1619 ** has a SHARED or RESERVED lock, then increment reference counts and
1620 ** return SQLITE_OK.
1622 if( eFileLock==SHARED_LOCK &&
1623 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
1624 assert( eFileLock==SHARED_LOCK );
1625 assert( pFile->eFileLock==0 );
1626 assert( pInode->nShared>0 );
1627 pFile->eFileLock = SHARED_LOCK;
1628 pInode->nShared++;
1629 pInode->nLock++;
1630 goto end_lock;
1634 /* A PENDING lock is needed before acquiring a SHARED lock and before
1635 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1636 ** be released.
1638 lock.l_len = 1L;
1639 lock.l_whence = SEEK_SET;
1640 if( eFileLock==SHARED_LOCK
1641 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
1643 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
1644 lock.l_start = PENDING_BYTE;
1645 if( unixFileLock(pFile, &lock) ){
1646 tErrno = errno;
1647 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1648 if( rc!=SQLITE_BUSY ){
1649 storeLastErrno(pFile, tErrno);
1651 goto end_lock;
1656 /* If control gets to this point, then actually go ahead and make
1657 ** operating system calls for the specified lock.
1659 if( eFileLock==SHARED_LOCK ){
1660 assert( pInode->nShared==0 );
1661 assert( pInode->eFileLock==0 );
1662 assert( rc==SQLITE_OK );
1664 /* Now get the read-lock */
1665 lock.l_start = SHARED_FIRST;
1666 lock.l_len = SHARED_SIZE;
1667 if( unixFileLock(pFile, &lock) ){
1668 tErrno = errno;
1669 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1672 /* Drop the temporary PENDING lock */
1673 lock.l_start = PENDING_BYTE;
1674 lock.l_len = 1L;
1675 lock.l_type = F_UNLCK;
1676 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1677 /* This could happen with a network mount */
1678 tErrno = errno;
1679 rc = SQLITE_IOERR_UNLOCK;
1682 if( rc ){
1683 if( rc!=SQLITE_BUSY ){
1684 storeLastErrno(pFile, tErrno);
1686 goto end_lock;
1687 }else{
1688 pFile->eFileLock = SHARED_LOCK;
1689 pInode->nLock++;
1690 pInode->nShared = 1;
1692 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
1693 /* We are trying for an exclusive lock but another thread in this
1694 ** same process is still holding a shared lock. */
1695 rc = SQLITE_BUSY;
1696 }else{
1697 /* The request was for a RESERVED or EXCLUSIVE lock. It is
1698 ** assumed that there is a SHARED or greater lock on the file
1699 ** already.
1701 assert( 0!=pFile->eFileLock );
1702 lock.l_type = F_WRLCK;
1704 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1705 if( eFileLock==RESERVED_LOCK ){
1706 lock.l_start = RESERVED_BYTE;
1707 lock.l_len = 1L;
1708 }else{
1709 lock.l_start = SHARED_FIRST;
1710 lock.l_len = SHARED_SIZE;
1713 if( unixFileLock(pFile, &lock) ){
1714 tErrno = errno;
1715 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1716 if( rc!=SQLITE_BUSY ){
1717 storeLastErrno(pFile, tErrno);
1723 #ifdef SQLITE_DEBUG
1724 /* Set up the transaction-counter change checking flags when
1725 ** transitioning from a SHARED to a RESERVED lock. The change
1726 ** from SHARED to RESERVED marks the beginning of a normal
1727 ** write operation (not a hot journal rollback).
1729 if( rc==SQLITE_OK
1730 && pFile->eFileLock<=SHARED_LOCK
1731 && eFileLock==RESERVED_LOCK
1733 pFile->transCntrChng = 0;
1734 pFile->dbUpdate = 0;
1735 pFile->inNormalWrite = 1;
1737 #endif
1740 if( rc==SQLITE_OK ){
1741 pFile->eFileLock = eFileLock;
1742 pInode->eFileLock = eFileLock;
1743 }else if( eFileLock==EXCLUSIVE_LOCK ){
1744 pFile->eFileLock = PENDING_LOCK;
1745 pInode->eFileLock = PENDING_LOCK;
1748 end_lock:
1749 unixLeaveMutex();
1750 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1751 rc==SQLITE_OK ? "ok" : "failed"));
1752 return rc;
1756 ** Add the file descriptor used by file handle pFile to the corresponding
1757 ** pUnused list.
1759 static void setPendingFd(unixFile *pFile){
1760 unixInodeInfo *pInode = pFile->pInode;
1761 UnixUnusedFd *p = pFile->pPreallocatedUnused;
1762 p->pNext = pInode->pUnused;
1763 pInode->pUnused = p;
1764 pFile->h = -1;
1765 pFile->pPreallocatedUnused = 0;
1766 nUnusedFd++;
1770 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
1771 ** must be either NO_LOCK or SHARED_LOCK.
1773 ** If the locking level of the file descriptor is already at or below
1774 ** the requested locking level, this routine is a no-op.
1776 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1777 ** the byte range is divided into 2 parts and the first part is unlocked then
1778 ** set to a read lock, then the other part is simply unlocked. This works
1779 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1780 ** remove the write lock on a region when a read lock is set.
1782 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
1783 unixFile *pFile = (unixFile*)id;
1784 unixInodeInfo *pInode;
1785 struct flock lock;
1786 int rc = SQLITE_OK;
1788 assert( pFile );
1789 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
1790 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
1791 osGetpid(0)));
1793 assert( eFileLock<=SHARED_LOCK );
1794 if( pFile->eFileLock<=eFileLock ){
1795 return SQLITE_OK;
1797 unixEnterMutex();
1798 pInode = pFile->pInode;
1799 assert( pInode->nShared!=0 );
1800 if( pFile->eFileLock>SHARED_LOCK ){
1801 assert( pInode->eFileLock==pFile->eFileLock );
1803 #ifdef SQLITE_DEBUG
1804 /* When reducing a lock such that other processes can start
1805 ** reading the database file again, make sure that the
1806 ** transaction counter was updated if any part of the database
1807 ** file changed. If the transaction counter is not updated,
1808 ** other connections to the same file might not realize that
1809 ** the file has changed and hence might not know to flush their
1810 ** cache. The use of a stale cache can lead to database corruption.
1812 pFile->inNormalWrite = 0;
1813 #endif
1815 /* downgrading to a shared lock on NFS involves clearing the write lock
1816 ** before establishing the readlock - to avoid a race condition we downgrade
1817 ** the lock in 2 blocks, so that part of the range will be covered by a
1818 ** write lock until the rest is covered by a read lock:
1819 ** 1: [WWWWW]
1820 ** 2: [....W]
1821 ** 3: [RRRRW]
1822 ** 4: [RRRR.]
1824 if( eFileLock==SHARED_LOCK ){
1825 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
1826 (void)handleNFSUnlock;
1827 assert( handleNFSUnlock==0 );
1828 #endif
1829 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
1830 if( handleNFSUnlock ){
1831 int tErrno; /* Error code from system call errors */
1832 off_t divSize = SHARED_SIZE - 1;
1834 lock.l_type = F_UNLCK;
1835 lock.l_whence = SEEK_SET;
1836 lock.l_start = SHARED_FIRST;
1837 lock.l_len = divSize;
1838 if( unixFileLock(pFile, &lock)==(-1) ){
1839 tErrno = errno;
1840 rc = SQLITE_IOERR_UNLOCK;
1841 storeLastErrno(pFile, tErrno);
1842 goto end_unlock;
1844 lock.l_type = F_RDLCK;
1845 lock.l_whence = SEEK_SET;
1846 lock.l_start = SHARED_FIRST;
1847 lock.l_len = divSize;
1848 if( unixFileLock(pFile, &lock)==(-1) ){
1849 tErrno = errno;
1850 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1851 if( IS_LOCK_ERROR(rc) ){
1852 storeLastErrno(pFile, tErrno);
1854 goto end_unlock;
1856 lock.l_type = F_UNLCK;
1857 lock.l_whence = SEEK_SET;
1858 lock.l_start = SHARED_FIRST+divSize;
1859 lock.l_len = SHARED_SIZE-divSize;
1860 if( unixFileLock(pFile, &lock)==(-1) ){
1861 tErrno = errno;
1862 rc = SQLITE_IOERR_UNLOCK;
1863 storeLastErrno(pFile, tErrno);
1864 goto end_unlock;
1866 }else
1867 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1869 lock.l_type = F_RDLCK;
1870 lock.l_whence = SEEK_SET;
1871 lock.l_start = SHARED_FIRST;
1872 lock.l_len = SHARED_SIZE;
1873 if( unixFileLock(pFile, &lock) ){
1874 /* In theory, the call to unixFileLock() cannot fail because another
1875 ** process is holding an incompatible lock. If it does, this
1876 ** indicates that the other process is not following the locking
1877 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1878 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1879 ** an assert to fail). */
1880 rc = SQLITE_IOERR_RDLOCK;
1881 storeLastErrno(pFile, errno);
1882 goto end_unlock;
1886 lock.l_type = F_UNLCK;
1887 lock.l_whence = SEEK_SET;
1888 lock.l_start = PENDING_BYTE;
1889 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
1890 if( unixFileLock(pFile, &lock)==0 ){
1891 pInode->eFileLock = SHARED_LOCK;
1892 }else{
1893 rc = SQLITE_IOERR_UNLOCK;
1894 storeLastErrno(pFile, errno);
1895 goto end_unlock;
1898 if( eFileLock==NO_LOCK ){
1899 /* Decrement the shared lock counter. Release the lock using an
1900 ** OS call only when all threads in this same process have released
1901 ** the lock.
1903 pInode->nShared--;
1904 if( pInode->nShared==0 ){
1905 lock.l_type = F_UNLCK;
1906 lock.l_whence = SEEK_SET;
1907 lock.l_start = lock.l_len = 0L;
1908 if( unixFileLock(pFile, &lock)==0 ){
1909 pInode->eFileLock = NO_LOCK;
1910 }else{
1911 rc = SQLITE_IOERR_UNLOCK;
1912 storeLastErrno(pFile, errno);
1913 pInode->eFileLock = NO_LOCK;
1914 pFile->eFileLock = NO_LOCK;
1918 /* Decrement the count of locks against this same file. When the
1919 ** count reaches zero, close any other file descriptors whose close
1920 ** was deferred because of outstanding locks.
1922 pInode->nLock--;
1923 assert( pInode->nLock>=0 );
1924 if( pInode->nLock==0 ){
1925 closePendingFds(pFile);
1929 end_unlock:
1930 unixLeaveMutex();
1931 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
1932 return rc;
1936 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
1937 ** must be either NO_LOCK or SHARED_LOCK.
1939 ** If the locking level of the file descriptor is already at or below
1940 ** the requested locking level, this routine is a no-op.
1942 static int unixUnlock(sqlite3_file *id, int eFileLock){
1943 #if SQLITE_MAX_MMAP_SIZE>0
1944 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
1945 #endif
1946 return posixUnlock(id, eFileLock, 0);
1949 #if SQLITE_MAX_MMAP_SIZE>0
1950 static int unixMapfile(unixFile *pFd, i64 nByte);
1951 static void unixUnmapfile(unixFile *pFd);
1952 #endif
1955 ** This function performs the parts of the "close file" operation
1956 ** common to all locking schemes. It closes the directory and file
1957 ** handles, if they are valid, and sets all fields of the unixFile
1958 ** structure to 0.
1960 ** It is *not* necessary to hold the mutex when this routine is called,
1961 ** even on VxWorks. A mutex will be acquired on VxWorks by the
1962 ** vxworksReleaseFileId() routine.
1964 static int closeUnixFile(sqlite3_file *id){
1965 unixFile *pFile = (unixFile*)id;
1966 #if SQLITE_MAX_MMAP_SIZE>0
1967 unixUnmapfile(pFile);
1968 #endif
1969 if( pFile->h>=0 ){
1970 robust_close(pFile, pFile->h, __LINE__);
1971 pFile->h = -1;
1973 #if OS_VXWORKS
1974 if( pFile->pId ){
1975 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
1976 osUnlink(pFile->pId->zCanonicalName);
1978 vxworksReleaseFileId(pFile->pId);
1979 pFile->pId = 0;
1981 #endif
1982 #ifdef SQLITE_UNLINK_AFTER_CLOSE
1983 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
1984 osUnlink(pFile->zPath);
1985 sqlite3_free(*(char**)&pFile->zPath);
1986 pFile->zPath = 0;
1988 #endif
1989 OSTRACE(("CLOSE %-3d\n", pFile->h));
1990 OpenCounter(-1);
1991 sqlite3_free(pFile->pPreallocatedUnused);
1992 memset(pFile, 0, sizeof(unixFile));
1993 return SQLITE_OK;
1997 ** Close a file.
1999 static int unixClose(sqlite3_file *id){
2000 int rc = SQLITE_OK;
2001 unixFile *pFile = (unixFile *)id;
2002 verifyDbFile(pFile);
2003 unixUnlock(id, NO_LOCK);
2004 unixEnterMutex();
2006 /* unixFile.pInode is always valid here. Otherwise, a different close
2007 ** routine (e.g. nolockClose()) would be called instead.
2009 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
2010 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
2011 /* If there are outstanding locks, do not actually close the file just
2012 ** yet because that would clear those locks. Instead, add the file
2013 ** descriptor to pInode->pUnused list. It will be automatically closed
2014 ** when the last lock is cleared.
2016 setPendingFd(pFile);
2018 releaseInodeInfo(pFile);
2019 rc = closeUnixFile(id);
2020 unixLeaveMutex();
2021 return rc;
2024 /************** End of the posix advisory lock implementation *****************
2025 ******************************************************************************/
2027 /******************************************************************************
2028 ****************************** No-op Locking **********************************
2030 ** Of the various locking implementations available, this is by far the
2031 ** simplest: locking is ignored. No attempt is made to lock the database
2032 ** file for reading or writing.
2034 ** This locking mode is appropriate for use on read-only databases
2035 ** (ex: databases that are burned into CD-ROM, for example.) It can
2036 ** also be used if the application employs some external mechanism to
2037 ** prevent simultaneous access of the same database by two or more
2038 ** database connections. But there is a serious risk of database
2039 ** corruption if this locking mode is used in situations where multiple
2040 ** database connections are accessing the same database file at the same
2041 ** time and one or more of those connections are writing.
2044 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
2045 UNUSED_PARAMETER(NotUsed);
2046 *pResOut = 0;
2047 return SQLITE_OK;
2049 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
2050 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2051 return SQLITE_OK;
2053 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
2054 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2055 return SQLITE_OK;
2059 ** Close the file.
2061 static int nolockClose(sqlite3_file *id) {
2062 return closeUnixFile(id);
2065 /******************* End of the no-op lock implementation *********************
2066 ******************************************************************************/
2068 /******************************************************************************
2069 ************************* Begin dot-file Locking ******************************
2071 ** The dotfile locking implementation uses the existence of separate lock
2072 ** files (really a directory) to control access to the database. This works
2073 ** on just about every filesystem imaginable. But there are serious downsides:
2075 ** (1) There is zero concurrency. A single reader blocks all other
2076 ** connections from reading or writing the database.
2078 ** (2) An application crash or power loss can leave stale lock files
2079 ** sitting around that need to be cleared manually.
2081 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
2082 ** other locking strategy is available.
2084 ** Dotfile locking works by creating a subdirectory in the same directory as
2085 ** the database and with the same name but with a ".lock" extension added.
2086 ** The existence of a lock directory implies an EXCLUSIVE lock. All other
2087 ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
2091 ** The file suffix added to the data base filename in order to create the
2092 ** lock directory.
2094 #define DOTLOCK_SUFFIX ".lock"
2097 ** This routine checks if there is a RESERVED lock held on the specified
2098 ** file by this or any other process. If such a lock is held, set *pResOut
2099 ** to a non-zero value otherwise *pResOut is set to zero. The return value
2100 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2102 ** In dotfile locking, either a lock exists or it does not. So in this
2103 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
2104 ** is held on the file and false if the file is unlocked.
2106 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2107 int rc = SQLITE_OK;
2108 int reserved = 0;
2109 unixFile *pFile = (unixFile*)id;
2111 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2113 assert( pFile );
2114 reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
2115 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
2116 *pResOut = reserved;
2117 return rc;
2121 ** Lock the file with the lock specified by parameter eFileLock - one
2122 ** of the following:
2124 ** (1) SHARED_LOCK
2125 ** (2) RESERVED_LOCK
2126 ** (3) PENDING_LOCK
2127 ** (4) EXCLUSIVE_LOCK
2129 ** Sometimes when requesting one lock state, additional lock states
2130 ** are inserted in between. The locking might fail on one of the later
2131 ** transitions leaving the lock state different from what it started but
2132 ** still short of its goal. The following chart shows the allowed
2133 ** transitions and the inserted intermediate states:
2135 ** UNLOCKED -> SHARED
2136 ** SHARED -> RESERVED
2137 ** SHARED -> (PENDING) -> EXCLUSIVE
2138 ** RESERVED -> (PENDING) -> EXCLUSIVE
2139 ** PENDING -> EXCLUSIVE
2141 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
2142 ** routine to lower a locking level.
2144 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
2145 ** But we track the other locking levels internally.
2147 static int dotlockLock(sqlite3_file *id, int eFileLock) {
2148 unixFile *pFile = (unixFile*)id;
2149 char *zLockFile = (char *)pFile->lockingContext;
2150 int rc = SQLITE_OK;
2153 /* If we have any lock, then the lock file already exists. All we have
2154 ** to do is adjust our internal record of the lock level.
2156 if( pFile->eFileLock > NO_LOCK ){
2157 pFile->eFileLock = eFileLock;
2158 /* Always update the timestamp on the old file */
2159 #ifdef HAVE_UTIME
2160 utime(zLockFile, NULL);
2161 #else
2162 utimes(zLockFile, NULL);
2163 #endif
2164 return SQLITE_OK;
2167 /* grab an exclusive lock */
2168 rc = osMkdir(zLockFile, 0777);
2169 if( rc<0 ){
2170 /* failed to open/create the lock directory */
2171 int tErrno = errno;
2172 if( EEXIST == tErrno ){
2173 rc = SQLITE_BUSY;
2174 } else {
2175 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2176 if( rc!=SQLITE_BUSY ){
2177 storeLastErrno(pFile, tErrno);
2180 return rc;
2183 /* got it, set the type and return ok */
2184 pFile->eFileLock = eFileLock;
2185 return rc;
2189 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
2190 ** must be either NO_LOCK or SHARED_LOCK.
2192 ** If the locking level of the file descriptor is already at or below
2193 ** the requested locking level, this routine is a no-op.
2195 ** When the locking level reaches NO_LOCK, delete the lock file.
2197 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
2198 unixFile *pFile = (unixFile*)id;
2199 char *zLockFile = (char *)pFile->lockingContext;
2200 int rc;
2202 assert( pFile );
2203 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
2204 pFile->eFileLock, osGetpid(0)));
2205 assert( eFileLock<=SHARED_LOCK );
2207 /* no-op if possible */
2208 if( pFile->eFileLock==eFileLock ){
2209 return SQLITE_OK;
2212 /* To downgrade to shared, simply update our internal notion of the
2213 ** lock state. No need to mess with the file on disk.
2215 if( eFileLock==SHARED_LOCK ){
2216 pFile->eFileLock = SHARED_LOCK;
2217 return SQLITE_OK;
2220 /* To fully unlock the database, delete the lock file */
2221 assert( eFileLock==NO_LOCK );
2222 rc = osRmdir(zLockFile);
2223 if( rc<0 ){
2224 int tErrno = errno;
2225 if( tErrno==ENOENT ){
2226 rc = SQLITE_OK;
2227 }else{
2228 rc = SQLITE_IOERR_UNLOCK;
2229 storeLastErrno(pFile, tErrno);
2231 return rc;
2233 pFile->eFileLock = NO_LOCK;
2234 return SQLITE_OK;
2238 ** Close a file. Make sure the lock has been released before closing.
2240 static int dotlockClose(sqlite3_file *id) {
2241 unixFile *pFile = (unixFile*)id;
2242 assert( id!=0 );
2243 dotlockUnlock(id, NO_LOCK);
2244 sqlite3_free(pFile->lockingContext);
2245 return closeUnixFile(id);
2247 /****************** End of the dot-file lock implementation *******************
2248 ******************************************************************************/
2250 /******************************************************************************
2251 ************************** Begin flock Locking ********************************
2253 ** Use the flock() system call to do file locking.
2255 ** flock() locking is like dot-file locking in that the various
2256 ** fine-grain locking levels supported by SQLite are collapsed into
2257 ** a single exclusive lock. In other words, SHARED, RESERVED, and
2258 ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2259 ** still works when you do this, but concurrency is reduced since
2260 ** only a single process can be reading the database at a time.
2262 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
2264 #if SQLITE_ENABLE_LOCKING_STYLE
2267 ** Retry flock() calls that fail with EINTR
2269 #ifdef EINTR
2270 static int robust_flock(int fd, int op){
2271 int rc;
2272 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2273 return rc;
2275 #else
2276 # define robust_flock(a,b) flock(a,b)
2277 #endif
2281 ** This routine checks if there is a RESERVED lock held on the specified
2282 ** file by this or any other process. If such a lock is held, set *pResOut
2283 ** to a non-zero value otherwise *pResOut is set to zero. The return value
2284 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2286 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2287 int rc = SQLITE_OK;
2288 int reserved = 0;
2289 unixFile *pFile = (unixFile*)id;
2291 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2293 assert( pFile );
2295 /* Check if a thread in this process holds such a lock */
2296 if( pFile->eFileLock>SHARED_LOCK ){
2297 reserved = 1;
2300 /* Otherwise see if some other process holds it. */
2301 if( !reserved ){
2302 /* attempt to get the lock */
2303 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
2304 if( !lrc ){
2305 /* got the lock, unlock it */
2306 lrc = robust_flock(pFile->h, LOCK_UN);
2307 if ( lrc ) {
2308 int tErrno = errno;
2309 /* unlock failed with an error */
2310 lrc = SQLITE_IOERR_UNLOCK;
2311 storeLastErrno(pFile, tErrno);
2312 rc = lrc;
2314 } else {
2315 int tErrno = errno;
2316 reserved = 1;
2317 /* someone else might have it reserved */
2318 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2319 if( IS_LOCK_ERROR(lrc) ){
2320 storeLastErrno(pFile, tErrno);
2321 rc = lrc;
2325 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
2327 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2328 if( (rc & 0xff) == SQLITE_IOERR ){
2329 rc = SQLITE_OK;
2330 reserved=1;
2332 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2333 *pResOut = reserved;
2334 return rc;
2338 ** Lock the file with the lock specified by parameter eFileLock - one
2339 ** of the following:
2341 ** (1) SHARED_LOCK
2342 ** (2) RESERVED_LOCK
2343 ** (3) PENDING_LOCK
2344 ** (4) EXCLUSIVE_LOCK
2346 ** Sometimes when requesting one lock state, additional lock states
2347 ** are inserted in between. The locking might fail on one of the later
2348 ** transitions leaving the lock state different from what it started but
2349 ** still short of its goal. The following chart shows the allowed
2350 ** transitions and the inserted intermediate states:
2352 ** UNLOCKED -> SHARED
2353 ** SHARED -> RESERVED
2354 ** SHARED -> (PENDING) -> EXCLUSIVE
2355 ** RESERVED -> (PENDING) -> EXCLUSIVE
2356 ** PENDING -> EXCLUSIVE
2358 ** flock() only really support EXCLUSIVE locks. We track intermediate
2359 ** lock states in the sqlite3_file structure, but all locks SHARED or
2360 ** above are really EXCLUSIVE locks and exclude all other processes from
2361 ** access the file.
2363 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
2364 ** routine to lower a locking level.
2366 static int flockLock(sqlite3_file *id, int eFileLock) {
2367 int rc = SQLITE_OK;
2368 unixFile *pFile = (unixFile*)id;
2370 assert( pFile );
2372 /* if we already have a lock, it is exclusive.
2373 ** Just adjust level and punt on outta here. */
2374 if (pFile->eFileLock > NO_LOCK) {
2375 pFile->eFileLock = eFileLock;
2376 return SQLITE_OK;
2379 /* grab an exclusive lock */
2381 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
2382 int tErrno = errno;
2383 /* didn't get, must be busy */
2384 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2385 if( IS_LOCK_ERROR(rc) ){
2386 storeLastErrno(pFile, tErrno);
2388 } else {
2389 /* got it, set the type and return ok */
2390 pFile->eFileLock = eFileLock;
2392 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2393 rc==SQLITE_OK ? "ok" : "failed"));
2394 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2395 if( (rc & 0xff) == SQLITE_IOERR ){
2396 rc = SQLITE_BUSY;
2398 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2399 return rc;
2404 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
2405 ** must be either NO_LOCK or SHARED_LOCK.
2407 ** If the locking level of the file descriptor is already at or below
2408 ** the requested locking level, this routine is a no-op.
2410 static int flockUnlock(sqlite3_file *id, int eFileLock) {
2411 unixFile *pFile = (unixFile*)id;
2413 assert( pFile );
2414 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2415 pFile->eFileLock, osGetpid(0)));
2416 assert( eFileLock<=SHARED_LOCK );
2418 /* no-op if possible */
2419 if( pFile->eFileLock==eFileLock ){
2420 return SQLITE_OK;
2423 /* shared can just be set because we always have an exclusive */
2424 if (eFileLock==SHARED_LOCK) {
2425 pFile->eFileLock = eFileLock;
2426 return SQLITE_OK;
2429 /* no, really, unlock. */
2430 if( robust_flock(pFile->h, LOCK_UN) ){
2431 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2432 return SQLITE_OK;
2433 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2434 return SQLITE_IOERR_UNLOCK;
2435 }else{
2436 pFile->eFileLock = NO_LOCK;
2437 return SQLITE_OK;
2442 ** Close a file.
2444 static int flockClose(sqlite3_file *id) {
2445 assert( id!=0 );
2446 flockUnlock(id, NO_LOCK);
2447 return closeUnixFile(id);
2450 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2452 /******************* End of the flock lock implementation *********************
2453 ******************************************************************************/
2455 /******************************************************************************
2456 ************************ Begin Named Semaphore Locking ************************
2458 ** Named semaphore locking is only supported on VxWorks.
2460 ** Semaphore locking is like dot-lock and flock in that it really only
2461 ** supports EXCLUSIVE locking. Only a single process can read or write
2462 ** the database file at a time. This reduces potential concurrency, but
2463 ** makes the lock implementation much easier.
2465 #if OS_VXWORKS
2468 ** This routine checks if there is a RESERVED lock held on the specified
2469 ** file by this or any other process. If such a lock is held, set *pResOut
2470 ** to a non-zero value otherwise *pResOut is set to zero. The return value
2471 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2473 static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
2474 int rc = SQLITE_OK;
2475 int reserved = 0;
2476 unixFile *pFile = (unixFile*)id;
2478 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2480 assert( pFile );
2482 /* Check if a thread in this process holds such a lock */
2483 if( pFile->eFileLock>SHARED_LOCK ){
2484 reserved = 1;
2487 /* Otherwise see if some other process holds it. */
2488 if( !reserved ){
2489 sem_t *pSem = pFile->pInode->pSem;
2491 if( sem_trywait(pSem)==-1 ){
2492 int tErrno = errno;
2493 if( EAGAIN != tErrno ){
2494 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2495 storeLastErrno(pFile, tErrno);
2496 } else {
2497 /* someone else has the lock when we are in NO_LOCK */
2498 reserved = (pFile->eFileLock < SHARED_LOCK);
2500 }else{
2501 /* we could have it if we want it */
2502 sem_post(pSem);
2505 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
2507 *pResOut = reserved;
2508 return rc;
2512 ** Lock the file with the lock specified by parameter eFileLock - one
2513 ** of the following:
2515 ** (1) SHARED_LOCK
2516 ** (2) RESERVED_LOCK
2517 ** (3) PENDING_LOCK
2518 ** (4) EXCLUSIVE_LOCK
2520 ** Sometimes when requesting one lock state, additional lock states
2521 ** are inserted in between. The locking might fail on one of the later
2522 ** transitions leaving the lock state different from what it started but
2523 ** still short of its goal. The following chart shows the allowed
2524 ** transitions and the inserted intermediate states:
2526 ** UNLOCKED -> SHARED
2527 ** SHARED -> RESERVED
2528 ** SHARED -> (PENDING) -> EXCLUSIVE
2529 ** RESERVED -> (PENDING) -> EXCLUSIVE
2530 ** PENDING -> EXCLUSIVE
2532 ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2533 ** lock states in the sqlite3_file structure, but all locks SHARED or
2534 ** above are really EXCLUSIVE locks and exclude all other processes from
2535 ** access the file.
2537 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
2538 ** routine to lower a locking level.
2540 static int semXLock(sqlite3_file *id, int eFileLock) {
2541 unixFile *pFile = (unixFile*)id;
2542 sem_t *pSem = pFile->pInode->pSem;
2543 int rc = SQLITE_OK;
2545 /* if we already have a lock, it is exclusive.
2546 ** Just adjust level and punt on outta here. */
2547 if (pFile->eFileLock > NO_LOCK) {
2548 pFile->eFileLock = eFileLock;
2549 rc = SQLITE_OK;
2550 goto sem_end_lock;
2553 /* lock semaphore now but bail out when already locked. */
2554 if( sem_trywait(pSem)==-1 ){
2555 rc = SQLITE_BUSY;
2556 goto sem_end_lock;
2559 /* got it, set the type and return ok */
2560 pFile->eFileLock = eFileLock;
2562 sem_end_lock:
2563 return rc;
2567 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
2568 ** must be either NO_LOCK or SHARED_LOCK.
2570 ** If the locking level of the file descriptor is already at or below
2571 ** the requested locking level, this routine is a no-op.
2573 static int semXUnlock(sqlite3_file *id, int eFileLock) {
2574 unixFile *pFile = (unixFile*)id;
2575 sem_t *pSem = pFile->pInode->pSem;
2577 assert( pFile );
2578 assert( pSem );
2579 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2580 pFile->eFileLock, osGetpid(0)));
2581 assert( eFileLock<=SHARED_LOCK );
2583 /* no-op if possible */
2584 if( pFile->eFileLock==eFileLock ){
2585 return SQLITE_OK;
2588 /* shared can just be set because we always have an exclusive */
2589 if (eFileLock==SHARED_LOCK) {
2590 pFile->eFileLock = eFileLock;
2591 return SQLITE_OK;
2594 /* no, really unlock. */
2595 if ( sem_post(pSem)==-1 ) {
2596 int rc, tErrno = errno;
2597 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2598 if( IS_LOCK_ERROR(rc) ){
2599 storeLastErrno(pFile, tErrno);
2601 return rc;
2603 pFile->eFileLock = NO_LOCK;
2604 return SQLITE_OK;
2608 ** Close a file.
2610 static int semXClose(sqlite3_file *id) {
2611 if( id ){
2612 unixFile *pFile = (unixFile*)id;
2613 semXUnlock(id, NO_LOCK);
2614 assert( pFile );
2615 unixEnterMutex();
2616 releaseInodeInfo(pFile);
2617 unixLeaveMutex();
2618 closeUnixFile(id);
2620 return SQLITE_OK;
2623 #endif /* OS_VXWORKS */
2625 ** Named semaphore locking is only available on VxWorks.
2627 *************** End of the named semaphore lock implementation ****************
2628 ******************************************************************************/
2631 /******************************************************************************
2632 *************************** Begin AFP Locking *********************************
2634 ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2635 ** on Apple Macintosh computers - both OS9 and OSX.
2637 ** Third-party implementations of AFP are available. But this code here
2638 ** only works on OSX.
2641 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2643 ** The afpLockingContext structure contains all afp lock specific state
2645 typedef struct afpLockingContext afpLockingContext;
2646 struct afpLockingContext {
2647 int reserved;
2648 const char *dbPath; /* Name of the open file */
2651 struct ByteRangeLockPB2
2653 unsigned long long offset; /* offset to first byte to lock */
2654 unsigned long long length; /* nbr of bytes to lock */
2655 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2656 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2657 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2658 int fd; /* file desc to assoc this lock with */
2661 #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
2664 ** This is a utility for setting or clearing a bit-range lock on an
2665 ** AFP filesystem.
2667 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2669 static int afpSetLock(
2670 const char *path, /* Name of the file to be locked or unlocked */
2671 unixFile *pFile, /* Open file descriptor on path */
2672 unsigned long long offset, /* First byte to be locked */
2673 unsigned long long length, /* Number of bytes to lock */
2674 int setLockFlag /* True to set lock. False to clear lock */
2676 struct ByteRangeLockPB2 pb;
2677 int err;
2679 pb.unLockFlag = setLockFlag ? 0 : 1;
2680 pb.startEndFlag = 0;
2681 pb.offset = offset;
2682 pb.length = length;
2683 pb.fd = pFile->h;
2685 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
2686 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
2687 offset, length));
2688 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2689 if ( err==-1 ) {
2690 int rc;
2691 int tErrno = errno;
2692 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2693 path, tErrno, strerror(tErrno)));
2694 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2695 rc = SQLITE_BUSY;
2696 #else
2697 rc = sqliteErrorFromPosixError(tErrno,
2698 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
2699 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
2700 if( IS_LOCK_ERROR(rc) ){
2701 storeLastErrno(pFile, tErrno);
2703 return rc;
2704 } else {
2705 return SQLITE_OK;
2710 ** This routine checks if there is a RESERVED lock held on the specified
2711 ** file by this or any other process. If such a lock is held, set *pResOut
2712 ** to a non-zero value otherwise *pResOut is set to zero. The return value
2713 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2715 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
2716 int rc = SQLITE_OK;
2717 int reserved = 0;
2718 unixFile *pFile = (unixFile*)id;
2719 afpLockingContext *context;
2721 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2723 assert( pFile );
2724 context = (afpLockingContext *) pFile->lockingContext;
2725 if( context->reserved ){
2726 *pResOut = 1;
2727 return SQLITE_OK;
2729 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
2731 /* Check if a thread in this process holds such a lock */
2732 if( pFile->pInode->eFileLock>SHARED_LOCK ){
2733 reserved = 1;
2736 /* Otherwise see if some other process holds it.
2738 if( !reserved ){
2739 /* lock the RESERVED byte */
2740 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
2741 if( SQLITE_OK==lrc ){
2742 /* if we succeeded in taking the reserved lock, unlock it to restore
2743 ** the original state */
2744 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2745 } else {
2746 /* if we failed to get the lock then someone else must have it */
2747 reserved = 1;
2749 if( IS_LOCK_ERROR(lrc) ){
2750 rc=lrc;
2754 unixLeaveMutex();
2755 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
2757 *pResOut = reserved;
2758 return rc;
2762 ** Lock the file with the lock specified by parameter eFileLock - one
2763 ** of the following:
2765 ** (1) SHARED_LOCK
2766 ** (2) RESERVED_LOCK
2767 ** (3) PENDING_LOCK
2768 ** (4) EXCLUSIVE_LOCK
2770 ** Sometimes when requesting one lock state, additional lock states
2771 ** are inserted in between. The locking might fail on one of the later
2772 ** transitions leaving the lock state different from what it started but
2773 ** still short of its goal. The following chart shows the allowed
2774 ** transitions and the inserted intermediate states:
2776 ** UNLOCKED -> SHARED
2777 ** SHARED -> RESERVED
2778 ** SHARED -> (PENDING) -> EXCLUSIVE
2779 ** RESERVED -> (PENDING) -> EXCLUSIVE
2780 ** PENDING -> EXCLUSIVE
2782 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
2783 ** routine to lower a locking level.
2785 static int afpLock(sqlite3_file *id, int eFileLock){
2786 int rc = SQLITE_OK;
2787 unixFile *pFile = (unixFile*)id;
2788 unixInodeInfo *pInode = pFile->pInode;
2789 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2791 assert( pFile );
2792 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2793 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
2794 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
2796 /* If there is already a lock of this type or more restrictive on the
2797 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
2798 ** unixEnterMutex() hasn't been called yet.
2800 if( pFile->eFileLock>=eFileLock ){
2801 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2802 azFileLock(eFileLock)));
2803 return SQLITE_OK;
2806 /* Make sure the locking sequence is correct
2807 ** (1) We never move from unlocked to anything higher than shared lock.
2808 ** (2) SQLite never explicitly requests a pendig lock.
2809 ** (3) A shared lock is always held when a reserve lock is requested.
2811 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2812 assert( eFileLock!=PENDING_LOCK );
2813 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
2815 /* This mutex is needed because pFile->pInode is shared across threads
2817 unixEnterMutex();
2818 pInode = pFile->pInode;
2820 /* If some thread using this PID has a lock via a different unixFile*
2821 ** handle that precludes the requested lock, return BUSY.
2823 if( (pFile->eFileLock!=pInode->eFileLock &&
2824 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
2826 rc = SQLITE_BUSY;
2827 goto afp_end_lock;
2830 /* If a SHARED lock is requested, and some thread using this PID already
2831 ** has a SHARED or RESERVED lock, then increment reference counts and
2832 ** return SQLITE_OK.
2834 if( eFileLock==SHARED_LOCK &&
2835 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
2836 assert( eFileLock==SHARED_LOCK );
2837 assert( pFile->eFileLock==0 );
2838 assert( pInode->nShared>0 );
2839 pFile->eFileLock = SHARED_LOCK;
2840 pInode->nShared++;
2841 pInode->nLock++;
2842 goto afp_end_lock;
2845 /* A PENDING lock is needed before acquiring a SHARED lock and before
2846 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2847 ** be released.
2849 if( eFileLock==SHARED_LOCK
2850 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
2852 int failed;
2853 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
2854 if (failed) {
2855 rc = failed;
2856 goto afp_end_lock;
2860 /* If control gets to this point, then actually go ahead and make
2861 ** operating system calls for the specified lock.
2863 if( eFileLock==SHARED_LOCK ){
2864 int lrc1, lrc2, lrc1Errno = 0;
2865 long lk, mask;
2867 assert( pInode->nShared==0 );
2868 assert( pInode->eFileLock==0 );
2870 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
2871 /* Now get the read-lock SHARED_LOCK */
2872 /* note that the quality of the randomness doesn't matter that much */
2873 lk = random();
2874 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
2875 lrc1 = afpSetLock(context->dbPath, pFile,
2876 SHARED_FIRST+pInode->sharedByte, 1, 1);
2877 if( IS_LOCK_ERROR(lrc1) ){
2878 lrc1Errno = pFile->lastErrno;
2880 /* Drop the temporary PENDING lock */
2881 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
2883 if( IS_LOCK_ERROR(lrc1) ) {
2884 storeLastErrno(pFile, lrc1Errno);
2885 rc = lrc1;
2886 goto afp_end_lock;
2887 } else if( IS_LOCK_ERROR(lrc2) ){
2888 rc = lrc2;
2889 goto afp_end_lock;
2890 } else if( lrc1 != SQLITE_OK ) {
2891 rc = lrc1;
2892 } else {
2893 pFile->eFileLock = SHARED_LOCK;
2894 pInode->nLock++;
2895 pInode->nShared = 1;
2897 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
2898 /* We are trying for an exclusive lock but another thread in this
2899 ** same process is still holding a shared lock. */
2900 rc = SQLITE_BUSY;
2901 }else{
2902 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2903 ** assumed that there is a SHARED or greater lock on the file
2904 ** already.
2906 int failed = 0;
2907 assert( 0!=pFile->eFileLock );
2908 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
2909 /* Acquire a RESERVED lock */
2910 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
2911 if( !failed ){
2912 context->reserved = 1;
2915 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
2916 /* Acquire an EXCLUSIVE lock */
2918 /* Remove the shared lock before trying the range. we'll need to
2919 ** reestablish the shared lock if we can't get the afpUnlock
2921 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
2922 pInode->sharedByte, 1, 0)) ){
2923 int failed2 = SQLITE_OK;
2924 /* now attemmpt to get the exclusive lock range */
2925 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
2926 SHARED_SIZE, 1);
2927 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
2928 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
2929 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2930 ** a critical I/O error
2932 rc = ((failed & 0xff) == SQLITE_IOERR) ? failed2 :
2933 SQLITE_IOERR_LOCK;
2934 goto afp_end_lock;
2936 }else{
2937 rc = failed;
2940 if( failed ){
2941 rc = failed;
2945 if( rc==SQLITE_OK ){
2946 pFile->eFileLock = eFileLock;
2947 pInode->eFileLock = eFileLock;
2948 }else if( eFileLock==EXCLUSIVE_LOCK ){
2949 pFile->eFileLock = PENDING_LOCK;
2950 pInode->eFileLock = PENDING_LOCK;
2953 afp_end_lock:
2954 unixLeaveMutex();
2955 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2956 rc==SQLITE_OK ? "ok" : "failed"));
2957 return rc;
2961 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
2962 ** must be either NO_LOCK or SHARED_LOCK.
2964 ** If the locking level of the file descriptor is already at or below
2965 ** the requested locking level, this routine is a no-op.
2967 static int afpUnlock(sqlite3_file *id, int eFileLock) {
2968 int rc = SQLITE_OK;
2969 unixFile *pFile = (unixFile*)id;
2970 unixInodeInfo *pInode;
2971 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2972 int skipShared = 0;
2973 #ifdef SQLITE_TEST
2974 int h = pFile->h;
2975 #endif
2977 assert( pFile );
2978 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
2979 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
2980 osGetpid(0)));
2982 assert( eFileLock<=SHARED_LOCK );
2983 if( pFile->eFileLock<=eFileLock ){
2984 return SQLITE_OK;
2986 unixEnterMutex();
2987 pInode = pFile->pInode;
2988 assert( pInode->nShared!=0 );
2989 if( pFile->eFileLock>SHARED_LOCK ){
2990 assert( pInode->eFileLock==pFile->eFileLock );
2991 SimulateIOErrorBenign(1);
2992 SimulateIOError( h=(-1) )
2993 SimulateIOErrorBenign(0);
2995 #ifdef SQLITE_DEBUG
2996 /* When reducing a lock such that other processes can start
2997 ** reading the database file again, make sure that the
2998 ** transaction counter was updated if any part of the database
2999 ** file changed. If the transaction counter is not updated,
3000 ** other connections to the same file might not realize that
3001 ** the file has changed and hence might not know to flush their
3002 ** cache. The use of a stale cache can lead to database corruption.
3004 assert( pFile->inNormalWrite==0
3005 || pFile->dbUpdate==0
3006 || pFile->transCntrChng==1 );
3007 pFile->inNormalWrite = 0;
3008 #endif
3010 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
3011 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
3012 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
3013 /* only re-establish the shared lock if necessary */
3014 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3015 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
3016 } else {
3017 skipShared = 1;
3020 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
3021 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
3023 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
3024 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
3025 if( !rc ){
3026 context->reserved = 0;
3029 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
3030 pInode->eFileLock = SHARED_LOCK;
3033 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
3035 /* Decrement the shared lock counter. Release the lock using an
3036 ** OS call only when all threads in this same process have released
3037 ** the lock.
3039 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3040 pInode->nShared--;
3041 if( pInode->nShared==0 ){
3042 SimulateIOErrorBenign(1);
3043 SimulateIOError( h=(-1) )
3044 SimulateIOErrorBenign(0);
3045 if( !skipShared ){
3046 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
3048 if( !rc ){
3049 pInode->eFileLock = NO_LOCK;
3050 pFile->eFileLock = NO_LOCK;
3053 if( rc==SQLITE_OK ){
3054 pInode->nLock--;
3055 assert( pInode->nLock>=0 );
3056 if( pInode->nLock==0 ){
3057 closePendingFds(pFile);
3062 unixLeaveMutex();
3063 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
3064 return rc;
3068 ** Close a file & cleanup AFP specific locking context
3070 static int afpClose(sqlite3_file *id) {
3071 int rc = SQLITE_OK;
3072 unixFile *pFile = (unixFile*)id;
3073 assert( id!=0 );
3074 afpUnlock(id, NO_LOCK);
3075 unixEnterMutex();
3076 if( pFile->pInode && pFile->pInode->nLock ){
3077 /* If there are outstanding locks, do not actually close the file just
3078 ** yet because that would clear those locks. Instead, add the file
3079 ** descriptor to pInode->aPending. It will be automatically closed when
3080 ** the last lock is cleared.
3082 setPendingFd(pFile);
3084 releaseInodeInfo(pFile);
3085 sqlite3_free(pFile->lockingContext);
3086 rc = closeUnixFile(id);
3087 unixLeaveMutex();
3088 return rc;
3091 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3093 ** The code above is the AFP lock implementation. The code is specific
3094 ** to MacOSX and does not work on other unix platforms. No alternative
3095 ** is available. If you don't compile for a mac, then the "unix-afp"
3096 ** VFS is not available.
3098 ********************* End of the AFP lock implementation **********************
3099 ******************************************************************************/
3101 /******************************************************************************
3102 *************************** Begin NFS Locking ********************************/
3104 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3106 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
3107 ** must be either NO_LOCK or SHARED_LOCK.
3109 ** If the locking level of the file descriptor is already at or below
3110 ** the requested locking level, this routine is a no-op.
3112 static int nfsUnlock(sqlite3_file *id, int eFileLock){
3113 return posixUnlock(id, eFileLock, 1);
3116 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3118 ** The code above is the NFS lock implementation. The code is specific
3119 ** to MacOSX and does not work on other unix platforms. No alternative
3120 ** is available.
3122 ********************* End of the NFS lock implementation **********************
3123 ******************************************************************************/
3125 /******************************************************************************
3126 **************** Non-locking sqlite3_file methods *****************************
3128 ** The next division contains implementations for all methods of the
3129 ** sqlite3_file object other than the locking methods. The locking
3130 ** methods were defined in divisions above (one locking method per
3131 ** division). Those methods that are common to all locking modes
3132 ** are gather together into this division.
3136 ** Seek to the offset passed as the second argument, then read cnt
3137 ** bytes into pBuf. Return the number of bytes actually read.
3139 ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3140 ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3141 ** one system to another. Since SQLite does not define USE_PREAD
3142 ** in any form by default, we will not attempt to define _XOPEN_SOURCE.
3143 ** See tickets #2741 and #2681.
3145 ** To avoid stomping the errno value on a failed read the lastErrno value
3146 ** is set before returning.
3148 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3149 int got;
3150 int prior = 0;
3151 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
3152 i64 newOffset;
3153 #endif
3154 TIMER_START;
3155 assert( cnt==(cnt&0x1ffff) );
3156 assert( id->h>2 );
3158 #if defined(USE_PREAD)
3159 got = osPread(id->h, pBuf, cnt, offset);
3160 SimulateIOError( got = -1 );
3161 #elif defined(USE_PREAD64)
3162 got = osPread64(id->h, pBuf, cnt, offset);
3163 SimulateIOError( got = -1 );
3164 #else
3165 newOffset = lseek(id->h, offset, SEEK_SET);
3166 SimulateIOError( newOffset = -1 );
3167 if( newOffset<0 ){
3168 storeLastErrno((unixFile*)id, errno);
3169 return -1;
3171 got = osRead(id->h, pBuf, cnt);
3172 #endif
3173 if( got==cnt ) break;
3174 if( got<0 ){
3175 if( errno==EINTR ){ got = 1; continue; }
3176 prior = 0;
3177 storeLastErrno((unixFile*)id, errno);
3178 break;
3179 }else if( got>0 ){
3180 cnt -= got;
3181 offset += got;
3182 prior += got;
3183 pBuf = (void*)(got + (char*)pBuf);
3185 }while( got>0 );
3186 TIMER_END;
3187 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3188 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3189 return got+prior;
3193 ** Read data from a file into a buffer. Return SQLITE_OK if all
3194 ** bytes were read successfully and SQLITE_IOERR if anything goes
3195 ** wrong.
3197 static int unixRead(
3198 sqlite3_file *id,
3199 void *pBuf,
3200 int amt,
3201 sqlite3_int64 offset
3203 unixFile *pFile = (unixFile *)id;
3204 int got;
3205 assert( id );
3206 assert( offset>=0 );
3207 assert( amt>0 );
3209 /* If this is a database file (not a journal, master-journal or temp
3210 ** file), the bytes in the locking range should never be read or written. */
3211 #if 0
3212 assert( pFile->pPreallocatedUnused==0
3213 || offset>=PENDING_BYTE+512
3214 || offset+amt<=PENDING_BYTE
3216 #endif
3218 #if SQLITE_MAX_MMAP_SIZE>0
3219 /* Deal with as much of this read request as possible by transfering
3220 ** data from the memory mapping using memcpy(). */
3221 if( offset<pFile->mmapSize ){
3222 if( offset+amt <= pFile->mmapSize ){
3223 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3224 return SQLITE_OK;
3225 }else{
3226 int nCopy = pFile->mmapSize - offset;
3227 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3228 pBuf = &((u8 *)pBuf)[nCopy];
3229 amt -= nCopy;
3230 offset += nCopy;
3233 #endif
3235 got = seekAndRead(pFile, offset, pBuf, amt);
3236 if( got==amt ){
3237 return SQLITE_OK;
3238 }else if( got<0 ){
3239 /* lastErrno set by seekAndRead */
3240 return SQLITE_IOERR_READ;
3241 }else{
3242 storeLastErrno(pFile, 0); /* not a system error */
3243 /* Unread parts of the buffer must be zero-filled */
3244 memset(&((char*)pBuf)[got], 0, amt-got);
3245 return SQLITE_IOERR_SHORT_READ;
3250 ** Attempt to seek the file-descriptor passed as the first argument to
3251 ** absolute offset iOff, then attempt to write nBuf bytes of data from
3252 ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3253 ** return the actual number of bytes written (which may be less than
3254 ** nBuf).
3256 static int seekAndWriteFd(
3257 int fd, /* File descriptor to write to */
3258 i64 iOff, /* File offset to begin writing at */
3259 const void *pBuf, /* Copy data from this buffer to the file */
3260 int nBuf, /* Size of buffer pBuf in bytes */
3261 int *piErrno /* OUT: Error number if error occurs */
3263 int rc = 0; /* Value returned by system call */
3265 assert( nBuf==(nBuf&0x1ffff) );
3266 assert( fd>2 );
3267 assert( piErrno!=0 );
3268 nBuf &= 0x1ffff;
3269 TIMER_START;
3271 #if defined(USE_PREAD)
3272 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
3273 #elif defined(USE_PREAD64)
3274 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
3275 #else
3277 i64 iSeek = lseek(fd, iOff, SEEK_SET);
3278 SimulateIOError( iSeek = -1 );
3279 if( iSeek<0 ){
3280 rc = -1;
3281 break;
3283 rc = osWrite(fd, pBuf, nBuf);
3284 }while( rc<0 && errno==EINTR );
3285 #endif
3287 TIMER_END;
3288 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3290 if( rc<0 ) *piErrno = errno;
3291 return rc;
3296 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
3297 ** Return the number of bytes actually read. Update the offset.
3299 ** To avoid stomping the errno value on a failed write the lastErrno value
3300 ** is set before returning.
3302 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
3303 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
3308 ** Write data from a buffer into a file. Return SQLITE_OK on success
3309 ** or some other error code on failure.
3311 static int unixWrite(
3312 sqlite3_file *id,
3313 const void *pBuf,
3314 int amt,
3315 sqlite3_int64 offset
3317 unixFile *pFile = (unixFile*)id;
3318 int wrote = 0;
3319 assert( id );
3320 assert( amt>0 );
3322 /* If this is a database file (not a journal, master-journal or temp
3323 ** file), the bytes in the locking range should never be read or written. */
3324 #if 0
3325 assert( pFile->pPreallocatedUnused==0
3326 || offset>=PENDING_BYTE+512
3327 || offset+amt<=PENDING_BYTE
3329 #endif
3331 #ifdef SQLITE_DEBUG
3332 /* If we are doing a normal write to a database file (as opposed to
3333 ** doing a hot-journal rollback or a write to some file other than a
3334 ** normal database file) then record the fact that the database
3335 ** has changed. If the transaction counter is modified, record that
3336 ** fact too.
3338 if( pFile->inNormalWrite ){
3339 pFile->dbUpdate = 1; /* The database has been modified */
3340 if( offset<=24 && offset+amt>=27 ){
3341 int rc;
3342 char oldCntr[4];
3343 SimulateIOErrorBenign(1);
3344 rc = seekAndRead(pFile, 24, oldCntr, 4);
3345 SimulateIOErrorBenign(0);
3346 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
3347 pFile->transCntrChng = 1; /* The transaction counter has changed */
3351 #endif
3353 #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
3354 /* Deal with as much of this write request as possible by transfering
3355 ** data from the memory mapping using memcpy(). */
3356 if( offset<pFile->mmapSize ){
3357 if( offset+amt <= pFile->mmapSize ){
3358 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3359 return SQLITE_OK;
3360 }else{
3361 int nCopy = pFile->mmapSize - offset;
3362 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3363 pBuf = &((u8 *)pBuf)[nCopy];
3364 amt -= nCopy;
3365 offset += nCopy;
3368 #endif
3370 while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
3371 amt -= wrote;
3372 offset += wrote;
3373 pBuf = &((char*)pBuf)[wrote];
3375 SimulateIOError(( wrote=(-1), amt=1 ));
3376 SimulateDiskfullError(( wrote=0, amt=1 ));
3378 if( amt>wrote ){
3379 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
3380 /* lastErrno set by seekAndWrite */
3381 return SQLITE_IOERR_WRITE;
3382 }else{
3383 storeLastErrno(pFile, 0); /* not a system error */
3384 return SQLITE_FULL;
3388 return SQLITE_OK;
3391 #ifdef SQLITE_TEST
3393 ** Count the number of fullsyncs and normal syncs. This is used to test
3394 ** that syncs and fullsyncs are occurring at the right times.
3396 int sqlite3_sync_count = 0;
3397 int sqlite3_fullsync_count = 0;
3398 #endif
3401 ** We do not trust systems to provide a working fdatasync(). Some do.
3402 ** Others do no. To be safe, we will stick with the (slightly slower)
3403 ** fsync(). If you know that your system does support fdatasync() correctly,
3404 ** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
3406 #if !defined(fdatasync) && !HAVE_FDATASYNC
3407 # define fdatasync fsync
3408 #endif
3411 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3412 ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3413 ** only available on Mac OS X. But that could change.
3415 #ifdef F_FULLFSYNC
3416 # define HAVE_FULLFSYNC 1
3417 #else
3418 # define HAVE_FULLFSYNC 0
3419 #endif
3423 ** The fsync() system call does not work as advertised on many
3424 ** unix systems. The following procedure is an attempt to make
3425 ** it work better.
3427 ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3428 ** for testing when we want to run through the test suite quickly.
3429 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3430 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3431 ** or power failure will likely corrupt the database file.
3433 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
3434 ** The idea behind dataOnly is that it should only write the file content
3435 ** to disk, not the inode. We only set dataOnly if the file size is
3436 ** unchanged since the file size is part of the inode. However,
3437 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
3438 ** file size has changed. The only real difference between fdatasync()
3439 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
3440 ** inode if the mtime or owner or other inode attributes have changed.
3441 ** We only care about the file size, not the other file attributes, so
3442 ** as far as SQLite is concerned, an fdatasync() is always adequate.
3443 ** So, we always use fdatasync() if it is available, regardless of
3444 ** the value of the dataOnly flag.
3446 static int full_fsync(int fd, int fullSync, int dataOnly){
3447 int rc;
3449 /* The following "ifdef/elif/else/" block has the same structure as
3450 ** the one below. It is replicated here solely to avoid cluttering
3451 ** up the real code with the UNUSED_PARAMETER() macros.
3453 #ifdef SQLITE_NO_SYNC
3454 UNUSED_PARAMETER(fd);
3455 UNUSED_PARAMETER(fullSync);
3456 UNUSED_PARAMETER(dataOnly);
3457 #elif HAVE_FULLFSYNC
3458 UNUSED_PARAMETER(dataOnly);
3459 #else
3460 UNUSED_PARAMETER(fullSync);
3461 UNUSED_PARAMETER(dataOnly);
3462 #endif
3464 /* Record the number of times that we do a normal fsync() and
3465 ** FULLSYNC. This is used during testing to verify that this procedure
3466 ** gets called with the correct arguments.
3468 #ifdef SQLITE_TEST
3469 if( fullSync ) sqlite3_fullsync_count++;
3470 sqlite3_sync_count++;
3471 #endif
3473 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3474 ** no-op. But go ahead and call fstat() to validate the file
3475 ** descriptor as we need a method to provoke a failure during
3476 ** coverate testing.
3478 #ifdef SQLITE_NO_SYNC
3480 struct stat buf;
3481 rc = osFstat(fd, &buf);
3483 #elif HAVE_FULLFSYNC
3484 if( fullSync ){
3485 rc = osFcntl(fd, F_FULLFSYNC, 0);
3486 }else{
3487 rc = 1;
3489 /* If the FULLFSYNC failed, fall back to attempting an fsync().
3490 ** It shouldn't be possible for fullfsync to fail on the local
3491 ** file system (on OSX), so failure indicates that FULLFSYNC
3492 ** isn't supported for this file system. So, attempt an fsync
3493 ** and (for now) ignore the overhead of a superfluous fcntl call.
3494 ** It'd be better to detect fullfsync support once and avoid
3495 ** the fcntl call every time sync is called.
3497 if( rc ) rc = fsync(fd);
3499 #elif defined(__APPLE__)
3500 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3501 ** so currently we default to the macro that redefines fdatasync to fsync
3503 rc = fsync(fd);
3504 #else
3505 rc = fdatasync(fd);
3506 #if OS_VXWORKS
3507 if( rc==-1 && errno==ENOTSUP ){
3508 rc = fsync(fd);
3510 #endif /* OS_VXWORKS */
3511 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3513 if( OS_VXWORKS && rc!= -1 ){
3514 rc = 0;
3516 return rc;
3520 ** Open a file descriptor to the directory containing file zFilename.
3521 ** If successful, *pFd is set to the opened file descriptor and
3522 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3523 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3524 ** value.
3526 ** The directory file descriptor is used for only one thing - to
3527 ** fsync() a directory to make sure file creation and deletion events
3528 ** are flushed to disk. Such fsyncs are not needed on newer
3529 ** journaling filesystems, but are required on older filesystems.
3531 ** This routine can be overridden using the xSetSysCall interface.
3532 ** The ability to override this routine was added in support of the
3533 ** chromium sandbox. Opening a directory is a security risk (we are
3534 ** told) so making it overrideable allows the chromium sandbox to
3535 ** replace this routine with a harmless no-op. To make this routine
3536 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3537 ** *pFd set to a negative number.
3539 ** If SQLITE_OK is returned, the caller is responsible for closing
3540 ** the file descriptor *pFd using close().
3542 static int openDirectory(const char *zFilename, int *pFd){
3543 int ii;
3544 int fd = -1;
3545 char zDirname[MAX_PATHNAME+1];
3547 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3548 for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
3549 if( ii>0 ){
3550 zDirname[ii] = '\0';
3551 }else{
3552 if( zDirname[0]!='/' ) zDirname[0] = '.';
3553 zDirname[1] = 0;
3555 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3556 if( fd>=0 ){
3557 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3559 *pFd = fd;
3560 if( fd>=0 ) return SQLITE_OK;
3561 return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
3565 ** Make sure all writes to a particular file are committed to disk.
3567 ** If dataOnly==0 then both the file itself and its metadata (file
3568 ** size, access time, etc) are synced. If dataOnly!=0 then only the
3569 ** file data is synced.
3571 ** Under Unix, also make sure that the directory entry for the file
3572 ** has been created by fsync-ing the directory that contains the file.
3573 ** If we do not do this and we encounter a power failure, the directory
3574 ** entry for the journal might not exist after we reboot. The next
3575 ** SQLite to access the file will not know that the journal exists (because
3576 ** the directory entry for the journal was never created) and the transaction
3577 ** will not roll back - possibly leading to database corruption.
3579 static int unixSync(sqlite3_file *id, int flags){
3580 int rc;
3581 unixFile *pFile = (unixFile*)id;
3583 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3584 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3586 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3587 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3588 || (flags&0x0F)==SQLITE_SYNC_FULL
3591 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3592 ** line is to test that doing so does not cause any problems.
3594 SimulateDiskfullError( return SQLITE_FULL );
3596 assert( pFile );
3597 OSTRACE(("SYNC %-3d\n", pFile->h));
3598 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3599 SimulateIOError( rc=1 );
3600 if( rc ){
3601 storeLastErrno(pFile, errno);
3602 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
3605 /* Also fsync the directory containing the file if the DIRSYNC flag
3606 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
3607 ** are unable to fsync a directory, so ignore errors on the fsync.
3609 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3610 int dirfd;
3611 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
3612 HAVE_FULLFSYNC, isFullsync));
3613 rc = osOpenDirectory(pFile->zPath, &dirfd);
3614 if( rc==SQLITE_OK ){
3615 full_fsync(dirfd, 0, 0);
3616 robust_close(pFile, dirfd, __LINE__);
3617 }else{
3618 assert( rc==SQLITE_CANTOPEN );
3619 rc = SQLITE_OK;
3621 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
3623 return rc;
3627 ** Truncate an open file to a specified size
3629 static int unixTruncate(sqlite3_file *id, i64 nByte){
3630 unixFile *pFile = (unixFile *)id;
3631 int rc;
3632 assert( pFile );
3633 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
3635 /* If the user has configured a chunk-size for this file, truncate the
3636 ** file so that it consists of an integer number of chunks (i.e. the
3637 ** actual file size after the operation may be larger than the requested
3638 ** size).
3640 if( pFile->szChunk>0 ){
3641 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3644 rc = robust_ftruncate(pFile->h, nByte);
3645 if( rc ){
3646 storeLastErrno(pFile, errno);
3647 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3648 }else{
3649 #ifdef SQLITE_DEBUG
3650 /* If we are doing a normal write to a database file (as opposed to
3651 ** doing a hot-journal rollback or a write to some file other than a
3652 ** normal database file) and we truncate the file to zero length,
3653 ** that effectively updates the change counter. This might happen
3654 ** when restoring a database using the backup API from a zero-length
3655 ** source.
3657 if( pFile->inNormalWrite && nByte==0 ){
3658 pFile->transCntrChng = 1;
3660 #endif
3662 #if SQLITE_MAX_MMAP_SIZE>0
3663 /* If the file was just truncated to a size smaller than the currently
3664 ** mapped region, reduce the effective mapping size as well. SQLite will
3665 ** use read() and write() to access data beyond this point from now on.
3667 if( nByte<pFile->mmapSize ){
3668 pFile->mmapSize = nByte;
3670 #endif
3672 return SQLITE_OK;
3677 ** Determine the current size of a file in bytes
3679 static int unixFileSize(sqlite3_file *id, i64 *pSize){
3680 int rc;
3681 struct stat buf;
3682 assert( id );
3683 rc = osFstat(((unixFile*)id)->h, &buf);
3684 SimulateIOError( rc=1 );
3685 if( rc!=0 ){
3686 storeLastErrno((unixFile*)id, errno);
3687 return SQLITE_IOERR_FSTAT;
3689 *pSize = buf.st_size;
3691 /* When opening a zero-size database, the findInodeInfo() procedure
3692 ** writes a single byte into that file in order to work around a bug
3693 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3694 ** layers, we need to report this file size as zero even though it is
3695 ** really 1. Ticket #3260.
3697 if( *pSize==1 ) *pSize = 0;
3700 return SQLITE_OK;
3703 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
3705 ** Handler for proxy-locking file-control verbs. Defined below in the
3706 ** proxying locking division.
3708 static int proxyFileControl(sqlite3_file*,int,void*);
3709 #endif
3712 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
3713 ** file-control operation. Enlarge the database to nBytes in size
3714 ** (rounded up to the next chunk-size). If the database is already
3715 ** nBytes or larger, this routine is a no-op.
3717 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
3718 if( pFile->szChunk>0 ){
3719 i64 nSize; /* Required file size */
3720 struct stat buf; /* Used to hold return values of fstat() */
3722 if( osFstat(pFile->h, &buf) ){
3723 return SQLITE_IOERR_FSTAT;
3726 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3727 if( nSize>(i64)buf.st_size ){
3729 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
3730 /* The code below is handling the return value of osFallocate()
3731 ** correctly. posix_fallocate() is defined to "returns zero on success,
3732 ** or an error number on failure". See the manpage for details. */
3733 int err;
3735 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3736 }while( err==EINTR );
3737 if( err ) return SQLITE_IOERR_WRITE;
3738 #else
3739 /* If the OS does not have posix_fallocate(), fake it. Write a
3740 ** single byte to the last byte in each block that falls entirely
3741 ** within the extended region. Then, if required, a single byte
3742 ** at offset (nSize-1), to set the size of the file correctly.
3743 ** This is a similar technique to that used by glibc on systems
3744 ** that do not have a real fallocate() call.
3746 int nBlk = buf.st_blksize; /* File-system block size */
3747 int nWrite = 0; /* Number of bytes written by seekAndWrite */
3748 i64 iWrite; /* Next offset to write to */
3750 iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
3751 assert( iWrite>=buf.st_size );
3752 assert( ((iWrite+1)%nBlk)==0 );
3753 for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
3754 if( iWrite>=nSize ) iWrite = nSize - 1;
3755 nWrite = seekAndWrite(pFile, iWrite, "", 1);
3756 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
3758 #endif
3762 #if SQLITE_MAX_MMAP_SIZE>0
3763 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
3764 int rc;
3765 if( pFile->szChunk<=0 ){
3766 if( robust_ftruncate(pFile->h, nByte) ){
3767 storeLastErrno(pFile, errno);
3768 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3772 rc = unixMapfile(pFile, nByte);
3773 return rc;
3775 #endif
3777 return SQLITE_OK;
3781 ** If *pArg is initially negative then this is a query. Set *pArg to
3782 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3784 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3786 static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3787 if( *pArg<0 ){
3788 *pArg = (pFile->ctrlFlags & mask)!=0;
3789 }else if( (*pArg)==0 ){
3790 pFile->ctrlFlags &= ~mask;
3791 }else{
3792 pFile->ctrlFlags |= mask;
3796 /* Forward declaration */
3797 static int unixGetTempname(int nBuf, char *zBuf);
3800 ** Information and control of an open file handle.
3802 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
3803 unixFile *pFile = (unixFile*)id;
3804 switch( op ){
3805 #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
3806 case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: {
3807 int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE);
3808 return rc ? SQLITE_IOERR_BEGIN_ATOMIC : SQLITE_OK;
3810 case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: {
3811 int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE);
3812 return rc ? SQLITE_IOERR_COMMIT_ATOMIC : SQLITE_OK;
3814 case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: {
3815 int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE);
3816 return rc ? SQLITE_IOERR_ROLLBACK_ATOMIC : SQLITE_OK;
3818 #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
3820 case SQLITE_FCNTL_LOCKSTATE: {
3821 *(int*)pArg = pFile->eFileLock;
3822 return SQLITE_OK;
3824 case SQLITE_FCNTL_LAST_ERRNO: {
3825 *(int*)pArg = pFile->lastErrno;
3826 return SQLITE_OK;
3828 case SQLITE_FCNTL_CHUNK_SIZE: {
3829 pFile->szChunk = *(int *)pArg;
3830 return SQLITE_OK;
3832 case SQLITE_FCNTL_SIZE_HINT: {
3833 int rc;
3834 SimulateIOErrorBenign(1);
3835 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3836 SimulateIOErrorBenign(0);
3837 return rc;
3839 case SQLITE_FCNTL_PERSIST_WAL: {
3840 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3841 return SQLITE_OK;
3843 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3844 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
3845 return SQLITE_OK;
3847 case SQLITE_FCNTL_VFSNAME: {
3848 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3849 return SQLITE_OK;
3851 case SQLITE_FCNTL_TEMPFILENAME: {
3852 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
3853 if( zTFile ){
3854 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3855 *(char**)pArg = zTFile;
3857 return SQLITE_OK;
3859 case SQLITE_FCNTL_HAS_MOVED: {
3860 *(int*)pArg = fileHasMoved(pFile);
3861 return SQLITE_OK;
3863 #if SQLITE_MAX_MMAP_SIZE>0
3864 case SQLITE_FCNTL_MMAP_SIZE: {
3865 i64 newLimit = *(i64*)pArg;
3866 int rc = SQLITE_OK;
3867 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3868 newLimit = sqlite3GlobalConfig.mxMmap;
3871 /* The value of newLimit may be eventually cast to (size_t) and passed
3872 ** to mmap(). Restrict its value to 2GB if (size_t) is not at least a
3873 ** 64-bit type. */
3874 if( newLimit>0 && sizeof(size_t)<8 ){
3875 newLimit = (newLimit & 0x7FFFFFFF);
3878 *(i64*)pArg = pFile->mmapSizeMax;
3879 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
3880 pFile->mmapSizeMax = newLimit;
3881 if( pFile->mmapSize>0 ){
3882 unixUnmapfile(pFile);
3883 rc = unixMapfile(pFile, -1);
3886 return rc;
3888 #endif
3889 #ifdef SQLITE_DEBUG
3890 /* The pager calls this method to signal that it has done
3891 ** a rollback and that the database is therefore unchanged and
3892 ** it hence it is OK for the transaction change counter to be
3893 ** unchanged.
3895 case SQLITE_FCNTL_DB_UNCHANGED: {
3896 ((unixFile*)id)->dbUpdate = 0;
3897 return SQLITE_OK;
3899 #endif
3900 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
3901 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
3902 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
3903 return proxyFileControl(id,op,pArg);
3905 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
3907 return SQLITE_NOTFOUND;
3911 ** If pFd->sectorSize is non-zero when this function is called, it is a
3912 ** no-op. Otherwise, the values of pFd->sectorSize and
3913 ** pFd->deviceCharacteristics are set according to the file-system
3914 ** characteristics.
3916 ** There are two versions of this function. One for QNX and one for all
3917 ** other systems.
3919 #ifndef __QNXNTO__
3920 static void setDeviceCharacteristics(unixFile *pFd){
3921 assert( pFd->deviceCharacteristics==0 || pFd->sectorSize!=0 );
3922 if( pFd->sectorSize==0 ){
3923 #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
3924 int res;
3925 u32 f = 0;
3927 /* Check for support for F2FS atomic batch writes. */
3928 res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES, &f);
3929 if( res==0 && (f & F2FS_FEATURE_ATOMIC_WRITE) ){
3930 pFd->deviceCharacteristics = SQLITE_IOCAP_BATCH_ATOMIC;
3932 #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
3934 /* Set the POWERSAFE_OVERWRITE flag if requested. */
3935 if( pFd->ctrlFlags & UNIXFILE_PSOW ){
3936 pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
3939 pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3942 #else
3943 #include <sys/dcmd_blk.h>
3944 #include <sys/statvfs.h>
3945 static void setDeviceCharacteristics(unixFile *pFile){
3946 if( pFile->sectorSize == 0 ){
3947 struct statvfs fsInfo;
3949 /* Set defaults for non-supported filesystems */
3950 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3951 pFile->deviceCharacteristics = 0;
3952 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3953 return pFile->sectorSize;
3956 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3957 pFile->sectorSize = fsInfo.f_bsize;
3958 pFile->deviceCharacteristics =
3959 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3960 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3961 ** the write succeeds */
3962 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3963 ** so it is ordered */
3965 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3966 pFile->sectorSize = fsInfo.f_bsize;
3967 pFile->deviceCharacteristics =
3968 /* etfs cluster size writes are atomic */
3969 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3970 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3971 ** the write succeeds */
3972 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3973 ** so it is ordered */
3975 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3976 pFile->sectorSize = fsInfo.f_bsize;
3977 pFile->deviceCharacteristics =
3978 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3979 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3980 ** the write succeeds */
3981 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3982 ** so it is ordered */
3984 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3985 pFile->sectorSize = fsInfo.f_bsize;
3986 pFile->deviceCharacteristics =
3987 /* full bitset of atomics from max sector size and smaller */
3988 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3989 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3990 ** so it is ordered */
3992 }else if( strstr(fsInfo.f_basetype, "dos") ){
3993 pFile->sectorSize = fsInfo.f_bsize;
3994 pFile->deviceCharacteristics =
3995 /* full bitset of atomics from max sector size and smaller */
3996 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3997 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3998 ** so it is ordered */
4000 }else{
4001 pFile->deviceCharacteristics =
4002 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
4003 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4004 ** the write succeeds */
4008 /* Last chance verification. If the sector size isn't a multiple of 512
4009 ** then it isn't valid.*/
4010 if( pFile->sectorSize % 512 != 0 ){
4011 pFile->deviceCharacteristics = 0;
4012 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4015 #endif
4018 ** Return the sector size in bytes of the underlying block device for
4019 ** the specified file. This is almost always 512 bytes, but may be
4020 ** larger for some devices.
4022 ** SQLite code assumes this function cannot fail. It also assumes that
4023 ** if two files are created in the same file-system directory (i.e.
4024 ** a database and its journal file) that the sector size will be the
4025 ** same for both.
4027 static int unixSectorSize(sqlite3_file *id){
4028 unixFile *pFd = (unixFile*)id;
4029 setDeviceCharacteristics(pFd);
4030 return pFd->sectorSize;
4034 ** Return the device characteristics for the file.
4036 ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
4037 ** However, that choice is controversial since technically the underlying
4038 ** file system does not always provide powersafe overwrites. (In other
4039 ** words, after a power-loss event, parts of the file that were never
4040 ** written might end up being altered.) However, non-PSOW behavior is very,
4041 ** very rare. And asserting PSOW makes a large reduction in the amount
4042 ** of required I/O for journaling, since a lot of padding is eliminated.
4043 ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
4044 ** available to turn it off and URI query parameter available to turn it off.
4046 static int unixDeviceCharacteristics(sqlite3_file *id){
4047 unixFile *pFd = (unixFile*)id;
4048 setDeviceCharacteristics(pFd);
4049 return pFd->deviceCharacteristics;
4052 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
4055 ** Return the system page size.
4057 ** This function should not be called directly by other code in this file.
4058 ** Instead, it should be called via macro osGetpagesize().
4060 static int unixGetpagesize(void){
4061 #if OS_VXWORKS
4062 return 1024;
4063 #elif defined(_BSD_SOURCE)
4064 return getpagesize();
4065 #else
4066 return (int)sysconf(_SC_PAGESIZE);
4067 #endif
4070 #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
4072 #ifndef SQLITE_OMIT_WAL
4075 ** Object used to represent an shared memory buffer.
4077 ** When multiple threads all reference the same wal-index, each thread
4078 ** has its own unixShm object, but they all point to a single instance
4079 ** of this unixShmNode object. In other words, each wal-index is opened
4080 ** only once per process.
4082 ** Each unixShmNode object is connected to a single unixInodeInfo object.
4083 ** We could coalesce this object into unixInodeInfo, but that would mean
4084 ** every open file that does not use shared memory (in other words, most
4085 ** open files) would have to carry around this extra information. So
4086 ** the unixInodeInfo object contains a pointer to this unixShmNode object
4087 ** and the unixShmNode object is created only when needed.
4089 ** unixMutexHeld() must be true when creating or destroying
4090 ** this object or while reading or writing the following fields:
4092 ** nRef
4094 ** The following fields are read-only after the object is created:
4096 ** fid
4097 ** zFilename
4099 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
4100 ** unixMutexHeld() is true when reading or writing any other field
4101 ** in this structure.
4103 struct unixShmNode {
4104 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
4105 sqlite3_mutex *mutex; /* Mutex to access this object */
4106 char *zFilename; /* Name of the mmapped file */
4107 int h; /* Open file descriptor */
4108 int szRegion; /* Size of shared-memory regions */
4109 u16 nRegion; /* Size of array apRegion */
4110 u8 isReadonly; /* True if read-only */
4111 u8 isUnlocked; /* True if no DMS lock held */
4112 char **apRegion; /* Array of mapped shared-memory regions */
4113 int nRef; /* Number of unixShm objects pointing to this */
4114 unixShm *pFirst; /* All unixShm objects pointing to this */
4115 #ifdef SQLITE_DEBUG
4116 u8 exclMask; /* Mask of exclusive locks held */
4117 u8 sharedMask; /* Mask of shared locks held */
4118 u8 nextShmId; /* Next available unixShm.id value */
4119 #endif
4123 ** Structure used internally by this VFS to record the state of an
4124 ** open shared memory connection.
4126 ** The following fields are initialized when this object is created and
4127 ** are read-only thereafter:
4129 ** unixShm.pFile
4130 ** unixShm.id
4132 ** All other fields are read/write. The unixShm.pFile->mutex must be held
4133 ** while accessing any read/write fields.
4135 struct unixShm {
4136 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4137 unixShm *pNext; /* Next unixShm with the same unixShmNode */
4138 u8 hasMutex; /* True if holding the unixShmNode mutex */
4139 u8 id; /* Id of this connection within its unixShmNode */
4140 u16 sharedMask; /* Mask of shared locks held */
4141 u16 exclMask; /* Mask of exclusive locks held */
4145 ** Constants used for locking
4147 #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
4148 #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
4151 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
4153 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4154 ** otherwise.
4156 static int unixShmSystemLock(
4157 unixFile *pFile, /* Open connection to the WAL file */
4158 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
4159 int ofst, /* First byte of the locking range */
4160 int n /* Number of bytes to lock */
4162 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4163 struct flock f; /* The posix advisory locking structure */
4164 int rc = SQLITE_OK; /* Result code form fcntl() */
4166 /* Access to the unixShmNode object is serialized by the caller */
4167 pShmNode = pFile->pInode->pShmNode;
4168 assert( pShmNode->nRef==0 || sqlite3_mutex_held(pShmNode->mutex) );
4170 /* Shared locks never span more than one byte */
4171 assert( n==1 || lockType!=F_RDLCK );
4173 /* Locks are within range */
4174 assert( n>=1 && n<=SQLITE_SHM_NLOCK );
4176 if( pShmNode->h>=0 ){
4177 /* Initialize the locking parameters */
4178 memset(&f, 0, sizeof(f));
4179 f.l_type = lockType;
4180 f.l_whence = SEEK_SET;
4181 f.l_start = ofst;
4182 f.l_len = n;
4184 rc = osFcntl(pShmNode->h, F_SETLK, &f);
4185 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4188 /* Update the global lock state and do debug tracing */
4189 #ifdef SQLITE_DEBUG
4190 { u16 mask;
4191 OSTRACE(("SHM-LOCK "));
4192 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
4193 if( rc==SQLITE_OK ){
4194 if( lockType==F_UNLCK ){
4195 OSTRACE(("unlock %d ok", ofst));
4196 pShmNode->exclMask &= ~mask;
4197 pShmNode->sharedMask &= ~mask;
4198 }else if( lockType==F_RDLCK ){
4199 OSTRACE(("read-lock %d ok", ofst));
4200 pShmNode->exclMask &= ~mask;
4201 pShmNode->sharedMask |= mask;
4202 }else{
4203 assert( lockType==F_WRLCK );
4204 OSTRACE(("write-lock %d ok", ofst));
4205 pShmNode->exclMask |= mask;
4206 pShmNode->sharedMask &= ~mask;
4208 }else{
4209 if( lockType==F_UNLCK ){
4210 OSTRACE(("unlock %d failed", ofst));
4211 }else if( lockType==F_RDLCK ){
4212 OSTRACE(("read-lock failed"));
4213 }else{
4214 assert( lockType==F_WRLCK );
4215 OSTRACE(("write-lock %d failed", ofst));
4218 OSTRACE((" - afterwards %03x,%03x\n",
4219 pShmNode->sharedMask, pShmNode->exclMask));
4221 #endif
4223 return rc;
4227 ** Return the minimum number of 32KB shm regions that should be mapped at
4228 ** a time, assuming that each mapping must be an integer multiple of the
4229 ** current system page-size.
4231 ** Usually, this is 1. The exception seems to be systems that are configured
4232 ** to use 64KB pages - in this case each mapping must cover at least two
4233 ** shm regions.
4235 static int unixShmRegionPerMap(void){
4236 int shmsz = 32*1024; /* SHM region size */
4237 int pgsz = osGetpagesize(); /* System page size */
4238 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4239 if( pgsz<shmsz ) return 1;
4240 return pgsz/shmsz;
4244 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
4246 ** This is not a VFS shared-memory method; it is a utility function called
4247 ** by VFS shared-memory methods.
4249 static void unixShmPurge(unixFile *pFd){
4250 unixShmNode *p = pFd->pInode->pShmNode;
4251 assert( unixMutexHeld() );
4252 if( p && ALWAYS(p->nRef==0) ){
4253 int nShmPerMap = unixShmRegionPerMap();
4254 int i;
4255 assert( p->pInode==pFd->pInode );
4256 sqlite3_mutex_free(p->mutex);
4257 for(i=0; i<p->nRegion; i+=nShmPerMap){
4258 if( p->h>=0 ){
4259 osMunmap(p->apRegion[i], p->szRegion);
4260 }else{
4261 sqlite3_free(p->apRegion[i]);
4264 sqlite3_free(p->apRegion);
4265 if( p->h>=0 ){
4266 robust_close(pFd, p->h, __LINE__);
4267 p->h = -1;
4269 p->pInode->pShmNode = 0;
4270 sqlite3_free(p);
4275 ** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
4276 ** take it now. Return SQLITE_OK if successful, or an SQLite error
4277 ** code otherwise.
4279 ** If the DMS cannot be locked because this is a readonly_shm=1
4280 ** connection and no other process already holds a lock, return
4281 ** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
4283 static int unixLockSharedMemory(unixFile *pDbFd, unixShmNode *pShmNode){
4284 struct flock lock;
4285 int rc = SQLITE_OK;
4287 /* Use F_GETLK to determine the locks other processes are holding
4288 ** on the DMS byte. If it indicates that another process is holding
4289 ** a SHARED lock, then this process may also take a SHARED lock
4290 ** and proceed with opening the *-shm file.
4292 ** Or, if no other process is holding any lock, then this process
4293 ** is the first to open it. In this case take an EXCLUSIVE lock on the
4294 ** DMS byte and truncate the *-shm file to zero bytes in size. Then
4295 ** downgrade to a SHARED lock on the DMS byte.
4297 ** If another process is holding an EXCLUSIVE lock on the DMS byte,
4298 ** return SQLITE_BUSY to the caller (it will try again). An earlier
4299 ** version of this code attempted the SHARED lock at this point. But
4300 ** this introduced a subtle race condition: if the process holding
4301 ** EXCLUSIVE failed just before truncating the *-shm file, then this
4302 ** process might open and use the *-shm file without truncating it.
4303 ** And if the *-shm file has been corrupted by a power failure or
4304 ** system crash, the database itself may also become corrupt. */
4305 lock.l_whence = SEEK_SET;
4306 lock.l_start = UNIX_SHM_DMS;
4307 lock.l_len = 1;
4308 lock.l_type = F_WRLCK;
4309 if( osFcntl(pShmNode->h, F_GETLK, &lock)!=0 ) {
4310 rc = SQLITE_IOERR_LOCK;
4311 }else if( lock.l_type==F_UNLCK ){
4312 if( pShmNode->isReadonly ){
4313 pShmNode->isUnlocked = 1;
4314 rc = SQLITE_READONLY_CANTINIT;
4315 }else{
4316 rc = unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1);
4317 if( rc==SQLITE_OK && robust_ftruncate(pShmNode->h, 0) ){
4318 rc = unixLogError(SQLITE_IOERR_SHMOPEN,"ftruncate",pShmNode->zFilename);
4321 }else if( lock.l_type==F_WRLCK ){
4322 rc = SQLITE_BUSY;
4325 if( rc==SQLITE_OK ){
4326 assert( lock.l_type==F_UNLCK || lock.l_type==F_RDLCK );
4327 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
4329 return rc;
4333 ** Open a shared-memory area associated with open database file pDbFd.
4334 ** This particular implementation uses mmapped files.
4336 ** The file used to implement shared-memory is in the same directory
4337 ** as the open database file and has the same name as the open database
4338 ** file with the "-shm" suffix added. For example, if the database file
4339 ** is "/home/user1/config.db" then the file that is created and mmapped
4340 ** for shared memory will be called "/home/user1/config.db-shm".
4342 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
4343 ** some other tmpfs mount. But if a file in a different directory
4344 ** from the database file is used, then differing access permissions
4345 ** or a chroot() might cause two different processes on the same
4346 ** database to end up using different files for shared memory -
4347 ** meaning that their memory would not really be shared - resulting
4348 ** in database corruption. Nevertheless, this tmpfs file usage
4349 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4350 ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4351 ** option results in an incompatible build of SQLite; builds of SQLite
4352 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4353 ** same database file at the same time, database corruption will likely
4354 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4355 ** "unsupported" and may go away in a future SQLite release.
4357 ** When opening a new shared-memory file, if no other instances of that
4358 ** file are currently open, in this process or in other processes, then
4359 ** the file must be truncated to zero length or have its header cleared.
4361 ** If the original database file (pDbFd) is using the "unix-excl" VFS
4362 ** that means that an exclusive lock is held on the database file and
4363 ** that no other processes are able to read or write the database. In
4364 ** that case, we do not really need shared memory. No shared memory
4365 ** file is created. The shared memory will be simulated with heap memory.
4367 static int unixOpenSharedMemory(unixFile *pDbFd){
4368 struct unixShm *p = 0; /* The connection to be opened */
4369 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4370 int rc = SQLITE_OK; /* Result code */
4371 unixInodeInfo *pInode; /* The inode of fd */
4372 char *zShm; /* Name of the file used for SHM */
4373 int nShmFilename; /* Size of the SHM filename in bytes */
4375 /* Allocate space for the new unixShm object. */
4376 p = sqlite3_malloc64( sizeof(*p) );
4377 if( p==0 ) return SQLITE_NOMEM_BKPT;
4378 memset(p, 0, sizeof(*p));
4379 assert( pDbFd->pShm==0 );
4381 /* Check to see if a unixShmNode object already exists. Reuse an existing
4382 ** one if present. Create a new one if necessary.
4384 unixEnterMutex();
4385 pInode = pDbFd->pInode;
4386 pShmNode = pInode->pShmNode;
4387 if( pShmNode==0 ){
4388 struct stat sStat; /* fstat() info for database file */
4389 #ifndef SQLITE_SHM_DIRECTORY
4390 const char *zBasePath = pDbFd->zPath;
4391 #endif
4393 /* Call fstat() to figure out the permissions on the database file. If
4394 ** a new *-shm file is created, an attempt will be made to create it
4395 ** with the same permissions.
4397 if( osFstat(pDbFd->h, &sStat) ){
4398 rc = SQLITE_IOERR_FSTAT;
4399 goto shm_open_err;
4402 #ifdef SQLITE_SHM_DIRECTORY
4403 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
4404 #else
4405 nShmFilename = 6 + (int)strlen(zBasePath);
4406 #endif
4407 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
4408 if( pShmNode==0 ){
4409 rc = SQLITE_NOMEM_BKPT;
4410 goto shm_open_err;
4412 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
4413 zShm = pShmNode->zFilename = (char*)&pShmNode[1];
4414 #ifdef SQLITE_SHM_DIRECTORY
4415 sqlite3_snprintf(nShmFilename, zShm,
4416 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4417 (u32)sStat.st_ino, (u32)sStat.st_dev);
4418 #else
4419 sqlite3_snprintf(nShmFilename, zShm, "%s-shm", zBasePath);
4420 sqlite3FileSuffix3(pDbFd->zPath, zShm);
4421 #endif
4422 pShmNode->h = -1;
4423 pDbFd->pInode->pShmNode = pShmNode;
4424 pShmNode->pInode = pDbFd->pInode;
4425 if( sqlite3GlobalConfig.bCoreMutex ){
4426 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4427 if( pShmNode->mutex==0 ){
4428 rc = SQLITE_NOMEM_BKPT;
4429 goto shm_open_err;
4433 if( pInode->bProcessLock==0 ){
4434 if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
4435 pShmNode->h = robust_open(zShm, O_RDWR|O_CREAT, (sStat.st_mode&0777));
4437 if( pShmNode->h<0 ){
4438 pShmNode->h = robust_open(zShm, O_RDONLY, (sStat.st_mode&0777));
4439 if( pShmNode->h<0 ){
4440 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShm);
4441 goto shm_open_err;
4443 pShmNode->isReadonly = 1;
4446 /* If this process is running as root, make sure that the SHM file
4447 ** is owned by the same user that owns the original database. Otherwise,
4448 ** the original owner will not be able to connect.
4450 robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
4452 rc = unixLockSharedMemory(pDbFd, pShmNode);
4453 if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
4457 /* Make the new connection a child of the unixShmNode */
4458 p->pShmNode = pShmNode;
4459 #ifdef SQLITE_DEBUG
4460 p->id = pShmNode->nextShmId++;
4461 #endif
4462 pShmNode->nRef++;
4463 pDbFd->pShm = p;
4464 unixLeaveMutex();
4466 /* The reference count on pShmNode has already been incremented under
4467 ** the cover of the unixEnterMutex() mutex and the pointer from the
4468 ** new (struct unixShm) object to the pShmNode has been set. All that is
4469 ** left to do is to link the new object into the linked list starting
4470 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4471 ** mutex.
4473 sqlite3_mutex_enter(pShmNode->mutex);
4474 p->pNext = pShmNode->pFirst;
4475 pShmNode->pFirst = p;
4476 sqlite3_mutex_leave(pShmNode->mutex);
4477 return rc;
4479 /* Jump here on any error */
4480 shm_open_err:
4481 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
4482 sqlite3_free(p);
4483 unixLeaveMutex();
4484 return rc;
4488 ** This function is called to obtain a pointer to region iRegion of the
4489 ** shared-memory associated with the database file fd. Shared-memory regions
4490 ** are numbered starting from zero. Each shared-memory region is szRegion
4491 ** bytes in size.
4493 ** If an error occurs, an error code is returned and *pp is set to NULL.
4495 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4496 ** region has not been allocated (by any client, including one running in a
4497 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4498 ** bExtend is non-zero and the requested shared-memory region has not yet
4499 ** been allocated, it is allocated by this function.
4501 ** If the shared-memory region has already been allocated or is allocated by
4502 ** this call as described above, then it is mapped into this processes
4503 ** address space (if it is not already), *pp is set to point to the mapped
4504 ** memory and SQLITE_OK returned.
4506 static int unixShmMap(
4507 sqlite3_file *fd, /* Handle open on database file */
4508 int iRegion, /* Region to retrieve */
4509 int szRegion, /* Size of regions */
4510 int bExtend, /* True to extend file if necessary */
4511 void volatile **pp /* OUT: Mapped memory */
4513 unixFile *pDbFd = (unixFile*)fd;
4514 unixShm *p;
4515 unixShmNode *pShmNode;
4516 int rc = SQLITE_OK;
4517 int nShmPerMap = unixShmRegionPerMap();
4518 int nReqRegion;
4520 /* If the shared-memory file has not yet been opened, open it now. */
4521 if( pDbFd->pShm==0 ){
4522 rc = unixOpenSharedMemory(pDbFd);
4523 if( rc!=SQLITE_OK ) return rc;
4526 p = pDbFd->pShm;
4527 pShmNode = p->pShmNode;
4528 sqlite3_mutex_enter(pShmNode->mutex);
4529 if( pShmNode->isUnlocked ){
4530 rc = unixLockSharedMemory(pDbFd, pShmNode);
4531 if( rc!=SQLITE_OK ) goto shmpage_out;
4532 pShmNode->isUnlocked = 0;
4534 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
4535 assert( pShmNode->pInode==pDbFd->pInode );
4536 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4537 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
4539 /* Minimum number of regions required to be mapped. */
4540 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4542 if( pShmNode->nRegion<nReqRegion ){
4543 char **apNew; /* New apRegion[] array */
4544 int nByte = nReqRegion*szRegion; /* Minimum required file size */
4545 struct stat sStat; /* Used by fstat() */
4547 pShmNode->szRegion = szRegion;
4549 if( pShmNode->h>=0 ){
4550 /* The requested region is not mapped into this processes address space.
4551 ** Check to see if it has been allocated (i.e. if the wal-index file is
4552 ** large enough to contain the requested region).
4554 if( osFstat(pShmNode->h, &sStat) ){
4555 rc = SQLITE_IOERR_SHMSIZE;
4556 goto shmpage_out;
4559 if( sStat.st_size<nByte ){
4560 /* The requested memory region does not exist. If bExtend is set to
4561 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
4563 if( !bExtend ){
4564 goto shmpage_out;
4567 /* Alternatively, if bExtend is true, extend the file. Do this by
4568 ** writing a single byte to the end of each (OS) page being
4569 ** allocated or extended. Technically, we need only write to the
4570 ** last page in order to extend the file. But writing to all new
4571 ** pages forces the OS to allocate them immediately, which reduces
4572 ** the chances of SIGBUS while accessing the mapped region later on.
4574 else{
4575 static const int pgsz = 4096;
4576 int iPg;
4578 /* Write to the last byte of each newly allocated or extended page */
4579 assert( (nByte % pgsz)==0 );
4580 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
4581 int x = 0;
4582 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
4583 const char *zFile = pShmNode->zFilename;
4584 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4585 goto shmpage_out;
4592 /* Map the requested memory region into this processes address space. */
4593 apNew = (char **)sqlite3_realloc(
4594 pShmNode->apRegion, nReqRegion*sizeof(char *)
4596 if( !apNew ){
4597 rc = SQLITE_IOERR_NOMEM_BKPT;
4598 goto shmpage_out;
4600 pShmNode->apRegion = apNew;
4601 while( pShmNode->nRegion<nReqRegion ){
4602 int nMap = szRegion*nShmPerMap;
4603 int i;
4604 void *pMem;
4605 if( pShmNode->h>=0 ){
4606 pMem = osMmap(0, nMap,
4607 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
4608 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
4610 if( pMem==MAP_FAILED ){
4611 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
4612 goto shmpage_out;
4614 }else{
4615 pMem = sqlite3_malloc64(szRegion);
4616 if( pMem==0 ){
4617 rc = SQLITE_NOMEM_BKPT;
4618 goto shmpage_out;
4620 memset(pMem, 0, szRegion);
4623 for(i=0; i<nShmPerMap; i++){
4624 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4626 pShmNode->nRegion += nShmPerMap;
4630 shmpage_out:
4631 if( pShmNode->nRegion>iRegion ){
4632 *pp = pShmNode->apRegion[iRegion];
4633 }else{
4634 *pp = 0;
4636 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
4637 sqlite3_mutex_leave(pShmNode->mutex);
4638 return rc;
4642 ** Change the lock state for a shared-memory segment.
4644 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4645 ** different here than in posix. In xShmLock(), one can go from unlocked
4646 ** to shared and back or from unlocked to exclusive and back. But one may
4647 ** not go from shared to exclusive or from exclusive to shared.
4649 static int unixShmLock(
4650 sqlite3_file *fd, /* Database file holding the shared memory */
4651 int ofst, /* First lock to acquire or release */
4652 int n, /* Number of locks to acquire or release */
4653 int flags /* What to do with the lock */
4655 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4656 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4657 unixShm *pX; /* For looping over all siblings */
4658 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4659 int rc = SQLITE_OK; /* Result code */
4660 u16 mask; /* Mask of locks to take or release */
4662 assert( pShmNode==pDbFd->pInode->pShmNode );
4663 assert( pShmNode->pInode==pDbFd->pInode );
4664 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
4665 assert( n>=1 );
4666 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4667 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4668 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4669 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4670 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
4671 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4672 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
4674 mask = (1<<(ofst+n)) - (1<<ofst);
4675 assert( n>1 || mask==(1<<ofst) );
4676 sqlite3_mutex_enter(pShmNode->mutex);
4677 if( flags & SQLITE_SHM_UNLOCK ){
4678 u16 allMask = 0; /* Mask of locks held by siblings */
4680 /* See if any siblings hold this same lock */
4681 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4682 if( pX==p ) continue;
4683 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4684 allMask |= pX->sharedMask;
4687 /* Unlock the system-level locks */
4688 if( (mask & allMask)==0 ){
4689 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
4690 }else{
4691 rc = SQLITE_OK;
4694 /* Undo the local locks */
4695 if( rc==SQLITE_OK ){
4696 p->exclMask &= ~mask;
4697 p->sharedMask &= ~mask;
4699 }else if( flags & SQLITE_SHM_SHARED ){
4700 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4702 /* Find out which shared locks are already held by sibling connections.
4703 ** If any sibling already holds an exclusive lock, go ahead and return
4704 ** SQLITE_BUSY.
4706 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4707 if( (pX->exclMask & mask)!=0 ){
4708 rc = SQLITE_BUSY;
4709 break;
4711 allShared |= pX->sharedMask;
4714 /* Get shared locks at the system level, if necessary */
4715 if( rc==SQLITE_OK ){
4716 if( (allShared & mask)==0 ){
4717 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
4718 }else{
4719 rc = SQLITE_OK;
4723 /* Get the local shared locks */
4724 if( rc==SQLITE_OK ){
4725 p->sharedMask |= mask;
4727 }else{
4728 /* Make sure no sibling connections hold locks that will block this
4729 ** lock. If any do, return SQLITE_BUSY right away.
4731 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4732 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4733 rc = SQLITE_BUSY;
4734 break;
4738 /* Get the exclusive locks at the system level. Then if successful
4739 ** also mark the local connection as being locked.
4741 if( rc==SQLITE_OK ){
4742 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
4743 if( rc==SQLITE_OK ){
4744 assert( (p->sharedMask & mask)==0 );
4745 p->exclMask |= mask;
4749 sqlite3_mutex_leave(pShmNode->mutex);
4750 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4751 p->id, osGetpid(0), p->sharedMask, p->exclMask));
4752 return rc;
4756 ** Implement a memory barrier or memory fence on shared memory.
4758 ** All loads and stores begun before the barrier must complete before
4759 ** any load or store begun after the barrier.
4761 static void unixShmBarrier(
4762 sqlite3_file *fd /* Database file holding the shared memory */
4764 UNUSED_PARAMETER(fd);
4765 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
4766 unixEnterMutex(); /* Also mutex, for redundancy */
4767 unixLeaveMutex();
4771 ** Close a connection to shared-memory. Delete the underlying
4772 ** storage if deleteFlag is true.
4774 ** If there is no shared memory associated with the connection then this
4775 ** routine is a harmless no-op.
4777 static int unixShmUnmap(
4778 sqlite3_file *fd, /* The underlying database file */
4779 int deleteFlag /* Delete shared-memory if true */
4781 unixShm *p; /* The connection to be closed */
4782 unixShmNode *pShmNode; /* The underlying shared-memory file */
4783 unixShm **pp; /* For looping over sibling connections */
4784 unixFile *pDbFd; /* The underlying database file */
4786 pDbFd = (unixFile*)fd;
4787 p = pDbFd->pShm;
4788 if( p==0 ) return SQLITE_OK;
4789 pShmNode = p->pShmNode;
4791 assert( pShmNode==pDbFd->pInode->pShmNode );
4792 assert( pShmNode->pInode==pDbFd->pInode );
4794 /* Remove connection p from the set of connections associated
4795 ** with pShmNode */
4796 sqlite3_mutex_enter(pShmNode->mutex);
4797 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4798 *pp = p->pNext;
4800 /* Free the connection p */
4801 sqlite3_free(p);
4802 pDbFd->pShm = 0;
4803 sqlite3_mutex_leave(pShmNode->mutex);
4805 /* If pShmNode->nRef has reached 0, then close the underlying
4806 ** shared-memory file, too */
4807 unixEnterMutex();
4808 assert( pShmNode->nRef>0 );
4809 pShmNode->nRef--;
4810 if( pShmNode->nRef==0 ){
4811 if( deleteFlag && pShmNode->h>=0 ){
4812 osUnlink(pShmNode->zFilename);
4814 unixShmPurge(pDbFd);
4816 unixLeaveMutex();
4818 return SQLITE_OK;
4822 #else
4823 # define unixShmMap 0
4824 # define unixShmLock 0
4825 # define unixShmBarrier 0
4826 # define unixShmUnmap 0
4827 #endif /* #ifndef SQLITE_OMIT_WAL */
4829 #if SQLITE_MAX_MMAP_SIZE>0
4831 ** If it is currently memory mapped, unmap file pFd.
4833 static void unixUnmapfile(unixFile *pFd){
4834 assert( pFd->nFetchOut==0 );
4835 if( pFd->pMapRegion ){
4836 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
4837 pFd->pMapRegion = 0;
4838 pFd->mmapSize = 0;
4839 pFd->mmapSizeActual = 0;
4844 ** Attempt to set the size of the memory mapping maintained by file
4845 ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4847 ** If successful, this function sets the following variables:
4849 ** unixFile.pMapRegion
4850 ** unixFile.mmapSize
4851 ** unixFile.mmapSizeActual
4853 ** If unsuccessful, an error message is logged via sqlite3_log() and
4854 ** the three variables above are zeroed. In this case SQLite should
4855 ** continue accessing the database using the xRead() and xWrite()
4856 ** methods.
4858 static void unixRemapfile(
4859 unixFile *pFd, /* File descriptor object */
4860 i64 nNew /* Required mapping size */
4862 const char *zErr = "mmap";
4863 int h = pFd->h; /* File descriptor open on db file */
4864 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
4865 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
4866 u8 *pNew = 0; /* Location of new mapping */
4867 int flags = PROT_READ; /* Flags to pass to mmap() */
4869 assert( pFd->nFetchOut==0 );
4870 assert( nNew>pFd->mmapSize );
4871 assert( nNew<=pFd->mmapSizeMax );
4872 assert( nNew>0 );
4873 assert( pFd->mmapSizeActual>=pFd->mmapSize );
4874 assert( MAP_FAILED!=0 );
4876 #ifdef SQLITE_MMAP_READWRITE
4877 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
4878 #endif
4880 if( pOrig ){
4881 #if HAVE_MREMAP
4882 i64 nReuse = pFd->mmapSize;
4883 #else
4884 const int szSyspage = osGetpagesize();
4885 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
4886 #endif
4887 u8 *pReq = &pOrig[nReuse];
4889 /* Unmap any pages of the existing mapping that cannot be reused. */
4890 if( nReuse!=nOrig ){
4891 osMunmap(pReq, nOrig-nReuse);
4894 #if HAVE_MREMAP
4895 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
4896 zErr = "mremap";
4897 #else
4898 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4899 if( pNew!=MAP_FAILED ){
4900 if( pNew!=pReq ){
4901 osMunmap(pNew, nNew - nReuse);
4902 pNew = 0;
4903 }else{
4904 pNew = pOrig;
4907 #endif
4909 /* The attempt to extend the existing mapping failed. Free it. */
4910 if( pNew==MAP_FAILED || pNew==0 ){
4911 osMunmap(pOrig, nReuse);
4915 /* If pNew is still NULL, try to create an entirely new mapping. */
4916 if( pNew==0 ){
4917 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
4920 if( pNew==MAP_FAILED ){
4921 pNew = 0;
4922 nNew = 0;
4923 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4925 /* If the mmap() above failed, assume that all subsequent mmap() calls
4926 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4927 ** in this case. */
4928 pFd->mmapSizeMax = 0;
4930 pFd->pMapRegion = (void *)pNew;
4931 pFd->mmapSize = pFd->mmapSizeActual = nNew;
4935 ** Memory map or remap the file opened by file-descriptor pFd (if the file
4936 ** is already mapped, the existing mapping is replaced by the new). Or, if
4937 ** there already exists a mapping for this file, and there are still
4938 ** outstanding xFetch() references to it, this function is a no-op.
4940 ** If parameter nByte is non-negative, then it is the requested size of
4941 ** the mapping to create. Otherwise, if nByte is less than zero, then the
4942 ** requested size is the size of the file on disk. The actual size of the
4943 ** created mapping is either the requested size or the value configured
4944 ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
4946 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
4947 ** recreated as a result of outstanding references) or an SQLite error
4948 ** code otherwise.
4950 static int unixMapfile(unixFile *pFd, i64 nMap){
4951 assert( nMap>=0 || pFd->nFetchOut==0 );
4952 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
4953 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4955 if( nMap<0 ){
4956 struct stat statbuf; /* Low-level file information */
4957 if( osFstat(pFd->h, &statbuf) ){
4958 return SQLITE_IOERR_FSTAT;
4960 nMap = statbuf.st_size;
4962 if( nMap>pFd->mmapSizeMax ){
4963 nMap = pFd->mmapSizeMax;
4966 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
4967 if( nMap!=pFd->mmapSize ){
4968 unixRemapfile(pFd, nMap);
4971 return SQLITE_OK;
4973 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
4976 ** If possible, return a pointer to a mapping of file fd starting at offset
4977 ** iOff. The mapping must be valid for at least nAmt bytes.
4979 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4980 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4981 ** Finally, if an error does occur, return an SQLite error code. The final
4982 ** value of *pp is undefined in this case.
4984 ** If this function does return a pointer, the caller must eventually
4985 ** release the reference by calling unixUnfetch().
4987 static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
4988 #if SQLITE_MAX_MMAP_SIZE>0
4989 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
4990 #endif
4991 *pp = 0;
4993 #if SQLITE_MAX_MMAP_SIZE>0
4994 if( pFd->mmapSizeMax>0 ){
4995 if( pFd->pMapRegion==0 ){
4996 int rc = unixMapfile(pFd, -1);
4997 if( rc!=SQLITE_OK ) return rc;
4999 if( pFd->mmapSize >= iOff+nAmt ){
5000 *pp = &((u8 *)pFd->pMapRegion)[iOff];
5001 pFd->nFetchOut++;
5004 #endif
5005 return SQLITE_OK;
5009 ** If the third argument is non-NULL, then this function releases a
5010 ** reference obtained by an earlier call to unixFetch(). The second
5011 ** argument passed to this function must be the same as the corresponding
5012 ** argument that was passed to the unixFetch() invocation.
5014 ** Or, if the third argument is NULL, then this function is being called
5015 ** to inform the VFS layer that, according to POSIX, any existing mapping
5016 ** may now be invalid and should be unmapped.
5018 static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
5019 #if SQLITE_MAX_MMAP_SIZE>0
5020 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
5021 UNUSED_PARAMETER(iOff);
5023 /* If p==0 (unmap the entire file) then there must be no outstanding
5024 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
5025 ** then there must be at least one outstanding. */
5026 assert( (p==0)==(pFd->nFetchOut==0) );
5028 /* If p!=0, it must match the iOff value. */
5029 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
5031 if( p ){
5032 pFd->nFetchOut--;
5033 }else{
5034 unixUnmapfile(pFd);
5037 assert( pFd->nFetchOut>=0 );
5038 #else
5039 UNUSED_PARAMETER(fd);
5040 UNUSED_PARAMETER(p);
5041 UNUSED_PARAMETER(iOff);
5042 #endif
5043 return SQLITE_OK;
5047 ** Here ends the implementation of all sqlite3_file methods.
5049 ********************** End sqlite3_file Methods *******************************
5050 ******************************************************************************/
5053 ** This division contains definitions of sqlite3_io_methods objects that
5054 ** implement various file locking strategies. It also contains definitions
5055 ** of "finder" functions. A finder-function is used to locate the appropriate
5056 ** sqlite3_io_methods object for a particular database file. The pAppData
5057 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
5058 ** the correct finder-function for that VFS.
5060 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
5061 ** object. The only interesting finder-function is autolockIoFinder, which
5062 ** looks at the filesystem type and tries to guess the best locking
5063 ** strategy from that.
5065 ** For finder-function F, two objects are created:
5067 ** (1) The real finder-function named "FImpt()".
5069 ** (2) A constant pointer to this function named just "F".
5072 ** A pointer to the F pointer is used as the pAppData value for VFS
5073 ** objects. We have to do this instead of letting pAppData point
5074 ** directly at the finder-function since C90 rules prevent a void*
5075 ** from be cast into a function pointer.
5078 ** Each instance of this macro generates two objects:
5080 ** * A constant sqlite3_io_methods object call METHOD that has locking
5081 ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
5083 ** * An I/O method finder function called FINDER that returns a pointer
5084 ** to the METHOD object in the previous bullet.
5086 #define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
5087 static const sqlite3_io_methods METHOD = { \
5088 VERSION, /* iVersion */ \
5089 CLOSE, /* xClose */ \
5090 unixRead, /* xRead */ \
5091 unixWrite, /* xWrite */ \
5092 unixTruncate, /* xTruncate */ \
5093 unixSync, /* xSync */ \
5094 unixFileSize, /* xFileSize */ \
5095 LOCK, /* xLock */ \
5096 UNLOCK, /* xUnlock */ \
5097 CKLOCK, /* xCheckReservedLock */ \
5098 unixFileControl, /* xFileControl */ \
5099 unixSectorSize, /* xSectorSize */ \
5100 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
5101 SHMMAP, /* xShmMap */ \
5102 unixShmLock, /* xShmLock */ \
5103 unixShmBarrier, /* xShmBarrier */ \
5104 unixShmUnmap, /* xShmUnmap */ \
5105 unixFetch, /* xFetch */ \
5106 unixUnfetch, /* xUnfetch */ \
5107 }; \
5108 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
5109 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
5110 return &METHOD; \
5112 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
5113 = FINDER##Impl;
5116 ** Here are all of the sqlite3_io_methods objects for each of the
5117 ** locking strategies. Functions that return pointers to these methods
5118 ** are also created.
5120 IOMETHODS(
5121 posixIoFinder, /* Finder function name */
5122 posixIoMethods, /* sqlite3_io_methods object name */
5123 3, /* shared memory and mmap are enabled */
5124 unixClose, /* xClose method */
5125 unixLock, /* xLock method */
5126 unixUnlock, /* xUnlock method */
5127 unixCheckReservedLock, /* xCheckReservedLock method */
5128 unixShmMap /* xShmMap method */
5130 IOMETHODS(
5131 nolockIoFinder, /* Finder function name */
5132 nolockIoMethods, /* sqlite3_io_methods object name */
5133 3, /* shared memory is disabled */
5134 nolockClose, /* xClose method */
5135 nolockLock, /* xLock method */
5136 nolockUnlock, /* xUnlock method */
5137 nolockCheckReservedLock, /* xCheckReservedLock method */
5138 0 /* xShmMap method */
5140 IOMETHODS(
5141 dotlockIoFinder, /* Finder function name */
5142 dotlockIoMethods, /* sqlite3_io_methods object name */
5143 1, /* shared memory is disabled */
5144 dotlockClose, /* xClose method */
5145 dotlockLock, /* xLock method */
5146 dotlockUnlock, /* xUnlock method */
5147 dotlockCheckReservedLock, /* xCheckReservedLock method */
5148 0 /* xShmMap method */
5151 #if SQLITE_ENABLE_LOCKING_STYLE
5152 IOMETHODS(
5153 flockIoFinder, /* Finder function name */
5154 flockIoMethods, /* sqlite3_io_methods object name */
5155 1, /* shared memory is disabled */
5156 flockClose, /* xClose method */
5157 flockLock, /* xLock method */
5158 flockUnlock, /* xUnlock method */
5159 flockCheckReservedLock, /* xCheckReservedLock method */
5160 0 /* xShmMap method */
5162 #endif
5164 #if OS_VXWORKS
5165 IOMETHODS(
5166 semIoFinder, /* Finder function name */
5167 semIoMethods, /* sqlite3_io_methods object name */
5168 1, /* shared memory is disabled */
5169 semXClose, /* xClose method */
5170 semXLock, /* xLock method */
5171 semXUnlock, /* xUnlock method */
5172 semXCheckReservedLock, /* xCheckReservedLock method */
5173 0 /* xShmMap method */
5175 #endif
5177 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5178 IOMETHODS(
5179 afpIoFinder, /* Finder function name */
5180 afpIoMethods, /* sqlite3_io_methods object name */
5181 1, /* shared memory is disabled */
5182 afpClose, /* xClose method */
5183 afpLock, /* xLock method */
5184 afpUnlock, /* xUnlock method */
5185 afpCheckReservedLock, /* xCheckReservedLock method */
5186 0 /* xShmMap method */
5188 #endif
5191 ** The proxy locking method is a "super-method" in the sense that it
5192 ** opens secondary file descriptors for the conch and lock files and
5193 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
5194 ** secondary files. For this reason, the division that implements
5195 ** proxy locking is located much further down in the file. But we need
5196 ** to go ahead and define the sqlite3_io_methods and finder function
5197 ** for proxy locking here. So we forward declare the I/O methods.
5199 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5200 static int proxyClose(sqlite3_file*);
5201 static int proxyLock(sqlite3_file*, int);
5202 static int proxyUnlock(sqlite3_file*, int);
5203 static int proxyCheckReservedLock(sqlite3_file*, int*);
5204 IOMETHODS(
5205 proxyIoFinder, /* Finder function name */
5206 proxyIoMethods, /* sqlite3_io_methods object name */
5207 1, /* shared memory is disabled */
5208 proxyClose, /* xClose method */
5209 proxyLock, /* xLock method */
5210 proxyUnlock, /* xUnlock method */
5211 proxyCheckReservedLock, /* xCheckReservedLock method */
5212 0 /* xShmMap method */
5214 #endif
5216 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5217 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5218 IOMETHODS(
5219 nfsIoFinder, /* Finder function name */
5220 nfsIoMethods, /* sqlite3_io_methods object name */
5221 1, /* shared memory is disabled */
5222 unixClose, /* xClose method */
5223 unixLock, /* xLock method */
5224 nfsUnlock, /* xUnlock method */
5225 unixCheckReservedLock, /* xCheckReservedLock method */
5226 0 /* xShmMap method */
5228 #endif
5230 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5232 ** This "finder" function attempts to determine the best locking strategy
5233 ** for the database file "filePath". It then returns the sqlite3_io_methods
5234 ** object that implements that strategy.
5236 ** This is for MacOSX only.
5238 static const sqlite3_io_methods *autolockIoFinderImpl(
5239 const char *filePath, /* name of the database file */
5240 unixFile *pNew /* open file object for the database file */
5242 static const struct Mapping {
5243 const char *zFilesystem; /* Filesystem type name */
5244 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
5245 } aMap[] = {
5246 { "hfs", &posixIoMethods },
5247 { "ufs", &posixIoMethods },
5248 { "afpfs", &afpIoMethods },
5249 { "smbfs", &afpIoMethods },
5250 { "webdav", &nolockIoMethods },
5251 { 0, 0 }
5253 int i;
5254 struct statfs fsInfo;
5255 struct flock lockInfo;
5257 if( !filePath ){
5258 /* If filePath==NULL that means we are dealing with a transient file
5259 ** that does not need to be locked. */
5260 return &nolockIoMethods;
5262 if( statfs(filePath, &fsInfo) != -1 ){
5263 if( fsInfo.f_flags & MNT_RDONLY ){
5264 return &nolockIoMethods;
5266 for(i=0; aMap[i].zFilesystem; i++){
5267 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5268 return aMap[i].pMethods;
5273 /* Default case. Handles, amongst others, "nfs".
5274 ** Test byte-range lock using fcntl(). If the call succeeds,
5275 ** assume that the file-system supports POSIX style locks.
5277 lockInfo.l_len = 1;
5278 lockInfo.l_start = 0;
5279 lockInfo.l_whence = SEEK_SET;
5280 lockInfo.l_type = F_RDLCK;
5281 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
5282 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5283 return &nfsIoMethods;
5284 } else {
5285 return &posixIoMethods;
5287 }else{
5288 return &dotlockIoMethods;
5291 static const sqlite3_io_methods
5292 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
5294 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
5296 #if OS_VXWORKS
5298 ** This "finder" function for VxWorks checks to see if posix advisory
5299 ** locking works. If it does, then that is what is used. If it does not
5300 ** work, then fallback to named semaphore locking.
5302 static const sqlite3_io_methods *vxworksIoFinderImpl(
5303 const char *filePath, /* name of the database file */
5304 unixFile *pNew /* the open file object */
5306 struct flock lockInfo;
5308 if( !filePath ){
5309 /* If filePath==NULL that means we are dealing with a transient file
5310 ** that does not need to be locked. */
5311 return &nolockIoMethods;
5314 /* Test if fcntl() is supported and use POSIX style locks.
5315 ** Otherwise fall back to the named semaphore method.
5317 lockInfo.l_len = 1;
5318 lockInfo.l_start = 0;
5319 lockInfo.l_whence = SEEK_SET;
5320 lockInfo.l_type = F_RDLCK;
5321 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
5322 return &posixIoMethods;
5323 }else{
5324 return &semIoMethods;
5327 static const sqlite3_io_methods
5328 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
5330 #endif /* OS_VXWORKS */
5333 ** An abstract type for a pointer to an IO method finder function:
5335 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
5338 /****************************************************************************
5339 **************************** sqlite3_vfs methods ****************************
5341 ** This division contains the implementation of methods on the
5342 ** sqlite3_vfs object.
5346 ** Initialize the contents of the unixFile structure pointed to by pId.
5348 static int fillInUnixFile(
5349 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5350 int h, /* Open file descriptor of file being opened */
5351 sqlite3_file *pId, /* Write to the unixFile structure here */
5352 const char *zFilename, /* Name of the file being opened */
5353 int ctrlFlags /* Zero or more UNIXFILE_* values */
5355 const sqlite3_io_methods *pLockingStyle;
5356 unixFile *pNew = (unixFile *)pId;
5357 int rc = SQLITE_OK;
5359 assert( pNew->pInode==NULL );
5361 /* No locking occurs in temporary files */
5362 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
5364 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
5365 pNew->h = h;
5366 pNew->pVfs = pVfs;
5367 pNew->zPath = zFilename;
5368 pNew->ctrlFlags = (u8)ctrlFlags;
5369 #if SQLITE_MAX_MMAP_SIZE>0
5370 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
5371 #endif
5372 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5373 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
5374 pNew->ctrlFlags |= UNIXFILE_PSOW;
5376 if( strcmp(pVfs->zName,"unix-excl")==0 ){
5377 pNew->ctrlFlags |= UNIXFILE_EXCL;
5380 #if OS_VXWORKS
5381 pNew->pId = vxworksFindFileId(zFilename);
5382 if( pNew->pId==0 ){
5383 ctrlFlags |= UNIXFILE_NOLOCK;
5384 rc = SQLITE_NOMEM_BKPT;
5386 #endif
5388 if( ctrlFlags & UNIXFILE_NOLOCK ){
5389 pLockingStyle = &nolockIoMethods;
5390 }else{
5391 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
5392 #if SQLITE_ENABLE_LOCKING_STYLE
5393 /* Cache zFilename in the locking context (AFP and dotlock override) for
5394 ** proxyLock activation is possible (remote proxy is based on db name)
5395 ** zFilename remains valid until file is closed, to support */
5396 pNew->lockingContext = (void*)zFilename;
5397 #endif
5400 if( pLockingStyle == &posixIoMethods
5401 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5402 || pLockingStyle == &nfsIoMethods
5403 #endif
5405 unixEnterMutex();
5406 rc = findInodeInfo(pNew, &pNew->pInode);
5407 if( rc!=SQLITE_OK ){
5408 /* If an error occurred in findInodeInfo(), close the file descriptor
5409 ** immediately, before releasing the mutex. findInodeInfo() may fail
5410 ** in two scenarios:
5412 ** (a) A call to fstat() failed.
5413 ** (b) A malloc failed.
5415 ** Scenario (b) may only occur if the process is holding no other
5416 ** file descriptors open on the same file. If there were other file
5417 ** descriptors on this file, then no malloc would be required by
5418 ** findInodeInfo(). If this is the case, it is quite safe to close
5419 ** handle h - as it is guaranteed that no posix locks will be released
5420 ** by doing so.
5422 ** If scenario (a) caused the error then things are not so safe. The
5423 ** implicit assumption here is that if fstat() fails, things are in
5424 ** such bad shape that dropping a lock or two doesn't matter much.
5426 robust_close(pNew, h, __LINE__);
5427 h = -1;
5429 unixLeaveMutex();
5432 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
5433 else if( pLockingStyle == &afpIoMethods ){
5434 /* AFP locking uses the file path so it needs to be included in
5435 ** the afpLockingContext.
5437 afpLockingContext *pCtx;
5438 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
5439 if( pCtx==0 ){
5440 rc = SQLITE_NOMEM_BKPT;
5441 }else{
5442 /* NB: zFilename exists and remains valid until the file is closed
5443 ** according to requirement F11141. So we do not need to make a
5444 ** copy of the filename. */
5445 pCtx->dbPath = zFilename;
5446 pCtx->reserved = 0;
5447 srandomdev();
5448 unixEnterMutex();
5449 rc = findInodeInfo(pNew, &pNew->pInode);
5450 if( rc!=SQLITE_OK ){
5451 sqlite3_free(pNew->lockingContext);
5452 robust_close(pNew, h, __LINE__);
5453 h = -1;
5455 unixLeaveMutex();
5458 #endif
5460 else if( pLockingStyle == &dotlockIoMethods ){
5461 /* Dotfile locking uses the file path so it needs to be included in
5462 ** the dotlockLockingContext
5464 char *zLockFile;
5465 int nFilename;
5466 assert( zFilename!=0 );
5467 nFilename = (int)strlen(zFilename) + 6;
5468 zLockFile = (char *)sqlite3_malloc64(nFilename);
5469 if( zLockFile==0 ){
5470 rc = SQLITE_NOMEM_BKPT;
5471 }else{
5472 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
5474 pNew->lockingContext = zLockFile;
5477 #if OS_VXWORKS
5478 else if( pLockingStyle == &semIoMethods ){
5479 /* Named semaphore locking uses the file path so it needs to be
5480 ** included in the semLockingContext
5482 unixEnterMutex();
5483 rc = findInodeInfo(pNew, &pNew->pInode);
5484 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5485 char *zSemName = pNew->pInode->aSemName;
5486 int n;
5487 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
5488 pNew->pId->zCanonicalName);
5489 for( n=1; zSemName[n]; n++ )
5490 if( zSemName[n]=='/' ) zSemName[n] = '_';
5491 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5492 if( pNew->pInode->pSem == SEM_FAILED ){
5493 rc = SQLITE_NOMEM_BKPT;
5494 pNew->pInode->aSemName[0] = '\0';
5497 unixLeaveMutex();
5499 #endif
5501 storeLastErrno(pNew, 0);
5502 #if OS_VXWORKS
5503 if( rc!=SQLITE_OK ){
5504 if( h>=0 ) robust_close(pNew, h, __LINE__);
5505 h = -1;
5506 osUnlink(zFilename);
5507 pNew->ctrlFlags |= UNIXFILE_DELETE;
5509 #endif
5510 if( rc!=SQLITE_OK ){
5511 if( h>=0 ) robust_close(pNew, h, __LINE__);
5512 }else{
5513 pNew->pMethod = pLockingStyle;
5514 OpenCounter(+1);
5515 verifyDbFile(pNew);
5517 return rc;
5521 ** Return the name of a directory in which to put temporary files.
5522 ** If no suitable temporary file directory can be found, return NULL.
5524 static const char *unixTempFileDir(void){
5525 static const char *azDirs[] = {
5528 "/var/tmp",
5529 "/usr/tmp",
5530 "/tmp",
5533 unsigned int i = 0;
5534 struct stat buf;
5535 const char *zDir = sqlite3_temp_directory;
5537 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
5538 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
5539 while(1){
5540 if( zDir!=0
5541 && osStat(zDir, &buf)==0
5542 && S_ISDIR(buf.st_mode)
5543 && osAccess(zDir, 03)==0
5545 return zDir;
5547 if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
5548 zDir = azDirs[i++];
5550 return 0;
5554 ** Create a temporary file name in zBuf. zBuf must be allocated
5555 ** by the calling process and must be big enough to hold at least
5556 ** pVfs->mxPathname bytes.
5558 static int unixGetTempname(int nBuf, char *zBuf){
5559 const char *zDir;
5560 int iLimit = 0;
5562 /* It's odd to simulate an io-error here, but really this is just
5563 ** using the io-error infrastructure to test that SQLite handles this
5564 ** function failing.
5566 zBuf[0] = 0;
5567 SimulateIOError( return SQLITE_IOERR );
5569 zDir = unixTempFileDir();
5570 if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
5572 u64 r;
5573 sqlite3_randomness(sizeof(r), &r);
5574 assert( nBuf>2 );
5575 zBuf[nBuf-2] = 0;
5576 sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
5577 zDir, r, 0);
5578 if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
5579 }while( osAccess(zBuf,0)==0 );
5580 return SQLITE_OK;
5583 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
5585 ** Routine to transform a unixFile into a proxy-locking unixFile.
5586 ** Implementation in the proxy-lock division, but used by unixOpen()
5587 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
5589 static int proxyTransformUnixFile(unixFile*, const char*);
5590 #endif
5593 ** Search for an unused file descriptor that was opened on the database
5594 ** file (not a journal or master-journal file) identified by pathname
5595 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5596 ** argument to this function.
5598 ** Such a file descriptor may exist if a database connection was closed
5599 ** but the associated file descriptor could not be closed because some
5600 ** other file descriptor open on the same file is holding a file-lock.
5601 ** Refer to comments in the unixClose() function and the lengthy comment
5602 ** describing "Posix Advisory Locking" at the start of this file for
5603 ** further details. Also, ticket #4018.
5605 ** If a suitable file descriptor is found, then it is returned. If no
5606 ** such file descriptor is located, -1 is returned.
5608 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5609 UnixUnusedFd *pUnused = 0;
5611 /* Do not search for an unused file descriptor on vxworks. Not because
5612 ** vxworks would not benefit from the change (it might, we're not sure),
5613 ** but because no way to test it is currently available. It is better
5614 ** not to risk breaking vxworks support for the sake of such an obscure
5615 ** feature. */
5616 #if !OS_VXWORKS
5617 struct stat sStat; /* Results of stat() call */
5619 unixEnterMutex();
5621 /* A stat() call may fail for various reasons. If this happens, it is
5622 ** almost certain that an open() call on the same path will also fail.
5623 ** For this reason, if an error occurs in the stat() call here, it is
5624 ** ignored and -1 is returned. The caller will try to open a new file
5625 ** descriptor on the same path, fail, and return an error to SQLite.
5627 ** Even if a subsequent open() call does succeed, the consequences of
5628 ** not searching for a reusable file descriptor are not dire. */
5629 if( nUnusedFd>0 && 0==osStat(zPath, &sStat) ){
5630 unixInodeInfo *pInode;
5632 pInode = inodeList;
5633 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5634 || pInode->fileId.ino!=(u64)sStat.st_ino) ){
5635 pInode = pInode->pNext;
5637 if( pInode ){
5638 UnixUnusedFd **pp;
5639 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
5640 pUnused = *pp;
5641 if( pUnused ){
5642 nUnusedFd--;
5643 *pp = pUnused->pNext;
5647 unixLeaveMutex();
5648 #endif /* if !OS_VXWORKS */
5649 return pUnused;
5653 ** Find the mode, uid and gid of file zFile.
5655 static int getFileMode(
5656 const char *zFile, /* File name */
5657 mode_t *pMode, /* OUT: Permissions of zFile */
5658 uid_t *pUid, /* OUT: uid of zFile. */
5659 gid_t *pGid /* OUT: gid of zFile. */
5661 struct stat sStat; /* Output of stat() on database file */
5662 int rc = SQLITE_OK;
5663 if( 0==osStat(zFile, &sStat) ){
5664 *pMode = sStat.st_mode & 0777;
5665 *pUid = sStat.st_uid;
5666 *pGid = sStat.st_gid;
5667 }else{
5668 rc = SQLITE_IOERR_FSTAT;
5670 return rc;
5674 ** This function is called by unixOpen() to determine the unix permissions
5675 ** to create new files with. If no error occurs, then SQLITE_OK is returned
5676 ** and a value suitable for passing as the third argument to open(2) is
5677 ** written to *pMode. If an IO error occurs, an SQLite error code is
5678 ** returned and the value of *pMode is not modified.
5680 ** In most cases, this routine sets *pMode to 0, which will become
5681 ** an indication to robust_open() to create the file using
5682 ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5683 ** But if the file being opened is a WAL or regular journal file, then
5684 ** this function queries the file-system for the permissions on the
5685 ** corresponding database file and sets *pMode to this value. Whenever
5686 ** possible, WAL and journal files are created using the same permissions
5687 ** as the associated database file.
5689 ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5690 ** original filename is unavailable. But 8_3_NAMES is only used for
5691 ** FAT filesystems and permissions do not matter there, so just use
5692 ** the default permissions.
5694 static int findCreateFileMode(
5695 const char *zPath, /* Path of file (possibly) being created */
5696 int flags, /* Flags passed as 4th argument to xOpen() */
5697 mode_t *pMode, /* OUT: Permissions to open file with */
5698 uid_t *pUid, /* OUT: uid to set on the file */
5699 gid_t *pGid /* OUT: gid to set on the file */
5701 int rc = SQLITE_OK; /* Return Code */
5702 *pMode = 0;
5703 *pUid = 0;
5704 *pGid = 0;
5705 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
5706 char zDb[MAX_PATHNAME+1]; /* Database file path */
5707 int nDb; /* Number of valid bytes in zDb */
5709 /* zPath is a path to a WAL or journal file. The following block derives
5710 ** the path to the associated database file from zPath. This block handles
5711 ** the following naming conventions:
5713 ** "<path to db>-journal"
5714 ** "<path to db>-wal"
5715 ** "<path to db>-journalNN"
5716 ** "<path to db>-walNN"
5718 ** where NN is a decimal number. The NN naming schemes are
5719 ** used by the test_multiplex.c module.
5721 nDb = sqlite3Strlen30(zPath) - 1;
5722 while( zPath[nDb]!='-' ){
5723 /* In normal operation, the journal file name will always contain
5724 ** a '-' character. However in 8+3 filename mode, or if a corrupt
5725 ** rollback journal specifies a master journal with a goofy name, then
5726 ** the '-' might be missing. */
5727 if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
5728 nDb--;
5730 memcpy(zDb, zPath, nDb);
5731 zDb[nDb] = '\0';
5733 rc = getFileMode(zDb, pMode, pUid, pGid);
5734 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5735 *pMode = 0600;
5736 }else if( flags & SQLITE_OPEN_URI ){
5737 /* If this is a main database file and the file was opened using a URI
5738 ** filename, check for the "modeof" parameter. If present, interpret
5739 ** its value as a filename and try to copy the mode, uid and gid from
5740 ** that file. */
5741 const char *z = sqlite3_uri_parameter(zPath, "modeof");
5742 if( z ){
5743 rc = getFileMode(z, pMode, pUid, pGid);
5746 return rc;
5750 ** Open the file zPath.
5752 ** Previously, the SQLite OS layer used three functions in place of this
5753 ** one:
5755 ** sqlite3OsOpenReadWrite();
5756 ** sqlite3OsOpenReadOnly();
5757 ** sqlite3OsOpenExclusive();
5759 ** These calls correspond to the following combinations of flags:
5761 ** ReadWrite() -> (READWRITE | CREATE)
5762 ** ReadOnly() -> (READONLY)
5763 ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5765 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5766 ** true, the file was configured to be automatically deleted when the
5767 ** file handle closed. To achieve the same effect using this new
5768 ** interface, add the DELETEONCLOSE flag to those specified above for
5769 ** OpenExclusive().
5771 static int unixOpen(
5772 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5773 const char *zPath, /* Pathname of file to be opened */
5774 sqlite3_file *pFile, /* The file descriptor to be filled in */
5775 int flags, /* Input flags to control the opening */
5776 int *pOutFlags /* Output flags returned to SQLite core */
5778 unixFile *p = (unixFile *)pFile;
5779 int fd = -1; /* File descriptor returned by open() */
5780 int openFlags = 0; /* Flags to pass to open() */
5781 int eType = flags&0xFFFFFF00; /* Type of file to open */
5782 int noLock; /* True to omit locking primitives */
5783 int rc = SQLITE_OK; /* Function Return Code */
5784 int ctrlFlags = 0; /* UNIXFILE_* flags */
5786 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5787 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5788 int isCreate = (flags & SQLITE_OPEN_CREATE);
5789 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5790 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
5791 #if SQLITE_ENABLE_LOCKING_STYLE
5792 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5793 #endif
5794 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5795 struct statfs fsInfo;
5796 #endif
5798 /* If creating a master or main-file journal, this function will open
5799 ** a file-descriptor on the directory too. The first time unixSync()
5800 ** is called the directory file descriptor will be fsync()ed and close()d.
5802 int isNewJrnl = (isCreate && (
5803 eType==SQLITE_OPEN_MASTER_JOURNAL
5804 || eType==SQLITE_OPEN_MAIN_JOURNAL
5805 || eType==SQLITE_OPEN_WAL
5808 /* If argument zPath is a NULL pointer, this function is required to open
5809 ** a temporary file. Use this buffer to store the file name in.
5811 char zTmpname[MAX_PATHNAME+2];
5812 const char *zName = zPath;
5814 /* Check the following statements are true:
5816 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5817 ** (b) if CREATE is set, then READWRITE must also be set, and
5818 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
5819 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
5821 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
5822 assert(isCreate==0 || isReadWrite);
5823 assert(isExclusive==0 || isCreate);
5824 assert(isDelete==0 || isCreate);
5826 /* The main DB, main journal, WAL file and master journal are never
5827 ** automatically deleted. Nor are they ever temporary files. */
5828 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5829 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5830 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
5831 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
5833 /* Assert that the upper layer has set one of the "file-type" flags. */
5834 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5835 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5836 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
5837 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
5840 /* Detect a pid change and reset the PRNG. There is a race condition
5841 ** here such that two or more threads all trying to open databases at
5842 ** the same instant might all reset the PRNG. But multiple resets
5843 ** are harmless.
5845 if( randomnessPid!=osGetpid(0) ){
5846 randomnessPid = osGetpid(0);
5847 sqlite3_randomness(0,0);
5850 memset(p, 0, sizeof(unixFile));
5852 if( eType==SQLITE_OPEN_MAIN_DB ){
5853 UnixUnusedFd *pUnused;
5854 pUnused = findReusableFd(zName, flags);
5855 if( pUnused ){
5856 fd = pUnused->fd;
5857 }else{
5858 pUnused = sqlite3_malloc64(sizeof(*pUnused));
5859 if( !pUnused ){
5860 return SQLITE_NOMEM_BKPT;
5863 p->pPreallocatedUnused = pUnused;
5865 /* Database filenames are double-zero terminated if they are not
5866 ** URIs with parameters. Hence, they can always be passed into
5867 ** sqlite3_uri_parameter(). */
5868 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5870 }else if( !zName ){
5871 /* If zName is NULL, the upper layer is requesting a temp file. */
5872 assert(isDelete && !isNewJrnl);
5873 rc = unixGetTempname(pVfs->mxPathname, zTmpname);
5874 if( rc!=SQLITE_OK ){
5875 return rc;
5877 zName = zTmpname;
5879 /* Generated temporary filenames are always double-zero terminated
5880 ** for use by sqlite3_uri_parameter(). */
5881 assert( zName[strlen(zName)+1]==0 );
5884 /* Determine the value of the flags parameter passed to POSIX function
5885 ** open(). These must be calculated even if open() is not called, as
5886 ** they may be stored as part of the file handle and used by the
5887 ** 'conch file' locking functions later on. */
5888 if( isReadonly ) openFlags |= O_RDONLY;
5889 if( isReadWrite ) openFlags |= O_RDWR;
5890 if( isCreate ) openFlags |= O_CREAT;
5891 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5892 openFlags |= (O_LARGEFILE|O_BINARY);
5894 if( fd<0 ){
5895 mode_t openMode; /* Permissions to create file with */
5896 uid_t uid; /* Userid for the file */
5897 gid_t gid; /* Groupid for the file */
5898 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
5899 if( rc!=SQLITE_OK ){
5900 assert( !p->pPreallocatedUnused );
5901 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
5902 return rc;
5904 fd = robust_open(zName, openFlags, openMode);
5905 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
5906 assert( !isExclusive || (openFlags & O_CREAT)!=0 );
5907 if( fd<0 && errno!=EISDIR && isReadWrite ){
5908 /* Failed to open the file for read/write access. Try read-only. */
5909 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
5910 openFlags &= ~(O_RDWR|O_CREAT);
5911 flags |= SQLITE_OPEN_READONLY;
5912 openFlags |= O_RDONLY;
5913 isReadonly = 1;
5914 fd = robust_open(zName, openFlags, openMode);
5916 if( fd<0 ){
5917 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
5918 /* If unable to create a journal, change the error code to
5919 ** indicate that the directory permissions are wrong. */
5920 if( isNewJrnl && osAccess(zName, F_OK) ) rc = SQLITE_READONLY_DIRECTORY;
5921 goto open_finished;
5924 /* If this process is running as root and if creating a new rollback
5925 ** journal or WAL file, set the ownership of the journal or WAL to be
5926 ** the same as the original database.
5928 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
5929 robustFchown(fd, uid, gid);
5932 assert( fd>=0 );
5933 if( pOutFlags ){
5934 *pOutFlags = flags;
5937 if( p->pPreallocatedUnused ){
5938 p->pPreallocatedUnused->fd = fd;
5939 p->pPreallocatedUnused->flags = flags;
5942 if( isDelete ){
5943 #if OS_VXWORKS
5944 zPath = zName;
5945 #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
5946 zPath = sqlite3_mprintf("%s", zName);
5947 if( zPath==0 ){
5948 robust_close(p, fd, __LINE__);
5949 return SQLITE_NOMEM_BKPT;
5951 #else
5952 osUnlink(zName);
5953 #endif
5955 #if SQLITE_ENABLE_LOCKING_STYLE
5956 else{
5957 p->openFlags = openFlags;
5959 #endif
5961 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5962 if( fstatfs(fd, &fsInfo) == -1 ){
5963 storeLastErrno(p, errno);
5964 robust_close(p, fd, __LINE__);
5965 return SQLITE_IOERR_ACCESS;
5967 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5968 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5970 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
5971 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5973 #endif
5975 /* Set up appropriate ctrlFlags */
5976 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5977 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5978 noLock = eType!=SQLITE_OPEN_MAIN_DB;
5979 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5980 if( isNewJrnl ) ctrlFlags |= UNIXFILE_DIRSYNC;
5981 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5983 #if SQLITE_ENABLE_LOCKING_STYLE
5984 #if SQLITE_PREFER_PROXY_LOCKING
5985 isAutoProxy = 1;
5986 #endif
5987 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
5988 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5989 int useProxy = 0;
5991 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5992 ** never use proxy, NULL means use proxy for non-local files only. */
5993 if( envforce!=NULL ){
5994 useProxy = atoi(envforce)>0;
5995 }else{
5996 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5998 if( useProxy ){
5999 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
6000 if( rc==SQLITE_OK ){
6001 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
6002 if( rc!=SQLITE_OK ){
6003 /* Use unixClose to clean up the resources added in fillInUnixFile
6004 ** and clear all the structure's references. Specifically,
6005 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
6007 unixClose(pFile);
6008 return rc;
6011 goto open_finished;
6014 #endif
6016 assert( zPath==0 || zPath[0]=='/'
6017 || eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL
6019 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
6021 open_finished:
6022 if( rc!=SQLITE_OK ){
6023 sqlite3_free(p->pPreallocatedUnused);
6025 return rc;
6030 ** Delete the file at zPath. If the dirSync argument is true, fsync()
6031 ** the directory after deleting the file.
6033 static int unixDelete(
6034 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
6035 const char *zPath, /* Name of file to be deleted */
6036 int dirSync /* If true, fsync() directory after deleting file */
6038 int rc = SQLITE_OK;
6039 UNUSED_PARAMETER(NotUsed);
6040 SimulateIOError(return SQLITE_IOERR_DELETE);
6041 if( osUnlink(zPath)==(-1) ){
6042 if( errno==ENOENT
6043 #if OS_VXWORKS
6044 || osAccess(zPath,0)!=0
6045 #endif
6047 rc = SQLITE_IOERR_DELETE_NOENT;
6048 }else{
6049 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
6051 return rc;
6053 #ifndef SQLITE_DISABLE_DIRSYNC
6054 if( (dirSync & 1)!=0 ){
6055 int fd;
6056 rc = osOpenDirectory(zPath, &fd);
6057 if( rc==SQLITE_OK ){
6058 if( full_fsync(fd,0,0) ){
6059 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
6061 robust_close(0, fd, __LINE__);
6062 }else{
6063 assert( rc==SQLITE_CANTOPEN );
6064 rc = SQLITE_OK;
6067 #endif
6068 return rc;
6072 ** Test the existence of or access permissions of file zPath. The
6073 ** test performed depends on the value of flags:
6075 ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
6076 ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
6077 ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
6079 ** Otherwise return 0.
6081 static int unixAccess(
6082 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
6083 const char *zPath, /* Path of the file to examine */
6084 int flags, /* What do we want to learn about the zPath file? */
6085 int *pResOut /* Write result boolean here */
6087 UNUSED_PARAMETER(NotUsed);
6088 SimulateIOError( return SQLITE_IOERR_ACCESS; );
6089 assert( pResOut!=0 );
6091 /* The spec says there are three possible values for flags. But only
6092 ** two of them are actually used */
6093 assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
6095 if( flags==SQLITE_ACCESS_EXISTS ){
6096 struct stat buf;
6097 *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
6098 }else{
6099 *pResOut = osAccess(zPath, W_OK|R_OK)==0;
6101 return SQLITE_OK;
6107 static int mkFullPathname(
6108 const char *zPath, /* Input path */
6109 char *zOut, /* Output buffer */
6110 int nOut /* Allocated size of buffer zOut */
6112 int nPath = sqlite3Strlen30(zPath);
6113 int iOff = 0;
6114 if( zPath[0]!='/' ){
6115 if( osGetcwd(zOut, nOut-2)==0 ){
6116 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
6118 iOff = sqlite3Strlen30(zOut);
6119 zOut[iOff++] = '/';
6121 if( (iOff+nPath+1)>nOut ){
6122 /* SQLite assumes that xFullPathname() nul-terminates the output buffer
6123 ** even if it returns an error. */
6124 zOut[iOff] = '\0';
6125 return SQLITE_CANTOPEN_BKPT;
6127 sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
6128 return SQLITE_OK;
6132 ** Turn a relative pathname into a full pathname. The relative path
6133 ** is stored as a nul-terminated string in the buffer pointed to by
6134 ** zPath.
6136 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
6137 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
6138 ** this buffer before returning.
6140 static int unixFullPathname(
6141 sqlite3_vfs *pVfs, /* Pointer to vfs object */
6142 const char *zPath, /* Possibly relative input path */
6143 int nOut, /* Size of output buffer in bytes */
6144 char *zOut /* Output buffer */
6146 #if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
6147 return mkFullPathname(zPath, zOut, nOut);
6148 #else
6149 int rc = SQLITE_OK;
6150 int nByte;
6151 int nLink = 1; /* Number of symbolic links followed so far */
6152 const char *zIn = zPath; /* Input path for each iteration of loop */
6153 char *zDel = 0;
6155 assert( pVfs->mxPathname==MAX_PATHNAME );
6156 UNUSED_PARAMETER(pVfs);
6158 /* It's odd to simulate an io-error here, but really this is just
6159 ** using the io-error infrastructure to test that SQLite handles this
6160 ** function failing. This function could fail if, for example, the
6161 ** current working directory has been unlinked.
6163 SimulateIOError( return SQLITE_ERROR );
6165 do {
6167 /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
6168 ** link, or false otherwise. */
6169 int bLink = 0;
6170 struct stat buf;
6171 if( osLstat(zIn, &buf)!=0 ){
6172 if( errno!=ENOENT ){
6173 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
6175 }else{
6176 bLink = S_ISLNK(buf.st_mode);
6179 if( bLink ){
6180 if( zDel==0 ){
6181 zDel = sqlite3_malloc(nOut);
6182 if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
6183 }else if( ++nLink>SQLITE_MAX_SYMLINKS ){
6184 rc = SQLITE_CANTOPEN_BKPT;
6187 if( rc==SQLITE_OK ){
6188 nByte = osReadlink(zIn, zDel, nOut-1);
6189 if( nByte<0 ){
6190 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
6191 }else{
6192 if( zDel[0]!='/' ){
6193 int n;
6194 for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
6195 if( nByte+n+1>nOut ){
6196 rc = SQLITE_CANTOPEN_BKPT;
6197 }else{
6198 memmove(&zDel[n], zDel, nByte+1);
6199 memcpy(zDel, zIn, n);
6200 nByte += n;
6203 zDel[nByte] = '\0';
6207 zIn = zDel;
6210 assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
6211 if( rc==SQLITE_OK && zIn!=zOut ){
6212 rc = mkFullPathname(zIn, zOut, nOut);
6214 if( bLink==0 ) break;
6215 zIn = zOut;
6216 }while( rc==SQLITE_OK );
6218 sqlite3_free(zDel);
6219 return rc;
6220 #endif /* HAVE_READLINK && HAVE_LSTAT */
6224 #ifndef SQLITE_OMIT_LOAD_EXTENSION
6226 ** Interfaces for opening a shared library, finding entry points
6227 ** within the shared library, and closing the shared library.
6229 #include <dlfcn.h>
6230 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6231 UNUSED_PARAMETER(NotUsed);
6232 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6236 ** SQLite calls this function immediately after a call to unixDlSym() or
6237 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
6238 ** message is available, it is written to zBufOut. If no error message
6239 ** is available, zBufOut is left unmodified and SQLite uses a default
6240 ** error message.
6242 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
6243 const char *zErr;
6244 UNUSED_PARAMETER(NotUsed);
6245 unixEnterMutex();
6246 zErr = dlerror();
6247 if( zErr ){
6248 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
6250 unixLeaveMutex();
6252 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6254 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6255 ** cast into a pointer to a function. And yet the library dlsym() routine
6256 ** returns a void* which is really a pointer to a function. So how do we
6257 ** use dlsym() with -pedantic-errors?
6259 ** Variable x below is defined to be a pointer to a function taking
6260 ** parameters void* and const char* and returning a pointer to a function.
6261 ** We initialize x by assigning it a pointer to the dlsym() function.
6262 ** (That assignment requires a cast.) Then we call the function that
6263 ** x points to.
6265 ** This work-around is unlikely to work correctly on any system where
6266 ** you really cannot cast a function pointer into void*. But then, on the
6267 ** other hand, dlsym() will not work on such a system either, so we have
6268 ** not really lost anything.
6270 void (*(*x)(void*,const char*))(void);
6271 UNUSED_PARAMETER(NotUsed);
6272 x = (void(*(*)(void*,const char*))(void))dlsym;
6273 return (*x)(p, zSym);
6275 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6276 UNUSED_PARAMETER(NotUsed);
6277 dlclose(pHandle);
6279 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6280 #define unixDlOpen 0
6281 #define unixDlError 0
6282 #define unixDlSym 0
6283 #define unixDlClose 0
6284 #endif
6287 ** Write nBuf bytes of random data to the supplied buffer zBuf.
6289 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6290 UNUSED_PARAMETER(NotUsed);
6291 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
6293 /* We have to initialize zBuf to prevent valgrind from reporting
6294 ** errors. The reports issued by valgrind are incorrect - we would
6295 ** prefer that the randomness be increased by making use of the
6296 ** uninitialized space in zBuf - but valgrind errors tend to worry
6297 ** some users. Rather than argue, it seems easier just to initialize
6298 ** the whole array and silence valgrind, even if that means less randomness
6299 ** in the random seed.
6301 ** When testing, initializing zBuf[] to zero is all we do. That means
6302 ** that we always use the same random number sequence. This makes the
6303 ** tests repeatable.
6305 memset(zBuf, 0, nBuf);
6306 randomnessPid = osGetpid(0);
6307 #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
6309 int fd, got;
6310 fd = robust_open("/dev/urandom", O_RDONLY, 0);
6311 if( fd<0 ){
6312 time_t t;
6313 time(&t);
6314 memcpy(zBuf, &t, sizeof(t));
6315 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6316 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6317 nBuf = sizeof(t) + sizeof(randomnessPid);
6318 }else{
6319 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
6320 robust_close(0, fd, __LINE__);
6323 #endif
6324 return nBuf;
6329 ** Sleep for a little while. Return the amount of time slept.
6330 ** The argument is the number of microseconds we want to sleep.
6331 ** The return value is the number of microseconds of sleep actually
6332 ** requested from the underlying operating system, a number which
6333 ** might be greater than or equal to the argument, but not less
6334 ** than the argument.
6336 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
6337 #if OS_VXWORKS
6338 struct timespec sp;
6340 sp.tv_sec = microseconds / 1000000;
6341 sp.tv_nsec = (microseconds % 1000000) * 1000;
6342 nanosleep(&sp, NULL);
6343 UNUSED_PARAMETER(NotUsed);
6344 return microseconds;
6345 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
6346 usleep(microseconds);
6347 UNUSED_PARAMETER(NotUsed);
6348 return microseconds;
6349 #else
6350 int seconds = (microseconds+999999)/1000000;
6351 sleep(seconds);
6352 UNUSED_PARAMETER(NotUsed);
6353 return seconds*1000000;
6354 #endif
6358 ** The following variable, if set to a non-zero value, is interpreted as
6359 ** the number of seconds since 1970 and is used to set the result of
6360 ** sqlite3OsCurrentTime() during testing.
6362 #ifdef SQLITE_TEST
6363 int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
6364 #endif
6367 ** Find the current time (in Universal Coordinated Time). Write into *piNow
6368 ** the current time and date as a Julian Day number times 86_400_000. In
6369 ** other words, write into *piNow the number of milliseconds since the Julian
6370 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6371 ** proleptic Gregorian calendar.
6373 ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6374 ** cannot be found.
6376 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6377 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
6378 int rc = SQLITE_OK;
6379 #if defined(NO_GETTOD)
6380 time_t t;
6381 time(&t);
6382 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
6383 #elif OS_VXWORKS
6384 struct timespec sNow;
6385 clock_gettime(CLOCK_REALTIME, &sNow);
6386 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6387 #else
6388 struct timeval sNow;
6389 (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
6390 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
6391 #endif
6393 #ifdef SQLITE_TEST
6394 if( sqlite3_current_time ){
6395 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6397 #endif
6398 UNUSED_PARAMETER(NotUsed);
6399 return rc;
6402 #ifndef SQLITE_OMIT_DEPRECATED
6404 ** Find the current time (in Universal Coordinated Time). Write the
6405 ** current time and date as a Julian Day number into *prNow and
6406 ** return 0. Return 1 if the time and date cannot be found.
6408 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
6409 sqlite3_int64 i = 0;
6410 int rc;
6411 UNUSED_PARAMETER(NotUsed);
6412 rc = unixCurrentTimeInt64(0, &i);
6413 *prNow = i/86400000.0;
6414 return rc;
6416 #else
6417 # define unixCurrentTime 0
6418 #endif
6421 ** The xGetLastError() method is designed to return a better
6422 ** low-level error message when operating-system problems come up
6423 ** during SQLite operation. Only the integer return code is currently
6424 ** used.
6426 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6427 UNUSED_PARAMETER(NotUsed);
6428 UNUSED_PARAMETER(NotUsed2);
6429 UNUSED_PARAMETER(NotUsed3);
6430 return errno;
6435 ************************ End of sqlite3_vfs methods ***************************
6436 ******************************************************************************/
6438 /******************************************************************************
6439 ************************** Begin Proxy Locking ********************************
6441 ** Proxy locking is a "uber-locking-method" in this sense: It uses the
6442 ** other locking methods on secondary lock files. Proxy locking is a
6443 ** meta-layer over top of the primitive locking implemented above. For
6444 ** this reason, the division that implements of proxy locking is deferred
6445 ** until late in the file (here) after all of the other I/O methods have
6446 ** been defined - so that the primitive locking methods are available
6447 ** as services to help with the implementation of proxy locking.
6449 ****
6451 ** The default locking schemes in SQLite use byte-range locks on the
6452 ** database file to coordinate safe, concurrent access by multiple readers
6453 ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6454 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6455 ** as POSIX read & write locks over fixed set of locations (via fsctl),
6456 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
6457 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6458 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6459 ** address in the shared range is taken for a SHARED lock, the entire
6460 ** shared range is taken for an EXCLUSIVE lock):
6462 ** PENDING_BYTE 0x40000000
6463 ** RESERVED_BYTE 0x40000001
6464 ** SHARED_RANGE 0x40000002 -> 0x40000200
6466 ** This works well on the local file system, but shows a nearly 100x
6467 ** slowdown in read performance on AFP because the AFP client disables
6468 ** the read cache when byte-range locks are present. Enabling the read
6469 ** cache exposes a cache coherency problem that is present on all OS X
6470 ** supported network file systems. NFS and AFP both observe the
6471 ** close-to-open semantics for ensuring cache coherency
6472 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6473 ** address the requirements for concurrent database access by multiple
6474 ** readers and writers
6475 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6477 ** To address the performance and cache coherency issues, proxy file locking
6478 ** changes the way database access is controlled by limiting access to a
6479 ** single host at a time and moving file locks off of the database file
6480 ** and onto a proxy file on the local file system.
6483 ** Using proxy locks
6484 ** -----------------
6486 ** C APIs
6488 ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
6489 ** <proxy_path> | ":auto:");
6490 ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6491 ** &<proxy_path>);
6494 ** SQL pragmas
6496 ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6497 ** PRAGMA [database.]lock_proxy_file
6499 ** Specifying ":auto:" means that if there is a conch file with a matching
6500 ** host ID in it, the proxy path in the conch file will be used, otherwise
6501 ** a proxy path based on the user's temp dir
6502 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6503 ** actual proxy file name is generated from the name and path of the
6504 ** database file. For example:
6506 ** For database path "/Users/me/foo.db"
6507 ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6509 ** Once a lock proxy is configured for a database connection, it can not
6510 ** be removed, however it may be switched to a different proxy path via
6511 ** the above APIs (assuming the conch file is not being held by another
6512 ** connection or process).
6515 ** How proxy locking works
6516 ** -----------------------
6518 ** Proxy file locking relies primarily on two new supporting files:
6520 ** * conch file to limit access to the database file to a single host
6521 ** at a time
6523 ** * proxy file to act as a proxy for the advisory locks normally
6524 ** taken on the database
6526 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
6527 ** by taking an sqlite-style shared lock on the conch file, reading the
6528 ** contents and comparing the host's unique host ID (see below) and lock
6529 ** proxy path against the values stored in the conch. The conch file is
6530 ** stored in the same directory as the database file and the file name
6531 ** is patterned after the database file name as ".<databasename>-conch".
6532 ** If the conch file does not exist, or its contents do not match the
6533 ** host ID and/or proxy path, then the lock is escalated to an exclusive
6534 ** lock and the conch file contents is updated with the host ID and proxy
6535 ** path and the lock is downgraded to a shared lock again. If the conch
6536 ** is held by another process (with a shared lock), the exclusive lock
6537 ** will fail and SQLITE_BUSY is returned.
6539 ** The proxy file - a single-byte file used for all advisory file locks
6540 ** normally taken on the database file. This allows for safe sharing
6541 ** of the database file for multiple readers and writers on the same
6542 ** host (the conch ensures that they all use the same local lock file).
6544 ** Requesting the lock proxy does not immediately take the conch, it is
6545 ** only taken when the first request to lock database file is made.
6546 ** This matches the semantics of the traditional locking behavior, where
6547 ** opening a connection to a database file does not take a lock on it.
6548 ** The shared lock and an open file descriptor are maintained until
6549 ** the connection to the database is closed.
6551 ** The proxy file and the lock file are never deleted so they only need
6552 ** to be created the first time they are used.
6554 ** Configuration options
6555 ** ---------------------
6557 ** SQLITE_PREFER_PROXY_LOCKING
6559 ** Database files accessed on non-local file systems are
6560 ** automatically configured for proxy locking, lock files are
6561 ** named automatically using the same logic as
6562 ** PRAGMA lock_proxy_file=":auto:"
6564 ** SQLITE_PROXY_DEBUG
6566 ** Enables the logging of error messages during host id file
6567 ** retrieval and creation
6569 ** LOCKPROXYDIR
6571 ** Overrides the default directory used for lock proxy files that
6572 ** are named automatically via the ":auto:" setting
6574 ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6576 ** Permissions to use when creating a directory for storing the
6577 ** lock proxy files, only used when LOCKPROXYDIR is not set.
6580 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6581 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6582 ** force proxy locking to be used for every database file opened, and 0
6583 ** will force automatic proxy locking to be disabled for all database
6584 ** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
6585 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6589 ** Proxy locking is only available on MacOSX
6591 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
6594 ** The proxyLockingContext has the path and file structures for the remote
6595 ** and local proxy files in it
6597 typedef struct proxyLockingContext proxyLockingContext;
6598 struct proxyLockingContext {
6599 unixFile *conchFile; /* Open conch file */
6600 char *conchFilePath; /* Name of the conch file */
6601 unixFile *lockProxy; /* Open proxy lock file */
6602 char *lockProxyPath; /* Name of the proxy lock file */
6603 char *dbPath; /* Name of the open file */
6604 int conchHeld; /* 1 if the conch is held, -1 if lockless */
6605 int nFails; /* Number of conch taking failures */
6606 void *oldLockingContext; /* Original lockingcontext to restore on close */
6607 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6611 ** The proxy lock file path for the database at dbPath is written into lPath,
6612 ** which must point to valid, writable memory large enough for a maxLen length
6613 ** file path.
6615 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6616 int len;
6617 int dbLen;
6618 int i;
6620 #ifdef LOCKPROXYDIR
6621 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6622 #else
6623 # ifdef _CS_DARWIN_USER_TEMP_DIR
6625 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
6626 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
6627 lPath, errno, osGetpid(0)));
6628 return SQLITE_IOERR_LOCK;
6630 len = strlcat(lPath, "sqliteplocks", maxLen);
6632 # else
6633 len = strlcpy(lPath, "/tmp/", maxLen);
6634 # endif
6635 #endif
6637 if( lPath[len-1]!='/' ){
6638 len = strlcat(lPath, "/", maxLen);
6641 /* transform the db path to a unique cache name */
6642 dbLen = (int)strlen(dbPath);
6643 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
6644 char c = dbPath[i];
6645 lPath[i+len] = (c=='/')?'_':c;
6647 lPath[i+len]='\0';
6648 strlcat(lPath, ":auto:", maxLen);
6649 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
6650 return SQLITE_OK;
6654 ** Creates the lock file and any missing directories in lockPath
6656 static int proxyCreateLockPath(const char *lockPath){
6657 int i, len;
6658 char buf[MAXPATHLEN];
6659 int start = 0;
6661 assert(lockPath!=NULL);
6662 /* try to create all the intermediate directories */
6663 len = (int)strlen(lockPath);
6664 buf[0] = lockPath[0];
6665 for( i=1; i<len; i++ ){
6666 if( lockPath[i] == '/' && (i - start > 0) ){
6667 /* only mkdir if leaf dir != "." or "/" or ".." */
6668 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6669 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6670 buf[i]='\0';
6671 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
6672 int err=errno;
6673 if( err!=EEXIST ) {
6674 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
6675 "'%s' proxy lock path=%s pid=%d\n",
6676 buf, strerror(err), lockPath, osGetpid(0)));
6677 return err;
6681 start=i+1;
6683 buf[i] = lockPath[i];
6685 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
6686 return 0;
6690 ** Create a new VFS file descriptor (stored in memory obtained from
6691 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
6693 ** The caller is responsible not only for closing the file descriptor
6694 ** but also for freeing the memory associated with the file descriptor.
6696 static int proxyCreateUnixFile(
6697 const char *path, /* path for the new unixFile */
6698 unixFile **ppFile, /* unixFile created and returned by ref */
6699 int islockfile /* if non zero missing dirs will be created */
6701 int fd = -1;
6702 unixFile *pNew;
6703 int rc = SQLITE_OK;
6704 int openFlags = O_RDWR | O_CREAT;
6705 sqlite3_vfs dummyVfs;
6706 int terrno = 0;
6707 UnixUnusedFd *pUnused = NULL;
6709 /* 1. first try to open/create the file
6710 ** 2. if that fails, and this is a lock file (not-conch), try creating
6711 ** the parent directories and then try again.
6712 ** 3. if that fails, try to open the file read-only
6713 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6715 pUnused = findReusableFd(path, openFlags);
6716 if( pUnused ){
6717 fd = pUnused->fd;
6718 }else{
6719 pUnused = sqlite3_malloc64(sizeof(*pUnused));
6720 if( !pUnused ){
6721 return SQLITE_NOMEM_BKPT;
6724 if( fd<0 ){
6725 fd = robust_open(path, openFlags, 0);
6726 terrno = errno;
6727 if( fd<0 && errno==ENOENT && islockfile ){
6728 if( proxyCreateLockPath(path) == SQLITE_OK ){
6729 fd = robust_open(path, openFlags, 0);
6733 if( fd<0 ){
6734 openFlags = O_RDONLY;
6735 fd = robust_open(path, openFlags, 0);
6736 terrno = errno;
6738 if( fd<0 ){
6739 if( islockfile ){
6740 return SQLITE_BUSY;
6742 switch (terrno) {
6743 case EACCES:
6744 return SQLITE_PERM;
6745 case EIO:
6746 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6747 default:
6748 return SQLITE_CANTOPEN_BKPT;
6752 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
6753 if( pNew==NULL ){
6754 rc = SQLITE_NOMEM_BKPT;
6755 goto end_create_proxy;
6757 memset(pNew, 0, sizeof(unixFile));
6758 pNew->openFlags = openFlags;
6759 memset(&dummyVfs, 0, sizeof(dummyVfs));
6760 dummyVfs.pAppData = (void*)&autolockIoFinder;
6761 dummyVfs.zName = "dummy";
6762 pUnused->fd = fd;
6763 pUnused->flags = openFlags;
6764 pNew->pPreallocatedUnused = pUnused;
6766 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
6767 if( rc==SQLITE_OK ){
6768 *ppFile = pNew;
6769 return SQLITE_OK;
6771 end_create_proxy:
6772 robust_close(pNew, fd, __LINE__);
6773 sqlite3_free(pNew);
6774 sqlite3_free(pUnused);
6775 return rc;
6778 #ifdef SQLITE_TEST
6779 /* simulate multiple hosts by creating unique hostid file paths */
6780 int sqlite3_hostid_num = 0;
6781 #endif
6783 #define PROXY_HOSTIDLEN 16 /* conch file host id length */
6785 #ifdef HAVE_GETHOSTUUID
6786 /* Not always defined in the headers as it ought to be */
6787 extern int gethostuuid(uuid_t id, const struct timespec *wait);
6788 #endif
6790 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6791 ** bytes of writable memory.
6793 static int proxyGetHostID(unsigned char *pHostID, int *pError){
6794 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6795 memset(pHostID, 0, PROXY_HOSTIDLEN);
6796 #ifdef HAVE_GETHOSTUUID
6798 struct timespec timeout = {1, 0}; /* 1 sec timeout */
6799 if( gethostuuid(pHostID, &timeout) ){
6800 int err = errno;
6801 if( pError ){
6802 *pError = err;
6804 return SQLITE_IOERR;
6807 #else
6808 UNUSED_PARAMETER(pError);
6809 #endif
6810 #ifdef SQLITE_TEST
6811 /* simulate multiple hosts by creating unique hostid file paths */
6812 if( sqlite3_hostid_num != 0){
6813 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6815 #endif
6817 return SQLITE_OK;
6820 /* The conch file contains the header, host id and lock file path
6822 #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6823 #define PROXY_HEADERLEN 1 /* conch file header length */
6824 #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6825 #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6828 ** Takes an open conch file, copies the contents to a new path and then moves
6829 ** it back. The newly created file's file descriptor is assigned to the
6830 ** conch file structure and finally the original conch file descriptor is
6831 ** closed. Returns zero if successful.
6833 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6834 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6835 unixFile *conchFile = pCtx->conchFile;
6836 char tPath[MAXPATHLEN];
6837 char buf[PROXY_MAXCONCHLEN];
6838 char *cPath = pCtx->conchFilePath;
6839 size_t readLen = 0;
6840 size_t pathLen = 0;
6841 char errmsg[64] = "";
6842 int fd = -1;
6843 int rc = -1;
6844 UNUSED_PARAMETER(myHostID);
6846 /* create a new path by replace the trailing '-conch' with '-break' */
6847 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6848 if( pathLen>MAXPATHLEN || pathLen<6 ||
6849 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
6850 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
6851 goto end_breaklock;
6853 /* read the conch content */
6854 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
6855 if( readLen<PROXY_PATHINDEX ){
6856 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
6857 goto end_breaklock;
6859 /* write it out to the temporary break file */
6860 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
6861 if( fd<0 ){
6862 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
6863 goto end_breaklock;
6865 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
6866 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
6867 goto end_breaklock;
6869 if( rename(tPath, cPath) ){
6870 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
6871 goto end_breaklock;
6873 rc = 0;
6874 fprintf(stderr, "broke stale lock on %s\n", cPath);
6875 robust_close(pFile, conchFile->h, __LINE__);
6876 conchFile->h = fd;
6877 conchFile->openFlags = O_RDWR | O_CREAT;
6879 end_breaklock:
6880 if( rc ){
6881 if( fd>=0 ){
6882 osUnlink(tPath);
6883 robust_close(pFile, fd, __LINE__);
6885 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6887 return rc;
6890 /* Take the requested lock on the conch file and break a stale lock if the
6891 ** host id matches.
6893 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6894 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6895 unixFile *conchFile = pCtx->conchFile;
6896 int rc = SQLITE_OK;
6897 int nTries = 0;
6898 struct timespec conchModTime;
6900 memset(&conchModTime, 0, sizeof(conchModTime));
6901 do {
6902 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6903 nTries ++;
6904 if( rc==SQLITE_BUSY ){
6905 /* If the lock failed (busy):
6906 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6907 * 2nd try: fail if the mod time changed or host id is different, wait
6908 * 10 sec and try again
6909 * 3rd try: break the lock unless the mod time has changed.
6911 struct stat buf;
6912 if( osFstat(conchFile->h, &buf) ){
6913 storeLastErrno(pFile, errno);
6914 return SQLITE_IOERR_LOCK;
6917 if( nTries==1 ){
6918 conchModTime = buf.st_mtimespec;
6919 usleep(500000); /* wait 0.5 sec and try the lock again*/
6920 continue;
6923 assert( nTries>1 );
6924 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6925 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6926 return SQLITE_BUSY;
6929 if( nTries==2 ){
6930 char tBuf[PROXY_MAXCONCHLEN];
6931 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
6932 if( len<0 ){
6933 storeLastErrno(pFile, errno);
6934 return SQLITE_IOERR_LOCK;
6936 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6937 /* don't break the lock if the host id doesn't match */
6938 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6939 return SQLITE_BUSY;
6941 }else{
6942 /* don't break the lock on short read or a version mismatch */
6943 return SQLITE_BUSY;
6945 usleep(10000000); /* wait 10 sec and try the lock again */
6946 continue;
6949 assert( nTries==3 );
6950 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6951 rc = SQLITE_OK;
6952 if( lockType==EXCLUSIVE_LOCK ){
6953 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
6955 if( !rc ){
6956 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6960 } while( rc==SQLITE_BUSY && nTries<3 );
6962 return rc;
6965 /* Takes the conch by taking a shared lock and read the contents conch, if
6966 ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6967 ** lockPath means that the lockPath in the conch file will be used if the
6968 ** host IDs match, or a new lock path will be generated automatically
6969 ** and written to the conch file.
6971 static int proxyTakeConch(unixFile *pFile){
6972 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6974 if( pCtx->conchHeld!=0 ){
6975 return SQLITE_OK;
6976 }else{
6977 unixFile *conchFile = pCtx->conchFile;
6978 uuid_t myHostID;
6979 int pError = 0;
6980 char readBuf[PROXY_MAXCONCHLEN];
6981 char lockPath[MAXPATHLEN];
6982 char *tempLockPath = NULL;
6983 int rc = SQLITE_OK;
6984 int createConch = 0;
6985 int hostIdMatch = 0;
6986 int readLen = 0;
6987 int tryOldLockPath = 0;
6988 int forceNewLockPath = 0;
6990 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6991 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
6992 osGetpid(0)));
6994 rc = proxyGetHostID(myHostID, &pError);
6995 if( (rc&0xff)==SQLITE_IOERR ){
6996 storeLastErrno(pFile, pError);
6997 goto end_takeconch;
6999 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
7000 if( rc!=SQLITE_OK ){
7001 goto end_takeconch;
7003 /* read the existing conch file */
7004 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
7005 if( readLen<0 ){
7006 /* I/O error: lastErrno set by seekAndRead */
7007 storeLastErrno(pFile, conchFile->lastErrno);
7008 rc = SQLITE_IOERR_READ;
7009 goto end_takeconch;
7010 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
7011 readBuf[0]!=(char)PROXY_CONCHVERSION ){
7012 /* a short read or version format mismatch means we need to create a new
7013 ** conch file.
7015 createConch = 1;
7017 /* if the host id matches and the lock path already exists in the conch
7018 ** we'll try to use the path there, if we can't open that path, we'll
7019 ** retry with a new auto-generated path
7021 do { /* in case we need to try again for an :auto: named lock file */
7023 if( !createConch && !forceNewLockPath ){
7024 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
7025 PROXY_HOSTIDLEN);
7026 /* if the conch has data compare the contents */
7027 if( !pCtx->lockProxyPath ){
7028 /* for auto-named local lock file, just check the host ID and we'll
7029 ** use the local lock file path that's already in there
7031 if( hostIdMatch ){
7032 size_t pathLen = (readLen - PROXY_PATHINDEX);
7034 if( pathLen>=MAXPATHLEN ){
7035 pathLen=MAXPATHLEN-1;
7037 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
7038 lockPath[pathLen] = 0;
7039 tempLockPath = lockPath;
7040 tryOldLockPath = 1;
7041 /* create a copy of the lock path if the conch is taken */
7042 goto end_takeconch;
7044 }else if( hostIdMatch
7045 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
7046 readLen-PROXY_PATHINDEX)
7048 /* conch host and lock path match */
7049 goto end_takeconch;
7053 /* if the conch isn't writable and doesn't match, we can't take it */
7054 if( (conchFile->openFlags&O_RDWR) == 0 ){
7055 rc = SQLITE_BUSY;
7056 goto end_takeconch;
7059 /* either the conch didn't match or we need to create a new one */
7060 if( !pCtx->lockProxyPath ){
7061 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
7062 tempLockPath = lockPath;
7063 /* create a copy of the lock path _only_ if the conch is taken */
7066 /* update conch with host and path (this will fail if other process
7067 ** has a shared lock already), if the host id matches, use the big
7068 ** stick.
7070 futimes(conchFile->h, NULL);
7071 if( hostIdMatch && !createConch ){
7072 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
7073 /* We are trying for an exclusive lock but another thread in this
7074 ** same process is still holding a shared lock. */
7075 rc = SQLITE_BUSY;
7076 } else {
7077 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
7079 }else{
7080 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
7082 if( rc==SQLITE_OK ){
7083 char writeBuffer[PROXY_MAXCONCHLEN];
7084 int writeSize = 0;
7086 writeBuffer[0] = (char)PROXY_CONCHVERSION;
7087 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
7088 if( pCtx->lockProxyPath!=NULL ){
7089 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
7090 MAXPATHLEN);
7091 }else{
7092 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
7094 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
7095 robust_ftruncate(conchFile->h, writeSize);
7096 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
7097 full_fsync(conchFile->h,0,0);
7098 /* If we created a new conch file (not just updated the contents of a
7099 ** valid conch file), try to match the permissions of the database
7101 if( rc==SQLITE_OK && createConch ){
7102 struct stat buf;
7103 int err = osFstat(pFile->h, &buf);
7104 if( err==0 ){
7105 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
7106 S_IROTH|S_IWOTH);
7107 /* try to match the database file R/W permissions, ignore failure */
7108 #ifndef SQLITE_PROXY_DEBUG
7109 osFchmod(conchFile->h, cmode);
7110 #else
7112 rc = osFchmod(conchFile->h, cmode);
7113 }while( rc==(-1) && errno==EINTR );
7114 if( rc!=0 ){
7115 int code = errno;
7116 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
7117 cmode, code, strerror(code));
7118 } else {
7119 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
7121 }else{
7122 int code = errno;
7123 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
7124 err, code, strerror(code));
7125 #endif
7129 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
7131 end_takeconch:
7132 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
7133 if( rc==SQLITE_OK && pFile->openFlags ){
7134 int fd;
7135 if( pFile->h>=0 ){
7136 robust_close(pFile, pFile->h, __LINE__);
7138 pFile->h = -1;
7139 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
7140 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
7141 if( fd>=0 ){
7142 pFile->h = fd;
7143 }else{
7144 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
7145 during locking */
7148 if( rc==SQLITE_OK && !pCtx->lockProxy ){
7149 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
7150 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
7151 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
7152 /* we couldn't create the proxy lock file with the old lock file path
7153 ** so try again via auto-naming
7155 forceNewLockPath = 1;
7156 tryOldLockPath = 0;
7157 continue; /* go back to the do {} while start point, try again */
7160 if( rc==SQLITE_OK ){
7161 /* Need to make a copy of path if we extracted the value
7162 ** from the conch file or the path was allocated on the stack
7164 if( tempLockPath ){
7165 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
7166 if( !pCtx->lockProxyPath ){
7167 rc = SQLITE_NOMEM_BKPT;
7171 if( rc==SQLITE_OK ){
7172 pCtx->conchHeld = 1;
7174 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
7175 afpLockingContext *afpCtx;
7176 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
7177 afpCtx->dbPath = pCtx->lockProxyPath;
7179 } else {
7180 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7182 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
7183 rc==SQLITE_OK?"ok":"failed"));
7184 return rc;
7185 } while (1); /* in case we need to retry the :auto: lock file -
7186 ** we should never get here except via the 'continue' call. */
7191 ** If pFile holds a lock on a conch file, then release that lock.
7193 static int proxyReleaseConch(unixFile *pFile){
7194 int rc = SQLITE_OK; /* Subroutine return code */
7195 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
7196 unixFile *conchFile; /* Name of the conch file */
7198 pCtx = (proxyLockingContext *)pFile->lockingContext;
7199 conchFile = pCtx->conchFile;
7200 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
7201 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
7202 osGetpid(0)));
7203 if( pCtx->conchHeld>0 ){
7204 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7206 pCtx->conchHeld = 0;
7207 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
7208 (rc==SQLITE_OK ? "ok" : "failed")));
7209 return rc;
7213 ** Given the name of a database file, compute the name of its conch file.
7214 ** Store the conch filename in memory obtained from sqlite3_malloc64().
7215 ** Make *pConchPath point to the new name. Return SQLITE_OK on success
7216 ** or SQLITE_NOMEM if unable to obtain memory.
7218 ** The caller is responsible for ensuring that the allocated memory
7219 ** space is eventually freed.
7221 ** *pConchPath is set to NULL if a memory allocation error occurs.
7223 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7224 int i; /* Loop counter */
7225 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
7226 char *conchPath; /* buffer in which to construct conch name */
7228 /* Allocate space for the conch filename and initialize the name to
7229 ** the name of the original database file. */
7230 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
7231 if( conchPath==0 ){
7232 return SQLITE_NOMEM_BKPT;
7234 memcpy(conchPath, dbPath, len+1);
7236 /* now insert a "." before the last / character */
7237 for( i=(len-1); i>=0; i-- ){
7238 if( conchPath[i]=='/' ){
7239 i++;
7240 break;
7243 conchPath[i]='.';
7244 while ( i<len ){
7245 conchPath[i+1]=dbPath[i];
7246 i++;
7249 /* append the "-conch" suffix to the file */
7250 memcpy(&conchPath[i+1], "-conch", 7);
7251 assert( (int)strlen(conchPath) == len+7 );
7253 return SQLITE_OK;
7257 /* Takes a fully configured proxy locking-style unix file and switches
7258 ** the local lock file path
7260 static int switchLockProxyPath(unixFile *pFile, const char *path) {
7261 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7262 char *oldPath = pCtx->lockProxyPath;
7263 int rc = SQLITE_OK;
7265 if( pFile->eFileLock!=NO_LOCK ){
7266 return SQLITE_BUSY;
7269 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7270 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7271 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7272 return SQLITE_OK;
7273 }else{
7274 unixFile *lockProxy = pCtx->lockProxy;
7275 pCtx->lockProxy=NULL;
7276 pCtx->conchHeld = 0;
7277 if( lockProxy!=NULL ){
7278 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7279 if( rc ) return rc;
7280 sqlite3_free(lockProxy);
7282 sqlite3_free(oldPath);
7283 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7286 return rc;
7290 ** pFile is a file that has been opened by a prior xOpen call. dbPath
7291 ** is a string buffer at least MAXPATHLEN+1 characters in size.
7293 ** This routine find the filename associated with pFile and writes it
7294 ** int dbPath.
7296 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
7297 #if defined(__APPLE__)
7298 if( pFile->pMethod == &afpIoMethods ){
7299 /* afp style keeps a reference to the db path in the filePath field
7300 ** of the struct */
7301 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
7302 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7303 MAXPATHLEN);
7304 } else
7305 #endif
7306 if( pFile->pMethod == &dotlockIoMethods ){
7307 /* dot lock style uses the locking context to store the dot lock
7308 ** file path */
7309 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7310 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7311 }else{
7312 /* all other styles use the locking context to store the db file path */
7313 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
7314 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
7316 return SQLITE_OK;
7320 ** Takes an already filled in unix file and alters it so all file locking
7321 ** will be performed on the local proxy lock file. The following fields
7322 ** are preserved in the locking context so that they can be restored and
7323 ** the unix structure properly cleaned up at close time:
7324 ** ->lockingContext
7325 ** ->pMethod
7327 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7328 proxyLockingContext *pCtx;
7329 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7330 char *lockPath=NULL;
7331 int rc = SQLITE_OK;
7333 if( pFile->eFileLock!=NO_LOCK ){
7334 return SQLITE_BUSY;
7336 proxyGetDbPathForUnixFile(pFile, dbPath);
7337 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7338 lockPath=NULL;
7339 }else{
7340 lockPath=(char *)path;
7343 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
7344 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
7346 pCtx = sqlite3_malloc64( sizeof(*pCtx) );
7347 if( pCtx==0 ){
7348 return SQLITE_NOMEM_BKPT;
7350 memset(pCtx, 0, sizeof(*pCtx));
7352 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7353 if( rc==SQLITE_OK ){
7354 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7355 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7356 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7357 ** (c) the file system is read-only, then enable no-locking access.
7358 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7359 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7361 struct statfs fsInfo;
7362 struct stat conchInfo;
7363 int goLockless = 0;
7365 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
7366 int err = errno;
7367 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7368 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7371 if( goLockless ){
7372 pCtx->conchHeld = -1; /* read only FS/ lockless */
7373 rc = SQLITE_OK;
7377 if( rc==SQLITE_OK && lockPath ){
7378 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7381 if( rc==SQLITE_OK ){
7382 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7383 if( pCtx->dbPath==NULL ){
7384 rc = SQLITE_NOMEM_BKPT;
7387 if( rc==SQLITE_OK ){
7388 /* all memory is allocated, proxys are created and assigned,
7389 ** switch the locking context and pMethod then return.
7391 pCtx->oldLockingContext = pFile->lockingContext;
7392 pFile->lockingContext = pCtx;
7393 pCtx->pOldMethod = pFile->pMethod;
7394 pFile->pMethod = &proxyIoMethods;
7395 }else{
7396 if( pCtx->conchFile ){
7397 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
7398 sqlite3_free(pCtx->conchFile);
7400 sqlite3DbFree(0, pCtx->lockProxyPath);
7401 sqlite3_free(pCtx->conchFilePath);
7402 sqlite3_free(pCtx);
7404 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7405 (rc==SQLITE_OK ? "ok" : "failed")));
7406 return rc;
7411 ** This routine handles sqlite3_file_control() calls that are specific
7412 ** to proxy locking.
7414 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7415 switch( op ){
7416 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
7417 unixFile *pFile = (unixFile*)id;
7418 if( pFile->pMethod == &proxyIoMethods ){
7419 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7420 proxyTakeConch(pFile);
7421 if( pCtx->lockProxyPath ){
7422 *(const char **)pArg = pCtx->lockProxyPath;
7423 }else{
7424 *(const char **)pArg = ":auto: (not held)";
7426 } else {
7427 *(const char **)pArg = NULL;
7429 return SQLITE_OK;
7431 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
7432 unixFile *pFile = (unixFile*)id;
7433 int rc = SQLITE_OK;
7434 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7435 if( pArg==NULL || (const char *)pArg==0 ){
7436 if( isProxyStyle ){
7437 /* turn off proxy locking - not supported. If support is added for
7438 ** switching proxy locking mode off then it will need to fail if
7439 ** the journal mode is WAL mode.
7441 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7442 }else{
7443 /* turn off proxy locking - already off - NOOP */
7444 rc = SQLITE_OK;
7446 }else{
7447 const char *proxyPath = (const char *)pArg;
7448 if( isProxyStyle ){
7449 proxyLockingContext *pCtx =
7450 (proxyLockingContext*)pFile->lockingContext;
7451 if( !strcmp(pArg, ":auto:")
7452 || (pCtx->lockProxyPath &&
7453 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7455 rc = SQLITE_OK;
7456 }else{
7457 rc = switchLockProxyPath(pFile, proxyPath);
7459 }else{
7460 /* turn on proxy file locking */
7461 rc = proxyTransformUnixFile(pFile, proxyPath);
7464 return rc;
7466 default: {
7467 assert( 0 ); /* The call assures that only valid opcodes are sent */
7470 /*NOTREACHED*/
7471 return SQLITE_ERROR;
7475 ** Within this division (the proxying locking implementation) the procedures
7476 ** above this point are all utilities. The lock-related methods of the
7477 ** proxy-locking sqlite3_io_method object follow.
7482 ** This routine checks if there is a RESERVED lock held on the specified
7483 ** file by this or any other process. If such a lock is held, set *pResOut
7484 ** to a non-zero value otherwise *pResOut is set to zero. The return value
7485 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7487 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7488 unixFile *pFile = (unixFile*)id;
7489 int rc = proxyTakeConch(pFile);
7490 if( rc==SQLITE_OK ){
7491 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7492 if( pCtx->conchHeld>0 ){
7493 unixFile *proxy = pCtx->lockProxy;
7494 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7495 }else{ /* conchHeld < 0 is lockless */
7496 pResOut=0;
7499 return rc;
7503 ** Lock the file with the lock specified by parameter eFileLock - one
7504 ** of the following:
7506 ** (1) SHARED_LOCK
7507 ** (2) RESERVED_LOCK
7508 ** (3) PENDING_LOCK
7509 ** (4) EXCLUSIVE_LOCK
7511 ** Sometimes when requesting one lock state, additional lock states
7512 ** are inserted in between. The locking might fail on one of the later
7513 ** transitions leaving the lock state different from what it started but
7514 ** still short of its goal. The following chart shows the allowed
7515 ** transitions and the inserted intermediate states:
7517 ** UNLOCKED -> SHARED
7518 ** SHARED -> RESERVED
7519 ** SHARED -> (PENDING) -> EXCLUSIVE
7520 ** RESERVED -> (PENDING) -> EXCLUSIVE
7521 ** PENDING -> EXCLUSIVE
7523 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
7524 ** routine to lower a locking level.
7526 static int proxyLock(sqlite3_file *id, int eFileLock) {
7527 unixFile *pFile = (unixFile*)id;
7528 int rc = proxyTakeConch(pFile);
7529 if( rc==SQLITE_OK ){
7530 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7531 if( pCtx->conchHeld>0 ){
7532 unixFile *proxy = pCtx->lockProxy;
7533 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7534 pFile->eFileLock = proxy->eFileLock;
7535 }else{
7536 /* conchHeld < 0 is lockless */
7539 return rc;
7544 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
7545 ** must be either NO_LOCK or SHARED_LOCK.
7547 ** If the locking level of the file descriptor is already at or below
7548 ** the requested locking level, this routine is a no-op.
7550 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
7551 unixFile *pFile = (unixFile*)id;
7552 int rc = proxyTakeConch(pFile);
7553 if( rc==SQLITE_OK ){
7554 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7555 if( pCtx->conchHeld>0 ){
7556 unixFile *proxy = pCtx->lockProxy;
7557 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7558 pFile->eFileLock = proxy->eFileLock;
7559 }else{
7560 /* conchHeld < 0 is lockless */
7563 return rc;
7567 ** Close a file that uses proxy locks.
7569 static int proxyClose(sqlite3_file *id) {
7570 if( ALWAYS(id) ){
7571 unixFile *pFile = (unixFile*)id;
7572 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7573 unixFile *lockProxy = pCtx->lockProxy;
7574 unixFile *conchFile = pCtx->conchFile;
7575 int rc = SQLITE_OK;
7577 if( lockProxy ){
7578 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7579 if( rc ) return rc;
7580 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7581 if( rc ) return rc;
7582 sqlite3_free(lockProxy);
7583 pCtx->lockProxy = 0;
7585 if( conchFile ){
7586 if( pCtx->conchHeld ){
7587 rc = proxyReleaseConch(pFile);
7588 if( rc ) return rc;
7590 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7591 if( rc ) return rc;
7592 sqlite3_free(conchFile);
7594 sqlite3DbFree(0, pCtx->lockProxyPath);
7595 sqlite3_free(pCtx->conchFilePath);
7596 sqlite3DbFree(0, pCtx->dbPath);
7597 /* restore the original locking context and pMethod then close it */
7598 pFile->lockingContext = pCtx->oldLockingContext;
7599 pFile->pMethod = pCtx->pOldMethod;
7600 sqlite3_free(pCtx);
7601 return pFile->pMethod->xClose(id);
7603 return SQLITE_OK;
7608 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
7610 ** The proxy locking style is intended for use with AFP filesystems.
7611 ** And since AFP is only supported on MacOSX, the proxy locking is also
7612 ** restricted to MacOSX.
7615 ******************* End of the proxy lock implementation **********************
7616 ******************************************************************************/
7619 ** Initialize the operating system interface.
7621 ** This routine registers all VFS implementations for unix-like operating
7622 ** systems. This routine, and the sqlite3_os_end() routine that follows,
7623 ** should be the only routines in this file that are visible from other
7624 ** files.
7626 ** This routine is called once during SQLite initialization and by a
7627 ** single thread. The memory allocation and mutex subsystems have not
7628 ** necessarily been initialized when this routine is called, and so they
7629 ** should not be used.
7631 int sqlite3_os_init(void){
7633 ** The following macro defines an initializer for an sqlite3_vfs object.
7634 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7635 ** to the "finder" function. (pAppData is a pointer to a pointer because
7636 ** silly C90 rules prohibit a void* from being cast to a function pointer
7637 ** and so we have to go through the intermediate pointer to avoid problems
7638 ** when compiling with -pedantic-errors on GCC.)
7640 ** The FINDER parameter to this macro is the name of the pointer to the
7641 ** finder-function. The finder-function returns a pointer to the
7642 ** sqlite_io_methods object that implements the desired locking
7643 ** behaviors. See the division above that contains the IOMETHODS
7644 ** macro for addition information on finder-functions.
7646 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7647 ** object. But the "autolockIoFinder" available on MacOSX does a little
7648 ** more than that; it looks at the filesystem type that hosts the
7649 ** database file and tries to choose an locking method appropriate for
7650 ** that filesystem time.
7652 #define UNIXVFS(VFSNAME, FINDER) { \
7653 3, /* iVersion */ \
7654 sizeof(unixFile), /* szOsFile */ \
7655 MAX_PATHNAME, /* mxPathname */ \
7656 0, /* pNext */ \
7657 VFSNAME, /* zName */ \
7658 (void*)&FINDER, /* pAppData */ \
7659 unixOpen, /* xOpen */ \
7660 unixDelete, /* xDelete */ \
7661 unixAccess, /* xAccess */ \
7662 unixFullPathname, /* xFullPathname */ \
7663 unixDlOpen, /* xDlOpen */ \
7664 unixDlError, /* xDlError */ \
7665 unixDlSym, /* xDlSym */ \
7666 unixDlClose, /* xDlClose */ \
7667 unixRandomness, /* xRandomness */ \
7668 unixSleep, /* xSleep */ \
7669 unixCurrentTime, /* xCurrentTime */ \
7670 unixGetLastError, /* xGetLastError */ \
7671 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
7672 unixSetSystemCall, /* xSetSystemCall */ \
7673 unixGetSystemCall, /* xGetSystemCall */ \
7674 unixNextSystemCall, /* xNextSystemCall */ \
7678 ** All default VFSes for unix are contained in the following array.
7680 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7681 ** by the SQLite core when the VFS is registered. So the following
7682 ** array cannot be const.
7684 static sqlite3_vfs aVfs[] = {
7685 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
7686 UNIXVFS("unix", autolockIoFinder ),
7687 #elif OS_VXWORKS
7688 UNIXVFS("unix", vxworksIoFinder ),
7689 #else
7690 UNIXVFS("unix", posixIoFinder ),
7691 #endif
7692 UNIXVFS("unix-none", nolockIoFinder ),
7693 UNIXVFS("unix-dotfile", dotlockIoFinder ),
7694 UNIXVFS("unix-excl", posixIoFinder ),
7695 #if OS_VXWORKS
7696 UNIXVFS("unix-namedsem", semIoFinder ),
7697 #endif
7698 #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
7699 UNIXVFS("unix-posix", posixIoFinder ),
7700 #endif
7701 #if SQLITE_ENABLE_LOCKING_STYLE
7702 UNIXVFS("unix-flock", flockIoFinder ),
7703 #endif
7704 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
7705 UNIXVFS("unix-afp", afpIoFinder ),
7706 UNIXVFS("unix-nfs", nfsIoFinder ),
7707 UNIXVFS("unix-proxy", proxyIoFinder ),
7708 #endif
7710 unsigned int i; /* Loop counter */
7712 /* Double-check that the aSyscall[] array has been constructed
7713 ** correctly. See ticket [bb3a86e890c8e96ab] */
7714 assert( ArraySize(aSyscall)==29 );
7716 /* Register all VFSes defined in the aVfs[] array */
7717 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
7718 sqlite3_vfs_register(&aVfs[i], i==0);
7720 return SQLITE_OK;
7724 ** Shutdown the operating system interface.
7726 ** Some operating systems might need to do some cleanup in this routine,
7727 ** to release dynamically allocated objects. But not on unix.
7728 ** This routine is a no-op for unix.
7730 int sqlite3_os_end(void){
7731 return SQLITE_OK;
7734 #endif /* SQLITE_OS_UNIX */