Make the walIndexPage() routine about 3x faster by factoring out the seldom
[sqlite.git] / src / os_unix.c
blobcb2ae33d0a643432600a3ff9892c6b53eb8e201b
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 #if defined(HAVE_FCHOWN)
472 { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
473 #else
474 { "geteuid", (sqlite3_syscall_ptr)0, 0 },
475 #endif
476 #define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
478 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
479 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
480 #else
481 { "mmap", (sqlite3_syscall_ptr)0, 0 },
482 #endif
483 #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
485 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
486 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
487 #else
488 { "munmap", (sqlite3_syscall_ptr)0, 0 },
489 #endif
490 #define osMunmap ((int(*)(void*,size_t))aSyscall[23].pCurrent)
492 #if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
493 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
494 #else
495 { "mremap", (sqlite3_syscall_ptr)0, 0 },
496 #endif
497 #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
499 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
500 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
501 #else
502 { "getpagesize", (sqlite3_syscall_ptr)0, 0 },
503 #endif
504 #define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
506 #if defined(HAVE_READLINK)
507 { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
508 #else
509 { "readlink", (sqlite3_syscall_ptr)0, 0 },
510 #endif
511 #define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
513 #if defined(HAVE_LSTAT)
514 { "lstat", (sqlite3_syscall_ptr)lstat, 0 },
515 #else
516 { "lstat", (sqlite3_syscall_ptr)0, 0 },
517 #endif
518 #define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
520 #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
521 { "ioctl", (sqlite3_syscall_ptr)ioctl, 0 },
522 #else
523 { "ioctl", (sqlite3_syscall_ptr)0, 0 },
524 #endif
525 #define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent)
527 }; /* End of the overrideable system calls */
531 ** On some systems, calls to fchown() will trigger a message in a security
532 ** log if they come from non-root processes. So avoid calling fchown() if
533 ** we are not running as root.
535 static int robustFchown(int fd, uid_t uid, gid_t gid){
536 #if defined(HAVE_FCHOWN)
537 return osGeteuid() ? 0 : osFchown(fd,uid,gid);
538 #else
539 return 0;
540 #endif
544 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
545 ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
546 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
547 ** system call named zName.
549 static int unixSetSystemCall(
550 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
551 const char *zName, /* Name of system call to override */
552 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
554 unsigned int i;
555 int rc = SQLITE_NOTFOUND;
557 UNUSED_PARAMETER(pNotUsed);
558 if( zName==0 ){
559 /* If no zName is given, restore all system calls to their default
560 ** settings and return NULL
562 rc = SQLITE_OK;
563 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
564 if( aSyscall[i].pDefault ){
565 aSyscall[i].pCurrent = aSyscall[i].pDefault;
568 }else{
569 /* If zName is specified, operate on only the one system call
570 ** specified.
572 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
573 if( strcmp(zName, aSyscall[i].zName)==0 ){
574 if( aSyscall[i].pDefault==0 ){
575 aSyscall[i].pDefault = aSyscall[i].pCurrent;
577 rc = SQLITE_OK;
578 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
579 aSyscall[i].pCurrent = pNewFunc;
580 break;
584 return rc;
588 ** Return the value of a system call. Return NULL if zName is not a
589 ** recognized system call name. NULL is also returned if the system call
590 ** is currently undefined.
592 static sqlite3_syscall_ptr unixGetSystemCall(
593 sqlite3_vfs *pNotUsed,
594 const char *zName
596 unsigned int i;
598 UNUSED_PARAMETER(pNotUsed);
599 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
600 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
602 return 0;
606 ** Return the name of the first system call after zName. If zName==NULL
607 ** then return the name of the first system call. Return NULL if zName
608 ** is the last system call or if zName is not the name of a valid
609 ** system call.
611 static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
612 int i = -1;
614 UNUSED_PARAMETER(p);
615 if( zName ){
616 for(i=0; i<ArraySize(aSyscall)-1; i++){
617 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
620 for(i++; i<ArraySize(aSyscall); i++){
621 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
623 return 0;
627 ** Do not accept any file descriptor less than this value, in order to avoid
628 ** opening database file using file descriptors that are commonly used for
629 ** standard input, output, and error.
631 #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
632 # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
633 #endif
636 ** Invoke open(). Do so multiple times, until it either succeeds or
637 ** fails for some reason other than EINTR.
639 ** If the file creation mode "m" is 0 then set it to the default for
640 ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
641 ** 0644) as modified by the system umask. If m is not 0, then
642 ** make the file creation mode be exactly m ignoring the umask.
644 ** The m parameter will be non-zero only when creating -wal, -journal,
645 ** and -shm files. We want those files to have *exactly* the same
646 ** permissions as their original database, unadulterated by the umask.
647 ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
648 ** transaction crashes and leaves behind hot journals, then any
649 ** process that is able to write to the database will also be able to
650 ** recover the hot journals.
652 static int robust_open(const char *z, int f, mode_t m){
653 int fd;
654 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
655 while(1){
656 #if defined(O_CLOEXEC)
657 fd = osOpen(z,f|O_CLOEXEC,m2);
658 #else
659 fd = osOpen(z,f,m2);
660 #endif
661 if( fd<0 ){
662 if( errno==EINTR ) continue;
663 break;
665 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
666 osClose(fd);
667 sqlite3_log(SQLITE_WARNING,
668 "attempt to open \"%s\" as file descriptor %d", z, fd);
669 fd = -1;
670 if( osOpen("/dev/null", f, m)<0 ) break;
672 if( fd>=0 ){
673 if( m!=0 ){
674 struct stat statbuf;
675 if( osFstat(fd, &statbuf)==0
676 && statbuf.st_size==0
677 && (statbuf.st_mode&0777)!=m
679 osFchmod(fd, m);
682 #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
683 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
684 #endif
686 return fd;
690 ** Helper functions to obtain and relinquish the global mutex. The
691 ** global mutex is used to protect the unixInodeInfo and
692 ** vxworksFileId objects used by this file, all of which may be
693 ** shared by multiple threads.
695 ** Function unixMutexHeld() is used to assert() that the global mutex
696 ** is held when required. This function is only used as part of assert()
697 ** statements. e.g.
699 ** unixEnterMutex()
700 ** assert( unixMutexHeld() );
701 ** unixEnterLeave()
703 static sqlite3_mutex *unixBigLock = 0;
704 static void unixEnterMutex(void){
705 sqlite3_mutex_enter(unixBigLock);
707 static void unixLeaveMutex(void){
708 sqlite3_mutex_leave(unixBigLock);
710 #ifdef SQLITE_DEBUG
711 static int unixMutexHeld(void) {
712 return sqlite3_mutex_held(unixBigLock);
714 #endif
717 #ifdef SQLITE_HAVE_OS_TRACE
719 ** Helper function for printing out trace information from debugging
720 ** binaries. This returns the string representation of the supplied
721 ** integer lock-type.
723 static const char *azFileLock(int eFileLock){
724 switch( eFileLock ){
725 case NO_LOCK: return "NONE";
726 case SHARED_LOCK: return "SHARED";
727 case RESERVED_LOCK: return "RESERVED";
728 case PENDING_LOCK: return "PENDING";
729 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
731 return "ERROR";
733 #endif
735 #ifdef SQLITE_LOCK_TRACE
737 ** Print out information about all locking operations.
739 ** This routine is used for troubleshooting locks on multithreaded
740 ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
741 ** command-line option on the compiler. This code is normally
742 ** turned off.
744 static int lockTrace(int fd, int op, struct flock *p){
745 char *zOpName, *zType;
746 int s;
747 int savedErrno;
748 if( op==F_GETLK ){
749 zOpName = "GETLK";
750 }else if( op==F_SETLK ){
751 zOpName = "SETLK";
752 }else{
753 s = osFcntl(fd, op, p);
754 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
755 return s;
757 if( p->l_type==F_RDLCK ){
758 zType = "RDLCK";
759 }else if( p->l_type==F_WRLCK ){
760 zType = "WRLCK";
761 }else if( p->l_type==F_UNLCK ){
762 zType = "UNLCK";
763 }else{
764 assert( 0 );
766 assert( p->l_whence==SEEK_SET );
767 s = osFcntl(fd, op, p);
768 savedErrno = errno;
769 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
770 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
771 (int)p->l_pid, s);
772 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
773 struct flock l2;
774 l2 = *p;
775 osFcntl(fd, F_GETLK, &l2);
776 if( l2.l_type==F_RDLCK ){
777 zType = "RDLCK";
778 }else if( l2.l_type==F_WRLCK ){
779 zType = "WRLCK";
780 }else if( l2.l_type==F_UNLCK ){
781 zType = "UNLCK";
782 }else{
783 assert( 0 );
785 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
786 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
788 errno = savedErrno;
789 return s;
791 #undef osFcntl
792 #define osFcntl lockTrace
793 #endif /* SQLITE_LOCK_TRACE */
796 ** Retry ftruncate() calls that fail due to EINTR
798 ** All calls to ftruncate() within this file should be made through
799 ** this wrapper. On the Android platform, bypassing the logic below
800 ** could lead to a corrupt database.
802 static int robust_ftruncate(int h, sqlite3_int64 sz){
803 int rc;
804 #ifdef __ANDROID__
805 /* On Android, ftruncate() always uses 32-bit offsets, even if
806 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
807 ** truncate a file to any size larger than 2GiB. Silently ignore any
808 ** such attempts. */
809 if( sz>(sqlite3_int64)0x7FFFFFFF ){
810 rc = SQLITE_OK;
811 }else
812 #endif
813 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
814 return rc;
818 ** This routine translates a standard POSIX errno code into something
819 ** useful to the clients of the sqlite3 functions. Specifically, it is
820 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
821 ** and a variety of "please close the file descriptor NOW" errors into
822 ** SQLITE_IOERR
824 ** Errors during initialization of locks, or file system support for locks,
825 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
827 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
828 assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
829 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
830 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
831 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
832 switch (posixError) {
833 case EACCES:
834 case EAGAIN:
835 case ETIMEDOUT:
836 case EBUSY:
837 case EINTR:
838 case ENOLCK:
839 /* random NFS retry error, unless during file system support
840 * introspection, in which it actually means what it says */
841 return SQLITE_BUSY;
843 case EPERM:
844 return SQLITE_PERM;
846 default:
847 return sqliteIOErr;
852 /******************************************************************************
853 ****************** Begin Unique File ID Utility Used By VxWorks ***************
855 ** On most versions of unix, we can get a unique ID for a file by concatenating
856 ** the device number and the inode number. But this does not work on VxWorks.
857 ** On VxWorks, a unique file id must be based on the canonical filename.
859 ** A pointer to an instance of the following structure can be used as a
860 ** unique file ID in VxWorks. Each instance of this structure contains
861 ** a copy of the canonical filename. There is also a reference count.
862 ** The structure is reclaimed when the number of pointers to it drops to
863 ** zero.
865 ** There are never very many files open at one time and lookups are not
866 ** a performance-critical path, so it is sufficient to put these
867 ** structures on a linked list.
869 struct vxworksFileId {
870 struct vxworksFileId *pNext; /* Next in a list of them all */
871 int nRef; /* Number of references to this one */
872 int nName; /* Length of the zCanonicalName[] string */
873 char *zCanonicalName; /* Canonical filename */
876 #if OS_VXWORKS
878 ** All unique filenames are held on a linked list headed by this
879 ** variable:
881 static struct vxworksFileId *vxworksFileList = 0;
884 ** Simplify a filename into its canonical form
885 ** by making the following changes:
887 ** * removing any trailing and duplicate /
888 ** * convert /./ into just /
889 ** * convert /A/../ where A is any simple name into just /
891 ** Changes are made in-place. Return the new name length.
893 ** The original filename is in z[0..n-1]. Return the number of
894 ** characters in the simplified name.
896 static int vxworksSimplifyName(char *z, int n){
897 int i, j;
898 while( n>1 && z[n-1]=='/' ){ n--; }
899 for(i=j=0; i<n; i++){
900 if( z[i]=='/' ){
901 if( z[i+1]=='/' ) continue;
902 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
903 i += 1;
904 continue;
906 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
907 while( j>0 && z[j-1]!='/' ){ j--; }
908 if( j>0 ){ j--; }
909 i += 2;
910 continue;
913 z[j++] = z[i];
915 z[j] = 0;
916 return j;
920 ** Find a unique file ID for the given absolute pathname. Return
921 ** a pointer to the vxworksFileId object. This pointer is the unique
922 ** file ID.
924 ** The nRef field of the vxworksFileId object is incremented before
925 ** the object is returned. A new vxworksFileId object is created
926 ** and added to the global list if necessary.
928 ** If a memory allocation error occurs, return NULL.
930 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
931 struct vxworksFileId *pNew; /* search key and new file ID */
932 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
933 int n; /* Length of zAbsoluteName string */
935 assert( zAbsoluteName[0]=='/' );
936 n = (int)strlen(zAbsoluteName);
937 pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
938 if( pNew==0 ) return 0;
939 pNew->zCanonicalName = (char*)&pNew[1];
940 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
941 n = vxworksSimplifyName(pNew->zCanonicalName, n);
943 /* Search for an existing entry that matching the canonical name.
944 ** If found, increment the reference count and return a pointer to
945 ** the existing file ID.
947 unixEnterMutex();
948 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
949 if( pCandidate->nName==n
950 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
952 sqlite3_free(pNew);
953 pCandidate->nRef++;
954 unixLeaveMutex();
955 return pCandidate;
959 /* No match was found. We will make a new file ID */
960 pNew->nRef = 1;
961 pNew->nName = n;
962 pNew->pNext = vxworksFileList;
963 vxworksFileList = pNew;
964 unixLeaveMutex();
965 return pNew;
969 ** Decrement the reference count on a vxworksFileId object. Free
970 ** the object when the reference count reaches zero.
972 static void vxworksReleaseFileId(struct vxworksFileId *pId){
973 unixEnterMutex();
974 assert( pId->nRef>0 );
975 pId->nRef--;
976 if( pId->nRef==0 ){
977 struct vxworksFileId **pp;
978 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
979 assert( *pp==pId );
980 *pp = pId->pNext;
981 sqlite3_free(pId);
983 unixLeaveMutex();
985 #endif /* OS_VXWORKS */
986 /*************** End of Unique File ID Utility Used By VxWorks ****************
987 ******************************************************************************/
990 /******************************************************************************
991 *************************** Posix Advisory Locking ****************************
993 ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
994 ** section 6.5.2.2 lines 483 through 490 specify that when a process
995 ** sets or clears a lock, that operation overrides any prior locks set
996 ** by the same process. It does not explicitly say so, but this implies
997 ** that it overrides locks set by the same process using a different
998 ** file descriptor. Consider this test case:
1000 ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
1001 ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
1003 ** Suppose ./file1 and ./file2 are really the same file (because
1004 ** one is a hard or symbolic link to the other) then if you set
1005 ** an exclusive lock on fd1, then try to get an exclusive lock
1006 ** on fd2, it works. I would have expected the second lock to
1007 ** fail since there was already a lock on the file due to fd1.
1008 ** But not so. Since both locks came from the same process, the
1009 ** second overrides the first, even though they were on different
1010 ** file descriptors opened on different file names.
1012 ** This means that we cannot use POSIX locks to synchronize file access
1013 ** among competing threads of the same process. POSIX locks will work fine
1014 ** to synchronize access for threads in separate processes, but not
1015 ** threads within the same process.
1017 ** To work around the problem, SQLite has to manage file locks internally
1018 ** on its own. Whenever a new database is opened, we have to find the
1019 ** specific inode of the database file (the inode is determined by the
1020 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
1021 ** and check for locks already existing on that inode. When locks are
1022 ** created or removed, we have to look at our own internal record of the
1023 ** locks to see if another thread has previously set a lock on that same
1024 ** inode.
1026 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
1027 ** For VxWorks, we have to use the alternative unique ID system based on
1028 ** canonical filename and implemented in the previous division.)
1030 ** The sqlite3_file structure for POSIX is no longer just an integer file
1031 ** descriptor. It is now a structure that holds the integer file
1032 ** descriptor and a pointer to a structure that describes the internal
1033 ** locks on the corresponding inode. There is one locking structure
1034 ** per inode, so if the same inode is opened twice, both unixFile structures
1035 ** point to the same locking structure. The locking structure keeps
1036 ** a reference count (so we will know when to delete it) and a "cnt"
1037 ** field that tells us its internal lock status. cnt==0 means the
1038 ** file is unlocked. cnt==-1 means the file has an exclusive lock.
1039 ** cnt>0 means there are cnt shared locks on the file.
1041 ** Any attempt to lock or unlock a file first checks the locking
1042 ** structure. The fcntl() system call is only invoked to set a
1043 ** POSIX lock if the internal lock structure transitions between
1044 ** a locked and an unlocked state.
1046 ** But wait: there are yet more problems with POSIX advisory locks.
1048 ** If you close a file descriptor that points to a file that has locks,
1049 ** all locks on that file that are owned by the current process are
1050 ** released. To work around this problem, each unixInodeInfo object
1051 ** maintains a count of the number of pending locks on tha inode.
1052 ** When an attempt is made to close an unixFile, if there are
1053 ** other unixFile open on the same inode that are holding locks, the call
1054 ** to close() the file descriptor is deferred until all of the locks clear.
1055 ** The unixInodeInfo structure keeps a list of file descriptors that need to
1056 ** be closed and that list is walked (and cleared) when the last lock
1057 ** clears.
1059 ** Yet another problem: LinuxThreads do not play well with posix locks.
1061 ** Many older versions of linux use the LinuxThreads library which is
1062 ** not posix compliant. Under LinuxThreads, a lock created by thread
1063 ** A cannot be modified or overridden by a different thread B.
1064 ** Only thread A can modify the lock. Locking behavior is correct
1065 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
1066 ** on linux - with NPTL a lock created by thread A can override locks
1067 ** in thread B. But there is no way to know at compile-time which
1068 ** threading library is being used. So there is no way to know at
1069 ** compile-time whether or not thread A can override locks on thread B.
1070 ** One has to do a run-time check to discover the behavior of the
1071 ** current process.
1073 ** SQLite used to support LinuxThreads. But support for LinuxThreads
1074 ** was dropped beginning with version 3.7.0. SQLite will still work with
1075 ** LinuxThreads provided that (1) there is no more than one connection
1076 ** per database file in the same process and (2) database connections
1077 ** do not move across threads.
1081 ** An instance of the following structure serves as the key used
1082 ** to locate a particular unixInodeInfo object.
1084 struct unixFileId {
1085 dev_t dev; /* Device number */
1086 #if OS_VXWORKS
1087 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
1088 #else
1089 /* We are told that some versions of Android contain a bug that
1090 ** sizes ino_t at only 32-bits instead of 64-bits. (See
1091 ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
1092 ** To work around this, always allocate 64-bits for the inode number.
1093 ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
1094 ** but that should not be a big deal. */
1095 /* WAS: ino_t ino; */
1096 u64 ino; /* Inode number */
1097 #endif
1101 ** An instance of the following structure is allocated for each open
1102 ** inode. Or, on LinuxThreads, there is one of these structures for
1103 ** each inode opened by each thread.
1105 ** A single inode can have multiple file descriptors, so each unixFile
1106 ** structure contains a pointer to an instance of this object and this
1107 ** object keeps a count of the number of unixFile pointing to it.
1109 struct unixInodeInfo {
1110 struct unixFileId fileId; /* The lookup key */
1111 int nShared; /* Number of SHARED locks held */
1112 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1113 unsigned char bProcessLock; /* An exclusive process lock is held */
1114 int nRef; /* Number of pointers to this structure */
1115 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1116 int nLock; /* Number of outstanding file locks */
1117 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1118 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1119 unixInodeInfo *pPrev; /* .... doubly linked */
1120 #if SQLITE_ENABLE_LOCKING_STYLE
1121 unsigned long long sharedByte; /* for AFP simulated shared lock */
1122 #endif
1123 #if OS_VXWORKS
1124 sem_t *pSem; /* Named POSIX semaphore */
1125 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
1126 #endif
1130 ** A lists of all unixInodeInfo objects.
1132 static unixInodeInfo *inodeList = 0; /* All unixInodeInfo objects */
1133 static unsigned int nUnusedFd = 0; /* Total unused file descriptors */
1137 ** This function - unixLogErrorAtLine(), is only ever called via the macro
1138 ** unixLogError().
1140 ** It is invoked after an error occurs in an OS function and errno has been
1141 ** set. It logs a message using sqlite3_log() containing the current value of
1142 ** errno and, if possible, the human-readable equivalent from strerror() or
1143 ** strerror_r().
1145 ** The first argument passed to the macro should be the error code that
1146 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1147 ** The two subsequent arguments should be the name of the OS function that
1148 ** failed (e.g. "unlink", "open") and the associated file-system path,
1149 ** if any.
1151 #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1152 static int unixLogErrorAtLine(
1153 int errcode, /* SQLite error code */
1154 const char *zFunc, /* Name of OS function that failed */
1155 const char *zPath, /* File path associated with error */
1156 int iLine /* Source line number where error occurred */
1158 char *zErr; /* Message from strerror() or equivalent */
1159 int iErrno = errno; /* Saved syscall error number */
1161 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1162 ** the strerror() function to obtain the human-readable error message
1163 ** equivalent to errno. Otherwise, use strerror_r().
1165 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1166 char aErr[80];
1167 memset(aErr, 0, sizeof(aErr));
1168 zErr = aErr;
1170 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
1171 ** assume that the system provides the GNU version of strerror_r() that
1172 ** returns a pointer to a buffer containing the error message. That pointer
1173 ** may point to aErr[], or it may point to some static storage somewhere.
1174 ** Otherwise, assume that the system provides the POSIX version of
1175 ** strerror_r(), which always writes an error message into aErr[].
1177 ** If the code incorrectly assumes that it is the POSIX version that is
1178 ** available, the error message will often be an empty string. Not a
1179 ** huge problem. Incorrectly concluding that the GNU version is available
1180 ** could lead to a segfault though.
1182 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1183 zErr =
1184 # endif
1185 strerror_r(iErrno, aErr, sizeof(aErr)-1);
1187 #elif SQLITE_THREADSAFE
1188 /* This is a threadsafe build, but strerror_r() is not available. */
1189 zErr = "";
1190 #else
1191 /* Non-threadsafe build, use strerror(). */
1192 zErr = strerror(iErrno);
1193 #endif
1195 if( zPath==0 ) zPath = "";
1196 sqlite3_log(errcode,
1197 "os_unix.c:%d: (%d) %s(%s) - %s",
1198 iLine, iErrno, zFunc, zPath, zErr
1201 return errcode;
1205 ** Close a file descriptor.
1207 ** We assume that close() almost always works, since it is only in a
1208 ** very sick application or on a very sick platform that it might fail.
1209 ** If it does fail, simply leak the file descriptor, but do log the
1210 ** error.
1212 ** Note that it is not safe to retry close() after EINTR since the
1213 ** file descriptor might have already been reused by another thread.
1214 ** So we don't even try to recover from an EINTR. Just log the error
1215 ** and move on.
1217 static void robust_close(unixFile *pFile, int h, int lineno){
1218 if( osClose(h) ){
1219 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1220 pFile ? pFile->zPath : 0, lineno);
1225 ** Set the pFile->lastErrno. Do this in a subroutine as that provides
1226 ** a convenient place to set a breakpoint.
1228 static void storeLastErrno(unixFile *pFile, int error){
1229 pFile->lastErrno = error;
1233 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
1235 static void closePendingFds(unixFile *pFile){
1236 unixInodeInfo *pInode = pFile->pInode;
1237 UnixUnusedFd *p;
1238 UnixUnusedFd *pNext;
1239 for(p=pInode->pUnused; p; p=pNext){
1240 pNext = p->pNext;
1241 robust_close(pFile, p->fd, __LINE__);
1242 sqlite3_free(p);
1243 nUnusedFd--;
1245 pInode->pUnused = 0;
1249 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
1251 ** The mutex entered using the unixEnterMutex() function must be held
1252 ** when this function is called.
1254 static void releaseInodeInfo(unixFile *pFile){
1255 unixInodeInfo *pInode = pFile->pInode;
1256 assert( unixMutexHeld() );
1257 if( ALWAYS(pInode) ){
1258 pInode->nRef--;
1259 if( pInode->nRef==0 ){
1260 assert( pInode->pShmNode==0 );
1261 closePendingFds(pFile);
1262 if( pInode->pPrev ){
1263 assert( pInode->pPrev->pNext==pInode );
1264 pInode->pPrev->pNext = pInode->pNext;
1265 }else{
1266 assert( inodeList==pInode );
1267 inodeList = pInode->pNext;
1269 if( pInode->pNext ){
1270 assert( pInode->pNext->pPrev==pInode );
1271 pInode->pNext->pPrev = pInode->pPrev;
1273 sqlite3_free(pInode);
1276 assert( inodeList!=0 || nUnusedFd==0 );
1280 ** Given a file descriptor, locate the unixInodeInfo object that
1281 ** describes that file descriptor. Create a new one if necessary. The
1282 ** return value might be uninitialized if an error occurs.
1284 ** The mutex entered using the unixEnterMutex() function must be held
1285 ** when this function is called.
1287 ** Return an appropriate error code.
1289 static int findInodeInfo(
1290 unixFile *pFile, /* Unix file with file desc used in the key */
1291 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
1293 int rc; /* System call return code */
1294 int fd; /* The file descriptor for pFile */
1295 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1296 struct stat statbuf; /* Low-level file information */
1297 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
1299 assert( unixMutexHeld() );
1301 /* Get low-level information about the file that we can used to
1302 ** create a unique name for the file.
1304 fd = pFile->h;
1305 rc = osFstat(fd, &statbuf);
1306 if( rc!=0 ){
1307 storeLastErrno(pFile, errno);
1308 #if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
1309 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1310 #endif
1311 return SQLITE_IOERR;
1314 #ifdef __APPLE__
1315 /* On OS X on an msdos filesystem, the inode number is reported
1316 ** incorrectly for zero-size files. See ticket #3260. To work
1317 ** around this problem (we consider it a bug in OS X, not SQLite)
1318 ** we always increase the file size to 1 by writing a single byte
1319 ** prior to accessing the inode number. The one byte written is
1320 ** an ASCII 'S' character which also happens to be the first byte
1321 ** in the header of every SQLite database. In this way, if there
1322 ** is a race condition such that another thread has already populated
1323 ** the first page of the database, no damage is done.
1325 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
1326 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
1327 if( rc!=1 ){
1328 storeLastErrno(pFile, errno);
1329 return SQLITE_IOERR;
1331 rc = osFstat(fd, &statbuf);
1332 if( rc!=0 ){
1333 storeLastErrno(pFile, errno);
1334 return SQLITE_IOERR;
1337 #endif
1339 memset(&fileId, 0, sizeof(fileId));
1340 fileId.dev = statbuf.st_dev;
1341 #if OS_VXWORKS
1342 fileId.pId = pFile->pId;
1343 #else
1344 fileId.ino = (u64)statbuf.st_ino;
1345 #endif
1346 assert( inodeList!=0 || nUnusedFd==0 );
1347 pInode = inodeList;
1348 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1349 pInode = pInode->pNext;
1351 if( pInode==0 ){
1352 pInode = sqlite3_malloc64( sizeof(*pInode) );
1353 if( pInode==0 ){
1354 return SQLITE_NOMEM_BKPT;
1356 memset(pInode, 0, sizeof(*pInode));
1357 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1358 pInode->nRef = 1;
1359 pInode->pNext = inodeList;
1360 pInode->pPrev = 0;
1361 if( inodeList ) inodeList->pPrev = pInode;
1362 inodeList = pInode;
1363 }else{
1364 pInode->nRef++;
1366 *ppInode = pInode;
1367 return SQLITE_OK;
1371 ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1373 static int fileHasMoved(unixFile *pFile){
1374 #if OS_VXWORKS
1375 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1376 #else
1377 struct stat buf;
1378 return pFile->pInode!=0 &&
1379 (osStat(pFile->zPath, &buf)!=0
1380 || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
1381 #endif
1386 ** Check a unixFile that is a database. Verify the following:
1388 ** (1) There is exactly one hard link on the file
1389 ** (2) The file is not a symbolic link
1390 ** (3) The file has not been renamed or unlinked
1392 ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1394 static void verifyDbFile(unixFile *pFile){
1395 struct stat buf;
1396 int rc;
1398 /* These verifications occurs for the main database only */
1399 if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
1401 rc = osFstat(pFile->h, &buf);
1402 if( rc!=0 ){
1403 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
1404 return;
1406 if( buf.st_nlink==0 ){
1407 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
1408 return;
1410 if( buf.st_nlink>1 ){
1411 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
1412 return;
1414 if( fileHasMoved(pFile) ){
1415 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
1416 return;
1422 ** This routine checks if there is a RESERVED lock held on the specified
1423 ** file by this or any other process. If such a lock is held, set *pResOut
1424 ** to a non-zero value otherwise *pResOut is set to zero. The return value
1425 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1427 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
1428 int rc = SQLITE_OK;
1429 int reserved = 0;
1430 unixFile *pFile = (unixFile*)id;
1432 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1434 assert( pFile );
1435 assert( pFile->eFileLock<=SHARED_LOCK );
1436 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
1438 /* Check if a thread in this process holds such a lock */
1439 if( pFile->pInode->eFileLock>SHARED_LOCK ){
1440 reserved = 1;
1443 /* Otherwise see if some other process holds it.
1445 #ifndef __DJGPP__
1446 if( !reserved && !pFile->pInode->bProcessLock ){
1447 struct flock lock;
1448 lock.l_whence = SEEK_SET;
1449 lock.l_start = RESERVED_BYTE;
1450 lock.l_len = 1;
1451 lock.l_type = F_WRLCK;
1452 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1453 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1454 storeLastErrno(pFile, errno);
1455 } else if( lock.l_type!=F_UNLCK ){
1456 reserved = 1;
1459 #endif
1461 unixLeaveMutex();
1462 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
1464 *pResOut = reserved;
1465 return rc;
1469 ** Attempt to set a system-lock on the file pFile. The lock is
1470 ** described by pLock.
1472 ** If the pFile was opened read/write from unix-excl, then the only lock
1473 ** ever obtained is an exclusive lock, and it is obtained exactly once
1474 ** the first time any lock is attempted. All subsequent system locking
1475 ** operations become no-ops. Locking operations still happen internally,
1476 ** in order to coordinate access between separate database connections
1477 ** within this process, but all of that is handled in memory and the
1478 ** operating system does not participate.
1480 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1481 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1482 ** and is read-only.
1484 ** Zero is returned if the call completes successfully, or -1 if a call
1485 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
1487 static int unixFileLock(unixFile *pFile, struct flock *pLock){
1488 int rc;
1489 unixInodeInfo *pInode = pFile->pInode;
1490 assert( unixMutexHeld() );
1491 assert( pInode!=0 );
1492 if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
1493 if( pInode->bProcessLock==0 ){
1494 struct flock lock;
1495 assert( pInode->nLock==0 );
1496 lock.l_whence = SEEK_SET;
1497 lock.l_start = SHARED_FIRST;
1498 lock.l_len = SHARED_SIZE;
1499 lock.l_type = F_WRLCK;
1500 rc = osFcntl(pFile->h, F_SETLK, &lock);
1501 if( rc<0 ) return rc;
1502 pInode->bProcessLock = 1;
1503 pInode->nLock++;
1504 }else{
1505 rc = 0;
1507 }else{
1508 rc = osFcntl(pFile->h, F_SETLK, pLock);
1510 return rc;
1514 ** Lock the file with the lock specified by parameter eFileLock - one
1515 ** of the following:
1517 ** (1) SHARED_LOCK
1518 ** (2) RESERVED_LOCK
1519 ** (3) PENDING_LOCK
1520 ** (4) EXCLUSIVE_LOCK
1522 ** Sometimes when requesting one lock state, additional lock states
1523 ** are inserted in between. The locking might fail on one of the later
1524 ** transitions leaving the lock state different from what it started but
1525 ** still short of its goal. The following chart shows the allowed
1526 ** transitions and the inserted intermediate states:
1528 ** UNLOCKED -> SHARED
1529 ** SHARED -> RESERVED
1530 ** SHARED -> (PENDING) -> EXCLUSIVE
1531 ** RESERVED -> (PENDING) -> EXCLUSIVE
1532 ** PENDING -> EXCLUSIVE
1534 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
1535 ** routine to lower a locking level.
1537 static int unixLock(sqlite3_file *id, int eFileLock){
1538 /* The following describes the implementation of the various locks and
1539 ** lock transitions in terms of the POSIX advisory shared and exclusive
1540 ** lock primitives (called read-locks and write-locks below, to avoid
1541 ** confusion with SQLite lock names). The algorithms are complicated
1542 ** slightly in order to be compatible with Windows95 systems simultaneously
1543 ** accessing the same database file, in case that is ever required.
1545 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1546 ** byte', each single bytes at well known offsets, and the 'shared byte
1547 ** range', a range of 510 bytes at a well known offset.
1549 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1550 ** byte'. If this is successful, 'shared byte range' is read-locked
1551 ** and the lock on the 'pending byte' released. (Legacy note: When
1552 ** SQLite was first developed, Windows95 systems were still very common,
1553 ** and Widnows95 lacks a shared-lock capability. So on Windows95, a
1554 ** single randomly selected by from the 'shared byte range' is locked.
1555 ** Windows95 is now pretty much extinct, but this work-around for the
1556 ** lack of shared-locks on Windows95 lives on, for backwards
1557 ** compatibility.)
1559 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1560 ** A RESERVED lock is implemented by grabbing a write-lock on the
1561 ** 'reserved byte'.
1563 ** A process may only obtain a PENDING lock after it has obtained a
1564 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1565 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1566 ** obtained, but existing SHARED locks are allowed to persist. A process
1567 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1568 ** This property is used by the algorithm for rolling back a journal file
1569 ** after a crash.
1571 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1572 ** implemented by obtaining a write-lock on the entire 'shared byte
1573 ** range'. Since all other locks require a read-lock on one of the bytes
1574 ** within this range, this ensures that no other locks are held on the
1575 ** database.
1577 int rc = SQLITE_OK;
1578 unixFile *pFile = (unixFile*)id;
1579 unixInodeInfo *pInode;
1580 struct flock lock;
1581 int tErrno = 0;
1583 assert( pFile );
1584 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1585 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
1586 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
1587 osGetpid(0)));
1589 /* If there is already a lock of this type or more restrictive on the
1590 ** unixFile, do nothing. Don't use the end_lock: exit path, as
1591 ** unixEnterMutex() hasn't been called yet.
1593 if( pFile->eFileLock>=eFileLock ){
1594 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1595 azFileLock(eFileLock)));
1596 return SQLITE_OK;
1599 /* Make sure the locking sequence is correct.
1600 ** (1) We never move from unlocked to anything higher than shared lock.
1601 ** (2) SQLite never explicitly requests a pendig lock.
1602 ** (3) A shared lock is always held when a reserve lock is requested.
1604 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1605 assert( eFileLock!=PENDING_LOCK );
1606 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
1608 /* This mutex is needed because pFile->pInode is shared across threads
1610 unixEnterMutex();
1611 pInode = pFile->pInode;
1613 /* If some thread using this PID has a lock via a different unixFile*
1614 ** handle that precludes the requested lock, return BUSY.
1616 if( (pFile->eFileLock!=pInode->eFileLock &&
1617 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
1619 rc = SQLITE_BUSY;
1620 goto end_lock;
1623 /* If a SHARED lock is requested, and some thread using this PID already
1624 ** has a SHARED or RESERVED lock, then increment reference counts and
1625 ** return SQLITE_OK.
1627 if( eFileLock==SHARED_LOCK &&
1628 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
1629 assert( eFileLock==SHARED_LOCK );
1630 assert( pFile->eFileLock==0 );
1631 assert( pInode->nShared>0 );
1632 pFile->eFileLock = SHARED_LOCK;
1633 pInode->nShared++;
1634 pInode->nLock++;
1635 goto end_lock;
1639 /* A PENDING lock is needed before acquiring a SHARED lock and before
1640 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1641 ** be released.
1643 lock.l_len = 1L;
1644 lock.l_whence = SEEK_SET;
1645 if( eFileLock==SHARED_LOCK
1646 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
1648 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
1649 lock.l_start = PENDING_BYTE;
1650 if( unixFileLock(pFile, &lock) ){
1651 tErrno = errno;
1652 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1653 if( rc!=SQLITE_BUSY ){
1654 storeLastErrno(pFile, tErrno);
1656 goto end_lock;
1661 /* If control gets to this point, then actually go ahead and make
1662 ** operating system calls for the specified lock.
1664 if( eFileLock==SHARED_LOCK ){
1665 assert( pInode->nShared==0 );
1666 assert( pInode->eFileLock==0 );
1667 assert( rc==SQLITE_OK );
1669 /* Now get the read-lock */
1670 lock.l_start = SHARED_FIRST;
1671 lock.l_len = SHARED_SIZE;
1672 if( unixFileLock(pFile, &lock) ){
1673 tErrno = errno;
1674 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1677 /* Drop the temporary PENDING lock */
1678 lock.l_start = PENDING_BYTE;
1679 lock.l_len = 1L;
1680 lock.l_type = F_UNLCK;
1681 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1682 /* This could happen with a network mount */
1683 tErrno = errno;
1684 rc = SQLITE_IOERR_UNLOCK;
1687 if( rc ){
1688 if( rc!=SQLITE_BUSY ){
1689 storeLastErrno(pFile, tErrno);
1691 goto end_lock;
1692 }else{
1693 pFile->eFileLock = SHARED_LOCK;
1694 pInode->nLock++;
1695 pInode->nShared = 1;
1697 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
1698 /* We are trying for an exclusive lock but another thread in this
1699 ** same process is still holding a shared lock. */
1700 rc = SQLITE_BUSY;
1701 }else{
1702 /* The request was for a RESERVED or EXCLUSIVE lock. It is
1703 ** assumed that there is a SHARED or greater lock on the file
1704 ** already.
1706 assert( 0!=pFile->eFileLock );
1707 lock.l_type = F_WRLCK;
1709 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1710 if( eFileLock==RESERVED_LOCK ){
1711 lock.l_start = RESERVED_BYTE;
1712 lock.l_len = 1L;
1713 }else{
1714 lock.l_start = SHARED_FIRST;
1715 lock.l_len = SHARED_SIZE;
1718 if( unixFileLock(pFile, &lock) ){
1719 tErrno = errno;
1720 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1721 if( rc!=SQLITE_BUSY ){
1722 storeLastErrno(pFile, tErrno);
1728 #ifdef SQLITE_DEBUG
1729 /* Set up the transaction-counter change checking flags when
1730 ** transitioning from a SHARED to a RESERVED lock. The change
1731 ** from SHARED to RESERVED marks the beginning of a normal
1732 ** write operation (not a hot journal rollback).
1734 if( rc==SQLITE_OK
1735 && pFile->eFileLock<=SHARED_LOCK
1736 && eFileLock==RESERVED_LOCK
1738 pFile->transCntrChng = 0;
1739 pFile->dbUpdate = 0;
1740 pFile->inNormalWrite = 1;
1742 #endif
1745 if( rc==SQLITE_OK ){
1746 pFile->eFileLock = eFileLock;
1747 pInode->eFileLock = eFileLock;
1748 }else if( eFileLock==EXCLUSIVE_LOCK ){
1749 pFile->eFileLock = PENDING_LOCK;
1750 pInode->eFileLock = PENDING_LOCK;
1753 end_lock:
1754 unixLeaveMutex();
1755 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1756 rc==SQLITE_OK ? "ok" : "failed"));
1757 return rc;
1761 ** Add the file descriptor used by file handle pFile to the corresponding
1762 ** pUnused list.
1764 static void setPendingFd(unixFile *pFile){
1765 unixInodeInfo *pInode = pFile->pInode;
1766 UnixUnusedFd *p = pFile->pPreallocatedUnused;
1767 p->pNext = pInode->pUnused;
1768 pInode->pUnused = p;
1769 pFile->h = -1;
1770 pFile->pPreallocatedUnused = 0;
1771 nUnusedFd++;
1775 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
1776 ** must be either NO_LOCK or SHARED_LOCK.
1778 ** If the locking level of the file descriptor is already at or below
1779 ** the requested locking level, this routine is a no-op.
1781 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1782 ** the byte range is divided into 2 parts and the first part is unlocked then
1783 ** set to a read lock, then the other part is simply unlocked. This works
1784 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1785 ** remove the write lock on a region when a read lock is set.
1787 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
1788 unixFile *pFile = (unixFile*)id;
1789 unixInodeInfo *pInode;
1790 struct flock lock;
1791 int rc = SQLITE_OK;
1793 assert( pFile );
1794 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
1795 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
1796 osGetpid(0)));
1798 assert( eFileLock<=SHARED_LOCK );
1799 if( pFile->eFileLock<=eFileLock ){
1800 return SQLITE_OK;
1802 unixEnterMutex();
1803 pInode = pFile->pInode;
1804 assert( pInode->nShared!=0 );
1805 if( pFile->eFileLock>SHARED_LOCK ){
1806 assert( pInode->eFileLock==pFile->eFileLock );
1808 #ifdef SQLITE_DEBUG
1809 /* When reducing a lock such that other processes can start
1810 ** reading the database file again, make sure that the
1811 ** transaction counter was updated if any part of the database
1812 ** file changed. If the transaction counter is not updated,
1813 ** other connections to the same file might not realize that
1814 ** the file has changed and hence might not know to flush their
1815 ** cache. The use of a stale cache can lead to database corruption.
1817 pFile->inNormalWrite = 0;
1818 #endif
1820 /* downgrading to a shared lock on NFS involves clearing the write lock
1821 ** before establishing the readlock - to avoid a race condition we downgrade
1822 ** the lock in 2 blocks, so that part of the range will be covered by a
1823 ** write lock until the rest is covered by a read lock:
1824 ** 1: [WWWWW]
1825 ** 2: [....W]
1826 ** 3: [RRRRW]
1827 ** 4: [RRRR.]
1829 if( eFileLock==SHARED_LOCK ){
1830 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
1831 (void)handleNFSUnlock;
1832 assert( handleNFSUnlock==0 );
1833 #endif
1834 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
1835 if( handleNFSUnlock ){
1836 int tErrno; /* Error code from system call errors */
1837 off_t divSize = SHARED_SIZE - 1;
1839 lock.l_type = F_UNLCK;
1840 lock.l_whence = SEEK_SET;
1841 lock.l_start = SHARED_FIRST;
1842 lock.l_len = divSize;
1843 if( unixFileLock(pFile, &lock)==(-1) ){
1844 tErrno = errno;
1845 rc = SQLITE_IOERR_UNLOCK;
1846 storeLastErrno(pFile, tErrno);
1847 goto end_unlock;
1849 lock.l_type = F_RDLCK;
1850 lock.l_whence = SEEK_SET;
1851 lock.l_start = SHARED_FIRST;
1852 lock.l_len = divSize;
1853 if( unixFileLock(pFile, &lock)==(-1) ){
1854 tErrno = errno;
1855 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1856 if( IS_LOCK_ERROR(rc) ){
1857 storeLastErrno(pFile, tErrno);
1859 goto end_unlock;
1861 lock.l_type = F_UNLCK;
1862 lock.l_whence = SEEK_SET;
1863 lock.l_start = SHARED_FIRST+divSize;
1864 lock.l_len = SHARED_SIZE-divSize;
1865 if( unixFileLock(pFile, &lock)==(-1) ){
1866 tErrno = errno;
1867 rc = SQLITE_IOERR_UNLOCK;
1868 storeLastErrno(pFile, tErrno);
1869 goto end_unlock;
1871 }else
1872 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1874 lock.l_type = F_RDLCK;
1875 lock.l_whence = SEEK_SET;
1876 lock.l_start = SHARED_FIRST;
1877 lock.l_len = SHARED_SIZE;
1878 if( unixFileLock(pFile, &lock) ){
1879 /* In theory, the call to unixFileLock() cannot fail because another
1880 ** process is holding an incompatible lock. If it does, this
1881 ** indicates that the other process is not following the locking
1882 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1883 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1884 ** an assert to fail). */
1885 rc = SQLITE_IOERR_RDLOCK;
1886 storeLastErrno(pFile, errno);
1887 goto end_unlock;
1891 lock.l_type = F_UNLCK;
1892 lock.l_whence = SEEK_SET;
1893 lock.l_start = PENDING_BYTE;
1894 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
1895 if( unixFileLock(pFile, &lock)==0 ){
1896 pInode->eFileLock = SHARED_LOCK;
1897 }else{
1898 rc = SQLITE_IOERR_UNLOCK;
1899 storeLastErrno(pFile, errno);
1900 goto end_unlock;
1903 if( eFileLock==NO_LOCK ){
1904 /* Decrement the shared lock counter. Release the lock using an
1905 ** OS call only when all threads in this same process have released
1906 ** the lock.
1908 pInode->nShared--;
1909 if( pInode->nShared==0 ){
1910 lock.l_type = F_UNLCK;
1911 lock.l_whence = SEEK_SET;
1912 lock.l_start = lock.l_len = 0L;
1913 if( unixFileLock(pFile, &lock)==0 ){
1914 pInode->eFileLock = NO_LOCK;
1915 }else{
1916 rc = SQLITE_IOERR_UNLOCK;
1917 storeLastErrno(pFile, errno);
1918 pInode->eFileLock = NO_LOCK;
1919 pFile->eFileLock = NO_LOCK;
1923 /* Decrement the count of locks against this same file. When the
1924 ** count reaches zero, close any other file descriptors whose close
1925 ** was deferred because of outstanding locks.
1927 pInode->nLock--;
1928 assert( pInode->nLock>=0 );
1929 if( pInode->nLock==0 ){
1930 closePendingFds(pFile);
1934 end_unlock:
1935 unixLeaveMutex();
1936 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
1937 return rc;
1941 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
1942 ** must be either NO_LOCK or SHARED_LOCK.
1944 ** If the locking level of the file descriptor is already at or below
1945 ** the requested locking level, this routine is a no-op.
1947 static int unixUnlock(sqlite3_file *id, int eFileLock){
1948 #if SQLITE_MAX_MMAP_SIZE>0
1949 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
1950 #endif
1951 return posixUnlock(id, eFileLock, 0);
1954 #if SQLITE_MAX_MMAP_SIZE>0
1955 static int unixMapfile(unixFile *pFd, i64 nByte);
1956 static void unixUnmapfile(unixFile *pFd);
1957 #endif
1960 ** This function performs the parts of the "close file" operation
1961 ** common to all locking schemes. It closes the directory and file
1962 ** handles, if they are valid, and sets all fields of the unixFile
1963 ** structure to 0.
1965 ** It is *not* necessary to hold the mutex when this routine is called,
1966 ** even on VxWorks. A mutex will be acquired on VxWorks by the
1967 ** vxworksReleaseFileId() routine.
1969 static int closeUnixFile(sqlite3_file *id){
1970 unixFile *pFile = (unixFile*)id;
1971 #if SQLITE_MAX_MMAP_SIZE>0
1972 unixUnmapfile(pFile);
1973 #endif
1974 if( pFile->h>=0 ){
1975 robust_close(pFile, pFile->h, __LINE__);
1976 pFile->h = -1;
1978 #if OS_VXWORKS
1979 if( pFile->pId ){
1980 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
1981 osUnlink(pFile->pId->zCanonicalName);
1983 vxworksReleaseFileId(pFile->pId);
1984 pFile->pId = 0;
1986 #endif
1987 #ifdef SQLITE_UNLINK_AFTER_CLOSE
1988 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
1989 osUnlink(pFile->zPath);
1990 sqlite3_free(*(char**)&pFile->zPath);
1991 pFile->zPath = 0;
1993 #endif
1994 OSTRACE(("CLOSE %-3d\n", pFile->h));
1995 OpenCounter(-1);
1996 sqlite3_free(pFile->pPreallocatedUnused);
1997 memset(pFile, 0, sizeof(unixFile));
1998 return SQLITE_OK;
2002 ** Close a file.
2004 static int unixClose(sqlite3_file *id){
2005 int rc = SQLITE_OK;
2006 unixFile *pFile = (unixFile *)id;
2007 verifyDbFile(pFile);
2008 unixUnlock(id, NO_LOCK);
2009 unixEnterMutex();
2011 /* unixFile.pInode is always valid here. Otherwise, a different close
2012 ** routine (e.g. nolockClose()) would be called instead.
2014 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
2015 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
2016 /* If there are outstanding locks, do not actually close the file just
2017 ** yet because that would clear those locks. Instead, add the file
2018 ** descriptor to pInode->pUnused list. It will be automatically closed
2019 ** when the last lock is cleared.
2021 setPendingFd(pFile);
2023 releaseInodeInfo(pFile);
2024 rc = closeUnixFile(id);
2025 unixLeaveMutex();
2026 return rc;
2029 /************** End of the posix advisory lock implementation *****************
2030 ******************************************************************************/
2032 /******************************************************************************
2033 ****************************** No-op Locking **********************************
2035 ** Of the various locking implementations available, this is by far the
2036 ** simplest: locking is ignored. No attempt is made to lock the database
2037 ** file for reading or writing.
2039 ** This locking mode is appropriate for use on read-only databases
2040 ** (ex: databases that are burned into CD-ROM, for example.) It can
2041 ** also be used if the application employs some external mechanism to
2042 ** prevent simultaneous access of the same database by two or more
2043 ** database connections. But there is a serious risk of database
2044 ** corruption if this locking mode is used in situations where multiple
2045 ** database connections are accessing the same database file at the same
2046 ** time and one or more of those connections are writing.
2049 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
2050 UNUSED_PARAMETER(NotUsed);
2051 *pResOut = 0;
2052 return SQLITE_OK;
2054 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
2055 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2056 return SQLITE_OK;
2058 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
2059 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2060 return SQLITE_OK;
2064 ** Close the file.
2066 static int nolockClose(sqlite3_file *id) {
2067 return closeUnixFile(id);
2070 /******************* End of the no-op lock implementation *********************
2071 ******************************************************************************/
2073 /******************************************************************************
2074 ************************* Begin dot-file Locking ******************************
2076 ** The dotfile locking implementation uses the existence of separate lock
2077 ** files (really a directory) to control access to the database. This works
2078 ** on just about every filesystem imaginable. But there are serious downsides:
2080 ** (1) There is zero concurrency. A single reader blocks all other
2081 ** connections from reading or writing the database.
2083 ** (2) An application crash or power loss can leave stale lock files
2084 ** sitting around that need to be cleared manually.
2086 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
2087 ** other locking strategy is available.
2089 ** Dotfile locking works by creating a subdirectory in the same directory as
2090 ** the database and with the same name but with a ".lock" extension added.
2091 ** The existence of a lock directory implies an EXCLUSIVE lock. All other
2092 ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
2096 ** The file suffix added to the data base filename in order to create the
2097 ** lock directory.
2099 #define DOTLOCK_SUFFIX ".lock"
2102 ** This routine checks if there is a RESERVED lock held on the specified
2103 ** file by this or any other process. If such a lock is held, set *pResOut
2104 ** to a non-zero value otherwise *pResOut is set to zero. The return value
2105 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2107 ** In dotfile locking, either a lock exists or it does not. So in this
2108 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
2109 ** is held on the file and false if the file is unlocked.
2111 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2112 int rc = SQLITE_OK;
2113 int reserved = 0;
2114 unixFile *pFile = (unixFile*)id;
2116 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2118 assert( pFile );
2119 reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
2120 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
2121 *pResOut = reserved;
2122 return rc;
2126 ** Lock the file with the lock specified by parameter eFileLock - one
2127 ** of the following:
2129 ** (1) SHARED_LOCK
2130 ** (2) RESERVED_LOCK
2131 ** (3) PENDING_LOCK
2132 ** (4) EXCLUSIVE_LOCK
2134 ** Sometimes when requesting one lock state, additional lock states
2135 ** are inserted in between. The locking might fail on one of the later
2136 ** transitions leaving the lock state different from what it started but
2137 ** still short of its goal. The following chart shows the allowed
2138 ** transitions and the inserted intermediate states:
2140 ** UNLOCKED -> SHARED
2141 ** SHARED -> RESERVED
2142 ** SHARED -> (PENDING) -> EXCLUSIVE
2143 ** RESERVED -> (PENDING) -> EXCLUSIVE
2144 ** PENDING -> EXCLUSIVE
2146 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
2147 ** routine to lower a locking level.
2149 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
2150 ** But we track the other locking levels internally.
2152 static int dotlockLock(sqlite3_file *id, int eFileLock) {
2153 unixFile *pFile = (unixFile*)id;
2154 char *zLockFile = (char *)pFile->lockingContext;
2155 int rc = SQLITE_OK;
2158 /* If we have any lock, then the lock file already exists. All we have
2159 ** to do is adjust our internal record of the lock level.
2161 if( pFile->eFileLock > NO_LOCK ){
2162 pFile->eFileLock = eFileLock;
2163 /* Always update the timestamp on the old file */
2164 #ifdef HAVE_UTIME
2165 utime(zLockFile, NULL);
2166 #else
2167 utimes(zLockFile, NULL);
2168 #endif
2169 return SQLITE_OK;
2172 /* grab an exclusive lock */
2173 rc = osMkdir(zLockFile, 0777);
2174 if( rc<0 ){
2175 /* failed to open/create the lock directory */
2176 int tErrno = errno;
2177 if( EEXIST == tErrno ){
2178 rc = SQLITE_BUSY;
2179 } else {
2180 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2181 if( rc!=SQLITE_BUSY ){
2182 storeLastErrno(pFile, tErrno);
2185 return rc;
2188 /* got it, set the type and return ok */
2189 pFile->eFileLock = eFileLock;
2190 return rc;
2194 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
2195 ** must be either NO_LOCK or SHARED_LOCK.
2197 ** If the locking level of the file descriptor is already at or below
2198 ** the requested locking level, this routine is a no-op.
2200 ** When the locking level reaches NO_LOCK, delete the lock file.
2202 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
2203 unixFile *pFile = (unixFile*)id;
2204 char *zLockFile = (char *)pFile->lockingContext;
2205 int rc;
2207 assert( pFile );
2208 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
2209 pFile->eFileLock, osGetpid(0)));
2210 assert( eFileLock<=SHARED_LOCK );
2212 /* no-op if possible */
2213 if( pFile->eFileLock==eFileLock ){
2214 return SQLITE_OK;
2217 /* To downgrade to shared, simply update our internal notion of the
2218 ** lock state. No need to mess with the file on disk.
2220 if( eFileLock==SHARED_LOCK ){
2221 pFile->eFileLock = SHARED_LOCK;
2222 return SQLITE_OK;
2225 /* To fully unlock the database, delete the lock file */
2226 assert( eFileLock==NO_LOCK );
2227 rc = osRmdir(zLockFile);
2228 if( rc<0 ){
2229 int tErrno = errno;
2230 if( tErrno==ENOENT ){
2231 rc = SQLITE_OK;
2232 }else{
2233 rc = SQLITE_IOERR_UNLOCK;
2234 storeLastErrno(pFile, tErrno);
2236 return rc;
2238 pFile->eFileLock = NO_LOCK;
2239 return SQLITE_OK;
2243 ** Close a file. Make sure the lock has been released before closing.
2245 static int dotlockClose(sqlite3_file *id) {
2246 unixFile *pFile = (unixFile*)id;
2247 assert( id!=0 );
2248 dotlockUnlock(id, NO_LOCK);
2249 sqlite3_free(pFile->lockingContext);
2250 return closeUnixFile(id);
2252 /****************** End of the dot-file lock implementation *******************
2253 ******************************************************************************/
2255 /******************************************************************************
2256 ************************** Begin flock Locking ********************************
2258 ** Use the flock() system call to do file locking.
2260 ** flock() locking is like dot-file locking in that the various
2261 ** fine-grain locking levels supported by SQLite are collapsed into
2262 ** a single exclusive lock. In other words, SHARED, RESERVED, and
2263 ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2264 ** still works when you do this, but concurrency is reduced since
2265 ** only a single process can be reading the database at a time.
2267 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
2269 #if SQLITE_ENABLE_LOCKING_STYLE
2272 ** Retry flock() calls that fail with EINTR
2274 #ifdef EINTR
2275 static int robust_flock(int fd, int op){
2276 int rc;
2277 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2278 return rc;
2280 #else
2281 # define robust_flock(a,b) flock(a,b)
2282 #endif
2286 ** This routine checks if there is a RESERVED lock held on the specified
2287 ** file by this or any other process. If such a lock is held, set *pResOut
2288 ** to a non-zero value otherwise *pResOut is set to zero. The return value
2289 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2291 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2292 int rc = SQLITE_OK;
2293 int reserved = 0;
2294 unixFile *pFile = (unixFile*)id;
2296 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2298 assert( pFile );
2300 /* Check if a thread in this process holds such a lock */
2301 if( pFile->eFileLock>SHARED_LOCK ){
2302 reserved = 1;
2305 /* Otherwise see if some other process holds it. */
2306 if( !reserved ){
2307 /* attempt to get the lock */
2308 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
2309 if( !lrc ){
2310 /* got the lock, unlock it */
2311 lrc = robust_flock(pFile->h, LOCK_UN);
2312 if ( lrc ) {
2313 int tErrno = errno;
2314 /* unlock failed with an error */
2315 lrc = SQLITE_IOERR_UNLOCK;
2316 storeLastErrno(pFile, tErrno);
2317 rc = lrc;
2319 } else {
2320 int tErrno = errno;
2321 reserved = 1;
2322 /* someone else might have it reserved */
2323 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2324 if( IS_LOCK_ERROR(lrc) ){
2325 storeLastErrno(pFile, tErrno);
2326 rc = lrc;
2330 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
2332 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2333 if( (rc & 0xff) == SQLITE_IOERR ){
2334 rc = SQLITE_OK;
2335 reserved=1;
2337 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2338 *pResOut = reserved;
2339 return rc;
2343 ** Lock the file with the lock specified by parameter eFileLock - one
2344 ** of the following:
2346 ** (1) SHARED_LOCK
2347 ** (2) RESERVED_LOCK
2348 ** (3) PENDING_LOCK
2349 ** (4) EXCLUSIVE_LOCK
2351 ** Sometimes when requesting one lock state, additional lock states
2352 ** are inserted in between. The locking might fail on one of the later
2353 ** transitions leaving the lock state different from what it started but
2354 ** still short of its goal. The following chart shows the allowed
2355 ** transitions and the inserted intermediate states:
2357 ** UNLOCKED -> SHARED
2358 ** SHARED -> RESERVED
2359 ** SHARED -> (PENDING) -> EXCLUSIVE
2360 ** RESERVED -> (PENDING) -> EXCLUSIVE
2361 ** PENDING -> EXCLUSIVE
2363 ** flock() only really support EXCLUSIVE locks. We track intermediate
2364 ** lock states in the sqlite3_file structure, but all locks SHARED or
2365 ** above are really EXCLUSIVE locks and exclude all other processes from
2366 ** access the file.
2368 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
2369 ** routine to lower a locking level.
2371 static int flockLock(sqlite3_file *id, int eFileLock) {
2372 int rc = SQLITE_OK;
2373 unixFile *pFile = (unixFile*)id;
2375 assert( pFile );
2377 /* if we already have a lock, it is exclusive.
2378 ** Just adjust level and punt on outta here. */
2379 if (pFile->eFileLock > NO_LOCK) {
2380 pFile->eFileLock = eFileLock;
2381 return SQLITE_OK;
2384 /* grab an exclusive lock */
2386 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
2387 int tErrno = errno;
2388 /* didn't get, must be busy */
2389 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2390 if( IS_LOCK_ERROR(rc) ){
2391 storeLastErrno(pFile, tErrno);
2393 } else {
2394 /* got it, set the type and return ok */
2395 pFile->eFileLock = eFileLock;
2397 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2398 rc==SQLITE_OK ? "ok" : "failed"));
2399 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2400 if( (rc & 0xff) == SQLITE_IOERR ){
2401 rc = SQLITE_BUSY;
2403 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2404 return rc;
2409 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
2410 ** must be either NO_LOCK or SHARED_LOCK.
2412 ** If the locking level of the file descriptor is already at or below
2413 ** the requested locking level, this routine is a no-op.
2415 static int flockUnlock(sqlite3_file *id, int eFileLock) {
2416 unixFile *pFile = (unixFile*)id;
2418 assert( pFile );
2419 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2420 pFile->eFileLock, osGetpid(0)));
2421 assert( eFileLock<=SHARED_LOCK );
2423 /* no-op if possible */
2424 if( pFile->eFileLock==eFileLock ){
2425 return SQLITE_OK;
2428 /* shared can just be set because we always have an exclusive */
2429 if (eFileLock==SHARED_LOCK) {
2430 pFile->eFileLock = eFileLock;
2431 return SQLITE_OK;
2434 /* no, really, unlock. */
2435 if( robust_flock(pFile->h, LOCK_UN) ){
2436 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2437 return SQLITE_OK;
2438 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2439 return SQLITE_IOERR_UNLOCK;
2440 }else{
2441 pFile->eFileLock = NO_LOCK;
2442 return SQLITE_OK;
2447 ** Close a file.
2449 static int flockClose(sqlite3_file *id) {
2450 assert( id!=0 );
2451 flockUnlock(id, NO_LOCK);
2452 return closeUnixFile(id);
2455 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2457 /******************* End of the flock lock implementation *********************
2458 ******************************************************************************/
2460 /******************************************************************************
2461 ************************ Begin Named Semaphore Locking ************************
2463 ** Named semaphore locking is only supported on VxWorks.
2465 ** Semaphore locking is like dot-lock and flock in that it really only
2466 ** supports EXCLUSIVE locking. Only a single process can read or write
2467 ** the database file at a time. This reduces potential concurrency, but
2468 ** makes the lock implementation much easier.
2470 #if OS_VXWORKS
2473 ** This routine checks if there is a RESERVED lock held on the specified
2474 ** file by this or any other process. If such a lock is held, set *pResOut
2475 ** to a non-zero value otherwise *pResOut is set to zero. The return value
2476 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2478 static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
2479 int rc = SQLITE_OK;
2480 int reserved = 0;
2481 unixFile *pFile = (unixFile*)id;
2483 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2485 assert( pFile );
2487 /* Check if a thread in this process holds such a lock */
2488 if( pFile->eFileLock>SHARED_LOCK ){
2489 reserved = 1;
2492 /* Otherwise see if some other process holds it. */
2493 if( !reserved ){
2494 sem_t *pSem = pFile->pInode->pSem;
2496 if( sem_trywait(pSem)==-1 ){
2497 int tErrno = errno;
2498 if( EAGAIN != tErrno ){
2499 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2500 storeLastErrno(pFile, tErrno);
2501 } else {
2502 /* someone else has the lock when we are in NO_LOCK */
2503 reserved = (pFile->eFileLock < SHARED_LOCK);
2505 }else{
2506 /* we could have it if we want it */
2507 sem_post(pSem);
2510 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
2512 *pResOut = reserved;
2513 return rc;
2517 ** Lock the file with the lock specified by parameter eFileLock - one
2518 ** of the following:
2520 ** (1) SHARED_LOCK
2521 ** (2) RESERVED_LOCK
2522 ** (3) PENDING_LOCK
2523 ** (4) EXCLUSIVE_LOCK
2525 ** Sometimes when requesting one lock state, additional lock states
2526 ** are inserted in between. The locking might fail on one of the later
2527 ** transitions leaving the lock state different from what it started but
2528 ** still short of its goal. The following chart shows the allowed
2529 ** transitions and the inserted intermediate states:
2531 ** UNLOCKED -> SHARED
2532 ** SHARED -> RESERVED
2533 ** SHARED -> (PENDING) -> EXCLUSIVE
2534 ** RESERVED -> (PENDING) -> EXCLUSIVE
2535 ** PENDING -> EXCLUSIVE
2537 ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2538 ** lock states in the sqlite3_file structure, but all locks SHARED or
2539 ** above are really EXCLUSIVE locks and exclude all other processes from
2540 ** access the file.
2542 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
2543 ** routine to lower a locking level.
2545 static int semXLock(sqlite3_file *id, int eFileLock) {
2546 unixFile *pFile = (unixFile*)id;
2547 sem_t *pSem = pFile->pInode->pSem;
2548 int rc = SQLITE_OK;
2550 /* if we already have a lock, it is exclusive.
2551 ** Just adjust level and punt on outta here. */
2552 if (pFile->eFileLock > NO_LOCK) {
2553 pFile->eFileLock = eFileLock;
2554 rc = SQLITE_OK;
2555 goto sem_end_lock;
2558 /* lock semaphore now but bail out when already locked. */
2559 if( sem_trywait(pSem)==-1 ){
2560 rc = SQLITE_BUSY;
2561 goto sem_end_lock;
2564 /* got it, set the type and return ok */
2565 pFile->eFileLock = eFileLock;
2567 sem_end_lock:
2568 return rc;
2572 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
2573 ** must be either NO_LOCK or SHARED_LOCK.
2575 ** If the locking level of the file descriptor is already at or below
2576 ** the requested locking level, this routine is a no-op.
2578 static int semXUnlock(sqlite3_file *id, int eFileLock) {
2579 unixFile *pFile = (unixFile*)id;
2580 sem_t *pSem = pFile->pInode->pSem;
2582 assert( pFile );
2583 assert( pSem );
2584 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2585 pFile->eFileLock, osGetpid(0)));
2586 assert( eFileLock<=SHARED_LOCK );
2588 /* no-op if possible */
2589 if( pFile->eFileLock==eFileLock ){
2590 return SQLITE_OK;
2593 /* shared can just be set because we always have an exclusive */
2594 if (eFileLock==SHARED_LOCK) {
2595 pFile->eFileLock = eFileLock;
2596 return SQLITE_OK;
2599 /* no, really unlock. */
2600 if ( sem_post(pSem)==-1 ) {
2601 int rc, tErrno = errno;
2602 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2603 if( IS_LOCK_ERROR(rc) ){
2604 storeLastErrno(pFile, tErrno);
2606 return rc;
2608 pFile->eFileLock = NO_LOCK;
2609 return SQLITE_OK;
2613 ** Close a file.
2615 static int semXClose(sqlite3_file *id) {
2616 if( id ){
2617 unixFile *pFile = (unixFile*)id;
2618 semXUnlock(id, NO_LOCK);
2619 assert( pFile );
2620 unixEnterMutex();
2621 releaseInodeInfo(pFile);
2622 unixLeaveMutex();
2623 closeUnixFile(id);
2625 return SQLITE_OK;
2628 #endif /* OS_VXWORKS */
2630 ** Named semaphore locking is only available on VxWorks.
2632 *************** End of the named semaphore lock implementation ****************
2633 ******************************************************************************/
2636 /******************************************************************************
2637 *************************** Begin AFP Locking *********************************
2639 ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2640 ** on Apple Macintosh computers - both OS9 and OSX.
2642 ** Third-party implementations of AFP are available. But this code here
2643 ** only works on OSX.
2646 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2648 ** The afpLockingContext structure contains all afp lock specific state
2650 typedef struct afpLockingContext afpLockingContext;
2651 struct afpLockingContext {
2652 int reserved;
2653 const char *dbPath; /* Name of the open file */
2656 struct ByteRangeLockPB2
2658 unsigned long long offset; /* offset to first byte to lock */
2659 unsigned long long length; /* nbr of bytes to lock */
2660 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2661 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2662 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2663 int fd; /* file desc to assoc this lock with */
2666 #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
2669 ** This is a utility for setting or clearing a bit-range lock on an
2670 ** AFP filesystem.
2672 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2674 static int afpSetLock(
2675 const char *path, /* Name of the file to be locked or unlocked */
2676 unixFile *pFile, /* Open file descriptor on path */
2677 unsigned long long offset, /* First byte to be locked */
2678 unsigned long long length, /* Number of bytes to lock */
2679 int setLockFlag /* True to set lock. False to clear lock */
2681 struct ByteRangeLockPB2 pb;
2682 int err;
2684 pb.unLockFlag = setLockFlag ? 0 : 1;
2685 pb.startEndFlag = 0;
2686 pb.offset = offset;
2687 pb.length = length;
2688 pb.fd = pFile->h;
2690 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
2691 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
2692 offset, length));
2693 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2694 if ( err==-1 ) {
2695 int rc;
2696 int tErrno = errno;
2697 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2698 path, tErrno, strerror(tErrno)));
2699 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2700 rc = SQLITE_BUSY;
2701 #else
2702 rc = sqliteErrorFromPosixError(tErrno,
2703 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
2704 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
2705 if( IS_LOCK_ERROR(rc) ){
2706 storeLastErrno(pFile, tErrno);
2708 return rc;
2709 } else {
2710 return SQLITE_OK;
2715 ** This routine checks if there is a RESERVED lock held on the specified
2716 ** file by this or any other process. If such a lock is held, set *pResOut
2717 ** to a non-zero value otherwise *pResOut is set to zero. The return value
2718 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2720 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
2721 int rc = SQLITE_OK;
2722 int reserved = 0;
2723 unixFile *pFile = (unixFile*)id;
2724 afpLockingContext *context;
2726 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2728 assert( pFile );
2729 context = (afpLockingContext *) pFile->lockingContext;
2730 if( context->reserved ){
2731 *pResOut = 1;
2732 return SQLITE_OK;
2734 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
2736 /* Check if a thread in this process holds such a lock */
2737 if( pFile->pInode->eFileLock>SHARED_LOCK ){
2738 reserved = 1;
2741 /* Otherwise see if some other process holds it.
2743 if( !reserved ){
2744 /* lock the RESERVED byte */
2745 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
2746 if( SQLITE_OK==lrc ){
2747 /* if we succeeded in taking the reserved lock, unlock it to restore
2748 ** the original state */
2749 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2750 } else {
2751 /* if we failed to get the lock then someone else must have it */
2752 reserved = 1;
2754 if( IS_LOCK_ERROR(lrc) ){
2755 rc=lrc;
2759 unixLeaveMutex();
2760 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
2762 *pResOut = reserved;
2763 return rc;
2767 ** Lock the file with the lock specified by parameter eFileLock - one
2768 ** of the following:
2770 ** (1) SHARED_LOCK
2771 ** (2) RESERVED_LOCK
2772 ** (3) PENDING_LOCK
2773 ** (4) EXCLUSIVE_LOCK
2775 ** Sometimes when requesting one lock state, additional lock states
2776 ** are inserted in between. The locking might fail on one of the later
2777 ** transitions leaving the lock state different from what it started but
2778 ** still short of its goal. The following chart shows the allowed
2779 ** transitions and the inserted intermediate states:
2781 ** UNLOCKED -> SHARED
2782 ** SHARED -> RESERVED
2783 ** SHARED -> (PENDING) -> EXCLUSIVE
2784 ** RESERVED -> (PENDING) -> EXCLUSIVE
2785 ** PENDING -> EXCLUSIVE
2787 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
2788 ** routine to lower a locking level.
2790 static int afpLock(sqlite3_file *id, int eFileLock){
2791 int rc = SQLITE_OK;
2792 unixFile *pFile = (unixFile*)id;
2793 unixInodeInfo *pInode = pFile->pInode;
2794 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2796 assert( pFile );
2797 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2798 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
2799 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
2801 /* If there is already a lock of this type or more restrictive on the
2802 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
2803 ** unixEnterMutex() hasn't been called yet.
2805 if( pFile->eFileLock>=eFileLock ){
2806 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2807 azFileLock(eFileLock)));
2808 return SQLITE_OK;
2811 /* Make sure the locking sequence is correct
2812 ** (1) We never move from unlocked to anything higher than shared lock.
2813 ** (2) SQLite never explicitly requests a pendig lock.
2814 ** (3) A shared lock is always held when a reserve lock is requested.
2816 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2817 assert( eFileLock!=PENDING_LOCK );
2818 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
2820 /* This mutex is needed because pFile->pInode is shared across threads
2822 unixEnterMutex();
2823 pInode = pFile->pInode;
2825 /* If some thread using this PID has a lock via a different unixFile*
2826 ** handle that precludes the requested lock, return BUSY.
2828 if( (pFile->eFileLock!=pInode->eFileLock &&
2829 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
2831 rc = SQLITE_BUSY;
2832 goto afp_end_lock;
2835 /* If a SHARED lock is requested, and some thread using this PID already
2836 ** has a SHARED or RESERVED lock, then increment reference counts and
2837 ** return SQLITE_OK.
2839 if( eFileLock==SHARED_LOCK &&
2840 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
2841 assert( eFileLock==SHARED_LOCK );
2842 assert( pFile->eFileLock==0 );
2843 assert( pInode->nShared>0 );
2844 pFile->eFileLock = SHARED_LOCK;
2845 pInode->nShared++;
2846 pInode->nLock++;
2847 goto afp_end_lock;
2850 /* A PENDING lock is needed before acquiring a SHARED lock and before
2851 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2852 ** be released.
2854 if( eFileLock==SHARED_LOCK
2855 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
2857 int failed;
2858 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
2859 if (failed) {
2860 rc = failed;
2861 goto afp_end_lock;
2865 /* If control gets to this point, then actually go ahead and make
2866 ** operating system calls for the specified lock.
2868 if( eFileLock==SHARED_LOCK ){
2869 int lrc1, lrc2, lrc1Errno = 0;
2870 long lk, mask;
2872 assert( pInode->nShared==0 );
2873 assert( pInode->eFileLock==0 );
2875 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
2876 /* Now get the read-lock SHARED_LOCK */
2877 /* note that the quality of the randomness doesn't matter that much */
2878 lk = random();
2879 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
2880 lrc1 = afpSetLock(context->dbPath, pFile,
2881 SHARED_FIRST+pInode->sharedByte, 1, 1);
2882 if( IS_LOCK_ERROR(lrc1) ){
2883 lrc1Errno = pFile->lastErrno;
2885 /* Drop the temporary PENDING lock */
2886 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
2888 if( IS_LOCK_ERROR(lrc1) ) {
2889 storeLastErrno(pFile, lrc1Errno);
2890 rc = lrc1;
2891 goto afp_end_lock;
2892 } else if( IS_LOCK_ERROR(lrc2) ){
2893 rc = lrc2;
2894 goto afp_end_lock;
2895 } else if( lrc1 != SQLITE_OK ) {
2896 rc = lrc1;
2897 } else {
2898 pFile->eFileLock = SHARED_LOCK;
2899 pInode->nLock++;
2900 pInode->nShared = 1;
2902 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
2903 /* We are trying for an exclusive lock but another thread in this
2904 ** same process is still holding a shared lock. */
2905 rc = SQLITE_BUSY;
2906 }else{
2907 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2908 ** assumed that there is a SHARED or greater lock on the file
2909 ** already.
2911 int failed = 0;
2912 assert( 0!=pFile->eFileLock );
2913 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
2914 /* Acquire a RESERVED lock */
2915 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
2916 if( !failed ){
2917 context->reserved = 1;
2920 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
2921 /* Acquire an EXCLUSIVE lock */
2923 /* Remove the shared lock before trying the range. we'll need to
2924 ** reestablish the shared lock if we can't get the afpUnlock
2926 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
2927 pInode->sharedByte, 1, 0)) ){
2928 int failed2 = SQLITE_OK;
2929 /* now attemmpt to get the exclusive lock range */
2930 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
2931 SHARED_SIZE, 1);
2932 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
2933 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
2934 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2935 ** a critical I/O error
2937 rc = ((failed & 0xff) == SQLITE_IOERR) ? failed2 :
2938 SQLITE_IOERR_LOCK;
2939 goto afp_end_lock;
2941 }else{
2942 rc = failed;
2945 if( failed ){
2946 rc = failed;
2950 if( rc==SQLITE_OK ){
2951 pFile->eFileLock = eFileLock;
2952 pInode->eFileLock = eFileLock;
2953 }else if( eFileLock==EXCLUSIVE_LOCK ){
2954 pFile->eFileLock = PENDING_LOCK;
2955 pInode->eFileLock = PENDING_LOCK;
2958 afp_end_lock:
2959 unixLeaveMutex();
2960 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2961 rc==SQLITE_OK ? "ok" : "failed"));
2962 return rc;
2966 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
2967 ** must be either NO_LOCK or SHARED_LOCK.
2969 ** If the locking level of the file descriptor is already at or below
2970 ** the requested locking level, this routine is a no-op.
2972 static int afpUnlock(sqlite3_file *id, int eFileLock) {
2973 int rc = SQLITE_OK;
2974 unixFile *pFile = (unixFile*)id;
2975 unixInodeInfo *pInode;
2976 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2977 int skipShared = 0;
2978 #ifdef SQLITE_TEST
2979 int h = pFile->h;
2980 #endif
2982 assert( pFile );
2983 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
2984 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
2985 osGetpid(0)));
2987 assert( eFileLock<=SHARED_LOCK );
2988 if( pFile->eFileLock<=eFileLock ){
2989 return SQLITE_OK;
2991 unixEnterMutex();
2992 pInode = pFile->pInode;
2993 assert( pInode->nShared!=0 );
2994 if( pFile->eFileLock>SHARED_LOCK ){
2995 assert( pInode->eFileLock==pFile->eFileLock );
2996 SimulateIOErrorBenign(1);
2997 SimulateIOError( h=(-1) )
2998 SimulateIOErrorBenign(0);
3000 #ifdef SQLITE_DEBUG
3001 /* When reducing a lock such that other processes can start
3002 ** reading the database file again, make sure that the
3003 ** transaction counter was updated if any part of the database
3004 ** file changed. If the transaction counter is not updated,
3005 ** other connections to the same file might not realize that
3006 ** the file has changed and hence might not know to flush their
3007 ** cache. The use of a stale cache can lead to database corruption.
3009 assert( pFile->inNormalWrite==0
3010 || pFile->dbUpdate==0
3011 || pFile->transCntrChng==1 );
3012 pFile->inNormalWrite = 0;
3013 #endif
3015 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
3016 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
3017 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
3018 /* only re-establish the shared lock if necessary */
3019 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3020 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
3021 } else {
3022 skipShared = 1;
3025 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
3026 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
3028 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
3029 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
3030 if( !rc ){
3031 context->reserved = 0;
3034 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
3035 pInode->eFileLock = SHARED_LOCK;
3038 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
3040 /* Decrement the shared lock counter. Release the lock using an
3041 ** OS call only when all threads in this same process have released
3042 ** the lock.
3044 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3045 pInode->nShared--;
3046 if( pInode->nShared==0 ){
3047 SimulateIOErrorBenign(1);
3048 SimulateIOError( h=(-1) )
3049 SimulateIOErrorBenign(0);
3050 if( !skipShared ){
3051 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
3053 if( !rc ){
3054 pInode->eFileLock = NO_LOCK;
3055 pFile->eFileLock = NO_LOCK;
3058 if( rc==SQLITE_OK ){
3059 pInode->nLock--;
3060 assert( pInode->nLock>=0 );
3061 if( pInode->nLock==0 ){
3062 closePendingFds(pFile);
3067 unixLeaveMutex();
3068 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
3069 return rc;
3073 ** Close a file & cleanup AFP specific locking context
3075 static int afpClose(sqlite3_file *id) {
3076 int rc = SQLITE_OK;
3077 unixFile *pFile = (unixFile*)id;
3078 assert( id!=0 );
3079 afpUnlock(id, NO_LOCK);
3080 unixEnterMutex();
3081 if( pFile->pInode && pFile->pInode->nLock ){
3082 /* If there are outstanding locks, do not actually close the file just
3083 ** yet because that would clear those locks. Instead, add the file
3084 ** descriptor to pInode->aPending. It will be automatically closed when
3085 ** the last lock is cleared.
3087 setPendingFd(pFile);
3089 releaseInodeInfo(pFile);
3090 sqlite3_free(pFile->lockingContext);
3091 rc = closeUnixFile(id);
3092 unixLeaveMutex();
3093 return rc;
3096 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3098 ** The code above is the AFP lock implementation. The code is specific
3099 ** to MacOSX and does not work on other unix platforms. No alternative
3100 ** is available. If you don't compile for a mac, then the "unix-afp"
3101 ** VFS is not available.
3103 ********************* End of the AFP lock implementation **********************
3104 ******************************************************************************/
3106 /******************************************************************************
3107 *************************** Begin NFS Locking ********************************/
3109 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3111 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
3112 ** must be either NO_LOCK or SHARED_LOCK.
3114 ** If the locking level of the file descriptor is already at or below
3115 ** the requested locking level, this routine is a no-op.
3117 static int nfsUnlock(sqlite3_file *id, int eFileLock){
3118 return posixUnlock(id, eFileLock, 1);
3121 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3123 ** The code above is the NFS lock implementation. The code is specific
3124 ** to MacOSX and does not work on other unix platforms. No alternative
3125 ** is available.
3127 ********************* End of the NFS lock implementation **********************
3128 ******************************************************************************/
3130 /******************************************************************************
3131 **************** Non-locking sqlite3_file methods *****************************
3133 ** The next division contains implementations for all methods of the
3134 ** sqlite3_file object other than the locking methods. The locking
3135 ** methods were defined in divisions above (one locking method per
3136 ** division). Those methods that are common to all locking modes
3137 ** are gather together into this division.
3141 ** Seek to the offset passed as the second argument, then read cnt
3142 ** bytes into pBuf. Return the number of bytes actually read.
3144 ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3145 ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3146 ** one system to another. Since SQLite does not define USE_PREAD
3147 ** in any form by default, we will not attempt to define _XOPEN_SOURCE.
3148 ** See tickets #2741 and #2681.
3150 ** To avoid stomping the errno value on a failed read the lastErrno value
3151 ** is set before returning.
3153 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3154 int got;
3155 int prior = 0;
3156 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
3157 i64 newOffset;
3158 #endif
3159 TIMER_START;
3160 assert( cnt==(cnt&0x1ffff) );
3161 assert( id->h>2 );
3163 #if defined(USE_PREAD)
3164 got = osPread(id->h, pBuf, cnt, offset);
3165 SimulateIOError( got = -1 );
3166 #elif defined(USE_PREAD64)
3167 got = osPread64(id->h, pBuf, cnt, offset);
3168 SimulateIOError( got = -1 );
3169 #else
3170 newOffset = lseek(id->h, offset, SEEK_SET);
3171 SimulateIOError( newOffset = -1 );
3172 if( newOffset<0 ){
3173 storeLastErrno((unixFile*)id, errno);
3174 return -1;
3176 got = osRead(id->h, pBuf, cnt);
3177 #endif
3178 if( got==cnt ) break;
3179 if( got<0 ){
3180 if( errno==EINTR ){ got = 1; continue; }
3181 prior = 0;
3182 storeLastErrno((unixFile*)id, errno);
3183 break;
3184 }else if( got>0 ){
3185 cnt -= got;
3186 offset += got;
3187 prior += got;
3188 pBuf = (void*)(got + (char*)pBuf);
3190 }while( got>0 );
3191 TIMER_END;
3192 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3193 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3194 return got+prior;
3198 ** Read data from a file into a buffer. Return SQLITE_OK if all
3199 ** bytes were read successfully and SQLITE_IOERR if anything goes
3200 ** wrong.
3202 static int unixRead(
3203 sqlite3_file *id,
3204 void *pBuf,
3205 int amt,
3206 sqlite3_int64 offset
3208 unixFile *pFile = (unixFile *)id;
3209 int got;
3210 assert( id );
3211 assert( offset>=0 );
3212 assert( amt>0 );
3214 /* If this is a database file (not a journal, master-journal or temp
3215 ** file), the bytes in the locking range should never be read or written. */
3216 #if 0
3217 assert( pFile->pPreallocatedUnused==0
3218 || offset>=PENDING_BYTE+512
3219 || offset+amt<=PENDING_BYTE
3221 #endif
3223 #if SQLITE_MAX_MMAP_SIZE>0
3224 /* Deal with as much of this read request as possible by transfering
3225 ** data from the memory mapping using memcpy(). */
3226 if( offset<pFile->mmapSize ){
3227 if( offset+amt <= pFile->mmapSize ){
3228 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3229 return SQLITE_OK;
3230 }else{
3231 int nCopy = pFile->mmapSize - offset;
3232 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3233 pBuf = &((u8 *)pBuf)[nCopy];
3234 amt -= nCopy;
3235 offset += nCopy;
3238 #endif
3240 got = seekAndRead(pFile, offset, pBuf, amt);
3241 if( got==amt ){
3242 return SQLITE_OK;
3243 }else if( got<0 ){
3244 /* lastErrno set by seekAndRead */
3245 return SQLITE_IOERR_READ;
3246 }else{
3247 storeLastErrno(pFile, 0); /* not a system error */
3248 /* Unread parts of the buffer must be zero-filled */
3249 memset(&((char*)pBuf)[got], 0, amt-got);
3250 return SQLITE_IOERR_SHORT_READ;
3255 ** Attempt to seek the file-descriptor passed as the first argument to
3256 ** absolute offset iOff, then attempt to write nBuf bytes of data from
3257 ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3258 ** return the actual number of bytes written (which may be less than
3259 ** nBuf).
3261 static int seekAndWriteFd(
3262 int fd, /* File descriptor to write to */
3263 i64 iOff, /* File offset to begin writing at */
3264 const void *pBuf, /* Copy data from this buffer to the file */
3265 int nBuf, /* Size of buffer pBuf in bytes */
3266 int *piErrno /* OUT: Error number if error occurs */
3268 int rc = 0; /* Value returned by system call */
3270 assert( nBuf==(nBuf&0x1ffff) );
3271 assert( fd>2 );
3272 assert( piErrno!=0 );
3273 nBuf &= 0x1ffff;
3274 TIMER_START;
3276 #if defined(USE_PREAD)
3277 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
3278 #elif defined(USE_PREAD64)
3279 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
3280 #else
3282 i64 iSeek = lseek(fd, iOff, SEEK_SET);
3283 SimulateIOError( iSeek = -1 );
3284 if( iSeek<0 ){
3285 rc = -1;
3286 break;
3288 rc = osWrite(fd, pBuf, nBuf);
3289 }while( rc<0 && errno==EINTR );
3290 #endif
3292 TIMER_END;
3293 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3295 if( rc<0 ) *piErrno = errno;
3296 return rc;
3301 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
3302 ** Return the number of bytes actually read. Update the offset.
3304 ** To avoid stomping the errno value on a failed write the lastErrno value
3305 ** is set before returning.
3307 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
3308 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
3313 ** Write data from a buffer into a file. Return SQLITE_OK on success
3314 ** or some other error code on failure.
3316 static int unixWrite(
3317 sqlite3_file *id,
3318 const void *pBuf,
3319 int amt,
3320 sqlite3_int64 offset
3322 unixFile *pFile = (unixFile*)id;
3323 int wrote = 0;
3324 assert( id );
3325 assert( amt>0 );
3327 /* If this is a database file (not a journal, master-journal or temp
3328 ** file), the bytes in the locking range should never be read or written. */
3329 #if 0
3330 assert( pFile->pPreallocatedUnused==0
3331 || offset>=PENDING_BYTE+512
3332 || offset+amt<=PENDING_BYTE
3334 #endif
3336 #ifdef SQLITE_DEBUG
3337 /* If we are doing a normal write to a database file (as opposed to
3338 ** doing a hot-journal rollback or a write to some file other than a
3339 ** normal database file) then record the fact that the database
3340 ** has changed. If the transaction counter is modified, record that
3341 ** fact too.
3343 if( pFile->inNormalWrite ){
3344 pFile->dbUpdate = 1; /* The database has been modified */
3345 if( offset<=24 && offset+amt>=27 ){
3346 int rc;
3347 char oldCntr[4];
3348 SimulateIOErrorBenign(1);
3349 rc = seekAndRead(pFile, 24, oldCntr, 4);
3350 SimulateIOErrorBenign(0);
3351 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
3352 pFile->transCntrChng = 1; /* The transaction counter has changed */
3356 #endif
3358 #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
3359 /* Deal with as much of this write request as possible by transfering
3360 ** data from the memory mapping using memcpy(). */
3361 if( offset<pFile->mmapSize ){
3362 if( offset+amt <= pFile->mmapSize ){
3363 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3364 return SQLITE_OK;
3365 }else{
3366 int nCopy = pFile->mmapSize - offset;
3367 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3368 pBuf = &((u8 *)pBuf)[nCopy];
3369 amt -= nCopy;
3370 offset += nCopy;
3373 #endif
3375 while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
3376 amt -= wrote;
3377 offset += wrote;
3378 pBuf = &((char*)pBuf)[wrote];
3380 SimulateIOError(( wrote=(-1), amt=1 ));
3381 SimulateDiskfullError(( wrote=0, amt=1 ));
3383 if( amt>wrote ){
3384 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
3385 /* lastErrno set by seekAndWrite */
3386 return SQLITE_IOERR_WRITE;
3387 }else{
3388 storeLastErrno(pFile, 0); /* not a system error */
3389 return SQLITE_FULL;
3393 return SQLITE_OK;
3396 #ifdef SQLITE_TEST
3398 ** Count the number of fullsyncs and normal syncs. This is used to test
3399 ** that syncs and fullsyncs are occurring at the right times.
3401 int sqlite3_sync_count = 0;
3402 int sqlite3_fullsync_count = 0;
3403 #endif
3406 ** We do not trust systems to provide a working fdatasync(). Some do.
3407 ** Others do no. To be safe, we will stick with the (slightly slower)
3408 ** fsync(). If you know that your system does support fdatasync() correctly,
3409 ** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
3411 #if !defined(fdatasync) && !HAVE_FDATASYNC
3412 # define fdatasync fsync
3413 #endif
3416 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3417 ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3418 ** only available on Mac OS X. But that could change.
3420 #ifdef F_FULLFSYNC
3421 # define HAVE_FULLFSYNC 1
3422 #else
3423 # define HAVE_FULLFSYNC 0
3424 #endif
3428 ** The fsync() system call does not work as advertised on many
3429 ** unix systems. The following procedure is an attempt to make
3430 ** it work better.
3432 ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3433 ** for testing when we want to run through the test suite quickly.
3434 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3435 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3436 ** or power failure will likely corrupt the database file.
3438 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
3439 ** The idea behind dataOnly is that it should only write the file content
3440 ** to disk, not the inode. We only set dataOnly if the file size is
3441 ** unchanged since the file size is part of the inode. However,
3442 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
3443 ** file size has changed. The only real difference between fdatasync()
3444 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
3445 ** inode if the mtime or owner or other inode attributes have changed.
3446 ** We only care about the file size, not the other file attributes, so
3447 ** as far as SQLite is concerned, an fdatasync() is always adequate.
3448 ** So, we always use fdatasync() if it is available, regardless of
3449 ** the value of the dataOnly flag.
3451 static int full_fsync(int fd, int fullSync, int dataOnly){
3452 int rc;
3454 /* The following "ifdef/elif/else/" block has the same structure as
3455 ** the one below. It is replicated here solely to avoid cluttering
3456 ** up the real code with the UNUSED_PARAMETER() macros.
3458 #ifdef SQLITE_NO_SYNC
3459 UNUSED_PARAMETER(fd);
3460 UNUSED_PARAMETER(fullSync);
3461 UNUSED_PARAMETER(dataOnly);
3462 #elif HAVE_FULLFSYNC
3463 UNUSED_PARAMETER(dataOnly);
3464 #else
3465 UNUSED_PARAMETER(fullSync);
3466 UNUSED_PARAMETER(dataOnly);
3467 #endif
3469 /* Record the number of times that we do a normal fsync() and
3470 ** FULLSYNC. This is used during testing to verify that this procedure
3471 ** gets called with the correct arguments.
3473 #ifdef SQLITE_TEST
3474 if( fullSync ) sqlite3_fullsync_count++;
3475 sqlite3_sync_count++;
3476 #endif
3478 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3479 ** no-op. But go ahead and call fstat() to validate the file
3480 ** descriptor as we need a method to provoke a failure during
3481 ** coverate testing.
3483 #ifdef SQLITE_NO_SYNC
3485 struct stat buf;
3486 rc = osFstat(fd, &buf);
3488 #elif HAVE_FULLFSYNC
3489 if( fullSync ){
3490 rc = osFcntl(fd, F_FULLFSYNC, 0);
3491 }else{
3492 rc = 1;
3494 /* If the FULLFSYNC failed, fall back to attempting an fsync().
3495 ** It shouldn't be possible for fullfsync to fail on the local
3496 ** file system (on OSX), so failure indicates that FULLFSYNC
3497 ** isn't supported for this file system. So, attempt an fsync
3498 ** and (for now) ignore the overhead of a superfluous fcntl call.
3499 ** It'd be better to detect fullfsync support once and avoid
3500 ** the fcntl call every time sync is called.
3502 if( rc ) rc = fsync(fd);
3504 #elif defined(__APPLE__)
3505 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3506 ** so currently we default to the macro that redefines fdatasync to fsync
3508 rc = fsync(fd);
3509 #else
3510 rc = fdatasync(fd);
3511 #if OS_VXWORKS
3512 if( rc==-1 && errno==ENOTSUP ){
3513 rc = fsync(fd);
3515 #endif /* OS_VXWORKS */
3516 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3518 if( OS_VXWORKS && rc!= -1 ){
3519 rc = 0;
3521 return rc;
3525 ** Open a file descriptor to the directory containing file zFilename.
3526 ** If successful, *pFd is set to the opened file descriptor and
3527 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3528 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3529 ** value.
3531 ** The directory file descriptor is used for only one thing - to
3532 ** fsync() a directory to make sure file creation and deletion events
3533 ** are flushed to disk. Such fsyncs are not needed on newer
3534 ** journaling filesystems, but are required on older filesystems.
3536 ** This routine can be overridden using the xSetSysCall interface.
3537 ** The ability to override this routine was added in support of the
3538 ** chromium sandbox. Opening a directory is a security risk (we are
3539 ** told) so making it overrideable allows the chromium sandbox to
3540 ** replace this routine with a harmless no-op. To make this routine
3541 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3542 ** *pFd set to a negative number.
3544 ** If SQLITE_OK is returned, the caller is responsible for closing
3545 ** the file descriptor *pFd using close().
3547 static int openDirectory(const char *zFilename, int *pFd){
3548 int ii;
3549 int fd = -1;
3550 char zDirname[MAX_PATHNAME+1];
3552 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3553 for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
3554 if( ii>0 ){
3555 zDirname[ii] = '\0';
3556 }else{
3557 if( zDirname[0]!='/' ) zDirname[0] = '.';
3558 zDirname[1] = 0;
3560 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3561 if( fd>=0 ){
3562 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3564 *pFd = fd;
3565 if( fd>=0 ) return SQLITE_OK;
3566 return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
3570 ** Make sure all writes to a particular file are committed to disk.
3572 ** If dataOnly==0 then both the file itself and its metadata (file
3573 ** size, access time, etc) are synced. If dataOnly!=0 then only the
3574 ** file data is synced.
3576 ** Under Unix, also make sure that the directory entry for the file
3577 ** has been created by fsync-ing the directory that contains the file.
3578 ** If we do not do this and we encounter a power failure, the directory
3579 ** entry for the journal might not exist after we reboot. The next
3580 ** SQLite to access the file will not know that the journal exists (because
3581 ** the directory entry for the journal was never created) and the transaction
3582 ** will not roll back - possibly leading to database corruption.
3584 static int unixSync(sqlite3_file *id, int flags){
3585 int rc;
3586 unixFile *pFile = (unixFile*)id;
3588 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3589 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3591 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3592 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3593 || (flags&0x0F)==SQLITE_SYNC_FULL
3596 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3597 ** line is to test that doing so does not cause any problems.
3599 SimulateDiskfullError( return SQLITE_FULL );
3601 assert( pFile );
3602 OSTRACE(("SYNC %-3d\n", pFile->h));
3603 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3604 SimulateIOError( rc=1 );
3605 if( rc ){
3606 storeLastErrno(pFile, errno);
3607 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
3610 /* Also fsync the directory containing the file if the DIRSYNC flag
3611 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
3612 ** are unable to fsync a directory, so ignore errors on the fsync.
3614 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3615 int dirfd;
3616 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
3617 HAVE_FULLFSYNC, isFullsync));
3618 rc = osOpenDirectory(pFile->zPath, &dirfd);
3619 if( rc==SQLITE_OK ){
3620 full_fsync(dirfd, 0, 0);
3621 robust_close(pFile, dirfd, __LINE__);
3622 }else{
3623 assert( rc==SQLITE_CANTOPEN );
3624 rc = SQLITE_OK;
3626 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
3628 return rc;
3632 ** Truncate an open file to a specified size
3634 static int unixTruncate(sqlite3_file *id, i64 nByte){
3635 unixFile *pFile = (unixFile *)id;
3636 int rc;
3637 assert( pFile );
3638 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
3640 /* If the user has configured a chunk-size for this file, truncate the
3641 ** file so that it consists of an integer number of chunks (i.e. the
3642 ** actual file size after the operation may be larger than the requested
3643 ** size).
3645 if( pFile->szChunk>0 ){
3646 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3649 rc = robust_ftruncate(pFile->h, nByte);
3650 if( rc ){
3651 storeLastErrno(pFile, errno);
3652 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3653 }else{
3654 #ifdef SQLITE_DEBUG
3655 /* If we are doing a normal write to a database file (as opposed to
3656 ** doing a hot-journal rollback or a write to some file other than a
3657 ** normal database file) and we truncate the file to zero length,
3658 ** that effectively updates the change counter. This might happen
3659 ** when restoring a database using the backup API from a zero-length
3660 ** source.
3662 if( pFile->inNormalWrite && nByte==0 ){
3663 pFile->transCntrChng = 1;
3665 #endif
3667 #if SQLITE_MAX_MMAP_SIZE>0
3668 /* If the file was just truncated to a size smaller than the currently
3669 ** mapped region, reduce the effective mapping size as well. SQLite will
3670 ** use read() and write() to access data beyond this point from now on.
3672 if( nByte<pFile->mmapSize ){
3673 pFile->mmapSize = nByte;
3675 #endif
3677 return SQLITE_OK;
3682 ** Determine the current size of a file in bytes
3684 static int unixFileSize(sqlite3_file *id, i64 *pSize){
3685 int rc;
3686 struct stat buf;
3687 assert( id );
3688 rc = osFstat(((unixFile*)id)->h, &buf);
3689 SimulateIOError( rc=1 );
3690 if( rc!=0 ){
3691 storeLastErrno((unixFile*)id, errno);
3692 return SQLITE_IOERR_FSTAT;
3694 *pSize = buf.st_size;
3696 /* When opening a zero-size database, the findInodeInfo() procedure
3697 ** writes a single byte into that file in order to work around a bug
3698 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3699 ** layers, we need to report this file size as zero even though it is
3700 ** really 1. Ticket #3260.
3702 if( *pSize==1 ) *pSize = 0;
3705 return SQLITE_OK;
3708 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
3710 ** Handler for proxy-locking file-control verbs. Defined below in the
3711 ** proxying locking division.
3713 static int proxyFileControl(sqlite3_file*,int,void*);
3714 #endif
3717 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
3718 ** file-control operation. Enlarge the database to nBytes in size
3719 ** (rounded up to the next chunk-size). If the database is already
3720 ** nBytes or larger, this routine is a no-op.
3722 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
3723 if( pFile->szChunk>0 ){
3724 i64 nSize; /* Required file size */
3725 struct stat buf; /* Used to hold return values of fstat() */
3727 if( osFstat(pFile->h, &buf) ){
3728 return SQLITE_IOERR_FSTAT;
3731 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3732 if( nSize>(i64)buf.st_size ){
3734 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
3735 /* The code below is handling the return value of osFallocate()
3736 ** correctly. posix_fallocate() is defined to "returns zero on success,
3737 ** or an error number on failure". See the manpage for details. */
3738 int err;
3740 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3741 }while( err==EINTR );
3742 if( err ) return SQLITE_IOERR_WRITE;
3743 #else
3744 /* If the OS does not have posix_fallocate(), fake it. Write a
3745 ** single byte to the last byte in each block that falls entirely
3746 ** within the extended region. Then, if required, a single byte
3747 ** at offset (nSize-1), to set the size of the file correctly.
3748 ** This is a similar technique to that used by glibc on systems
3749 ** that do not have a real fallocate() call.
3751 int nBlk = buf.st_blksize; /* File-system block size */
3752 int nWrite = 0; /* Number of bytes written by seekAndWrite */
3753 i64 iWrite; /* Next offset to write to */
3755 iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
3756 assert( iWrite>=buf.st_size );
3757 assert( ((iWrite+1)%nBlk)==0 );
3758 for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
3759 if( iWrite>=nSize ) iWrite = nSize - 1;
3760 nWrite = seekAndWrite(pFile, iWrite, "", 1);
3761 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
3763 #endif
3767 #if SQLITE_MAX_MMAP_SIZE>0
3768 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
3769 int rc;
3770 if( pFile->szChunk<=0 ){
3771 if( robust_ftruncate(pFile->h, nByte) ){
3772 storeLastErrno(pFile, errno);
3773 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3777 rc = unixMapfile(pFile, nByte);
3778 return rc;
3780 #endif
3782 return SQLITE_OK;
3786 ** If *pArg is initially negative then this is a query. Set *pArg to
3787 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3789 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3791 static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3792 if( *pArg<0 ){
3793 *pArg = (pFile->ctrlFlags & mask)!=0;
3794 }else if( (*pArg)==0 ){
3795 pFile->ctrlFlags &= ~mask;
3796 }else{
3797 pFile->ctrlFlags |= mask;
3801 /* Forward declaration */
3802 static int unixGetTempname(int nBuf, char *zBuf);
3805 ** Information and control of an open file handle.
3807 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
3808 unixFile *pFile = (unixFile*)id;
3809 switch( op ){
3810 #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
3811 case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: {
3812 int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE);
3813 return rc ? SQLITE_IOERR_BEGIN_ATOMIC : SQLITE_OK;
3815 case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: {
3816 int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE);
3817 return rc ? SQLITE_IOERR_COMMIT_ATOMIC : SQLITE_OK;
3819 case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: {
3820 int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE);
3821 return rc ? SQLITE_IOERR_ROLLBACK_ATOMIC : SQLITE_OK;
3823 #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
3825 case SQLITE_FCNTL_LOCKSTATE: {
3826 *(int*)pArg = pFile->eFileLock;
3827 return SQLITE_OK;
3829 case SQLITE_FCNTL_LAST_ERRNO: {
3830 *(int*)pArg = pFile->lastErrno;
3831 return SQLITE_OK;
3833 case SQLITE_FCNTL_CHUNK_SIZE: {
3834 pFile->szChunk = *(int *)pArg;
3835 return SQLITE_OK;
3837 case SQLITE_FCNTL_SIZE_HINT: {
3838 int rc;
3839 SimulateIOErrorBenign(1);
3840 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3841 SimulateIOErrorBenign(0);
3842 return rc;
3844 case SQLITE_FCNTL_PERSIST_WAL: {
3845 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3846 return SQLITE_OK;
3848 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3849 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
3850 return SQLITE_OK;
3852 case SQLITE_FCNTL_VFSNAME: {
3853 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3854 return SQLITE_OK;
3856 case SQLITE_FCNTL_TEMPFILENAME: {
3857 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
3858 if( zTFile ){
3859 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3860 *(char**)pArg = zTFile;
3862 return SQLITE_OK;
3864 case SQLITE_FCNTL_HAS_MOVED: {
3865 *(int*)pArg = fileHasMoved(pFile);
3866 return SQLITE_OK;
3868 #if SQLITE_MAX_MMAP_SIZE>0
3869 case SQLITE_FCNTL_MMAP_SIZE: {
3870 i64 newLimit = *(i64*)pArg;
3871 int rc = SQLITE_OK;
3872 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3873 newLimit = sqlite3GlobalConfig.mxMmap;
3876 /* The value of newLimit may be eventually cast to (size_t) and passed
3877 ** to mmap(). Restrict its value to 2GB if (size_t) is not at least a
3878 ** 64-bit type. */
3879 if( newLimit>0 && sizeof(size_t)<8 ){
3880 newLimit = (newLimit & 0x7FFFFFFF);
3883 *(i64*)pArg = pFile->mmapSizeMax;
3884 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
3885 pFile->mmapSizeMax = newLimit;
3886 if( pFile->mmapSize>0 ){
3887 unixUnmapfile(pFile);
3888 rc = unixMapfile(pFile, -1);
3891 return rc;
3893 #endif
3894 #ifdef SQLITE_DEBUG
3895 /* The pager calls this method to signal that it has done
3896 ** a rollback and that the database is therefore unchanged and
3897 ** it hence it is OK for the transaction change counter to be
3898 ** unchanged.
3900 case SQLITE_FCNTL_DB_UNCHANGED: {
3901 ((unixFile*)id)->dbUpdate = 0;
3902 return SQLITE_OK;
3904 #endif
3905 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
3906 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
3907 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
3908 return proxyFileControl(id,op,pArg);
3910 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
3912 return SQLITE_NOTFOUND;
3916 ** If pFd->sectorSize is non-zero when this function is called, it is a
3917 ** no-op. Otherwise, the values of pFd->sectorSize and
3918 ** pFd->deviceCharacteristics are set according to the file-system
3919 ** characteristics.
3921 ** There are two versions of this function. One for QNX and one for all
3922 ** other systems.
3924 #ifndef __QNXNTO__
3925 static void setDeviceCharacteristics(unixFile *pFd){
3926 assert( pFd->deviceCharacteristics==0 || pFd->sectorSize!=0 );
3927 if( pFd->sectorSize==0 ){
3928 #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
3929 int res;
3930 u32 f = 0;
3932 /* Check for support for F2FS atomic batch writes. */
3933 res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES, &f);
3934 if( res==0 && (f & F2FS_FEATURE_ATOMIC_WRITE) ){
3935 pFd->deviceCharacteristics = SQLITE_IOCAP_BATCH_ATOMIC;
3937 #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
3939 /* Set the POWERSAFE_OVERWRITE flag if requested. */
3940 if( pFd->ctrlFlags & UNIXFILE_PSOW ){
3941 pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
3944 pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3947 #else
3948 #include <sys/dcmd_blk.h>
3949 #include <sys/statvfs.h>
3950 static void setDeviceCharacteristics(unixFile *pFile){
3951 if( pFile->sectorSize == 0 ){
3952 struct statvfs fsInfo;
3954 /* Set defaults for non-supported filesystems */
3955 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3956 pFile->deviceCharacteristics = 0;
3957 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3958 return;
3961 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3962 pFile->sectorSize = fsInfo.f_bsize;
3963 pFile->deviceCharacteristics =
3964 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3965 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3966 ** the write succeeds */
3967 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3968 ** so it is ordered */
3970 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3971 pFile->sectorSize = fsInfo.f_bsize;
3972 pFile->deviceCharacteristics =
3973 /* etfs cluster size writes are atomic */
3974 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3975 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3976 ** the write succeeds */
3977 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3978 ** so it is ordered */
3980 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3981 pFile->sectorSize = fsInfo.f_bsize;
3982 pFile->deviceCharacteristics =
3983 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3984 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3985 ** the write succeeds */
3986 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3987 ** so it is ordered */
3989 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3990 pFile->sectorSize = fsInfo.f_bsize;
3991 pFile->deviceCharacteristics =
3992 /* full bitset of atomics from max sector size and smaller */
3993 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3994 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3995 ** so it is ordered */
3997 }else if( strstr(fsInfo.f_basetype, "dos") ){
3998 pFile->sectorSize = fsInfo.f_bsize;
3999 pFile->deviceCharacteristics =
4000 /* full bitset of atomics from max sector size and smaller */
4001 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
4002 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4003 ** so it is ordered */
4005 }else{
4006 pFile->deviceCharacteristics =
4007 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
4008 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4009 ** the write succeeds */
4013 /* Last chance verification. If the sector size isn't a multiple of 512
4014 ** then it isn't valid.*/
4015 if( pFile->sectorSize % 512 != 0 ){
4016 pFile->deviceCharacteristics = 0;
4017 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4020 #endif
4023 ** Return the sector size in bytes of the underlying block device for
4024 ** the specified file. This is almost always 512 bytes, but may be
4025 ** larger for some devices.
4027 ** SQLite code assumes this function cannot fail. It also assumes that
4028 ** if two files are created in the same file-system directory (i.e.
4029 ** a database and its journal file) that the sector size will be the
4030 ** same for both.
4032 static int unixSectorSize(sqlite3_file *id){
4033 unixFile *pFd = (unixFile*)id;
4034 setDeviceCharacteristics(pFd);
4035 return pFd->sectorSize;
4039 ** Return the device characteristics for the file.
4041 ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
4042 ** However, that choice is controversial since technically the underlying
4043 ** file system does not always provide powersafe overwrites. (In other
4044 ** words, after a power-loss event, parts of the file that were never
4045 ** written might end up being altered.) However, non-PSOW behavior is very,
4046 ** very rare. And asserting PSOW makes a large reduction in the amount
4047 ** of required I/O for journaling, since a lot of padding is eliminated.
4048 ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
4049 ** available to turn it off and URI query parameter available to turn it off.
4051 static int unixDeviceCharacteristics(sqlite3_file *id){
4052 unixFile *pFd = (unixFile*)id;
4053 setDeviceCharacteristics(pFd);
4054 return pFd->deviceCharacteristics;
4057 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
4060 ** Return the system page size.
4062 ** This function should not be called directly by other code in this file.
4063 ** Instead, it should be called via macro osGetpagesize().
4065 static int unixGetpagesize(void){
4066 #if OS_VXWORKS
4067 return 1024;
4068 #elif defined(_BSD_SOURCE)
4069 return getpagesize();
4070 #else
4071 return (int)sysconf(_SC_PAGESIZE);
4072 #endif
4075 #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
4077 #ifndef SQLITE_OMIT_WAL
4080 ** Object used to represent an shared memory buffer.
4082 ** When multiple threads all reference the same wal-index, each thread
4083 ** has its own unixShm object, but they all point to a single instance
4084 ** of this unixShmNode object. In other words, each wal-index is opened
4085 ** only once per process.
4087 ** Each unixShmNode object is connected to a single unixInodeInfo object.
4088 ** We could coalesce this object into unixInodeInfo, but that would mean
4089 ** every open file that does not use shared memory (in other words, most
4090 ** open files) would have to carry around this extra information. So
4091 ** the unixInodeInfo object contains a pointer to this unixShmNode object
4092 ** and the unixShmNode object is created only when needed.
4094 ** unixMutexHeld() must be true when creating or destroying
4095 ** this object or while reading or writing the following fields:
4097 ** nRef
4099 ** The following fields are read-only after the object is created:
4101 ** fid
4102 ** zFilename
4104 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
4105 ** unixMutexHeld() is true when reading or writing any other field
4106 ** in this structure.
4108 struct unixShmNode {
4109 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
4110 sqlite3_mutex *mutex; /* Mutex to access this object */
4111 char *zFilename; /* Name of the mmapped file */
4112 int h; /* Open file descriptor */
4113 int szRegion; /* Size of shared-memory regions */
4114 u16 nRegion; /* Size of array apRegion */
4115 u8 isReadonly; /* True if read-only */
4116 u8 isUnlocked; /* True if no DMS lock held */
4117 char **apRegion; /* Array of mapped shared-memory regions */
4118 int nRef; /* Number of unixShm objects pointing to this */
4119 unixShm *pFirst; /* All unixShm objects pointing to this */
4120 #ifdef SQLITE_DEBUG
4121 u8 exclMask; /* Mask of exclusive locks held */
4122 u8 sharedMask; /* Mask of shared locks held */
4123 u8 nextShmId; /* Next available unixShm.id value */
4124 #endif
4128 ** Structure used internally by this VFS to record the state of an
4129 ** open shared memory connection.
4131 ** The following fields are initialized when this object is created and
4132 ** are read-only thereafter:
4134 ** unixShm.pFile
4135 ** unixShm.id
4137 ** All other fields are read/write. The unixShm.pFile->mutex must be held
4138 ** while accessing any read/write fields.
4140 struct unixShm {
4141 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4142 unixShm *pNext; /* Next unixShm with the same unixShmNode */
4143 u8 hasMutex; /* True if holding the unixShmNode mutex */
4144 u8 id; /* Id of this connection within its unixShmNode */
4145 u16 sharedMask; /* Mask of shared locks held */
4146 u16 exclMask; /* Mask of exclusive locks held */
4150 ** Constants used for locking
4152 #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
4153 #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
4156 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
4158 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4159 ** otherwise.
4161 static int unixShmSystemLock(
4162 unixFile *pFile, /* Open connection to the WAL file */
4163 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
4164 int ofst, /* First byte of the locking range */
4165 int n /* Number of bytes to lock */
4167 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4168 struct flock f; /* The posix advisory locking structure */
4169 int rc = SQLITE_OK; /* Result code form fcntl() */
4171 /* Access to the unixShmNode object is serialized by the caller */
4172 pShmNode = pFile->pInode->pShmNode;
4173 assert( pShmNode->nRef==0 || sqlite3_mutex_held(pShmNode->mutex) );
4175 /* Shared locks never span more than one byte */
4176 assert( n==1 || lockType!=F_RDLCK );
4178 /* Locks are within range */
4179 assert( n>=1 && n<=SQLITE_SHM_NLOCK );
4181 if( pShmNode->h>=0 ){
4182 /* Initialize the locking parameters */
4183 memset(&f, 0, sizeof(f));
4184 f.l_type = lockType;
4185 f.l_whence = SEEK_SET;
4186 f.l_start = ofst;
4187 f.l_len = n;
4189 rc = osFcntl(pShmNode->h, F_SETLK, &f);
4190 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4193 /* Update the global lock state and do debug tracing */
4194 #ifdef SQLITE_DEBUG
4195 { u16 mask;
4196 OSTRACE(("SHM-LOCK "));
4197 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
4198 if( rc==SQLITE_OK ){
4199 if( lockType==F_UNLCK ){
4200 OSTRACE(("unlock %d ok", ofst));
4201 pShmNode->exclMask &= ~mask;
4202 pShmNode->sharedMask &= ~mask;
4203 }else if( lockType==F_RDLCK ){
4204 OSTRACE(("read-lock %d ok", ofst));
4205 pShmNode->exclMask &= ~mask;
4206 pShmNode->sharedMask |= mask;
4207 }else{
4208 assert( lockType==F_WRLCK );
4209 OSTRACE(("write-lock %d ok", ofst));
4210 pShmNode->exclMask |= mask;
4211 pShmNode->sharedMask &= ~mask;
4213 }else{
4214 if( lockType==F_UNLCK ){
4215 OSTRACE(("unlock %d failed", ofst));
4216 }else if( lockType==F_RDLCK ){
4217 OSTRACE(("read-lock failed"));
4218 }else{
4219 assert( lockType==F_WRLCK );
4220 OSTRACE(("write-lock %d failed", ofst));
4223 OSTRACE((" - afterwards %03x,%03x\n",
4224 pShmNode->sharedMask, pShmNode->exclMask));
4226 #endif
4228 return rc;
4232 ** Return the minimum number of 32KB shm regions that should be mapped at
4233 ** a time, assuming that each mapping must be an integer multiple of the
4234 ** current system page-size.
4236 ** Usually, this is 1. The exception seems to be systems that are configured
4237 ** to use 64KB pages - in this case each mapping must cover at least two
4238 ** shm regions.
4240 static int unixShmRegionPerMap(void){
4241 int shmsz = 32*1024; /* SHM region size */
4242 int pgsz = osGetpagesize(); /* System page size */
4243 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4244 if( pgsz<shmsz ) return 1;
4245 return pgsz/shmsz;
4249 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
4251 ** This is not a VFS shared-memory method; it is a utility function called
4252 ** by VFS shared-memory methods.
4254 static void unixShmPurge(unixFile *pFd){
4255 unixShmNode *p = pFd->pInode->pShmNode;
4256 assert( unixMutexHeld() );
4257 if( p && ALWAYS(p->nRef==0) ){
4258 int nShmPerMap = unixShmRegionPerMap();
4259 int i;
4260 assert( p->pInode==pFd->pInode );
4261 sqlite3_mutex_free(p->mutex);
4262 for(i=0; i<p->nRegion; i+=nShmPerMap){
4263 if( p->h>=0 ){
4264 osMunmap(p->apRegion[i], p->szRegion);
4265 }else{
4266 sqlite3_free(p->apRegion[i]);
4269 sqlite3_free(p->apRegion);
4270 if( p->h>=0 ){
4271 robust_close(pFd, p->h, __LINE__);
4272 p->h = -1;
4274 p->pInode->pShmNode = 0;
4275 sqlite3_free(p);
4280 ** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
4281 ** take it now. Return SQLITE_OK if successful, or an SQLite error
4282 ** code otherwise.
4284 ** If the DMS cannot be locked because this is a readonly_shm=1
4285 ** connection and no other process already holds a lock, return
4286 ** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
4288 static int unixLockSharedMemory(unixFile *pDbFd, unixShmNode *pShmNode){
4289 struct flock lock;
4290 int rc = SQLITE_OK;
4292 /* Use F_GETLK to determine the locks other processes are holding
4293 ** on the DMS byte. If it indicates that another process is holding
4294 ** a SHARED lock, then this process may also take a SHARED lock
4295 ** and proceed with opening the *-shm file.
4297 ** Or, if no other process is holding any lock, then this process
4298 ** is the first to open it. In this case take an EXCLUSIVE lock on the
4299 ** DMS byte and truncate the *-shm file to zero bytes in size. Then
4300 ** downgrade to a SHARED lock on the DMS byte.
4302 ** If another process is holding an EXCLUSIVE lock on the DMS byte,
4303 ** return SQLITE_BUSY to the caller (it will try again). An earlier
4304 ** version of this code attempted the SHARED lock at this point. But
4305 ** this introduced a subtle race condition: if the process holding
4306 ** EXCLUSIVE failed just before truncating the *-shm file, then this
4307 ** process might open and use the *-shm file without truncating it.
4308 ** And if the *-shm file has been corrupted by a power failure or
4309 ** system crash, the database itself may also become corrupt. */
4310 lock.l_whence = SEEK_SET;
4311 lock.l_start = UNIX_SHM_DMS;
4312 lock.l_len = 1;
4313 lock.l_type = F_WRLCK;
4314 if( osFcntl(pShmNode->h, F_GETLK, &lock)!=0 ) {
4315 rc = SQLITE_IOERR_LOCK;
4316 }else if( lock.l_type==F_UNLCK ){
4317 if( pShmNode->isReadonly ){
4318 pShmNode->isUnlocked = 1;
4319 rc = SQLITE_READONLY_CANTINIT;
4320 }else{
4321 rc = unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1);
4322 if( rc==SQLITE_OK && robust_ftruncate(pShmNode->h, 0) ){
4323 rc = unixLogError(SQLITE_IOERR_SHMOPEN,"ftruncate",pShmNode->zFilename);
4326 }else if( lock.l_type==F_WRLCK ){
4327 rc = SQLITE_BUSY;
4330 if( rc==SQLITE_OK ){
4331 assert( lock.l_type==F_UNLCK || lock.l_type==F_RDLCK );
4332 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
4334 return rc;
4338 ** Open a shared-memory area associated with open database file pDbFd.
4339 ** This particular implementation uses mmapped files.
4341 ** The file used to implement shared-memory is in the same directory
4342 ** as the open database file and has the same name as the open database
4343 ** file with the "-shm" suffix added. For example, if the database file
4344 ** is "/home/user1/config.db" then the file that is created and mmapped
4345 ** for shared memory will be called "/home/user1/config.db-shm".
4347 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
4348 ** some other tmpfs mount. But if a file in a different directory
4349 ** from the database file is used, then differing access permissions
4350 ** or a chroot() might cause two different processes on the same
4351 ** database to end up using different files for shared memory -
4352 ** meaning that their memory would not really be shared - resulting
4353 ** in database corruption. Nevertheless, this tmpfs file usage
4354 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4355 ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4356 ** option results in an incompatible build of SQLite; builds of SQLite
4357 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4358 ** same database file at the same time, database corruption will likely
4359 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4360 ** "unsupported" and may go away in a future SQLite release.
4362 ** When opening a new shared-memory file, if no other instances of that
4363 ** file are currently open, in this process or in other processes, then
4364 ** the file must be truncated to zero length or have its header cleared.
4366 ** If the original database file (pDbFd) is using the "unix-excl" VFS
4367 ** that means that an exclusive lock is held on the database file and
4368 ** that no other processes are able to read or write the database. In
4369 ** that case, we do not really need shared memory. No shared memory
4370 ** file is created. The shared memory will be simulated with heap memory.
4372 static int unixOpenSharedMemory(unixFile *pDbFd){
4373 struct unixShm *p = 0; /* The connection to be opened */
4374 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4375 int rc = SQLITE_OK; /* Result code */
4376 unixInodeInfo *pInode; /* The inode of fd */
4377 char *zShm; /* Name of the file used for SHM */
4378 int nShmFilename; /* Size of the SHM filename in bytes */
4380 /* Allocate space for the new unixShm object. */
4381 p = sqlite3_malloc64( sizeof(*p) );
4382 if( p==0 ) return SQLITE_NOMEM_BKPT;
4383 memset(p, 0, sizeof(*p));
4384 assert( pDbFd->pShm==0 );
4386 /* Check to see if a unixShmNode object already exists. Reuse an existing
4387 ** one if present. Create a new one if necessary.
4389 unixEnterMutex();
4390 pInode = pDbFd->pInode;
4391 pShmNode = pInode->pShmNode;
4392 if( pShmNode==0 ){
4393 struct stat sStat; /* fstat() info for database file */
4394 #ifndef SQLITE_SHM_DIRECTORY
4395 const char *zBasePath = pDbFd->zPath;
4396 #endif
4398 /* Call fstat() to figure out the permissions on the database file. If
4399 ** a new *-shm file is created, an attempt will be made to create it
4400 ** with the same permissions.
4402 if( osFstat(pDbFd->h, &sStat) ){
4403 rc = SQLITE_IOERR_FSTAT;
4404 goto shm_open_err;
4407 #ifdef SQLITE_SHM_DIRECTORY
4408 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
4409 #else
4410 nShmFilename = 6 + (int)strlen(zBasePath);
4411 #endif
4412 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
4413 if( pShmNode==0 ){
4414 rc = SQLITE_NOMEM_BKPT;
4415 goto shm_open_err;
4417 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
4418 zShm = pShmNode->zFilename = (char*)&pShmNode[1];
4419 #ifdef SQLITE_SHM_DIRECTORY
4420 sqlite3_snprintf(nShmFilename, zShm,
4421 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4422 (u32)sStat.st_ino, (u32)sStat.st_dev);
4423 #else
4424 sqlite3_snprintf(nShmFilename, zShm, "%s-shm", zBasePath);
4425 sqlite3FileSuffix3(pDbFd->zPath, zShm);
4426 #endif
4427 pShmNode->h = -1;
4428 pDbFd->pInode->pShmNode = pShmNode;
4429 pShmNode->pInode = pDbFd->pInode;
4430 if( sqlite3GlobalConfig.bCoreMutex ){
4431 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4432 if( pShmNode->mutex==0 ){
4433 rc = SQLITE_NOMEM_BKPT;
4434 goto shm_open_err;
4438 if( pInode->bProcessLock==0 ){
4439 if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
4440 pShmNode->h = robust_open(zShm, O_RDWR|O_CREAT, (sStat.st_mode&0777));
4442 if( pShmNode->h<0 ){
4443 pShmNode->h = robust_open(zShm, O_RDONLY, (sStat.st_mode&0777));
4444 if( pShmNode->h<0 ){
4445 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShm);
4446 goto shm_open_err;
4448 pShmNode->isReadonly = 1;
4451 /* If this process is running as root, make sure that the SHM file
4452 ** is owned by the same user that owns the original database. Otherwise,
4453 ** the original owner will not be able to connect.
4455 robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
4457 rc = unixLockSharedMemory(pDbFd, pShmNode);
4458 if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
4462 /* Make the new connection a child of the unixShmNode */
4463 p->pShmNode = pShmNode;
4464 #ifdef SQLITE_DEBUG
4465 p->id = pShmNode->nextShmId++;
4466 #endif
4467 pShmNode->nRef++;
4468 pDbFd->pShm = p;
4469 unixLeaveMutex();
4471 /* The reference count on pShmNode has already been incremented under
4472 ** the cover of the unixEnterMutex() mutex and the pointer from the
4473 ** new (struct unixShm) object to the pShmNode has been set. All that is
4474 ** left to do is to link the new object into the linked list starting
4475 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4476 ** mutex.
4478 sqlite3_mutex_enter(pShmNode->mutex);
4479 p->pNext = pShmNode->pFirst;
4480 pShmNode->pFirst = p;
4481 sqlite3_mutex_leave(pShmNode->mutex);
4482 return rc;
4484 /* Jump here on any error */
4485 shm_open_err:
4486 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
4487 sqlite3_free(p);
4488 unixLeaveMutex();
4489 return rc;
4493 ** This function is called to obtain a pointer to region iRegion of the
4494 ** shared-memory associated with the database file fd. Shared-memory regions
4495 ** are numbered starting from zero. Each shared-memory region is szRegion
4496 ** bytes in size.
4498 ** If an error occurs, an error code is returned and *pp is set to NULL.
4500 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4501 ** region has not been allocated (by any client, including one running in a
4502 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4503 ** bExtend is non-zero and the requested shared-memory region has not yet
4504 ** been allocated, it is allocated by this function.
4506 ** If the shared-memory region has already been allocated or is allocated by
4507 ** this call as described above, then it is mapped into this processes
4508 ** address space (if it is not already), *pp is set to point to the mapped
4509 ** memory and SQLITE_OK returned.
4511 static int unixShmMap(
4512 sqlite3_file *fd, /* Handle open on database file */
4513 int iRegion, /* Region to retrieve */
4514 int szRegion, /* Size of regions */
4515 int bExtend, /* True to extend file if necessary */
4516 void volatile **pp /* OUT: Mapped memory */
4518 unixFile *pDbFd = (unixFile*)fd;
4519 unixShm *p;
4520 unixShmNode *pShmNode;
4521 int rc = SQLITE_OK;
4522 int nShmPerMap = unixShmRegionPerMap();
4523 int nReqRegion;
4525 /* If the shared-memory file has not yet been opened, open it now. */
4526 if( pDbFd->pShm==0 ){
4527 rc = unixOpenSharedMemory(pDbFd);
4528 if( rc!=SQLITE_OK ) return rc;
4531 p = pDbFd->pShm;
4532 pShmNode = p->pShmNode;
4533 sqlite3_mutex_enter(pShmNode->mutex);
4534 if( pShmNode->isUnlocked ){
4535 rc = unixLockSharedMemory(pDbFd, pShmNode);
4536 if( rc!=SQLITE_OK ) goto shmpage_out;
4537 pShmNode->isUnlocked = 0;
4539 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
4540 assert( pShmNode->pInode==pDbFd->pInode );
4541 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4542 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
4544 /* Minimum number of regions required to be mapped. */
4545 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4547 if( pShmNode->nRegion<nReqRegion ){
4548 char **apNew; /* New apRegion[] array */
4549 int nByte = nReqRegion*szRegion; /* Minimum required file size */
4550 struct stat sStat; /* Used by fstat() */
4552 pShmNode->szRegion = szRegion;
4554 if( pShmNode->h>=0 ){
4555 /* The requested region is not mapped into this processes address space.
4556 ** Check to see if it has been allocated (i.e. if the wal-index file is
4557 ** large enough to contain the requested region).
4559 if( osFstat(pShmNode->h, &sStat) ){
4560 rc = SQLITE_IOERR_SHMSIZE;
4561 goto shmpage_out;
4564 if( sStat.st_size<nByte ){
4565 /* The requested memory region does not exist. If bExtend is set to
4566 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
4568 if( !bExtend ){
4569 goto shmpage_out;
4572 /* Alternatively, if bExtend is true, extend the file. Do this by
4573 ** writing a single byte to the end of each (OS) page being
4574 ** allocated or extended. Technically, we need only write to the
4575 ** last page in order to extend the file. But writing to all new
4576 ** pages forces the OS to allocate them immediately, which reduces
4577 ** the chances of SIGBUS while accessing the mapped region later on.
4579 else{
4580 static const int pgsz = 4096;
4581 int iPg;
4583 /* Write to the last byte of each newly allocated or extended page */
4584 assert( (nByte % pgsz)==0 );
4585 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
4586 int x = 0;
4587 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
4588 const char *zFile = pShmNode->zFilename;
4589 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4590 goto shmpage_out;
4597 /* Map the requested memory region into this processes address space. */
4598 apNew = (char **)sqlite3_realloc(
4599 pShmNode->apRegion, nReqRegion*sizeof(char *)
4601 if( !apNew ){
4602 rc = SQLITE_IOERR_NOMEM_BKPT;
4603 goto shmpage_out;
4605 pShmNode->apRegion = apNew;
4606 while( pShmNode->nRegion<nReqRegion ){
4607 int nMap = szRegion*nShmPerMap;
4608 int i;
4609 void *pMem;
4610 if( pShmNode->h>=0 ){
4611 pMem = osMmap(0, nMap,
4612 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
4613 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
4615 if( pMem==MAP_FAILED ){
4616 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
4617 goto shmpage_out;
4619 }else{
4620 pMem = sqlite3_malloc64(szRegion);
4621 if( pMem==0 ){
4622 rc = SQLITE_NOMEM_BKPT;
4623 goto shmpage_out;
4625 memset(pMem, 0, szRegion);
4628 for(i=0; i<nShmPerMap; i++){
4629 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4631 pShmNode->nRegion += nShmPerMap;
4635 shmpage_out:
4636 if( pShmNode->nRegion>iRegion ){
4637 *pp = pShmNode->apRegion[iRegion];
4638 }else{
4639 *pp = 0;
4641 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
4642 sqlite3_mutex_leave(pShmNode->mutex);
4643 return rc;
4647 ** Change the lock state for a shared-memory segment.
4649 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4650 ** different here than in posix. In xShmLock(), one can go from unlocked
4651 ** to shared and back or from unlocked to exclusive and back. But one may
4652 ** not go from shared to exclusive or from exclusive to shared.
4654 static int unixShmLock(
4655 sqlite3_file *fd, /* Database file holding the shared memory */
4656 int ofst, /* First lock to acquire or release */
4657 int n, /* Number of locks to acquire or release */
4658 int flags /* What to do with the lock */
4660 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4661 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4662 unixShm *pX; /* For looping over all siblings */
4663 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4664 int rc = SQLITE_OK; /* Result code */
4665 u16 mask; /* Mask of locks to take or release */
4667 assert( pShmNode==pDbFd->pInode->pShmNode );
4668 assert( pShmNode->pInode==pDbFd->pInode );
4669 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
4670 assert( n>=1 );
4671 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4672 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4673 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4674 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4675 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
4676 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4677 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
4679 mask = (1<<(ofst+n)) - (1<<ofst);
4680 assert( n>1 || mask==(1<<ofst) );
4681 sqlite3_mutex_enter(pShmNode->mutex);
4682 if( flags & SQLITE_SHM_UNLOCK ){
4683 u16 allMask = 0; /* Mask of locks held by siblings */
4685 /* See if any siblings hold this same lock */
4686 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4687 if( pX==p ) continue;
4688 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4689 allMask |= pX->sharedMask;
4692 /* Unlock the system-level locks */
4693 if( (mask & allMask)==0 ){
4694 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
4695 }else{
4696 rc = SQLITE_OK;
4699 /* Undo the local locks */
4700 if( rc==SQLITE_OK ){
4701 p->exclMask &= ~mask;
4702 p->sharedMask &= ~mask;
4704 }else if( flags & SQLITE_SHM_SHARED ){
4705 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4707 /* Find out which shared locks are already held by sibling connections.
4708 ** If any sibling already holds an exclusive lock, go ahead and return
4709 ** SQLITE_BUSY.
4711 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4712 if( (pX->exclMask & mask)!=0 ){
4713 rc = SQLITE_BUSY;
4714 break;
4716 allShared |= pX->sharedMask;
4719 /* Get shared locks at the system level, if necessary */
4720 if( rc==SQLITE_OK ){
4721 if( (allShared & mask)==0 ){
4722 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
4723 }else{
4724 rc = SQLITE_OK;
4728 /* Get the local shared locks */
4729 if( rc==SQLITE_OK ){
4730 p->sharedMask |= mask;
4732 }else{
4733 /* Make sure no sibling connections hold locks that will block this
4734 ** lock. If any do, return SQLITE_BUSY right away.
4736 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4737 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4738 rc = SQLITE_BUSY;
4739 break;
4743 /* Get the exclusive locks at the system level. Then if successful
4744 ** also mark the local connection as being locked.
4746 if( rc==SQLITE_OK ){
4747 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
4748 if( rc==SQLITE_OK ){
4749 assert( (p->sharedMask & mask)==0 );
4750 p->exclMask |= mask;
4754 sqlite3_mutex_leave(pShmNode->mutex);
4755 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4756 p->id, osGetpid(0), p->sharedMask, p->exclMask));
4757 return rc;
4761 ** Implement a memory barrier or memory fence on shared memory.
4763 ** All loads and stores begun before the barrier must complete before
4764 ** any load or store begun after the barrier.
4766 static void unixShmBarrier(
4767 sqlite3_file *fd /* Database file holding the shared memory */
4769 UNUSED_PARAMETER(fd);
4770 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
4771 unixEnterMutex(); /* Also mutex, for redundancy */
4772 unixLeaveMutex();
4776 ** Close a connection to shared-memory. Delete the underlying
4777 ** storage if deleteFlag is true.
4779 ** If there is no shared memory associated with the connection then this
4780 ** routine is a harmless no-op.
4782 static int unixShmUnmap(
4783 sqlite3_file *fd, /* The underlying database file */
4784 int deleteFlag /* Delete shared-memory if true */
4786 unixShm *p; /* The connection to be closed */
4787 unixShmNode *pShmNode; /* The underlying shared-memory file */
4788 unixShm **pp; /* For looping over sibling connections */
4789 unixFile *pDbFd; /* The underlying database file */
4791 pDbFd = (unixFile*)fd;
4792 p = pDbFd->pShm;
4793 if( p==0 ) return SQLITE_OK;
4794 pShmNode = p->pShmNode;
4796 assert( pShmNode==pDbFd->pInode->pShmNode );
4797 assert( pShmNode->pInode==pDbFd->pInode );
4799 /* Remove connection p from the set of connections associated
4800 ** with pShmNode */
4801 sqlite3_mutex_enter(pShmNode->mutex);
4802 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4803 *pp = p->pNext;
4805 /* Free the connection p */
4806 sqlite3_free(p);
4807 pDbFd->pShm = 0;
4808 sqlite3_mutex_leave(pShmNode->mutex);
4810 /* If pShmNode->nRef has reached 0, then close the underlying
4811 ** shared-memory file, too */
4812 unixEnterMutex();
4813 assert( pShmNode->nRef>0 );
4814 pShmNode->nRef--;
4815 if( pShmNode->nRef==0 ){
4816 if( deleteFlag && pShmNode->h>=0 ){
4817 osUnlink(pShmNode->zFilename);
4819 unixShmPurge(pDbFd);
4821 unixLeaveMutex();
4823 return SQLITE_OK;
4827 #else
4828 # define unixShmMap 0
4829 # define unixShmLock 0
4830 # define unixShmBarrier 0
4831 # define unixShmUnmap 0
4832 #endif /* #ifndef SQLITE_OMIT_WAL */
4834 #if SQLITE_MAX_MMAP_SIZE>0
4836 ** If it is currently memory mapped, unmap file pFd.
4838 static void unixUnmapfile(unixFile *pFd){
4839 assert( pFd->nFetchOut==0 );
4840 if( pFd->pMapRegion ){
4841 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
4842 pFd->pMapRegion = 0;
4843 pFd->mmapSize = 0;
4844 pFd->mmapSizeActual = 0;
4849 ** Attempt to set the size of the memory mapping maintained by file
4850 ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4852 ** If successful, this function sets the following variables:
4854 ** unixFile.pMapRegion
4855 ** unixFile.mmapSize
4856 ** unixFile.mmapSizeActual
4858 ** If unsuccessful, an error message is logged via sqlite3_log() and
4859 ** the three variables above are zeroed. In this case SQLite should
4860 ** continue accessing the database using the xRead() and xWrite()
4861 ** methods.
4863 static void unixRemapfile(
4864 unixFile *pFd, /* File descriptor object */
4865 i64 nNew /* Required mapping size */
4867 const char *zErr = "mmap";
4868 int h = pFd->h; /* File descriptor open on db file */
4869 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
4870 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
4871 u8 *pNew = 0; /* Location of new mapping */
4872 int flags = PROT_READ; /* Flags to pass to mmap() */
4874 assert( pFd->nFetchOut==0 );
4875 assert( nNew>pFd->mmapSize );
4876 assert( nNew<=pFd->mmapSizeMax );
4877 assert( nNew>0 );
4878 assert( pFd->mmapSizeActual>=pFd->mmapSize );
4879 assert( MAP_FAILED!=0 );
4881 #ifdef SQLITE_MMAP_READWRITE
4882 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
4883 #endif
4885 if( pOrig ){
4886 #if HAVE_MREMAP
4887 i64 nReuse = pFd->mmapSize;
4888 #else
4889 const int szSyspage = osGetpagesize();
4890 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
4891 #endif
4892 u8 *pReq = &pOrig[nReuse];
4894 /* Unmap any pages of the existing mapping that cannot be reused. */
4895 if( nReuse!=nOrig ){
4896 osMunmap(pReq, nOrig-nReuse);
4899 #if HAVE_MREMAP
4900 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
4901 zErr = "mremap";
4902 #else
4903 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4904 if( pNew!=MAP_FAILED ){
4905 if( pNew!=pReq ){
4906 osMunmap(pNew, nNew - nReuse);
4907 pNew = 0;
4908 }else{
4909 pNew = pOrig;
4912 #endif
4914 /* The attempt to extend the existing mapping failed. Free it. */
4915 if( pNew==MAP_FAILED || pNew==0 ){
4916 osMunmap(pOrig, nReuse);
4920 /* If pNew is still NULL, try to create an entirely new mapping. */
4921 if( pNew==0 ){
4922 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
4925 if( pNew==MAP_FAILED ){
4926 pNew = 0;
4927 nNew = 0;
4928 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4930 /* If the mmap() above failed, assume that all subsequent mmap() calls
4931 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4932 ** in this case. */
4933 pFd->mmapSizeMax = 0;
4935 pFd->pMapRegion = (void *)pNew;
4936 pFd->mmapSize = pFd->mmapSizeActual = nNew;
4940 ** Memory map or remap the file opened by file-descriptor pFd (if the file
4941 ** is already mapped, the existing mapping is replaced by the new). Or, if
4942 ** there already exists a mapping for this file, and there are still
4943 ** outstanding xFetch() references to it, this function is a no-op.
4945 ** If parameter nByte is non-negative, then it is the requested size of
4946 ** the mapping to create. Otherwise, if nByte is less than zero, then the
4947 ** requested size is the size of the file on disk. The actual size of the
4948 ** created mapping is either the requested size or the value configured
4949 ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
4951 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
4952 ** recreated as a result of outstanding references) or an SQLite error
4953 ** code otherwise.
4955 static int unixMapfile(unixFile *pFd, i64 nMap){
4956 assert( nMap>=0 || pFd->nFetchOut==0 );
4957 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
4958 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4960 if( nMap<0 ){
4961 struct stat statbuf; /* Low-level file information */
4962 if( osFstat(pFd->h, &statbuf) ){
4963 return SQLITE_IOERR_FSTAT;
4965 nMap = statbuf.st_size;
4967 if( nMap>pFd->mmapSizeMax ){
4968 nMap = pFd->mmapSizeMax;
4971 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
4972 if( nMap!=pFd->mmapSize ){
4973 unixRemapfile(pFd, nMap);
4976 return SQLITE_OK;
4978 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
4981 ** If possible, return a pointer to a mapping of file fd starting at offset
4982 ** iOff. The mapping must be valid for at least nAmt bytes.
4984 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4985 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4986 ** Finally, if an error does occur, return an SQLite error code. The final
4987 ** value of *pp is undefined in this case.
4989 ** If this function does return a pointer, the caller must eventually
4990 ** release the reference by calling unixUnfetch().
4992 static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
4993 #if SQLITE_MAX_MMAP_SIZE>0
4994 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
4995 #endif
4996 *pp = 0;
4998 #if SQLITE_MAX_MMAP_SIZE>0
4999 if( pFd->mmapSizeMax>0 ){
5000 if( pFd->pMapRegion==0 ){
5001 int rc = unixMapfile(pFd, -1);
5002 if( rc!=SQLITE_OK ) return rc;
5004 if( pFd->mmapSize >= iOff+nAmt ){
5005 *pp = &((u8 *)pFd->pMapRegion)[iOff];
5006 pFd->nFetchOut++;
5009 #endif
5010 return SQLITE_OK;
5014 ** If the third argument is non-NULL, then this function releases a
5015 ** reference obtained by an earlier call to unixFetch(). The second
5016 ** argument passed to this function must be the same as the corresponding
5017 ** argument that was passed to the unixFetch() invocation.
5019 ** Or, if the third argument is NULL, then this function is being called
5020 ** to inform the VFS layer that, according to POSIX, any existing mapping
5021 ** may now be invalid and should be unmapped.
5023 static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
5024 #if SQLITE_MAX_MMAP_SIZE>0
5025 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
5026 UNUSED_PARAMETER(iOff);
5028 /* If p==0 (unmap the entire file) then there must be no outstanding
5029 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
5030 ** then there must be at least one outstanding. */
5031 assert( (p==0)==(pFd->nFetchOut==0) );
5033 /* If p!=0, it must match the iOff value. */
5034 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
5036 if( p ){
5037 pFd->nFetchOut--;
5038 }else{
5039 unixUnmapfile(pFd);
5042 assert( pFd->nFetchOut>=0 );
5043 #else
5044 UNUSED_PARAMETER(fd);
5045 UNUSED_PARAMETER(p);
5046 UNUSED_PARAMETER(iOff);
5047 #endif
5048 return SQLITE_OK;
5052 ** Here ends the implementation of all sqlite3_file methods.
5054 ********************** End sqlite3_file Methods *******************************
5055 ******************************************************************************/
5058 ** This division contains definitions of sqlite3_io_methods objects that
5059 ** implement various file locking strategies. It also contains definitions
5060 ** of "finder" functions. A finder-function is used to locate the appropriate
5061 ** sqlite3_io_methods object for a particular database file. The pAppData
5062 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
5063 ** the correct finder-function for that VFS.
5065 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
5066 ** object. The only interesting finder-function is autolockIoFinder, which
5067 ** looks at the filesystem type and tries to guess the best locking
5068 ** strategy from that.
5070 ** For finder-function F, two objects are created:
5072 ** (1) The real finder-function named "FImpt()".
5074 ** (2) A constant pointer to this function named just "F".
5077 ** A pointer to the F pointer is used as the pAppData value for VFS
5078 ** objects. We have to do this instead of letting pAppData point
5079 ** directly at the finder-function since C90 rules prevent a void*
5080 ** from be cast into a function pointer.
5083 ** Each instance of this macro generates two objects:
5085 ** * A constant sqlite3_io_methods object call METHOD that has locking
5086 ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
5088 ** * An I/O method finder function called FINDER that returns a pointer
5089 ** to the METHOD object in the previous bullet.
5091 #define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
5092 static const sqlite3_io_methods METHOD = { \
5093 VERSION, /* iVersion */ \
5094 CLOSE, /* xClose */ \
5095 unixRead, /* xRead */ \
5096 unixWrite, /* xWrite */ \
5097 unixTruncate, /* xTruncate */ \
5098 unixSync, /* xSync */ \
5099 unixFileSize, /* xFileSize */ \
5100 LOCK, /* xLock */ \
5101 UNLOCK, /* xUnlock */ \
5102 CKLOCK, /* xCheckReservedLock */ \
5103 unixFileControl, /* xFileControl */ \
5104 unixSectorSize, /* xSectorSize */ \
5105 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
5106 SHMMAP, /* xShmMap */ \
5107 unixShmLock, /* xShmLock */ \
5108 unixShmBarrier, /* xShmBarrier */ \
5109 unixShmUnmap, /* xShmUnmap */ \
5110 unixFetch, /* xFetch */ \
5111 unixUnfetch, /* xUnfetch */ \
5112 }; \
5113 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
5114 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
5115 return &METHOD; \
5117 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
5118 = FINDER##Impl;
5121 ** Here are all of the sqlite3_io_methods objects for each of the
5122 ** locking strategies. Functions that return pointers to these methods
5123 ** are also created.
5125 IOMETHODS(
5126 posixIoFinder, /* Finder function name */
5127 posixIoMethods, /* sqlite3_io_methods object name */
5128 3, /* shared memory and mmap are enabled */
5129 unixClose, /* xClose method */
5130 unixLock, /* xLock method */
5131 unixUnlock, /* xUnlock method */
5132 unixCheckReservedLock, /* xCheckReservedLock method */
5133 unixShmMap /* xShmMap method */
5135 IOMETHODS(
5136 nolockIoFinder, /* Finder function name */
5137 nolockIoMethods, /* sqlite3_io_methods object name */
5138 3, /* shared memory is disabled */
5139 nolockClose, /* xClose method */
5140 nolockLock, /* xLock method */
5141 nolockUnlock, /* xUnlock method */
5142 nolockCheckReservedLock, /* xCheckReservedLock method */
5143 0 /* xShmMap method */
5145 IOMETHODS(
5146 dotlockIoFinder, /* Finder function name */
5147 dotlockIoMethods, /* sqlite3_io_methods object name */
5148 1, /* shared memory is disabled */
5149 dotlockClose, /* xClose method */
5150 dotlockLock, /* xLock method */
5151 dotlockUnlock, /* xUnlock method */
5152 dotlockCheckReservedLock, /* xCheckReservedLock method */
5153 0 /* xShmMap method */
5156 #if SQLITE_ENABLE_LOCKING_STYLE
5157 IOMETHODS(
5158 flockIoFinder, /* Finder function name */
5159 flockIoMethods, /* sqlite3_io_methods object name */
5160 1, /* shared memory is disabled */
5161 flockClose, /* xClose method */
5162 flockLock, /* xLock method */
5163 flockUnlock, /* xUnlock method */
5164 flockCheckReservedLock, /* xCheckReservedLock method */
5165 0 /* xShmMap method */
5167 #endif
5169 #if OS_VXWORKS
5170 IOMETHODS(
5171 semIoFinder, /* Finder function name */
5172 semIoMethods, /* sqlite3_io_methods object name */
5173 1, /* shared memory is disabled */
5174 semXClose, /* xClose method */
5175 semXLock, /* xLock method */
5176 semXUnlock, /* xUnlock method */
5177 semXCheckReservedLock, /* xCheckReservedLock method */
5178 0 /* xShmMap method */
5180 #endif
5182 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5183 IOMETHODS(
5184 afpIoFinder, /* Finder function name */
5185 afpIoMethods, /* sqlite3_io_methods object name */
5186 1, /* shared memory is disabled */
5187 afpClose, /* xClose method */
5188 afpLock, /* xLock method */
5189 afpUnlock, /* xUnlock method */
5190 afpCheckReservedLock, /* xCheckReservedLock method */
5191 0 /* xShmMap method */
5193 #endif
5196 ** The proxy locking method is a "super-method" in the sense that it
5197 ** opens secondary file descriptors for the conch and lock files and
5198 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
5199 ** secondary files. For this reason, the division that implements
5200 ** proxy locking is located much further down in the file. But we need
5201 ** to go ahead and define the sqlite3_io_methods and finder function
5202 ** for proxy locking here. So we forward declare the I/O methods.
5204 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5205 static int proxyClose(sqlite3_file*);
5206 static int proxyLock(sqlite3_file*, int);
5207 static int proxyUnlock(sqlite3_file*, int);
5208 static int proxyCheckReservedLock(sqlite3_file*, int*);
5209 IOMETHODS(
5210 proxyIoFinder, /* Finder function name */
5211 proxyIoMethods, /* sqlite3_io_methods object name */
5212 1, /* shared memory is disabled */
5213 proxyClose, /* xClose method */
5214 proxyLock, /* xLock method */
5215 proxyUnlock, /* xUnlock method */
5216 proxyCheckReservedLock, /* xCheckReservedLock method */
5217 0 /* xShmMap method */
5219 #endif
5221 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5222 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5223 IOMETHODS(
5224 nfsIoFinder, /* Finder function name */
5225 nfsIoMethods, /* sqlite3_io_methods object name */
5226 1, /* shared memory is disabled */
5227 unixClose, /* xClose method */
5228 unixLock, /* xLock method */
5229 nfsUnlock, /* xUnlock method */
5230 unixCheckReservedLock, /* xCheckReservedLock method */
5231 0 /* xShmMap method */
5233 #endif
5235 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5237 ** This "finder" function attempts to determine the best locking strategy
5238 ** for the database file "filePath". It then returns the sqlite3_io_methods
5239 ** object that implements that strategy.
5241 ** This is for MacOSX only.
5243 static const sqlite3_io_methods *autolockIoFinderImpl(
5244 const char *filePath, /* name of the database file */
5245 unixFile *pNew /* open file object for the database file */
5247 static const struct Mapping {
5248 const char *zFilesystem; /* Filesystem type name */
5249 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
5250 } aMap[] = {
5251 { "hfs", &posixIoMethods },
5252 { "ufs", &posixIoMethods },
5253 { "afpfs", &afpIoMethods },
5254 { "smbfs", &afpIoMethods },
5255 { "webdav", &nolockIoMethods },
5256 { 0, 0 }
5258 int i;
5259 struct statfs fsInfo;
5260 struct flock lockInfo;
5262 if( !filePath ){
5263 /* If filePath==NULL that means we are dealing with a transient file
5264 ** that does not need to be locked. */
5265 return &nolockIoMethods;
5267 if( statfs(filePath, &fsInfo) != -1 ){
5268 if( fsInfo.f_flags & MNT_RDONLY ){
5269 return &nolockIoMethods;
5271 for(i=0; aMap[i].zFilesystem; i++){
5272 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5273 return aMap[i].pMethods;
5278 /* Default case. Handles, amongst others, "nfs".
5279 ** Test byte-range lock using fcntl(). If the call succeeds,
5280 ** assume that the file-system supports POSIX style locks.
5282 lockInfo.l_len = 1;
5283 lockInfo.l_start = 0;
5284 lockInfo.l_whence = SEEK_SET;
5285 lockInfo.l_type = F_RDLCK;
5286 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
5287 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5288 return &nfsIoMethods;
5289 } else {
5290 return &posixIoMethods;
5292 }else{
5293 return &dotlockIoMethods;
5296 static const sqlite3_io_methods
5297 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
5299 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
5301 #if OS_VXWORKS
5303 ** This "finder" function for VxWorks checks to see if posix advisory
5304 ** locking works. If it does, then that is what is used. If it does not
5305 ** work, then fallback to named semaphore locking.
5307 static const sqlite3_io_methods *vxworksIoFinderImpl(
5308 const char *filePath, /* name of the database file */
5309 unixFile *pNew /* the open file object */
5311 struct flock lockInfo;
5313 if( !filePath ){
5314 /* If filePath==NULL that means we are dealing with a transient file
5315 ** that does not need to be locked. */
5316 return &nolockIoMethods;
5319 /* Test if fcntl() is supported and use POSIX style locks.
5320 ** Otherwise fall back to the named semaphore method.
5322 lockInfo.l_len = 1;
5323 lockInfo.l_start = 0;
5324 lockInfo.l_whence = SEEK_SET;
5325 lockInfo.l_type = F_RDLCK;
5326 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
5327 return &posixIoMethods;
5328 }else{
5329 return &semIoMethods;
5332 static const sqlite3_io_methods
5333 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
5335 #endif /* OS_VXWORKS */
5338 ** An abstract type for a pointer to an IO method finder function:
5340 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
5343 /****************************************************************************
5344 **************************** sqlite3_vfs methods ****************************
5346 ** This division contains the implementation of methods on the
5347 ** sqlite3_vfs object.
5351 ** Initialize the contents of the unixFile structure pointed to by pId.
5353 static int fillInUnixFile(
5354 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5355 int h, /* Open file descriptor of file being opened */
5356 sqlite3_file *pId, /* Write to the unixFile structure here */
5357 const char *zFilename, /* Name of the file being opened */
5358 int ctrlFlags /* Zero or more UNIXFILE_* values */
5360 const sqlite3_io_methods *pLockingStyle;
5361 unixFile *pNew = (unixFile *)pId;
5362 int rc = SQLITE_OK;
5364 assert( pNew->pInode==NULL );
5366 /* No locking occurs in temporary files */
5367 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
5369 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
5370 pNew->h = h;
5371 pNew->pVfs = pVfs;
5372 pNew->zPath = zFilename;
5373 pNew->ctrlFlags = (u8)ctrlFlags;
5374 #if SQLITE_MAX_MMAP_SIZE>0
5375 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
5376 #endif
5377 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5378 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
5379 pNew->ctrlFlags |= UNIXFILE_PSOW;
5381 if( strcmp(pVfs->zName,"unix-excl")==0 ){
5382 pNew->ctrlFlags |= UNIXFILE_EXCL;
5385 #if OS_VXWORKS
5386 pNew->pId = vxworksFindFileId(zFilename);
5387 if( pNew->pId==0 ){
5388 ctrlFlags |= UNIXFILE_NOLOCK;
5389 rc = SQLITE_NOMEM_BKPT;
5391 #endif
5393 if( ctrlFlags & UNIXFILE_NOLOCK ){
5394 pLockingStyle = &nolockIoMethods;
5395 }else{
5396 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
5397 #if SQLITE_ENABLE_LOCKING_STYLE
5398 /* Cache zFilename in the locking context (AFP and dotlock override) for
5399 ** proxyLock activation is possible (remote proxy is based on db name)
5400 ** zFilename remains valid until file is closed, to support */
5401 pNew->lockingContext = (void*)zFilename;
5402 #endif
5405 if( pLockingStyle == &posixIoMethods
5406 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5407 || pLockingStyle == &nfsIoMethods
5408 #endif
5410 unixEnterMutex();
5411 rc = findInodeInfo(pNew, &pNew->pInode);
5412 if( rc!=SQLITE_OK ){
5413 /* If an error occurred in findInodeInfo(), close the file descriptor
5414 ** immediately, before releasing the mutex. findInodeInfo() may fail
5415 ** in two scenarios:
5417 ** (a) A call to fstat() failed.
5418 ** (b) A malloc failed.
5420 ** Scenario (b) may only occur if the process is holding no other
5421 ** file descriptors open on the same file. If there were other file
5422 ** descriptors on this file, then no malloc would be required by
5423 ** findInodeInfo(). If this is the case, it is quite safe to close
5424 ** handle h - as it is guaranteed that no posix locks will be released
5425 ** by doing so.
5427 ** If scenario (a) caused the error then things are not so safe. The
5428 ** implicit assumption here is that if fstat() fails, things are in
5429 ** such bad shape that dropping a lock or two doesn't matter much.
5431 robust_close(pNew, h, __LINE__);
5432 h = -1;
5434 unixLeaveMutex();
5437 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
5438 else if( pLockingStyle == &afpIoMethods ){
5439 /* AFP locking uses the file path so it needs to be included in
5440 ** the afpLockingContext.
5442 afpLockingContext *pCtx;
5443 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
5444 if( pCtx==0 ){
5445 rc = SQLITE_NOMEM_BKPT;
5446 }else{
5447 /* NB: zFilename exists and remains valid until the file is closed
5448 ** according to requirement F11141. So we do not need to make a
5449 ** copy of the filename. */
5450 pCtx->dbPath = zFilename;
5451 pCtx->reserved = 0;
5452 srandomdev();
5453 unixEnterMutex();
5454 rc = findInodeInfo(pNew, &pNew->pInode);
5455 if( rc!=SQLITE_OK ){
5456 sqlite3_free(pNew->lockingContext);
5457 robust_close(pNew, h, __LINE__);
5458 h = -1;
5460 unixLeaveMutex();
5463 #endif
5465 else if( pLockingStyle == &dotlockIoMethods ){
5466 /* Dotfile locking uses the file path so it needs to be included in
5467 ** the dotlockLockingContext
5469 char *zLockFile;
5470 int nFilename;
5471 assert( zFilename!=0 );
5472 nFilename = (int)strlen(zFilename) + 6;
5473 zLockFile = (char *)sqlite3_malloc64(nFilename);
5474 if( zLockFile==0 ){
5475 rc = SQLITE_NOMEM_BKPT;
5476 }else{
5477 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
5479 pNew->lockingContext = zLockFile;
5482 #if OS_VXWORKS
5483 else if( pLockingStyle == &semIoMethods ){
5484 /* Named semaphore locking uses the file path so it needs to be
5485 ** included in the semLockingContext
5487 unixEnterMutex();
5488 rc = findInodeInfo(pNew, &pNew->pInode);
5489 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5490 char *zSemName = pNew->pInode->aSemName;
5491 int n;
5492 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
5493 pNew->pId->zCanonicalName);
5494 for( n=1; zSemName[n]; n++ )
5495 if( zSemName[n]=='/' ) zSemName[n] = '_';
5496 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5497 if( pNew->pInode->pSem == SEM_FAILED ){
5498 rc = SQLITE_NOMEM_BKPT;
5499 pNew->pInode->aSemName[0] = '\0';
5502 unixLeaveMutex();
5504 #endif
5506 storeLastErrno(pNew, 0);
5507 #if OS_VXWORKS
5508 if( rc!=SQLITE_OK ){
5509 if( h>=0 ) robust_close(pNew, h, __LINE__);
5510 h = -1;
5511 osUnlink(zFilename);
5512 pNew->ctrlFlags |= UNIXFILE_DELETE;
5514 #endif
5515 if( rc!=SQLITE_OK ){
5516 if( h>=0 ) robust_close(pNew, h, __LINE__);
5517 }else{
5518 pNew->pMethod = pLockingStyle;
5519 OpenCounter(+1);
5520 verifyDbFile(pNew);
5522 return rc;
5526 ** Return the name of a directory in which to put temporary files.
5527 ** If no suitable temporary file directory can be found, return NULL.
5529 static const char *unixTempFileDir(void){
5530 static const char *azDirs[] = {
5533 "/var/tmp",
5534 "/usr/tmp",
5535 "/tmp",
5538 unsigned int i = 0;
5539 struct stat buf;
5540 const char *zDir = sqlite3_temp_directory;
5542 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
5543 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
5544 while(1){
5545 if( zDir!=0
5546 && osStat(zDir, &buf)==0
5547 && S_ISDIR(buf.st_mode)
5548 && osAccess(zDir, 03)==0
5550 return zDir;
5552 if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
5553 zDir = azDirs[i++];
5555 return 0;
5559 ** Create a temporary file name in zBuf. zBuf must be allocated
5560 ** by the calling process and must be big enough to hold at least
5561 ** pVfs->mxPathname bytes.
5563 static int unixGetTempname(int nBuf, char *zBuf){
5564 const char *zDir;
5565 int iLimit = 0;
5567 /* It's odd to simulate an io-error here, but really this is just
5568 ** using the io-error infrastructure to test that SQLite handles this
5569 ** function failing.
5571 zBuf[0] = 0;
5572 SimulateIOError( return SQLITE_IOERR );
5574 zDir = unixTempFileDir();
5575 if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
5577 u64 r;
5578 sqlite3_randomness(sizeof(r), &r);
5579 assert( nBuf>2 );
5580 zBuf[nBuf-2] = 0;
5581 sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
5582 zDir, r, 0);
5583 if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
5584 }while( osAccess(zBuf,0)==0 );
5585 return SQLITE_OK;
5588 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
5590 ** Routine to transform a unixFile into a proxy-locking unixFile.
5591 ** Implementation in the proxy-lock division, but used by unixOpen()
5592 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
5594 static int proxyTransformUnixFile(unixFile*, const char*);
5595 #endif
5598 ** Search for an unused file descriptor that was opened on the database
5599 ** file (not a journal or master-journal file) identified by pathname
5600 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5601 ** argument to this function.
5603 ** Such a file descriptor may exist if a database connection was closed
5604 ** but the associated file descriptor could not be closed because some
5605 ** other file descriptor open on the same file is holding a file-lock.
5606 ** Refer to comments in the unixClose() function and the lengthy comment
5607 ** describing "Posix Advisory Locking" at the start of this file for
5608 ** further details. Also, ticket #4018.
5610 ** If a suitable file descriptor is found, then it is returned. If no
5611 ** such file descriptor is located, -1 is returned.
5613 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5614 UnixUnusedFd *pUnused = 0;
5616 /* Do not search for an unused file descriptor on vxworks. Not because
5617 ** vxworks would not benefit from the change (it might, we're not sure),
5618 ** but because no way to test it is currently available. It is better
5619 ** not to risk breaking vxworks support for the sake of such an obscure
5620 ** feature. */
5621 #if !OS_VXWORKS
5622 struct stat sStat; /* Results of stat() call */
5624 unixEnterMutex();
5626 /* A stat() call may fail for various reasons. If this happens, it is
5627 ** almost certain that an open() call on the same path will also fail.
5628 ** For this reason, if an error occurs in the stat() call here, it is
5629 ** ignored and -1 is returned. The caller will try to open a new file
5630 ** descriptor on the same path, fail, and return an error to SQLite.
5632 ** Even if a subsequent open() call does succeed, the consequences of
5633 ** not searching for a reusable file descriptor are not dire. */
5634 if( nUnusedFd>0 && 0==osStat(zPath, &sStat) ){
5635 unixInodeInfo *pInode;
5637 pInode = inodeList;
5638 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5639 || pInode->fileId.ino!=(u64)sStat.st_ino) ){
5640 pInode = pInode->pNext;
5642 if( pInode ){
5643 UnixUnusedFd **pp;
5644 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
5645 pUnused = *pp;
5646 if( pUnused ){
5647 nUnusedFd--;
5648 *pp = pUnused->pNext;
5652 unixLeaveMutex();
5653 #endif /* if !OS_VXWORKS */
5654 return pUnused;
5658 ** Find the mode, uid and gid of file zFile.
5660 static int getFileMode(
5661 const char *zFile, /* File name */
5662 mode_t *pMode, /* OUT: Permissions of zFile */
5663 uid_t *pUid, /* OUT: uid of zFile. */
5664 gid_t *pGid /* OUT: gid of zFile. */
5666 struct stat sStat; /* Output of stat() on database file */
5667 int rc = SQLITE_OK;
5668 if( 0==osStat(zFile, &sStat) ){
5669 *pMode = sStat.st_mode & 0777;
5670 *pUid = sStat.st_uid;
5671 *pGid = sStat.st_gid;
5672 }else{
5673 rc = SQLITE_IOERR_FSTAT;
5675 return rc;
5679 ** This function is called by unixOpen() to determine the unix permissions
5680 ** to create new files with. If no error occurs, then SQLITE_OK is returned
5681 ** and a value suitable for passing as the third argument to open(2) is
5682 ** written to *pMode. If an IO error occurs, an SQLite error code is
5683 ** returned and the value of *pMode is not modified.
5685 ** In most cases, this routine sets *pMode to 0, which will become
5686 ** an indication to robust_open() to create the file using
5687 ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5688 ** But if the file being opened is a WAL or regular journal file, then
5689 ** this function queries the file-system for the permissions on the
5690 ** corresponding database file and sets *pMode to this value. Whenever
5691 ** possible, WAL and journal files are created using the same permissions
5692 ** as the associated database file.
5694 ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5695 ** original filename is unavailable. But 8_3_NAMES is only used for
5696 ** FAT filesystems and permissions do not matter there, so just use
5697 ** the default permissions.
5699 static int findCreateFileMode(
5700 const char *zPath, /* Path of file (possibly) being created */
5701 int flags, /* Flags passed as 4th argument to xOpen() */
5702 mode_t *pMode, /* OUT: Permissions to open file with */
5703 uid_t *pUid, /* OUT: uid to set on the file */
5704 gid_t *pGid /* OUT: gid to set on the file */
5706 int rc = SQLITE_OK; /* Return Code */
5707 *pMode = 0;
5708 *pUid = 0;
5709 *pGid = 0;
5710 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
5711 char zDb[MAX_PATHNAME+1]; /* Database file path */
5712 int nDb; /* Number of valid bytes in zDb */
5714 /* zPath is a path to a WAL or journal file. The following block derives
5715 ** the path to the associated database file from zPath. This block handles
5716 ** the following naming conventions:
5718 ** "<path to db>-journal"
5719 ** "<path to db>-wal"
5720 ** "<path to db>-journalNN"
5721 ** "<path to db>-walNN"
5723 ** where NN is a decimal number. The NN naming schemes are
5724 ** used by the test_multiplex.c module.
5726 nDb = sqlite3Strlen30(zPath) - 1;
5727 while( zPath[nDb]!='-' ){
5728 /* In normal operation, the journal file name will always contain
5729 ** a '-' character. However in 8+3 filename mode, or if a corrupt
5730 ** rollback journal specifies a master journal with a goofy name, then
5731 ** the '-' might be missing. */
5732 if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
5733 nDb--;
5735 memcpy(zDb, zPath, nDb);
5736 zDb[nDb] = '\0';
5738 rc = getFileMode(zDb, pMode, pUid, pGid);
5739 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5740 *pMode = 0600;
5741 }else if( flags & SQLITE_OPEN_URI ){
5742 /* If this is a main database file and the file was opened using a URI
5743 ** filename, check for the "modeof" parameter. If present, interpret
5744 ** its value as a filename and try to copy the mode, uid and gid from
5745 ** that file. */
5746 const char *z = sqlite3_uri_parameter(zPath, "modeof");
5747 if( z ){
5748 rc = getFileMode(z, pMode, pUid, pGid);
5751 return rc;
5755 ** Open the file zPath.
5757 ** Previously, the SQLite OS layer used three functions in place of this
5758 ** one:
5760 ** sqlite3OsOpenReadWrite();
5761 ** sqlite3OsOpenReadOnly();
5762 ** sqlite3OsOpenExclusive();
5764 ** These calls correspond to the following combinations of flags:
5766 ** ReadWrite() -> (READWRITE | CREATE)
5767 ** ReadOnly() -> (READONLY)
5768 ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5770 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5771 ** true, the file was configured to be automatically deleted when the
5772 ** file handle closed. To achieve the same effect using this new
5773 ** interface, add the DELETEONCLOSE flag to those specified above for
5774 ** OpenExclusive().
5776 static int unixOpen(
5777 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5778 const char *zPath, /* Pathname of file to be opened */
5779 sqlite3_file *pFile, /* The file descriptor to be filled in */
5780 int flags, /* Input flags to control the opening */
5781 int *pOutFlags /* Output flags returned to SQLite core */
5783 unixFile *p = (unixFile *)pFile;
5784 int fd = -1; /* File descriptor returned by open() */
5785 int openFlags = 0; /* Flags to pass to open() */
5786 int eType = flags&0xFFFFFF00; /* Type of file to open */
5787 int noLock; /* True to omit locking primitives */
5788 int rc = SQLITE_OK; /* Function Return Code */
5789 int ctrlFlags = 0; /* UNIXFILE_* flags */
5791 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5792 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5793 int isCreate = (flags & SQLITE_OPEN_CREATE);
5794 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5795 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
5796 #if SQLITE_ENABLE_LOCKING_STYLE
5797 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5798 #endif
5799 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5800 struct statfs fsInfo;
5801 #endif
5803 /* If creating a master or main-file journal, this function will open
5804 ** a file-descriptor on the directory too. The first time unixSync()
5805 ** is called the directory file descriptor will be fsync()ed and close()d.
5807 int isNewJrnl = (isCreate && (
5808 eType==SQLITE_OPEN_MASTER_JOURNAL
5809 || eType==SQLITE_OPEN_MAIN_JOURNAL
5810 || eType==SQLITE_OPEN_WAL
5813 /* If argument zPath is a NULL pointer, this function is required to open
5814 ** a temporary file. Use this buffer to store the file name in.
5816 char zTmpname[MAX_PATHNAME+2];
5817 const char *zName = zPath;
5819 /* Check the following statements are true:
5821 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5822 ** (b) if CREATE is set, then READWRITE must also be set, and
5823 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
5824 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
5826 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
5827 assert(isCreate==0 || isReadWrite);
5828 assert(isExclusive==0 || isCreate);
5829 assert(isDelete==0 || isCreate);
5831 /* The main DB, main journal, WAL file and master journal are never
5832 ** automatically deleted. Nor are they ever temporary files. */
5833 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5834 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5835 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
5836 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
5838 /* Assert that the upper layer has set one of the "file-type" flags. */
5839 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5840 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5841 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
5842 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
5845 /* Detect a pid change and reset the PRNG. There is a race condition
5846 ** here such that two or more threads all trying to open databases at
5847 ** the same instant might all reset the PRNG. But multiple resets
5848 ** are harmless.
5850 if( randomnessPid!=osGetpid(0) ){
5851 randomnessPid = osGetpid(0);
5852 sqlite3_randomness(0,0);
5854 memset(p, 0, sizeof(unixFile));
5856 if( eType==SQLITE_OPEN_MAIN_DB ){
5857 UnixUnusedFd *pUnused;
5858 pUnused = findReusableFd(zName, flags);
5859 if( pUnused ){
5860 fd = pUnused->fd;
5861 }else{
5862 pUnused = sqlite3_malloc64(sizeof(*pUnused));
5863 if( !pUnused ){
5864 return SQLITE_NOMEM_BKPT;
5867 p->pPreallocatedUnused = pUnused;
5869 /* Database filenames are double-zero terminated if they are not
5870 ** URIs with parameters. Hence, they can always be passed into
5871 ** sqlite3_uri_parameter(). */
5872 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5874 }else if( !zName ){
5875 /* If zName is NULL, the upper layer is requesting a temp file. */
5876 assert(isDelete && !isNewJrnl);
5877 rc = unixGetTempname(pVfs->mxPathname, zTmpname);
5878 if( rc!=SQLITE_OK ){
5879 return rc;
5881 zName = zTmpname;
5883 /* Generated temporary filenames are always double-zero terminated
5884 ** for use by sqlite3_uri_parameter(). */
5885 assert( zName[strlen(zName)+1]==0 );
5888 /* Determine the value of the flags parameter passed to POSIX function
5889 ** open(). These must be calculated even if open() is not called, as
5890 ** they may be stored as part of the file handle and used by the
5891 ** 'conch file' locking functions later on. */
5892 if( isReadonly ) openFlags |= O_RDONLY;
5893 if( isReadWrite ) openFlags |= O_RDWR;
5894 if( isCreate ) openFlags |= O_CREAT;
5895 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5896 openFlags |= (O_LARGEFILE|O_BINARY);
5898 if( fd<0 ){
5899 mode_t openMode; /* Permissions to create file with */
5900 uid_t uid; /* Userid for the file */
5901 gid_t gid; /* Groupid for the file */
5902 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
5903 if( rc!=SQLITE_OK ){
5904 assert( !p->pPreallocatedUnused );
5905 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
5906 return rc;
5908 fd = robust_open(zName, openFlags, openMode);
5909 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
5910 assert( !isExclusive || (openFlags & O_CREAT)!=0 );
5911 if( fd<0 ){
5912 if( isNewJrnl && errno==EACCES && osAccess(zName, F_OK) ){
5913 /* If unable to create a journal because the directory is not
5914 ** writable, change the error code to indicate that. */
5915 rc = SQLITE_READONLY_DIRECTORY;
5916 }else if( errno!=EISDIR && isReadWrite ){
5917 /* Failed to open the file for read/write access. Try read-only. */
5918 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
5919 openFlags &= ~(O_RDWR|O_CREAT);
5920 flags |= SQLITE_OPEN_READONLY;
5921 openFlags |= O_RDONLY;
5922 isReadonly = 1;
5923 fd = robust_open(zName, openFlags, openMode);
5926 if( fd<0 ){
5927 int rc2 = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
5928 if( rc==SQLITE_OK ) rc = rc2;
5929 goto open_finished;
5932 /* If this process is running as root and if creating a new rollback
5933 ** journal or WAL file, set the ownership of the journal or WAL to be
5934 ** the same as the original database.
5936 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
5937 robustFchown(fd, uid, gid);
5940 assert( fd>=0 );
5941 if( pOutFlags ){
5942 *pOutFlags = flags;
5945 if( p->pPreallocatedUnused ){
5946 p->pPreallocatedUnused->fd = fd;
5947 p->pPreallocatedUnused->flags = flags;
5950 if( isDelete ){
5951 #if OS_VXWORKS
5952 zPath = zName;
5953 #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
5954 zPath = sqlite3_mprintf("%s", zName);
5955 if( zPath==0 ){
5956 robust_close(p, fd, __LINE__);
5957 return SQLITE_NOMEM_BKPT;
5959 #else
5960 osUnlink(zName);
5961 #endif
5963 #if SQLITE_ENABLE_LOCKING_STYLE
5964 else{
5965 p->openFlags = openFlags;
5967 #endif
5969 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5970 if( fstatfs(fd, &fsInfo) == -1 ){
5971 storeLastErrno(p, errno);
5972 robust_close(p, fd, __LINE__);
5973 return SQLITE_IOERR_ACCESS;
5975 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5976 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5978 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
5979 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5981 #endif
5983 /* Set up appropriate ctrlFlags */
5984 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5985 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5986 noLock = eType!=SQLITE_OPEN_MAIN_DB;
5987 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5988 if( isNewJrnl ) ctrlFlags |= UNIXFILE_DIRSYNC;
5989 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5991 #if SQLITE_ENABLE_LOCKING_STYLE
5992 #if SQLITE_PREFER_PROXY_LOCKING
5993 isAutoProxy = 1;
5994 #endif
5995 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
5996 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5997 int useProxy = 0;
5999 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
6000 ** never use proxy, NULL means use proxy for non-local files only. */
6001 if( envforce!=NULL ){
6002 useProxy = atoi(envforce)>0;
6003 }else{
6004 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
6006 if( useProxy ){
6007 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
6008 if( rc==SQLITE_OK ){
6009 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
6010 if( rc!=SQLITE_OK ){
6011 /* Use unixClose to clean up the resources added in fillInUnixFile
6012 ** and clear all the structure's references. Specifically,
6013 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
6015 unixClose(pFile);
6016 return rc;
6019 goto open_finished;
6022 #endif
6024 assert( zPath==0 || zPath[0]=='/'
6025 || eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL
6027 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
6029 open_finished:
6030 if( rc!=SQLITE_OK ){
6031 sqlite3_free(p->pPreallocatedUnused);
6033 return rc;
6038 ** Delete the file at zPath. If the dirSync argument is true, fsync()
6039 ** the directory after deleting the file.
6041 static int unixDelete(
6042 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
6043 const char *zPath, /* Name of file to be deleted */
6044 int dirSync /* If true, fsync() directory after deleting file */
6046 int rc = SQLITE_OK;
6047 UNUSED_PARAMETER(NotUsed);
6048 SimulateIOError(return SQLITE_IOERR_DELETE);
6049 if( osUnlink(zPath)==(-1) ){
6050 if( errno==ENOENT
6051 #if OS_VXWORKS
6052 || osAccess(zPath,0)!=0
6053 #endif
6055 rc = SQLITE_IOERR_DELETE_NOENT;
6056 }else{
6057 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
6059 return rc;
6061 #ifndef SQLITE_DISABLE_DIRSYNC
6062 if( (dirSync & 1)!=0 ){
6063 int fd;
6064 rc = osOpenDirectory(zPath, &fd);
6065 if( rc==SQLITE_OK ){
6066 if( full_fsync(fd,0,0) ){
6067 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
6069 robust_close(0, fd, __LINE__);
6070 }else{
6071 assert( rc==SQLITE_CANTOPEN );
6072 rc = SQLITE_OK;
6075 #endif
6076 return rc;
6080 ** Test the existence of or access permissions of file zPath. The
6081 ** test performed depends on the value of flags:
6083 ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
6084 ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
6085 ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
6087 ** Otherwise return 0.
6089 static int unixAccess(
6090 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
6091 const char *zPath, /* Path of the file to examine */
6092 int flags, /* What do we want to learn about the zPath file? */
6093 int *pResOut /* Write result boolean here */
6095 UNUSED_PARAMETER(NotUsed);
6096 SimulateIOError( return SQLITE_IOERR_ACCESS; );
6097 assert( pResOut!=0 );
6099 /* The spec says there are three possible values for flags. But only
6100 ** two of them are actually used */
6101 assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
6103 if( flags==SQLITE_ACCESS_EXISTS ){
6104 struct stat buf;
6105 *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
6106 }else{
6107 *pResOut = osAccess(zPath, W_OK|R_OK)==0;
6109 return SQLITE_OK;
6115 static int mkFullPathname(
6116 const char *zPath, /* Input path */
6117 char *zOut, /* Output buffer */
6118 int nOut /* Allocated size of buffer zOut */
6120 int nPath = sqlite3Strlen30(zPath);
6121 int iOff = 0;
6122 if( zPath[0]!='/' ){
6123 if( osGetcwd(zOut, nOut-2)==0 ){
6124 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
6126 iOff = sqlite3Strlen30(zOut);
6127 zOut[iOff++] = '/';
6129 if( (iOff+nPath+1)>nOut ){
6130 /* SQLite assumes that xFullPathname() nul-terminates the output buffer
6131 ** even if it returns an error. */
6132 zOut[iOff] = '\0';
6133 return SQLITE_CANTOPEN_BKPT;
6135 sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
6136 return SQLITE_OK;
6140 ** Turn a relative pathname into a full pathname. The relative path
6141 ** is stored as a nul-terminated string in the buffer pointed to by
6142 ** zPath.
6144 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
6145 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
6146 ** this buffer before returning.
6148 static int unixFullPathname(
6149 sqlite3_vfs *pVfs, /* Pointer to vfs object */
6150 const char *zPath, /* Possibly relative input path */
6151 int nOut, /* Size of output buffer in bytes */
6152 char *zOut /* Output buffer */
6154 #if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
6155 return mkFullPathname(zPath, zOut, nOut);
6156 #else
6157 int rc = SQLITE_OK;
6158 int nByte;
6159 int nLink = 1; /* Number of symbolic links followed so far */
6160 const char *zIn = zPath; /* Input path for each iteration of loop */
6161 char *zDel = 0;
6163 assert( pVfs->mxPathname==MAX_PATHNAME );
6164 UNUSED_PARAMETER(pVfs);
6166 /* It's odd to simulate an io-error here, but really this is just
6167 ** using the io-error infrastructure to test that SQLite handles this
6168 ** function failing. This function could fail if, for example, the
6169 ** current working directory has been unlinked.
6171 SimulateIOError( return SQLITE_ERROR );
6173 do {
6175 /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
6176 ** link, or false otherwise. */
6177 int bLink = 0;
6178 struct stat buf;
6179 if( osLstat(zIn, &buf)!=0 ){
6180 if( errno!=ENOENT ){
6181 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
6183 }else{
6184 bLink = S_ISLNK(buf.st_mode);
6187 if( bLink ){
6188 if( zDel==0 ){
6189 zDel = sqlite3_malloc(nOut);
6190 if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
6191 }else if( ++nLink>SQLITE_MAX_SYMLINKS ){
6192 rc = SQLITE_CANTOPEN_BKPT;
6195 if( rc==SQLITE_OK ){
6196 nByte = osReadlink(zIn, zDel, nOut-1);
6197 if( nByte<0 ){
6198 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
6199 }else{
6200 if( zDel[0]!='/' ){
6201 int n;
6202 for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
6203 if( nByte+n+1>nOut ){
6204 rc = SQLITE_CANTOPEN_BKPT;
6205 }else{
6206 memmove(&zDel[n], zDel, nByte+1);
6207 memcpy(zDel, zIn, n);
6208 nByte += n;
6211 zDel[nByte] = '\0';
6215 zIn = zDel;
6218 assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
6219 if( rc==SQLITE_OK && zIn!=zOut ){
6220 rc = mkFullPathname(zIn, zOut, nOut);
6222 if( bLink==0 ) break;
6223 zIn = zOut;
6224 }while( rc==SQLITE_OK );
6226 sqlite3_free(zDel);
6227 return rc;
6228 #endif /* HAVE_READLINK && HAVE_LSTAT */
6232 #ifndef SQLITE_OMIT_LOAD_EXTENSION
6234 ** Interfaces for opening a shared library, finding entry points
6235 ** within the shared library, and closing the shared library.
6237 #include <dlfcn.h>
6238 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6239 UNUSED_PARAMETER(NotUsed);
6240 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6244 ** SQLite calls this function immediately after a call to unixDlSym() or
6245 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
6246 ** message is available, it is written to zBufOut. If no error message
6247 ** is available, zBufOut is left unmodified and SQLite uses a default
6248 ** error message.
6250 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
6251 const char *zErr;
6252 UNUSED_PARAMETER(NotUsed);
6253 unixEnterMutex();
6254 zErr = dlerror();
6255 if( zErr ){
6256 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
6258 unixLeaveMutex();
6260 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6262 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6263 ** cast into a pointer to a function. And yet the library dlsym() routine
6264 ** returns a void* which is really a pointer to a function. So how do we
6265 ** use dlsym() with -pedantic-errors?
6267 ** Variable x below is defined to be a pointer to a function taking
6268 ** parameters void* and const char* and returning a pointer to a function.
6269 ** We initialize x by assigning it a pointer to the dlsym() function.
6270 ** (That assignment requires a cast.) Then we call the function that
6271 ** x points to.
6273 ** This work-around is unlikely to work correctly on any system where
6274 ** you really cannot cast a function pointer into void*. But then, on the
6275 ** other hand, dlsym() will not work on such a system either, so we have
6276 ** not really lost anything.
6278 void (*(*x)(void*,const char*))(void);
6279 UNUSED_PARAMETER(NotUsed);
6280 x = (void(*(*)(void*,const char*))(void))dlsym;
6281 return (*x)(p, zSym);
6283 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6284 UNUSED_PARAMETER(NotUsed);
6285 dlclose(pHandle);
6287 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6288 #define unixDlOpen 0
6289 #define unixDlError 0
6290 #define unixDlSym 0
6291 #define unixDlClose 0
6292 #endif
6295 ** Write nBuf bytes of random data to the supplied buffer zBuf.
6297 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6298 UNUSED_PARAMETER(NotUsed);
6299 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
6301 /* We have to initialize zBuf to prevent valgrind from reporting
6302 ** errors. The reports issued by valgrind are incorrect - we would
6303 ** prefer that the randomness be increased by making use of the
6304 ** uninitialized space in zBuf - but valgrind errors tend to worry
6305 ** some users. Rather than argue, it seems easier just to initialize
6306 ** the whole array and silence valgrind, even if that means less randomness
6307 ** in the random seed.
6309 ** When testing, initializing zBuf[] to zero is all we do. That means
6310 ** that we always use the same random number sequence. This makes the
6311 ** tests repeatable.
6313 memset(zBuf, 0, nBuf);
6314 randomnessPid = osGetpid(0);
6315 #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
6317 int fd, got;
6318 fd = robust_open("/dev/urandom", O_RDONLY, 0);
6319 if( fd<0 ){
6320 time_t t;
6321 time(&t);
6322 memcpy(zBuf, &t, sizeof(t));
6323 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6324 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6325 nBuf = sizeof(t) + sizeof(randomnessPid);
6326 }else{
6327 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
6328 robust_close(0, fd, __LINE__);
6331 #endif
6332 return nBuf;
6337 ** Sleep for a little while. Return the amount of time slept.
6338 ** The argument is the number of microseconds we want to sleep.
6339 ** The return value is the number of microseconds of sleep actually
6340 ** requested from the underlying operating system, a number which
6341 ** might be greater than or equal to the argument, but not less
6342 ** than the argument.
6344 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
6345 #if OS_VXWORKS
6346 struct timespec sp;
6348 sp.tv_sec = microseconds / 1000000;
6349 sp.tv_nsec = (microseconds % 1000000) * 1000;
6350 nanosleep(&sp, NULL);
6351 UNUSED_PARAMETER(NotUsed);
6352 return microseconds;
6353 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
6354 usleep(microseconds);
6355 UNUSED_PARAMETER(NotUsed);
6356 return microseconds;
6357 #else
6358 int seconds = (microseconds+999999)/1000000;
6359 sleep(seconds);
6360 UNUSED_PARAMETER(NotUsed);
6361 return seconds*1000000;
6362 #endif
6366 ** The following variable, if set to a non-zero value, is interpreted as
6367 ** the number of seconds since 1970 and is used to set the result of
6368 ** sqlite3OsCurrentTime() during testing.
6370 #ifdef SQLITE_TEST
6371 int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
6372 #endif
6375 ** Find the current time (in Universal Coordinated Time). Write into *piNow
6376 ** the current time and date as a Julian Day number times 86_400_000. In
6377 ** other words, write into *piNow the number of milliseconds since the Julian
6378 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6379 ** proleptic Gregorian calendar.
6381 ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6382 ** cannot be found.
6384 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6385 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
6386 int rc = SQLITE_OK;
6387 #if defined(NO_GETTOD)
6388 time_t t;
6389 time(&t);
6390 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
6391 #elif OS_VXWORKS
6392 struct timespec sNow;
6393 clock_gettime(CLOCK_REALTIME, &sNow);
6394 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6395 #else
6396 struct timeval sNow;
6397 (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
6398 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
6399 #endif
6401 #ifdef SQLITE_TEST
6402 if( sqlite3_current_time ){
6403 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6405 #endif
6406 UNUSED_PARAMETER(NotUsed);
6407 return rc;
6410 #ifndef SQLITE_OMIT_DEPRECATED
6412 ** Find the current time (in Universal Coordinated Time). Write the
6413 ** current time and date as a Julian Day number into *prNow and
6414 ** return 0. Return 1 if the time and date cannot be found.
6416 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
6417 sqlite3_int64 i = 0;
6418 int rc;
6419 UNUSED_PARAMETER(NotUsed);
6420 rc = unixCurrentTimeInt64(0, &i);
6421 *prNow = i/86400000.0;
6422 return rc;
6424 #else
6425 # define unixCurrentTime 0
6426 #endif
6429 ** The xGetLastError() method is designed to return a better
6430 ** low-level error message when operating-system problems come up
6431 ** during SQLite operation. Only the integer return code is currently
6432 ** used.
6434 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6435 UNUSED_PARAMETER(NotUsed);
6436 UNUSED_PARAMETER(NotUsed2);
6437 UNUSED_PARAMETER(NotUsed3);
6438 return errno;
6443 ************************ End of sqlite3_vfs methods ***************************
6444 ******************************************************************************/
6446 /******************************************************************************
6447 ************************** Begin Proxy Locking ********************************
6449 ** Proxy locking is a "uber-locking-method" in this sense: It uses the
6450 ** other locking methods on secondary lock files. Proxy locking is a
6451 ** meta-layer over top of the primitive locking implemented above. For
6452 ** this reason, the division that implements of proxy locking is deferred
6453 ** until late in the file (here) after all of the other I/O methods have
6454 ** been defined - so that the primitive locking methods are available
6455 ** as services to help with the implementation of proxy locking.
6457 ****
6459 ** The default locking schemes in SQLite use byte-range locks on the
6460 ** database file to coordinate safe, concurrent access by multiple readers
6461 ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6462 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6463 ** as POSIX read & write locks over fixed set of locations (via fsctl),
6464 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
6465 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6466 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6467 ** address in the shared range is taken for a SHARED lock, the entire
6468 ** shared range is taken for an EXCLUSIVE lock):
6470 ** PENDING_BYTE 0x40000000
6471 ** RESERVED_BYTE 0x40000001
6472 ** SHARED_RANGE 0x40000002 -> 0x40000200
6474 ** This works well on the local file system, but shows a nearly 100x
6475 ** slowdown in read performance on AFP because the AFP client disables
6476 ** the read cache when byte-range locks are present. Enabling the read
6477 ** cache exposes a cache coherency problem that is present on all OS X
6478 ** supported network file systems. NFS and AFP both observe the
6479 ** close-to-open semantics for ensuring cache coherency
6480 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6481 ** address the requirements for concurrent database access by multiple
6482 ** readers and writers
6483 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6485 ** To address the performance and cache coherency issues, proxy file locking
6486 ** changes the way database access is controlled by limiting access to a
6487 ** single host at a time and moving file locks off of the database file
6488 ** and onto a proxy file on the local file system.
6491 ** Using proxy locks
6492 ** -----------------
6494 ** C APIs
6496 ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
6497 ** <proxy_path> | ":auto:");
6498 ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6499 ** &<proxy_path>);
6502 ** SQL pragmas
6504 ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6505 ** PRAGMA [database.]lock_proxy_file
6507 ** Specifying ":auto:" means that if there is a conch file with a matching
6508 ** host ID in it, the proxy path in the conch file will be used, otherwise
6509 ** a proxy path based on the user's temp dir
6510 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6511 ** actual proxy file name is generated from the name and path of the
6512 ** database file. For example:
6514 ** For database path "/Users/me/foo.db"
6515 ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6517 ** Once a lock proxy is configured for a database connection, it can not
6518 ** be removed, however it may be switched to a different proxy path via
6519 ** the above APIs (assuming the conch file is not being held by another
6520 ** connection or process).
6523 ** How proxy locking works
6524 ** -----------------------
6526 ** Proxy file locking relies primarily on two new supporting files:
6528 ** * conch file to limit access to the database file to a single host
6529 ** at a time
6531 ** * proxy file to act as a proxy for the advisory locks normally
6532 ** taken on the database
6534 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
6535 ** by taking an sqlite-style shared lock on the conch file, reading the
6536 ** contents and comparing the host's unique host ID (see below) and lock
6537 ** proxy path against the values stored in the conch. The conch file is
6538 ** stored in the same directory as the database file and the file name
6539 ** is patterned after the database file name as ".<databasename>-conch".
6540 ** If the conch file does not exist, or its contents do not match the
6541 ** host ID and/or proxy path, then the lock is escalated to an exclusive
6542 ** lock and the conch file contents is updated with the host ID and proxy
6543 ** path and the lock is downgraded to a shared lock again. If the conch
6544 ** is held by another process (with a shared lock), the exclusive lock
6545 ** will fail and SQLITE_BUSY is returned.
6547 ** The proxy file - a single-byte file used for all advisory file locks
6548 ** normally taken on the database file. This allows for safe sharing
6549 ** of the database file for multiple readers and writers on the same
6550 ** host (the conch ensures that they all use the same local lock file).
6552 ** Requesting the lock proxy does not immediately take the conch, it is
6553 ** only taken when the first request to lock database file is made.
6554 ** This matches the semantics of the traditional locking behavior, where
6555 ** opening a connection to a database file does not take a lock on it.
6556 ** The shared lock and an open file descriptor are maintained until
6557 ** the connection to the database is closed.
6559 ** The proxy file and the lock file are never deleted so they only need
6560 ** to be created the first time they are used.
6562 ** Configuration options
6563 ** ---------------------
6565 ** SQLITE_PREFER_PROXY_LOCKING
6567 ** Database files accessed on non-local file systems are
6568 ** automatically configured for proxy locking, lock files are
6569 ** named automatically using the same logic as
6570 ** PRAGMA lock_proxy_file=":auto:"
6572 ** SQLITE_PROXY_DEBUG
6574 ** Enables the logging of error messages during host id file
6575 ** retrieval and creation
6577 ** LOCKPROXYDIR
6579 ** Overrides the default directory used for lock proxy files that
6580 ** are named automatically via the ":auto:" setting
6582 ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6584 ** Permissions to use when creating a directory for storing the
6585 ** lock proxy files, only used when LOCKPROXYDIR is not set.
6588 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6589 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6590 ** force proxy locking to be used for every database file opened, and 0
6591 ** will force automatic proxy locking to be disabled for all database
6592 ** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
6593 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6597 ** Proxy locking is only available on MacOSX
6599 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
6602 ** The proxyLockingContext has the path and file structures for the remote
6603 ** and local proxy files in it
6605 typedef struct proxyLockingContext proxyLockingContext;
6606 struct proxyLockingContext {
6607 unixFile *conchFile; /* Open conch file */
6608 char *conchFilePath; /* Name of the conch file */
6609 unixFile *lockProxy; /* Open proxy lock file */
6610 char *lockProxyPath; /* Name of the proxy lock file */
6611 char *dbPath; /* Name of the open file */
6612 int conchHeld; /* 1 if the conch is held, -1 if lockless */
6613 int nFails; /* Number of conch taking failures */
6614 void *oldLockingContext; /* Original lockingcontext to restore on close */
6615 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6619 ** The proxy lock file path for the database at dbPath is written into lPath,
6620 ** which must point to valid, writable memory large enough for a maxLen length
6621 ** file path.
6623 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6624 int len;
6625 int dbLen;
6626 int i;
6628 #ifdef LOCKPROXYDIR
6629 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6630 #else
6631 # ifdef _CS_DARWIN_USER_TEMP_DIR
6633 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
6634 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
6635 lPath, errno, osGetpid(0)));
6636 return SQLITE_IOERR_LOCK;
6638 len = strlcat(lPath, "sqliteplocks", maxLen);
6640 # else
6641 len = strlcpy(lPath, "/tmp/", maxLen);
6642 # endif
6643 #endif
6645 if( lPath[len-1]!='/' ){
6646 len = strlcat(lPath, "/", maxLen);
6649 /* transform the db path to a unique cache name */
6650 dbLen = (int)strlen(dbPath);
6651 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
6652 char c = dbPath[i];
6653 lPath[i+len] = (c=='/')?'_':c;
6655 lPath[i+len]='\0';
6656 strlcat(lPath, ":auto:", maxLen);
6657 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
6658 return SQLITE_OK;
6662 ** Creates the lock file and any missing directories in lockPath
6664 static int proxyCreateLockPath(const char *lockPath){
6665 int i, len;
6666 char buf[MAXPATHLEN];
6667 int start = 0;
6669 assert(lockPath!=NULL);
6670 /* try to create all the intermediate directories */
6671 len = (int)strlen(lockPath);
6672 buf[0] = lockPath[0];
6673 for( i=1; i<len; i++ ){
6674 if( lockPath[i] == '/' && (i - start > 0) ){
6675 /* only mkdir if leaf dir != "." or "/" or ".." */
6676 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6677 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6678 buf[i]='\0';
6679 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
6680 int err=errno;
6681 if( err!=EEXIST ) {
6682 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
6683 "'%s' proxy lock path=%s pid=%d\n",
6684 buf, strerror(err), lockPath, osGetpid(0)));
6685 return err;
6689 start=i+1;
6691 buf[i] = lockPath[i];
6693 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
6694 return 0;
6698 ** Create a new VFS file descriptor (stored in memory obtained from
6699 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
6701 ** The caller is responsible not only for closing the file descriptor
6702 ** but also for freeing the memory associated with the file descriptor.
6704 static int proxyCreateUnixFile(
6705 const char *path, /* path for the new unixFile */
6706 unixFile **ppFile, /* unixFile created and returned by ref */
6707 int islockfile /* if non zero missing dirs will be created */
6709 int fd = -1;
6710 unixFile *pNew;
6711 int rc = SQLITE_OK;
6712 int openFlags = O_RDWR | O_CREAT;
6713 sqlite3_vfs dummyVfs;
6714 int terrno = 0;
6715 UnixUnusedFd *pUnused = NULL;
6717 /* 1. first try to open/create the file
6718 ** 2. if that fails, and this is a lock file (not-conch), try creating
6719 ** the parent directories and then try again.
6720 ** 3. if that fails, try to open the file read-only
6721 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6723 pUnused = findReusableFd(path, openFlags);
6724 if( pUnused ){
6725 fd = pUnused->fd;
6726 }else{
6727 pUnused = sqlite3_malloc64(sizeof(*pUnused));
6728 if( !pUnused ){
6729 return SQLITE_NOMEM_BKPT;
6732 if( fd<0 ){
6733 fd = robust_open(path, openFlags, 0);
6734 terrno = errno;
6735 if( fd<0 && errno==ENOENT && islockfile ){
6736 if( proxyCreateLockPath(path) == SQLITE_OK ){
6737 fd = robust_open(path, openFlags, 0);
6741 if( fd<0 ){
6742 openFlags = O_RDONLY;
6743 fd = robust_open(path, openFlags, 0);
6744 terrno = errno;
6746 if( fd<0 ){
6747 if( islockfile ){
6748 return SQLITE_BUSY;
6750 switch (terrno) {
6751 case EACCES:
6752 return SQLITE_PERM;
6753 case EIO:
6754 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6755 default:
6756 return SQLITE_CANTOPEN_BKPT;
6760 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
6761 if( pNew==NULL ){
6762 rc = SQLITE_NOMEM_BKPT;
6763 goto end_create_proxy;
6765 memset(pNew, 0, sizeof(unixFile));
6766 pNew->openFlags = openFlags;
6767 memset(&dummyVfs, 0, sizeof(dummyVfs));
6768 dummyVfs.pAppData = (void*)&autolockIoFinder;
6769 dummyVfs.zName = "dummy";
6770 pUnused->fd = fd;
6771 pUnused->flags = openFlags;
6772 pNew->pPreallocatedUnused = pUnused;
6774 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
6775 if( rc==SQLITE_OK ){
6776 *ppFile = pNew;
6777 return SQLITE_OK;
6779 end_create_proxy:
6780 robust_close(pNew, fd, __LINE__);
6781 sqlite3_free(pNew);
6782 sqlite3_free(pUnused);
6783 return rc;
6786 #ifdef SQLITE_TEST
6787 /* simulate multiple hosts by creating unique hostid file paths */
6788 int sqlite3_hostid_num = 0;
6789 #endif
6791 #define PROXY_HOSTIDLEN 16 /* conch file host id length */
6793 #ifdef HAVE_GETHOSTUUID
6794 /* Not always defined in the headers as it ought to be */
6795 extern int gethostuuid(uuid_t id, const struct timespec *wait);
6796 #endif
6798 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6799 ** bytes of writable memory.
6801 static int proxyGetHostID(unsigned char *pHostID, int *pError){
6802 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6803 memset(pHostID, 0, PROXY_HOSTIDLEN);
6804 #ifdef HAVE_GETHOSTUUID
6806 struct timespec timeout = {1, 0}; /* 1 sec timeout */
6807 if( gethostuuid(pHostID, &timeout) ){
6808 int err = errno;
6809 if( pError ){
6810 *pError = err;
6812 return SQLITE_IOERR;
6815 #else
6816 UNUSED_PARAMETER(pError);
6817 #endif
6818 #ifdef SQLITE_TEST
6819 /* simulate multiple hosts by creating unique hostid file paths */
6820 if( sqlite3_hostid_num != 0){
6821 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6823 #endif
6825 return SQLITE_OK;
6828 /* The conch file contains the header, host id and lock file path
6830 #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6831 #define PROXY_HEADERLEN 1 /* conch file header length */
6832 #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6833 #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6836 ** Takes an open conch file, copies the contents to a new path and then moves
6837 ** it back. The newly created file's file descriptor is assigned to the
6838 ** conch file structure and finally the original conch file descriptor is
6839 ** closed. Returns zero if successful.
6841 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6842 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6843 unixFile *conchFile = pCtx->conchFile;
6844 char tPath[MAXPATHLEN];
6845 char buf[PROXY_MAXCONCHLEN];
6846 char *cPath = pCtx->conchFilePath;
6847 size_t readLen = 0;
6848 size_t pathLen = 0;
6849 char errmsg[64] = "";
6850 int fd = -1;
6851 int rc = -1;
6852 UNUSED_PARAMETER(myHostID);
6854 /* create a new path by replace the trailing '-conch' with '-break' */
6855 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6856 if( pathLen>MAXPATHLEN || pathLen<6 ||
6857 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
6858 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
6859 goto end_breaklock;
6861 /* read the conch content */
6862 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
6863 if( readLen<PROXY_PATHINDEX ){
6864 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
6865 goto end_breaklock;
6867 /* write it out to the temporary break file */
6868 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
6869 if( fd<0 ){
6870 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
6871 goto end_breaklock;
6873 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
6874 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
6875 goto end_breaklock;
6877 if( rename(tPath, cPath) ){
6878 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
6879 goto end_breaklock;
6881 rc = 0;
6882 fprintf(stderr, "broke stale lock on %s\n", cPath);
6883 robust_close(pFile, conchFile->h, __LINE__);
6884 conchFile->h = fd;
6885 conchFile->openFlags = O_RDWR | O_CREAT;
6887 end_breaklock:
6888 if( rc ){
6889 if( fd>=0 ){
6890 osUnlink(tPath);
6891 robust_close(pFile, fd, __LINE__);
6893 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6895 return rc;
6898 /* Take the requested lock on the conch file and break a stale lock if the
6899 ** host id matches.
6901 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6902 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6903 unixFile *conchFile = pCtx->conchFile;
6904 int rc = SQLITE_OK;
6905 int nTries = 0;
6906 struct timespec conchModTime;
6908 memset(&conchModTime, 0, sizeof(conchModTime));
6909 do {
6910 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6911 nTries ++;
6912 if( rc==SQLITE_BUSY ){
6913 /* If the lock failed (busy):
6914 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6915 * 2nd try: fail if the mod time changed or host id is different, wait
6916 * 10 sec and try again
6917 * 3rd try: break the lock unless the mod time has changed.
6919 struct stat buf;
6920 if( osFstat(conchFile->h, &buf) ){
6921 storeLastErrno(pFile, errno);
6922 return SQLITE_IOERR_LOCK;
6925 if( nTries==1 ){
6926 conchModTime = buf.st_mtimespec;
6927 usleep(500000); /* wait 0.5 sec and try the lock again*/
6928 continue;
6931 assert( nTries>1 );
6932 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6933 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6934 return SQLITE_BUSY;
6937 if( nTries==2 ){
6938 char tBuf[PROXY_MAXCONCHLEN];
6939 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
6940 if( len<0 ){
6941 storeLastErrno(pFile, errno);
6942 return SQLITE_IOERR_LOCK;
6944 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6945 /* don't break the lock if the host id doesn't match */
6946 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6947 return SQLITE_BUSY;
6949 }else{
6950 /* don't break the lock on short read or a version mismatch */
6951 return SQLITE_BUSY;
6953 usleep(10000000); /* wait 10 sec and try the lock again */
6954 continue;
6957 assert( nTries==3 );
6958 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6959 rc = SQLITE_OK;
6960 if( lockType==EXCLUSIVE_LOCK ){
6961 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
6963 if( !rc ){
6964 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6968 } while( rc==SQLITE_BUSY && nTries<3 );
6970 return rc;
6973 /* Takes the conch by taking a shared lock and read the contents conch, if
6974 ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6975 ** lockPath means that the lockPath in the conch file will be used if the
6976 ** host IDs match, or a new lock path will be generated automatically
6977 ** and written to the conch file.
6979 static int proxyTakeConch(unixFile *pFile){
6980 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6982 if( pCtx->conchHeld!=0 ){
6983 return SQLITE_OK;
6984 }else{
6985 unixFile *conchFile = pCtx->conchFile;
6986 uuid_t myHostID;
6987 int pError = 0;
6988 char readBuf[PROXY_MAXCONCHLEN];
6989 char lockPath[MAXPATHLEN];
6990 char *tempLockPath = NULL;
6991 int rc = SQLITE_OK;
6992 int createConch = 0;
6993 int hostIdMatch = 0;
6994 int readLen = 0;
6995 int tryOldLockPath = 0;
6996 int forceNewLockPath = 0;
6998 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6999 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
7000 osGetpid(0)));
7002 rc = proxyGetHostID(myHostID, &pError);
7003 if( (rc&0xff)==SQLITE_IOERR ){
7004 storeLastErrno(pFile, pError);
7005 goto end_takeconch;
7007 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
7008 if( rc!=SQLITE_OK ){
7009 goto end_takeconch;
7011 /* read the existing conch file */
7012 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
7013 if( readLen<0 ){
7014 /* I/O error: lastErrno set by seekAndRead */
7015 storeLastErrno(pFile, conchFile->lastErrno);
7016 rc = SQLITE_IOERR_READ;
7017 goto end_takeconch;
7018 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
7019 readBuf[0]!=(char)PROXY_CONCHVERSION ){
7020 /* a short read or version format mismatch means we need to create a new
7021 ** conch file.
7023 createConch = 1;
7025 /* if the host id matches and the lock path already exists in the conch
7026 ** we'll try to use the path there, if we can't open that path, we'll
7027 ** retry with a new auto-generated path
7029 do { /* in case we need to try again for an :auto: named lock file */
7031 if( !createConch && !forceNewLockPath ){
7032 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
7033 PROXY_HOSTIDLEN);
7034 /* if the conch has data compare the contents */
7035 if( !pCtx->lockProxyPath ){
7036 /* for auto-named local lock file, just check the host ID and we'll
7037 ** use the local lock file path that's already in there
7039 if( hostIdMatch ){
7040 size_t pathLen = (readLen - PROXY_PATHINDEX);
7042 if( pathLen>=MAXPATHLEN ){
7043 pathLen=MAXPATHLEN-1;
7045 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
7046 lockPath[pathLen] = 0;
7047 tempLockPath = lockPath;
7048 tryOldLockPath = 1;
7049 /* create a copy of the lock path if the conch is taken */
7050 goto end_takeconch;
7052 }else if( hostIdMatch
7053 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
7054 readLen-PROXY_PATHINDEX)
7056 /* conch host and lock path match */
7057 goto end_takeconch;
7061 /* if the conch isn't writable and doesn't match, we can't take it */
7062 if( (conchFile->openFlags&O_RDWR) == 0 ){
7063 rc = SQLITE_BUSY;
7064 goto end_takeconch;
7067 /* either the conch didn't match or we need to create a new one */
7068 if( !pCtx->lockProxyPath ){
7069 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
7070 tempLockPath = lockPath;
7071 /* create a copy of the lock path _only_ if the conch is taken */
7074 /* update conch with host and path (this will fail if other process
7075 ** has a shared lock already), if the host id matches, use the big
7076 ** stick.
7078 futimes(conchFile->h, NULL);
7079 if( hostIdMatch && !createConch ){
7080 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
7081 /* We are trying for an exclusive lock but another thread in this
7082 ** same process is still holding a shared lock. */
7083 rc = SQLITE_BUSY;
7084 } else {
7085 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
7087 }else{
7088 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
7090 if( rc==SQLITE_OK ){
7091 char writeBuffer[PROXY_MAXCONCHLEN];
7092 int writeSize = 0;
7094 writeBuffer[0] = (char)PROXY_CONCHVERSION;
7095 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
7096 if( pCtx->lockProxyPath!=NULL ){
7097 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
7098 MAXPATHLEN);
7099 }else{
7100 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
7102 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
7103 robust_ftruncate(conchFile->h, writeSize);
7104 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
7105 full_fsync(conchFile->h,0,0);
7106 /* If we created a new conch file (not just updated the contents of a
7107 ** valid conch file), try to match the permissions of the database
7109 if( rc==SQLITE_OK && createConch ){
7110 struct stat buf;
7111 int err = osFstat(pFile->h, &buf);
7112 if( err==0 ){
7113 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
7114 S_IROTH|S_IWOTH);
7115 /* try to match the database file R/W permissions, ignore failure */
7116 #ifndef SQLITE_PROXY_DEBUG
7117 osFchmod(conchFile->h, cmode);
7118 #else
7120 rc = osFchmod(conchFile->h, cmode);
7121 }while( rc==(-1) && errno==EINTR );
7122 if( rc!=0 ){
7123 int code = errno;
7124 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
7125 cmode, code, strerror(code));
7126 } else {
7127 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
7129 }else{
7130 int code = errno;
7131 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
7132 err, code, strerror(code));
7133 #endif
7137 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
7139 end_takeconch:
7140 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
7141 if( rc==SQLITE_OK && pFile->openFlags ){
7142 int fd;
7143 if( pFile->h>=0 ){
7144 robust_close(pFile, pFile->h, __LINE__);
7146 pFile->h = -1;
7147 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
7148 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
7149 if( fd>=0 ){
7150 pFile->h = fd;
7151 }else{
7152 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
7153 during locking */
7156 if( rc==SQLITE_OK && !pCtx->lockProxy ){
7157 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
7158 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
7159 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
7160 /* we couldn't create the proxy lock file with the old lock file path
7161 ** so try again via auto-naming
7163 forceNewLockPath = 1;
7164 tryOldLockPath = 0;
7165 continue; /* go back to the do {} while start point, try again */
7168 if( rc==SQLITE_OK ){
7169 /* Need to make a copy of path if we extracted the value
7170 ** from the conch file or the path was allocated on the stack
7172 if( tempLockPath ){
7173 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
7174 if( !pCtx->lockProxyPath ){
7175 rc = SQLITE_NOMEM_BKPT;
7179 if( rc==SQLITE_OK ){
7180 pCtx->conchHeld = 1;
7182 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
7183 afpLockingContext *afpCtx;
7184 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
7185 afpCtx->dbPath = pCtx->lockProxyPath;
7187 } else {
7188 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7190 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
7191 rc==SQLITE_OK?"ok":"failed"));
7192 return rc;
7193 } while (1); /* in case we need to retry the :auto: lock file -
7194 ** we should never get here except via the 'continue' call. */
7199 ** If pFile holds a lock on a conch file, then release that lock.
7201 static int proxyReleaseConch(unixFile *pFile){
7202 int rc = SQLITE_OK; /* Subroutine return code */
7203 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
7204 unixFile *conchFile; /* Name of the conch file */
7206 pCtx = (proxyLockingContext *)pFile->lockingContext;
7207 conchFile = pCtx->conchFile;
7208 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
7209 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
7210 osGetpid(0)));
7211 if( pCtx->conchHeld>0 ){
7212 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7214 pCtx->conchHeld = 0;
7215 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
7216 (rc==SQLITE_OK ? "ok" : "failed")));
7217 return rc;
7221 ** Given the name of a database file, compute the name of its conch file.
7222 ** Store the conch filename in memory obtained from sqlite3_malloc64().
7223 ** Make *pConchPath point to the new name. Return SQLITE_OK on success
7224 ** or SQLITE_NOMEM if unable to obtain memory.
7226 ** The caller is responsible for ensuring that the allocated memory
7227 ** space is eventually freed.
7229 ** *pConchPath is set to NULL if a memory allocation error occurs.
7231 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7232 int i; /* Loop counter */
7233 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
7234 char *conchPath; /* buffer in which to construct conch name */
7236 /* Allocate space for the conch filename and initialize the name to
7237 ** the name of the original database file. */
7238 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
7239 if( conchPath==0 ){
7240 return SQLITE_NOMEM_BKPT;
7242 memcpy(conchPath, dbPath, len+1);
7244 /* now insert a "." before the last / character */
7245 for( i=(len-1); i>=0; i-- ){
7246 if( conchPath[i]=='/' ){
7247 i++;
7248 break;
7251 conchPath[i]='.';
7252 while ( i<len ){
7253 conchPath[i+1]=dbPath[i];
7254 i++;
7257 /* append the "-conch" suffix to the file */
7258 memcpy(&conchPath[i+1], "-conch", 7);
7259 assert( (int)strlen(conchPath) == len+7 );
7261 return SQLITE_OK;
7265 /* Takes a fully configured proxy locking-style unix file and switches
7266 ** the local lock file path
7268 static int switchLockProxyPath(unixFile *pFile, const char *path) {
7269 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7270 char *oldPath = pCtx->lockProxyPath;
7271 int rc = SQLITE_OK;
7273 if( pFile->eFileLock!=NO_LOCK ){
7274 return SQLITE_BUSY;
7277 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7278 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7279 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7280 return SQLITE_OK;
7281 }else{
7282 unixFile *lockProxy = pCtx->lockProxy;
7283 pCtx->lockProxy=NULL;
7284 pCtx->conchHeld = 0;
7285 if( lockProxy!=NULL ){
7286 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7287 if( rc ) return rc;
7288 sqlite3_free(lockProxy);
7290 sqlite3_free(oldPath);
7291 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7294 return rc;
7298 ** pFile is a file that has been opened by a prior xOpen call. dbPath
7299 ** is a string buffer at least MAXPATHLEN+1 characters in size.
7301 ** This routine find the filename associated with pFile and writes it
7302 ** int dbPath.
7304 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
7305 #if defined(__APPLE__)
7306 if( pFile->pMethod == &afpIoMethods ){
7307 /* afp style keeps a reference to the db path in the filePath field
7308 ** of the struct */
7309 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
7310 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7311 MAXPATHLEN);
7312 } else
7313 #endif
7314 if( pFile->pMethod == &dotlockIoMethods ){
7315 /* dot lock style uses the locking context to store the dot lock
7316 ** file path */
7317 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7318 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7319 }else{
7320 /* all other styles use the locking context to store the db file path */
7321 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
7322 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
7324 return SQLITE_OK;
7328 ** Takes an already filled in unix file and alters it so all file locking
7329 ** will be performed on the local proxy lock file. The following fields
7330 ** are preserved in the locking context so that they can be restored and
7331 ** the unix structure properly cleaned up at close time:
7332 ** ->lockingContext
7333 ** ->pMethod
7335 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7336 proxyLockingContext *pCtx;
7337 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7338 char *lockPath=NULL;
7339 int rc = SQLITE_OK;
7341 if( pFile->eFileLock!=NO_LOCK ){
7342 return SQLITE_BUSY;
7344 proxyGetDbPathForUnixFile(pFile, dbPath);
7345 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7346 lockPath=NULL;
7347 }else{
7348 lockPath=(char *)path;
7351 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
7352 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
7354 pCtx = sqlite3_malloc64( sizeof(*pCtx) );
7355 if( pCtx==0 ){
7356 return SQLITE_NOMEM_BKPT;
7358 memset(pCtx, 0, sizeof(*pCtx));
7360 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7361 if( rc==SQLITE_OK ){
7362 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7363 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7364 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7365 ** (c) the file system is read-only, then enable no-locking access.
7366 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7367 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7369 struct statfs fsInfo;
7370 struct stat conchInfo;
7371 int goLockless = 0;
7373 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
7374 int err = errno;
7375 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7376 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7379 if( goLockless ){
7380 pCtx->conchHeld = -1; /* read only FS/ lockless */
7381 rc = SQLITE_OK;
7385 if( rc==SQLITE_OK && lockPath ){
7386 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7389 if( rc==SQLITE_OK ){
7390 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7391 if( pCtx->dbPath==NULL ){
7392 rc = SQLITE_NOMEM_BKPT;
7395 if( rc==SQLITE_OK ){
7396 /* all memory is allocated, proxys are created and assigned,
7397 ** switch the locking context and pMethod then return.
7399 pCtx->oldLockingContext = pFile->lockingContext;
7400 pFile->lockingContext = pCtx;
7401 pCtx->pOldMethod = pFile->pMethod;
7402 pFile->pMethod = &proxyIoMethods;
7403 }else{
7404 if( pCtx->conchFile ){
7405 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
7406 sqlite3_free(pCtx->conchFile);
7408 sqlite3DbFree(0, pCtx->lockProxyPath);
7409 sqlite3_free(pCtx->conchFilePath);
7410 sqlite3_free(pCtx);
7412 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7413 (rc==SQLITE_OK ? "ok" : "failed")));
7414 return rc;
7419 ** This routine handles sqlite3_file_control() calls that are specific
7420 ** to proxy locking.
7422 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7423 switch( op ){
7424 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
7425 unixFile *pFile = (unixFile*)id;
7426 if( pFile->pMethod == &proxyIoMethods ){
7427 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7428 proxyTakeConch(pFile);
7429 if( pCtx->lockProxyPath ){
7430 *(const char **)pArg = pCtx->lockProxyPath;
7431 }else{
7432 *(const char **)pArg = ":auto: (not held)";
7434 } else {
7435 *(const char **)pArg = NULL;
7437 return SQLITE_OK;
7439 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
7440 unixFile *pFile = (unixFile*)id;
7441 int rc = SQLITE_OK;
7442 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7443 if( pArg==NULL || (const char *)pArg==0 ){
7444 if( isProxyStyle ){
7445 /* turn off proxy locking - not supported. If support is added for
7446 ** switching proxy locking mode off then it will need to fail if
7447 ** the journal mode is WAL mode.
7449 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7450 }else{
7451 /* turn off proxy locking - already off - NOOP */
7452 rc = SQLITE_OK;
7454 }else{
7455 const char *proxyPath = (const char *)pArg;
7456 if( isProxyStyle ){
7457 proxyLockingContext *pCtx =
7458 (proxyLockingContext*)pFile->lockingContext;
7459 if( !strcmp(pArg, ":auto:")
7460 || (pCtx->lockProxyPath &&
7461 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7463 rc = SQLITE_OK;
7464 }else{
7465 rc = switchLockProxyPath(pFile, proxyPath);
7467 }else{
7468 /* turn on proxy file locking */
7469 rc = proxyTransformUnixFile(pFile, proxyPath);
7472 return rc;
7474 default: {
7475 assert( 0 ); /* The call assures that only valid opcodes are sent */
7478 /*NOTREACHED*/
7479 return SQLITE_ERROR;
7483 ** Within this division (the proxying locking implementation) the procedures
7484 ** above this point are all utilities. The lock-related methods of the
7485 ** proxy-locking sqlite3_io_method object follow.
7490 ** This routine checks if there is a RESERVED lock held on the specified
7491 ** file by this or any other process. If such a lock is held, set *pResOut
7492 ** to a non-zero value otherwise *pResOut is set to zero. The return value
7493 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7495 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7496 unixFile *pFile = (unixFile*)id;
7497 int rc = proxyTakeConch(pFile);
7498 if( rc==SQLITE_OK ){
7499 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7500 if( pCtx->conchHeld>0 ){
7501 unixFile *proxy = pCtx->lockProxy;
7502 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7503 }else{ /* conchHeld < 0 is lockless */
7504 pResOut=0;
7507 return rc;
7511 ** Lock the file with the lock specified by parameter eFileLock - one
7512 ** of the following:
7514 ** (1) SHARED_LOCK
7515 ** (2) RESERVED_LOCK
7516 ** (3) PENDING_LOCK
7517 ** (4) EXCLUSIVE_LOCK
7519 ** Sometimes when requesting one lock state, additional lock states
7520 ** are inserted in between. The locking might fail on one of the later
7521 ** transitions leaving the lock state different from what it started but
7522 ** still short of its goal. The following chart shows the allowed
7523 ** transitions and the inserted intermediate states:
7525 ** UNLOCKED -> SHARED
7526 ** SHARED -> RESERVED
7527 ** SHARED -> (PENDING) -> EXCLUSIVE
7528 ** RESERVED -> (PENDING) -> EXCLUSIVE
7529 ** PENDING -> EXCLUSIVE
7531 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
7532 ** routine to lower a locking level.
7534 static int proxyLock(sqlite3_file *id, int eFileLock) {
7535 unixFile *pFile = (unixFile*)id;
7536 int rc = proxyTakeConch(pFile);
7537 if( rc==SQLITE_OK ){
7538 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7539 if( pCtx->conchHeld>0 ){
7540 unixFile *proxy = pCtx->lockProxy;
7541 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7542 pFile->eFileLock = proxy->eFileLock;
7543 }else{
7544 /* conchHeld < 0 is lockless */
7547 return rc;
7552 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
7553 ** must be either NO_LOCK or SHARED_LOCK.
7555 ** If the locking level of the file descriptor is already at or below
7556 ** the requested locking level, this routine is a no-op.
7558 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
7559 unixFile *pFile = (unixFile*)id;
7560 int rc = proxyTakeConch(pFile);
7561 if( rc==SQLITE_OK ){
7562 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7563 if( pCtx->conchHeld>0 ){
7564 unixFile *proxy = pCtx->lockProxy;
7565 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7566 pFile->eFileLock = proxy->eFileLock;
7567 }else{
7568 /* conchHeld < 0 is lockless */
7571 return rc;
7575 ** Close a file that uses proxy locks.
7577 static int proxyClose(sqlite3_file *id) {
7578 if( ALWAYS(id) ){
7579 unixFile *pFile = (unixFile*)id;
7580 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7581 unixFile *lockProxy = pCtx->lockProxy;
7582 unixFile *conchFile = pCtx->conchFile;
7583 int rc = SQLITE_OK;
7585 if( lockProxy ){
7586 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7587 if( rc ) return rc;
7588 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7589 if( rc ) return rc;
7590 sqlite3_free(lockProxy);
7591 pCtx->lockProxy = 0;
7593 if( conchFile ){
7594 if( pCtx->conchHeld ){
7595 rc = proxyReleaseConch(pFile);
7596 if( rc ) return rc;
7598 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7599 if( rc ) return rc;
7600 sqlite3_free(conchFile);
7602 sqlite3DbFree(0, pCtx->lockProxyPath);
7603 sqlite3_free(pCtx->conchFilePath);
7604 sqlite3DbFree(0, pCtx->dbPath);
7605 /* restore the original locking context and pMethod then close it */
7606 pFile->lockingContext = pCtx->oldLockingContext;
7607 pFile->pMethod = pCtx->pOldMethod;
7608 sqlite3_free(pCtx);
7609 return pFile->pMethod->xClose(id);
7611 return SQLITE_OK;
7616 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
7618 ** The proxy locking style is intended for use with AFP filesystems.
7619 ** And since AFP is only supported on MacOSX, the proxy locking is also
7620 ** restricted to MacOSX.
7623 ******************* End of the proxy lock implementation **********************
7624 ******************************************************************************/
7627 ** Initialize the operating system interface.
7629 ** This routine registers all VFS implementations for unix-like operating
7630 ** systems. This routine, and the sqlite3_os_end() routine that follows,
7631 ** should be the only routines in this file that are visible from other
7632 ** files.
7634 ** This routine is called once during SQLite initialization and by a
7635 ** single thread. The memory allocation and mutex subsystems have not
7636 ** necessarily been initialized when this routine is called, and so they
7637 ** should not be used.
7639 int sqlite3_os_init(void){
7641 ** The following macro defines an initializer for an sqlite3_vfs object.
7642 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7643 ** to the "finder" function. (pAppData is a pointer to a pointer because
7644 ** silly C90 rules prohibit a void* from being cast to a function pointer
7645 ** and so we have to go through the intermediate pointer to avoid problems
7646 ** when compiling with -pedantic-errors on GCC.)
7648 ** The FINDER parameter to this macro is the name of the pointer to the
7649 ** finder-function. The finder-function returns a pointer to the
7650 ** sqlite_io_methods object that implements the desired locking
7651 ** behaviors. See the division above that contains the IOMETHODS
7652 ** macro for addition information on finder-functions.
7654 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7655 ** object. But the "autolockIoFinder" available on MacOSX does a little
7656 ** more than that; it looks at the filesystem type that hosts the
7657 ** database file and tries to choose an locking method appropriate for
7658 ** that filesystem time.
7660 #define UNIXVFS(VFSNAME, FINDER) { \
7661 3, /* iVersion */ \
7662 sizeof(unixFile), /* szOsFile */ \
7663 MAX_PATHNAME, /* mxPathname */ \
7664 0, /* pNext */ \
7665 VFSNAME, /* zName */ \
7666 (void*)&FINDER, /* pAppData */ \
7667 unixOpen, /* xOpen */ \
7668 unixDelete, /* xDelete */ \
7669 unixAccess, /* xAccess */ \
7670 unixFullPathname, /* xFullPathname */ \
7671 unixDlOpen, /* xDlOpen */ \
7672 unixDlError, /* xDlError */ \
7673 unixDlSym, /* xDlSym */ \
7674 unixDlClose, /* xDlClose */ \
7675 unixRandomness, /* xRandomness */ \
7676 unixSleep, /* xSleep */ \
7677 unixCurrentTime, /* xCurrentTime */ \
7678 unixGetLastError, /* xGetLastError */ \
7679 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
7680 unixSetSystemCall, /* xSetSystemCall */ \
7681 unixGetSystemCall, /* xGetSystemCall */ \
7682 unixNextSystemCall, /* xNextSystemCall */ \
7686 ** All default VFSes for unix are contained in the following array.
7688 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7689 ** by the SQLite core when the VFS is registered. So the following
7690 ** array cannot be const.
7692 static sqlite3_vfs aVfs[] = {
7693 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
7694 UNIXVFS("unix", autolockIoFinder ),
7695 #elif OS_VXWORKS
7696 UNIXVFS("unix", vxworksIoFinder ),
7697 #else
7698 UNIXVFS("unix", posixIoFinder ),
7699 #endif
7700 UNIXVFS("unix-none", nolockIoFinder ),
7701 UNIXVFS("unix-dotfile", dotlockIoFinder ),
7702 UNIXVFS("unix-excl", posixIoFinder ),
7703 #if OS_VXWORKS
7704 UNIXVFS("unix-namedsem", semIoFinder ),
7705 #endif
7706 #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
7707 UNIXVFS("unix-posix", posixIoFinder ),
7708 #endif
7709 #if SQLITE_ENABLE_LOCKING_STYLE
7710 UNIXVFS("unix-flock", flockIoFinder ),
7711 #endif
7712 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
7713 UNIXVFS("unix-afp", afpIoFinder ),
7714 UNIXVFS("unix-nfs", nfsIoFinder ),
7715 UNIXVFS("unix-proxy", proxyIoFinder ),
7716 #endif
7718 unsigned int i; /* Loop counter */
7720 /* Double-check that the aSyscall[] array has been constructed
7721 ** correctly. See ticket [bb3a86e890c8e96ab] */
7722 assert( ArraySize(aSyscall)==29 );
7724 /* Register all VFSes defined in the aVfs[] array */
7725 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
7726 sqlite3_vfs_register(&aVfs[i], i==0);
7728 unixBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
7729 return SQLITE_OK;
7733 ** Shutdown the operating system interface.
7735 ** Some operating systems might need to do some cleanup in this routine,
7736 ** to release dynamically allocated objects. But not on unix.
7737 ** This routine is a no-op for unix.
7739 int sqlite3_os_end(void){
7740 unixBigLock = 0;
7741 return SQLITE_OK;
7744 #endif /* SQLITE_OS_UNIX */