Get writes working on the sqlite_dbpage virtual table. Add a few test cases.
[sqlite.git] / src / os_unix.c
blob4445104dd62a8f29dcd6841dcd2c69d06d486c41
1 /*
2 ** 2004 May 22
3 **
4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
6 **
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 ******************************************************************************
13 ** This file contains the VFS implementation for unix-like operating systems
14 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
16 ** There are actually several different VFS implementations in this file.
17 ** The differences are in the way that file locking is done. The default
18 ** implementation uses Posix Advisory Locks. Alternative implementations
19 ** use flock(), dot-files, various proprietary locking schemas, or simply
20 ** skip locking all together.
22 ** This source file is organized into divisions where the logic for various
23 ** subfunctions is contained within the appropriate division. PLEASE
24 ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
25 ** in the correct division and should be clearly labeled.
27 ** The layout of divisions is as follows:
29 ** * General-purpose declarations and utility functions.
30 ** * Unique file ID logic used by VxWorks.
31 ** * Various locking primitive implementations (all except proxy locking):
32 ** + for Posix Advisory Locks
33 ** + for no-op locks
34 ** + for dot-file locks
35 ** + for flock() locking
36 ** + for named semaphore locks (VxWorks only)
37 ** + for AFP filesystem locks (MacOSX only)
38 ** * sqlite3_file methods not associated with locking.
39 ** * Definitions of sqlite3_io_methods objects for all locking
40 ** methods plus "finder" functions for each locking method.
41 ** * sqlite3_vfs method implementations.
42 ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
43 ** * Definitions of sqlite3_vfs objects for all locking methods
44 ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
46 #include "sqliteInt.h"
47 #if SQLITE_OS_UNIX /* This file is used on unix only */
50 ** There are various methods for file locking used for concurrency
51 ** control:
53 ** 1. POSIX locking (the default),
54 ** 2. No locking,
55 ** 3. Dot-file locking,
56 ** 4. flock() locking,
57 ** 5. AFP locking (OSX only),
58 ** 6. Named POSIX semaphores (VXWorks only),
59 ** 7. proxy locking. (OSX only)
61 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
62 ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
63 ** selection of the appropriate locking style based on the filesystem
64 ** where the database is located.
66 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
67 # if defined(__APPLE__)
68 # define SQLITE_ENABLE_LOCKING_STYLE 1
69 # else
70 # define SQLITE_ENABLE_LOCKING_STYLE 0
71 # endif
72 #endif
74 /* Use pread() and pwrite() if they are available */
75 #if defined(__APPLE__)
76 # define HAVE_PREAD 1
77 # define HAVE_PWRITE 1
78 #endif
79 #if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
80 # undef USE_PREAD
81 # define USE_PREAD64 1
82 #elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)
83 # undef USE_PREAD64
84 # define USE_PREAD 1
85 #endif
88 ** standard include files.
90 #include <sys/types.h>
91 #include <sys/stat.h>
92 #include <fcntl.h>
93 #include <sys/ioctl.h>
94 #include <unistd.h>
95 #include <time.h>
96 #include <sys/time.h>
97 #include <errno.h>
98 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
99 # include <sys/mman.h>
100 #endif
102 #if SQLITE_ENABLE_LOCKING_STYLE
103 # include <sys/ioctl.h>
104 # include <sys/file.h>
105 # include <sys/param.h>
106 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
108 #if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
109 (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
110 # if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
111 && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
112 # define HAVE_GETHOSTUUID 1
113 # else
114 # warning "gethostuuid() is disabled."
115 # endif
116 #endif
119 #if OS_VXWORKS
120 # include <sys/ioctl.h>
121 # include <semaphore.h>
122 # include <limits.h>
123 #endif /* OS_VXWORKS */
125 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
126 # include <sys/mount.h>
127 #endif
129 #ifdef HAVE_UTIME
130 # include <utime.h>
131 #endif
134 ** Allowed values of unixFile.fsFlags
136 #define SQLITE_FSFLAGS_IS_MSDOS 0x1
139 ** If we are to be thread-safe, include the pthreads header and define
140 ** the SQLITE_UNIX_THREADS macro.
142 #if SQLITE_THREADSAFE
143 # include <pthread.h>
144 # define SQLITE_UNIX_THREADS 1
145 #endif
148 ** Default permissions when creating a new file
150 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
151 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
152 #endif
155 ** Default permissions when creating auto proxy dir
157 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
158 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
159 #endif
162 ** Maximum supported path-length.
164 #define MAX_PATHNAME 512
167 ** Maximum supported symbolic links
169 #define SQLITE_MAX_SYMLINKS 100
171 /* Always cast the getpid() return type for compatibility with
172 ** kernel modules in VxWorks. */
173 #define osGetpid(X) (pid_t)getpid()
176 ** Only set the lastErrno if the error code is a real error and not
177 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
179 #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
181 /* Forward references */
182 typedef struct unixShm unixShm; /* Connection shared memory */
183 typedef struct unixShmNode unixShmNode; /* Shared memory instance */
184 typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
185 typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
188 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
189 ** cannot be closed immediately. In these cases, instances of the following
190 ** structure are used to store the file descriptor while waiting for an
191 ** opportunity to either close or reuse it.
193 struct UnixUnusedFd {
194 int fd; /* File descriptor to close */
195 int flags; /* Flags this file descriptor was opened with */
196 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
200 ** The unixFile structure is subclass of sqlite3_file specific to the unix
201 ** VFS implementations.
203 typedef struct unixFile unixFile;
204 struct unixFile {
205 sqlite3_io_methods const *pMethod; /* Always the first entry */
206 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
207 unixInodeInfo *pInode; /* Info about locks on this inode */
208 int h; /* The file descriptor */
209 unsigned char eFileLock; /* The type of lock held on this fd */
210 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
211 int lastErrno; /* The unix errno from last I/O error */
212 void *lockingContext; /* Locking style specific state */
213 UnixUnusedFd *pPreallocatedUnused; /* Pre-allocated UnixUnusedFd */
214 const char *zPath; /* Name of the file */
215 unixShm *pShm; /* Shared memory segment information */
216 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
217 #if SQLITE_MAX_MMAP_SIZE>0
218 int nFetchOut; /* Number of outstanding xFetch refs */
219 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
220 sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
221 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
222 void *pMapRegion; /* Memory mapped region */
223 #endif
224 int sectorSize; /* Device sector size */
225 int deviceCharacteristics; /* Precomputed device characteristics */
226 #if SQLITE_ENABLE_LOCKING_STYLE
227 int openFlags; /* The flags specified at open() */
228 #endif
229 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
230 unsigned fsFlags; /* cached details from statfs() */
231 #endif
232 #if OS_VXWORKS
233 struct vxworksFileId *pId; /* Unique file ID */
234 #endif
235 #ifdef SQLITE_DEBUG
236 /* The next group of variables are used to track whether or not the
237 ** transaction counter in bytes 24-27 of database files are updated
238 ** whenever any part of the database changes. An assertion fault will
239 ** occur if a file is updated without also updating the transaction
240 ** counter. This test is made to avoid new problems similar to the
241 ** one described by ticket #3584.
243 unsigned char transCntrChng; /* True if the transaction counter changed */
244 unsigned char dbUpdate; /* True if any part of database file changed */
245 unsigned char inNormalWrite; /* True if in a normal write operation */
247 #endif
249 #ifdef SQLITE_TEST
250 /* In test mode, increase the size of this structure a bit so that
251 ** it is larger than the struct CrashFile defined in test6.c.
253 char aPadding[32];
254 #endif
257 /* This variable holds the process id (pid) from when the xRandomness()
258 ** method was called. If xOpen() is called from a different process id,
259 ** indicating that a fork() has occurred, the PRNG will be reset.
261 static pid_t randomnessPid = 0;
264 ** Allowed values for the unixFile.ctrlFlags bitmask:
266 #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
267 #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
268 #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
269 #ifndef SQLITE_DISABLE_DIRSYNC
270 # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
271 #else
272 # define UNIXFILE_DIRSYNC 0x00
273 #endif
274 #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
275 #define UNIXFILE_DELETE 0x20 /* Delete on close */
276 #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
277 #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
280 ** Include code that is common to all os_*.c files
282 #include "os_common.h"
285 ** Define various macros that are missing from some systems.
287 #ifndef O_LARGEFILE
288 # define O_LARGEFILE 0
289 #endif
290 #ifdef SQLITE_DISABLE_LFS
291 # undef O_LARGEFILE
292 # define O_LARGEFILE 0
293 #endif
294 #ifndef O_NOFOLLOW
295 # define O_NOFOLLOW 0
296 #endif
297 #ifndef O_BINARY
298 # define O_BINARY 0
299 #endif
302 ** The threadid macro resolves to the thread-id or to 0. Used for
303 ** testing and debugging only.
305 #if SQLITE_THREADSAFE
306 #define threadid pthread_self()
307 #else
308 #define threadid 0
309 #endif
312 ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
314 #if !defined(HAVE_MREMAP)
315 # if defined(__linux__) && defined(_GNU_SOURCE)
316 # define HAVE_MREMAP 1
317 # else
318 # define HAVE_MREMAP 0
319 # endif
320 #endif
323 ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
324 ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
326 #ifdef __ANDROID__
327 # define lseek lseek64
328 #endif
330 #ifdef __linux__
332 ** Linux-specific IOCTL magic numbers used for controlling F2FS
334 #define F2FS_IOCTL_MAGIC 0xf5
335 #define F2FS_IOC_START_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 1)
336 #define F2FS_IOC_COMMIT_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 2)
337 #define F2FS_IOC_START_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 3)
338 #define F2FS_IOC_ABORT_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 5)
339 #define F2FS_IOC_GET_FEATURES _IOR(F2FS_IOCTL_MAGIC, 12, u32)
340 #define F2FS_FEATURE_ATOMIC_WRITE 0x0004
341 #endif /* __linux__ */
345 ** Different Unix systems declare open() in different ways. Same use
346 ** open(const char*,int,mode_t). Others use open(const char*,int,...).
347 ** The difference is important when using a pointer to the function.
349 ** The safest way to deal with the problem is to always use this wrapper
350 ** which always has the same well-defined interface.
352 static int posixOpen(const char *zFile, int flags, int mode){
353 return open(zFile, flags, mode);
356 /* Forward reference */
357 static int openDirectory(const char*, int*);
358 static int unixGetpagesize(void);
361 ** Many system calls are accessed through pointer-to-functions so that
362 ** they may be overridden at runtime to facilitate fault injection during
363 ** testing and sandboxing. The following array holds the names and pointers
364 ** to all overrideable system calls.
366 static struct unix_syscall {
367 const char *zName; /* Name of the system call */
368 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
369 sqlite3_syscall_ptr pDefault; /* Default value */
370 } aSyscall[] = {
371 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
372 #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
374 { "close", (sqlite3_syscall_ptr)close, 0 },
375 #define osClose ((int(*)(int))aSyscall[1].pCurrent)
377 { "access", (sqlite3_syscall_ptr)access, 0 },
378 #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
380 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
381 #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
383 { "stat", (sqlite3_syscall_ptr)stat, 0 },
384 #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
387 ** The DJGPP compiler environment looks mostly like Unix, but it
388 ** lacks the fcntl() system call. So redefine fcntl() to be something
389 ** that always succeeds. This means that locking does not occur under
390 ** DJGPP. But it is DOS - what did you expect?
392 #ifdef __DJGPP__
393 { "fstat", 0, 0 },
394 #define osFstat(a,b,c) 0
395 #else
396 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
397 #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
398 #endif
400 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
401 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
403 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
404 #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
406 { "read", (sqlite3_syscall_ptr)read, 0 },
407 #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
409 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
410 { "pread", (sqlite3_syscall_ptr)pread, 0 },
411 #else
412 { "pread", (sqlite3_syscall_ptr)0, 0 },
413 #endif
414 #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
416 #if defined(USE_PREAD64)
417 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
418 #else
419 { "pread64", (sqlite3_syscall_ptr)0, 0 },
420 #endif
421 #define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
423 { "write", (sqlite3_syscall_ptr)write, 0 },
424 #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
426 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
427 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
428 #else
429 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
430 #endif
431 #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
432 aSyscall[12].pCurrent)
434 #if defined(USE_PREAD64)
435 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
436 #else
437 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
438 #endif
439 #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off64_t))\
440 aSyscall[13].pCurrent)
442 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
443 #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
445 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
446 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
447 #else
448 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
449 #endif
450 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
452 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
453 #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
455 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
456 #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
458 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
459 #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
461 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
462 #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
464 #if defined(HAVE_FCHOWN)
465 { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
466 #else
467 { "fchown", (sqlite3_syscall_ptr)0, 0 },
468 #endif
469 #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
471 { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
472 #define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
474 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
475 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
476 #else
477 { "mmap", (sqlite3_syscall_ptr)0, 0 },
478 #endif
479 #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
481 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
482 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
483 #else
484 { "munmap", (sqlite3_syscall_ptr)0, 0 },
485 #endif
486 #define osMunmap ((void*(*)(void*,size_t))aSyscall[23].pCurrent)
488 #if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
489 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
490 #else
491 { "mremap", (sqlite3_syscall_ptr)0, 0 },
492 #endif
493 #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
495 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
496 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
497 #else
498 { "getpagesize", (sqlite3_syscall_ptr)0, 0 },
499 #endif
500 #define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
502 #if defined(HAVE_READLINK)
503 { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
504 #else
505 { "readlink", (sqlite3_syscall_ptr)0, 0 },
506 #endif
507 #define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
509 #if defined(HAVE_LSTAT)
510 { "lstat", (sqlite3_syscall_ptr)lstat, 0 },
511 #else
512 { "lstat", (sqlite3_syscall_ptr)0, 0 },
513 #endif
514 #define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
516 { "ioctl", (sqlite3_syscall_ptr)ioctl, 0 },
517 #define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent)
519 }; /* End of the overrideable system calls */
523 ** On some systems, calls to fchown() will trigger a message in a security
524 ** log if they come from non-root processes. So avoid calling fchown() if
525 ** we are not running as root.
527 static int robustFchown(int fd, uid_t uid, gid_t gid){
528 #if defined(HAVE_FCHOWN)
529 return osGeteuid() ? 0 : osFchown(fd,uid,gid);
530 #else
531 return 0;
532 #endif
536 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
537 ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
538 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
539 ** system call named zName.
541 static int unixSetSystemCall(
542 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
543 const char *zName, /* Name of system call to override */
544 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
546 unsigned int i;
547 int rc = SQLITE_NOTFOUND;
549 UNUSED_PARAMETER(pNotUsed);
550 if( zName==0 ){
551 /* If no zName is given, restore all system calls to their default
552 ** settings and return NULL
554 rc = SQLITE_OK;
555 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
556 if( aSyscall[i].pDefault ){
557 aSyscall[i].pCurrent = aSyscall[i].pDefault;
560 }else{
561 /* If zName is specified, operate on only the one system call
562 ** specified.
564 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
565 if( strcmp(zName, aSyscall[i].zName)==0 ){
566 if( aSyscall[i].pDefault==0 ){
567 aSyscall[i].pDefault = aSyscall[i].pCurrent;
569 rc = SQLITE_OK;
570 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
571 aSyscall[i].pCurrent = pNewFunc;
572 break;
576 return rc;
580 ** Return the value of a system call. Return NULL if zName is not a
581 ** recognized system call name. NULL is also returned if the system call
582 ** is currently undefined.
584 static sqlite3_syscall_ptr unixGetSystemCall(
585 sqlite3_vfs *pNotUsed,
586 const char *zName
588 unsigned int i;
590 UNUSED_PARAMETER(pNotUsed);
591 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
592 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
594 return 0;
598 ** Return the name of the first system call after zName. If zName==NULL
599 ** then return the name of the first system call. Return NULL if zName
600 ** is the last system call or if zName is not the name of a valid
601 ** system call.
603 static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
604 int i = -1;
606 UNUSED_PARAMETER(p);
607 if( zName ){
608 for(i=0; i<ArraySize(aSyscall)-1; i++){
609 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
612 for(i++; i<ArraySize(aSyscall); i++){
613 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
615 return 0;
619 ** Do not accept any file descriptor less than this value, in order to avoid
620 ** opening database file using file descriptors that are commonly used for
621 ** standard input, output, and error.
623 #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
624 # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
625 #endif
628 ** Invoke open(). Do so multiple times, until it either succeeds or
629 ** fails for some reason other than EINTR.
631 ** If the file creation mode "m" is 0 then set it to the default for
632 ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
633 ** 0644) as modified by the system umask. If m is not 0, then
634 ** make the file creation mode be exactly m ignoring the umask.
636 ** The m parameter will be non-zero only when creating -wal, -journal,
637 ** and -shm files. We want those files to have *exactly* the same
638 ** permissions as their original database, unadulterated by the umask.
639 ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
640 ** transaction crashes and leaves behind hot journals, then any
641 ** process that is able to write to the database will also be able to
642 ** recover the hot journals.
644 static int robust_open(const char *z, int f, mode_t m){
645 int fd;
646 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
647 while(1){
648 #if defined(O_CLOEXEC)
649 fd = osOpen(z,f|O_CLOEXEC,m2);
650 #else
651 fd = osOpen(z,f,m2);
652 #endif
653 if( fd<0 ){
654 if( errno==EINTR ) continue;
655 break;
657 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
658 osClose(fd);
659 sqlite3_log(SQLITE_WARNING,
660 "attempt to open \"%s\" as file descriptor %d", z, fd);
661 fd = -1;
662 if( osOpen("/dev/null", f, m)<0 ) break;
664 if( fd>=0 ){
665 if( m!=0 ){
666 struct stat statbuf;
667 if( osFstat(fd, &statbuf)==0
668 && statbuf.st_size==0
669 && (statbuf.st_mode&0777)!=m
671 osFchmod(fd, m);
674 #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
675 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
676 #endif
678 return fd;
682 ** Helper functions to obtain and relinquish the global mutex. The
683 ** global mutex is used to protect the unixInodeInfo and
684 ** vxworksFileId objects used by this file, all of which may be
685 ** shared by multiple threads.
687 ** Function unixMutexHeld() is used to assert() that the global mutex
688 ** is held when required. This function is only used as part of assert()
689 ** statements. e.g.
691 ** unixEnterMutex()
692 ** assert( unixMutexHeld() );
693 ** unixEnterLeave()
695 static void unixEnterMutex(void){
696 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
698 static void unixLeaveMutex(void){
699 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
701 #ifdef SQLITE_DEBUG
702 static int unixMutexHeld(void) {
703 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
705 #endif
708 #ifdef SQLITE_HAVE_OS_TRACE
710 ** Helper function for printing out trace information from debugging
711 ** binaries. This returns the string representation of the supplied
712 ** integer lock-type.
714 static const char *azFileLock(int eFileLock){
715 switch( eFileLock ){
716 case NO_LOCK: return "NONE";
717 case SHARED_LOCK: return "SHARED";
718 case RESERVED_LOCK: return "RESERVED";
719 case PENDING_LOCK: return "PENDING";
720 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
722 return "ERROR";
724 #endif
726 #ifdef SQLITE_LOCK_TRACE
728 ** Print out information about all locking operations.
730 ** This routine is used for troubleshooting locks on multithreaded
731 ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
732 ** command-line option on the compiler. This code is normally
733 ** turned off.
735 static int lockTrace(int fd, int op, struct flock *p){
736 char *zOpName, *zType;
737 int s;
738 int savedErrno;
739 if( op==F_GETLK ){
740 zOpName = "GETLK";
741 }else if( op==F_SETLK ){
742 zOpName = "SETLK";
743 }else{
744 s = osFcntl(fd, op, p);
745 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
746 return s;
748 if( p->l_type==F_RDLCK ){
749 zType = "RDLCK";
750 }else if( p->l_type==F_WRLCK ){
751 zType = "WRLCK";
752 }else if( p->l_type==F_UNLCK ){
753 zType = "UNLCK";
754 }else{
755 assert( 0 );
757 assert( p->l_whence==SEEK_SET );
758 s = osFcntl(fd, op, p);
759 savedErrno = errno;
760 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
761 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
762 (int)p->l_pid, s);
763 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
764 struct flock l2;
765 l2 = *p;
766 osFcntl(fd, F_GETLK, &l2);
767 if( l2.l_type==F_RDLCK ){
768 zType = "RDLCK";
769 }else if( l2.l_type==F_WRLCK ){
770 zType = "WRLCK";
771 }else if( l2.l_type==F_UNLCK ){
772 zType = "UNLCK";
773 }else{
774 assert( 0 );
776 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
777 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
779 errno = savedErrno;
780 return s;
782 #undef osFcntl
783 #define osFcntl lockTrace
784 #endif /* SQLITE_LOCK_TRACE */
787 ** Retry ftruncate() calls that fail due to EINTR
789 ** All calls to ftruncate() within this file should be made through
790 ** this wrapper. On the Android platform, bypassing the logic below
791 ** could lead to a corrupt database.
793 static int robust_ftruncate(int h, sqlite3_int64 sz){
794 int rc;
795 #ifdef __ANDROID__
796 /* On Android, ftruncate() always uses 32-bit offsets, even if
797 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
798 ** truncate a file to any size larger than 2GiB. Silently ignore any
799 ** such attempts. */
800 if( sz>(sqlite3_int64)0x7FFFFFFF ){
801 rc = SQLITE_OK;
802 }else
803 #endif
804 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
805 return rc;
809 ** This routine translates a standard POSIX errno code into something
810 ** useful to the clients of the sqlite3 functions. Specifically, it is
811 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
812 ** and a variety of "please close the file descriptor NOW" errors into
813 ** SQLITE_IOERR
815 ** Errors during initialization of locks, or file system support for locks,
816 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
818 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
819 assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
820 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
821 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
822 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
823 switch (posixError) {
824 case EACCES:
825 case EAGAIN:
826 case ETIMEDOUT:
827 case EBUSY:
828 case EINTR:
829 case ENOLCK:
830 /* random NFS retry error, unless during file system support
831 * introspection, in which it actually means what it says */
832 return SQLITE_BUSY;
834 case EPERM:
835 return SQLITE_PERM;
837 default:
838 return sqliteIOErr;
843 /******************************************************************************
844 ****************** Begin Unique File ID Utility Used By VxWorks ***************
846 ** On most versions of unix, we can get a unique ID for a file by concatenating
847 ** the device number and the inode number. But this does not work on VxWorks.
848 ** On VxWorks, a unique file id must be based on the canonical filename.
850 ** A pointer to an instance of the following structure can be used as a
851 ** unique file ID in VxWorks. Each instance of this structure contains
852 ** a copy of the canonical filename. There is also a reference count.
853 ** The structure is reclaimed when the number of pointers to it drops to
854 ** zero.
856 ** There are never very many files open at one time and lookups are not
857 ** a performance-critical path, so it is sufficient to put these
858 ** structures on a linked list.
860 struct vxworksFileId {
861 struct vxworksFileId *pNext; /* Next in a list of them all */
862 int nRef; /* Number of references to this one */
863 int nName; /* Length of the zCanonicalName[] string */
864 char *zCanonicalName; /* Canonical filename */
867 #if OS_VXWORKS
869 ** All unique filenames are held on a linked list headed by this
870 ** variable:
872 static struct vxworksFileId *vxworksFileList = 0;
875 ** Simplify a filename into its canonical form
876 ** by making the following changes:
878 ** * removing any trailing and duplicate /
879 ** * convert /./ into just /
880 ** * convert /A/../ where A is any simple name into just /
882 ** Changes are made in-place. Return the new name length.
884 ** The original filename is in z[0..n-1]. Return the number of
885 ** characters in the simplified name.
887 static int vxworksSimplifyName(char *z, int n){
888 int i, j;
889 while( n>1 && z[n-1]=='/' ){ n--; }
890 for(i=j=0; i<n; i++){
891 if( z[i]=='/' ){
892 if( z[i+1]=='/' ) continue;
893 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
894 i += 1;
895 continue;
897 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
898 while( j>0 && z[j-1]!='/' ){ j--; }
899 if( j>0 ){ j--; }
900 i += 2;
901 continue;
904 z[j++] = z[i];
906 z[j] = 0;
907 return j;
911 ** Find a unique file ID for the given absolute pathname. Return
912 ** a pointer to the vxworksFileId object. This pointer is the unique
913 ** file ID.
915 ** The nRef field of the vxworksFileId object is incremented before
916 ** the object is returned. A new vxworksFileId object is created
917 ** and added to the global list if necessary.
919 ** If a memory allocation error occurs, return NULL.
921 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
922 struct vxworksFileId *pNew; /* search key and new file ID */
923 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
924 int n; /* Length of zAbsoluteName string */
926 assert( zAbsoluteName[0]=='/' );
927 n = (int)strlen(zAbsoluteName);
928 pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
929 if( pNew==0 ) return 0;
930 pNew->zCanonicalName = (char*)&pNew[1];
931 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
932 n = vxworksSimplifyName(pNew->zCanonicalName, n);
934 /* Search for an existing entry that matching the canonical name.
935 ** If found, increment the reference count and return a pointer to
936 ** the existing file ID.
938 unixEnterMutex();
939 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
940 if( pCandidate->nName==n
941 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
943 sqlite3_free(pNew);
944 pCandidate->nRef++;
945 unixLeaveMutex();
946 return pCandidate;
950 /* No match was found. We will make a new file ID */
951 pNew->nRef = 1;
952 pNew->nName = n;
953 pNew->pNext = vxworksFileList;
954 vxworksFileList = pNew;
955 unixLeaveMutex();
956 return pNew;
960 ** Decrement the reference count on a vxworksFileId object. Free
961 ** the object when the reference count reaches zero.
963 static void vxworksReleaseFileId(struct vxworksFileId *pId){
964 unixEnterMutex();
965 assert( pId->nRef>0 );
966 pId->nRef--;
967 if( pId->nRef==0 ){
968 struct vxworksFileId **pp;
969 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
970 assert( *pp==pId );
971 *pp = pId->pNext;
972 sqlite3_free(pId);
974 unixLeaveMutex();
976 #endif /* OS_VXWORKS */
977 /*************** End of Unique File ID Utility Used By VxWorks ****************
978 ******************************************************************************/
981 /******************************************************************************
982 *************************** Posix Advisory Locking ****************************
984 ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
985 ** section 6.5.2.2 lines 483 through 490 specify that when a process
986 ** sets or clears a lock, that operation overrides any prior locks set
987 ** by the same process. It does not explicitly say so, but this implies
988 ** that it overrides locks set by the same process using a different
989 ** file descriptor. Consider this test case:
991 ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
992 ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
994 ** Suppose ./file1 and ./file2 are really the same file (because
995 ** one is a hard or symbolic link to the other) then if you set
996 ** an exclusive lock on fd1, then try to get an exclusive lock
997 ** on fd2, it works. I would have expected the second lock to
998 ** fail since there was already a lock on the file due to fd1.
999 ** But not so. Since both locks came from the same process, the
1000 ** second overrides the first, even though they were on different
1001 ** file descriptors opened on different file names.
1003 ** This means that we cannot use POSIX locks to synchronize file access
1004 ** among competing threads of the same process. POSIX locks will work fine
1005 ** to synchronize access for threads in separate processes, but not
1006 ** threads within the same process.
1008 ** To work around the problem, SQLite has to manage file locks internally
1009 ** on its own. Whenever a new database is opened, we have to find the
1010 ** specific inode of the database file (the inode is determined by the
1011 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
1012 ** and check for locks already existing on that inode. When locks are
1013 ** created or removed, we have to look at our own internal record of the
1014 ** locks to see if another thread has previously set a lock on that same
1015 ** inode.
1017 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
1018 ** For VxWorks, we have to use the alternative unique ID system based on
1019 ** canonical filename and implemented in the previous division.)
1021 ** The sqlite3_file structure for POSIX is no longer just an integer file
1022 ** descriptor. It is now a structure that holds the integer file
1023 ** descriptor and a pointer to a structure that describes the internal
1024 ** locks on the corresponding inode. There is one locking structure
1025 ** per inode, so if the same inode is opened twice, both unixFile structures
1026 ** point to the same locking structure. The locking structure keeps
1027 ** a reference count (so we will know when to delete it) and a "cnt"
1028 ** field that tells us its internal lock status. cnt==0 means the
1029 ** file is unlocked. cnt==-1 means the file has an exclusive lock.
1030 ** cnt>0 means there are cnt shared locks on the file.
1032 ** Any attempt to lock or unlock a file first checks the locking
1033 ** structure. The fcntl() system call is only invoked to set a
1034 ** POSIX lock if the internal lock structure transitions between
1035 ** a locked and an unlocked state.
1037 ** But wait: there are yet more problems with POSIX advisory locks.
1039 ** If you close a file descriptor that points to a file that has locks,
1040 ** all locks on that file that are owned by the current process are
1041 ** released. To work around this problem, each unixInodeInfo object
1042 ** maintains a count of the number of pending locks on tha inode.
1043 ** When an attempt is made to close an unixFile, if there are
1044 ** other unixFile open on the same inode that are holding locks, the call
1045 ** to close() the file descriptor is deferred until all of the locks clear.
1046 ** The unixInodeInfo structure keeps a list of file descriptors that need to
1047 ** be closed and that list is walked (and cleared) when the last lock
1048 ** clears.
1050 ** Yet another problem: LinuxThreads do not play well with posix locks.
1052 ** Many older versions of linux use the LinuxThreads library which is
1053 ** not posix compliant. Under LinuxThreads, a lock created by thread
1054 ** A cannot be modified or overridden by a different thread B.
1055 ** Only thread A can modify the lock. Locking behavior is correct
1056 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
1057 ** on linux - with NPTL a lock created by thread A can override locks
1058 ** in thread B. But there is no way to know at compile-time which
1059 ** threading library is being used. So there is no way to know at
1060 ** compile-time whether or not thread A can override locks on thread B.
1061 ** One has to do a run-time check to discover the behavior of the
1062 ** current process.
1064 ** SQLite used to support LinuxThreads. But support for LinuxThreads
1065 ** was dropped beginning with version 3.7.0. SQLite will still work with
1066 ** LinuxThreads provided that (1) there is no more than one connection
1067 ** per database file in the same process and (2) database connections
1068 ** do not move across threads.
1072 ** An instance of the following structure serves as the key used
1073 ** to locate a particular unixInodeInfo object.
1075 struct unixFileId {
1076 dev_t dev; /* Device number */
1077 #if OS_VXWORKS
1078 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
1079 #else
1080 /* We are told that some versions of Android contain a bug that
1081 ** sizes ino_t at only 32-bits instead of 64-bits. (See
1082 ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
1083 ** To work around this, always allocate 64-bits for the inode number.
1084 ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
1085 ** but that should not be a big deal. */
1086 /* WAS: ino_t ino; */
1087 u64 ino; /* Inode number */
1088 #endif
1092 ** An instance of the following structure is allocated for each open
1093 ** inode. Or, on LinuxThreads, there is one of these structures for
1094 ** each inode opened by each thread.
1096 ** A single inode can have multiple file descriptors, so each unixFile
1097 ** structure contains a pointer to an instance of this object and this
1098 ** object keeps a count of the number of unixFile pointing to it.
1100 struct unixInodeInfo {
1101 struct unixFileId fileId; /* The lookup key */
1102 int nShared; /* Number of SHARED locks held */
1103 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1104 unsigned char bProcessLock; /* An exclusive process lock is held */
1105 int nRef; /* Number of pointers to this structure */
1106 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1107 int nLock; /* Number of outstanding file locks */
1108 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1109 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1110 unixInodeInfo *pPrev; /* .... doubly linked */
1111 #if SQLITE_ENABLE_LOCKING_STYLE
1112 unsigned long long sharedByte; /* for AFP simulated shared lock */
1113 #endif
1114 #if OS_VXWORKS
1115 sem_t *pSem; /* Named POSIX semaphore */
1116 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
1117 #endif
1121 ** A lists of all unixInodeInfo objects.
1123 static unixInodeInfo *inodeList = 0; /* All unixInodeInfo objects */
1124 static unsigned int nUnusedFd = 0; /* Total unused file descriptors */
1128 ** This function - unixLogErrorAtLine(), is only ever called via the macro
1129 ** unixLogError().
1131 ** It is invoked after an error occurs in an OS function and errno has been
1132 ** set. It logs a message using sqlite3_log() containing the current value of
1133 ** errno and, if possible, the human-readable equivalent from strerror() or
1134 ** strerror_r().
1136 ** The first argument passed to the macro should be the error code that
1137 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1138 ** The two subsequent arguments should be the name of the OS function that
1139 ** failed (e.g. "unlink", "open") and the associated file-system path,
1140 ** if any.
1142 #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1143 static int unixLogErrorAtLine(
1144 int errcode, /* SQLite error code */
1145 const char *zFunc, /* Name of OS function that failed */
1146 const char *zPath, /* File path associated with error */
1147 int iLine /* Source line number where error occurred */
1149 char *zErr; /* Message from strerror() or equivalent */
1150 int iErrno = errno; /* Saved syscall error number */
1152 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1153 ** the strerror() function to obtain the human-readable error message
1154 ** equivalent to errno. Otherwise, use strerror_r().
1156 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1157 char aErr[80];
1158 memset(aErr, 0, sizeof(aErr));
1159 zErr = aErr;
1161 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
1162 ** assume that the system provides the GNU version of strerror_r() that
1163 ** returns a pointer to a buffer containing the error message. That pointer
1164 ** may point to aErr[], or it may point to some static storage somewhere.
1165 ** Otherwise, assume that the system provides the POSIX version of
1166 ** strerror_r(), which always writes an error message into aErr[].
1168 ** If the code incorrectly assumes that it is the POSIX version that is
1169 ** available, the error message will often be an empty string. Not a
1170 ** huge problem. Incorrectly concluding that the GNU version is available
1171 ** could lead to a segfault though.
1173 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1174 zErr =
1175 # endif
1176 strerror_r(iErrno, aErr, sizeof(aErr)-1);
1178 #elif SQLITE_THREADSAFE
1179 /* This is a threadsafe build, but strerror_r() is not available. */
1180 zErr = "";
1181 #else
1182 /* Non-threadsafe build, use strerror(). */
1183 zErr = strerror(iErrno);
1184 #endif
1186 if( zPath==0 ) zPath = "";
1187 sqlite3_log(errcode,
1188 "os_unix.c:%d: (%d) %s(%s) - %s",
1189 iLine, iErrno, zFunc, zPath, zErr
1192 return errcode;
1196 ** Close a file descriptor.
1198 ** We assume that close() almost always works, since it is only in a
1199 ** very sick application or on a very sick platform that it might fail.
1200 ** If it does fail, simply leak the file descriptor, but do log the
1201 ** error.
1203 ** Note that it is not safe to retry close() after EINTR since the
1204 ** file descriptor might have already been reused by another thread.
1205 ** So we don't even try to recover from an EINTR. Just log the error
1206 ** and move on.
1208 static void robust_close(unixFile *pFile, int h, int lineno){
1209 if( osClose(h) ){
1210 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1211 pFile ? pFile->zPath : 0, lineno);
1216 ** Set the pFile->lastErrno. Do this in a subroutine as that provides
1217 ** a convenient place to set a breakpoint.
1219 static void storeLastErrno(unixFile *pFile, int error){
1220 pFile->lastErrno = error;
1224 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
1226 static void closePendingFds(unixFile *pFile){
1227 unixInodeInfo *pInode = pFile->pInode;
1228 UnixUnusedFd *p;
1229 UnixUnusedFd *pNext;
1230 for(p=pInode->pUnused; p; p=pNext){
1231 pNext = p->pNext;
1232 robust_close(pFile, p->fd, __LINE__);
1233 sqlite3_free(p);
1234 nUnusedFd--;
1236 pInode->pUnused = 0;
1240 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
1242 ** The mutex entered using the unixEnterMutex() function must be held
1243 ** when this function is called.
1245 static void releaseInodeInfo(unixFile *pFile){
1246 unixInodeInfo *pInode = pFile->pInode;
1247 assert( unixMutexHeld() );
1248 if( ALWAYS(pInode) ){
1249 pInode->nRef--;
1250 if( pInode->nRef==0 ){
1251 assert( pInode->pShmNode==0 );
1252 closePendingFds(pFile);
1253 if( pInode->pPrev ){
1254 assert( pInode->pPrev->pNext==pInode );
1255 pInode->pPrev->pNext = pInode->pNext;
1256 }else{
1257 assert( inodeList==pInode );
1258 inodeList = pInode->pNext;
1260 if( pInode->pNext ){
1261 assert( pInode->pNext->pPrev==pInode );
1262 pInode->pNext->pPrev = pInode->pPrev;
1264 sqlite3_free(pInode);
1267 assert( inodeList!=0 || nUnusedFd==0 );
1271 ** Given a file descriptor, locate the unixInodeInfo object that
1272 ** describes that file descriptor. Create a new one if necessary. The
1273 ** return value might be uninitialized if an error occurs.
1275 ** The mutex entered using the unixEnterMutex() function must be held
1276 ** when this function is called.
1278 ** Return an appropriate error code.
1280 static int findInodeInfo(
1281 unixFile *pFile, /* Unix file with file desc used in the key */
1282 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
1284 int rc; /* System call return code */
1285 int fd; /* The file descriptor for pFile */
1286 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1287 struct stat statbuf; /* Low-level file information */
1288 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
1290 assert( unixMutexHeld() );
1292 /* Get low-level information about the file that we can used to
1293 ** create a unique name for the file.
1295 fd = pFile->h;
1296 rc = osFstat(fd, &statbuf);
1297 if( rc!=0 ){
1298 storeLastErrno(pFile, errno);
1299 #if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
1300 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1301 #endif
1302 return SQLITE_IOERR;
1305 #ifdef __APPLE__
1306 /* On OS X on an msdos filesystem, the inode number is reported
1307 ** incorrectly for zero-size files. See ticket #3260. To work
1308 ** around this problem (we consider it a bug in OS X, not SQLite)
1309 ** we always increase the file size to 1 by writing a single byte
1310 ** prior to accessing the inode number. The one byte written is
1311 ** an ASCII 'S' character which also happens to be the first byte
1312 ** in the header of every SQLite database. In this way, if there
1313 ** is a race condition such that another thread has already populated
1314 ** the first page of the database, no damage is done.
1316 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
1317 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
1318 if( rc!=1 ){
1319 storeLastErrno(pFile, errno);
1320 return SQLITE_IOERR;
1322 rc = osFstat(fd, &statbuf);
1323 if( rc!=0 ){
1324 storeLastErrno(pFile, errno);
1325 return SQLITE_IOERR;
1328 #endif
1330 memset(&fileId, 0, sizeof(fileId));
1331 fileId.dev = statbuf.st_dev;
1332 #if OS_VXWORKS
1333 fileId.pId = pFile->pId;
1334 #else
1335 fileId.ino = (u64)statbuf.st_ino;
1336 #endif
1337 assert( inodeList!=0 || nUnusedFd==0 );
1338 pInode = inodeList;
1339 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1340 pInode = pInode->pNext;
1342 if( pInode==0 ){
1343 pInode = sqlite3_malloc64( sizeof(*pInode) );
1344 if( pInode==0 ){
1345 return SQLITE_NOMEM_BKPT;
1347 memset(pInode, 0, sizeof(*pInode));
1348 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1349 pInode->nRef = 1;
1350 pInode->pNext = inodeList;
1351 pInode->pPrev = 0;
1352 if( inodeList ) inodeList->pPrev = pInode;
1353 inodeList = pInode;
1354 }else{
1355 pInode->nRef++;
1357 *ppInode = pInode;
1358 return SQLITE_OK;
1362 ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1364 static int fileHasMoved(unixFile *pFile){
1365 #if OS_VXWORKS
1366 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1367 #else
1368 struct stat buf;
1369 return pFile->pInode!=0 &&
1370 (osStat(pFile->zPath, &buf)!=0
1371 || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
1372 #endif
1377 ** Check a unixFile that is a database. Verify the following:
1379 ** (1) There is exactly one hard link on the file
1380 ** (2) The file is not a symbolic link
1381 ** (3) The file has not been renamed or unlinked
1383 ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1385 static void verifyDbFile(unixFile *pFile){
1386 struct stat buf;
1387 int rc;
1389 /* These verifications occurs for the main database only */
1390 if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
1392 rc = osFstat(pFile->h, &buf);
1393 if( rc!=0 ){
1394 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
1395 return;
1397 if( buf.st_nlink==0 ){
1398 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
1399 return;
1401 if( buf.st_nlink>1 ){
1402 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
1403 return;
1405 if( fileHasMoved(pFile) ){
1406 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
1407 return;
1413 ** This routine checks if there is a RESERVED lock held on the specified
1414 ** file by this or any other process. If such a lock is held, set *pResOut
1415 ** to a non-zero value otherwise *pResOut is set to zero. The return value
1416 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1418 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
1419 int rc = SQLITE_OK;
1420 int reserved = 0;
1421 unixFile *pFile = (unixFile*)id;
1423 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1425 assert( pFile );
1426 assert( pFile->eFileLock<=SHARED_LOCK );
1427 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
1429 /* Check if a thread in this process holds such a lock */
1430 if( pFile->pInode->eFileLock>SHARED_LOCK ){
1431 reserved = 1;
1434 /* Otherwise see if some other process holds it.
1436 #ifndef __DJGPP__
1437 if( !reserved && !pFile->pInode->bProcessLock ){
1438 struct flock lock;
1439 lock.l_whence = SEEK_SET;
1440 lock.l_start = RESERVED_BYTE;
1441 lock.l_len = 1;
1442 lock.l_type = F_WRLCK;
1443 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1444 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1445 storeLastErrno(pFile, errno);
1446 } else if( lock.l_type!=F_UNLCK ){
1447 reserved = 1;
1450 #endif
1452 unixLeaveMutex();
1453 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
1455 *pResOut = reserved;
1456 return rc;
1460 ** Attempt to set a system-lock on the file pFile. The lock is
1461 ** described by pLock.
1463 ** If the pFile was opened read/write from unix-excl, then the only lock
1464 ** ever obtained is an exclusive lock, and it is obtained exactly once
1465 ** the first time any lock is attempted. All subsequent system locking
1466 ** operations become no-ops. Locking operations still happen internally,
1467 ** in order to coordinate access between separate database connections
1468 ** within this process, but all of that is handled in memory and the
1469 ** operating system does not participate.
1471 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1472 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1473 ** and is read-only.
1475 ** Zero is returned if the call completes successfully, or -1 if a call
1476 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
1478 static int unixFileLock(unixFile *pFile, struct flock *pLock){
1479 int rc;
1480 unixInodeInfo *pInode = pFile->pInode;
1481 assert( unixMutexHeld() );
1482 assert( pInode!=0 );
1483 if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
1484 if( pInode->bProcessLock==0 ){
1485 struct flock lock;
1486 assert( pInode->nLock==0 );
1487 lock.l_whence = SEEK_SET;
1488 lock.l_start = SHARED_FIRST;
1489 lock.l_len = SHARED_SIZE;
1490 lock.l_type = F_WRLCK;
1491 rc = osFcntl(pFile->h, F_SETLK, &lock);
1492 if( rc<0 ) return rc;
1493 pInode->bProcessLock = 1;
1494 pInode->nLock++;
1495 }else{
1496 rc = 0;
1498 }else{
1499 rc = osFcntl(pFile->h, F_SETLK, pLock);
1501 return rc;
1505 ** Lock the file with the lock specified by parameter eFileLock - one
1506 ** of the following:
1508 ** (1) SHARED_LOCK
1509 ** (2) RESERVED_LOCK
1510 ** (3) PENDING_LOCK
1511 ** (4) EXCLUSIVE_LOCK
1513 ** Sometimes when requesting one lock state, additional lock states
1514 ** are inserted in between. The locking might fail on one of the later
1515 ** transitions leaving the lock state different from what it started but
1516 ** still short of its goal. The following chart shows the allowed
1517 ** transitions and the inserted intermediate states:
1519 ** UNLOCKED -> SHARED
1520 ** SHARED -> RESERVED
1521 ** SHARED -> (PENDING) -> EXCLUSIVE
1522 ** RESERVED -> (PENDING) -> EXCLUSIVE
1523 ** PENDING -> EXCLUSIVE
1525 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
1526 ** routine to lower a locking level.
1528 static int unixLock(sqlite3_file *id, int eFileLock){
1529 /* The following describes the implementation of the various locks and
1530 ** lock transitions in terms of the POSIX advisory shared and exclusive
1531 ** lock primitives (called read-locks and write-locks below, to avoid
1532 ** confusion with SQLite lock names). The algorithms are complicated
1533 ** slightly in order to be compatible with Windows95 systems simultaneously
1534 ** accessing the same database file, in case that is ever required.
1536 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1537 ** byte', each single bytes at well known offsets, and the 'shared byte
1538 ** range', a range of 510 bytes at a well known offset.
1540 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1541 ** byte'. If this is successful, 'shared byte range' is read-locked
1542 ** and the lock on the 'pending byte' released. (Legacy note: When
1543 ** SQLite was first developed, Windows95 systems were still very common,
1544 ** and Widnows95 lacks a shared-lock capability. So on Windows95, a
1545 ** single randomly selected by from the 'shared byte range' is locked.
1546 ** Windows95 is now pretty much extinct, but this work-around for the
1547 ** lack of shared-locks on Windows95 lives on, for backwards
1548 ** compatibility.)
1550 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1551 ** A RESERVED lock is implemented by grabbing a write-lock on the
1552 ** 'reserved byte'.
1554 ** A process may only obtain a PENDING lock after it has obtained a
1555 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1556 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1557 ** obtained, but existing SHARED locks are allowed to persist. A process
1558 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1559 ** This property is used by the algorithm for rolling back a journal file
1560 ** after a crash.
1562 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1563 ** implemented by obtaining a write-lock on the entire 'shared byte
1564 ** range'. Since all other locks require a read-lock on one of the bytes
1565 ** within this range, this ensures that no other locks are held on the
1566 ** database.
1568 int rc = SQLITE_OK;
1569 unixFile *pFile = (unixFile*)id;
1570 unixInodeInfo *pInode;
1571 struct flock lock;
1572 int tErrno = 0;
1574 assert( pFile );
1575 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1576 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
1577 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
1578 osGetpid(0)));
1580 /* If there is already a lock of this type or more restrictive on the
1581 ** unixFile, do nothing. Don't use the end_lock: exit path, as
1582 ** unixEnterMutex() hasn't been called yet.
1584 if( pFile->eFileLock>=eFileLock ){
1585 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1586 azFileLock(eFileLock)));
1587 return SQLITE_OK;
1590 /* Make sure the locking sequence is correct.
1591 ** (1) We never move from unlocked to anything higher than shared lock.
1592 ** (2) SQLite never explicitly requests a pendig lock.
1593 ** (3) A shared lock is always held when a reserve lock is requested.
1595 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1596 assert( eFileLock!=PENDING_LOCK );
1597 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
1599 /* This mutex is needed because pFile->pInode is shared across threads
1601 unixEnterMutex();
1602 pInode = pFile->pInode;
1604 /* If some thread using this PID has a lock via a different unixFile*
1605 ** handle that precludes the requested lock, return BUSY.
1607 if( (pFile->eFileLock!=pInode->eFileLock &&
1608 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
1610 rc = SQLITE_BUSY;
1611 goto end_lock;
1614 /* If a SHARED lock is requested, and some thread using this PID already
1615 ** has a SHARED or RESERVED lock, then increment reference counts and
1616 ** return SQLITE_OK.
1618 if( eFileLock==SHARED_LOCK &&
1619 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
1620 assert( eFileLock==SHARED_LOCK );
1621 assert( pFile->eFileLock==0 );
1622 assert( pInode->nShared>0 );
1623 pFile->eFileLock = SHARED_LOCK;
1624 pInode->nShared++;
1625 pInode->nLock++;
1626 goto end_lock;
1630 /* A PENDING lock is needed before acquiring a SHARED lock and before
1631 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1632 ** be released.
1634 lock.l_len = 1L;
1635 lock.l_whence = SEEK_SET;
1636 if( eFileLock==SHARED_LOCK
1637 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
1639 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
1640 lock.l_start = PENDING_BYTE;
1641 if( unixFileLock(pFile, &lock) ){
1642 tErrno = errno;
1643 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1644 if( rc!=SQLITE_BUSY ){
1645 storeLastErrno(pFile, tErrno);
1647 goto end_lock;
1652 /* If control gets to this point, then actually go ahead and make
1653 ** operating system calls for the specified lock.
1655 if( eFileLock==SHARED_LOCK ){
1656 assert( pInode->nShared==0 );
1657 assert( pInode->eFileLock==0 );
1658 assert( rc==SQLITE_OK );
1660 /* Now get the read-lock */
1661 lock.l_start = SHARED_FIRST;
1662 lock.l_len = SHARED_SIZE;
1663 if( unixFileLock(pFile, &lock) ){
1664 tErrno = errno;
1665 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1668 /* Drop the temporary PENDING lock */
1669 lock.l_start = PENDING_BYTE;
1670 lock.l_len = 1L;
1671 lock.l_type = F_UNLCK;
1672 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1673 /* This could happen with a network mount */
1674 tErrno = errno;
1675 rc = SQLITE_IOERR_UNLOCK;
1678 if( rc ){
1679 if( rc!=SQLITE_BUSY ){
1680 storeLastErrno(pFile, tErrno);
1682 goto end_lock;
1683 }else{
1684 pFile->eFileLock = SHARED_LOCK;
1685 pInode->nLock++;
1686 pInode->nShared = 1;
1688 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
1689 /* We are trying for an exclusive lock but another thread in this
1690 ** same process is still holding a shared lock. */
1691 rc = SQLITE_BUSY;
1692 }else{
1693 /* The request was for a RESERVED or EXCLUSIVE lock. It is
1694 ** assumed that there is a SHARED or greater lock on the file
1695 ** already.
1697 assert( 0!=pFile->eFileLock );
1698 lock.l_type = F_WRLCK;
1700 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1701 if( eFileLock==RESERVED_LOCK ){
1702 lock.l_start = RESERVED_BYTE;
1703 lock.l_len = 1L;
1704 }else{
1705 lock.l_start = SHARED_FIRST;
1706 lock.l_len = SHARED_SIZE;
1709 if( unixFileLock(pFile, &lock) ){
1710 tErrno = errno;
1711 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1712 if( rc!=SQLITE_BUSY ){
1713 storeLastErrno(pFile, tErrno);
1719 #ifdef SQLITE_DEBUG
1720 /* Set up the transaction-counter change checking flags when
1721 ** transitioning from a SHARED to a RESERVED lock. The change
1722 ** from SHARED to RESERVED marks the beginning of a normal
1723 ** write operation (not a hot journal rollback).
1725 if( rc==SQLITE_OK
1726 && pFile->eFileLock<=SHARED_LOCK
1727 && eFileLock==RESERVED_LOCK
1729 pFile->transCntrChng = 0;
1730 pFile->dbUpdate = 0;
1731 pFile->inNormalWrite = 1;
1733 #endif
1736 if( rc==SQLITE_OK ){
1737 pFile->eFileLock = eFileLock;
1738 pInode->eFileLock = eFileLock;
1739 }else if( eFileLock==EXCLUSIVE_LOCK ){
1740 pFile->eFileLock = PENDING_LOCK;
1741 pInode->eFileLock = PENDING_LOCK;
1744 end_lock:
1745 unixLeaveMutex();
1746 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1747 rc==SQLITE_OK ? "ok" : "failed"));
1748 return rc;
1752 ** Add the file descriptor used by file handle pFile to the corresponding
1753 ** pUnused list.
1755 static void setPendingFd(unixFile *pFile){
1756 unixInodeInfo *pInode = pFile->pInode;
1757 UnixUnusedFd *p = pFile->pPreallocatedUnused;
1758 p->pNext = pInode->pUnused;
1759 pInode->pUnused = p;
1760 pFile->h = -1;
1761 pFile->pPreallocatedUnused = 0;
1762 nUnusedFd++;
1766 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
1767 ** must be either NO_LOCK or SHARED_LOCK.
1769 ** If the locking level of the file descriptor is already at or below
1770 ** the requested locking level, this routine is a no-op.
1772 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1773 ** the byte range is divided into 2 parts and the first part is unlocked then
1774 ** set to a read lock, then the other part is simply unlocked. This works
1775 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1776 ** remove the write lock on a region when a read lock is set.
1778 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
1779 unixFile *pFile = (unixFile*)id;
1780 unixInodeInfo *pInode;
1781 struct flock lock;
1782 int rc = SQLITE_OK;
1784 assert( pFile );
1785 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
1786 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
1787 osGetpid(0)));
1789 assert( eFileLock<=SHARED_LOCK );
1790 if( pFile->eFileLock<=eFileLock ){
1791 return SQLITE_OK;
1793 unixEnterMutex();
1794 pInode = pFile->pInode;
1795 assert( pInode->nShared!=0 );
1796 if( pFile->eFileLock>SHARED_LOCK ){
1797 assert( pInode->eFileLock==pFile->eFileLock );
1799 #ifdef SQLITE_DEBUG
1800 /* When reducing a lock such that other processes can start
1801 ** reading the database file again, make sure that the
1802 ** transaction counter was updated if any part of the database
1803 ** file changed. If the transaction counter is not updated,
1804 ** other connections to the same file might not realize that
1805 ** the file has changed and hence might not know to flush their
1806 ** cache. The use of a stale cache can lead to database corruption.
1808 pFile->inNormalWrite = 0;
1809 #endif
1811 /* downgrading to a shared lock on NFS involves clearing the write lock
1812 ** before establishing the readlock - to avoid a race condition we downgrade
1813 ** the lock in 2 blocks, so that part of the range will be covered by a
1814 ** write lock until the rest is covered by a read lock:
1815 ** 1: [WWWWW]
1816 ** 2: [....W]
1817 ** 3: [RRRRW]
1818 ** 4: [RRRR.]
1820 if( eFileLock==SHARED_LOCK ){
1821 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
1822 (void)handleNFSUnlock;
1823 assert( handleNFSUnlock==0 );
1824 #endif
1825 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
1826 if( handleNFSUnlock ){
1827 int tErrno; /* Error code from system call errors */
1828 off_t divSize = SHARED_SIZE - 1;
1830 lock.l_type = F_UNLCK;
1831 lock.l_whence = SEEK_SET;
1832 lock.l_start = SHARED_FIRST;
1833 lock.l_len = divSize;
1834 if( unixFileLock(pFile, &lock)==(-1) ){
1835 tErrno = errno;
1836 rc = SQLITE_IOERR_UNLOCK;
1837 storeLastErrno(pFile, tErrno);
1838 goto end_unlock;
1840 lock.l_type = F_RDLCK;
1841 lock.l_whence = SEEK_SET;
1842 lock.l_start = SHARED_FIRST;
1843 lock.l_len = divSize;
1844 if( unixFileLock(pFile, &lock)==(-1) ){
1845 tErrno = errno;
1846 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1847 if( IS_LOCK_ERROR(rc) ){
1848 storeLastErrno(pFile, tErrno);
1850 goto end_unlock;
1852 lock.l_type = F_UNLCK;
1853 lock.l_whence = SEEK_SET;
1854 lock.l_start = SHARED_FIRST+divSize;
1855 lock.l_len = SHARED_SIZE-divSize;
1856 if( unixFileLock(pFile, &lock)==(-1) ){
1857 tErrno = errno;
1858 rc = SQLITE_IOERR_UNLOCK;
1859 storeLastErrno(pFile, tErrno);
1860 goto end_unlock;
1862 }else
1863 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1865 lock.l_type = F_RDLCK;
1866 lock.l_whence = SEEK_SET;
1867 lock.l_start = SHARED_FIRST;
1868 lock.l_len = SHARED_SIZE;
1869 if( unixFileLock(pFile, &lock) ){
1870 /* In theory, the call to unixFileLock() cannot fail because another
1871 ** process is holding an incompatible lock. If it does, this
1872 ** indicates that the other process is not following the locking
1873 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1874 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1875 ** an assert to fail). */
1876 rc = SQLITE_IOERR_RDLOCK;
1877 storeLastErrno(pFile, errno);
1878 goto end_unlock;
1882 lock.l_type = F_UNLCK;
1883 lock.l_whence = SEEK_SET;
1884 lock.l_start = PENDING_BYTE;
1885 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
1886 if( unixFileLock(pFile, &lock)==0 ){
1887 pInode->eFileLock = SHARED_LOCK;
1888 }else{
1889 rc = SQLITE_IOERR_UNLOCK;
1890 storeLastErrno(pFile, errno);
1891 goto end_unlock;
1894 if( eFileLock==NO_LOCK ){
1895 /* Decrement the shared lock counter. Release the lock using an
1896 ** OS call only when all threads in this same process have released
1897 ** the lock.
1899 pInode->nShared--;
1900 if( pInode->nShared==0 ){
1901 lock.l_type = F_UNLCK;
1902 lock.l_whence = SEEK_SET;
1903 lock.l_start = lock.l_len = 0L;
1904 if( unixFileLock(pFile, &lock)==0 ){
1905 pInode->eFileLock = NO_LOCK;
1906 }else{
1907 rc = SQLITE_IOERR_UNLOCK;
1908 storeLastErrno(pFile, errno);
1909 pInode->eFileLock = NO_LOCK;
1910 pFile->eFileLock = NO_LOCK;
1914 /* Decrement the count of locks against this same file. When the
1915 ** count reaches zero, close any other file descriptors whose close
1916 ** was deferred because of outstanding locks.
1918 pInode->nLock--;
1919 assert( pInode->nLock>=0 );
1920 if( pInode->nLock==0 ){
1921 closePendingFds(pFile);
1925 end_unlock:
1926 unixLeaveMutex();
1927 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
1928 return rc;
1932 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
1933 ** must be either NO_LOCK or SHARED_LOCK.
1935 ** If the locking level of the file descriptor is already at or below
1936 ** the requested locking level, this routine is a no-op.
1938 static int unixUnlock(sqlite3_file *id, int eFileLock){
1939 #if SQLITE_MAX_MMAP_SIZE>0
1940 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
1941 #endif
1942 return posixUnlock(id, eFileLock, 0);
1945 #if SQLITE_MAX_MMAP_SIZE>0
1946 static int unixMapfile(unixFile *pFd, i64 nByte);
1947 static void unixUnmapfile(unixFile *pFd);
1948 #endif
1951 ** This function performs the parts of the "close file" operation
1952 ** common to all locking schemes. It closes the directory and file
1953 ** handles, if they are valid, and sets all fields of the unixFile
1954 ** structure to 0.
1956 ** It is *not* necessary to hold the mutex when this routine is called,
1957 ** even on VxWorks. A mutex will be acquired on VxWorks by the
1958 ** vxworksReleaseFileId() routine.
1960 static int closeUnixFile(sqlite3_file *id){
1961 unixFile *pFile = (unixFile*)id;
1962 #if SQLITE_MAX_MMAP_SIZE>0
1963 unixUnmapfile(pFile);
1964 #endif
1965 if( pFile->h>=0 ){
1966 robust_close(pFile, pFile->h, __LINE__);
1967 pFile->h = -1;
1969 #if OS_VXWORKS
1970 if( pFile->pId ){
1971 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
1972 osUnlink(pFile->pId->zCanonicalName);
1974 vxworksReleaseFileId(pFile->pId);
1975 pFile->pId = 0;
1977 #endif
1978 #ifdef SQLITE_UNLINK_AFTER_CLOSE
1979 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
1980 osUnlink(pFile->zPath);
1981 sqlite3_free(*(char**)&pFile->zPath);
1982 pFile->zPath = 0;
1984 #endif
1985 OSTRACE(("CLOSE %-3d\n", pFile->h));
1986 OpenCounter(-1);
1987 sqlite3_free(pFile->pPreallocatedUnused);
1988 memset(pFile, 0, sizeof(unixFile));
1989 return SQLITE_OK;
1993 ** Close a file.
1995 static int unixClose(sqlite3_file *id){
1996 int rc = SQLITE_OK;
1997 unixFile *pFile = (unixFile *)id;
1998 verifyDbFile(pFile);
1999 unixUnlock(id, NO_LOCK);
2000 unixEnterMutex();
2002 /* unixFile.pInode is always valid here. Otherwise, a different close
2003 ** routine (e.g. nolockClose()) would be called instead.
2005 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
2006 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
2007 /* If there are outstanding locks, do not actually close the file just
2008 ** yet because that would clear those locks. Instead, add the file
2009 ** descriptor to pInode->pUnused list. It will be automatically closed
2010 ** when the last lock is cleared.
2012 setPendingFd(pFile);
2014 releaseInodeInfo(pFile);
2015 rc = closeUnixFile(id);
2016 unixLeaveMutex();
2017 return rc;
2020 /************** End of the posix advisory lock implementation *****************
2021 ******************************************************************************/
2023 /******************************************************************************
2024 ****************************** No-op Locking **********************************
2026 ** Of the various locking implementations available, this is by far the
2027 ** simplest: locking is ignored. No attempt is made to lock the database
2028 ** file for reading or writing.
2030 ** This locking mode is appropriate for use on read-only databases
2031 ** (ex: databases that are burned into CD-ROM, for example.) It can
2032 ** also be used if the application employs some external mechanism to
2033 ** prevent simultaneous access of the same database by two or more
2034 ** database connections. But there is a serious risk of database
2035 ** corruption if this locking mode is used in situations where multiple
2036 ** database connections are accessing the same database file at the same
2037 ** time and one or more of those connections are writing.
2040 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
2041 UNUSED_PARAMETER(NotUsed);
2042 *pResOut = 0;
2043 return SQLITE_OK;
2045 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
2046 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2047 return SQLITE_OK;
2049 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
2050 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2051 return SQLITE_OK;
2055 ** Close the file.
2057 static int nolockClose(sqlite3_file *id) {
2058 return closeUnixFile(id);
2061 /******************* End of the no-op lock implementation *********************
2062 ******************************************************************************/
2064 /******************************************************************************
2065 ************************* Begin dot-file Locking ******************************
2067 ** The dotfile locking implementation uses the existence of separate lock
2068 ** files (really a directory) to control access to the database. This works
2069 ** on just about every filesystem imaginable. But there are serious downsides:
2071 ** (1) There is zero concurrency. A single reader blocks all other
2072 ** connections from reading or writing the database.
2074 ** (2) An application crash or power loss can leave stale lock files
2075 ** sitting around that need to be cleared manually.
2077 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
2078 ** other locking strategy is available.
2080 ** Dotfile locking works by creating a subdirectory in the same directory as
2081 ** the database and with the same name but with a ".lock" extension added.
2082 ** The existence of a lock directory implies an EXCLUSIVE lock. All other
2083 ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
2087 ** The file suffix added to the data base filename in order to create the
2088 ** lock directory.
2090 #define DOTLOCK_SUFFIX ".lock"
2093 ** This routine checks if there is a RESERVED lock held on the specified
2094 ** file by this or any other process. If such a lock is held, set *pResOut
2095 ** to a non-zero value otherwise *pResOut is set to zero. The return value
2096 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2098 ** In dotfile locking, either a lock exists or it does not. So in this
2099 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
2100 ** is held on the file and false if the file is unlocked.
2102 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2103 int rc = SQLITE_OK;
2104 int reserved = 0;
2105 unixFile *pFile = (unixFile*)id;
2107 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2109 assert( pFile );
2110 reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
2111 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
2112 *pResOut = reserved;
2113 return rc;
2117 ** Lock the file with the lock specified by parameter eFileLock - one
2118 ** of the following:
2120 ** (1) SHARED_LOCK
2121 ** (2) RESERVED_LOCK
2122 ** (3) PENDING_LOCK
2123 ** (4) EXCLUSIVE_LOCK
2125 ** Sometimes when requesting one lock state, additional lock states
2126 ** are inserted in between. The locking might fail on one of the later
2127 ** transitions leaving the lock state different from what it started but
2128 ** still short of its goal. The following chart shows the allowed
2129 ** transitions and the inserted intermediate states:
2131 ** UNLOCKED -> SHARED
2132 ** SHARED -> RESERVED
2133 ** SHARED -> (PENDING) -> EXCLUSIVE
2134 ** RESERVED -> (PENDING) -> EXCLUSIVE
2135 ** PENDING -> EXCLUSIVE
2137 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
2138 ** routine to lower a locking level.
2140 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
2141 ** But we track the other locking levels internally.
2143 static int dotlockLock(sqlite3_file *id, int eFileLock) {
2144 unixFile *pFile = (unixFile*)id;
2145 char *zLockFile = (char *)pFile->lockingContext;
2146 int rc = SQLITE_OK;
2149 /* If we have any lock, then the lock file already exists. All we have
2150 ** to do is adjust our internal record of the lock level.
2152 if( pFile->eFileLock > NO_LOCK ){
2153 pFile->eFileLock = eFileLock;
2154 /* Always update the timestamp on the old file */
2155 #ifdef HAVE_UTIME
2156 utime(zLockFile, NULL);
2157 #else
2158 utimes(zLockFile, NULL);
2159 #endif
2160 return SQLITE_OK;
2163 /* grab an exclusive lock */
2164 rc = osMkdir(zLockFile, 0777);
2165 if( rc<0 ){
2166 /* failed to open/create the lock directory */
2167 int tErrno = errno;
2168 if( EEXIST == tErrno ){
2169 rc = SQLITE_BUSY;
2170 } else {
2171 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2172 if( rc!=SQLITE_BUSY ){
2173 storeLastErrno(pFile, tErrno);
2176 return rc;
2179 /* got it, set the type and return ok */
2180 pFile->eFileLock = eFileLock;
2181 return rc;
2185 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
2186 ** must be either NO_LOCK or SHARED_LOCK.
2188 ** If the locking level of the file descriptor is already at or below
2189 ** the requested locking level, this routine is a no-op.
2191 ** When the locking level reaches NO_LOCK, delete the lock file.
2193 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
2194 unixFile *pFile = (unixFile*)id;
2195 char *zLockFile = (char *)pFile->lockingContext;
2196 int rc;
2198 assert( pFile );
2199 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
2200 pFile->eFileLock, osGetpid(0)));
2201 assert( eFileLock<=SHARED_LOCK );
2203 /* no-op if possible */
2204 if( pFile->eFileLock==eFileLock ){
2205 return SQLITE_OK;
2208 /* To downgrade to shared, simply update our internal notion of the
2209 ** lock state. No need to mess with the file on disk.
2211 if( eFileLock==SHARED_LOCK ){
2212 pFile->eFileLock = SHARED_LOCK;
2213 return SQLITE_OK;
2216 /* To fully unlock the database, delete the lock file */
2217 assert( eFileLock==NO_LOCK );
2218 rc = osRmdir(zLockFile);
2219 if( rc<0 ){
2220 int tErrno = errno;
2221 if( tErrno==ENOENT ){
2222 rc = SQLITE_OK;
2223 }else{
2224 rc = SQLITE_IOERR_UNLOCK;
2225 storeLastErrno(pFile, tErrno);
2227 return rc;
2229 pFile->eFileLock = NO_LOCK;
2230 return SQLITE_OK;
2234 ** Close a file. Make sure the lock has been released before closing.
2236 static int dotlockClose(sqlite3_file *id) {
2237 unixFile *pFile = (unixFile*)id;
2238 assert( id!=0 );
2239 dotlockUnlock(id, NO_LOCK);
2240 sqlite3_free(pFile->lockingContext);
2241 return closeUnixFile(id);
2243 /****************** End of the dot-file lock implementation *******************
2244 ******************************************************************************/
2246 /******************************************************************************
2247 ************************** Begin flock Locking ********************************
2249 ** Use the flock() system call to do file locking.
2251 ** flock() locking is like dot-file locking in that the various
2252 ** fine-grain locking levels supported by SQLite are collapsed into
2253 ** a single exclusive lock. In other words, SHARED, RESERVED, and
2254 ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2255 ** still works when you do this, but concurrency is reduced since
2256 ** only a single process can be reading the database at a time.
2258 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
2260 #if SQLITE_ENABLE_LOCKING_STYLE
2263 ** Retry flock() calls that fail with EINTR
2265 #ifdef EINTR
2266 static int robust_flock(int fd, int op){
2267 int rc;
2268 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2269 return rc;
2271 #else
2272 # define robust_flock(a,b) flock(a,b)
2273 #endif
2277 ** This routine checks if there is a RESERVED lock held on the specified
2278 ** file by this or any other process. If such a lock is held, set *pResOut
2279 ** to a non-zero value otherwise *pResOut is set to zero. The return value
2280 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2282 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2283 int rc = SQLITE_OK;
2284 int reserved = 0;
2285 unixFile *pFile = (unixFile*)id;
2287 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2289 assert( pFile );
2291 /* Check if a thread in this process holds such a lock */
2292 if( pFile->eFileLock>SHARED_LOCK ){
2293 reserved = 1;
2296 /* Otherwise see if some other process holds it. */
2297 if( !reserved ){
2298 /* attempt to get the lock */
2299 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
2300 if( !lrc ){
2301 /* got the lock, unlock it */
2302 lrc = robust_flock(pFile->h, LOCK_UN);
2303 if ( lrc ) {
2304 int tErrno = errno;
2305 /* unlock failed with an error */
2306 lrc = SQLITE_IOERR_UNLOCK;
2307 storeLastErrno(pFile, tErrno);
2308 rc = lrc;
2310 } else {
2311 int tErrno = errno;
2312 reserved = 1;
2313 /* someone else might have it reserved */
2314 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2315 if( IS_LOCK_ERROR(lrc) ){
2316 storeLastErrno(pFile, tErrno);
2317 rc = lrc;
2321 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
2323 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2324 if( (rc & 0xff) == SQLITE_IOERR ){
2325 rc = SQLITE_OK;
2326 reserved=1;
2328 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2329 *pResOut = reserved;
2330 return rc;
2334 ** Lock the file with the lock specified by parameter eFileLock - one
2335 ** of the following:
2337 ** (1) SHARED_LOCK
2338 ** (2) RESERVED_LOCK
2339 ** (3) PENDING_LOCK
2340 ** (4) EXCLUSIVE_LOCK
2342 ** Sometimes when requesting one lock state, additional lock states
2343 ** are inserted in between. The locking might fail on one of the later
2344 ** transitions leaving the lock state different from what it started but
2345 ** still short of its goal. The following chart shows the allowed
2346 ** transitions and the inserted intermediate states:
2348 ** UNLOCKED -> SHARED
2349 ** SHARED -> RESERVED
2350 ** SHARED -> (PENDING) -> EXCLUSIVE
2351 ** RESERVED -> (PENDING) -> EXCLUSIVE
2352 ** PENDING -> EXCLUSIVE
2354 ** flock() only really support EXCLUSIVE locks. We track intermediate
2355 ** lock states in the sqlite3_file structure, but all locks SHARED or
2356 ** above are really EXCLUSIVE locks and exclude all other processes from
2357 ** access the file.
2359 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
2360 ** routine to lower a locking level.
2362 static int flockLock(sqlite3_file *id, int eFileLock) {
2363 int rc = SQLITE_OK;
2364 unixFile *pFile = (unixFile*)id;
2366 assert( pFile );
2368 /* if we already have a lock, it is exclusive.
2369 ** Just adjust level and punt on outta here. */
2370 if (pFile->eFileLock > NO_LOCK) {
2371 pFile->eFileLock = eFileLock;
2372 return SQLITE_OK;
2375 /* grab an exclusive lock */
2377 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
2378 int tErrno = errno;
2379 /* didn't get, must be busy */
2380 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2381 if( IS_LOCK_ERROR(rc) ){
2382 storeLastErrno(pFile, tErrno);
2384 } else {
2385 /* got it, set the type and return ok */
2386 pFile->eFileLock = eFileLock;
2388 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2389 rc==SQLITE_OK ? "ok" : "failed"));
2390 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2391 if( (rc & 0xff) == SQLITE_IOERR ){
2392 rc = SQLITE_BUSY;
2394 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2395 return rc;
2400 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
2401 ** must be either NO_LOCK or SHARED_LOCK.
2403 ** If the locking level of the file descriptor is already at or below
2404 ** the requested locking level, this routine is a no-op.
2406 static int flockUnlock(sqlite3_file *id, int eFileLock) {
2407 unixFile *pFile = (unixFile*)id;
2409 assert( pFile );
2410 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2411 pFile->eFileLock, osGetpid(0)));
2412 assert( eFileLock<=SHARED_LOCK );
2414 /* no-op if possible */
2415 if( pFile->eFileLock==eFileLock ){
2416 return SQLITE_OK;
2419 /* shared can just be set because we always have an exclusive */
2420 if (eFileLock==SHARED_LOCK) {
2421 pFile->eFileLock = eFileLock;
2422 return SQLITE_OK;
2425 /* no, really, unlock. */
2426 if( robust_flock(pFile->h, LOCK_UN) ){
2427 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2428 return SQLITE_OK;
2429 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2430 return SQLITE_IOERR_UNLOCK;
2431 }else{
2432 pFile->eFileLock = NO_LOCK;
2433 return SQLITE_OK;
2438 ** Close a file.
2440 static int flockClose(sqlite3_file *id) {
2441 assert( id!=0 );
2442 flockUnlock(id, NO_LOCK);
2443 return closeUnixFile(id);
2446 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2448 /******************* End of the flock lock implementation *********************
2449 ******************************************************************************/
2451 /******************************************************************************
2452 ************************ Begin Named Semaphore Locking ************************
2454 ** Named semaphore locking is only supported on VxWorks.
2456 ** Semaphore locking is like dot-lock and flock in that it really only
2457 ** supports EXCLUSIVE locking. Only a single process can read or write
2458 ** the database file at a time. This reduces potential concurrency, but
2459 ** makes the lock implementation much easier.
2461 #if OS_VXWORKS
2464 ** This routine checks if there is a RESERVED lock held on the specified
2465 ** file by this or any other process. If such a lock is held, set *pResOut
2466 ** to a non-zero value otherwise *pResOut is set to zero. The return value
2467 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2469 static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
2470 int rc = SQLITE_OK;
2471 int reserved = 0;
2472 unixFile *pFile = (unixFile*)id;
2474 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2476 assert( pFile );
2478 /* Check if a thread in this process holds such a lock */
2479 if( pFile->eFileLock>SHARED_LOCK ){
2480 reserved = 1;
2483 /* Otherwise see if some other process holds it. */
2484 if( !reserved ){
2485 sem_t *pSem = pFile->pInode->pSem;
2487 if( sem_trywait(pSem)==-1 ){
2488 int tErrno = errno;
2489 if( EAGAIN != tErrno ){
2490 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2491 storeLastErrno(pFile, tErrno);
2492 } else {
2493 /* someone else has the lock when we are in NO_LOCK */
2494 reserved = (pFile->eFileLock < SHARED_LOCK);
2496 }else{
2497 /* we could have it if we want it */
2498 sem_post(pSem);
2501 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
2503 *pResOut = reserved;
2504 return rc;
2508 ** Lock the file with the lock specified by parameter eFileLock - one
2509 ** of the following:
2511 ** (1) SHARED_LOCK
2512 ** (2) RESERVED_LOCK
2513 ** (3) PENDING_LOCK
2514 ** (4) EXCLUSIVE_LOCK
2516 ** Sometimes when requesting one lock state, additional lock states
2517 ** are inserted in between. The locking might fail on one of the later
2518 ** transitions leaving the lock state different from what it started but
2519 ** still short of its goal. The following chart shows the allowed
2520 ** transitions and the inserted intermediate states:
2522 ** UNLOCKED -> SHARED
2523 ** SHARED -> RESERVED
2524 ** SHARED -> (PENDING) -> EXCLUSIVE
2525 ** RESERVED -> (PENDING) -> EXCLUSIVE
2526 ** PENDING -> EXCLUSIVE
2528 ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2529 ** lock states in the sqlite3_file structure, but all locks SHARED or
2530 ** above are really EXCLUSIVE locks and exclude all other processes from
2531 ** access the file.
2533 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
2534 ** routine to lower a locking level.
2536 static int semXLock(sqlite3_file *id, int eFileLock) {
2537 unixFile *pFile = (unixFile*)id;
2538 sem_t *pSem = pFile->pInode->pSem;
2539 int rc = SQLITE_OK;
2541 /* if we already have a lock, it is exclusive.
2542 ** Just adjust level and punt on outta here. */
2543 if (pFile->eFileLock > NO_LOCK) {
2544 pFile->eFileLock = eFileLock;
2545 rc = SQLITE_OK;
2546 goto sem_end_lock;
2549 /* lock semaphore now but bail out when already locked. */
2550 if( sem_trywait(pSem)==-1 ){
2551 rc = SQLITE_BUSY;
2552 goto sem_end_lock;
2555 /* got it, set the type and return ok */
2556 pFile->eFileLock = eFileLock;
2558 sem_end_lock:
2559 return rc;
2563 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
2564 ** must be either NO_LOCK or SHARED_LOCK.
2566 ** If the locking level of the file descriptor is already at or below
2567 ** the requested locking level, this routine is a no-op.
2569 static int semXUnlock(sqlite3_file *id, int eFileLock) {
2570 unixFile *pFile = (unixFile*)id;
2571 sem_t *pSem = pFile->pInode->pSem;
2573 assert( pFile );
2574 assert( pSem );
2575 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2576 pFile->eFileLock, osGetpid(0)));
2577 assert( eFileLock<=SHARED_LOCK );
2579 /* no-op if possible */
2580 if( pFile->eFileLock==eFileLock ){
2581 return SQLITE_OK;
2584 /* shared can just be set because we always have an exclusive */
2585 if (eFileLock==SHARED_LOCK) {
2586 pFile->eFileLock = eFileLock;
2587 return SQLITE_OK;
2590 /* no, really unlock. */
2591 if ( sem_post(pSem)==-1 ) {
2592 int rc, tErrno = errno;
2593 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2594 if( IS_LOCK_ERROR(rc) ){
2595 storeLastErrno(pFile, tErrno);
2597 return rc;
2599 pFile->eFileLock = NO_LOCK;
2600 return SQLITE_OK;
2604 ** Close a file.
2606 static int semXClose(sqlite3_file *id) {
2607 if( id ){
2608 unixFile *pFile = (unixFile*)id;
2609 semXUnlock(id, NO_LOCK);
2610 assert( pFile );
2611 unixEnterMutex();
2612 releaseInodeInfo(pFile);
2613 unixLeaveMutex();
2614 closeUnixFile(id);
2616 return SQLITE_OK;
2619 #endif /* OS_VXWORKS */
2621 ** Named semaphore locking is only available on VxWorks.
2623 *************** End of the named semaphore lock implementation ****************
2624 ******************************************************************************/
2627 /******************************************************************************
2628 *************************** Begin AFP Locking *********************************
2630 ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2631 ** on Apple Macintosh computers - both OS9 and OSX.
2633 ** Third-party implementations of AFP are available. But this code here
2634 ** only works on OSX.
2637 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2639 ** The afpLockingContext structure contains all afp lock specific state
2641 typedef struct afpLockingContext afpLockingContext;
2642 struct afpLockingContext {
2643 int reserved;
2644 const char *dbPath; /* Name of the open file */
2647 struct ByteRangeLockPB2
2649 unsigned long long offset; /* offset to first byte to lock */
2650 unsigned long long length; /* nbr of bytes to lock */
2651 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2652 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2653 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2654 int fd; /* file desc to assoc this lock with */
2657 #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
2660 ** This is a utility for setting or clearing a bit-range lock on an
2661 ** AFP filesystem.
2663 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2665 static int afpSetLock(
2666 const char *path, /* Name of the file to be locked or unlocked */
2667 unixFile *pFile, /* Open file descriptor on path */
2668 unsigned long long offset, /* First byte to be locked */
2669 unsigned long long length, /* Number of bytes to lock */
2670 int setLockFlag /* True to set lock. False to clear lock */
2672 struct ByteRangeLockPB2 pb;
2673 int err;
2675 pb.unLockFlag = setLockFlag ? 0 : 1;
2676 pb.startEndFlag = 0;
2677 pb.offset = offset;
2678 pb.length = length;
2679 pb.fd = pFile->h;
2681 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
2682 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
2683 offset, length));
2684 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2685 if ( err==-1 ) {
2686 int rc;
2687 int tErrno = errno;
2688 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2689 path, tErrno, strerror(tErrno)));
2690 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2691 rc = SQLITE_BUSY;
2692 #else
2693 rc = sqliteErrorFromPosixError(tErrno,
2694 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
2695 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
2696 if( IS_LOCK_ERROR(rc) ){
2697 storeLastErrno(pFile, tErrno);
2699 return rc;
2700 } else {
2701 return SQLITE_OK;
2706 ** This routine checks if there is a RESERVED lock held on the specified
2707 ** file by this or any other process. If such a lock is held, set *pResOut
2708 ** to a non-zero value otherwise *pResOut is set to zero. The return value
2709 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2711 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
2712 int rc = SQLITE_OK;
2713 int reserved = 0;
2714 unixFile *pFile = (unixFile*)id;
2715 afpLockingContext *context;
2717 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2719 assert( pFile );
2720 context = (afpLockingContext *) pFile->lockingContext;
2721 if( context->reserved ){
2722 *pResOut = 1;
2723 return SQLITE_OK;
2725 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
2727 /* Check if a thread in this process holds such a lock */
2728 if( pFile->pInode->eFileLock>SHARED_LOCK ){
2729 reserved = 1;
2732 /* Otherwise see if some other process holds it.
2734 if( !reserved ){
2735 /* lock the RESERVED byte */
2736 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
2737 if( SQLITE_OK==lrc ){
2738 /* if we succeeded in taking the reserved lock, unlock it to restore
2739 ** the original state */
2740 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2741 } else {
2742 /* if we failed to get the lock then someone else must have it */
2743 reserved = 1;
2745 if( IS_LOCK_ERROR(lrc) ){
2746 rc=lrc;
2750 unixLeaveMutex();
2751 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
2753 *pResOut = reserved;
2754 return rc;
2758 ** Lock the file with the lock specified by parameter eFileLock - one
2759 ** of the following:
2761 ** (1) SHARED_LOCK
2762 ** (2) RESERVED_LOCK
2763 ** (3) PENDING_LOCK
2764 ** (4) EXCLUSIVE_LOCK
2766 ** Sometimes when requesting one lock state, additional lock states
2767 ** are inserted in between. The locking might fail on one of the later
2768 ** transitions leaving the lock state different from what it started but
2769 ** still short of its goal. The following chart shows the allowed
2770 ** transitions and the inserted intermediate states:
2772 ** UNLOCKED -> SHARED
2773 ** SHARED -> RESERVED
2774 ** SHARED -> (PENDING) -> EXCLUSIVE
2775 ** RESERVED -> (PENDING) -> EXCLUSIVE
2776 ** PENDING -> EXCLUSIVE
2778 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
2779 ** routine to lower a locking level.
2781 static int afpLock(sqlite3_file *id, int eFileLock){
2782 int rc = SQLITE_OK;
2783 unixFile *pFile = (unixFile*)id;
2784 unixInodeInfo *pInode = pFile->pInode;
2785 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2787 assert( pFile );
2788 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2789 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
2790 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
2792 /* If there is already a lock of this type or more restrictive on the
2793 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
2794 ** unixEnterMutex() hasn't been called yet.
2796 if( pFile->eFileLock>=eFileLock ){
2797 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2798 azFileLock(eFileLock)));
2799 return SQLITE_OK;
2802 /* Make sure the locking sequence is correct
2803 ** (1) We never move from unlocked to anything higher than shared lock.
2804 ** (2) SQLite never explicitly requests a pendig lock.
2805 ** (3) A shared lock is always held when a reserve lock is requested.
2807 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2808 assert( eFileLock!=PENDING_LOCK );
2809 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
2811 /* This mutex is needed because pFile->pInode is shared across threads
2813 unixEnterMutex();
2814 pInode = pFile->pInode;
2816 /* If some thread using this PID has a lock via a different unixFile*
2817 ** handle that precludes the requested lock, return BUSY.
2819 if( (pFile->eFileLock!=pInode->eFileLock &&
2820 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
2822 rc = SQLITE_BUSY;
2823 goto afp_end_lock;
2826 /* If a SHARED lock is requested, and some thread using this PID already
2827 ** has a SHARED or RESERVED lock, then increment reference counts and
2828 ** return SQLITE_OK.
2830 if( eFileLock==SHARED_LOCK &&
2831 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
2832 assert( eFileLock==SHARED_LOCK );
2833 assert( pFile->eFileLock==0 );
2834 assert( pInode->nShared>0 );
2835 pFile->eFileLock = SHARED_LOCK;
2836 pInode->nShared++;
2837 pInode->nLock++;
2838 goto afp_end_lock;
2841 /* A PENDING lock is needed before acquiring a SHARED lock and before
2842 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2843 ** be released.
2845 if( eFileLock==SHARED_LOCK
2846 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
2848 int failed;
2849 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
2850 if (failed) {
2851 rc = failed;
2852 goto afp_end_lock;
2856 /* If control gets to this point, then actually go ahead and make
2857 ** operating system calls for the specified lock.
2859 if( eFileLock==SHARED_LOCK ){
2860 int lrc1, lrc2, lrc1Errno = 0;
2861 long lk, mask;
2863 assert( pInode->nShared==0 );
2864 assert( pInode->eFileLock==0 );
2866 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
2867 /* Now get the read-lock SHARED_LOCK */
2868 /* note that the quality of the randomness doesn't matter that much */
2869 lk = random();
2870 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
2871 lrc1 = afpSetLock(context->dbPath, pFile,
2872 SHARED_FIRST+pInode->sharedByte, 1, 1);
2873 if( IS_LOCK_ERROR(lrc1) ){
2874 lrc1Errno = pFile->lastErrno;
2876 /* Drop the temporary PENDING lock */
2877 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
2879 if( IS_LOCK_ERROR(lrc1) ) {
2880 storeLastErrno(pFile, lrc1Errno);
2881 rc = lrc1;
2882 goto afp_end_lock;
2883 } else if( IS_LOCK_ERROR(lrc2) ){
2884 rc = lrc2;
2885 goto afp_end_lock;
2886 } else if( lrc1 != SQLITE_OK ) {
2887 rc = lrc1;
2888 } else {
2889 pFile->eFileLock = SHARED_LOCK;
2890 pInode->nLock++;
2891 pInode->nShared = 1;
2893 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
2894 /* We are trying for an exclusive lock but another thread in this
2895 ** same process is still holding a shared lock. */
2896 rc = SQLITE_BUSY;
2897 }else{
2898 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2899 ** assumed that there is a SHARED or greater lock on the file
2900 ** already.
2902 int failed = 0;
2903 assert( 0!=pFile->eFileLock );
2904 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
2905 /* Acquire a RESERVED lock */
2906 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
2907 if( !failed ){
2908 context->reserved = 1;
2911 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
2912 /* Acquire an EXCLUSIVE lock */
2914 /* Remove the shared lock before trying the range. we'll need to
2915 ** reestablish the shared lock if we can't get the afpUnlock
2917 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
2918 pInode->sharedByte, 1, 0)) ){
2919 int failed2 = SQLITE_OK;
2920 /* now attemmpt to get the exclusive lock range */
2921 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
2922 SHARED_SIZE, 1);
2923 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
2924 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
2925 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2926 ** a critical I/O error
2928 rc = ((failed & 0xff) == SQLITE_IOERR) ? failed2 :
2929 SQLITE_IOERR_LOCK;
2930 goto afp_end_lock;
2932 }else{
2933 rc = failed;
2936 if( failed ){
2937 rc = failed;
2941 if( rc==SQLITE_OK ){
2942 pFile->eFileLock = eFileLock;
2943 pInode->eFileLock = eFileLock;
2944 }else if( eFileLock==EXCLUSIVE_LOCK ){
2945 pFile->eFileLock = PENDING_LOCK;
2946 pInode->eFileLock = PENDING_LOCK;
2949 afp_end_lock:
2950 unixLeaveMutex();
2951 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2952 rc==SQLITE_OK ? "ok" : "failed"));
2953 return rc;
2957 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
2958 ** must be either NO_LOCK or SHARED_LOCK.
2960 ** If the locking level of the file descriptor is already at or below
2961 ** the requested locking level, this routine is a no-op.
2963 static int afpUnlock(sqlite3_file *id, int eFileLock) {
2964 int rc = SQLITE_OK;
2965 unixFile *pFile = (unixFile*)id;
2966 unixInodeInfo *pInode;
2967 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2968 int skipShared = 0;
2969 #ifdef SQLITE_TEST
2970 int h = pFile->h;
2971 #endif
2973 assert( pFile );
2974 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
2975 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
2976 osGetpid(0)));
2978 assert( eFileLock<=SHARED_LOCK );
2979 if( pFile->eFileLock<=eFileLock ){
2980 return SQLITE_OK;
2982 unixEnterMutex();
2983 pInode = pFile->pInode;
2984 assert( pInode->nShared!=0 );
2985 if( pFile->eFileLock>SHARED_LOCK ){
2986 assert( pInode->eFileLock==pFile->eFileLock );
2987 SimulateIOErrorBenign(1);
2988 SimulateIOError( h=(-1) )
2989 SimulateIOErrorBenign(0);
2991 #ifdef SQLITE_DEBUG
2992 /* When reducing a lock such that other processes can start
2993 ** reading the database file again, make sure that the
2994 ** transaction counter was updated if any part of the database
2995 ** file changed. If the transaction counter is not updated,
2996 ** other connections to the same file might not realize that
2997 ** the file has changed and hence might not know to flush their
2998 ** cache. The use of a stale cache can lead to database corruption.
3000 assert( pFile->inNormalWrite==0
3001 || pFile->dbUpdate==0
3002 || pFile->transCntrChng==1 );
3003 pFile->inNormalWrite = 0;
3004 #endif
3006 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
3007 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
3008 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
3009 /* only re-establish the shared lock if necessary */
3010 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3011 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
3012 } else {
3013 skipShared = 1;
3016 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
3017 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
3019 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
3020 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
3021 if( !rc ){
3022 context->reserved = 0;
3025 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
3026 pInode->eFileLock = SHARED_LOCK;
3029 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
3031 /* Decrement the shared lock counter. Release the lock using an
3032 ** OS call only when all threads in this same process have released
3033 ** the lock.
3035 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3036 pInode->nShared--;
3037 if( pInode->nShared==0 ){
3038 SimulateIOErrorBenign(1);
3039 SimulateIOError( h=(-1) )
3040 SimulateIOErrorBenign(0);
3041 if( !skipShared ){
3042 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
3044 if( !rc ){
3045 pInode->eFileLock = NO_LOCK;
3046 pFile->eFileLock = NO_LOCK;
3049 if( rc==SQLITE_OK ){
3050 pInode->nLock--;
3051 assert( pInode->nLock>=0 );
3052 if( pInode->nLock==0 ){
3053 closePendingFds(pFile);
3058 unixLeaveMutex();
3059 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
3060 return rc;
3064 ** Close a file & cleanup AFP specific locking context
3066 static int afpClose(sqlite3_file *id) {
3067 int rc = SQLITE_OK;
3068 unixFile *pFile = (unixFile*)id;
3069 assert( id!=0 );
3070 afpUnlock(id, NO_LOCK);
3071 unixEnterMutex();
3072 if( pFile->pInode && pFile->pInode->nLock ){
3073 /* If there are outstanding locks, do not actually close the file just
3074 ** yet because that would clear those locks. Instead, add the file
3075 ** descriptor to pInode->aPending. It will be automatically closed when
3076 ** the last lock is cleared.
3078 setPendingFd(pFile);
3080 releaseInodeInfo(pFile);
3081 sqlite3_free(pFile->lockingContext);
3082 rc = closeUnixFile(id);
3083 unixLeaveMutex();
3084 return rc;
3087 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3089 ** The code above is the AFP lock implementation. The code is specific
3090 ** to MacOSX and does not work on other unix platforms. No alternative
3091 ** is available. If you don't compile for a mac, then the "unix-afp"
3092 ** VFS is not available.
3094 ********************* End of the AFP lock implementation **********************
3095 ******************************************************************************/
3097 /******************************************************************************
3098 *************************** Begin NFS Locking ********************************/
3100 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3102 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
3103 ** must be either NO_LOCK or SHARED_LOCK.
3105 ** If the locking level of the file descriptor is already at or below
3106 ** the requested locking level, this routine is a no-op.
3108 static int nfsUnlock(sqlite3_file *id, int eFileLock){
3109 return posixUnlock(id, eFileLock, 1);
3112 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3114 ** The code above is the NFS lock implementation. The code is specific
3115 ** to MacOSX and does not work on other unix platforms. No alternative
3116 ** is available.
3118 ********************* End of the NFS lock implementation **********************
3119 ******************************************************************************/
3121 /******************************************************************************
3122 **************** Non-locking sqlite3_file methods *****************************
3124 ** The next division contains implementations for all methods of the
3125 ** sqlite3_file object other than the locking methods. The locking
3126 ** methods were defined in divisions above (one locking method per
3127 ** division). Those methods that are common to all locking modes
3128 ** are gather together into this division.
3132 ** Seek to the offset passed as the second argument, then read cnt
3133 ** bytes into pBuf. Return the number of bytes actually read.
3135 ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3136 ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3137 ** one system to another. Since SQLite does not define USE_PREAD
3138 ** in any form by default, we will not attempt to define _XOPEN_SOURCE.
3139 ** See tickets #2741 and #2681.
3141 ** To avoid stomping the errno value on a failed read the lastErrno value
3142 ** is set before returning.
3144 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3145 int got;
3146 int prior = 0;
3147 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
3148 i64 newOffset;
3149 #endif
3150 TIMER_START;
3151 assert( cnt==(cnt&0x1ffff) );
3152 assert( id->h>2 );
3154 #if defined(USE_PREAD)
3155 got = osPread(id->h, pBuf, cnt, offset);
3156 SimulateIOError( got = -1 );
3157 #elif defined(USE_PREAD64)
3158 got = osPread64(id->h, pBuf, cnt, offset);
3159 SimulateIOError( got = -1 );
3160 #else
3161 newOffset = lseek(id->h, offset, SEEK_SET);
3162 SimulateIOError( newOffset = -1 );
3163 if( newOffset<0 ){
3164 storeLastErrno((unixFile*)id, errno);
3165 return -1;
3167 got = osRead(id->h, pBuf, cnt);
3168 #endif
3169 if( got==cnt ) break;
3170 if( got<0 ){
3171 if( errno==EINTR ){ got = 1; continue; }
3172 prior = 0;
3173 storeLastErrno((unixFile*)id, errno);
3174 break;
3175 }else if( got>0 ){
3176 cnt -= got;
3177 offset += got;
3178 prior += got;
3179 pBuf = (void*)(got + (char*)pBuf);
3181 }while( got>0 );
3182 TIMER_END;
3183 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3184 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3185 return got+prior;
3189 ** Read data from a file into a buffer. Return SQLITE_OK if all
3190 ** bytes were read successfully and SQLITE_IOERR if anything goes
3191 ** wrong.
3193 static int unixRead(
3194 sqlite3_file *id,
3195 void *pBuf,
3196 int amt,
3197 sqlite3_int64 offset
3199 unixFile *pFile = (unixFile *)id;
3200 int got;
3201 assert( id );
3202 assert( offset>=0 );
3203 assert( amt>0 );
3205 /* If this is a database file (not a journal, master-journal or temp
3206 ** file), the bytes in the locking range should never be read or written. */
3207 #if 0
3208 assert( pFile->pPreallocatedUnused==0
3209 || offset>=PENDING_BYTE+512
3210 || offset+amt<=PENDING_BYTE
3212 #endif
3214 #if SQLITE_MAX_MMAP_SIZE>0
3215 /* Deal with as much of this read request as possible by transfering
3216 ** data from the memory mapping using memcpy(). */
3217 if( offset<pFile->mmapSize ){
3218 if( offset+amt <= pFile->mmapSize ){
3219 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3220 return SQLITE_OK;
3221 }else{
3222 int nCopy = pFile->mmapSize - offset;
3223 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3224 pBuf = &((u8 *)pBuf)[nCopy];
3225 amt -= nCopy;
3226 offset += nCopy;
3229 #endif
3231 got = seekAndRead(pFile, offset, pBuf, amt);
3232 if( got==amt ){
3233 return SQLITE_OK;
3234 }else if( got<0 ){
3235 /* lastErrno set by seekAndRead */
3236 return SQLITE_IOERR_READ;
3237 }else{
3238 storeLastErrno(pFile, 0); /* not a system error */
3239 /* Unread parts of the buffer must be zero-filled */
3240 memset(&((char*)pBuf)[got], 0, amt-got);
3241 return SQLITE_IOERR_SHORT_READ;
3246 ** Attempt to seek the file-descriptor passed as the first argument to
3247 ** absolute offset iOff, then attempt to write nBuf bytes of data from
3248 ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3249 ** return the actual number of bytes written (which may be less than
3250 ** nBuf).
3252 static int seekAndWriteFd(
3253 int fd, /* File descriptor to write to */
3254 i64 iOff, /* File offset to begin writing at */
3255 const void *pBuf, /* Copy data from this buffer to the file */
3256 int nBuf, /* Size of buffer pBuf in bytes */
3257 int *piErrno /* OUT: Error number if error occurs */
3259 int rc = 0; /* Value returned by system call */
3261 assert( nBuf==(nBuf&0x1ffff) );
3262 assert( fd>2 );
3263 assert( piErrno!=0 );
3264 nBuf &= 0x1ffff;
3265 TIMER_START;
3267 #if defined(USE_PREAD)
3268 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
3269 #elif defined(USE_PREAD64)
3270 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
3271 #else
3273 i64 iSeek = lseek(fd, iOff, SEEK_SET);
3274 SimulateIOError( iSeek = -1 );
3275 if( iSeek<0 ){
3276 rc = -1;
3277 break;
3279 rc = osWrite(fd, pBuf, nBuf);
3280 }while( rc<0 && errno==EINTR );
3281 #endif
3283 TIMER_END;
3284 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3286 if( rc<0 ) *piErrno = errno;
3287 return rc;
3292 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
3293 ** Return the number of bytes actually read. Update the offset.
3295 ** To avoid stomping the errno value on a failed write the lastErrno value
3296 ** is set before returning.
3298 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
3299 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
3304 ** Write data from a buffer into a file. Return SQLITE_OK on success
3305 ** or some other error code on failure.
3307 static int unixWrite(
3308 sqlite3_file *id,
3309 const void *pBuf,
3310 int amt,
3311 sqlite3_int64 offset
3313 unixFile *pFile = (unixFile*)id;
3314 int wrote = 0;
3315 assert( id );
3316 assert( amt>0 );
3318 /* If this is a database file (not a journal, master-journal or temp
3319 ** file), the bytes in the locking range should never be read or written. */
3320 #if 0
3321 assert( pFile->pPreallocatedUnused==0
3322 || offset>=PENDING_BYTE+512
3323 || offset+amt<=PENDING_BYTE
3325 #endif
3327 #ifdef SQLITE_DEBUG
3328 /* If we are doing a normal write to a database file (as opposed to
3329 ** doing a hot-journal rollback or a write to some file other than a
3330 ** normal database file) then record the fact that the database
3331 ** has changed. If the transaction counter is modified, record that
3332 ** fact too.
3334 if( pFile->inNormalWrite ){
3335 pFile->dbUpdate = 1; /* The database has been modified */
3336 if( offset<=24 && offset+amt>=27 ){
3337 int rc;
3338 char oldCntr[4];
3339 SimulateIOErrorBenign(1);
3340 rc = seekAndRead(pFile, 24, oldCntr, 4);
3341 SimulateIOErrorBenign(0);
3342 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
3343 pFile->transCntrChng = 1; /* The transaction counter has changed */
3347 #endif
3349 #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
3350 /* Deal with as much of this write request as possible by transfering
3351 ** data from the memory mapping using memcpy(). */
3352 if( offset<pFile->mmapSize ){
3353 if( offset+amt <= pFile->mmapSize ){
3354 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3355 return SQLITE_OK;
3356 }else{
3357 int nCopy = pFile->mmapSize - offset;
3358 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3359 pBuf = &((u8 *)pBuf)[nCopy];
3360 amt -= nCopy;
3361 offset += nCopy;
3364 #endif
3366 while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
3367 amt -= wrote;
3368 offset += wrote;
3369 pBuf = &((char*)pBuf)[wrote];
3371 SimulateIOError(( wrote=(-1), amt=1 ));
3372 SimulateDiskfullError(( wrote=0, amt=1 ));
3374 if( amt>wrote ){
3375 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
3376 /* lastErrno set by seekAndWrite */
3377 return SQLITE_IOERR_WRITE;
3378 }else{
3379 storeLastErrno(pFile, 0); /* not a system error */
3380 return SQLITE_FULL;
3384 return SQLITE_OK;
3387 #ifdef SQLITE_TEST
3389 ** Count the number of fullsyncs and normal syncs. This is used to test
3390 ** that syncs and fullsyncs are occurring at the right times.
3392 int sqlite3_sync_count = 0;
3393 int sqlite3_fullsync_count = 0;
3394 #endif
3397 ** We do not trust systems to provide a working fdatasync(). Some do.
3398 ** Others do no. To be safe, we will stick with the (slightly slower)
3399 ** fsync(). If you know that your system does support fdatasync() correctly,
3400 ** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
3402 #if !defined(fdatasync) && !HAVE_FDATASYNC
3403 # define fdatasync fsync
3404 #endif
3407 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3408 ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3409 ** only available on Mac OS X. But that could change.
3411 #ifdef F_FULLFSYNC
3412 # define HAVE_FULLFSYNC 1
3413 #else
3414 # define HAVE_FULLFSYNC 0
3415 #endif
3419 ** The fsync() system call does not work as advertised on many
3420 ** unix systems. The following procedure is an attempt to make
3421 ** it work better.
3423 ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3424 ** for testing when we want to run through the test suite quickly.
3425 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3426 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3427 ** or power failure will likely corrupt the database file.
3429 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
3430 ** The idea behind dataOnly is that it should only write the file content
3431 ** to disk, not the inode. We only set dataOnly if the file size is
3432 ** unchanged since the file size is part of the inode. However,
3433 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
3434 ** file size has changed. The only real difference between fdatasync()
3435 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
3436 ** inode if the mtime or owner or other inode attributes have changed.
3437 ** We only care about the file size, not the other file attributes, so
3438 ** as far as SQLite is concerned, an fdatasync() is always adequate.
3439 ** So, we always use fdatasync() if it is available, regardless of
3440 ** the value of the dataOnly flag.
3442 static int full_fsync(int fd, int fullSync, int dataOnly){
3443 int rc;
3445 /* The following "ifdef/elif/else/" block has the same structure as
3446 ** the one below. It is replicated here solely to avoid cluttering
3447 ** up the real code with the UNUSED_PARAMETER() macros.
3449 #ifdef SQLITE_NO_SYNC
3450 UNUSED_PARAMETER(fd);
3451 UNUSED_PARAMETER(fullSync);
3452 UNUSED_PARAMETER(dataOnly);
3453 #elif HAVE_FULLFSYNC
3454 UNUSED_PARAMETER(dataOnly);
3455 #else
3456 UNUSED_PARAMETER(fullSync);
3457 UNUSED_PARAMETER(dataOnly);
3458 #endif
3460 /* Record the number of times that we do a normal fsync() and
3461 ** FULLSYNC. This is used during testing to verify that this procedure
3462 ** gets called with the correct arguments.
3464 #ifdef SQLITE_TEST
3465 if( fullSync ) sqlite3_fullsync_count++;
3466 sqlite3_sync_count++;
3467 #endif
3469 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3470 ** no-op. But go ahead and call fstat() to validate the file
3471 ** descriptor as we need a method to provoke a failure during
3472 ** coverate testing.
3474 #ifdef SQLITE_NO_SYNC
3476 struct stat buf;
3477 rc = osFstat(fd, &buf);
3479 #elif HAVE_FULLFSYNC
3480 if( fullSync ){
3481 rc = osFcntl(fd, F_FULLFSYNC, 0);
3482 }else{
3483 rc = 1;
3485 /* If the FULLFSYNC failed, fall back to attempting an fsync().
3486 ** It shouldn't be possible for fullfsync to fail on the local
3487 ** file system (on OSX), so failure indicates that FULLFSYNC
3488 ** isn't supported for this file system. So, attempt an fsync
3489 ** and (for now) ignore the overhead of a superfluous fcntl call.
3490 ** It'd be better to detect fullfsync support once and avoid
3491 ** the fcntl call every time sync is called.
3493 if( rc ) rc = fsync(fd);
3495 #elif defined(__APPLE__)
3496 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3497 ** so currently we default to the macro that redefines fdatasync to fsync
3499 rc = fsync(fd);
3500 #else
3501 rc = fdatasync(fd);
3502 #if OS_VXWORKS
3503 if( rc==-1 && errno==ENOTSUP ){
3504 rc = fsync(fd);
3506 #endif /* OS_VXWORKS */
3507 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3509 if( OS_VXWORKS && rc!= -1 ){
3510 rc = 0;
3512 return rc;
3516 ** Open a file descriptor to the directory containing file zFilename.
3517 ** If successful, *pFd is set to the opened file descriptor and
3518 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3519 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3520 ** value.
3522 ** The directory file descriptor is used for only one thing - to
3523 ** fsync() a directory to make sure file creation and deletion events
3524 ** are flushed to disk. Such fsyncs are not needed on newer
3525 ** journaling filesystems, but are required on older filesystems.
3527 ** This routine can be overridden using the xSetSysCall interface.
3528 ** The ability to override this routine was added in support of the
3529 ** chromium sandbox. Opening a directory is a security risk (we are
3530 ** told) so making it overrideable allows the chromium sandbox to
3531 ** replace this routine with a harmless no-op. To make this routine
3532 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3533 ** *pFd set to a negative number.
3535 ** If SQLITE_OK is returned, the caller is responsible for closing
3536 ** the file descriptor *pFd using close().
3538 static int openDirectory(const char *zFilename, int *pFd){
3539 int ii;
3540 int fd = -1;
3541 char zDirname[MAX_PATHNAME+1];
3543 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3544 for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
3545 if( ii>0 ){
3546 zDirname[ii] = '\0';
3547 }else{
3548 if( zDirname[0]!='/' ) zDirname[0] = '.';
3549 zDirname[1] = 0;
3551 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3552 if( fd>=0 ){
3553 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3555 *pFd = fd;
3556 if( fd>=0 ) return SQLITE_OK;
3557 return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
3561 ** Make sure all writes to a particular file are committed to disk.
3563 ** If dataOnly==0 then both the file itself and its metadata (file
3564 ** size, access time, etc) are synced. If dataOnly!=0 then only the
3565 ** file data is synced.
3567 ** Under Unix, also make sure that the directory entry for the file
3568 ** has been created by fsync-ing the directory that contains the file.
3569 ** If we do not do this and we encounter a power failure, the directory
3570 ** entry for the journal might not exist after we reboot. The next
3571 ** SQLite to access the file will not know that the journal exists (because
3572 ** the directory entry for the journal was never created) and the transaction
3573 ** will not roll back - possibly leading to database corruption.
3575 static int unixSync(sqlite3_file *id, int flags){
3576 int rc;
3577 unixFile *pFile = (unixFile*)id;
3579 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3580 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3582 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3583 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3584 || (flags&0x0F)==SQLITE_SYNC_FULL
3587 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3588 ** line is to test that doing so does not cause any problems.
3590 SimulateDiskfullError( return SQLITE_FULL );
3592 assert( pFile );
3593 OSTRACE(("SYNC %-3d\n", pFile->h));
3594 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3595 SimulateIOError( rc=1 );
3596 if( rc ){
3597 storeLastErrno(pFile, errno);
3598 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
3601 /* Also fsync the directory containing the file if the DIRSYNC flag
3602 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
3603 ** are unable to fsync a directory, so ignore errors on the fsync.
3605 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3606 int dirfd;
3607 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
3608 HAVE_FULLFSYNC, isFullsync));
3609 rc = osOpenDirectory(pFile->zPath, &dirfd);
3610 if( rc==SQLITE_OK ){
3611 full_fsync(dirfd, 0, 0);
3612 robust_close(pFile, dirfd, __LINE__);
3613 }else{
3614 assert( rc==SQLITE_CANTOPEN );
3615 rc = SQLITE_OK;
3617 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
3619 return rc;
3623 ** Truncate an open file to a specified size
3625 static int unixTruncate(sqlite3_file *id, i64 nByte){
3626 unixFile *pFile = (unixFile *)id;
3627 int rc;
3628 assert( pFile );
3629 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
3631 /* If the user has configured a chunk-size for this file, truncate the
3632 ** file so that it consists of an integer number of chunks (i.e. the
3633 ** actual file size after the operation may be larger than the requested
3634 ** size).
3636 if( pFile->szChunk>0 ){
3637 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3640 rc = robust_ftruncate(pFile->h, nByte);
3641 if( rc ){
3642 storeLastErrno(pFile, errno);
3643 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3644 }else{
3645 #ifdef SQLITE_DEBUG
3646 /* If we are doing a normal write to a database file (as opposed to
3647 ** doing a hot-journal rollback or a write to some file other than a
3648 ** normal database file) and we truncate the file to zero length,
3649 ** that effectively updates the change counter. This might happen
3650 ** when restoring a database using the backup API from a zero-length
3651 ** source.
3653 if( pFile->inNormalWrite && nByte==0 ){
3654 pFile->transCntrChng = 1;
3656 #endif
3658 #if SQLITE_MAX_MMAP_SIZE>0
3659 /* If the file was just truncated to a size smaller than the currently
3660 ** mapped region, reduce the effective mapping size as well. SQLite will
3661 ** use read() and write() to access data beyond this point from now on.
3663 if( nByte<pFile->mmapSize ){
3664 pFile->mmapSize = nByte;
3666 #endif
3668 return SQLITE_OK;
3673 ** Determine the current size of a file in bytes
3675 static int unixFileSize(sqlite3_file *id, i64 *pSize){
3676 int rc;
3677 struct stat buf;
3678 assert( id );
3679 rc = osFstat(((unixFile*)id)->h, &buf);
3680 SimulateIOError( rc=1 );
3681 if( rc!=0 ){
3682 storeLastErrno((unixFile*)id, errno);
3683 return SQLITE_IOERR_FSTAT;
3685 *pSize = buf.st_size;
3687 /* When opening a zero-size database, the findInodeInfo() procedure
3688 ** writes a single byte into that file in order to work around a bug
3689 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3690 ** layers, we need to report this file size as zero even though it is
3691 ** really 1. Ticket #3260.
3693 if( *pSize==1 ) *pSize = 0;
3696 return SQLITE_OK;
3699 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
3701 ** Handler for proxy-locking file-control verbs. Defined below in the
3702 ** proxying locking division.
3704 static int proxyFileControl(sqlite3_file*,int,void*);
3705 #endif
3708 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
3709 ** file-control operation. Enlarge the database to nBytes in size
3710 ** (rounded up to the next chunk-size). If the database is already
3711 ** nBytes or larger, this routine is a no-op.
3713 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
3714 if( pFile->szChunk>0 ){
3715 i64 nSize; /* Required file size */
3716 struct stat buf; /* Used to hold return values of fstat() */
3718 if( osFstat(pFile->h, &buf) ){
3719 return SQLITE_IOERR_FSTAT;
3722 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3723 if( nSize>(i64)buf.st_size ){
3725 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
3726 /* The code below is handling the return value of osFallocate()
3727 ** correctly. posix_fallocate() is defined to "returns zero on success,
3728 ** or an error number on failure". See the manpage for details. */
3729 int err;
3731 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3732 }while( err==EINTR );
3733 if( err ) return SQLITE_IOERR_WRITE;
3734 #else
3735 /* If the OS does not have posix_fallocate(), fake it. Write a
3736 ** single byte to the last byte in each block that falls entirely
3737 ** within the extended region. Then, if required, a single byte
3738 ** at offset (nSize-1), to set the size of the file correctly.
3739 ** This is a similar technique to that used by glibc on systems
3740 ** that do not have a real fallocate() call.
3742 int nBlk = buf.st_blksize; /* File-system block size */
3743 int nWrite = 0; /* Number of bytes written by seekAndWrite */
3744 i64 iWrite; /* Next offset to write to */
3746 iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
3747 assert( iWrite>=buf.st_size );
3748 assert( ((iWrite+1)%nBlk)==0 );
3749 for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
3750 if( iWrite>=nSize ) iWrite = nSize - 1;
3751 nWrite = seekAndWrite(pFile, iWrite, "", 1);
3752 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
3754 #endif
3758 #if SQLITE_MAX_MMAP_SIZE>0
3759 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
3760 int rc;
3761 if( pFile->szChunk<=0 ){
3762 if( robust_ftruncate(pFile->h, nByte) ){
3763 storeLastErrno(pFile, errno);
3764 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3768 rc = unixMapfile(pFile, nByte);
3769 return rc;
3771 #endif
3773 return SQLITE_OK;
3777 ** If *pArg is initially negative then this is a query. Set *pArg to
3778 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3780 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3782 static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3783 if( *pArg<0 ){
3784 *pArg = (pFile->ctrlFlags & mask)!=0;
3785 }else if( (*pArg)==0 ){
3786 pFile->ctrlFlags &= ~mask;
3787 }else{
3788 pFile->ctrlFlags |= mask;
3792 /* Forward declaration */
3793 static int unixGetTempname(int nBuf, char *zBuf);
3796 ** Information and control of an open file handle.
3798 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
3799 unixFile *pFile = (unixFile*)id;
3800 switch( op ){
3801 #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
3802 case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: {
3803 int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE);
3804 return rc ? SQLITE_IOERR_BEGIN_ATOMIC : SQLITE_OK;
3806 case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: {
3807 int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE);
3808 return rc ? SQLITE_IOERR_COMMIT_ATOMIC : SQLITE_OK;
3810 case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: {
3811 int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE);
3812 return rc ? SQLITE_IOERR_ROLLBACK_ATOMIC : SQLITE_OK;
3814 #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
3816 case SQLITE_FCNTL_LOCKSTATE: {
3817 *(int*)pArg = pFile->eFileLock;
3818 return SQLITE_OK;
3820 case SQLITE_FCNTL_LAST_ERRNO: {
3821 *(int*)pArg = pFile->lastErrno;
3822 return SQLITE_OK;
3824 case SQLITE_FCNTL_CHUNK_SIZE: {
3825 pFile->szChunk = *(int *)pArg;
3826 return SQLITE_OK;
3828 case SQLITE_FCNTL_SIZE_HINT: {
3829 int rc;
3830 SimulateIOErrorBenign(1);
3831 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3832 SimulateIOErrorBenign(0);
3833 return rc;
3835 case SQLITE_FCNTL_PERSIST_WAL: {
3836 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3837 return SQLITE_OK;
3839 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3840 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
3841 return SQLITE_OK;
3843 case SQLITE_FCNTL_VFSNAME: {
3844 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3845 return SQLITE_OK;
3847 case SQLITE_FCNTL_TEMPFILENAME: {
3848 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
3849 if( zTFile ){
3850 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3851 *(char**)pArg = zTFile;
3853 return SQLITE_OK;
3855 case SQLITE_FCNTL_HAS_MOVED: {
3856 *(int*)pArg = fileHasMoved(pFile);
3857 return SQLITE_OK;
3859 #if SQLITE_MAX_MMAP_SIZE>0
3860 case SQLITE_FCNTL_MMAP_SIZE: {
3861 i64 newLimit = *(i64*)pArg;
3862 int rc = SQLITE_OK;
3863 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3864 newLimit = sqlite3GlobalConfig.mxMmap;
3867 /* The value of newLimit may be eventually cast to (size_t) and passed
3868 ** to mmap(). Restrict its value to 2GB if (size_t) is not at least a
3869 ** 64-bit type. */
3870 if( newLimit>0 && sizeof(size_t)<8 ){
3871 newLimit = (newLimit & 0x7FFFFFFF);
3874 *(i64*)pArg = pFile->mmapSizeMax;
3875 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
3876 pFile->mmapSizeMax = newLimit;
3877 if( pFile->mmapSize>0 ){
3878 unixUnmapfile(pFile);
3879 rc = unixMapfile(pFile, -1);
3882 return rc;
3884 #endif
3885 #ifdef SQLITE_DEBUG
3886 /* The pager calls this method to signal that it has done
3887 ** a rollback and that the database is therefore unchanged and
3888 ** it hence it is OK for the transaction change counter to be
3889 ** unchanged.
3891 case SQLITE_FCNTL_DB_UNCHANGED: {
3892 ((unixFile*)id)->dbUpdate = 0;
3893 return SQLITE_OK;
3895 #endif
3896 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
3897 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
3898 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
3899 return proxyFileControl(id,op,pArg);
3901 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
3903 return SQLITE_NOTFOUND;
3907 ** If pFd->sectorSize is non-zero when this function is called, it is a
3908 ** no-op. Otherwise, the values of pFd->sectorSize and
3909 ** pFd->deviceCharacteristics are set according to the file-system
3910 ** characteristics.
3912 ** There are two versions of this function. One for QNX and one for all
3913 ** other systems.
3915 #ifndef __QNXNTO__
3916 static void setDeviceCharacteristics(unixFile *pFd){
3917 assert( pFd->deviceCharacteristics==0 || pFd->sectorSize!=0 );
3918 if( pFd->sectorSize==0 ){
3919 #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
3920 int res;
3921 u32 f = 0;
3923 /* Check for support for F2FS atomic batch writes. */
3924 res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES, &f);
3925 if( res==0 && (f & F2FS_FEATURE_ATOMIC_WRITE) ){
3926 pFd->deviceCharacteristics = SQLITE_IOCAP_BATCH_ATOMIC;
3928 #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
3930 /* Set the POWERSAFE_OVERWRITE flag if requested. */
3931 if( pFd->ctrlFlags & UNIXFILE_PSOW ){
3932 pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
3935 pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3938 #else
3939 #include <sys/dcmd_blk.h>
3940 #include <sys/statvfs.h>
3941 static void setDeviceCharacteristics(unixFile *pFile){
3942 if( pFile->sectorSize == 0 ){
3943 struct statvfs fsInfo;
3945 /* Set defaults for non-supported filesystems */
3946 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3947 pFile->deviceCharacteristics = 0;
3948 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3949 return pFile->sectorSize;
3952 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3953 pFile->sectorSize = fsInfo.f_bsize;
3954 pFile->deviceCharacteristics =
3955 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3956 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3957 ** the write succeeds */
3958 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3959 ** so it is ordered */
3961 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3962 pFile->sectorSize = fsInfo.f_bsize;
3963 pFile->deviceCharacteristics =
3964 /* etfs cluster size writes are atomic */
3965 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3966 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3967 ** the write succeeds */
3968 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3969 ** so it is ordered */
3971 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3972 pFile->sectorSize = fsInfo.f_bsize;
3973 pFile->deviceCharacteristics =
3974 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
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, "qnx4") ){
3981 pFile->sectorSize = fsInfo.f_bsize;
3982 pFile->deviceCharacteristics =
3983 /* full bitset of atomics from max sector size and smaller */
3984 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3985 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3986 ** so it is ordered */
3988 }else if( strstr(fsInfo.f_basetype, "dos") ){
3989 pFile->sectorSize = fsInfo.f_bsize;
3990 pFile->deviceCharacteristics =
3991 /* full bitset of atomics from max sector size and smaller */
3992 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3993 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3994 ** so it is ordered */
3996 }else{
3997 pFile->deviceCharacteristics =
3998 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3999 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4000 ** the write succeeds */
4004 /* Last chance verification. If the sector size isn't a multiple of 512
4005 ** then it isn't valid.*/
4006 if( pFile->sectorSize % 512 != 0 ){
4007 pFile->deviceCharacteristics = 0;
4008 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4011 #endif
4014 ** Return the sector size in bytes of the underlying block device for
4015 ** the specified file. This is almost always 512 bytes, but may be
4016 ** larger for some devices.
4018 ** SQLite code assumes this function cannot fail. It also assumes that
4019 ** if two files are created in the same file-system directory (i.e.
4020 ** a database and its journal file) that the sector size will be the
4021 ** same for both.
4023 static int unixSectorSize(sqlite3_file *id){
4024 unixFile *pFd = (unixFile*)id;
4025 setDeviceCharacteristics(pFd);
4026 return pFd->sectorSize;
4030 ** Return the device characteristics for the file.
4032 ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
4033 ** However, that choice is controversial since technically the underlying
4034 ** file system does not always provide powersafe overwrites. (In other
4035 ** words, after a power-loss event, parts of the file that were never
4036 ** written might end up being altered.) However, non-PSOW behavior is very,
4037 ** very rare. And asserting PSOW makes a large reduction in the amount
4038 ** of required I/O for journaling, since a lot of padding is eliminated.
4039 ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
4040 ** available to turn it off and URI query parameter available to turn it off.
4042 static int unixDeviceCharacteristics(sqlite3_file *id){
4043 unixFile *pFd = (unixFile*)id;
4044 setDeviceCharacteristics(pFd);
4045 return pFd->deviceCharacteristics;
4048 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
4051 ** Return the system page size.
4053 ** This function should not be called directly by other code in this file.
4054 ** Instead, it should be called via macro osGetpagesize().
4056 static int unixGetpagesize(void){
4057 #if OS_VXWORKS
4058 return 1024;
4059 #elif defined(_BSD_SOURCE)
4060 return getpagesize();
4061 #else
4062 return (int)sysconf(_SC_PAGESIZE);
4063 #endif
4066 #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
4068 #ifndef SQLITE_OMIT_WAL
4071 ** Object used to represent an shared memory buffer.
4073 ** When multiple threads all reference the same wal-index, each thread
4074 ** has its own unixShm object, but they all point to a single instance
4075 ** of this unixShmNode object. In other words, each wal-index is opened
4076 ** only once per process.
4078 ** Each unixShmNode object is connected to a single unixInodeInfo object.
4079 ** We could coalesce this object into unixInodeInfo, but that would mean
4080 ** every open file that does not use shared memory (in other words, most
4081 ** open files) would have to carry around this extra information. So
4082 ** the unixInodeInfo object contains a pointer to this unixShmNode object
4083 ** and the unixShmNode object is created only when needed.
4085 ** unixMutexHeld() must be true when creating or destroying
4086 ** this object or while reading or writing the following fields:
4088 ** nRef
4090 ** The following fields are read-only after the object is created:
4092 ** fid
4093 ** zFilename
4095 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
4096 ** unixMutexHeld() is true when reading or writing any other field
4097 ** in this structure.
4099 struct unixShmNode {
4100 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
4101 sqlite3_mutex *mutex; /* Mutex to access this object */
4102 char *zFilename; /* Name of the mmapped file */
4103 int h; /* Open file descriptor */
4104 int szRegion; /* Size of shared-memory regions */
4105 u16 nRegion; /* Size of array apRegion */
4106 u8 isReadonly; /* True if read-only */
4107 char **apRegion; /* Array of mapped shared-memory regions */
4108 int nRef; /* Number of unixShm objects pointing to this */
4109 unixShm *pFirst; /* All unixShm objects pointing to this */
4110 #ifdef SQLITE_DEBUG
4111 u8 exclMask; /* Mask of exclusive locks held */
4112 u8 sharedMask; /* Mask of shared locks held */
4113 u8 nextShmId; /* Next available unixShm.id value */
4114 #endif
4118 ** Structure used internally by this VFS to record the state of an
4119 ** open shared memory connection.
4121 ** The following fields are initialized when this object is created and
4122 ** are read-only thereafter:
4124 ** unixShm.pFile
4125 ** unixShm.id
4127 ** All other fields are read/write. The unixShm.pFile->mutex must be held
4128 ** while accessing any read/write fields.
4130 struct unixShm {
4131 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4132 unixShm *pNext; /* Next unixShm with the same unixShmNode */
4133 u8 hasMutex; /* True if holding the unixShmNode mutex */
4134 u8 id; /* Id of this connection within its unixShmNode */
4135 u16 sharedMask; /* Mask of shared locks held */
4136 u16 exclMask; /* Mask of exclusive locks held */
4140 ** Constants used for locking
4142 #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
4143 #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
4146 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
4148 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4149 ** otherwise.
4151 static int unixShmSystemLock(
4152 unixFile *pFile, /* Open connection to the WAL file */
4153 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
4154 int ofst, /* First byte of the locking range */
4155 int n /* Number of bytes to lock */
4157 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4158 struct flock f; /* The posix advisory locking structure */
4159 int rc = SQLITE_OK; /* Result code form fcntl() */
4161 /* Access to the unixShmNode object is serialized by the caller */
4162 pShmNode = pFile->pInode->pShmNode;
4163 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
4165 /* Shared locks never span more than one byte */
4166 assert( n==1 || lockType!=F_RDLCK );
4168 /* Locks are within range */
4169 assert( n>=1 && n<=SQLITE_SHM_NLOCK );
4171 if( pShmNode->h>=0 ){
4172 /* Initialize the locking parameters */
4173 memset(&f, 0, sizeof(f));
4174 f.l_type = lockType;
4175 f.l_whence = SEEK_SET;
4176 f.l_start = ofst;
4177 f.l_len = n;
4179 rc = osFcntl(pShmNode->h, F_SETLK, &f);
4180 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4183 /* Update the global lock state and do debug tracing */
4184 #ifdef SQLITE_DEBUG
4185 { u16 mask;
4186 OSTRACE(("SHM-LOCK "));
4187 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
4188 if( rc==SQLITE_OK ){
4189 if( lockType==F_UNLCK ){
4190 OSTRACE(("unlock %d ok", ofst));
4191 pShmNode->exclMask &= ~mask;
4192 pShmNode->sharedMask &= ~mask;
4193 }else if( lockType==F_RDLCK ){
4194 OSTRACE(("read-lock %d ok", ofst));
4195 pShmNode->exclMask &= ~mask;
4196 pShmNode->sharedMask |= mask;
4197 }else{
4198 assert( lockType==F_WRLCK );
4199 OSTRACE(("write-lock %d ok", ofst));
4200 pShmNode->exclMask |= mask;
4201 pShmNode->sharedMask &= ~mask;
4203 }else{
4204 if( lockType==F_UNLCK ){
4205 OSTRACE(("unlock %d failed", ofst));
4206 }else if( lockType==F_RDLCK ){
4207 OSTRACE(("read-lock failed"));
4208 }else{
4209 assert( lockType==F_WRLCK );
4210 OSTRACE(("write-lock %d failed", ofst));
4213 OSTRACE((" - afterwards %03x,%03x\n",
4214 pShmNode->sharedMask, pShmNode->exclMask));
4216 #endif
4218 return rc;
4222 ** Return the minimum number of 32KB shm regions that should be mapped at
4223 ** a time, assuming that each mapping must be an integer multiple of the
4224 ** current system page-size.
4226 ** Usually, this is 1. The exception seems to be systems that are configured
4227 ** to use 64KB pages - in this case each mapping must cover at least two
4228 ** shm regions.
4230 static int unixShmRegionPerMap(void){
4231 int shmsz = 32*1024; /* SHM region size */
4232 int pgsz = osGetpagesize(); /* System page size */
4233 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4234 if( pgsz<shmsz ) return 1;
4235 return pgsz/shmsz;
4239 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
4241 ** This is not a VFS shared-memory method; it is a utility function called
4242 ** by VFS shared-memory methods.
4244 static void unixShmPurge(unixFile *pFd){
4245 unixShmNode *p = pFd->pInode->pShmNode;
4246 assert( unixMutexHeld() );
4247 if( p && ALWAYS(p->nRef==0) ){
4248 int nShmPerMap = unixShmRegionPerMap();
4249 int i;
4250 assert( p->pInode==pFd->pInode );
4251 sqlite3_mutex_free(p->mutex);
4252 for(i=0; i<p->nRegion; i+=nShmPerMap){
4253 if( p->h>=0 ){
4254 osMunmap(p->apRegion[i], p->szRegion);
4255 }else{
4256 sqlite3_free(p->apRegion[i]);
4259 sqlite3_free(p->apRegion);
4260 if( p->h>=0 ){
4261 robust_close(pFd, p->h, __LINE__);
4262 p->h = -1;
4264 p->pInode->pShmNode = 0;
4265 sqlite3_free(p);
4270 ** Open a shared-memory area associated with open database file pDbFd.
4271 ** This particular implementation uses mmapped files.
4273 ** The file used to implement shared-memory is in the same directory
4274 ** as the open database file and has the same name as the open database
4275 ** file with the "-shm" suffix added. For example, if the database file
4276 ** is "/home/user1/config.db" then the file that is created and mmapped
4277 ** for shared memory will be called "/home/user1/config.db-shm".
4279 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
4280 ** some other tmpfs mount. But if a file in a different directory
4281 ** from the database file is used, then differing access permissions
4282 ** or a chroot() might cause two different processes on the same
4283 ** database to end up using different files for shared memory -
4284 ** meaning that their memory would not really be shared - resulting
4285 ** in database corruption. Nevertheless, this tmpfs file usage
4286 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4287 ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4288 ** option results in an incompatible build of SQLite; builds of SQLite
4289 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4290 ** same database file at the same time, database corruption will likely
4291 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4292 ** "unsupported" and may go away in a future SQLite release.
4294 ** When opening a new shared-memory file, if no other instances of that
4295 ** file are currently open, in this process or in other processes, then
4296 ** the file must be truncated to zero length or have its header cleared.
4298 ** If the original database file (pDbFd) is using the "unix-excl" VFS
4299 ** that means that an exclusive lock is held on the database file and
4300 ** that no other processes are able to read or write the database. In
4301 ** that case, we do not really need shared memory. No shared memory
4302 ** file is created. The shared memory will be simulated with heap memory.
4304 static int unixOpenSharedMemory(unixFile *pDbFd){
4305 struct unixShm *p = 0; /* The connection to be opened */
4306 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4307 int rc; /* Result code */
4308 unixInodeInfo *pInode; /* The inode of fd */
4309 char *zShmFilename; /* Name of the file used for SHM */
4310 int nShmFilename; /* Size of the SHM filename in bytes */
4312 /* Allocate space for the new unixShm object. */
4313 p = sqlite3_malloc64( sizeof(*p) );
4314 if( p==0 ) return SQLITE_NOMEM_BKPT;
4315 memset(p, 0, sizeof(*p));
4316 assert( pDbFd->pShm==0 );
4318 /* Check to see if a unixShmNode object already exists. Reuse an existing
4319 ** one if present. Create a new one if necessary.
4321 unixEnterMutex();
4322 pInode = pDbFd->pInode;
4323 pShmNode = pInode->pShmNode;
4324 if( pShmNode==0 ){
4325 struct stat sStat; /* fstat() info for database file */
4326 #ifndef SQLITE_SHM_DIRECTORY
4327 const char *zBasePath = pDbFd->zPath;
4328 #endif
4330 /* Call fstat() to figure out the permissions on the database file. If
4331 ** a new *-shm file is created, an attempt will be made to create it
4332 ** with the same permissions.
4334 if( osFstat(pDbFd->h, &sStat) ){
4335 rc = SQLITE_IOERR_FSTAT;
4336 goto shm_open_err;
4339 #ifdef SQLITE_SHM_DIRECTORY
4340 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
4341 #else
4342 nShmFilename = 6 + (int)strlen(zBasePath);
4343 #endif
4344 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
4345 if( pShmNode==0 ){
4346 rc = SQLITE_NOMEM_BKPT;
4347 goto shm_open_err;
4349 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
4350 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
4351 #ifdef SQLITE_SHM_DIRECTORY
4352 sqlite3_snprintf(nShmFilename, zShmFilename,
4353 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4354 (u32)sStat.st_ino, (u32)sStat.st_dev);
4355 #else
4356 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
4357 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
4358 #endif
4359 pShmNode->h = -1;
4360 pDbFd->pInode->pShmNode = pShmNode;
4361 pShmNode->pInode = pDbFd->pInode;
4362 if( sqlite3GlobalConfig.bCoreMutex ){
4363 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4364 if( pShmNode->mutex==0 ){
4365 rc = SQLITE_NOMEM_BKPT;
4366 goto shm_open_err;
4370 if( pInode->bProcessLock==0 ){
4371 int openFlags = O_RDWR | O_CREAT;
4372 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
4373 openFlags = O_RDONLY;
4374 pShmNode->isReadonly = 1;
4376 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
4377 if( pShmNode->h<0 ){
4378 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4379 goto shm_open_err;
4382 /* If this process is running as root, make sure that the SHM file
4383 ** is owned by the same user that owns the original database. Otherwise,
4384 ** the original owner will not be able to connect.
4386 robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
4388 /* Check to see if another process is holding the dead-man switch.
4389 ** If not, truncate the file to zero length.
4391 rc = SQLITE_OK;
4392 if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
4393 if( robust_ftruncate(pShmNode->h, 0) ){
4394 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
4397 if( rc==SQLITE_OK ){
4398 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
4400 if( rc ) goto shm_open_err;
4404 /* Make the new connection a child of the unixShmNode */
4405 p->pShmNode = pShmNode;
4406 #ifdef SQLITE_DEBUG
4407 p->id = pShmNode->nextShmId++;
4408 #endif
4409 pShmNode->nRef++;
4410 pDbFd->pShm = p;
4411 unixLeaveMutex();
4413 /* The reference count on pShmNode has already been incremented under
4414 ** the cover of the unixEnterMutex() mutex and the pointer from the
4415 ** new (struct unixShm) object to the pShmNode has been set. All that is
4416 ** left to do is to link the new object into the linked list starting
4417 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4418 ** mutex.
4420 sqlite3_mutex_enter(pShmNode->mutex);
4421 p->pNext = pShmNode->pFirst;
4422 pShmNode->pFirst = p;
4423 sqlite3_mutex_leave(pShmNode->mutex);
4424 return SQLITE_OK;
4426 /* Jump here on any error */
4427 shm_open_err:
4428 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
4429 sqlite3_free(p);
4430 unixLeaveMutex();
4431 return rc;
4435 ** This function is called to obtain a pointer to region iRegion of the
4436 ** shared-memory associated with the database file fd. Shared-memory regions
4437 ** are numbered starting from zero. Each shared-memory region is szRegion
4438 ** bytes in size.
4440 ** If an error occurs, an error code is returned and *pp is set to NULL.
4442 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4443 ** region has not been allocated (by any client, including one running in a
4444 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4445 ** bExtend is non-zero and the requested shared-memory region has not yet
4446 ** been allocated, it is allocated by this function.
4448 ** If the shared-memory region has already been allocated or is allocated by
4449 ** this call as described above, then it is mapped into this processes
4450 ** address space (if it is not already), *pp is set to point to the mapped
4451 ** memory and SQLITE_OK returned.
4453 static int unixShmMap(
4454 sqlite3_file *fd, /* Handle open on database file */
4455 int iRegion, /* Region to retrieve */
4456 int szRegion, /* Size of regions */
4457 int bExtend, /* True to extend file if necessary */
4458 void volatile **pp /* OUT: Mapped memory */
4460 unixFile *pDbFd = (unixFile*)fd;
4461 unixShm *p;
4462 unixShmNode *pShmNode;
4463 int rc = SQLITE_OK;
4464 int nShmPerMap = unixShmRegionPerMap();
4465 int nReqRegion;
4467 /* If the shared-memory file has not yet been opened, open it now. */
4468 if( pDbFd->pShm==0 ){
4469 rc = unixOpenSharedMemory(pDbFd);
4470 if( rc!=SQLITE_OK ) return rc;
4473 p = pDbFd->pShm;
4474 pShmNode = p->pShmNode;
4475 sqlite3_mutex_enter(pShmNode->mutex);
4476 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
4477 assert( pShmNode->pInode==pDbFd->pInode );
4478 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4479 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
4481 /* Minimum number of regions required to be mapped. */
4482 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4484 if( pShmNode->nRegion<nReqRegion ){
4485 char **apNew; /* New apRegion[] array */
4486 int nByte = nReqRegion*szRegion; /* Minimum required file size */
4487 struct stat sStat; /* Used by fstat() */
4489 pShmNode->szRegion = szRegion;
4491 if( pShmNode->h>=0 ){
4492 /* The requested region is not mapped into this processes address space.
4493 ** Check to see if it has been allocated (i.e. if the wal-index file is
4494 ** large enough to contain the requested region).
4496 if( osFstat(pShmNode->h, &sStat) ){
4497 rc = SQLITE_IOERR_SHMSIZE;
4498 goto shmpage_out;
4501 if( sStat.st_size<nByte ){
4502 /* The requested memory region does not exist. If bExtend is set to
4503 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
4505 if( !bExtend ){
4506 goto shmpage_out;
4509 /* Alternatively, if bExtend is true, extend the file. Do this by
4510 ** writing a single byte to the end of each (OS) page being
4511 ** allocated or extended. Technically, we need only write to the
4512 ** last page in order to extend the file. But writing to all new
4513 ** pages forces the OS to allocate them immediately, which reduces
4514 ** the chances of SIGBUS while accessing the mapped region later on.
4516 else{
4517 static const int pgsz = 4096;
4518 int iPg;
4520 /* Write to the last byte of each newly allocated or extended page */
4521 assert( (nByte % pgsz)==0 );
4522 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
4523 int x = 0;
4524 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
4525 const char *zFile = pShmNode->zFilename;
4526 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4527 goto shmpage_out;
4534 /* Map the requested memory region into this processes address space. */
4535 apNew = (char **)sqlite3_realloc(
4536 pShmNode->apRegion, nReqRegion*sizeof(char *)
4538 if( !apNew ){
4539 rc = SQLITE_IOERR_NOMEM_BKPT;
4540 goto shmpage_out;
4542 pShmNode->apRegion = apNew;
4543 while( pShmNode->nRegion<nReqRegion ){
4544 int nMap = szRegion*nShmPerMap;
4545 int i;
4546 void *pMem;
4547 if( pShmNode->h>=0 ){
4548 pMem = osMmap(0, nMap,
4549 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
4550 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
4552 if( pMem==MAP_FAILED ){
4553 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
4554 goto shmpage_out;
4556 }else{
4557 pMem = sqlite3_malloc64(szRegion);
4558 if( pMem==0 ){
4559 rc = SQLITE_NOMEM_BKPT;
4560 goto shmpage_out;
4562 memset(pMem, 0, szRegion);
4565 for(i=0; i<nShmPerMap; i++){
4566 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4568 pShmNode->nRegion += nShmPerMap;
4572 shmpage_out:
4573 if( pShmNode->nRegion>iRegion ){
4574 *pp = pShmNode->apRegion[iRegion];
4575 }else{
4576 *pp = 0;
4578 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
4579 sqlite3_mutex_leave(pShmNode->mutex);
4580 return rc;
4584 ** Change the lock state for a shared-memory segment.
4586 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4587 ** different here than in posix. In xShmLock(), one can go from unlocked
4588 ** to shared and back or from unlocked to exclusive and back. But one may
4589 ** not go from shared to exclusive or from exclusive to shared.
4591 static int unixShmLock(
4592 sqlite3_file *fd, /* Database file holding the shared memory */
4593 int ofst, /* First lock to acquire or release */
4594 int n, /* Number of locks to acquire or release */
4595 int flags /* What to do with the lock */
4597 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4598 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4599 unixShm *pX; /* For looping over all siblings */
4600 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4601 int rc = SQLITE_OK; /* Result code */
4602 u16 mask; /* Mask of locks to take or release */
4604 assert( pShmNode==pDbFd->pInode->pShmNode );
4605 assert( pShmNode->pInode==pDbFd->pInode );
4606 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
4607 assert( n>=1 );
4608 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4609 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4610 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4611 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4612 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
4613 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4614 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
4616 mask = (1<<(ofst+n)) - (1<<ofst);
4617 assert( n>1 || mask==(1<<ofst) );
4618 sqlite3_mutex_enter(pShmNode->mutex);
4619 if( flags & SQLITE_SHM_UNLOCK ){
4620 u16 allMask = 0; /* Mask of locks held by siblings */
4622 /* See if any siblings hold this same lock */
4623 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4624 if( pX==p ) continue;
4625 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4626 allMask |= pX->sharedMask;
4629 /* Unlock the system-level locks */
4630 if( (mask & allMask)==0 ){
4631 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
4632 }else{
4633 rc = SQLITE_OK;
4636 /* Undo the local locks */
4637 if( rc==SQLITE_OK ){
4638 p->exclMask &= ~mask;
4639 p->sharedMask &= ~mask;
4641 }else if( flags & SQLITE_SHM_SHARED ){
4642 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4644 /* Find out which shared locks are already held by sibling connections.
4645 ** If any sibling already holds an exclusive lock, go ahead and return
4646 ** SQLITE_BUSY.
4648 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4649 if( (pX->exclMask & mask)!=0 ){
4650 rc = SQLITE_BUSY;
4651 break;
4653 allShared |= pX->sharedMask;
4656 /* Get shared locks at the system level, if necessary */
4657 if( rc==SQLITE_OK ){
4658 if( (allShared & mask)==0 ){
4659 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
4660 }else{
4661 rc = SQLITE_OK;
4665 /* Get the local shared locks */
4666 if( rc==SQLITE_OK ){
4667 p->sharedMask |= mask;
4669 }else{
4670 /* Make sure no sibling connections hold locks that will block this
4671 ** lock. If any do, return SQLITE_BUSY right away.
4673 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4674 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4675 rc = SQLITE_BUSY;
4676 break;
4680 /* Get the exclusive locks at the system level. Then if successful
4681 ** also mark the local connection as being locked.
4683 if( rc==SQLITE_OK ){
4684 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
4685 if( rc==SQLITE_OK ){
4686 assert( (p->sharedMask & mask)==0 );
4687 p->exclMask |= mask;
4691 sqlite3_mutex_leave(pShmNode->mutex);
4692 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4693 p->id, osGetpid(0), p->sharedMask, p->exclMask));
4694 return rc;
4698 ** Implement a memory barrier or memory fence on shared memory.
4700 ** All loads and stores begun before the barrier must complete before
4701 ** any load or store begun after the barrier.
4703 static void unixShmBarrier(
4704 sqlite3_file *fd /* Database file holding the shared memory */
4706 UNUSED_PARAMETER(fd);
4707 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
4708 unixEnterMutex(); /* Also mutex, for redundancy */
4709 unixLeaveMutex();
4713 ** Close a connection to shared-memory. Delete the underlying
4714 ** storage if deleteFlag is true.
4716 ** If there is no shared memory associated with the connection then this
4717 ** routine is a harmless no-op.
4719 static int unixShmUnmap(
4720 sqlite3_file *fd, /* The underlying database file */
4721 int deleteFlag /* Delete shared-memory if true */
4723 unixShm *p; /* The connection to be closed */
4724 unixShmNode *pShmNode; /* The underlying shared-memory file */
4725 unixShm **pp; /* For looping over sibling connections */
4726 unixFile *pDbFd; /* The underlying database file */
4728 pDbFd = (unixFile*)fd;
4729 p = pDbFd->pShm;
4730 if( p==0 ) return SQLITE_OK;
4731 pShmNode = p->pShmNode;
4733 assert( pShmNode==pDbFd->pInode->pShmNode );
4734 assert( pShmNode->pInode==pDbFd->pInode );
4736 /* Remove connection p from the set of connections associated
4737 ** with pShmNode */
4738 sqlite3_mutex_enter(pShmNode->mutex);
4739 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4740 *pp = p->pNext;
4742 /* Free the connection p */
4743 sqlite3_free(p);
4744 pDbFd->pShm = 0;
4745 sqlite3_mutex_leave(pShmNode->mutex);
4747 /* If pShmNode->nRef has reached 0, then close the underlying
4748 ** shared-memory file, too */
4749 unixEnterMutex();
4750 assert( pShmNode->nRef>0 );
4751 pShmNode->nRef--;
4752 if( pShmNode->nRef==0 ){
4753 if( deleteFlag && pShmNode->h>=0 ){
4754 osUnlink(pShmNode->zFilename);
4756 unixShmPurge(pDbFd);
4758 unixLeaveMutex();
4760 return SQLITE_OK;
4764 #else
4765 # define unixShmMap 0
4766 # define unixShmLock 0
4767 # define unixShmBarrier 0
4768 # define unixShmUnmap 0
4769 #endif /* #ifndef SQLITE_OMIT_WAL */
4771 #if SQLITE_MAX_MMAP_SIZE>0
4773 ** If it is currently memory mapped, unmap file pFd.
4775 static void unixUnmapfile(unixFile *pFd){
4776 assert( pFd->nFetchOut==0 );
4777 if( pFd->pMapRegion ){
4778 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
4779 pFd->pMapRegion = 0;
4780 pFd->mmapSize = 0;
4781 pFd->mmapSizeActual = 0;
4786 ** Attempt to set the size of the memory mapping maintained by file
4787 ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4789 ** If successful, this function sets the following variables:
4791 ** unixFile.pMapRegion
4792 ** unixFile.mmapSize
4793 ** unixFile.mmapSizeActual
4795 ** If unsuccessful, an error message is logged via sqlite3_log() and
4796 ** the three variables above are zeroed. In this case SQLite should
4797 ** continue accessing the database using the xRead() and xWrite()
4798 ** methods.
4800 static void unixRemapfile(
4801 unixFile *pFd, /* File descriptor object */
4802 i64 nNew /* Required mapping size */
4804 const char *zErr = "mmap";
4805 int h = pFd->h; /* File descriptor open on db file */
4806 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
4807 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
4808 u8 *pNew = 0; /* Location of new mapping */
4809 int flags = PROT_READ; /* Flags to pass to mmap() */
4811 assert( pFd->nFetchOut==0 );
4812 assert( nNew>pFd->mmapSize );
4813 assert( nNew<=pFd->mmapSizeMax );
4814 assert( nNew>0 );
4815 assert( pFd->mmapSizeActual>=pFd->mmapSize );
4816 assert( MAP_FAILED!=0 );
4818 #ifdef SQLITE_MMAP_READWRITE
4819 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
4820 #endif
4822 if( pOrig ){
4823 #if HAVE_MREMAP
4824 i64 nReuse = pFd->mmapSize;
4825 #else
4826 const int szSyspage = osGetpagesize();
4827 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
4828 #endif
4829 u8 *pReq = &pOrig[nReuse];
4831 /* Unmap any pages of the existing mapping that cannot be reused. */
4832 if( nReuse!=nOrig ){
4833 osMunmap(pReq, nOrig-nReuse);
4836 #if HAVE_MREMAP
4837 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
4838 zErr = "mremap";
4839 #else
4840 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4841 if( pNew!=MAP_FAILED ){
4842 if( pNew!=pReq ){
4843 osMunmap(pNew, nNew - nReuse);
4844 pNew = 0;
4845 }else{
4846 pNew = pOrig;
4849 #endif
4851 /* The attempt to extend the existing mapping failed. Free it. */
4852 if( pNew==MAP_FAILED || pNew==0 ){
4853 osMunmap(pOrig, nReuse);
4857 /* If pNew is still NULL, try to create an entirely new mapping. */
4858 if( pNew==0 ){
4859 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
4862 if( pNew==MAP_FAILED ){
4863 pNew = 0;
4864 nNew = 0;
4865 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4867 /* If the mmap() above failed, assume that all subsequent mmap() calls
4868 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4869 ** in this case. */
4870 pFd->mmapSizeMax = 0;
4872 pFd->pMapRegion = (void *)pNew;
4873 pFd->mmapSize = pFd->mmapSizeActual = nNew;
4877 ** Memory map or remap the file opened by file-descriptor pFd (if the file
4878 ** is already mapped, the existing mapping is replaced by the new). Or, if
4879 ** there already exists a mapping for this file, and there are still
4880 ** outstanding xFetch() references to it, this function is a no-op.
4882 ** If parameter nByte is non-negative, then it is the requested size of
4883 ** the mapping to create. Otherwise, if nByte is less than zero, then the
4884 ** requested size is the size of the file on disk. The actual size of the
4885 ** created mapping is either the requested size or the value configured
4886 ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
4888 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
4889 ** recreated as a result of outstanding references) or an SQLite error
4890 ** code otherwise.
4892 static int unixMapfile(unixFile *pFd, i64 nMap){
4893 assert( nMap>=0 || pFd->nFetchOut==0 );
4894 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
4895 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4897 if( nMap<0 ){
4898 struct stat statbuf; /* Low-level file information */
4899 if( osFstat(pFd->h, &statbuf) ){
4900 return SQLITE_IOERR_FSTAT;
4902 nMap = statbuf.st_size;
4904 if( nMap>pFd->mmapSizeMax ){
4905 nMap = pFd->mmapSizeMax;
4908 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
4909 if( nMap!=pFd->mmapSize ){
4910 unixRemapfile(pFd, nMap);
4913 return SQLITE_OK;
4915 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
4918 ** If possible, return a pointer to a mapping of file fd starting at offset
4919 ** iOff. The mapping must be valid for at least nAmt bytes.
4921 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4922 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4923 ** Finally, if an error does occur, return an SQLite error code. The final
4924 ** value of *pp is undefined in this case.
4926 ** If this function does return a pointer, the caller must eventually
4927 ** release the reference by calling unixUnfetch().
4929 static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
4930 #if SQLITE_MAX_MMAP_SIZE>0
4931 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
4932 #endif
4933 *pp = 0;
4935 #if SQLITE_MAX_MMAP_SIZE>0
4936 if( pFd->mmapSizeMax>0 ){
4937 if( pFd->pMapRegion==0 ){
4938 int rc = unixMapfile(pFd, -1);
4939 if( rc!=SQLITE_OK ) return rc;
4941 if( pFd->mmapSize >= iOff+nAmt ){
4942 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4943 pFd->nFetchOut++;
4946 #endif
4947 return SQLITE_OK;
4951 ** If the third argument is non-NULL, then this function releases a
4952 ** reference obtained by an earlier call to unixFetch(). The second
4953 ** argument passed to this function must be the same as the corresponding
4954 ** argument that was passed to the unixFetch() invocation.
4956 ** Or, if the third argument is NULL, then this function is being called
4957 ** to inform the VFS layer that, according to POSIX, any existing mapping
4958 ** may now be invalid and should be unmapped.
4960 static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
4961 #if SQLITE_MAX_MMAP_SIZE>0
4962 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
4963 UNUSED_PARAMETER(iOff);
4965 /* If p==0 (unmap the entire file) then there must be no outstanding
4966 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4967 ** then there must be at least one outstanding. */
4968 assert( (p==0)==(pFd->nFetchOut==0) );
4970 /* If p!=0, it must match the iOff value. */
4971 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4973 if( p ){
4974 pFd->nFetchOut--;
4975 }else{
4976 unixUnmapfile(pFd);
4979 assert( pFd->nFetchOut>=0 );
4980 #else
4981 UNUSED_PARAMETER(fd);
4982 UNUSED_PARAMETER(p);
4983 UNUSED_PARAMETER(iOff);
4984 #endif
4985 return SQLITE_OK;
4989 ** Here ends the implementation of all sqlite3_file methods.
4991 ********************** End sqlite3_file Methods *******************************
4992 ******************************************************************************/
4995 ** This division contains definitions of sqlite3_io_methods objects that
4996 ** implement various file locking strategies. It also contains definitions
4997 ** of "finder" functions. A finder-function is used to locate the appropriate
4998 ** sqlite3_io_methods object for a particular database file. The pAppData
4999 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
5000 ** the correct finder-function for that VFS.
5002 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
5003 ** object. The only interesting finder-function is autolockIoFinder, which
5004 ** looks at the filesystem type and tries to guess the best locking
5005 ** strategy from that.
5007 ** For finder-function F, two objects are created:
5009 ** (1) The real finder-function named "FImpt()".
5011 ** (2) A constant pointer to this function named just "F".
5014 ** A pointer to the F pointer is used as the pAppData value for VFS
5015 ** objects. We have to do this instead of letting pAppData point
5016 ** directly at the finder-function since C90 rules prevent a void*
5017 ** from be cast into a function pointer.
5020 ** Each instance of this macro generates two objects:
5022 ** * A constant sqlite3_io_methods object call METHOD that has locking
5023 ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
5025 ** * An I/O method finder function called FINDER that returns a pointer
5026 ** to the METHOD object in the previous bullet.
5028 #define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
5029 static const sqlite3_io_methods METHOD = { \
5030 VERSION, /* iVersion */ \
5031 CLOSE, /* xClose */ \
5032 unixRead, /* xRead */ \
5033 unixWrite, /* xWrite */ \
5034 unixTruncate, /* xTruncate */ \
5035 unixSync, /* xSync */ \
5036 unixFileSize, /* xFileSize */ \
5037 LOCK, /* xLock */ \
5038 UNLOCK, /* xUnlock */ \
5039 CKLOCK, /* xCheckReservedLock */ \
5040 unixFileControl, /* xFileControl */ \
5041 unixSectorSize, /* xSectorSize */ \
5042 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
5043 SHMMAP, /* xShmMap */ \
5044 unixShmLock, /* xShmLock */ \
5045 unixShmBarrier, /* xShmBarrier */ \
5046 unixShmUnmap, /* xShmUnmap */ \
5047 unixFetch, /* xFetch */ \
5048 unixUnfetch, /* xUnfetch */ \
5049 }; \
5050 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
5051 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
5052 return &METHOD; \
5054 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
5055 = FINDER##Impl;
5058 ** Here are all of the sqlite3_io_methods objects for each of the
5059 ** locking strategies. Functions that return pointers to these methods
5060 ** are also created.
5062 IOMETHODS(
5063 posixIoFinder, /* Finder function name */
5064 posixIoMethods, /* sqlite3_io_methods object name */
5065 3, /* shared memory and mmap are enabled */
5066 unixClose, /* xClose method */
5067 unixLock, /* xLock method */
5068 unixUnlock, /* xUnlock method */
5069 unixCheckReservedLock, /* xCheckReservedLock method */
5070 unixShmMap /* xShmMap method */
5072 IOMETHODS(
5073 nolockIoFinder, /* Finder function name */
5074 nolockIoMethods, /* sqlite3_io_methods object name */
5075 3, /* shared memory is disabled */
5076 nolockClose, /* xClose method */
5077 nolockLock, /* xLock method */
5078 nolockUnlock, /* xUnlock method */
5079 nolockCheckReservedLock, /* xCheckReservedLock method */
5080 0 /* xShmMap method */
5082 IOMETHODS(
5083 dotlockIoFinder, /* Finder function name */
5084 dotlockIoMethods, /* sqlite3_io_methods object name */
5085 1, /* shared memory is disabled */
5086 dotlockClose, /* xClose method */
5087 dotlockLock, /* xLock method */
5088 dotlockUnlock, /* xUnlock method */
5089 dotlockCheckReservedLock, /* xCheckReservedLock method */
5090 0 /* xShmMap method */
5093 #if SQLITE_ENABLE_LOCKING_STYLE
5094 IOMETHODS(
5095 flockIoFinder, /* Finder function name */
5096 flockIoMethods, /* sqlite3_io_methods object name */
5097 1, /* shared memory is disabled */
5098 flockClose, /* xClose method */
5099 flockLock, /* xLock method */
5100 flockUnlock, /* xUnlock method */
5101 flockCheckReservedLock, /* xCheckReservedLock method */
5102 0 /* xShmMap method */
5104 #endif
5106 #if OS_VXWORKS
5107 IOMETHODS(
5108 semIoFinder, /* Finder function name */
5109 semIoMethods, /* sqlite3_io_methods object name */
5110 1, /* shared memory is disabled */
5111 semXClose, /* xClose method */
5112 semXLock, /* xLock method */
5113 semXUnlock, /* xUnlock method */
5114 semXCheckReservedLock, /* xCheckReservedLock method */
5115 0 /* xShmMap method */
5117 #endif
5119 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5120 IOMETHODS(
5121 afpIoFinder, /* Finder function name */
5122 afpIoMethods, /* sqlite3_io_methods object name */
5123 1, /* shared memory is disabled */
5124 afpClose, /* xClose method */
5125 afpLock, /* xLock method */
5126 afpUnlock, /* xUnlock method */
5127 afpCheckReservedLock, /* xCheckReservedLock method */
5128 0 /* xShmMap method */
5130 #endif
5133 ** The proxy locking method is a "super-method" in the sense that it
5134 ** opens secondary file descriptors for the conch and lock files and
5135 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
5136 ** secondary files. For this reason, the division that implements
5137 ** proxy locking is located much further down in the file. But we need
5138 ** to go ahead and define the sqlite3_io_methods and finder function
5139 ** for proxy locking here. So we forward declare the I/O methods.
5141 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5142 static int proxyClose(sqlite3_file*);
5143 static int proxyLock(sqlite3_file*, int);
5144 static int proxyUnlock(sqlite3_file*, int);
5145 static int proxyCheckReservedLock(sqlite3_file*, int*);
5146 IOMETHODS(
5147 proxyIoFinder, /* Finder function name */
5148 proxyIoMethods, /* sqlite3_io_methods object name */
5149 1, /* shared memory is disabled */
5150 proxyClose, /* xClose method */
5151 proxyLock, /* xLock method */
5152 proxyUnlock, /* xUnlock method */
5153 proxyCheckReservedLock, /* xCheckReservedLock method */
5154 0 /* xShmMap method */
5156 #endif
5158 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5159 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5160 IOMETHODS(
5161 nfsIoFinder, /* Finder function name */
5162 nfsIoMethods, /* sqlite3_io_methods object name */
5163 1, /* shared memory is disabled */
5164 unixClose, /* xClose method */
5165 unixLock, /* xLock method */
5166 nfsUnlock, /* xUnlock method */
5167 unixCheckReservedLock, /* xCheckReservedLock method */
5168 0 /* xShmMap method */
5170 #endif
5172 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5174 ** This "finder" function attempts to determine the best locking strategy
5175 ** for the database file "filePath". It then returns the sqlite3_io_methods
5176 ** object that implements that strategy.
5178 ** This is for MacOSX only.
5180 static const sqlite3_io_methods *autolockIoFinderImpl(
5181 const char *filePath, /* name of the database file */
5182 unixFile *pNew /* open file object for the database file */
5184 static const struct Mapping {
5185 const char *zFilesystem; /* Filesystem type name */
5186 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
5187 } aMap[] = {
5188 { "hfs", &posixIoMethods },
5189 { "ufs", &posixIoMethods },
5190 { "afpfs", &afpIoMethods },
5191 { "smbfs", &afpIoMethods },
5192 { "webdav", &nolockIoMethods },
5193 { 0, 0 }
5195 int i;
5196 struct statfs fsInfo;
5197 struct flock lockInfo;
5199 if( !filePath ){
5200 /* If filePath==NULL that means we are dealing with a transient file
5201 ** that does not need to be locked. */
5202 return &nolockIoMethods;
5204 if( statfs(filePath, &fsInfo) != -1 ){
5205 if( fsInfo.f_flags & MNT_RDONLY ){
5206 return &nolockIoMethods;
5208 for(i=0; aMap[i].zFilesystem; i++){
5209 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5210 return aMap[i].pMethods;
5215 /* Default case. Handles, amongst others, "nfs".
5216 ** Test byte-range lock using fcntl(). If the call succeeds,
5217 ** assume that the file-system supports POSIX style locks.
5219 lockInfo.l_len = 1;
5220 lockInfo.l_start = 0;
5221 lockInfo.l_whence = SEEK_SET;
5222 lockInfo.l_type = F_RDLCK;
5223 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
5224 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5225 return &nfsIoMethods;
5226 } else {
5227 return &posixIoMethods;
5229 }else{
5230 return &dotlockIoMethods;
5233 static const sqlite3_io_methods
5234 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
5236 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
5238 #if OS_VXWORKS
5240 ** This "finder" function for VxWorks checks to see if posix advisory
5241 ** locking works. If it does, then that is what is used. If it does not
5242 ** work, then fallback to named semaphore locking.
5244 static const sqlite3_io_methods *vxworksIoFinderImpl(
5245 const char *filePath, /* name of the database file */
5246 unixFile *pNew /* the open file object */
5248 struct flock lockInfo;
5250 if( !filePath ){
5251 /* If filePath==NULL that means we are dealing with a transient file
5252 ** that does not need to be locked. */
5253 return &nolockIoMethods;
5256 /* Test if fcntl() is supported and use POSIX style locks.
5257 ** Otherwise fall back to the named semaphore method.
5259 lockInfo.l_len = 1;
5260 lockInfo.l_start = 0;
5261 lockInfo.l_whence = SEEK_SET;
5262 lockInfo.l_type = F_RDLCK;
5263 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
5264 return &posixIoMethods;
5265 }else{
5266 return &semIoMethods;
5269 static const sqlite3_io_methods
5270 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
5272 #endif /* OS_VXWORKS */
5275 ** An abstract type for a pointer to an IO method finder function:
5277 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
5280 /****************************************************************************
5281 **************************** sqlite3_vfs methods ****************************
5283 ** This division contains the implementation of methods on the
5284 ** sqlite3_vfs object.
5288 ** Initialize the contents of the unixFile structure pointed to by pId.
5290 static int fillInUnixFile(
5291 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5292 int h, /* Open file descriptor of file being opened */
5293 sqlite3_file *pId, /* Write to the unixFile structure here */
5294 const char *zFilename, /* Name of the file being opened */
5295 int ctrlFlags /* Zero or more UNIXFILE_* values */
5297 const sqlite3_io_methods *pLockingStyle;
5298 unixFile *pNew = (unixFile *)pId;
5299 int rc = SQLITE_OK;
5301 assert( pNew->pInode==NULL );
5303 /* No locking occurs in temporary files */
5304 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
5306 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
5307 pNew->h = h;
5308 pNew->pVfs = pVfs;
5309 pNew->zPath = zFilename;
5310 pNew->ctrlFlags = (u8)ctrlFlags;
5311 #if SQLITE_MAX_MMAP_SIZE>0
5312 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
5313 #endif
5314 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5315 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
5316 pNew->ctrlFlags |= UNIXFILE_PSOW;
5318 if( strcmp(pVfs->zName,"unix-excl")==0 ){
5319 pNew->ctrlFlags |= UNIXFILE_EXCL;
5322 #if OS_VXWORKS
5323 pNew->pId = vxworksFindFileId(zFilename);
5324 if( pNew->pId==0 ){
5325 ctrlFlags |= UNIXFILE_NOLOCK;
5326 rc = SQLITE_NOMEM_BKPT;
5328 #endif
5330 if( ctrlFlags & UNIXFILE_NOLOCK ){
5331 pLockingStyle = &nolockIoMethods;
5332 }else{
5333 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
5334 #if SQLITE_ENABLE_LOCKING_STYLE
5335 /* Cache zFilename in the locking context (AFP and dotlock override) for
5336 ** proxyLock activation is possible (remote proxy is based on db name)
5337 ** zFilename remains valid until file is closed, to support */
5338 pNew->lockingContext = (void*)zFilename;
5339 #endif
5342 if( pLockingStyle == &posixIoMethods
5343 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5344 || pLockingStyle == &nfsIoMethods
5345 #endif
5347 unixEnterMutex();
5348 rc = findInodeInfo(pNew, &pNew->pInode);
5349 if( rc!=SQLITE_OK ){
5350 /* If an error occurred in findInodeInfo(), close the file descriptor
5351 ** immediately, before releasing the mutex. findInodeInfo() may fail
5352 ** in two scenarios:
5354 ** (a) A call to fstat() failed.
5355 ** (b) A malloc failed.
5357 ** Scenario (b) may only occur if the process is holding no other
5358 ** file descriptors open on the same file. If there were other file
5359 ** descriptors on this file, then no malloc would be required by
5360 ** findInodeInfo(). If this is the case, it is quite safe to close
5361 ** handle h - as it is guaranteed that no posix locks will be released
5362 ** by doing so.
5364 ** If scenario (a) caused the error then things are not so safe. The
5365 ** implicit assumption here is that if fstat() fails, things are in
5366 ** such bad shape that dropping a lock or two doesn't matter much.
5368 robust_close(pNew, h, __LINE__);
5369 h = -1;
5371 unixLeaveMutex();
5374 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
5375 else if( pLockingStyle == &afpIoMethods ){
5376 /* AFP locking uses the file path so it needs to be included in
5377 ** the afpLockingContext.
5379 afpLockingContext *pCtx;
5380 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
5381 if( pCtx==0 ){
5382 rc = SQLITE_NOMEM_BKPT;
5383 }else{
5384 /* NB: zFilename exists and remains valid until the file is closed
5385 ** according to requirement F11141. So we do not need to make a
5386 ** copy of the filename. */
5387 pCtx->dbPath = zFilename;
5388 pCtx->reserved = 0;
5389 srandomdev();
5390 unixEnterMutex();
5391 rc = findInodeInfo(pNew, &pNew->pInode);
5392 if( rc!=SQLITE_OK ){
5393 sqlite3_free(pNew->lockingContext);
5394 robust_close(pNew, h, __LINE__);
5395 h = -1;
5397 unixLeaveMutex();
5400 #endif
5402 else if( pLockingStyle == &dotlockIoMethods ){
5403 /* Dotfile locking uses the file path so it needs to be included in
5404 ** the dotlockLockingContext
5406 char *zLockFile;
5407 int nFilename;
5408 assert( zFilename!=0 );
5409 nFilename = (int)strlen(zFilename) + 6;
5410 zLockFile = (char *)sqlite3_malloc64(nFilename);
5411 if( zLockFile==0 ){
5412 rc = SQLITE_NOMEM_BKPT;
5413 }else{
5414 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
5416 pNew->lockingContext = zLockFile;
5419 #if OS_VXWORKS
5420 else if( pLockingStyle == &semIoMethods ){
5421 /* Named semaphore locking uses the file path so it needs to be
5422 ** included in the semLockingContext
5424 unixEnterMutex();
5425 rc = findInodeInfo(pNew, &pNew->pInode);
5426 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5427 char *zSemName = pNew->pInode->aSemName;
5428 int n;
5429 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
5430 pNew->pId->zCanonicalName);
5431 for( n=1; zSemName[n]; n++ )
5432 if( zSemName[n]=='/' ) zSemName[n] = '_';
5433 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5434 if( pNew->pInode->pSem == SEM_FAILED ){
5435 rc = SQLITE_NOMEM_BKPT;
5436 pNew->pInode->aSemName[0] = '\0';
5439 unixLeaveMutex();
5441 #endif
5443 storeLastErrno(pNew, 0);
5444 #if OS_VXWORKS
5445 if( rc!=SQLITE_OK ){
5446 if( h>=0 ) robust_close(pNew, h, __LINE__);
5447 h = -1;
5448 osUnlink(zFilename);
5449 pNew->ctrlFlags |= UNIXFILE_DELETE;
5451 #endif
5452 if( rc!=SQLITE_OK ){
5453 if( h>=0 ) robust_close(pNew, h, __LINE__);
5454 }else{
5455 pNew->pMethod = pLockingStyle;
5456 OpenCounter(+1);
5457 verifyDbFile(pNew);
5459 return rc;
5463 ** Return the name of a directory in which to put temporary files.
5464 ** If no suitable temporary file directory can be found, return NULL.
5466 static const char *unixTempFileDir(void){
5467 static const char *azDirs[] = {
5470 "/var/tmp",
5471 "/usr/tmp",
5472 "/tmp",
5475 unsigned int i = 0;
5476 struct stat buf;
5477 const char *zDir = sqlite3_temp_directory;
5479 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
5480 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
5481 while(1){
5482 if( zDir!=0
5483 && osStat(zDir, &buf)==0
5484 && S_ISDIR(buf.st_mode)
5485 && osAccess(zDir, 03)==0
5487 return zDir;
5489 if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
5490 zDir = azDirs[i++];
5492 return 0;
5496 ** Create a temporary file name in zBuf. zBuf must be allocated
5497 ** by the calling process and must be big enough to hold at least
5498 ** pVfs->mxPathname bytes.
5500 static int unixGetTempname(int nBuf, char *zBuf){
5501 const char *zDir;
5502 int iLimit = 0;
5504 /* It's odd to simulate an io-error here, but really this is just
5505 ** using the io-error infrastructure to test that SQLite handles this
5506 ** function failing.
5508 zBuf[0] = 0;
5509 SimulateIOError( return SQLITE_IOERR );
5511 zDir = unixTempFileDir();
5512 if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
5514 u64 r;
5515 sqlite3_randomness(sizeof(r), &r);
5516 assert( nBuf>2 );
5517 zBuf[nBuf-2] = 0;
5518 sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
5519 zDir, r, 0);
5520 if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
5521 }while( osAccess(zBuf,0)==0 );
5522 return SQLITE_OK;
5525 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
5527 ** Routine to transform a unixFile into a proxy-locking unixFile.
5528 ** Implementation in the proxy-lock division, but used by unixOpen()
5529 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
5531 static int proxyTransformUnixFile(unixFile*, const char*);
5532 #endif
5535 ** Search for an unused file descriptor that was opened on the database
5536 ** file (not a journal or master-journal file) identified by pathname
5537 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5538 ** argument to this function.
5540 ** Such a file descriptor may exist if a database connection was closed
5541 ** but the associated file descriptor could not be closed because some
5542 ** other file descriptor open on the same file is holding a file-lock.
5543 ** Refer to comments in the unixClose() function and the lengthy comment
5544 ** describing "Posix Advisory Locking" at the start of this file for
5545 ** further details. Also, ticket #4018.
5547 ** If a suitable file descriptor is found, then it is returned. If no
5548 ** such file descriptor is located, -1 is returned.
5550 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5551 UnixUnusedFd *pUnused = 0;
5553 /* Do not search for an unused file descriptor on vxworks. Not because
5554 ** vxworks would not benefit from the change (it might, we're not sure),
5555 ** but because no way to test it is currently available. It is better
5556 ** not to risk breaking vxworks support for the sake of such an obscure
5557 ** feature. */
5558 #if !OS_VXWORKS
5559 struct stat sStat; /* Results of stat() call */
5561 unixEnterMutex();
5563 /* A stat() call may fail for various reasons. If this happens, it is
5564 ** almost certain that an open() call on the same path will also fail.
5565 ** For this reason, if an error occurs in the stat() call here, it is
5566 ** ignored and -1 is returned. The caller will try to open a new file
5567 ** descriptor on the same path, fail, and return an error to SQLite.
5569 ** Even if a subsequent open() call does succeed, the consequences of
5570 ** not searching for a reusable file descriptor are not dire. */
5571 if( nUnusedFd>0 && 0==osStat(zPath, &sStat) ){
5572 unixInodeInfo *pInode;
5574 pInode = inodeList;
5575 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5576 || pInode->fileId.ino!=(u64)sStat.st_ino) ){
5577 pInode = pInode->pNext;
5579 if( pInode ){
5580 UnixUnusedFd **pp;
5581 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
5582 pUnused = *pp;
5583 if( pUnused ){
5584 nUnusedFd--;
5585 *pp = pUnused->pNext;
5589 unixLeaveMutex();
5590 #endif /* if !OS_VXWORKS */
5591 return pUnused;
5595 ** Find the mode, uid and gid of file zFile.
5597 static int getFileMode(
5598 const char *zFile, /* File name */
5599 mode_t *pMode, /* OUT: Permissions of zFile */
5600 uid_t *pUid, /* OUT: uid of zFile. */
5601 gid_t *pGid /* OUT: gid of zFile. */
5603 struct stat sStat; /* Output of stat() on database file */
5604 int rc = SQLITE_OK;
5605 if( 0==osStat(zFile, &sStat) ){
5606 *pMode = sStat.st_mode & 0777;
5607 *pUid = sStat.st_uid;
5608 *pGid = sStat.st_gid;
5609 }else{
5610 rc = SQLITE_IOERR_FSTAT;
5612 return rc;
5616 ** This function is called by unixOpen() to determine the unix permissions
5617 ** to create new files with. If no error occurs, then SQLITE_OK is returned
5618 ** and a value suitable for passing as the third argument to open(2) is
5619 ** written to *pMode. If an IO error occurs, an SQLite error code is
5620 ** returned and the value of *pMode is not modified.
5622 ** In most cases, this routine sets *pMode to 0, which will become
5623 ** an indication to robust_open() to create the file using
5624 ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5625 ** But if the file being opened is a WAL or regular journal file, then
5626 ** this function queries the file-system for the permissions on the
5627 ** corresponding database file and sets *pMode to this value. Whenever
5628 ** possible, WAL and journal files are created using the same permissions
5629 ** as the associated database file.
5631 ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5632 ** original filename is unavailable. But 8_3_NAMES is only used for
5633 ** FAT filesystems and permissions do not matter there, so just use
5634 ** the default permissions.
5636 static int findCreateFileMode(
5637 const char *zPath, /* Path of file (possibly) being created */
5638 int flags, /* Flags passed as 4th argument to xOpen() */
5639 mode_t *pMode, /* OUT: Permissions to open file with */
5640 uid_t *pUid, /* OUT: uid to set on the file */
5641 gid_t *pGid /* OUT: gid to set on the file */
5643 int rc = SQLITE_OK; /* Return Code */
5644 *pMode = 0;
5645 *pUid = 0;
5646 *pGid = 0;
5647 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
5648 char zDb[MAX_PATHNAME+1]; /* Database file path */
5649 int nDb; /* Number of valid bytes in zDb */
5651 /* zPath is a path to a WAL or journal file. The following block derives
5652 ** the path to the associated database file from zPath. This block handles
5653 ** the following naming conventions:
5655 ** "<path to db>-journal"
5656 ** "<path to db>-wal"
5657 ** "<path to db>-journalNN"
5658 ** "<path to db>-walNN"
5660 ** where NN is a decimal number. The NN naming schemes are
5661 ** used by the test_multiplex.c module.
5663 nDb = sqlite3Strlen30(zPath) - 1;
5664 while( zPath[nDb]!='-' ){
5665 /* In normal operation, the journal file name will always contain
5666 ** a '-' character. However in 8+3 filename mode, or if a corrupt
5667 ** rollback journal specifies a master journal with a goofy name, then
5668 ** the '-' might be missing. */
5669 if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
5670 nDb--;
5672 memcpy(zDb, zPath, nDb);
5673 zDb[nDb] = '\0';
5675 rc = getFileMode(zDb, pMode, pUid, pGid);
5676 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5677 *pMode = 0600;
5678 }else if( flags & SQLITE_OPEN_URI ){
5679 /* If this is a main database file and the file was opened using a URI
5680 ** filename, check for the "modeof" parameter. If present, interpret
5681 ** its value as a filename and try to copy the mode, uid and gid from
5682 ** that file. */
5683 const char *z = sqlite3_uri_parameter(zPath, "modeof");
5684 if( z ){
5685 rc = getFileMode(z, pMode, pUid, pGid);
5688 return rc;
5692 ** Open the file zPath.
5694 ** Previously, the SQLite OS layer used three functions in place of this
5695 ** one:
5697 ** sqlite3OsOpenReadWrite();
5698 ** sqlite3OsOpenReadOnly();
5699 ** sqlite3OsOpenExclusive();
5701 ** These calls correspond to the following combinations of flags:
5703 ** ReadWrite() -> (READWRITE | CREATE)
5704 ** ReadOnly() -> (READONLY)
5705 ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5707 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5708 ** true, the file was configured to be automatically deleted when the
5709 ** file handle closed. To achieve the same effect using this new
5710 ** interface, add the DELETEONCLOSE flag to those specified above for
5711 ** OpenExclusive().
5713 static int unixOpen(
5714 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5715 const char *zPath, /* Pathname of file to be opened */
5716 sqlite3_file *pFile, /* The file descriptor to be filled in */
5717 int flags, /* Input flags to control the opening */
5718 int *pOutFlags /* Output flags returned to SQLite core */
5720 unixFile *p = (unixFile *)pFile;
5721 int fd = -1; /* File descriptor returned by open() */
5722 int openFlags = 0; /* Flags to pass to open() */
5723 int eType = flags&0xFFFFFF00; /* Type of file to open */
5724 int noLock; /* True to omit locking primitives */
5725 int rc = SQLITE_OK; /* Function Return Code */
5726 int ctrlFlags = 0; /* UNIXFILE_* flags */
5728 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5729 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5730 int isCreate = (flags & SQLITE_OPEN_CREATE);
5731 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5732 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
5733 #if SQLITE_ENABLE_LOCKING_STYLE
5734 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5735 #endif
5736 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5737 struct statfs fsInfo;
5738 #endif
5740 /* If creating a master or main-file journal, this function will open
5741 ** a file-descriptor on the directory too. The first time unixSync()
5742 ** is called the directory file descriptor will be fsync()ed and close()d.
5744 int syncDir = (isCreate && (
5745 eType==SQLITE_OPEN_MASTER_JOURNAL
5746 || eType==SQLITE_OPEN_MAIN_JOURNAL
5747 || eType==SQLITE_OPEN_WAL
5750 /* If argument zPath is a NULL pointer, this function is required to open
5751 ** a temporary file. Use this buffer to store the file name in.
5753 char zTmpname[MAX_PATHNAME+2];
5754 const char *zName = zPath;
5756 /* Check the following statements are true:
5758 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5759 ** (b) if CREATE is set, then READWRITE must also be set, and
5760 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
5761 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
5763 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
5764 assert(isCreate==0 || isReadWrite);
5765 assert(isExclusive==0 || isCreate);
5766 assert(isDelete==0 || isCreate);
5768 /* The main DB, main journal, WAL file and master journal are never
5769 ** automatically deleted. Nor are they ever temporary files. */
5770 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5771 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5772 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
5773 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
5775 /* Assert that the upper layer has set one of the "file-type" flags. */
5776 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5777 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5778 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
5779 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
5782 /* Detect a pid change and reset the PRNG. There is a race condition
5783 ** here such that two or more threads all trying to open databases at
5784 ** the same instant might all reset the PRNG. But multiple resets
5785 ** are harmless.
5787 if( randomnessPid!=osGetpid(0) ){
5788 randomnessPid = osGetpid(0);
5789 sqlite3_randomness(0,0);
5792 memset(p, 0, sizeof(unixFile));
5794 if( eType==SQLITE_OPEN_MAIN_DB ){
5795 UnixUnusedFd *pUnused;
5796 pUnused = findReusableFd(zName, flags);
5797 if( pUnused ){
5798 fd = pUnused->fd;
5799 }else{
5800 pUnused = sqlite3_malloc64(sizeof(*pUnused));
5801 if( !pUnused ){
5802 return SQLITE_NOMEM_BKPT;
5805 p->pPreallocatedUnused = pUnused;
5807 /* Database filenames are double-zero terminated if they are not
5808 ** URIs with parameters. Hence, they can always be passed into
5809 ** sqlite3_uri_parameter(). */
5810 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5812 }else if( !zName ){
5813 /* If zName is NULL, the upper layer is requesting a temp file. */
5814 assert(isDelete && !syncDir);
5815 rc = unixGetTempname(pVfs->mxPathname, zTmpname);
5816 if( rc!=SQLITE_OK ){
5817 return rc;
5819 zName = zTmpname;
5821 /* Generated temporary filenames are always double-zero terminated
5822 ** for use by sqlite3_uri_parameter(). */
5823 assert( zName[strlen(zName)+1]==0 );
5826 /* Determine the value of the flags parameter passed to POSIX function
5827 ** open(). These must be calculated even if open() is not called, as
5828 ** they may be stored as part of the file handle and used by the
5829 ** 'conch file' locking functions later on. */
5830 if( isReadonly ) openFlags |= O_RDONLY;
5831 if( isReadWrite ) openFlags |= O_RDWR;
5832 if( isCreate ) openFlags |= O_CREAT;
5833 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5834 openFlags |= (O_LARGEFILE|O_BINARY);
5836 if( fd<0 ){
5837 mode_t openMode; /* Permissions to create file with */
5838 uid_t uid; /* Userid for the file */
5839 gid_t gid; /* Groupid for the file */
5840 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
5841 if( rc!=SQLITE_OK ){
5842 assert( !p->pPreallocatedUnused );
5843 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
5844 return rc;
5846 fd = robust_open(zName, openFlags, openMode);
5847 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
5848 assert( !isExclusive || (openFlags & O_CREAT)!=0 );
5849 if( fd<0 && errno!=EISDIR && isReadWrite ){
5850 /* Failed to open the file for read/write access. Try read-only. */
5851 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
5852 openFlags &= ~(O_RDWR|O_CREAT);
5853 flags |= SQLITE_OPEN_READONLY;
5854 openFlags |= O_RDONLY;
5855 isReadonly = 1;
5856 fd = robust_open(zName, openFlags, openMode);
5858 if( fd<0 ){
5859 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
5860 goto open_finished;
5863 /* If this process is running as root and if creating a new rollback
5864 ** journal or WAL file, set the ownership of the journal or WAL to be
5865 ** the same as the original database.
5867 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
5868 robustFchown(fd, uid, gid);
5871 assert( fd>=0 );
5872 if( pOutFlags ){
5873 *pOutFlags = flags;
5876 if( p->pPreallocatedUnused ){
5877 p->pPreallocatedUnused->fd = fd;
5878 p->pPreallocatedUnused->flags = flags;
5881 if( isDelete ){
5882 #if OS_VXWORKS
5883 zPath = zName;
5884 #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
5885 zPath = sqlite3_mprintf("%s", zName);
5886 if( zPath==0 ){
5887 robust_close(p, fd, __LINE__);
5888 return SQLITE_NOMEM_BKPT;
5890 #else
5891 osUnlink(zName);
5892 #endif
5894 #if SQLITE_ENABLE_LOCKING_STYLE
5895 else{
5896 p->openFlags = openFlags;
5898 #endif
5900 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5901 if( fstatfs(fd, &fsInfo) == -1 ){
5902 storeLastErrno(p, errno);
5903 robust_close(p, fd, __LINE__);
5904 return SQLITE_IOERR_ACCESS;
5906 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5907 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5909 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
5910 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5912 #endif
5914 /* Set up appropriate ctrlFlags */
5915 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5916 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5917 noLock = eType!=SQLITE_OPEN_MAIN_DB;
5918 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5919 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5920 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5922 #if SQLITE_ENABLE_LOCKING_STYLE
5923 #if SQLITE_PREFER_PROXY_LOCKING
5924 isAutoProxy = 1;
5925 #endif
5926 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
5927 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5928 int useProxy = 0;
5930 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5931 ** never use proxy, NULL means use proxy for non-local files only. */
5932 if( envforce!=NULL ){
5933 useProxy = atoi(envforce)>0;
5934 }else{
5935 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5937 if( useProxy ){
5938 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5939 if( rc==SQLITE_OK ){
5940 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
5941 if( rc!=SQLITE_OK ){
5942 /* Use unixClose to clean up the resources added in fillInUnixFile
5943 ** and clear all the structure's references. Specifically,
5944 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5946 unixClose(pFile);
5947 return rc;
5950 goto open_finished;
5953 #endif
5955 assert( zPath==0 || zPath[0]=='/'
5956 || eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL
5958 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5960 open_finished:
5961 if( rc!=SQLITE_OK ){
5962 sqlite3_free(p->pPreallocatedUnused);
5964 return rc;
5969 ** Delete the file at zPath. If the dirSync argument is true, fsync()
5970 ** the directory after deleting the file.
5972 static int unixDelete(
5973 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5974 const char *zPath, /* Name of file to be deleted */
5975 int dirSync /* If true, fsync() directory after deleting file */
5977 int rc = SQLITE_OK;
5978 UNUSED_PARAMETER(NotUsed);
5979 SimulateIOError(return SQLITE_IOERR_DELETE);
5980 if( osUnlink(zPath)==(-1) ){
5981 if( errno==ENOENT
5982 #if OS_VXWORKS
5983 || osAccess(zPath,0)!=0
5984 #endif
5986 rc = SQLITE_IOERR_DELETE_NOENT;
5987 }else{
5988 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
5990 return rc;
5992 #ifndef SQLITE_DISABLE_DIRSYNC
5993 if( (dirSync & 1)!=0 ){
5994 int fd;
5995 rc = osOpenDirectory(zPath, &fd);
5996 if( rc==SQLITE_OK ){
5997 if( full_fsync(fd,0,0) ){
5998 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
6000 robust_close(0, fd, __LINE__);
6001 }else{
6002 assert( rc==SQLITE_CANTOPEN );
6003 rc = SQLITE_OK;
6006 #endif
6007 return rc;
6011 ** Test the existence of or access permissions of file zPath. The
6012 ** test performed depends on the value of flags:
6014 ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
6015 ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
6016 ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
6018 ** Otherwise return 0.
6020 static int unixAccess(
6021 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
6022 const char *zPath, /* Path of the file to examine */
6023 int flags, /* What do we want to learn about the zPath file? */
6024 int *pResOut /* Write result boolean here */
6026 UNUSED_PARAMETER(NotUsed);
6027 SimulateIOError( return SQLITE_IOERR_ACCESS; );
6028 assert( pResOut!=0 );
6030 /* The spec says there are three possible values for flags. But only
6031 ** two of them are actually used */
6032 assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
6034 if( flags==SQLITE_ACCESS_EXISTS ){
6035 struct stat buf;
6036 *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
6037 }else{
6038 *pResOut = osAccess(zPath, W_OK|R_OK)==0;
6040 return SQLITE_OK;
6046 static int mkFullPathname(
6047 const char *zPath, /* Input path */
6048 char *zOut, /* Output buffer */
6049 int nOut /* Allocated size of buffer zOut */
6051 int nPath = sqlite3Strlen30(zPath);
6052 int iOff = 0;
6053 if( zPath[0]!='/' ){
6054 if( osGetcwd(zOut, nOut-2)==0 ){
6055 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
6057 iOff = sqlite3Strlen30(zOut);
6058 zOut[iOff++] = '/';
6060 if( (iOff+nPath+1)>nOut ){
6061 /* SQLite assumes that xFullPathname() nul-terminates the output buffer
6062 ** even if it returns an error. */
6063 zOut[iOff] = '\0';
6064 return SQLITE_CANTOPEN_BKPT;
6066 sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
6067 return SQLITE_OK;
6071 ** Turn a relative pathname into a full pathname. The relative path
6072 ** is stored as a nul-terminated string in the buffer pointed to by
6073 ** zPath.
6075 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
6076 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
6077 ** this buffer before returning.
6079 static int unixFullPathname(
6080 sqlite3_vfs *pVfs, /* Pointer to vfs object */
6081 const char *zPath, /* Possibly relative input path */
6082 int nOut, /* Size of output buffer in bytes */
6083 char *zOut /* Output buffer */
6085 #if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
6086 return mkFullPathname(zPath, zOut, nOut);
6087 #else
6088 int rc = SQLITE_OK;
6089 int nByte;
6090 int nLink = 1; /* Number of symbolic links followed so far */
6091 const char *zIn = zPath; /* Input path for each iteration of loop */
6092 char *zDel = 0;
6094 assert( pVfs->mxPathname==MAX_PATHNAME );
6095 UNUSED_PARAMETER(pVfs);
6097 /* It's odd to simulate an io-error here, but really this is just
6098 ** using the io-error infrastructure to test that SQLite handles this
6099 ** function failing. This function could fail if, for example, the
6100 ** current working directory has been unlinked.
6102 SimulateIOError( return SQLITE_ERROR );
6104 do {
6106 /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
6107 ** link, or false otherwise. */
6108 int bLink = 0;
6109 struct stat buf;
6110 if( osLstat(zIn, &buf)!=0 ){
6111 if( errno!=ENOENT ){
6112 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
6114 }else{
6115 bLink = S_ISLNK(buf.st_mode);
6118 if( bLink ){
6119 if( zDel==0 ){
6120 zDel = sqlite3_malloc(nOut);
6121 if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
6122 }else if( ++nLink>SQLITE_MAX_SYMLINKS ){
6123 rc = SQLITE_CANTOPEN_BKPT;
6126 if( rc==SQLITE_OK ){
6127 nByte = osReadlink(zIn, zDel, nOut-1);
6128 if( nByte<0 ){
6129 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
6130 }else{
6131 if( zDel[0]!='/' ){
6132 int n;
6133 for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
6134 if( nByte+n+1>nOut ){
6135 rc = SQLITE_CANTOPEN_BKPT;
6136 }else{
6137 memmove(&zDel[n], zDel, nByte+1);
6138 memcpy(zDel, zIn, n);
6139 nByte += n;
6142 zDel[nByte] = '\0';
6146 zIn = zDel;
6149 assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
6150 if( rc==SQLITE_OK && zIn!=zOut ){
6151 rc = mkFullPathname(zIn, zOut, nOut);
6153 if( bLink==0 ) break;
6154 zIn = zOut;
6155 }while( rc==SQLITE_OK );
6157 sqlite3_free(zDel);
6158 return rc;
6159 #endif /* HAVE_READLINK && HAVE_LSTAT */
6163 #ifndef SQLITE_OMIT_LOAD_EXTENSION
6165 ** Interfaces for opening a shared library, finding entry points
6166 ** within the shared library, and closing the shared library.
6168 #include <dlfcn.h>
6169 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6170 UNUSED_PARAMETER(NotUsed);
6171 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6175 ** SQLite calls this function immediately after a call to unixDlSym() or
6176 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
6177 ** message is available, it is written to zBufOut. If no error message
6178 ** is available, zBufOut is left unmodified and SQLite uses a default
6179 ** error message.
6181 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
6182 const char *zErr;
6183 UNUSED_PARAMETER(NotUsed);
6184 unixEnterMutex();
6185 zErr = dlerror();
6186 if( zErr ){
6187 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
6189 unixLeaveMutex();
6191 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6193 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6194 ** cast into a pointer to a function. And yet the library dlsym() routine
6195 ** returns a void* which is really a pointer to a function. So how do we
6196 ** use dlsym() with -pedantic-errors?
6198 ** Variable x below is defined to be a pointer to a function taking
6199 ** parameters void* and const char* and returning a pointer to a function.
6200 ** We initialize x by assigning it a pointer to the dlsym() function.
6201 ** (That assignment requires a cast.) Then we call the function that
6202 ** x points to.
6204 ** This work-around is unlikely to work correctly on any system where
6205 ** you really cannot cast a function pointer into void*. But then, on the
6206 ** other hand, dlsym() will not work on such a system either, so we have
6207 ** not really lost anything.
6209 void (*(*x)(void*,const char*))(void);
6210 UNUSED_PARAMETER(NotUsed);
6211 x = (void(*(*)(void*,const char*))(void))dlsym;
6212 return (*x)(p, zSym);
6214 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6215 UNUSED_PARAMETER(NotUsed);
6216 dlclose(pHandle);
6218 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6219 #define unixDlOpen 0
6220 #define unixDlError 0
6221 #define unixDlSym 0
6222 #define unixDlClose 0
6223 #endif
6226 ** Write nBuf bytes of random data to the supplied buffer zBuf.
6228 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6229 UNUSED_PARAMETER(NotUsed);
6230 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
6232 /* We have to initialize zBuf to prevent valgrind from reporting
6233 ** errors. The reports issued by valgrind are incorrect - we would
6234 ** prefer that the randomness be increased by making use of the
6235 ** uninitialized space in zBuf - but valgrind errors tend to worry
6236 ** some users. Rather than argue, it seems easier just to initialize
6237 ** the whole array and silence valgrind, even if that means less randomness
6238 ** in the random seed.
6240 ** When testing, initializing zBuf[] to zero is all we do. That means
6241 ** that we always use the same random number sequence. This makes the
6242 ** tests repeatable.
6244 memset(zBuf, 0, nBuf);
6245 randomnessPid = osGetpid(0);
6246 #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
6248 int fd, got;
6249 fd = robust_open("/dev/urandom", O_RDONLY, 0);
6250 if( fd<0 ){
6251 time_t t;
6252 time(&t);
6253 memcpy(zBuf, &t, sizeof(t));
6254 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6255 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6256 nBuf = sizeof(t) + sizeof(randomnessPid);
6257 }else{
6258 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
6259 robust_close(0, fd, __LINE__);
6262 #endif
6263 return nBuf;
6268 ** Sleep for a little while. Return the amount of time slept.
6269 ** The argument is the number of microseconds we want to sleep.
6270 ** The return value is the number of microseconds of sleep actually
6271 ** requested from the underlying operating system, a number which
6272 ** might be greater than or equal to the argument, but not less
6273 ** than the argument.
6275 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
6276 #if OS_VXWORKS
6277 struct timespec sp;
6279 sp.tv_sec = microseconds / 1000000;
6280 sp.tv_nsec = (microseconds % 1000000) * 1000;
6281 nanosleep(&sp, NULL);
6282 UNUSED_PARAMETER(NotUsed);
6283 return microseconds;
6284 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
6285 usleep(microseconds);
6286 UNUSED_PARAMETER(NotUsed);
6287 return microseconds;
6288 #else
6289 int seconds = (microseconds+999999)/1000000;
6290 sleep(seconds);
6291 UNUSED_PARAMETER(NotUsed);
6292 return seconds*1000000;
6293 #endif
6297 ** The following variable, if set to a non-zero value, is interpreted as
6298 ** the number of seconds since 1970 and is used to set the result of
6299 ** sqlite3OsCurrentTime() during testing.
6301 #ifdef SQLITE_TEST
6302 int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
6303 #endif
6306 ** Find the current time (in Universal Coordinated Time). Write into *piNow
6307 ** the current time and date as a Julian Day number times 86_400_000. In
6308 ** other words, write into *piNow the number of milliseconds since the Julian
6309 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6310 ** proleptic Gregorian calendar.
6312 ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6313 ** cannot be found.
6315 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6316 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
6317 int rc = SQLITE_OK;
6318 #if defined(NO_GETTOD)
6319 time_t t;
6320 time(&t);
6321 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
6322 #elif OS_VXWORKS
6323 struct timespec sNow;
6324 clock_gettime(CLOCK_REALTIME, &sNow);
6325 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6326 #else
6327 struct timeval sNow;
6328 (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
6329 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
6330 #endif
6332 #ifdef SQLITE_TEST
6333 if( sqlite3_current_time ){
6334 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6336 #endif
6337 UNUSED_PARAMETER(NotUsed);
6338 return rc;
6341 #ifndef SQLITE_OMIT_DEPRECATED
6343 ** Find the current time (in Universal Coordinated Time). Write the
6344 ** current time and date as a Julian Day number into *prNow and
6345 ** return 0. Return 1 if the time and date cannot be found.
6347 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
6348 sqlite3_int64 i = 0;
6349 int rc;
6350 UNUSED_PARAMETER(NotUsed);
6351 rc = unixCurrentTimeInt64(0, &i);
6352 *prNow = i/86400000.0;
6353 return rc;
6355 #else
6356 # define unixCurrentTime 0
6357 #endif
6360 ** The xGetLastError() method is designed to return a better
6361 ** low-level error message when operating-system problems come up
6362 ** during SQLite operation. Only the integer return code is currently
6363 ** used.
6365 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6366 UNUSED_PARAMETER(NotUsed);
6367 UNUSED_PARAMETER(NotUsed2);
6368 UNUSED_PARAMETER(NotUsed3);
6369 return errno;
6374 ************************ End of sqlite3_vfs methods ***************************
6375 ******************************************************************************/
6377 /******************************************************************************
6378 ************************** Begin Proxy Locking ********************************
6380 ** Proxy locking is a "uber-locking-method" in this sense: It uses the
6381 ** other locking methods on secondary lock files. Proxy locking is a
6382 ** meta-layer over top of the primitive locking implemented above. For
6383 ** this reason, the division that implements of proxy locking is deferred
6384 ** until late in the file (here) after all of the other I/O methods have
6385 ** been defined - so that the primitive locking methods are available
6386 ** as services to help with the implementation of proxy locking.
6388 ****
6390 ** The default locking schemes in SQLite use byte-range locks on the
6391 ** database file to coordinate safe, concurrent access by multiple readers
6392 ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6393 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6394 ** as POSIX read & write locks over fixed set of locations (via fsctl),
6395 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
6396 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6397 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6398 ** address in the shared range is taken for a SHARED lock, the entire
6399 ** shared range is taken for an EXCLUSIVE lock):
6401 ** PENDING_BYTE 0x40000000
6402 ** RESERVED_BYTE 0x40000001
6403 ** SHARED_RANGE 0x40000002 -> 0x40000200
6405 ** This works well on the local file system, but shows a nearly 100x
6406 ** slowdown in read performance on AFP because the AFP client disables
6407 ** the read cache when byte-range locks are present. Enabling the read
6408 ** cache exposes a cache coherency problem that is present on all OS X
6409 ** supported network file systems. NFS and AFP both observe the
6410 ** close-to-open semantics for ensuring cache coherency
6411 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6412 ** address the requirements for concurrent database access by multiple
6413 ** readers and writers
6414 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6416 ** To address the performance and cache coherency issues, proxy file locking
6417 ** changes the way database access is controlled by limiting access to a
6418 ** single host at a time and moving file locks off of the database file
6419 ** and onto a proxy file on the local file system.
6422 ** Using proxy locks
6423 ** -----------------
6425 ** C APIs
6427 ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
6428 ** <proxy_path> | ":auto:");
6429 ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6430 ** &<proxy_path>);
6433 ** SQL pragmas
6435 ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6436 ** PRAGMA [database.]lock_proxy_file
6438 ** Specifying ":auto:" means that if there is a conch file with a matching
6439 ** host ID in it, the proxy path in the conch file will be used, otherwise
6440 ** a proxy path based on the user's temp dir
6441 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6442 ** actual proxy file name is generated from the name and path of the
6443 ** database file. For example:
6445 ** For database path "/Users/me/foo.db"
6446 ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6448 ** Once a lock proxy is configured for a database connection, it can not
6449 ** be removed, however it may be switched to a different proxy path via
6450 ** the above APIs (assuming the conch file is not being held by another
6451 ** connection or process).
6454 ** How proxy locking works
6455 ** -----------------------
6457 ** Proxy file locking relies primarily on two new supporting files:
6459 ** * conch file to limit access to the database file to a single host
6460 ** at a time
6462 ** * proxy file to act as a proxy for the advisory locks normally
6463 ** taken on the database
6465 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
6466 ** by taking an sqlite-style shared lock on the conch file, reading the
6467 ** contents and comparing the host's unique host ID (see below) and lock
6468 ** proxy path against the values stored in the conch. The conch file is
6469 ** stored in the same directory as the database file and the file name
6470 ** is patterned after the database file name as ".<databasename>-conch".
6471 ** If the conch file does not exist, or its contents do not match the
6472 ** host ID and/or proxy path, then the lock is escalated to an exclusive
6473 ** lock and the conch file contents is updated with the host ID and proxy
6474 ** path and the lock is downgraded to a shared lock again. If the conch
6475 ** is held by another process (with a shared lock), the exclusive lock
6476 ** will fail and SQLITE_BUSY is returned.
6478 ** The proxy file - a single-byte file used for all advisory file locks
6479 ** normally taken on the database file. This allows for safe sharing
6480 ** of the database file for multiple readers and writers on the same
6481 ** host (the conch ensures that they all use the same local lock file).
6483 ** Requesting the lock proxy does not immediately take the conch, it is
6484 ** only taken when the first request to lock database file is made.
6485 ** This matches the semantics of the traditional locking behavior, where
6486 ** opening a connection to a database file does not take a lock on it.
6487 ** The shared lock and an open file descriptor are maintained until
6488 ** the connection to the database is closed.
6490 ** The proxy file and the lock file are never deleted so they only need
6491 ** to be created the first time they are used.
6493 ** Configuration options
6494 ** ---------------------
6496 ** SQLITE_PREFER_PROXY_LOCKING
6498 ** Database files accessed on non-local file systems are
6499 ** automatically configured for proxy locking, lock files are
6500 ** named automatically using the same logic as
6501 ** PRAGMA lock_proxy_file=":auto:"
6503 ** SQLITE_PROXY_DEBUG
6505 ** Enables the logging of error messages during host id file
6506 ** retrieval and creation
6508 ** LOCKPROXYDIR
6510 ** Overrides the default directory used for lock proxy files that
6511 ** are named automatically via the ":auto:" setting
6513 ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6515 ** Permissions to use when creating a directory for storing the
6516 ** lock proxy files, only used when LOCKPROXYDIR is not set.
6519 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6520 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6521 ** force proxy locking to be used for every database file opened, and 0
6522 ** will force automatic proxy locking to be disabled for all database
6523 ** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
6524 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6528 ** Proxy locking is only available on MacOSX
6530 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
6533 ** The proxyLockingContext has the path and file structures for the remote
6534 ** and local proxy files in it
6536 typedef struct proxyLockingContext proxyLockingContext;
6537 struct proxyLockingContext {
6538 unixFile *conchFile; /* Open conch file */
6539 char *conchFilePath; /* Name of the conch file */
6540 unixFile *lockProxy; /* Open proxy lock file */
6541 char *lockProxyPath; /* Name of the proxy lock file */
6542 char *dbPath; /* Name of the open file */
6543 int conchHeld; /* 1 if the conch is held, -1 if lockless */
6544 int nFails; /* Number of conch taking failures */
6545 void *oldLockingContext; /* Original lockingcontext to restore on close */
6546 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6550 ** The proxy lock file path for the database at dbPath is written into lPath,
6551 ** which must point to valid, writable memory large enough for a maxLen length
6552 ** file path.
6554 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6555 int len;
6556 int dbLen;
6557 int i;
6559 #ifdef LOCKPROXYDIR
6560 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6561 #else
6562 # ifdef _CS_DARWIN_USER_TEMP_DIR
6564 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
6565 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
6566 lPath, errno, osGetpid(0)));
6567 return SQLITE_IOERR_LOCK;
6569 len = strlcat(lPath, "sqliteplocks", maxLen);
6571 # else
6572 len = strlcpy(lPath, "/tmp/", maxLen);
6573 # endif
6574 #endif
6576 if( lPath[len-1]!='/' ){
6577 len = strlcat(lPath, "/", maxLen);
6580 /* transform the db path to a unique cache name */
6581 dbLen = (int)strlen(dbPath);
6582 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
6583 char c = dbPath[i];
6584 lPath[i+len] = (c=='/')?'_':c;
6586 lPath[i+len]='\0';
6587 strlcat(lPath, ":auto:", maxLen);
6588 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
6589 return SQLITE_OK;
6593 ** Creates the lock file and any missing directories in lockPath
6595 static int proxyCreateLockPath(const char *lockPath){
6596 int i, len;
6597 char buf[MAXPATHLEN];
6598 int start = 0;
6600 assert(lockPath!=NULL);
6601 /* try to create all the intermediate directories */
6602 len = (int)strlen(lockPath);
6603 buf[0] = lockPath[0];
6604 for( i=1; i<len; i++ ){
6605 if( lockPath[i] == '/' && (i - start > 0) ){
6606 /* only mkdir if leaf dir != "." or "/" or ".." */
6607 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6608 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6609 buf[i]='\0';
6610 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
6611 int err=errno;
6612 if( err!=EEXIST ) {
6613 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
6614 "'%s' proxy lock path=%s pid=%d\n",
6615 buf, strerror(err), lockPath, osGetpid(0)));
6616 return err;
6620 start=i+1;
6622 buf[i] = lockPath[i];
6624 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
6625 return 0;
6629 ** Create a new VFS file descriptor (stored in memory obtained from
6630 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
6632 ** The caller is responsible not only for closing the file descriptor
6633 ** but also for freeing the memory associated with the file descriptor.
6635 static int proxyCreateUnixFile(
6636 const char *path, /* path for the new unixFile */
6637 unixFile **ppFile, /* unixFile created and returned by ref */
6638 int islockfile /* if non zero missing dirs will be created */
6640 int fd = -1;
6641 unixFile *pNew;
6642 int rc = SQLITE_OK;
6643 int openFlags = O_RDWR | O_CREAT;
6644 sqlite3_vfs dummyVfs;
6645 int terrno = 0;
6646 UnixUnusedFd *pUnused = NULL;
6648 /* 1. first try to open/create the file
6649 ** 2. if that fails, and this is a lock file (not-conch), try creating
6650 ** the parent directories and then try again.
6651 ** 3. if that fails, try to open the file read-only
6652 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6654 pUnused = findReusableFd(path, openFlags);
6655 if( pUnused ){
6656 fd = pUnused->fd;
6657 }else{
6658 pUnused = sqlite3_malloc64(sizeof(*pUnused));
6659 if( !pUnused ){
6660 return SQLITE_NOMEM_BKPT;
6663 if( fd<0 ){
6664 fd = robust_open(path, openFlags, 0);
6665 terrno = errno;
6666 if( fd<0 && errno==ENOENT && islockfile ){
6667 if( proxyCreateLockPath(path) == SQLITE_OK ){
6668 fd = robust_open(path, openFlags, 0);
6672 if( fd<0 ){
6673 openFlags = O_RDONLY;
6674 fd = robust_open(path, openFlags, 0);
6675 terrno = errno;
6677 if( fd<0 ){
6678 if( islockfile ){
6679 return SQLITE_BUSY;
6681 switch (terrno) {
6682 case EACCES:
6683 return SQLITE_PERM;
6684 case EIO:
6685 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6686 default:
6687 return SQLITE_CANTOPEN_BKPT;
6691 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
6692 if( pNew==NULL ){
6693 rc = SQLITE_NOMEM_BKPT;
6694 goto end_create_proxy;
6696 memset(pNew, 0, sizeof(unixFile));
6697 pNew->openFlags = openFlags;
6698 memset(&dummyVfs, 0, sizeof(dummyVfs));
6699 dummyVfs.pAppData = (void*)&autolockIoFinder;
6700 dummyVfs.zName = "dummy";
6701 pUnused->fd = fd;
6702 pUnused->flags = openFlags;
6703 pNew->pPreallocatedUnused = pUnused;
6705 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
6706 if( rc==SQLITE_OK ){
6707 *ppFile = pNew;
6708 return SQLITE_OK;
6710 end_create_proxy:
6711 robust_close(pNew, fd, __LINE__);
6712 sqlite3_free(pNew);
6713 sqlite3_free(pUnused);
6714 return rc;
6717 #ifdef SQLITE_TEST
6718 /* simulate multiple hosts by creating unique hostid file paths */
6719 int sqlite3_hostid_num = 0;
6720 #endif
6722 #define PROXY_HOSTIDLEN 16 /* conch file host id length */
6724 #ifdef HAVE_GETHOSTUUID
6725 /* Not always defined in the headers as it ought to be */
6726 extern int gethostuuid(uuid_t id, const struct timespec *wait);
6727 #endif
6729 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6730 ** bytes of writable memory.
6732 static int proxyGetHostID(unsigned char *pHostID, int *pError){
6733 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6734 memset(pHostID, 0, PROXY_HOSTIDLEN);
6735 #ifdef HAVE_GETHOSTUUID
6737 struct timespec timeout = {1, 0}; /* 1 sec timeout */
6738 if( gethostuuid(pHostID, &timeout) ){
6739 int err = errno;
6740 if( pError ){
6741 *pError = err;
6743 return SQLITE_IOERR;
6746 #else
6747 UNUSED_PARAMETER(pError);
6748 #endif
6749 #ifdef SQLITE_TEST
6750 /* simulate multiple hosts by creating unique hostid file paths */
6751 if( sqlite3_hostid_num != 0){
6752 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6754 #endif
6756 return SQLITE_OK;
6759 /* The conch file contains the header, host id and lock file path
6761 #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6762 #define PROXY_HEADERLEN 1 /* conch file header length */
6763 #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6764 #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6767 ** Takes an open conch file, copies the contents to a new path and then moves
6768 ** it back. The newly created file's file descriptor is assigned to the
6769 ** conch file structure and finally the original conch file descriptor is
6770 ** closed. Returns zero if successful.
6772 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6773 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6774 unixFile *conchFile = pCtx->conchFile;
6775 char tPath[MAXPATHLEN];
6776 char buf[PROXY_MAXCONCHLEN];
6777 char *cPath = pCtx->conchFilePath;
6778 size_t readLen = 0;
6779 size_t pathLen = 0;
6780 char errmsg[64] = "";
6781 int fd = -1;
6782 int rc = -1;
6783 UNUSED_PARAMETER(myHostID);
6785 /* create a new path by replace the trailing '-conch' with '-break' */
6786 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6787 if( pathLen>MAXPATHLEN || pathLen<6 ||
6788 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
6789 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
6790 goto end_breaklock;
6792 /* read the conch content */
6793 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
6794 if( readLen<PROXY_PATHINDEX ){
6795 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
6796 goto end_breaklock;
6798 /* write it out to the temporary break file */
6799 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
6800 if( fd<0 ){
6801 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
6802 goto end_breaklock;
6804 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
6805 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
6806 goto end_breaklock;
6808 if( rename(tPath, cPath) ){
6809 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
6810 goto end_breaklock;
6812 rc = 0;
6813 fprintf(stderr, "broke stale lock on %s\n", cPath);
6814 robust_close(pFile, conchFile->h, __LINE__);
6815 conchFile->h = fd;
6816 conchFile->openFlags = O_RDWR | O_CREAT;
6818 end_breaklock:
6819 if( rc ){
6820 if( fd>=0 ){
6821 osUnlink(tPath);
6822 robust_close(pFile, fd, __LINE__);
6824 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6826 return rc;
6829 /* Take the requested lock on the conch file and break a stale lock if the
6830 ** host id matches.
6832 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6833 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6834 unixFile *conchFile = pCtx->conchFile;
6835 int rc = SQLITE_OK;
6836 int nTries = 0;
6837 struct timespec conchModTime;
6839 memset(&conchModTime, 0, sizeof(conchModTime));
6840 do {
6841 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6842 nTries ++;
6843 if( rc==SQLITE_BUSY ){
6844 /* If the lock failed (busy):
6845 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6846 * 2nd try: fail if the mod time changed or host id is different, wait
6847 * 10 sec and try again
6848 * 3rd try: break the lock unless the mod time has changed.
6850 struct stat buf;
6851 if( osFstat(conchFile->h, &buf) ){
6852 storeLastErrno(pFile, errno);
6853 return SQLITE_IOERR_LOCK;
6856 if( nTries==1 ){
6857 conchModTime = buf.st_mtimespec;
6858 usleep(500000); /* wait 0.5 sec and try the lock again*/
6859 continue;
6862 assert( nTries>1 );
6863 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6864 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6865 return SQLITE_BUSY;
6868 if( nTries==2 ){
6869 char tBuf[PROXY_MAXCONCHLEN];
6870 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
6871 if( len<0 ){
6872 storeLastErrno(pFile, errno);
6873 return SQLITE_IOERR_LOCK;
6875 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6876 /* don't break the lock if the host id doesn't match */
6877 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6878 return SQLITE_BUSY;
6880 }else{
6881 /* don't break the lock on short read or a version mismatch */
6882 return SQLITE_BUSY;
6884 usleep(10000000); /* wait 10 sec and try the lock again */
6885 continue;
6888 assert( nTries==3 );
6889 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6890 rc = SQLITE_OK;
6891 if( lockType==EXCLUSIVE_LOCK ){
6892 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
6894 if( !rc ){
6895 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6899 } while( rc==SQLITE_BUSY && nTries<3 );
6901 return rc;
6904 /* Takes the conch by taking a shared lock and read the contents conch, if
6905 ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6906 ** lockPath means that the lockPath in the conch file will be used if the
6907 ** host IDs match, or a new lock path will be generated automatically
6908 ** and written to the conch file.
6910 static int proxyTakeConch(unixFile *pFile){
6911 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6913 if( pCtx->conchHeld!=0 ){
6914 return SQLITE_OK;
6915 }else{
6916 unixFile *conchFile = pCtx->conchFile;
6917 uuid_t myHostID;
6918 int pError = 0;
6919 char readBuf[PROXY_MAXCONCHLEN];
6920 char lockPath[MAXPATHLEN];
6921 char *tempLockPath = NULL;
6922 int rc = SQLITE_OK;
6923 int createConch = 0;
6924 int hostIdMatch = 0;
6925 int readLen = 0;
6926 int tryOldLockPath = 0;
6927 int forceNewLockPath = 0;
6929 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6930 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
6931 osGetpid(0)));
6933 rc = proxyGetHostID(myHostID, &pError);
6934 if( (rc&0xff)==SQLITE_IOERR ){
6935 storeLastErrno(pFile, pError);
6936 goto end_takeconch;
6938 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
6939 if( rc!=SQLITE_OK ){
6940 goto end_takeconch;
6942 /* read the existing conch file */
6943 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6944 if( readLen<0 ){
6945 /* I/O error: lastErrno set by seekAndRead */
6946 storeLastErrno(pFile, conchFile->lastErrno);
6947 rc = SQLITE_IOERR_READ;
6948 goto end_takeconch;
6949 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6950 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6951 /* a short read or version format mismatch means we need to create a new
6952 ** conch file.
6954 createConch = 1;
6956 /* if the host id matches and the lock path already exists in the conch
6957 ** we'll try to use the path there, if we can't open that path, we'll
6958 ** retry with a new auto-generated path
6960 do { /* in case we need to try again for an :auto: named lock file */
6962 if( !createConch && !forceNewLockPath ){
6963 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6964 PROXY_HOSTIDLEN);
6965 /* if the conch has data compare the contents */
6966 if( !pCtx->lockProxyPath ){
6967 /* for auto-named local lock file, just check the host ID and we'll
6968 ** use the local lock file path that's already in there
6970 if( hostIdMatch ){
6971 size_t pathLen = (readLen - PROXY_PATHINDEX);
6973 if( pathLen>=MAXPATHLEN ){
6974 pathLen=MAXPATHLEN-1;
6976 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6977 lockPath[pathLen] = 0;
6978 tempLockPath = lockPath;
6979 tryOldLockPath = 1;
6980 /* create a copy of the lock path if the conch is taken */
6981 goto end_takeconch;
6983 }else if( hostIdMatch
6984 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6985 readLen-PROXY_PATHINDEX)
6987 /* conch host and lock path match */
6988 goto end_takeconch;
6992 /* if the conch isn't writable and doesn't match, we can't take it */
6993 if( (conchFile->openFlags&O_RDWR) == 0 ){
6994 rc = SQLITE_BUSY;
6995 goto end_takeconch;
6998 /* either the conch didn't match or we need to create a new one */
6999 if( !pCtx->lockProxyPath ){
7000 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
7001 tempLockPath = lockPath;
7002 /* create a copy of the lock path _only_ if the conch is taken */
7005 /* update conch with host and path (this will fail if other process
7006 ** has a shared lock already), if the host id matches, use the big
7007 ** stick.
7009 futimes(conchFile->h, NULL);
7010 if( hostIdMatch && !createConch ){
7011 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
7012 /* We are trying for an exclusive lock but another thread in this
7013 ** same process is still holding a shared lock. */
7014 rc = SQLITE_BUSY;
7015 } else {
7016 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
7018 }else{
7019 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
7021 if( rc==SQLITE_OK ){
7022 char writeBuffer[PROXY_MAXCONCHLEN];
7023 int writeSize = 0;
7025 writeBuffer[0] = (char)PROXY_CONCHVERSION;
7026 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
7027 if( pCtx->lockProxyPath!=NULL ){
7028 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
7029 MAXPATHLEN);
7030 }else{
7031 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
7033 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
7034 robust_ftruncate(conchFile->h, writeSize);
7035 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
7036 full_fsync(conchFile->h,0,0);
7037 /* If we created a new conch file (not just updated the contents of a
7038 ** valid conch file), try to match the permissions of the database
7040 if( rc==SQLITE_OK && createConch ){
7041 struct stat buf;
7042 int err = osFstat(pFile->h, &buf);
7043 if( err==0 ){
7044 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
7045 S_IROTH|S_IWOTH);
7046 /* try to match the database file R/W permissions, ignore failure */
7047 #ifndef SQLITE_PROXY_DEBUG
7048 osFchmod(conchFile->h, cmode);
7049 #else
7051 rc = osFchmod(conchFile->h, cmode);
7052 }while( rc==(-1) && errno==EINTR );
7053 if( rc!=0 ){
7054 int code = errno;
7055 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
7056 cmode, code, strerror(code));
7057 } else {
7058 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
7060 }else{
7061 int code = errno;
7062 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
7063 err, code, strerror(code));
7064 #endif
7068 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
7070 end_takeconch:
7071 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
7072 if( rc==SQLITE_OK && pFile->openFlags ){
7073 int fd;
7074 if( pFile->h>=0 ){
7075 robust_close(pFile, pFile->h, __LINE__);
7077 pFile->h = -1;
7078 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
7079 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
7080 if( fd>=0 ){
7081 pFile->h = fd;
7082 }else{
7083 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
7084 during locking */
7087 if( rc==SQLITE_OK && !pCtx->lockProxy ){
7088 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
7089 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
7090 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
7091 /* we couldn't create the proxy lock file with the old lock file path
7092 ** so try again via auto-naming
7094 forceNewLockPath = 1;
7095 tryOldLockPath = 0;
7096 continue; /* go back to the do {} while start point, try again */
7099 if( rc==SQLITE_OK ){
7100 /* Need to make a copy of path if we extracted the value
7101 ** from the conch file or the path was allocated on the stack
7103 if( tempLockPath ){
7104 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
7105 if( !pCtx->lockProxyPath ){
7106 rc = SQLITE_NOMEM_BKPT;
7110 if( rc==SQLITE_OK ){
7111 pCtx->conchHeld = 1;
7113 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
7114 afpLockingContext *afpCtx;
7115 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
7116 afpCtx->dbPath = pCtx->lockProxyPath;
7118 } else {
7119 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7121 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
7122 rc==SQLITE_OK?"ok":"failed"));
7123 return rc;
7124 } while (1); /* in case we need to retry the :auto: lock file -
7125 ** we should never get here except via the 'continue' call. */
7130 ** If pFile holds a lock on a conch file, then release that lock.
7132 static int proxyReleaseConch(unixFile *pFile){
7133 int rc = SQLITE_OK; /* Subroutine return code */
7134 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
7135 unixFile *conchFile; /* Name of the conch file */
7137 pCtx = (proxyLockingContext *)pFile->lockingContext;
7138 conchFile = pCtx->conchFile;
7139 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
7140 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
7141 osGetpid(0)));
7142 if( pCtx->conchHeld>0 ){
7143 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7145 pCtx->conchHeld = 0;
7146 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
7147 (rc==SQLITE_OK ? "ok" : "failed")));
7148 return rc;
7152 ** Given the name of a database file, compute the name of its conch file.
7153 ** Store the conch filename in memory obtained from sqlite3_malloc64().
7154 ** Make *pConchPath point to the new name. Return SQLITE_OK on success
7155 ** or SQLITE_NOMEM if unable to obtain memory.
7157 ** The caller is responsible for ensuring that the allocated memory
7158 ** space is eventually freed.
7160 ** *pConchPath is set to NULL if a memory allocation error occurs.
7162 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7163 int i; /* Loop counter */
7164 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
7165 char *conchPath; /* buffer in which to construct conch name */
7167 /* Allocate space for the conch filename and initialize the name to
7168 ** the name of the original database file. */
7169 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
7170 if( conchPath==0 ){
7171 return SQLITE_NOMEM_BKPT;
7173 memcpy(conchPath, dbPath, len+1);
7175 /* now insert a "." before the last / character */
7176 for( i=(len-1); i>=0; i-- ){
7177 if( conchPath[i]=='/' ){
7178 i++;
7179 break;
7182 conchPath[i]='.';
7183 while ( i<len ){
7184 conchPath[i+1]=dbPath[i];
7185 i++;
7188 /* append the "-conch" suffix to the file */
7189 memcpy(&conchPath[i+1], "-conch", 7);
7190 assert( (int)strlen(conchPath) == len+7 );
7192 return SQLITE_OK;
7196 /* Takes a fully configured proxy locking-style unix file and switches
7197 ** the local lock file path
7199 static int switchLockProxyPath(unixFile *pFile, const char *path) {
7200 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7201 char *oldPath = pCtx->lockProxyPath;
7202 int rc = SQLITE_OK;
7204 if( pFile->eFileLock!=NO_LOCK ){
7205 return SQLITE_BUSY;
7208 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7209 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7210 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7211 return SQLITE_OK;
7212 }else{
7213 unixFile *lockProxy = pCtx->lockProxy;
7214 pCtx->lockProxy=NULL;
7215 pCtx->conchHeld = 0;
7216 if( lockProxy!=NULL ){
7217 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7218 if( rc ) return rc;
7219 sqlite3_free(lockProxy);
7221 sqlite3_free(oldPath);
7222 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7225 return rc;
7229 ** pFile is a file that has been opened by a prior xOpen call. dbPath
7230 ** is a string buffer at least MAXPATHLEN+1 characters in size.
7232 ** This routine find the filename associated with pFile and writes it
7233 ** int dbPath.
7235 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
7236 #if defined(__APPLE__)
7237 if( pFile->pMethod == &afpIoMethods ){
7238 /* afp style keeps a reference to the db path in the filePath field
7239 ** of the struct */
7240 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
7241 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7242 MAXPATHLEN);
7243 } else
7244 #endif
7245 if( pFile->pMethod == &dotlockIoMethods ){
7246 /* dot lock style uses the locking context to store the dot lock
7247 ** file path */
7248 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7249 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7250 }else{
7251 /* all other styles use the locking context to store the db file path */
7252 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
7253 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
7255 return SQLITE_OK;
7259 ** Takes an already filled in unix file and alters it so all file locking
7260 ** will be performed on the local proxy lock file. The following fields
7261 ** are preserved in the locking context so that they can be restored and
7262 ** the unix structure properly cleaned up at close time:
7263 ** ->lockingContext
7264 ** ->pMethod
7266 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7267 proxyLockingContext *pCtx;
7268 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7269 char *lockPath=NULL;
7270 int rc = SQLITE_OK;
7272 if( pFile->eFileLock!=NO_LOCK ){
7273 return SQLITE_BUSY;
7275 proxyGetDbPathForUnixFile(pFile, dbPath);
7276 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7277 lockPath=NULL;
7278 }else{
7279 lockPath=(char *)path;
7282 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
7283 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
7285 pCtx = sqlite3_malloc64( sizeof(*pCtx) );
7286 if( pCtx==0 ){
7287 return SQLITE_NOMEM_BKPT;
7289 memset(pCtx, 0, sizeof(*pCtx));
7291 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7292 if( rc==SQLITE_OK ){
7293 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7294 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7295 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7296 ** (c) the file system is read-only, then enable no-locking access.
7297 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7298 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7300 struct statfs fsInfo;
7301 struct stat conchInfo;
7302 int goLockless = 0;
7304 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
7305 int err = errno;
7306 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7307 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7310 if( goLockless ){
7311 pCtx->conchHeld = -1; /* read only FS/ lockless */
7312 rc = SQLITE_OK;
7316 if( rc==SQLITE_OK && lockPath ){
7317 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7320 if( rc==SQLITE_OK ){
7321 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7322 if( pCtx->dbPath==NULL ){
7323 rc = SQLITE_NOMEM_BKPT;
7326 if( rc==SQLITE_OK ){
7327 /* all memory is allocated, proxys are created and assigned,
7328 ** switch the locking context and pMethod then return.
7330 pCtx->oldLockingContext = pFile->lockingContext;
7331 pFile->lockingContext = pCtx;
7332 pCtx->pOldMethod = pFile->pMethod;
7333 pFile->pMethod = &proxyIoMethods;
7334 }else{
7335 if( pCtx->conchFile ){
7336 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
7337 sqlite3_free(pCtx->conchFile);
7339 sqlite3DbFree(0, pCtx->lockProxyPath);
7340 sqlite3_free(pCtx->conchFilePath);
7341 sqlite3_free(pCtx);
7343 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7344 (rc==SQLITE_OK ? "ok" : "failed")));
7345 return rc;
7350 ** This routine handles sqlite3_file_control() calls that are specific
7351 ** to proxy locking.
7353 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7354 switch( op ){
7355 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
7356 unixFile *pFile = (unixFile*)id;
7357 if( pFile->pMethod == &proxyIoMethods ){
7358 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7359 proxyTakeConch(pFile);
7360 if( pCtx->lockProxyPath ){
7361 *(const char **)pArg = pCtx->lockProxyPath;
7362 }else{
7363 *(const char **)pArg = ":auto: (not held)";
7365 } else {
7366 *(const char **)pArg = NULL;
7368 return SQLITE_OK;
7370 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
7371 unixFile *pFile = (unixFile*)id;
7372 int rc = SQLITE_OK;
7373 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7374 if( pArg==NULL || (const char *)pArg==0 ){
7375 if( isProxyStyle ){
7376 /* turn off proxy locking - not supported. If support is added for
7377 ** switching proxy locking mode off then it will need to fail if
7378 ** the journal mode is WAL mode.
7380 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7381 }else{
7382 /* turn off proxy locking - already off - NOOP */
7383 rc = SQLITE_OK;
7385 }else{
7386 const char *proxyPath = (const char *)pArg;
7387 if( isProxyStyle ){
7388 proxyLockingContext *pCtx =
7389 (proxyLockingContext*)pFile->lockingContext;
7390 if( !strcmp(pArg, ":auto:")
7391 || (pCtx->lockProxyPath &&
7392 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7394 rc = SQLITE_OK;
7395 }else{
7396 rc = switchLockProxyPath(pFile, proxyPath);
7398 }else{
7399 /* turn on proxy file locking */
7400 rc = proxyTransformUnixFile(pFile, proxyPath);
7403 return rc;
7405 default: {
7406 assert( 0 ); /* The call assures that only valid opcodes are sent */
7409 /*NOTREACHED*/
7410 return SQLITE_ERROR;
7414 ** Within this division (the proxying locking implementation) the procedures
7415 ** above this point are all utilities. The lock-related methods of the
7416 ** proxy-locking sqlite3_io_method object follow.
7421 ** This routine checks if there is a RESERVED lock held on the specified
7422 ** file by this or any other process. If such a lock is held, set *pResOut
7423 ** to a non-zero value otherwise *pResOut is set to zero. The return value
7424 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7426 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7427 unixFile *pFile = (unixFile*)id;
7428 int rc = proxyTakeConch(pFile);
7429 if( rc==SQLITE_OK ){
7430 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7431 if( pCtx->conchHeld>0 ){
7432 unixFile *proxy = pCtx->lockProxy;
7433 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7434 }else{ /* conchHeld < 0 is lockless */
7435 pResOut=0;
7438 return rc;
7442 ** Lock the file with the lock specified by parameter eFileLock - one
7443 ** of the following:
7445 ** (1) SHARED_LOCK
7446 ** (2) RESERVED_LOCK
7447 ** (3) PENDING_LOCK
7448 ** (4) EXCLUSIVE_LOCK
7450 ** Sometimes when requesting one lock state, additional lock states
7451 ** are inserted in between. The locking might fail on one of the later
7452 ** transitions leaving the lock state different from what it started but
7453 ** still short of its goal. The following chart shows the allowed
7454 ** transitions and the inserted intermediate states:
7456 ** UNLOCKED -> SHARED
7457 ** SHARED -> RESERVED
7458 ** SHARED -> (PENDING) -> EXCLUSIVE
7459 ** RESERVED -> (PENDING) -> EXCLUSIVE
7460 ** PENDING -> EXCLUSIVE
7462 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
7463 ** routine to lower a locking level.
7465 static int proxyLock(sqlite3_file *id, int eFileLock) {
7466 unixFile *pFile = (unixFile*)id;
7467 int rc = proxyTakeConch(pFile);
7468 if( rc==SQLITE_OK ){
7469 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7470 if( pCtx->conchHeld>0 ){
7471 unixFile *proxy = pCtx->lockProxy;
7472 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7473 pFile->eFileLock = proxy->eFileLock;
7474 }else{
7475 /* conchHeld < 0 is lockless */
7478 return rc;
7483 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
7484 ** must be either NO_LOCK or SHARED_LOCK.
7486 ** If the locking level of the file descriptor is already at or below
7487 ** the requested locking level, this routine is a no-op.
7489 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
7490 unixFile *pFile = (unixFile*)id;
7491 int rc = proxyTakeConch(pFile);
7492 if( rc==SQLITE_OK ){
7493 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7494 if( pCtx->conchHeld>0 ){
7495 unixFile *proxy = pCtx->lockProxy;
7496 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7497 pFile->eFileLock = proxy->eFileLock;
7498 }else{
7499 /* conchHeld < 0 is lockless */
7502 return rc;
7506 ** Close a file that uses proxy locks.
7508 static int proxyClose(sqlite3_file *id) {
7509 if( ALWAYS(id) ){
7510 unixFile *pFile = (unixFile*)id;
7511 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7512 unixFile *lockProxy = pCtx->lockProxy;
7513 unixFile *conchFile = pCtx->conchFile;
7514 int rc = SQLITE_OK;
7516 if( lockProxy ){
7517 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7518 if( rc ) return rc;
7519 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7520 if( rc ) return rc;
7521 sqlite3_free(lockProxy);
7522 pCtx->lockProxy = 0;
7524 if( conchFile ){
7525 if( pCtx->conchHeld ){
7526 rc = proxyReleaseConch(pFile);
7527 if( rc ) return rc;
7529 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7530 if( rc ) return rc;
7531 sqlite3_free(conchFile);
7533 sqlite3DbFree(0, pCtx->lockProxyPath);
7534 sqlite3_free(pCtx->conchFilePath);
7535 sqlite3DbFree(0, pCtx->dbPath);
7536 /* restore the original locking context and pMethod then close it */
7537 pFile->lockingContext = pCtx->oldLockingContext;
7538 pFile->pMethod = pCtx->pOldMethod;
7539 sqlite3_free(pCtx);
7540 return pFile->pMethod->xClose(id);
7542 return SQLITE_OK;
7547 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
7549 ** The proxy locking style is intended for use with AFP filesystems.
7550 ** And since AFP is only supported on MacOSX, the proxy locking is also
7551 ** restricted to MacOSX.
7554 ******************* End of the proxy lock implementation **********************
7555 ******************************************************************************/
7558 ** Initialize the operating system interface.
7560 ** This routine registers all VFS implementations for unix-like operating
7561 ** systems. This routine, and the sqlite3_os_end() routine that follows,
7562 ** should be the only routines in this file that are visible from other
7563 ** files.
7565 ** This routine is called once during SQLite initialization and by a
7566 ** single thread. The memory allocation and mutex subsystems have not
7567 ** necessarily been initialized when this routine is called, and so they
7568 ** should not be used.
7570 int sqlite3_os_init(void){
7572 ** The following macro defines an initializer for an sqlite3_vfs object.
7573 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7574 ** to the "finder" function. (pAppData is a pointer to a pointer because
7575 ** silly C90 rules prohibit a void* from being cast to a function pointer
7576 ** and so we have to go through the intermediate pointer to avoid problems
7577 ** when compiling with -pedantic-errors on GCC.)
7579 ** The FINDER parameter to this macro is the name of the pointer to the
7580 ** finder-function. The finder-function returns a pointer to the
7581 ** sqlite_io_methods object that implements the desired locking
7582 ** behaviors. See the division above that contains the IOMETHODS
7583 ** macro for addition information on finder-functions.
7585 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7586 ** object. But the "autolockIoFinder" available on MacOSX does a little
7587 ** more than that; it looks at the filesystem type that hosts the
7588 ** database file and tries to choose an locking method appropriate for
7589 ** that filesystem time.
7591 #define UNIXVFS(VFSNAME, FINDER) { \
7592 3, /* iVersion */ \
7593 sizeof(unixFile), /* szOsFile */ \
7594 MAX_PATHNAME, /* mxPathname */ \
7595 0, /* pNext */ \
7596 VFSNAME, /* zName */ \
7597 (void*)&FINDER, /* pAppData */ \
7598 unixOpen, /* xOpen */ \
7599 unixDelete, /* xDelete */ \
7600 unixAccess, /* xAccess */ \
7601 unixFullPathname, /* xFullPathname */ \
7602 unixDlOpen, /* xDlOpen */ \
7603 unixDlError, /* xDlError */ \
7604 unixDlSym, /* xDlSym */ \
7605 unixDlClose, /* xDlClose */ \
7606 unixRandomness, /* xRandomness */ \
7607 unixSleep, /* xSleep */ \
7608 unixCurrentTime, /* xCurrentTime */ \
7609 unixGetLastError, /* xGetLastError */ \
7610 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
7611 unixSetSystemCall, /* xSetSystemCall */ \
7612 unixGetSystemCall, /* xGetSystemCall */ \
7613 unixNextSystemCall, /* xNextSystemCall */ \
7617 ** All default VFSes for unix are contained in the following array.
7619 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7620 ** by the SQLite core when the VFS is registered. So the following
7621 ** array cannot be const.
7623 static sqlite3_vfs aVfs[] = {
7624 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
7625 UNIXVFS("unix", autolockIoFinder ),
7626 #elif OS_VXWORKS
7627 UNIXVFS("unix", vxworksIoFinder ),
7628 #else
7629 UNIXVFS("unix", posixIoFinder ),
7630 #endif
7631 UNIXVFS("unix-none", nolockIoFinder ),
7632 UNIXVFS("unix-dotfile", dotlockIoFinder ),
7633 UNIXVFS("unix-excl", posixIoFinder ),
7634 #if OS_VXWORKS
7635 UNIXVFS("unix-namedsem", semIoFinder ),
7636 #endif
7637 #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
7638 UNIXVFS("unix-posix", posixIoFinder ),
7639 #endif
7640 #if SQLITE_ENABLE_LOCKING_STYLE
7641 UNIXVFS("unix-flock", flockIoFinder ),
7642 #endif
7643 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
7644 UNIXVFS("unix-afp", afpIoFinder ),
7645 UNIXVFS("unix-nfs", nfsIoFinder ),
7646 UNIXVFS("unix-proxy", proxyIoFinder ),
7647 #endif
7649 unsigned int i; /* Loop counter */
7651 /* Double-check that the aSyscall[] array has been constructed
7652 ** correctly. See ticket [bb3a86e890c8e96ab] */
7653 assert( ArraySize(aSyscall)==29 );
7655 /* Register all VFSes defined in the aVfs[] array */
7656 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
7657 sqlite3_vfs_register(&aVfs[i], i==0);
7659 return SQLITE_OK;
7663 ** Shutdown the operating system interface.
7665 ** Some operating systems might need to do some cleanup in this routine,
7666 ** to release dynamically allocated objects. But not on unix.
7667 ** This routine is a no-op for unix.
7669 int sqlite3_os_end(void){
7670 return SQLITE_OK;
7673 #endif /* SQLITE_OS_UNIX */