Fix rounding in zero-precision %f and %g printf conversions.
[sqlite.git] / src / os_unix.c
blob4b3d63c2c18b72af273438943272c0643cb6a658
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 labelled.
27 ** The layout of divisions is as follows:
29 ** * General-purpose declarations and utility functions.
30 ** * Unique file ID logic used by VxWorks.
31 ** * Various locking primitive implementations (all except proxy locking):
32 ** + for Posix Advisory Locks
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__) || defined(__linux__)
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> /* amalgamator: keep */
91 #include <sys/stat.h> /* amalgamator: keep */
92 #include <fcntl.h>
93 #include <sys/ioctl.h>
94 #include <unistd.h> /* amalgamator: keep */
95 #include <time.h>
96 #include <sys/time.h> /* amalgamator: keep */
97 #include <errno.h>
98 #if (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) \
99 && !defined(SQLITE_WASI)
100 # include <sys/mman.h>
101 #endif
103 #if SQLITE_ENABLE_LOCKING_STYLE
104 # include <sys/ioctl.h>
105 # include <sys/file.h>
106 # include <sys/param.h>
107 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
110 ** Try to determine if gethostuuid() is available based on standard
111 ** macros. This might sometimes compute the wrong value for some
112 ** obscure platforms. For those cases, simply compile with one of
113 ** the following:
115 ** -DHAVE_GETHOSTUUID=0
116 ** -DHAVE_GETHOSTUUID=1
118 ** None if this matters except when building on Apple products with
119 ** -DSQLITE_ENABLE_LOCKING_STYLE.
121 #ifndef HAVE_GETHOSTUUID
122 # define HAVE_GETHOSTUUID 0
123 # if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
124 (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
125 # if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
126 && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))\
127 && (!defined(TARGET_OS_MACCATALYST) || (TARGET_OS_MACCATALYST==0))
128 # undef HAVE_GETHOSTUUID
129 # define HAVE_GETHOSTUUID 1
130 # else
131 # warning "gethostuuid() is disabled."
132 # endif
133 # endif
134 #endif
137 #if OS_VXWORKS
138 # include <sys/ioctl.h>
139 # include <semaphore.h>
140 # include <limits.h>
141 #endif /* OS_VXWORKS */
143 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
144 # include <sys/mount.h>
145 #endif
147 #ifdef HAVE_UTIME
148 # include <utime.h>
149 #endif
152 ** Allowed values of unixFile.fsFlags
154 #define SQLITE_FSFLAGS_IS_MSDOS 0x1
157 ** If we are to be thread-safe, include the pthreads header.
159 #if SQLITE_THREADSAFE
160 # include <pthread.h>
161 #endif
164 ** Default permissions when creating a new file
166 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
167 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
168 #endif
171 ** Default permissions when creating auto proxy dir
173 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
174 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
175 #endif
178 ** Maximum supported path-length.
180 #define MAX_PATHNAME 512
183 ** Maximum supported symbolic links
185 #define SQLITE_MAX_SYMLINKS 100
188 ** Remove and stub certain info for WASI (WebAssembly System
189 ** Interface) builds.
191 #ifdef SQLITE_WASI
192 # undef HAVE_FCHMOD
193 # undef HAVE_FCHOWN
194 # undef HAVE_MREMAP
195 # define HAVE_MREMAP 0
196 # ifndef SQLITE_DEFAULT_UNIX_VFS
197 # define SQLITE_DEFAULT_UNIX_VFS "unix-dotfile"
198 /* ^^^ should SQLITE_DEFAULT_UNIX_VFS be "unix-none"? */
199 # endif
200 # ifndef F_RDLCK
201 # define F_RDLCK 0
202 # define F_WRLCK 1
203 # define F_UNLCK 2
204 # if __LONG_MAX == 0x7fffffffL
205 # define F_GETLK 12
206 # define F_SETLK 13
207 # define F_SETLKW 14
208 # else
209 # define F_GETLK 5
210 # define F_SETLK 6
211 # define F_SETLKW 7
212 # endif
213 # endif
214 #else /* !SQLITE_WASI */
215 # ifndef HAVE_FCHMOD
216 # define HAVE_FCHMOD
217 # endif
218 #endif /* SQLITE_WASI */
220 #ifdef SQLITE_WASI
221 # define osGetpid(X) (pid_t)1
222 #else
223 /* Always cast the getpid() return type for compatibility with
224 ** kernel modules in VxWorks. */
225 # define osGetpid(X) (pid_t)getpid()
226 #endif
229 ** Only set the lastErrno if the error code is a real error and not
230 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
232 #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
234 /* Forward references */
235 typedef struct unixShm unixShm; /* Connection shared memory */
236 typedef struct unixShmNode unixShmNode; /* Shared memory instance */
237 typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
238 typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
241 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
242 ** cannot be closed immediately. In these cases, instances of the following
243 ** structure are used to store the file descriptor while waiting for an
244 ** opportunity to either close or reuse it.
246 struct UnixUnusedFd {
247 int fd; /* File descriptor to close */
248 int flags; /* Flags this file descriptor was opened with */
249 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
253 ** The unixFile structure is subclass of sqlite3_file specific to the unix
254 ** VFS implementations.
256 typedef struct unixFile unixFile;
257 struct unixFile {
258 sqlite3_io_methods const *pMethod; /* Always the first entry */
259 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
260 unixInodeInfo *pInode; /* Info about locks on this inode */
261 int h; /* The file descriptor */
262 unsigned char eFileLock; /* The type of lock held on this fd */
263 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
264 int lastErrno; /* The unix errno from last I/O error */
265 void *lockingContext; /* Locking style specific state */
266 UnixUnusedFd *pPreallocatedUnused; /* Pre-allocated UnixUnusedFd */
267 const char *zPath; /* Name of the file */
268 unixShm *pShm; /* Shared memory segment information */
269 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
270 #if SQLITE_MAX_MMAP_SIZE>0
271 int nFetchOut; /* Number of outstanding xFetch refs */
272 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
273 sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
274 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
275 void *pMapRegion; /* Memory mapped region */
276 #endif
277 int sectorSize; /* Device sector size */
278 int deviceCharacteristics; /* Precomputed device characteristics */
279 #if SQLITE_ENABLE_LOCKING_STYLE
280 int openFlags; /* The flags specified at open() */
281 #endif
282 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
283 unsigned fsFlags; /* cached details from statfs() */
284 #endif
285 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
286 unsigned iBusyTimeout; /* Wait this many millisec on locks */
287 #endif
288 #if OS_VXWORKS
289 struct vxworksFileId *pId; /* Unique file ID */
290 #endif
291 #ifdef SQLITE_DEBUG
292 /* The next group of variables are used to track whether or not the
293 ** transaction counter in bytes 24-27 of database files are updated
294 ** whenever any part of the database changes. An assertion fault will
295 ** occur if a file is updated without also updating the transaction
296 ** counter. This test is made to avoid new problems similar to the
297 ** one described by ticket #3584.
299 unsigned char transCntrChng; /* True if the transaction counter changed */
300 unsigned char dbUpdate; /* True if any part of database file changed */
301 unsigned char inNormalWrite; /* True if in a normal write operation */
303 #endif
305 #ifdef SQLITE_TEST
306 /* In test mode, increase the size of this structure a bit so that
307 ** it is larger than the struct CrashFile defined in test6.c.
309 char aPadding[32];
310 #endif
313 /* This variable holds the process id (pid) from when the xRandomness()
314 ** method was called. If xOpen() is called from a different process id,
315 ** indicating that a fork() has occurred, the PRNG will be reset.
317 static pid_t randomnessPid = 0;
320 ** Allowed values for the unixFile.ctrlFlags bitmask:
322 #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
323 #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
324 #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
325 #ifndef SQLITE_DISABLE_DIRSYNC
326 # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
327 #else
328 # define UNIXFILE_DIRSYNC 0x00
329 #endif
330 #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
331 #define UNIXFILE_DELETE 0x20 /* Delete on close */
332 #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
333 #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
336 ** Include code that is common to all os_*.c files
338 #include "os_common.h"
341 ** Define various macros that are missing from some systems.
343 #ifndef O_LARGEFILE
344 # define O_LARGEFILE 0
345 #endif
346 #ifdef SQLITE_DISABLE_LFS
347 # undef O_LARGEFILE
348 # define O_LARGEFILE 0
349 #endif
350 #ifndef O_NOFOLLOW
351 # define O_NOFOLLOW 0
352 #endif
353 #ifndef O_BINARY
354 # define O_BINARY 0
355 #endif
358 ** The threadid macro resolves to the thread-id or to 0. Used for
359 ** testing and debugging only.
361 #if SQLITE_THREADSAFE
362 #define threadid pthread_self()
363 #else
364 #define threadid 0
365 #endif
368 ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
370 #if !defined(HAVE_MREMAP)
371 # if defined(__linux__) && defined(_GNU_SOURCE)
372 # define HAVE_MREMAP 1
373 # else
374 # define HAVE_MREMAP 0
375 # endif
376 #endif
379 ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
380 ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
382 #ifdef __ANDROID__
383 # define lseek lseek64
384 #endif
386 #ifdef __linux__
388 ** Linux-specific IOCTL magic numbers used for controlling F2FS
390 #define F2FS_IOCTL_MAGIC 0xf5
391 #define F2FS_IOC_START_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 1)
392 #define F2FS_IOC_COMMIT_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 2)
393 #define F2FS_IOC_START_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 3)
394 #define F2FS_IOC_ABORT_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 5)
395 #define F2FS_IOC_GET_FEATURES _IOR(F2FS_IOCTL_MAGIC, 12, u32)
396 #define F2FS_FEATURE_ATOMIC_WRITE 0x0004
397 #endif /* __linux__ */
401 ** Different Unix systems declare open() in different ways. Same use
402 ** open(const char*,int,mode_t). Others use open(const char*,int,...).
403 ** The difference is important when using a pointer to the function.
405 ** The safest way to deal with the problem is to always use this wrapper
406 ** which always has the same well-defined interface.
408 static int posixOpen(const char *zFile, int flags, int mode){
409 return open(zFile, flags, mode);
412 /* Forward reference */
413 static int openDirectory(const char*, int*);
414 static int unixGetpagesize(void);
417 ** Many system calls are accessed through pointer-to-functions so that
418 ** they may be overridden at runtime to facilitate fault injection during
419 ** testing and sandboxing. The following array holds the names and pointers
420 ** to all overrideable system calls.
422 static struct unix_syscall {
423 const char *zName; /* Name of the system call */
424 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
425 sqlite3_syscall_ptr pDefault; /* Default value */
426 } aSyscall[] = {
427 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
428 #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
430 { "close", (sqlite3_syscall_ptr)close, 0 },
431 #define osClose ((int(*)(int))aSyscall[1].pCurrent)
433 { "access", (sqlite3_syscall_ptr)access, 0 },
434 #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
436 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
437 #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
439 { "stat", (sqlite3_syscall_ptr)stat, 0 },
440 #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
443 ** The DJGPP compiler environment looks mostly like Unix, but it
444 ** lacks the fcntl() system call. So redefine fcntl() to be something
445 ** that always succeeds. This means that locking does not occur under
446 ** DJGPP. But it is DOS - what did you expect?
448 #ifdef __DJGPP__
449 { "fstat", 0, 0 },
450 #define osFstat(a,b,c) 0
451 #else
452 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
453 #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
454 #endif
456 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
457 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
459 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
460 #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
462 { "read", (sqlite3_syscall_ptr)read, 0 },
463 #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
465 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
466 { "pread", (sqlite3_syscall_ptr)pread, 0 },
467 #else
468 { "pread", (sqlite3_syscall_ptr)0, 0 },
469 #endif
470 #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
472 #if defined(USE_PREAD64)
473 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
474 #else
475 { "pread64", (sqlite3_syscall_ptr)0, 0 },
476 #endif
477 #define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
479 { "write", (sqlite3_syscall_ptr)write, 0 },
480 #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
482 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
483 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
484 #else
485 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
486 #endif
487 #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
488 aSyscall[12].pCurrent)
490 #if defined(USE_PREAD64)
491 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
492 #else
493 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
494 #endif
495 #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off64_t))\
496 aSyscall[13].pCurrent)
498 #if defined(HAVE_FCHMOD)
499 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
500 #else
501 { "fchmod", (sqlite3_syscall_ptr)0, 0 },
502 #endif
503 #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
505 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
506 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
507 #else
508 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
509 #endif
510 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
512 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
513 #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
515 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
516 #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
518 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
519 #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
521 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
522 #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
524 #if defined(HAVE_FCHOWN)
525 { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
526 #else
527 { "fchown", (sqlite3_syscall_ptr)0, 0 },
528 #endif
529 #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
531 #if defined(HAVE_FCHOWN)
532 { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
533 #else
534 { "geteuid", (sqlite3_syscall_ptr)0, 0 },
535 #endif
536 #define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
538 #if (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) \
539 && !defined(SQLITE_WASI)
540 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
541 #else
542 { "mmap", (sqlite3_syscall_ptr)0, 0 },
543 #endif
544 #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
546 #if (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) \
547 && !defined(SQLITE_WASI)
548 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
549 #else
550 { "munmap", (sqlite3_syscall_ptr)0, 0 },
551 #endif
552 #define osMunmap ((int(*)(void*,size_t))aSyscall[23].pCurrent)
554 #if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
555 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
556 #else
557 { "mremap", (sqlite3_syscall_ptr)0, 0 },
558 #endif
559 #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
561 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
562 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
563 #else
564 { "getpagesize", (sqlite3_syscall_ptr)0, 0 },
565 #endif
566 #define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
568 #if defined(HAVE_READLINK)
569 { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
570 #else
571 { "readlink", (sqlite3_syscall_ptr)0, 0 },
572 #endif
573 #define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
575 #if defined(HAVE_LSTAT)
576 { "lstat", (sqlite3_syscall_ptr)lstat, 0 },
577 #else
578 { "lstat", (sqlite3_syscall_ptr)0, 0 },
579 #endif
580 #define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
582 #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
583 # ifdef __ANDROID__
584 { "ioctl", (sqlite3_syscall_ptr)(int(*)(int, int, ...))ioctl, 0 },
585 #define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent)
586 # else
587 { "ioctl", (sqlite3_syscall_ptr)ioctl, 0 },
588 #define osIoctl ((int(*)(int,unsigned long,...))aSyscall[28].pCurrent)
589 # endif
590 #else
591 { "ioctl", (sqlite3_syscall_ptr)0, 0 },
592 #endif
594 }; /* End of the overrideable system calls */
598 ** On some systems, calls to fchown() will trigger a message in a security
599 ** log if they come from non-root processes. So avoid calling fchown() if
600 ** we are not running as root.
602 static int robustFchown(int fd, uid_t uid, gid_t gid){
603 #if defined(HAVE_FCHOWN)
604 return osGeteuid() ? 0 : osFchown(fd,uid,gid);
605 #else
606 return 0;
607 #endif
611 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
612 ** "unix" VFSes. Return SQLITE_OK upon successfully updating the
613 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
614 ** system call named zName.
616 static int unixSetSystemCall(
617 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
618 const char *zName, /* Name of system call to override */
619 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
621 unsigned int i;
622 int rc = SQLITE_NOTFOUND;
624 UNUSED_PARAMETER(pNotUsed);
625 if( zName==0 ){
626 /* If no zName is given, restore all system calls to their default
627 ** settings and return NULL
629 rc = SQLITE_OK;
630 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
631 if( aSyscall[i].pDefault ){
632 aSyscall[i].pCurrent = aSyscall[i].pDefault;
635 }else{
636 /* If zName is specified, operate on only the one system call
637 ** specified.
639 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
640 if( strcmp(zName, aSyscall[i].zName)==0 ){
641 if( aSyscall[i].pDefault==0 ){
642 aSyscall[i].pDefault = aSyscall[i].pCurrent;
644 rc = SQLITE_OK;
645 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
646 aSyscall[i].pCurrent = pNewFunc;
647 break;
651 return rc;
655 ** Return the value of a system call. Return NULL if zName is not a
656 ** recognized system call name. NULL is also returned if the system call
657 ** is currently undefined.
659 static sqlite3_syscall_ptr unixGetSystemCall(
660 sqlite3_vfs *pNotUsed,
661 const char *zName
663 unsigned int i;
665 UNUSED_PARAMETER(pNotUsed);
666 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
667 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
669 return 0;
673 ** Return the name of the first system call after zName. If zName==NULL
674 ** then return the name of the first system call. Return NULL if zName
675 ** is the last system call or if zName is not the name of a valid
676 ** system call.
678 static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
679 int i = -1;
681 UNUSED_PARAMETER(p);
682 if( zName ){
683 for(i=0; i<ArraySize(aSyscall)-1; i++){
684 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
687 for(i++; i<ArraySize(aSyscall); i++){
688 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
690 return 0;
694 ** Do not accept any file descriptor less than this value, in order to avoid
695 ** opening database file using file descriptors that are commonly used for
696 ** standard input, output, and error.
698 #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
699 # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
700 #endif
703 ** Invoke open(). Do so multiple times, until it either succeeds or
704 ** fails for some reason other than EINTR.
706 ** If the file creation mode "m" is 0 then set it to the default for
707 ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
708 ** 0644) as modified by the system umask. If m is not 0, then
709 ** make the file creation mode be exactly m ignoring the umask.
711 ** The m parameter will be non-zero only when creating -wal, -journal,
712 ** and -shm files. We want those files to have *exactly* the same
713 ** permissions as their original database, unadulterated by the umask.
714 ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
715 ** transaction crashes and leaves behind hot journals, then any
716 ** process that is able to write to the database will also be able to
717 ** recover the hot journals.
719 static int robust_open(const char *z, int f, mode_t m){
720 int fd;
721 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
722 while(1){
723 #if defined(O_CLOEXEC)
724 fd = osOpen(z,f|O_CLOEXEC,m2);
725 #else
726 fd = osOpen(z,f,m2);
727 #endif
728 if( fd<0 ){
729 if( errno==EINTR ) continue;
730 break;
732 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
733 if( (f & (O_EXCL|O_CREAT))==(O_EXCL|O_CREAT) ){
734 (void)osUnlink(z);
736 osClose(fd);
737 sqlite3_log(SQLITE_WARNING,
738 "attempt to open \"%s\" as file descriptor %d", z, fd);
739 fd = -1;
740 if( osOpen("/dev/null", O_RDONLY, m)<0 ) break;
742 if( fd>=0 ){
743 if( m!=0 ){
744 struct stat statbuf;
745 if( osFstat(fd, &statbuf)==0
746 && statbuf.st_size==0
747 && (statbuf.st_mode&0777)!=m
749 osFchmod(fd, m);
752 #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
753 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
754 #endif
756 return fd;
760 ** Helper functions to obtain and relinquish the global mutex. The
761 ** global mutex is used to protect the unixInodeInfo and
762 ** vxworksFileId objects used by this file, all of which may be
763 ** shared by multiple threads.
765 ** Function unixMutexHeld() is used to assert() that the global mutex
766 ** is held when required. This function is only used as part of assert()
767 ** statements. e.g.
769 ** unixEnterMutex()
770 ** assert( unixMutexHeld() );
771 ** unixEnterLeave()
773 ** To prevent deadlock, the global unixBigLock must must be acquired
774 ** before the unixInodeInfo.pLockMutex mutex, if both are held. It is
775 ** OK to get the pLockMutex without holding unixBigLock first, but if
776 ** that happens, the unixBigLock mutex must not be acquired until after
777 ** pLockMutex is released.
779 ** OK: enter(unixBigLock), enter(pLockInfo)
780 ** OK: enter(unixBigLock)
781 ** OK: enter(pLockInfo)
782 ** ERROR: enter(pLockInfo), enter(unixBigLock)
784 static sqlite3_mutex *unixBigLock = 0;
785 static void unixEnterMutex(void){
786 assert( sqlite3_mutex_notheld(unixBigLock) ); /* Not a recursive mutex */
787 sqlite3_mutex_enter(unixBigLock);
789 static void unixLeaveMutex(void){
790 assert( sqlite3_mutex_held(unixBigLock) );
791 sqlite3_mutex_leave(unixBigLock);
793 #ifdef SQLITE_DEBUG
794 static int unixMutexHeld(void) {
795 return sqlite3_mutex_held(unixBigLock);
797 #endif
800 #ifdef SQLITE_HAVE_OS_TRACE
802 ** Helper function for printing out trace information from debugging
803 ** binaries. This returns the string representation of the supplied
804 ** integer lock-type.
806 static const char *azFileLock(int eFileLock){
807 switch( eFileLock ){
808 case NO_LOCK: return "NONE";
809 case SHARED_LOCK: return "SHARED";
810 case RESERVED_LOCK: return "RESERVED";
811 case PENDING_LOCK: return "PENDING";
812 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
814 return "ERROR";
816 #endif
818 #ifdef SQLITE_LOCK_TRACE
820 ** Print out information about all locking operations.
822 ** This routine is used for troubleshooting locks on multithreaded
823 ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
824 ** command-line option on the compiler. This code is normally
825 ** turned off.
827 static int lockTrace(int fd, int op, struct flock *p){
828 char *zOpName, *zType;
829 int s;
830 int savedErrno;
831 if( op==F_GETLK ){
832 zOpName = "GETLK";
833 }else if( op==F_SETLK ){
834 zOpName = "SETLK";
835 }else{
836 s = osFcntl(fd, op, p);
837 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
838 return s;
840 if( p->l_type==F_RDLCK ){
841 zType = "RDLCK";
842 }else if( p->l_type==F_WRLCK ){
843 zType = "WRLCK";
844 }else if( p->l_type==F_UNLCK ){
845 zType = "UNLCK";
846 }else{
847 assert( 0 );
849 assert( p->l_whence==SEEK_SET );
850 s = osFcntl(fd, op, p);
851 savedErrno = errno;
852 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
853 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
854 (int)p->l_pid, s);
855 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
856 struct flock l2;
857 l2 = *p;
858 osFcntl(fd, F_GETLK, &l2);
859 if( l2.l_type==F_RDLCK ){
860 zType = "RDLCK";
861 }else if( l2.l_type==F_WRLCK ){
862 zType = "WRLCK";
863 }else if( l2.l_type==F_UNLCK ){
864 zType = "UNLCK";
865 }else{
866 assert( 0 );
868 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
869 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
871 errno = savedErrno;
872 return s;
874 #undef osFcntl
875 #define osFcntl lockTrace
876 #endif /* SQLITE_LOCK_TRACE */
879 ** Retry ftruncate() calls that fail due to EINTR
881 ** All calls to ftruncate() within this file should be made through
882 ** this wrapper. On the Android platform, bypassing the logic below
883 ** could lead to a corrupt database.
885 static int robust_ftruncate(int h, sqlite3_int64 sz){
886 int rc;
887 #ifdef __ANDROID__
888 /* On Android, ftruncate() always uses 32-bit offsets, even if
889 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
890 ** truncate a file to any size larger than 2GiB. Silently ignore any
891 ** such attempts. */
892 if( sz>(sqlite3_int64)0x7FFFFFFF ){
893 rc = SQLITE_OK;
894 }else
895 #endif
896 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
897 return rc;
901 ** This routine translates a standard POSIX errno code into something
902 ** useful to the clients of the sqlite3 functions. Specifically, it is
903 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
904 ** and a variety of "please close the file descriptor NOW" errors into
905 ** SQLITE_IOERR
907 ** Errors during initialization of locks, or file system support for locks,
908 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
910 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
911 assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
912 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
913 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
914 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
915 switch (posixError) {
916 case EACCES:
917 case EAGAIN:
918 case ETIMEDOUT:
919 case EBUSY:
920 case EINTR:
921 case ENOLCK:
922 /* random NFS retry error, unless during file system support
923 * introspection, in which it actually means what it says */
924 return SQLITE_BUSY;
926 case EPERM:
927 return SQLITE_PERM;
929 default:
930 return sqliteIOErr;
935 /******************************************************************************
936 ****************** Begin Unique File ID Utility Used By VxWorks ***************
938 ** On most versions of unix, we can get a unique ID for a file by concatenating
939 ** the device number and the inode number. But this does not work on VxWorks.
940 ** On VxWorks, a unique file id must be based on the canonical filename.
942 ** A pointer to an instance of the following structure can be used as a
943 ** unique file ID in VxWorks. Each instance of this structure contains
944 ** a copy of the canonical filename. There is also a reference count.
945 ** The structure is reclaimed when the number of pointers to it drops to
946 ** zero.
948 ** There are never very many files open at one time and lookups are not
949 ** a performance-critical path, so it is sufficient to put these
950 ** structures on a linked list.
952 struct vxworksFileId {
953 struct vxworksFileId *pNext; /* Next in a list of them all */
954 int nRef; /* Number of references to this one */
955 int nName; /* Length of the zCanonicalName[] string */
956 char *zCanonicalName; /* Canonical filename */
959 #if OS_VXWORKS
961 ** All unique filenames are held on a linked list headed by this
962 ** variable:
964 static struct vxworksFileId *vxworksFileList = 0;
967 ** Simplify a filename into its canonical form
968 ** by making the following changes:
970 ** * removing any trailing and duplicate /
971 ** * convert /./ into just /
972 ** * convert /A/../ where A is any simple name into just /
974 ** Changes are made in-place. Return the new name length.
976 ** The original filename is in z[0..n-1]. Return the number of
977 ** characters in the simplified name.
979 static int vxworksSimplifyName(char *z, int n){
980 int i, j;
981 while( n>1 && z[n-1]=='/' ){ n--; }
982 for(i=j=0; i<n; i++){
983 if( z[i]=='/' ){
984 if( z[i+1]=='/' ) continue;
985 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
986 i += 1;
987 continue;
989 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
990 while( j>0 && z[j-1]!='/' ){ j--; }
991 if( j>0 ){ j--; }
992 i += 2;
993 continue;
996 z[j++] = z[i];
998 z[j] = 0;
999 return j;
1003 ** Find a unique file ID for the given absolute pathname. Return
1004 ** a pointer to the vxworksFileId object. This pointer is the unique
1005 ** file ID.
1007 ** The nRef field of the vxworksFileId object is incremented before
1008 ** the object is returned. A new vxworksFileId object is created
1009 ** and added to the global list if necessary.
1011 ** If a memory allocation error occurs, return NULL.
1013 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
1014 struct vxworksFileId *pNew; /* search key and new file ID */
1015 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
1016 int n; /* Length of zAbsoluteName string */
1018 assert( zAbsoluteName[0]=='/' );
1019 n = (int)strlen(zAbsoluteName);
1020 pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
1021 if( pNew==0 ) return 0;
1022 pNew->zCanonicalName = (char*)&pNew[1];
1023 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
1024 n = vxworksSimplifyName(pNew->zCanonicalName, n);
1026 /* Search for an existing entry that matching the canonical name.
1027 ** If found, increment the reference count and return a pointer to
1028 ** the existing file ID.
1030 unixEnterMutex();
1031 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
1032 if( pCandidate->nName==n
1033 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
1035 sqlite3_free(pNew);
1036 pCandidate->nRef++;
1037 unixLeaveMutex();
1038 return pCandidate;
1042 /* No match was found. We will make a new file ID */
1043 pNew->nRef = 1;
1044 pNew->nName = n;
1045 pNew->pNext = vxworksFileList;
1046 vxworksFileList = pNew;
1047 unixLeaveMutex();
1048 return pNew;
1052 ** Decrement the reference count on a vxworksFileId object. Free
1053 ** the object when the reference count reaches zero.
1055 static void vxworksReleaseFileId(struct vxworksFileId *pId){
1056 unixEnterMutex();
1057 assert( pId->nRef>0 );
1058 pId->nRef--;
1059 if( pId->nRef==0 ){
1060 struct vxworksFileId **pp;
1061 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
1062 assert( *pp==pId );
1063 *pp = pId->pNext;
1064 sqlite3_free(pId);
1066 unixLeaveMutex();
1068 #endif /* OS_VXWORKS */
1069 /*************** End of Unique File ID Utility Used By VxWorks ****************
1070 ******************************************************************************/
1073 /******************************************************************************
1074 *************************** Posix Advisory Locking ****************************
1076 ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
1077 ** section 6.5.2.2 lines 483 through 490 specify that when a process
1078 ** sets or clears a lock, that operation overrides any prior locks set
1079 ** by the same process. It does not explicitly say so, but this implies
1080 ** that it overrides locks set by the same process using a different
1081 ** file descriptor. Consider this test case:
1083 ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
1084 ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
1086 ** Suppose ./file1 and ./file2 are really the same file (because
1087 ** one is a hard or symbolic link to the other) then if you set
1088 ** an exclusive lock on fd1, then try to get an exclusive lock
1089 ** on fd2, it works. I would have expected the second lock to
1090 ** fail since there was already a lock on the file due to fd1.
1091 ** But not so. Since both locks came from the same process, the
1092 ** second overrides the first, even though they were on different
1093 ** file descriptors opened on different file names.
1095 ** This means that we cannot use POSIX locks to synchronize file access
1096 ** among competing threads of the same process. POSIX locks will work fine
1097 ** to synchronize access for threads in separate processes, but not
1098 ** threads within the same process.
1100 ** To work around the problem, SQLite has to manage file locks internally
1101 ** on its own. Whenever a new database is opened, we have to find the
1102 ** specific inode of the database file (the inode is determined by the
1103 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
1104 ** and check for locks already existing on that inode. When locks are
1105 ** created or removed, we have to look at our own internal record of the
1106 ** locks to see if another thread has previously set a lock on that same
1107 ** inode.
1109 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
1110 ** For VxWorks, we have to use the alternative unique ID system based on
1111 ** canonical filename and implemented in the previous division.)
1113 ** The sqlite3_file structure for POSIX is no longer just an integer file
1114 ** descriptor. It is now a structure that holds the integer file
1115 ** descriptor and a pointer to a structure that describes the internal
1116 ** locks on the corresponding inode. There is one locking structure
1117 ** per inode, so if the same inode is opened twice, both unixFile structures
1118 ** point to the same locking structure. The locking structure keeps
1119 ** a reference count (so we will know when to delete it) and a "cnt"
1120 ** field that tells us its internal lock status. cnt==0 means the
1121 ** file is unlocked. cnt==-1 means the file has an exclusive lock.
1122 ** cnt>0 means there are cnt shared locks on the file.
1124 ** Any attempt to lock or unlock a file first checks the locking
1125 ** structure. The fcntl() system call is only invoked to set a
1126 ** POSIX lock if the internal lock structure transitions between
1127 ** a locked and an unlocked state.
1129 ** But wait: there are yet more problems with POSIX advisory locks.
1131 ** If you close a file descriptor that points to a file that has locks,
1132 ** all locks on that file that are owned by the current process are
1133 ** released. To work around this problem, each unixInodeInfo object
1134 ** maintains a count of the number of pending locks on the inode.
1135 ** When an attempt is made to close an unixFile, if there are
1136 ** other unixFile open on the same inode that are holding locks, the call
1137 ** to close() the file descriptor is deferred until all of the locks clear.
1138 ** The unixInodeInfo structure keeps a list of file descriptors that need to
1139 ** be closed and that list is walked (and cleared) when the last lock
1140 ** clears.
1142 ** Yet another problem: LinuxThreads do not play well with posix locks.
1144 ** Many older versions of linux use the LinuxThreads library which is
1145 ** not posix compliant. Under LinuxThreads, a lock created by thread
1146 ** A cannot be modified or overridden by a different thread B.
1147 ** Only thread A can modify the lock. Locking behavior is correct
1148 ** if the application uses the newer Native Posix Thread Library (NPTL)
1149 ** on linux - with NPTL a lock created by thread A can override locks
1150 ** in thread B. But there is no way to know at compile-time which
1151 ** threading library is being used. So there is no way to know at
1152 ** compile-time whether or not thread A can override locks on thread B.
1153 ** One has to do a run-time check to discover the behavior of the
1154 ** current process.
1156 ** SQLite used to support LinuxThreads. But support for LinuxThreads
1157 ** was dropped beginning with version 3.7.0. SQLite will still work with
1158 ** LinuxThreads provided that (1) there is no more than one connection
1159 ** per database file in the same process and (2) database connections
1160 ** do not move across threads.
1164 ** An instance of the following structure serves as the key used
1165 ** to locate a particular unixInodeInfo object.
1167 struct unixFileId {
1168 dev_t dev; /* Device number */
1169 #if OS_VXWORKS
1170 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
1171 #else
1172 /* We are told that some versions of Android contain a bug that
1173 ** sizes ino_t at only 32-bits instead of 64-bits. (See
1174 ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
1175 ** To work around this, always allocate 64-bits for the inode number.
1176 ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
1177 ** but that should not be a big deal. */
1178 /* WAS: ino_t ino; */
1179 u64 ino; /* Inode number */
1180 #endif
1184 ** An instance of the following structure is allocated for each open
1185 ** inode.
1187 ** A single inode can have multiple file descriptors, so each unixFile
1188 ** structure contains a pointer to an instance of this object and this
1189 ** object keeps a count of the number of unixFile pointing to it.
1191 ** Mutex rules:
1193 ** (1) Only the pLockMutex mutex must be held in order to read or write
1194 ** any of the locking fields:
1195 ** nShared, nLock, eFileLock, bProcessLock, pUnused
1197 ** (2) When nRef>0, then the following fields are unchanging and can
1198 ** be read (but not written) without holding any mutex:
1199 ** fileId, pLockMutex
1201 ** (3) With the exceptions above, all the fields may only be read
1202 ** or written while holding the global unixBigLock mutex.
1204 ** Deadlock prevention: The global unixBigLock mutex may not
1205 ** be acquired while holding the pLockMutex mutex. If both unixBigLock
1206 ** and pLockMutex are needed, then unixBigLock must be acquired first.
1208 struct unixInodeInfo {
1209 struct unixFileId fileId; /* The lookup key */
1210 sqlite3_mutex *pLockMutex; /* Hold this mutex for... */
1211 int nShared; /* Number of SHARED locks held */
1212 int nLock; /* Number of outstanding file locks */
1213 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1214 unsigned char bProcessLock; /* An exclusive process lock is held */
1215 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1216 int nRef; /* Number of pointers to this structure */
1217 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1218 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1219 unixInodeInfo *pPrev; /* .... doubly linked */
1220 #if SQLITE_ENABLE_LOCKING_STYLE
1221 unsigned long long sharedByte; /* for AFP simulated shared lock */
1222 #endif
1223 #if OS_VXWORKS
1224 sem_t *pSem; /* Named POSIX semaphore */
1225 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
1226 #endif
1230 ** A lists of all unixInodeInfo objects.
1232 ** Must hold unixBigLock in order to read or write this variable.
1234 static unixInodeInfo *inodeList = 0; /* All unixInodeInfo objects */
1236 #ifdef SQLITE_DEBUG
1238 ** True if the inode mutex (on the unixFile.pFileMutex field) is held, or not.
1239 ** This routine is used only within assert() to help verify correct mutex
1240 ** usage.
1242 int unixFileMutexHeld(unixFile *pFile){
1243 assert( pFile->pInode );
1244 return sqlite3_mutex_held(pFile->pInode->pLockMutex);
1246 int unixFileMutexNotheld(unixFile *pFile){
1247 assert( pFile->pInode );
1248 return sqlite3_mutex_notheld(pFile->pInode->pLockMutex);
1250 #endif
1254 ** This function - unixLogErrorAtLine(), is only ever called via the macro
1255 ** unixLogError().
1257 ** It is invoked after an error occurs in an OS function and errno has been
1258 ** set. It logs a message using sqlite3_log() containing the current value of
1259 ** errno and, if possible, the human-readable equivalent from strerror() or
1260 ** strerror_r().
1262 ** The first argument passed to the macro should be the error code that
1263 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1264 ** The two subsequent arguments should be the name of the OS function that
1265 ** failed (e.g. "unlink", "open") and the associated file-system path,
1266 ** if any.
1268 #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1269 static int unixLogErrorAtLine(
1270 int errcode, /* SQLite error code */
1271 const char *zFunc, /* Name of OS function that failed */
1272 const char *zPath, /* File path associated with error */
1273 int iLine /* Source line number where error occurred */
1275 char *zErr; /* Message from strerror() or equivalent */
1276 int iErrno = errno; /* Saved syscall error number */
1278 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1279 ** the strerror() function to obtain the human-readable error message
1280 ** equivalent to errno. Otherwise, use strerror_r().
1282 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1283 char aErr[80];
1284 memset(aErr, 0, sizeof(aErr));
1285 zErr = aErr;
1287 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
1288 ** assume that the system provides the GNU version of strerror_r() that
1289 ** returns a pointer to a buffer containing the error message. That pointer
1290 ** may point to aErr[], or it may point to some static storage somewhere.
1291 ** Otherwise, assume that the system provides the POSIX version of
1292 ** strerror_r(), which always writes an error message into aErr[].
1294 ** If the code incorrectly assumes that it is the POSIX version that is
1295 ** available, the error message will often be an empty string. Not a
1296 ** huge problem. Incorrectly concluding that the GNU version is available
1297 ** could lead to a segfault though.
1299 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1300 zErr =
1301 # endif
1302 strerror_r(iErrno, aErr, sizeof(aErr)-1);
1304 #elif SQLITE_THREADSAFE
1305 /* This is a threadsafe build, but strerror_r() is not available. */
1306 zErr = "";
1307 #else
1308 /* Non-threadsafe build, use strerror(). */
1309 zErr = strerror(iErrno);
1310 #endif
1312 if( zPath==0 ) zPath = "";
1313 sqlite3_log(errcode,
1314 "os_unix.c:%d: (%d) %s(%s) - %s",
1315 iLine, iErrno, zFunc, zPath, zErr
1318 return errcode;
1322 ** Close a file descriptor.
1324 ** We assume that close() almost always works, since it is only in a
1325 ** very sick application or on a very sick platform that it might fail.
1326 ** If it does fail, simply leak the file descriptor, but do log the
1327 ** error.
1329 ** Note that it is not safe to retry close() after EINTR since the
1330 ** file descriptor might have already been reused by another thread.
1331 ** So we don't even try to recover from an EINTR. Just log the error
1332 ** and move on.
1334 static void robust_close(unixFile *pFile, int h, int lineno){
1335 if( osClose(h) ){
1336 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1337 pFile ? pFile->zPath : 0, lineno);
1342 ** Set the pFile->lastErrno. Do this in a subroutine as that provides
1343 ** a convenient place to set a breakpoint.
1345 static void storeLastErrno(unixFile *pFile, int error){
1346 pFile->lastErrno = error;
1350 ** Close all file descriptors accumulated in the unixInodeInfo->pUnused list.
1352 static void closePendingFds(unixFile *pFile){
1353 unixInodeInfo *pInode = pFile->pInode;
1354 UnixUnusedFd *p;
1355 UnixUnusedFd *pNext;
1356 assert( unixFileMutexHeld(pFile) );
1357 for(p=pInode->pUnused; p; p=pNext){
1358 pNext = p->pNext;
1359 robust_close(pFile, p->fd, __LINE__);
1360 sqlite3_free(p);
1362 pInode->pUnused = 0;
1366 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
1368 ** The global mutex must be held when this routine is called, but the mutex
1369 ** on the inode being deleted must NOT be held.
1371 static void releaseInodeInfo(unixFile *pFile){
1372 unixInodeInfo *pInode = pFile->pInode;
1373 assert( unixMutexHeld() );
1374 assert( unixFileMutexNotheld(pFile) );
1375 if( ALWAYS(pInode) ){
1376 pInode->nRef--;
1377 if( pInode->nRef==0 ){
1378 assert( pInode->pShmNode==0 );
1379 sqlite3_mutex_enter(pInode->pLockMutex);
1380 closePendingFds(pFile);
1381 sqlite3_mutex_leave(pInode->pLockMutex);
1382 if( pInode->pPrev ){
1383 assert( pInode->pPrev->pNext==pInode );
1384 pInode->pPrev->pNext = pInode->pNext;
1385 }else{
1386 assert( inodeList==pInode );
1387 inodeList = pInode->pNext;
1389 if( pInode->pNext ){
1390 assert( pInode->pNext->pPrev==pInode );
1391 pInode->pNext->pPrev = pInode->pPrev;
1393 sqlite3_mutex_free(pInode->pLockMutex);
1394 sqlite3_free(pInode);
1400 ** Given a file descriptor, locate the unixInodeInfo object that
1401 ** describes that file descriptor. Create a new one if necessary. The
1402 ** return value might be uninitialized if an error occurs.
1404 ** The global mutex must held when calling this routine.
1406 ** Return an appropriate error code.
1408 static int findInodeInfo(
1409 unixFile *pFile, /* Unix file with file desc used in the key */
1410 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
1412 int rc; /* System call return code */
1413 int fd; /* The file descriptor for pFile */
1414 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1415 struct stat statbuf; /* Low-level file information */
1416 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
1418 assert( unixMutexHeld() );
1420 /* Get low-level information about the file that we can used to
1421 ** create a unique name for the file.
1423 fd = pFile->h;
1424 rc = osFstat(fd, &statbuf);
1425 if( rc!=0 ){
1426 storeLastErrno(pFile, errno);
1427 #if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
1428 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1429 #endif
1430 return SQLITE_IOERR;
1433 #ifdef __APPLE__
1434 /* On OS X on an msdos filesystem, the inode number is reported
1435 ** incorrectly for zero-size files. See ticket #3260. To work
1436 ** around this problem (we consider it a bug in OS X, not SQLite)
1437 ** we always increase the file size to 1 by writing a single byte
1438 ** prior to accessing the inode number. The one byte written is
1439 ** an ASCII 'S' character which also happens to be the first byte
1440 ** in the header of every SQLite database. In this way, if there
1441 ** is a race condition such that another thread has already populated
1442 ** the first page of the database, no damage is done.
1444 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
1445 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
1446 if( rc!=1 ){
1447 storeLastErrno(pFile, errno);
1448 return SQLITE_IOERR;
1450 rc = osFstat(fd, &statbuf);
1451 if( rc!=0 ){
1452 storeLastErrno(pFile, errno);
1453 return SQLITE_IOERR;
1456 #endif
1458 memset(&fileId, 0, sizeof(fileId));
1459 fileId.dev = statbuf.st_dev;
1460 #if OS_VXWORKS
1461 fileId.pId = pFile->pId;
1462 #else
1463 fileId.ino = (u64)statbuf.st_ino;
1464 #endif
1465 assert( unixMutexHeld() );
1466 pInode = inodeList;
1467 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1468 pInode = pInode->pNext;
1470 if( pInode==0 ){
1471 pInode = sqlite3_malloc64( sizeof(*pInode) );
1472 if( pInode==0 ){
1473 return SQLITE_NOMEM_BKPT;
1475 memset(pInode, 0, sizeof(*pInode));
1476 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1477 if( sqlite3GlobalConfig.bCoreMutex ){
1478 pInode->pLockMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
1479 if( pInode->pLockMutex==0 ){
1480 sqlite3_free(pInode);
1481 return SQLITE_NOMEM_BKPT;
1484 pInode->nRef = 1;
1485 assert( unixMutexHeld() );
1486 pInode->pNext = inodeList;
1487 pInode->pPrev = 0;
1488 if( inodeList ) inodeList->pPrev = pInode;
1489 inodeList = pInode;
1490 }else{
1491 pInode->nRef++;
1493 *ppInode = pInode;
1494 return SQLITE_OK;
1498 ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1500 static int fileHasMoved(unixFile *pFile){
1501 #if OS_VXWORKS
1502 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1503 #else
1504 struct stat buf;
1505 return pFile->pInode!=0 &&
1506 (osStat(pFile->zPath, &buf)!=0
1507 || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
1508 #endif
1513 ** Check a unixFile that is a database. Verify the following:
1515 ** (1) There is exactly one hard link on the file
1516 ** (2) The file is not a symbolic link
1517 ** (3) The file has not been renamed or unlinked
1519 ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1521 static void verifyDbFile(unixFile *pFile){
1522 struct stat buf;
1523 int rc;
1525 /* These verifications occurs for the main database only */
1526 if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
1528 rc = osFstat(pFile->h, &buf);
1529 if( rc!=0 ){
1530 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
1531 return;
1533 if( buf.st_nlink==0 ){
1534 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
1535 return;
1537 if( buf.st_nlink>1 ){
1538 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
1539 return;
1541 if( fileHasMoved(pFile) ){
1542 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
1543 return;
1549 ** This routine checks if there is a RESERVED lock held on the specified
1550 ** file by this or any other process. If such a lock is held, set *pResOut
1551 ** to a non-zero value otherwise *pResOut is set to zero. The return value
1552 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1554 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
1555 int rc = SQLITE_OK;
1556 int reserved = 0;
1557 unixFile *pFile = (unixFile*)id;
1559 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1561 assert( pFile );
1562 assert( pFile->eFileLock<=SHARED_LOCK );
1563 sqlite3_mutex_enter(pFile->pInode->pLockMutex);
1565 /* Check if a thread in this process holds such a lock */
1566 if( pFile->pInode->eFileLock>SHARED_LOCK ){
1567 reserved = 1;
1570 /* Otherwise see if some other process holds it.
1572 #ifndef __DJGPP__
1573 if( !reserved && !pFile->pInode->bProcessLock ){
1574 struct flock lock;
1575 lock.l_whence = SEEK_SET;
1576 lock.l_start = RESERVED_BYTE;
1577 lock.l_len = 1;
1578 lock.l_type = F_WRLCK;
1579 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1580 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1581 storeLastErrno(pFile, errno);
1582 } else if( lock.l_type!=F_UNLCK ){
1583 reserved = 1;
1586 #endif
1588 sqlite3_mutex_leave(pFile->pInode->pLockMutex);
1589 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
1591 *pResOut = reserved;
1592 return rc;
1595 /* Forward declaration*/
1596 static int unixSleep(sqlite3_vfs*,int);
1599 ** Set a posix-advisory-lock.
1601 ** There are two versions of this routine. If compiled with
1602 ** SQLITE_ENABLE_SETLK_TIMEOUT then the routine has an extra parameter
1603 ** which is a pointer to a unixFile. If the unixFile->iBusyTimeout
1604 ** value is set, then it is the number of milliseconds to wait before
1605 ** failing the lock. The iBusyTimeout value is always reset back to
1606 ** zero on each call.
1608 ** If SQLITE_ENABLE_SETLK_TIMEOUT is not defined, then do a non-blocking
1609 ** attempt to set the lock.
1611 #ifndef SQLITE_ENABLE_SETLK_TIMEOUT
1612 # define osSetPosixAdvisoryLock(h,x,t) osFcntl(h,F_SETLK,x)
1613 #else
1614 static int osSetPosixAdvisoryLock(
1615 int h, /* The file descriptor on which to take the lock */
1616 struct flock *pLock, /* The description of the lock */
1617 unixFile *pFile /* Structure holding timeout value */
1619 int tm = pFile->iBusyTimeout;
1620 int rc = osFcntl(h,F_SETLK,pLock);
1621 while( rc<0 && tm>0 ){
1622 /* On systems that support some kind of blocking file lock with a timeout,
1623 ** make appropriate changes here to invoke that blocking file lock. On
1624 ** generic posix, however, there is no such API. So we simply try the
1625 ** lock once every millisecond until either the timeout expires, or until
1626 ** the lock is obtained. */
1627 unixSleep(0,1000);
1628 rc = osFcntl(h,F_SETLK,pLock);
1629 tm--;
1631 return rc;
1633 #endif /* SQLITE_ENABLE_SETLK_TIMEOUT */
1637 ** Attempt to set a system-lock on the file pFile. The lock is
1638 ** described by pLock.
1640 ** If the pFile was opened read/write from unix-excl, then the only lock
1641 ** ever obtained is an exclusive lock, and it is obtained exactly once
1642 ** the first time any lock is attempted. All subsequent system locking
1643 ** operations become no-ops. Locking operations still happen internally,
1644 ** in order to coordinate access between separate database connections
1645 ** within this process, but all of that is handled in memory and the
1646 ** operating system does not participate.
1648 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1649 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1650 ** and is read-only.
1652 ** Zero is returned if the call completes successfully, or -1 if a call
1653 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
1655 static int unixFileLock(unixFile *pFile, struct flock *pLock){
1656 int rc;
1657 unixInodeInfo *pInode = pFile->pInode;
1658 assert( pInode!=0 );
1659 assert( sqlite3_mutex_held(pInode->pLockMutex) );
1660 if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
1661 if( pInode->bProcessLock==0 ){
1662 struct flock lock;
1663 assert( pInode->nLock==0 );
1664 lock.l_whence = SEEK_SET;
1665 lock.l_start = SHARED_FIRST;
1666 lock.l_len = SHARED_SIZE;
1667 lock.l_type = F_WRLCK;
1668 rc = osSetPosixAdvisoryLock(pFile->h, &lock, pFile);
1669 if( rc<0 ) return rc;
1670 pInode->bProcessLock = 1;
1671 pInode->nLock++;
1672 }else{
1673 rc = 0;
1675 }else{
1676 rc = osSetPosixAdvisoryLock(pFile->h, pLock, pFile);
1678 return rc;
1682 ** Lock the file with the lock specified by parameter eFileLock - one
1683 ** of the following:
1685 ** (1) SHARED_LOCK
1686 ** (2) RESERVED_LOCK
1687 ** (3) PENDING_LOCK
1688 ** (4) EXCLUSIVE_LOCK
1690 ** Sometimes when requesting one lock state, additional lock states
1691 ** are inserted in between. The locking might fail on one of the later
1692 ** transitions leaving the lock state different from what it started but
1693 ** still short of its goal. The following chart shows the allowed
1694 ** transitions and the inserted intermediate states:
1696 ** UNLOCKED -> SHARED
1697 ** SHARED -> RESERVED
1698 ** SHARED -> EXCLUSIVE
1699 ** RESERVED -> (PENDING) -> EXCLUSIVE
1700 ** PENDING -> EXCLUSIVE
1702 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
1703 ** routine to lower a locking level.
1705 static int unixLock(sqlite3_file *id, int eFileLock){
1706 /* The following describes the implementation of the various locks and
1707 ** lock transitions in terms of the POSIX advisory shared and exclusive
1708 ** lock primitives (called read-locks and write-locks below, to avoid
1709 ** confusion with SQLite lock names). The algorithms are complicated
1710 ** slightly in order to be compatible with Windows95 systems simultaneously
1711 ** accessing the same database file, in case that is ever required.
1713 ** Symbols defined in os.h identify the 'pending byte' and the 'reserved
1714 ** byte', each single bytes at well known offsets, and the 'shared byte
1715 ** range', a range of 510 bytes at a well known offset.
1717 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1718 ** byte'. If this is successful, 'shared byte range' is read-locked
1719 ** and the lock on the 'pending byte' released. (Legacy note: When
1720 ** SQLite was first developed, Windows95 systems were still very common,
1721 ** and Windows95 lacks a shared-lock capability. So on Windows95, a
1722 ** single randomly selected by from the 'shared byte range' is locked.
1723 ** Windows95 is now pretty much extinct, but this work-around for the
1724 ** lack of shared-locks on Windows95 lives on, for backwards
1725 ** compatibility.)
1727 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1728 ** A RESERVED lock is implemented by grabbing a write-lock on the
1729 ** 'reserved byte'.
1731 ** An EXCLUSIVE lock may only be requested after either a SHARED or
1732 ** RESERVED lock is held. An EXCLUSIVE lock is implemented by obtaining
1733 ** a write-lock on the entire 'shared byte range'. Since all other locks
1734 ** require a read-lock on one of the bytes within this range, this ensures
1735 ** that no other locks are held on the database.
1737 ** If a process that holds a RESERVED lock requests an EXCLUSIVE, then
1738 ** a PENDING lock is obtained first. A PENDING lock is implemented by
1739 ** obtaining a write-lock on the 'pending byte'. This ensures that no new
1740 ** SHARED locks can be obtained, but existing SHARED locks are allowed to
1741 ** persist. If the call to this function fails to obtain the EXCLUSIVE
1742 ** lock in this case, it holds the PENDING lock instead. The client may
1743 ** then re-attempt the EXCLUSIVE lock later on, after existing SHARED
1744 ** locks have cleared.
1746 int rc = SQLITE_OK;
1747 unixFile *pFile = (unixFile*)id;
1748 unixInodeInfo *pInode;
1749 struct flock lock;
1750 int tErrno = 0;
1752 assert( pFile );
1753 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1754 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
1755 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
1756 osGetpid(0)));
1758 /* If there is already a lock of this type or more restrictive on the
1759 ** unixFile, do nothing. Don't use the end_lock: exit path, as
1760 ** unixEnterMutex() hasn't been called yet.
1762 if( pFile->eFileLock>=eFileLock ){
1763 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1764 azFileLock(eFileLock)));
1765 return SQLITE_OK;
1768 /* Make sure the locking sequence is correct.
1769 ** (1) We never move from unlocked to anything higher than shared lock.
1770 ** (2) SQLite never explicitly requests a pending lock.
1771 ** (3) A shared lock is always held when a reserve lock is requested.
1773 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1774 assert( eFileLock!=PENDING_LOCK );
1775 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
1777 /* This mutex is needed because pFile->pInode is shared across threads
1779 pInode = pFile->pInode;
1780 sqlite3_mutex_enter(pInode->pLockMutex);
1782 /* If some thread using this PID has a lock via a different unixFile*
1783 ** handle that precludes the requested lock, return BUSY.
1785 if( (pFile->eFileLock!=pInode->eFileLock &&
1786 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
1788 rc = SQLITE_BUSY;
1789 goto end_lock;
1792 /* If a SHARED lock is requested, and some thread using this PID already
1793 ** has a SHARED or RESERVED lock, then increment reference counts and
1794 ** return SQLITE_OK.
1796 if( eFileLock==SHARED_LOCK &&
1797 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
1798 assert( eFileLock==SHARED_LOCK );
1799 assert( pFile->eFileLock==0 );
1800 assert( pInode->nShared>0 );
1801 pFile->eFileLock = SHARED_LOCK;
1802 pInode->nShared++;
1803 pInode->nLock++;
1804 goto end_lock;
1808 /* A PENDING lock is needed before acquiring a SHARED lock and before
1809 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1810 ** be released.
1812 lock.l_len = 1L;
1813 lock.l_whence = SEEK_SET;
1814 if( eFileLock==SHARED_LOCK
1815 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock==RESERVED_LOCK)
1817 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
1818 lock.l_start = PENDING_BYTE;
1819 if( unixFileLock(pFile, &lock) ){
1820 tErrno = errno;
1821 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1822 if( rc!=SQLITE_BUSY ){
1823 storeLastErrno(pFile, tErrno);
1825 goto end_lock;
1826 }else if( eFileLock==EXCLUSIVE_LOCK ){
1827 pFile->eFileLock = PENDING_LOCK;
1828 pInode->eFileLock = PENDING_LOCK;
1833 /* If control gets to this point, then actually go ahead and make
1834 ** operating system calls for the specified lock.
1836 if( eFileLock==SHARED_LOCK ){
1837 assert( pInode->nShared==0 );
1838 assert( pInode->eFileLock==0 );
1839 assert( rc==SQLITE_OK );
1841 /* Now get the read-lock */
1842 lock.l_start = SHARED_FIRST;
1843 lock.l_len = SHARED_SIZE;
1844 if( unixFileLock(pFile, &lock) ){
1845 tErrno = errno;
1846 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1849 /* Drop the temporary PENDING lock */
1850 lock.l_start = PENDING_BYTE;
1851 lock.l_len = 1L;
1852 lock.l_type = F_UNLCK;
1853 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1854 /* This could happen with a network mount */
1855 tErrno = errno;
1856 rc = SQLITE_IOERR_UNLOCK;
1859 if( rc ){
1860 if( rc!=SQLITE_BUSY ){
1861 storeLastErrno(pFile, tErrno);
1863 goto end_lock;
1864 }else{
1865 pFile->eFileLock = SHARED_LOCK;
1866 pInode->nLock++;
1867 pInode->nShared = 1;
1869 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
1870 /* We are trying for an exclusive lock but another thread in this
1871 ** same process is still holding a shared lock. */
1872 rc = SQLITE_BUSY;
1873 }else{
1874 /* The request was for a RESERVED or EXCLUSIVE lock. It is
1875 ** assumed that there is a SHARED or greater lock on the file
1876 ** already.
1878 assert( 0!=pFile->eFileLock );
1879 lock.l_type = F_WRLCK;
1881 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1882 if( eFileLock==RESERVED_LOCK ){
1883 lock.l_start = RESERVED_BYTE;
1884 lock.l_len = 1L;
1885 }else{
1886 lock.l_start = SHARED_FIRST;
1887 lock.l_len = SHARED_SIZE;
1890 if( unixFileLock(pFile, &lock) ){
1891 tErrno = errno;
1892 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1893 if( rc!=SQLITE_BUSY ){
1894 storeLastErrno(pFile, tErrno);
1900 #ifdef SQLITE_DEBUG
1901 /* Set up the transaction-counter change checking flags when
1902 ** transitioning from a SHARED to a RESERVED lock. The change
1903 ** from SHARED to RESERVED marks the beginning of a normal
1904 ** write operation (not a hot journal rollback).
1906 if( rc==SQLITE_OK
1907 && pFile->eFileLock<=SHARED_LOCK
1908 && eFileLock==RESERVED_LOCK
1910 pFile->transCntrChng = 0;
1911 pFile->dbUpdate = 0;
1912 pFile->inNormalWrite = 1;
1914 #endif
1916 if( rc==SQLITE_OK ){
1917 pFile->eFileLock = eFileLock;
1918 pInode->eFileLock = eFileLock;
1921 end_lock:
1922 sqlite3_mutex_leave(pInode->pLockMutex);
1923 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1924 rc==SQLITE_OK ? "ok" : "failed"));
1925 return rc;
1929 ** Add the file descriptor used by file handle pFile to the corresponding
1930 ** pUnused list.
1932 static void setPendingFd(unixFile *pFile){
1933 unixInodeInfo *pInode = pFile->pInode;
1934 UnixUnusedFd *p = pFile->pPreallocatedUnused;
1935 assert( unixFileMutexHeld(pFile) );
1936 p->pNext = pInode->pUnused;
1937 pInode->pUnused = p;
1938 pFile->h = -1;
1939 pFile->pPreallocatedUnused = 0;
1943 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
1944 ** must be either NO_LOCK or SHARED_LOCK.
1946 ** If the locking level of the file descriptor is already at or below
1947 ** the requested locking level, this routine is a no-op.
1949 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1950 ** the byte range is divided into 2 parts and the first part is unlocked then
1951 ** set to a read lock, then the other part is simply unlocked. This works
1952 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1953 ** remove the write lock on a region when a read lock is set.
1955 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
1956 unixFile *pFile = (unixFile*)id;
1957 unixInodeInfo *pInode;
1958 struct flock lock;
1959 int rc = SQLITE_OK;
1961 assert( pFile );
1962 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
1963 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
1964 osGetpid(0)));
1966 assert( eFileLock<=SHARED_LOCK );
1967 if( pFile->eFileLock<=eFileLock ){
1968 return SQLITE_OK;
1970 pInode = pFile->pInode;
1971 sqlite3_mutex_enter(pInode->pLockMutex);
1972 assert( pInode->nShared!=0 );
1973 if( pFile->eFileLock>SHARED_LOCK ){
1974 assert( pInode->eFileLock==pFile->eFileLock );
1976 #ifdef SQLITE_DEBUG
1977 /* When reducing a lock such that other processes can start
1978 ** reading the database file again, make sure that the
1979 ** transaction counter was updated if any part of the database
1980 ** file changed. If the transaction counter is not updated,
1981 ** other connections to the same file might not realize that
1982 ** the file has changed and hence might not know to flush their
1983 ** cache. The use of a stale cache can lead to database corruption.
1985 pFile->inNormalWrite = 0;
1986 #endif
1988 /* downgrading to a shared lock on NFS involves clearing the write lock
1989 ** before establishing the readlock - to avoid a race condition we downgrade
1990 ** the lock in 2 blocks, so that part of the range will be covered by a
1991 ** write lock until the rest is covered by a read lock:
1992 ** 1: [WWWWW]
1993 ** 2: [....W]
1994 ** 3: [RRRRW]
1995 ** 4: [RRRR.]
1997 if( eFileLock==SHARED_LOCK ){
1998 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
1999 (void)handleNFSUnlock;
2000 assert( handleNFSUnlock==0 );
2001 #endif
2002 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2003 if( handleNFSUnlock ){
2004 int tErrno; /* Error code from system call errors */
2005 off_t divSize = SHARED_SIZE - 1;
2007 lock.l_type = F_UNLCK;
2008 lock.l_whence = SEEK_SET;
2009 lock.l_start = SHARED_FIRST;
2010 lock.l_len = divSize;
2011 if( unixFileLock(pFile, &lock)==(-1) ){
2012 tErrno = errno;
2013 rc = SQLITE_IOERR_UNLOCK;
2014 storeLastErrno(pFile, tErrno);
2015 goto end_unlock;
2017 lock.l_type = F_RDLCK;
2018 lock.l_whence = SEEK_SET;
2019 lock.l_start = SHARED_FIRST;
2020 lock.l_len = divSize;
2021 if( unixFileLock(pFile, &lock)==(-1) ){
2022 tErrno = errno;
2023 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
2024 if( IS_LOCK_ERROR(rc) ){
2025 storeLastErrno(pFile, tErrno);
2027 goto end_unlock;
2029 lock.l_type = F_UNLCK;
2030 lock.l_whence = SEEK_SET;
2031 lock.l_start = SHARED_FIRST+divSize;
2032 lock.l_len = SHARED_SIZE-divSize;
2033 if( unixFileLock(pFile, &lock)==(-1) ){
2034 tErrno = errno;
2035 rc = SQLITE_IOERR_UNLOCK;
2036 storeLastErrno(pFile, tErrno);
2037 goto end_unlock;
2039 }else
2040 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2042 lock.l_type = F_RDLCK;
2043 lock.l_whence = SEEK_SET;
2044 lock.l_start = SHARED_FIRST;
2045 lock.l_len = SHARED_SIZE;
2046 if( unixFileLock(pFile, &lock) ){
2047 /* In theory, the call to unixFileLock() cannot fail because another
2048 ** process is holding an incompatible lock. If it does, this
2049 ** indicates that the other process is not following the locking
2050 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
2051 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
2052 ** an assert to fail). */
2053 rc = SQLITE_IOERR_RDLOCK;
2054 storeLastErrno(pFile, errno);
2055 goto end_unlock;
2059 lock.l_type = F_UNLCK;
2060 lock.l_whence = SEEK_SET;
2061 lock.l_start = PENDING_BYTE;
2062 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
2063 if( unixFileLock(pFile, &lock)==0 ){
2064 pInode->eFileLock = SHARED_LOCK;
2065 }else{
2066 rc = SQLITE_IOERR_UNLOCK;
2067 storeLastErrno(pFile, errno);
2068 goto end_unlock;
2071 if( eFileLock==NO_LOCK ){
2072 /* Decrement the shared lock counter. Release the lock using an
2073 ** OS call only when all threads in this same process have released
2074 ** the lock.
2076 pInode->nShared--;
2077 if( pInode->nShared==0 ){
2078 lock.l_type = F_UNLCK;
2079 lock.l_whence = SEEK_SET;
2080 lock.l_start = lock.l_len = 0L;
2081 if( unixFileLock(pFile, &lock)==0 ){
2082 pInode->eFileLock = NO_LOCK;
2083 }else{
2084 rc = SQLITE_IOERR_UNLOCK;
2085 storeLastErrno(pFile, errno);
2086 pInode->eFileLock = NO_LOCK;
2087 pFile->eFileLock = NO_LOCK;
2091 /* Decrement the count of locks against this same file. When the
2092 ** count reaches zero, close any other file descriptors whose close
2093 ** was deferred because of outstanding locks.
2095 pInode->nLock--;
2096 assert( pInode->nLock>=0 );
2097 if( pInode->nLock==0 ) closePendingFds(pFile);
2100 end_unlock:
2101 sqlite3_mutex_leave(pInode->pLockMutex);
2102 if( rc==SQLITE_OK ){
2103 pFile->eFileLock = eFileLock;
2105 return rc;
2109 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
2110 ** must be either NO_LOCK or SHARED_LOCK.
2112 ** If the locking level of the file descriptor is already at or below
2113 ** the requested locking level, this routine is a no-op.
2115 static int unixUnlock(sqlite3_file *id, int eFileLock){
2116 #if SQLITE_MAX_MMAP_SIZE>0
2117 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
2118 #endif
2119 return posixUnlock(id, eFileLock, 0);
2122 #if SQLITE_MAX_MMAP_SIZE>0
2123 static int unixMapfile(unixFile *pFd, i64 nByte);
2124 static void unixUnmapfile(unixFile *pFd);
2125 #endif
2128 ** This function performs the parts of the "close file" operation
2129 ** common to all locking schemes. It closes the directory and file
2130 ** handles, if they are valid, and sets all fields of the unixFile
2131 ** structure to 0.
2133 ** It is *not* necessary to hold the mutex when this routine is called,
2134 ** even on VxWorks. A mutex will be acquired on VxWorks by the
2135 ** vxworksReleaseFileId() routine.
2137 static int closeUnixFile(sqlite3_file *id){
2138 unixFile *pFile = (unixFile*)id;
2139 #if SQLITE_MAX_MMAP_SIZE>0
2140 unixUnmapfile(pFile);
2141 #endif
2142 if( pFile->h>=0 ){
2143 robust_close(pFile, pFile->h, __LINE__);
2144 pFile->h = -1;
2146 #if OS_VXWORKS
2147 if( pFile->pId ){
2148 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
2149 osUnlink(pFile->pId->zCanonicalName);
2151 vxworksReleaseFileId(pFile->pId);
2152 pFile->pId = 0;
2154 #endif
2155 #ifdef SQLITE_UNLINK_AFTER_CLOSE
2156 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
2157 osUnlink(pFile->zPath);
2158 sqlite3_free(*(char**)&pFile->zPath);
2159 pFile->zPath = 0;
2161 #endif
2162 OSTRACE(("CLOSE %-3d\n", pFile->h));
2163 OpenCounter(-1);
2164 sqlite3_free(pFile->pPreallocatedUnused);
2165 memset(pFile, 0, sizeof(unixFile));
2166 return SQLITE_OK;
2170 ** Close a file.
2172 static int unixClose(sqlite3_file *id){
2173 int rc = SQLITE_OK;
2174 unixFile *pFile = (unixFile *)id;
2175 unixInodeInfo *pInode = pFile->pInode;
2177 assert( pInode!=0 );
2178 verifyDbFile(pFile);
2179 unixUnlock(id, NO_LOCK);
2180 assert( unixFileMutexNotheld(pFile) );
2181 unixEnterMutex();
2183 /* unixFile.pInode is always valid here. Otherwise, a different close
2184 ** routine (e.g. nolockClose()) would be called instead.
2186 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
2187 sqlite3_mutex_enter(pInode->pLockMutex);
2188 if( pInode->nLock ){
2189 /* If there are outstanding locks, do not actually close the file just
2190 ** yet because that would clear those locks. Instead, add the file
2191 ** descriptor to pInode->pUnused list. It will be automatically closed
2192 ** when the last lock is cleared.
2194 setPendingFd(pFile);
2196 sqlite3_mutex_leave(pInode->pLockMutex);
2197 releaseInodeInfo(pFile);
2198 assert( pFile->pShm==0 );
2199 rc = closeUnixFile(id);
2200 unixLeaveMutex();
2201 return rc;
2204 /************** End of the posix advisory lock implementation *****************
2205 ******************************************************************************/
2207 /******************************************************************************
2208 ****************************** No-op Locking **********************************
2210 ** Of the various locking implementations available, this is by far the
2211 ** simplest: locking is ignored. No attempt is made to lock the database
2212 ** file for reading or writing.
2214 ** This locking mode is appropriate for use on read-only databases
2215 ** (ex: databases that are burned into CD-ROM, for example.) It can
2216 ** also be used if the application employs some external mechanism to
2217 ** prevent simultaneous access of the same database by two or more
2218 ** database connections. But there is a serious risk of database
2219 ** corruption if this locking mode is used in situations where multiple
2220 ** database connections are accessing the same database file at the same
2221 ** time and one or more of those connections are writing.
2224 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
2225 UNUSED_PARAMETER(NotUsed);
2226 *pResOut = 0;
2227 return SQLITE_OK;
2229 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
2230 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2231 return SQLITE_OK;
2233 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
2234 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2235 return SQLITE_OK;
2239 ** Close the file.
2241 static int nolockClose(sqlite3_file *id) {
2242 return closeUnixFile(id);
2245 /******************* End of the no-op lock implementation *********************
2246 ******************************************************************************/
2248 /******************************************************************************
2249 ************************* Begin dot-file Locking ******************************
2251 ** The dotfile locking implementation uses the existence of separate lock
2252 ** files (really a directory) to control access to the database. This works
2253 ** on just about every filesystem imaginable. But there are serious downsides:
2255 ** (1) There is zero concurrency. A single reader blocks all other
2256 ** connections from reading or writing the database.
2258 ** (2) An application crash or power loss can leave stale lock files
2259 ** sitting around that need to be cleared manually.
2261 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
2262 ** other locking strategy is available.
2264 ** Dotfile locking works by creating a subdirectory in the same directory as
2265 ** the database and with the same name but with a ".lock" extension added.
2266 ** The existence of a lock directory implies an EXCLUSIVE lock. All other
2267 ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
2271 ** The file suffix added to the data base filename in order to create the
2272 ** lock directory.
2274 #define DOTLOCK_SUFFIX ".lock"
2277 ** This routine checks if there is a RESERVED lock held on the specified
2278 ** file by this or any other process. If such a lock is held, set *pResOut
2279 ** to a non-zero value otherwise *pResOut is set to zero. The return value
2280 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2282 ** In dotfile locking, either a lock exists or it does not. So in this
2283 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
2284 ** is held on the file and false if the file is unlocked.
2286 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2287 int rc = SQLITE_OK;
2288 int reserved = 0;
2289 unixFile *pFile = (unixFile*)id;
2291 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2293 assert( pFile );
2294 reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
2295 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
2296 *pResOut = reserved;
2297 return rc;
2301 ** Lock the file with the lock specified by parameter eFileLock - one
2302 ** of the following:
2304 ** (1) SHARED_LOCK
2305 ** (2) RESERVED_LOCK
2306 ** (3) PENDING_LOCK
2307 ** (4) EXCLUSIVE_LOCK
2309 ** Sometimes when requesting one lock state, additional lock states
2310 ** are inserted in between. The locking might fail on one of the later
2311 ** transitions leaving the lock state different from what it started but
2312 ** still short of its goal. The following chart shows the allowed
2313 ** transitions and the inserted intermediate states:
2315 ** UNLOCKED -> SHARED
2316 ** SHARED -> RESERVED
2317 ** SHARED -> (PENDING) -> EXCLUSIVE
2318 ** RESERVED -> (PENDING) -> EXCLUSIVE
2319 ** PENDING -> EXCLUSIVE
2321 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
2322 ** routine to lower a locking level.
2324 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
2325 ** But we track the other locking levels internally.
2327 static int dotlockLock(sqlite3_file *id, int eFileLock) {
2328 unixFile *pFile = (unixFile*)id;
2329 char *zLockFile = (char *)pFile->lockingContext;
2330 int rc = SQLITE_OK;
2333 /* If we have any lock, then the lock file already exists. All we have
2334 ** to do is adjust our internal record of the lock level.
2336 if( pFile->eFileLock > NO_LOCK ){
2337 pFile->eFileLock = eFileLock;
2338 /* Always update the timestamp on the old file */
2339 #ifdef HAVE_UTIME
2340 utime(zLockFile, NULL);
2341 #else
2342 utimes(zLockFile, NULL);
2343 #endif
2344 return SQLITE_OK;
2347 /* grab an exclusive lock */
2348 rc = osMkdir(zLockFile, 0777);
2349 if( rc<0 ){
2350 /* failed to open/create the lock directory */
2351 int tErrno = errno;
2352 if( EEXIST == tErrno ){
2353 rc = SQLITE_BUSY;
2354 } else {
2355 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2356 if( rc!=SQLITE_BUSY ){
2357 storeLastErrno(pFile, tErrno);
2360 return rc;
2363 /* got it, set the type and return ok */
2364 pFile->eFileLock = eFileLock;
2365 return rc;
2369 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
2370 ** must be either NO_LOCK or SHARED_LOCK.
2372 ** If the locking level of the file descriptor is already at or below
2373 ** the requested locking level, this routine is a no-op.
2375 ** When the locking level reaches NO_LOCK, delete the lock file.
2377 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
2378 unixFile *pFile = (unixFile*)id;
2379 char *zLockFile = (char *)pFile->lockingContext;
2380 int rc;
2382 assert( pFile );
2383 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
2384 pFile->eFileLock, osGetpid(0)));
2385 assert( eFileLock<=SHARED_LOCK );
2387 /* no-op if possible */
2388 if( pFile->eFileLock==eFileLock ){
2389 return SQLITE_OK;
2392 /* To downgrade to shared, simply update our internal notion of the
2393 ** lock state. No need to mess with the file on disk.
2395 if( eFileLock==SHARED_LOCK ){
2396 pFile->eFileLock = SHARED_LOCK;
2397 return SQLITE_OK;
2400 /* To fully unlock the database, delete the lock file */
2401 assert( eFileLock==NO_LOCK );
2402 rc = osRmdir(zLockFile);
2403 if( rc<0 ){
2404 int tErrno = errno;
2405 if( tErrno==ENOENT ){
2406 rc = SQLITE_OK;
2407 }else{
2408 rc = SQLITE_IOERR_UNLOCK;
2409 storeLastErrno(pFile, tErrno);
2411 return rc;
2413 pFile->eFileLock = NO_LOCK;
2414 return SQLITE_OK;
2418 ** Close a file. Make sure the lock has been released before closing.
2420 static int dotlockClose(sqlite3_file *id) {
2421 unixFile *pFile = (unixFile*)id;
2422 assert( id!=0 );
2423 dotlockUnlock(id, NO_LOCK);
2424 sqlite3_free(pFile->lockingContext);
2425 return closeUnixFile(id);
2427 /****************** End of the dot-file lock implementation *******************
2428 ******************************************************************************/
2430 /******************************************************************************
2431 ************************** Begin flock Locking ********************************
2433 ** Use the flock() system call to do file locking.
2435 ** flock() locking is like dot-file locking in that the various
2436 ** fine-grain locking levels supported by SQLite are collapsed into
2437 ** a single exclusive lock. In other words, SHARED, RESERVED, and
2438 ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2439 ** still works when you do this, but concurrency is reduced since
2440 ** only a single process can be reading the database at a time.
2442 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
2444 #if SQLITE_ENABLE_LOCKING_STYLE
2447 ** Retry flock() calls that fail with EINTR
2449 #ifdef EINTR
2450 static int robust_flock(int fd, int op){
2451 int rc;
2452 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2453 return rc;
2455 #else
2456 # define robust_flock(a,b) flock(a,b)
2457 #endif
2461 ** This routine checks if there is a RESERVED lock held on the specified
2462 ** file by this or any other process. If such a lock is held, set *pResOut
2463 ** to a non-zero value otherwise *pResOut is set to zero. The return value
2464 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2466 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2467 int rc = SQLITE_OK;
2468 int reserved = 0;
2469 unixFile *pFile = (unixFile*)id;
2471 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2473 assert( pFile );
2475 /* Check if a thread in this process holds such a lock */
2476 if( pFile->eFileLock>SHARED_LOCK ){
2477 reserved = 1;
2480 /* Otherwise see if some other process holds it. */
2481 if( !reserved ){
2482 /* attempt to get the lock */
2483 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
2484 if( !lrc ){
2485 /* got the lock, unlock it */
2486 lrc = robust_flock(pFile->h, LOCK_UN);
2487 if ( lrc ) {
2488 int tErrno = errno;
2489 /* unlock failed with an error */
2490 lrc = SQLITE_IOERR_UNLOCK;
2491 storeLastErrno(pFile, tErrno);
2492 rc = lrc;
2494 } else {
2495 int tErrno = errno;
2496 reserved = 1;
2497 /* someone else might have it reserved */
2498 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2499 if( IS_LOCK_ERROR(lrc) ){
2500 storeLastErrno(pFile, tErrno);
2501 rc = lrc;
2505 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
2507 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2508 if( (rc & 0xff) == SQLITE_IOERR ){
2509 rc = SQLITE_OK;
2510 reserved=1;
2512 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2513 *pResOut = reserved;
2514 return rc;
2518 ** Lock the file with the lock specified by parameter eFileLock - one
2519 ** of the following:
2521 ** (1) SHARED_LOCK
2522 ** (2) RESERVED_LOCK
2523 ** (3) PENDING_LOCK
2524 ** (4) EXCLUSIVE_LOCK
2526 ** Sometimes when requesting one lock state, additional lock states
2527 ** are inserted in between. The locking might fail on one of the later
2528 ** transitions leaving the lock state different from what it started but
2529 ** still short of its goal. The following chart shows the allowed
2530 ** transitions and the inserted intermediate states:
2532 ** UNLOCKED -> SHARED
2533 ** SHARED -> RESERVED
2534 ** SHARED -> (PENDING) -> EXCLUSIVE
2535 ** RESERVED -> (PENDING) -> EXCLUSIVE
2536 ** PENDING -> EXCLUSIVE
2538 ** flock() only really support EXCLUSIVE locks. We track intermediate
2539 ** lock states in the sqlite3_file structure, but all locks SHARED or
2540 ** above are really EXCLUSIVE locks and exclude all other processes from
2541 ** access the file.
2543 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
2544 ** routine to lower a locking level.
2546 static int flockLock(sqlite3_file *id, int eFileLock) {
2547 int rc = SQLITE_OK;
2548 unixFile *pFile = (unixFile*)id;
2550 assert( pFile );
2552 /* if we already have a lock, it is exclusive.
2553 ** Just adjust level and punt on outta here. */
2554 if (pFile->eFileLock > NO_LOCK) {
2555 pFile->eFileLock = eFileLock;
2556 return SQLITE_OK;
2559 /* grab an exclusive lock */
2561 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
2562 int tErrno = errno;
2563 /* didn't get, must be busy */
2564 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2565 if( IS_LOCK_ERROR(rc) ){
2566 storeLastErrno(pFile, tErrno);
2568 } else {
2569 /* got it, set the type and return ok */
2570 pFile->eFileLock = eFileLock;
2572 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2573 rc==SQLITE_OK ? "ok" : "failed"));
2574 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2575 if( (rc & 0xff) == SQLITE_IOERR ){
2576 rc = SQLITE_BUSY;
2578 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2579 return rc;
2584 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
2585 ** must be either NO_LOCK or SHARED_LOCK.
2587 ** If the locking level of the file descriptor is already at or below
2588 ** the requested locking level, this routine is a no-op.
2590 static int flockUnlock(sqlite3_file *id, int eFileLock) {
2591 unixFile *pFile = (unixFile*)id;
2593 assert( pFile );
2594 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2595 pFile->eFileLock, osGetpid(0)));
2596 assert( eFileLock<=SHARED_LOCK );
2598 /* no-op if possible */
2599 if( pFile->eFileLock==eFileLock ){
2600 return SQLITE_OK;
2603 /* shared can just be set because we always have an exclusive */
2604 if (eFileLock==SHARED_LOCK) {
2605 pFile->eFileLock = eFileLock;
2606 return SQLITE_OK;
2609 /* no, really, unlock. */
2610 if( robust_flock(pFile->h, LOCK_UN) ){
2611 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2612 return SQLITE_OK;
2613 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2614 return SQLITE_IOERR_UNLOCK;
2615 }else{
2616 pFile->eFileLock = NO_LOCK;
2617 return SQLITE_OK;
2622 ** Close a file.
2624 static int flockClose(sqlite3_file *id) {
2625 assert( id!=0 );
2626 flockUnlock(id, NO_LOCK);
2627 return closeUnixFile(id);
2630 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2632 /******************* End of the flock lock implementation *********************
2633 ******************************************************************************/
2635 /******************************************************************************
2636 ************************ Begin Named Semaphore Locking ************************
2638 ** Named semaphore locking is only supported on VxWorks.
2640 ** Semaphore locking is like dot-lock and flock in that it really only
2641 ** supports EXCLUSIVE locking. Only a single process can read or write
2642 ** the database file at a time. This reduces potential concurrency, but
2643 ** makes the lock implementation much easier.
2645 #if OS_VXWORKS
2648 ** This routine checks if there is a RESERVED lock held on the specified
2649 ** file by this or any other process. If such a lock is held, set *pResOut
2650 ** to a non-zero value otherwise *pResOut is set to zero. The return value
2651 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2653 static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
2654 int rc = SQLITE_OK;
2655 int reserved = 0;
2656 unixFile *pFile = (unixFile*)id;
2658 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2660 assert( pFile );
2662 /* Check if a thread in this process holds such a lock */
2663 if( pFile->eFileLock>SHARED_LOCK ){
2664 reserved = 1;
2667 /* Otherwise see if some other process holds it. */
2668 if( !reserved ){
2669 sem_t *pSem = pFile->pInode->pSem;
2671 if( sem_trywait(pSem)==-1 ){
2672 int tErrno = errno;
2673 if( EAGAIN != tErrno ){
2674 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2675 storeLastErrno(pFile, tErrno);
2676 } else {
2677 /* someone else has the lock when we are in NO_LOCK */
2678 reserved = (pFile->eFileLock < SHARED_LOCK);
2680 }else{
2681 /* we could have it if we want it */
2682 sem_post(pSem);
2685 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
2687 *pResOut = reserved;
2688 return rc;
2692 ** Lock the file with the lock specified by parameter eFileLock - one
2693 ** of the following:
2695 ** (1) SHARED_LOCK
2696 ** (2) RESERVED_LOCK
2697 ** (3) PENDING_LOCK
2698 ** (4) EXCLUSIVE_LOCK
2700 ** Sometimes when requesting one lock state, additional lock states
2701 ** are inserted in between. The locking might fail on one of the later
2702 ** transitions leaving the lock state different from what it started but
2703 ** still short of its goal. The following chart shows the allowed
2704 ** transitions and the inserted intermediate states:
2706 ** UNLOCKED -> SHARED
2707 ** SHARED -> RESERVED
2708 ** SHARED -> (PENDING) -> EXCLUSIVE
2709 ** RESERVED -> (PENDING) -> EXCLUSIVE
2710 ** PENDING -> EXCLUSIVE
2712 ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2713 ** lock states in the sqlite3_file structure, but all locks SHARED or
2714 ** above are really EXCLUSIVE locks and exclude all other processes from
2715 ** access the file.
2717 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
2718 ** routine to lower a locking level.
2720 static int semXLock(sqlite3_file *id, int eFileLock) {
2721 unixFile *pFile = (unixFile*)id;
2722 sem_t *pSem = pFile->pInode->pSem;
2723 int rc = SQLITE_OK;
2725 /* if we already have a lock, it is exclusive.
2726 ** Just adjust level and punt on outta here. */
2727 if (pFile->eFileLock > NO_LOCK) {
2728 pFile->eFileLock = eFileLock;
2729 rc = SQLITE_OK;
2730 goto sem_end_lock;
2733 /* lock semaphore now but bail out when already locked. */
2734 if( sem_trywait(pSem)==-1 ){
2735 rc = SQLITE_BUSY;
2736 goto sem_end_lock;
2739 /* got it, set the type and return ok */
2740 pFile->eFileLock = eFileLock;
2742 sem_end_lock:
2743 return rc;
2747 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
2748 ** must be either NO_LOCK or SHARED_LOCK.
2750 ** If the locking level of the file descriptor is already at or below
2751 ** the requested locking level, this routine is a no-op.
2753 static int semXUnlock(sqlite3_file *id, int eFileLock) {
2754 unixFile *pFile = (unixFile*)id;
2755 sem_t *pSem = pFile->pInode->pSem;
2757 assert( pFile );
2758 assert( pSem );
2759 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2760 pFile->eFileLock, osGetpid(0)));
2761 assert( eFileLock<=SHARED_LOCK );
2763 /* no-op if possible */
2764 if( pFile->eFileLock==eFileLock ){
2765 return SQLITE_OK;
2768 /* shared can just be set because we always have an exclusive */
2769 if (eFileLock==SHARED_LOCK) {
2770 pFile->eFileLock = eFileLock;
2771 return SQLITE_OK;
2774 /* no, really unlock. */
2775 if ( sem_post(pSem)==-1 ) {
2776 int rc, tErrno = errno;
2777 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2778 if( IS_LOCK_ERROR(rc) ){
2779 storeLastErrno(pFile, tErrno);
2781 return rc;
2783 pFile->eFileLock = NO_LOCK;
2784 return SQLITE_OK;
2788 ** Close a file.
2790 static int semXClose(sqlite3_file *id) {
2791 if( id ){
2792 unixFile *pFile = (unixFile*)id;
2793 semXUnlock(id, NO_LOCK);
2794 assert( pFile );
2795 assert( unixFileMutexNotheld(pFile) );
2796 unixEnterMutex();
2797 releaseInodeInfo(pFile);
2798 unixLeaveMutex();
2799 closeUnixFile(id);
2801 return SQLITE_OK;
2804 #endif /* OS_VXWORKS */
2806 ** Named semaphore locking is only available on VxWorks.
2808 *************** End of the named semaphore lock implementation ****************
2809 ******************************************************************************/
2812 /******************************************************************************
2813 *************************** Begin AFP Locking *********************************
2815 ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2816 ** on Apple Macintosh computers - both OS9 and OSX.
2818 ** Third-party implementations of AFP are available. But this code here
2819 ** only works on OSX.
2822 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2824 ** The afpLockingContext structure contains all afp lock specific state
2826 typedef struct afpLockingContext afpLockingContext;
2827 struct afpLockingContext {
2828 int reserved;
2829 const char *dbPath; /* Name of the open file */
2832 struct ByteRangeLockPB2
2834 unsigned long long offset; /* offset to first byte to lock */
2835 unsigned long long length; /* nbr of bytes to lock */
2836 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2837 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2838 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2839 int fd; /* file desc to assoc this lock with */
2842 #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
2845 ** This is a utility for setting or clearing a bit-range lock on an
2846 ** AFP filesystem.
2848 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2850 static int afpSetLock(
2851 const char *path, /* Name of the file to be locked or unlocked */
2852 unixFile *pFile, /* Open file descriptor on path */
2853 unsigned long long offset, /* First byte to be locked */
2854 unsigned long long length, /* Number of bytes to lock */
2855 int setLockFlag /* True to set lock. False to clear lock */
2857 struct ByteRangeLockPB2 pb;
2858 int err;
2860 pb.unLockFlag = setLockFlag ? 0 : 1;
2861 pb.startEndFlag = 0;
2862 pb.offset = offset;
2863 pb.length = length;
2864 pb.fd = pFile->h;
2866 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
2867 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
2868 offset, length));
2869 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2870 if ( err==-1 ) {
2871 int rc;
2872 int tErrno = errno;
2873 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2874 path, tErrno, strerror(tErrno)));
2875 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2876 rc = SQLITE_BUSY;
2877 #else
2878 rc = sqliteErrorFromPosixError(tErrno,
2879 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
2880 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
2881 if( IS_LOCK_ERROR(rc) ){
2882 storeLastErrno(pFile, tErrno);
2884 return rc;
2885 } else {
2886 return SQLITE_OK;
2891 ** This routine checks if there is a RESERVED lock held on the specified
2892 ** file by this or any other process. If such a lock is held, set *pResOut
2893 ** to a non-zero value otherwise *pResOut is set to zero. The return value
2894 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2896 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
2897 int rc = SQLITE_OK;
2898 int reserved = 0;
2899 unixFile *pFile = (unixFile*)id;
2900 afpLockingContext *context;
2902 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2904 assert( pFile );
2905 context = (afpLockingContext *) pFile->lockingContext;
2906 if( context->reserved ){
2907 *pResOut = 1;
2908 return SQLITE_OK;
2910 sqlite3_mutex_enter(pFile->pInode->pLockMutex);
2911 /* Check if a thread in this process holds such a lock */
2912 if( pFile->pInode->eFileLock>SHARED_LOCK ){
2913 reserved = 1;
2916 /* Otherwise see if some other process holds it.
2918 if( !reserved ){
2919 /* lock the RESERVED byte */
2920 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
2921 if( SQLITE_OK==lrc ){
2922 /* if we succeeded in taking the reserved lock, unlock it to restore
2923 ** the original state */
2924 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2925 } else {
2926 /* if we failed to get the lock then someone else must have it */
2927 reserved = 1;
2929 if( IS_LOCK_ERROR(lrc) ){
2930 rc=lrc;
2934 sqlite3_mutex_leave(pFile->pInode->pLockMutex);
2935 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
2937 *pResOut = reserved;
2938 return rc;
2942 ** Lock the file with the lock specified by parameter eFileLock - one
2943 ** of the following:
2945 ** (1) SHARED_LOCK
2946 ** (2) RESERVED_LOCK
2947 ** (3) PENDING_LOCK
2948 ** (4) EXCLUSIVE_LOCK
2950 ** Sometimes when requesting one lock state, additional lock states
2951 ** are inserted in between. The locking might fail on one of the later
2952 ** transitions leaving the lock state different from what it started but
2953 ** still short of its goal. The following chart shows the allowed
2954 ** transitions and the inserted intermediate states:
2956 ** UNLOCKED -> SHARED
2957 ** SHARED -> RESERVED
2958 ** SHARED -> (PENDING) -> EXCLUSIVE
2959 ** RESERVED -> (PENDING) -> EXCLUSIVE
2960 ** PENDING -> EXCLUSIVE
2962 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
2963 ** routine to lower a locking level.
2965 static int afpLock(sqlite3_file *id, int eFileLock){
2966 int rc = SQLITE_OK;
2967 unixFile *pFile = (unixFile*)id;
2968 unixInodeInfo *pInode = pFile->pInode;
2969 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2971 assert( pFile );
2972 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2973 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
2974 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
2976 /* If there is already a lock of this type or more restrictive on the
2977 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
2978 ** unixEnterMutex() hasn't been called yet.
2980 if( pFile->eFileLock>=eFileLock ){
2981 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2982 azFileLock(eFileLock)));
2983 return SQLITE_OK;
2986 /* Make sure the locking sequence is correct
2987 ** (1) We never move from unlocked to anything higher than shared lock.
2988 ** (2) SQLite never explicitly requests a pending lock.
2989 ** (3) A shared lock is always held when a reserve lock is requested.
2991 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2992 assert( eFileLock!=PENDING_LOCK );
2993 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
2995 /* This mutex is needed because pFile->pInode is shared across threads
2997 pInode = pFile->pInode;
2998 sqlite3_mutex_enter(pInode->pLockMutex);
3000 /* If some thread using this PID has a lock via a different unixFile*
3001 ** handle that precludes the requested lock, return BUSY.
3003 if( (pFile->eFileLock!=pInode->eFileLock &&
3004 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
3006 rc = SQLITE_BUSY;
3007 goto afp_end_lock;
3010 /* If a SHARED lock is requested, and some thread using this PID already
3011 ** has a SHARED or RESERVED lock, then increment reference counts and
3012 ** return SQLITE_OK.
3014 if( eFileLock==SHARED_LOCK &&
3015 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
3016 assert( eFileLock==SHARED_LOCK );
3017 assert( pFile->eFileLock==0 );
3018 assert( pInode->nShared>0 );
3019 pFile->eFileLock = SHARED_LOCK;
3020 pInode->nShared++;
3021 pInode->nLock++;
3022 goto afp_end_lock;
3025 /* A PENDING lock is needed before acquiring a SHARED lock and before
3026 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
3027 ** be released.
3029 if( eFileLock==SHARED_LOCK
3030 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
3032 int failed;
3033 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
3034 if (failed) {
3035 rc = failed;
3036 goto afp_end_lock;
3040 /* If control gets to this point, then actually go ahead and make
3041 ** operating system calls for the specified lock.
3043 if( eFileLock==SHARED_LOCK ){
3044 int lrc1, lrc2, lrc1Errno = 0;
3045 long lk, mask;
3047 assert( pInode->nShared==0 );
3048 assert( pInode->eFileLock==0 );
3050 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
3051 /* Now get the read-lock SHARED_LOCK */
3052 /* note that the quality of the randomness doesn't matter that much */
3053 lk = random();
3054 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
3055 lrc1 = afpSetLock(context->dbPath, pFile,
3056 SHARED_FIRST+pInode->sharedByte, 1, 1);
3057 if( IS_LOCK_ERROR(lrc1) ){
3058 lrc1Errno = pFile->lastErrno;
3060 /* Drop the temporary PENDING lock */
3061 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
3063 if( IS_LOCK_ERROR(lrc1) ) {
3064 storeLastErrno(pFile, lrc1Errno);
3065 rc = lrc1;
3066 goto afp_end_lock;
3067 } else if( IS_LOCK_ERROR(lrc2) ){
3068 rc = lrc2;
3069 goto afp_end_lock;
3070 } else if( lrc1 != SQLITE_OK ) {
3071 rc = lrc1;
3072 } else {
3073 pFile->eFileLock = SHARED_LOCK;
3074 pInode->nLock++;
3075 pInode->nShared = 1;
3077 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
3078 /* We are trying for an exclusive lock but another thread in this
3079 ** same process is still holding a shared lock. */
3080 rc = SQLITE_BUSY;
3081 }else{
3082 /* The request was for a RESERVED or EXCLUSIVE lock. It is
3083 ** assumed that there is a SHARED or greater lock on the file
3084 ** already.
3086 int failed = 0;
3087 assert( 0!=pFile->eFileLock );
3088 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
3089 /* Acquire a RESERVED lock */
3090 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
3091 if( !failed ){
3092 context->reserved = 1;
3095 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
3096 /* Acquire an EXCLUSIVE lock */
3098 /* Remove the shared lock before trying the range. we'll need to
3099 ** reestablish the shared lock if we can't get the afpUnlock
3101 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
3102 pInode->sharedByte, 1, 0)) ){
3103 int failed2 = SQLITE_OK;
3104 /* now attempt to get the exclusive lock range */
3105 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
3106 SHARED_SIZE, 1);
3107 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
3108 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
3109 /* Can't reestablish the shared lock. Sqlite can't deal, this is
3110 ** a critical I/O error
3112 rc = ((failed & 0xff) == SQLITE_IOERR) ? failed2 :
3113 SQLITE_IOERR_LOCK;
3114 goto afp_end_lock;
3116 }else{
3117 rc = failed;
3120 if( failed ){
3121 rc = failed;
3125 if( rc==SQLITE_OK ){
3126 pFile->eFileLock = eFileLock;
3127 pInode->eFileLock = eFileLock;
3128 }else if( eFileLock==EXCLUSIVE_LOCK ){
3129 pFile->eFileLock = PENDING_LOCK;
3130 pInode->eFileLock = PENDING_LOCK;
3133 afp_end_lock:
3134 sqlite3_mutex_leave(pInode->pLockMutex);
3135 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
3136 rc==SQLITE_OK ? "ok" : "failed"));
3137 return rc;
3141 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
3142 ** must be either NO_LOCK or SHARED_LOCK.
3144 ** If the locking level of the file descriptor is already at or below
3145 ** the requested locking level, this routine is a no-op.
3147 static int afpUnlock(sqlite3_file *id, int eFileLock) {
3148 int rc = SQLITE_OK;
3149 unixFile *pFile = (unixFile*)id;
3150 unixInodeInfo *pInode;
3151 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
3152 int skipShared = 0;
3154 assert( pFile );
3155 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
3156 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
3157 osGetpid(0)));
3159 assert( eFileLock<=SHARED_LOCK );
3160 if( pFile->eFileLock<=eFileLock ){
3161 return SQLITE_OK;
3163 pInode = pFile->pInode;
3164 sqlite3_mutex_enter(pInode->pLockMutex);
3165 assert( pInode->nShared!=0 );
3166 if( pFile->eFileLock>SHARED_LOCK ){
3167 assert( pInode->eFileLock==pFile->eFileLock );
3169 #ifdef SQLITE_DEBUG
3170 /* When reducing a lock such that other processes can start
3171 ** reading the database file again, make sure that the
3172 ** transaction counter was updated if any part of the database
3173 ** file changed. If the transaction counter is not updated,
3174 ** other connections to the same file might not realize that
3175 ** the file has changed and hence might not know to flush their
3176 ** cache. The use of a stale cache can lead to database corruption.
3178 assert( pFile->inNormalWrite==0
3179 || pFile->dbUpdate==0
3180 || pFile->transCntrChng==1 );
3181 pFile->inNormalWrite = 0;
3182 #endif
3184 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
3185 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
3186 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
3187 /* only re-establish the shared lock if necessary */
3188 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3189 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
3190 } else {
3191 skipShared = 1;
3194 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
3195 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
3197 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
3198 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
3199 if( !rc ){
3200 context->reserved = 0;
3203 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
3204 pInode->eFileLock = SHARED_LOCK;
3207 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
3209 /* Decrement the shared lock counter. Release the lock using an
3210 ** OS call only when all threads in this same process have released
3211 ** the lock.
3213 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3214 pInode->nShared--;
3215 if( pInode->nShared==0 ){
3216 if( !skipShared ){
3217 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
3219 if( !rc ){
3220 pInode->eFileLock = NO_LOCK;
3221 pFile->eFileLock = NO_LOCK;
3224 if( rc==SQLITE_OK ){
3225 pInode->nLock--;
3226 assert( pInode->nLock>=0 );
3227 if( pInode->nLock==0 ) closePendingFds(pFile);
3231 sqlite3_mutex_leave(pInode->pLockMutex);
3232 if( rc==SQLITE_OK ){
3233 pFile->eFileLock = eFileLock;
3235 return rc;
3239 ** Close a file & cleanup AFP specific locking context
3241 static int afpClose(sqlite3_file *id) {
3242 int rc = SQLITE_OK;
3243 unixFile *pFile = (unixFile*)id;
3244 assert( id!=0 );
3245 afpUnlock(id, NO_LOCK);
3246 assert( unixFileMutexNotheld(pFile) );
3247 unixEnterMutex();
3248 if( pFile->pInode ){
3249 unixInodeInfo *pInode = pFile->pInode;
3250 sqlite3_mutex_enter(pInode->pLockMutex);
3251 if( pInode->nLock ){
3252 /* If there are outstanding locks, do not actually close the file just
3253 ** yet because that would clear those locks. Instead, add the file
3254 ** descriptor to pInode->aPending. It will be automatically closed when
3255 ** the last lock is cleared.
3257 setPendingFd(pFile);
3259 sqlite3_mutex_leave(pInode->pLockMutex);
3261 releaseInodeInfo(pFile);
3262 sqlite3_free(pFile->lockingContext);
3263 rc = closeUnixFile(id);
3264 unixLeaveMutex();
3265 return rc;
3268 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3270 ** The code above is the AFP lock implementation. The code is specific
3271 ** to MacOSX and does not work on other unix platforms. No alternative
3272 ** is available. If you don't compile for a mac, then the "unix-afp"
3273 ** VFS is not available.
3275 ********************* End of the AFP lock implementation **********************
3276 ******************************************************************************/
3278 /******************************************************************************
3279 *************************** Begin NFS Locking ********************************/
3281 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3283 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
3284 ** must be either NO_LOCK or SHARED_LOCK.
3286 ** If the locking level of the file descriptor is already at or below
3287 ** the requested locking level, this routine is a no-op.
3289 static int nfsUnlock(sqlite3_file *id, int eFileLock){
3290 return posixUnlock(id, eFileLock, 1);
3293 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3295 ** The code above is the NFS lock implementation. The code is specific
3296 ** to MacOSX and does not work on other unix platforms. No alternative
3297 ** is available.
3299 ********************* End of the NFS lock implementation **********************
3300 ******************************************************************************/
3302 /******************************************************************************
3303 **************** Non-locking sqlite3_file methods *****************************
3305 ** The next division contains implementations for all methods of the
3306 ** sqlite3_file object other than the locking methods. The locking
3307 ** methods were defined in divisions above (one locking method per
3308 ** division). Those methods that are common to all locking modes
3309 ** are gather together into this division.
3313 ** Seek to the offset passed as the second argument, then read cnt
3314 ** bytes into pBuf. Return the number of bytes actually read.
3316 ** To avoid stomping the errno value on a failed read the lastErrno value
3317 ** is set before returning.
3319 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3320 int got;
3321 int prior = 0;
3322 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
3323 i64 newOffset;
3324 #endif
3325 TIMER_START;
3326 assert( cnt==(cnt&0x1ffff) );
3327 assert( id->h>2 );
3329 #if defined(USE_PREAD)
3330 got = osPread(id->h, pBuf, cnt, offset);
3331 SimulateIOError( got = -1 );
3332 #elif defined(USE_PREAD64)
3333 got = osPread64(id->h, pBuf, cnt, offset);
3334 SimulateIOError( got = -1 );
3335 #else
3336 newOffset = lseek(id->h, offset, SEEK_SET);
3337 SimulateIOError( newOffset = -1 );
3338 if( newOffset<0 ){
3339 storeLastErrno((unixFile*)id, errno);
3340 return -1;
3342 got = osRead(id->h, pBuf, cnt);
3343 #endif
3344 if( got==cnt ) break;
3345 if( got<0 ){
3346 if( errno==EINTR ){ got = 1; continue; }
3347 prior = 0;
3348 storeLastErrno((unixFile*)id, errno);
3349 break;
3350 }else if( got>0 ){
3351 cnt -= got;
3352 offset += got;
3353 prior += got;
3354 pBuf = (void*)(got + (char*)pBuf);
3356 }while( got>0 );
3357 TIMER_END;
3358 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3359 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3360 return got+prior;
3364 ** Read data from a file into a buffer. Return SQLITE_OK if all
3365 ** bytes were read successfully and SQLITE_IOERR if anything goes
3366 ** wrong.
3368 static int unixRead(
3369 sqlite3_file *id,
3370 void *pBuf,
3371 int amt,
3372 sqlite3_int64 offset
3374 unixFile *pFile = (unixFile *)id;
3375 int got;
3376 assert( id );
3377 assert( offset>=0 );
3378 assert( amt>0 );
3380 /* If this is a database file (not a journal, super-journal or temp
3381 ** file), the bytes in the locking range should never be read or written. */
3382 #if 0
3383 assert( pFile->pPreallocatedUnused==0
3384 || offset>=PENDING_BYTE+512
3385 || offset+amt<=PENDING_BYTE
3387 #endif
3389 #if SQLITE_MAX_MMAP_SIZE>0
3390 /* Deal with as much of this read request as possible by transferring
3391 ** data from the memory mapping using memcpy(). */
3392 if( offset<pFile->mmapSize ){
3393 if( offset+amt <= pFile->mmapSize ){
3394 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3395 return SQLITE_OK;
3396 }else{
3397 int nCopy = pFile->mmapSize - offset;
3398 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3399 pBuf = &((u8 *)pBuf)[nCopy];
3400 amt -= nCopy;
3401 offset += nCopy;
3404 #endif
3406 got = seekAndRead(pFile, offset, pBuf, amt);
3407 if( got==amt ){
3408 return SQLITE_OK;
3409 }else if( got<0 ){
3410 /* pFile->lastErrno has been set by seekAndRead().
3411 ** Usually we return SQLITE_IOERR_READ here, though for some
3412 ** kinds of errors we return SQLITE_IOERR_CORRUPTFS. The
3413 ** SQLITE_IOERR_CORRUPTFS will be converted into SQLITE_CORRUPT
3414 ** prior to returning to the application by the sqlite3ApiExit()
3415 ** routine.
3417 switch( pFile->lastErrno ){
3418 case ERANGE:
3419 case EIO:
3420 #ifdef ENXIO
3421 case ENXIO:
3422 #endif
3423 #ifdef EDEVERR
3424 case EDEVERR:
3425 #endif
3426 return SQLITE_IOERR_CORRUPTFS;
3428 return SQLITE_IOERR_READ;
3429 }else{
3430 storeLastErrno(pFile, 0); /* not a system error */
3431 /* Unread parts of the buffer must be zero-filled */
3432 memset(&((char*)pBuf)[got], 0, amt-got);
3433 return SQLITE_IOERR_SHORT_READ;
3438 ** Attempt to seek the file-descriptor passed as the first argument to
3439 ** absolute offset iOff, then attempt to write nBuf bytes of data from
3440 ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3441 ** return the actual number of bytes written (which may be less than
3442 ** nBuf).
3444 static int seekAndWriteFd(
3445 int fd, /* File descriptor to write to */
3446 i64 iOff, /* File offset to begin writing at */
3447 const void *pBuf, /* Copy data from this buffer to the file */
3448 int nBuf, /* Size of buffer pBuf in bytes */
3449 int *piErrno /* OUT: Error number if error occurs */
3451 int rc = 0; /* Value returned by system call */
3453 assert( nBuf==(nBuf&0x1ffff) );
3454 assert( fd>2 );
3455 assert( piErrno!=0 );
3456 nBuf &= 0x1ffff;
3457 TIMER_START;
3459 #if defined(USE_PREAD)
3460 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
3461 #elif defined(USE_PREAD64)
3462 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
3463 #else
3465 i64 iSeek = lseek(fd, iOff, SEEK_SET);
3466 SimulateIOError( iSeek = -1 );
3467 if( iSeek<0 ){
3468 rc = -1;
3469 break;
3471 rc = osWrite(fd, pBuf, nBuf);
3472 }while( rc<0 && errno==EINTR );
3473 #endif
3475 TIMER_END;
3476 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3478 if( rc<0 ) *piErrno = errno;
3479 return rc;
3484 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
3485 ** Return the number of bytes actually read. Update the offset.
3487 ** To avoid stomping the errno value on a failed write the lastErrno value
3488 ** is set before returning.
3490 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
3491 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
3496 ** Write data from a buffer into a file. Return SQLITE_OK on success
3497 ** or some other error code on failure.
3499 static int unixWrite(
3500 sqlite3_file *id,
3501 const void *pBuf,
3502 int amt,
3503 sqlite3_int64 offset
3505 unixFile *pFile = (unixFile*)id;
3506 int wrote = 0;
3507 assert( id );
3508 assert( amt>0 );
3510 /* If this is a database file (not a journal, super-journal or temp
3511 ** file), the bytes in the locking range should never be read or written. */
3512 #if 0
3513 assert( pFile->pPreallocatedUnused==0
3514 || offset>=PENDING_BYTE+512
3515 || offset+amt<=PENDING_BYTE
3517 #endif
3519 #ifdef SQLITE_DEBUG
3520 /* If we are doing a normal write to a database file (as opposed to
3521 ** doing a hot-journal rollback or a write to some file other than a
3522 ** normal database file) then record the fact that the database
3523 ** has changed. If the transaction counter is modified, record that
3524 ** fact too.
3526 if( pFile->inNormalWrite ){
3527 pFile->dbUpdate = 1; /* The database has been modified */
3528 if( offset<=24 && offset+amt>=27 ){
3529 int rc;
3530 char oldCntr[4];
3531 SimulateIOErrorBenign(1);
3532 rc = seekAndRead(pFile, 24, oldCntr, 4);
3533 SimulateIOErrorBenign(0);
3534 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
3535 pFile->transCntrChng = 1; /* The transaction counter has changed */
3539 #endif
3541 #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
3542 /* Deal with as much of this write request as possible by transferring
3543 ** data from the memory mapping using memcpy(). */
3544 if( offset<pFile->mmapSize ){
3545 if( offset+amt <= pFile->mmapSize ){
3546 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3547 return SQLITE_OK;
3548 }else{
3549 int nCopy = pFile->mmapSize - offset;
3550 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3551 pBuf = &((u8 *)pBuf)[nCopy];
3552 amt -= nCopy;
3553 offset += nCopy;
3556 #endif
3558 while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
3559 amt -= wrote;
3560 offset += wrote;
3561 pBuf = &((char*)pBuf)[wrote];
3563 SimulateIOError(( wrote=(-1), amt=1 ));
3564 SimulateDiskfullError(( wrote=0, amt=1 ));
3566 if( amt>wrote ){
3567 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
3568 /* lastErrno set by seekAndWrite */
3569 return SQLITE_IOERR_WRITE;
3570 }else{
3571 storeLastErrno(pFile, 0); /* not a system error */
3572 return SQLITE_FULL;
3576 return SQLITE_OK;
3579 #ifdef SQLITE_TEST
3581 ** Count the number of fullsyncs and normal syncs. This is used to test
3582 ** that syncs and fullsyncs are occurring at the right times.
3584 int sqlite3_sync_count = 0;
3585 int sqlite3_fullsync_count = 0;
3586 #endif
3589 ** We do not trust systems to provide a working fdatasync(). Some do.
3590 ** Others do no. To be safe, we will stick with the (slightly slower)
3591 ** fsync(). If you know that your system does support fdatasync() correctly,
3592 ** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
3594 #if !defined(fdatasync) && !HAVE_FDATASYNC
3595 # define fdatasync fsync
3596 #endif
3599 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3600 ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3601 ** only available on Mac OS X. But that could change.
3603 #ifdef F_FULLFSYNC
3604 # define HAVE_FULLFSYNC 1
3605 #else
3606 # define HAVE_FULLFSYNC 0
3607 #endif
3611 ** The fsync() system call does not work as advertised on many
3612 ** unix systems. The following procedure is an attempt to make
3613 ** it work better.
3615 ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3616 ** for testing when we want to run through the test suite quickly.
3617 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3618 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3619 ** or power failure will likely corrupt the database file.
3621 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
3622 ** The idea behind dataOnly is that it should only write the file content
3623 ** to disk, not the inode. We only set dataOnly if the file size is
3624 ** unchanged since the file size is part of the inode. However,
3625 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
3626 ** file size has changed. The only real difference between fdatasync()
3627 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
3628 ** inode if the mtime or owner or other inode attributes have changed.
3629 ** We only care about the file size, not the other file attributes, so
3630 ** as far as SQLite is concerned, an fdatasync() is always adequate.
3631 ** So, we always use fdatasync() if it is available, regardless of
3632 ** the value of the dataOnly flag.
3634 static int full_fsync(int fd, int fullSync, int dataOnly){
3635 int rc;
3637 /* The following "ifdef/elif/else/" block has the same structure as
3638 ** the one below. It is replicated here solely to avoid cluttering
3639 ** up the real code with the UNUSED_PARAMETER() macros.
3641 #ifdef SQLITE_NO_SYNC
3642 UNUSED_PARAMETER(fd);
3643 UNUSED_PARAMETER(fullSync);
3644 UNUSED_PARAMETER(dataOnly);
3645 #elif HAVE_FULLFSYNC
3646 UNUSED_PARAMETER(dataOnly);
3647 #else
3648 UNUSED_PARAMETER(fullSync);
3649 UNUSED_PARAMETER(dataOnly);
3650 #endif
3652 /* Record the number of times that we do a normal fsync() and
3653 ** FULLSYNC. This is used during testing to verify that this procedure
3654 ** gets called with the correct arguments.
3656 #ifdef SQLITE_TEST
3657 if( fullSync ) sqlite3_fullsync_count++;
3658 sqlite3_sync_count++;
3659 #endif
3661 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3662 ** no-op. But go ahead and call fstat() to validate the file
3663 ** descriptor as we need a method to provoke a failure during
3664 ** coverage testing.
3666 #ifdef SQLITE_NO_SYNC
3668 struct stat buf;
3669 rc = osFstat(fd, &buf);
3671 #elif HAVE_FULLFSYNC
3672 if( fullSync ){
3673 rc = osFcntl(fd, F_FULLFSYNC, 0);
3674 }else{
3675 rc = 1;
3677 /* If the FULLFSYNC failed, fall back to attempting an fsync().
3678 ** It shouldn't be possible for fullfsync to fail on the local
3679 ** file system (on OSX), so failure indicates that FULLFSYNC
3680 ** isn't supported for this file system. So, attempt an fsync
3681 ** and (for now) ignore the overhead of a superfluous fcntl call.
3682 ** It'd be better to detect fullfsync support once and avoid
3683 ** the fcntl call every time sync is called.
3685 if( rc ) rc = fsync(fd);
3687 #elif defined(__APPLE__)
3688 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3689 ** so currently we default to the macro that redefines fdatasync to fsync
3691 rc = fsync(fd);
3692 #else
3693 rc = fdatasync(fd);
3694 #if OS_VXWORKS
3695 if( rc==-1 && errno==ENOTSUP ){
3696 rc = fsync(fd);
3698 #endif /* OS_VXWORKS */
3699 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3701 if( OS_VXWORKS && rc!= -1 ){
3702 rc = 0;
3704 return rc;
3708 ** Open a file descriptor to the directory containing file zFilename.
3709 ** If successful, *pFd is set to the opened file descriptor and
3710 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3711 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3712 ** value.
3714 ** The directory file descriptor is used for only one thing - to
3715 ** fsync() a directory to make sure file creation and deletion events
3716 ** are flushed to disk. Such fsyncs are not needed on newer
3717 ** journaling filesystems, but are required on older filesystems.
3719 ** This routine can be overridden using the xSetSysCall interface.
3720 ** The ability to override this routine was added in support of the
3721 ** chromium sandbox. Opening a directory is a security risk (we are
3722 ** told) so making it overrideable allows the chromium sandbox to
3723 ** replace this routine with a harmless no-op. To make this routine
3724 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3725 ** *pFd set to a negative number.
3727 ** If SQLITE_OK is returned, the caller is responsible for closing
3728 ** the file descriptor *pFd using close().
3730 static int openDirectory(const char *zFilename, int *pFd){
3731 int ii;
3732 int fd = -1;
3733 char zDirname[MAX_PATHNAME+1];
3735 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3736 for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
3737 if( ii>0 ){
3738 zDirname[ii] = '\0';
3739 }else{
3740 if( zDirname[0]!='/' ) zDirname[0] = '.';
3741 zDirname[1] = 0;
3743 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3744 if( fd>=0 ){
3745 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3747 *pFd = fd;
3748 if( fd>=0 ) return SQLITE_OK;
3749 return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
3753 ** Make sure all writes to a particular file are committed to disk.
3755 ** If dataOnly==0 then both the file itself and its metadata (file
3756 ** size, access time, etc) are synced. If dataOnly!=0 then only the
3757 ** file data is synced.
3759 ** Under Unix, also make sure that the directory entry for the file
3760 ** has been created by fsync-ing the directory that contains the file.
3761 ** If we do not do this and we encounter a power failure, the directory
3762 ** entry for the journal might not exist after we reboot. The next
3763 ** SQLite to access the file will not know that the journal exists (because
3764 ** the directory entry for the journal was never created) and the transaction
3765 ** will not roll back - possibly leading to database corruption.
3767 static int unixSync(sqlite3_file *id, int flags){
3768 int rc;
3769 unixFile *pFile = (unixFile*)id;
3771 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3772 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3774 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3775 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3776 || (flags&0x0F)==SQLITE_SYNC_FULL
3779 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3780 ** line is to test that doing so does not cause any problems.
3782 SimulateDiskfullError( return SQLITE_FULL );
3784 assert( pFile );
3785 OSTRACE(("SYNC %-3d\n", pFile->h));
3786 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3787 SimulateIOError( rc=1 );
3788 if( rc ){
3789 storeLastErrno(pFile, errno);
3790 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
3793 /* Also fsync the directory containing the file if the DIRSYNC flag
3794 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
3795 ** are unable to fsync a directory, so ignore errors on the fsync.
3797 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3798 int dirfd;
3799 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
3800 HAVE_FULLFSYNC, isFullsync));
3801 rc = osOpenDirectory(pFile->zPath, &dirfd);
3802 if( rc==SQLITE_OK ){
3803 full_fsync(dirfd, 0, 0);
3804 robust_close(pFile, dirfd, __LINE__);
3805 }else{
3806 assert( rc==SQLITE_CANTOPEN );
3807 rc = SQLITE_OK;
3809 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
3811 return rc;
3815 ** Truncate an open file to a specified size
3817 static int unixTruncate(sqlite3_file *id, i64 nByte){
3818 unixFile *pFile = (unixFile *)id;
3819 int rc;
3820 assert( pFile );
3821 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
3823 /* If the user has configured a chunk-size for this file, truncate the
3824 ** file so that it consists of an integer number of chunks (i.e. the
3825 ** actual file size after the operation may be larger than the requested
3826 ** size).
3828 if( pFile->szChunk>0 ){
3829 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3832 rc = robust_ftruncate(pFile->h, nByte);
3833 if( rc ){
3834 storeLastErrno(pFile, errno);
3835 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3836 }else{
3837 #ifdef SQLITE_DEBUG
3838 /* If we are doing a normal write to a database file (as opposed to
3839 ** doing a hot-journal rollback or a write to some file other than a
3840 ** normal database file) and we truncate the file to zero length,
3841 ** that effectively updates the change counter. This might happen
3842 ** when restoring a database using the backup API from a zero-length
3843 ** source.
3845 if( pFile->inNormalWrite && nByte==0 ){
3846 pFile->transCntrChng = 1;
3848 #endif
3850 #if SQLITE_MAX_MMAP_SIZE>0
3851 /* If the file was just truncated to a size smaller than the currently
3852 ** mapped region, reduce the effective mapping size as well. SQLite will
3853 ** use read() and write() to access data beyond this point from now on.
3855 if( nByte<pFile->mmapSize ){
3856 pFile->mmapSize = nByte;
3858 #endif
3860 return SQLITE_OK;
3865 ** Determine the current size of a file in bytes
3867 static int unixFileSize(sqlite3_file *id, i64 *pSize){
3868 int rc;
3869 struct stat buf;
3870 assert( id );
3871 rc = osFstat(((unixFile*)id)->h, &buf);
3872 SimulateIOError( rc=1 );
3873 if( rc!=0 ){
3874 storeLastErrno((unixFile*)id, errno);
3875 return SQLITE_IOERR_FSTAT;
3877 *pSize = buf.st_size;
3879 /* When opening a zero-size database, the findInodeInfo() procedure
3880 ** writes a single byte into that file in order to work around a bug
3881 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3882 ** layers, we need to report this file size as zero even though it is
3883 ** really 1. Ticket #3260.
3885 if( *pSize==1 ) *pSize = 0;
3888 return SQLITE_OK;
3891 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
3893 ** Handler for proxy-locking file-control verbs. Defined below in the
3894 ** proxying locking division.
3896 static int proxyFileControl(sqlite3_file*,int,void*);
3897 #endif
3900 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
3901 ** file-control operation. Enlarge the database to nBytes in size
3902 ** (rounded up to the next chunk-size). If the database is already
3903 ** nBytes or larger, this routine is a no-op.
3905 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
3906 if( pFile->szChunk>0 ){
3907 i64 nSize; /* Required file size */
3908 struct stat buf; /* Used to hold return values of fstat() */
3910 if( osFstat(pFile->h, &buf) ){
3911 return SQLITE_IOERR_FSTAT;
3914 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3915 if( nSize>(i64)buf.st_size ){
3917 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
3918 /* The code below is handling the return value of osFallocate()
3919 ** correctly. posix_fallocate() is defined to "returns zero on success,
3920 ** or an error number on failure". See the manpage for details. */
3921 int err;
3923 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3924 }while( err==EINTR );
3925 if( err && err!=EINVAL ) return SQLITE_IOERR_WRITE;
3926 #else
3927 /* If the OS does not have posix_fallocate(), fake it. Write a
3928 ** single byte to the last byte in each block that falls entirely
3929 ** within the extended region. Then, if required, a single byte
3930 ** at offset (nSize-1), to set the size of the file correctly.
3931 ** This is a similar technique to that used by glibc on systems
3932 ** that do not have a real fallocate() call.
3934 int nBlk = buf.st_blksize; /* File-system block size */
3935 int nWrite = 0; /* Number of bytes written by seekAndWrite */
3936 i64 iWrite; /* Next offset to write to */
3938 iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
3939 assert( iWrite>=buf.st_size );
3940 assert( ((iWrite+1)%nBlk)==0 );
3941 for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
3942 if( iWrite>=nSize ) iWrite = nSize - 1;
3943 nWrite = seekAndWrite(pFile, iWrite, "", 1);
3944 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
3946 #endif
3950 #if SQLITE_MAX_MMAP_SIZE>0
3951 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
3952 int rc;
3953 if( pFile->szChunk<=0 ){
3954 if( robust_ftruncate(pFile->h, nByte) ){
3955 storeLastErrno(pFile, errno);
3956 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3960 rc = unixMapfile(pFile, nByte);
3961 return rc;
3963 #endif
3965 return SQLITE_OK;
3969 ** If *pArg is initially negative then this is a query. Set *pArg to
3970 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3972 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3974 static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3975 if( *pArg<0 ){
3976 *pArg = (pFile->ctrlFlags & mask)!=0;
3977 }else if( (*pArg)==0 ){
3978 pFile->ctrlFlags &= ~mask;
3979 }else{
3980 pFile->ctrlFlags |= mask;
3984 /* Forward declaration */
3985 static int unixGetTempname(int nBuf, char *zBuf);
3986 #ifndef SQLITE_OMIT_WAL
3987 static int unixFcntlExternalReader(unixFile*, int*);
3988 #endif
3991 ** Information and control of an open file handle.
3993 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
3994 unixFile *pFile = (unixFile*)id;
3995 switch( op ){
3996 #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
3997 case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: {
3998 int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE);
3999 return rc ? SQLITE_IOERR_BEGIN_ATOMIC : SQLITE_OK;
4001 case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: {
4002 int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE);
4003 return rc ? SQLITE_IOERR_COMMIT_ATOMIC : SQLITE_OK;
4005 case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: {
4006 int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE);
4007 return rc ? SQLITE_IOERR_ROLLBACK_ATOMIC : SQLITE_OK;
4009 #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
4011 case SQLITE_FCNTL_LOCKSTATE: {
4012 *(int*)pArg = pFile->eFileLock;
4013 return SQLITE_OK;
4015 case SQLITE_FCNTL_LAST_ERRNO: {
4016 *(int*)pArg = pFile->lastErrno;
4017 return SQLITE_OK;
4019 case SQLITE_FCNTL_CHUNK_SIZE: {
4020 pFile->szChunk = *(int *)pArg;
4021 return SQLITE_OK;
4023 case SQLITE_FCNTL_SIZE_HINT: {
4024 int rc;
4025 SimulateIOErrorBenign(1);
4026 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
4027 SimulateIOErrorBenign(0);
4028 return rc;
4030 case SQLITE_FCNTL_PERSIST_WAL: {
4031 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
4032 return SQLITE_OK;
4034 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
4035 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
4036 return SQLITE_OK;
4038 case SQLITE_FCNTL_VFSNAME: {
4039 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
4040 return SQLITE_OK;
4042 case SQLITE_FCNTL_TEMPFILENAME: {
4043 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
4044 if( zTFile ){
4045 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
4046 *(char**)pArg = zTFile;
4048 return SQLITE_OK;
4050 case SQLITE_FCNTL_HAS_MOVED: {
4051 *(int*)pArg = fileHasMoved(pFile);
4052 return SQLITE_OK;
4054 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
4055 case SQLITE_FCNTL_LOCK_TIMEOUT: {
4056 int iOld = pFile->iBusyTimeout;
4057 #if SQLITE_ENABLE_SETLK_TIMEOUT==1
4058 pFile->iBusyTimeout = *(int*)pArg;
4059 #elif SQLITE_ENABLE_SETLK_TIMEOUT==2
4060 pFile->iBusyTimeout = !!(*(int*)pArg);
4061 #else
4062 # error "SQLITE_ENABLE_SETLK_TIMEOUT must be set to 1 or 2"
4063 #endif
4064 *(int*)pArg = iOld;
4065 return SQLITE_OK;
4067 #endif
4068 #if SQLITE_MAX_MMAP_SIZE>0
4069 case SQLITE_FCNTL_MMAP_SIZE: {
4070 i64 newLimit = *(i64*)pArg;
4071 int rc = SQLITE_OK;
4072 if( newLimit>sqlite3GlobalConfig.mxMmap ){
4073 newLimit = sqlite3GlobalConfig.mxMmap;
4076 /* The value of newLimit may be eventually cast to (size_t) and passed
4077 ** to mmap(). Restrict its value to 2GB if (size_t) is not at least a
4078 ** 64-bit type. */
4079 if( newLimit>0 && sizeof(size_t)<8 ){
4080 newLimit = (newLimit & 0x7FFFFFFF);
4083 *(i64*)pArg = pFile->mmapSizeMax;
4084 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
4085 pFile->mmapSizeMax = newLimit;
4086 if( pFile->mmapSize>0 ){
4087 unixUnmapfile(pFile);
4088 rc = unixMapfile(pFile, -1);
4091 return rc;
4093 #endif
4094 #ifdef SQLITE_DEBUG
4095 /* The pager calls this method to signal that it has done
4096 ** a rollback and that the database is therefore unchanged and
4097 ** it hence it is OK for the transaction change counter to be
4098 ** unchanged.
4100 case SQLITE_FCNTL_DB_UNCHANGED: {
4101 ((unixFile*)id)->dbUpdate = 0;
4102 return SQLITE_OK;
4104 #endif
4105 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
4106 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
4107 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
4108 return proxyFileControl(id,op,pArg);
4110 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
4112 case SQLITE_FCNTL_EXTERNAL_READER: {
4113 #ifndef SQLITE_OMIT_WAL
4114 return unixFcntlExternalReader((unixFile*)id, (int*)pArg);
4115 #else
4116 *(int*)pArg = 0;
4117 return SQLITE_OK;
4118 #endif
4121 return SQLITE_NOTFOUND;
4125 ** If pFd->sectorSize is non-zero when this function is called, it is a
4126 ** no-op. Otherwise, the values of pFd->sectorSize and
4127 ** pFd->deviceCharacteristics are set according to the file-system
4128 ** characteristics.
4130 ** There are two versions of this function. One for QNX and one for all
4131 ** other systems.
4133 #ifndef __QNXNTO__
4134 static void setDeviceCharacteristics(unixFile *pFd){
4135 assert( pFd->deviceCharacteristics==0 || pFd->sectorSize!=0 );
4136 if( pFd->sectorSize==0 ){
4137 #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
4138 int res;
4139 u32 f = 0;
4141 /* Check for support for F2FS atomic batch writes. */
4142 res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES, &f);
4143 if( res==0 && (f & F2FS_FEATURE_ATOMIC_WRITE) ){
4144 pFd->deviceCharacteristics = SQLITE_IOCAP_BATCH_ATOMIC;
4146 #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
4148 /* Set the POWERSAFE_OVERWRITE flag if requested. */
4149 if( pFd->ctrlFlags & UNIXFILE_PSOW ){
4150 pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
4153 pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4156 #else
4157 #include <sys/dcmd_blk.h>
4158 #include <sys/statvfs.h>
4159 static void setDeviceCharacteristics(unixFile *pFile){
4160 if( pFile->sectorSize == 0 ){
4161 struct statvfs fsInfo;
4163 /* Set defaults for non-supported filesystems */
4164 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4165 pFile->deviceCharacteristics = 0;
4166 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
4167 return;
4170 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
4171 pFile->sectorSize = fsInfo.f_bsize;
4172 pFile->deviceCharacteristics =
4173 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
4174 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4175 ** the write succeeds */
4176 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4177 ** so it is ordered */
4179 }else if( strstr(fsInfo.f_basetype, "etfs") ){
4180 pFile->sectorSize = fsInfo.f_bsize;
4181 pFile->deviceCharacteristics =
4182 /* etfs cluster size writes are atomic */
4183 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
4184 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4185 ** the write succeeds */
4186 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4187 ** so it is ordered */
4189 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
4190 pFile->sectorSize = fsInfo.f_bsize;
4191 pFile->deviceCharacteristics =
4192 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
4193 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4194 ** the write succeeds */
4195 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4196 ** so it is ordered */
4198 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
4199 pFile->sectorSize = fsInfo.f_bsize;
4200 pFile->deviceCharacteristics =
4201 /* full bitset of atomics from max sector size and smaller */
4202 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
4203 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4204 ** so it is ordered */
4206 }else if( strstr(fsInfo.f_basetype, "dos") ){
4207 pFile->sectorSize = fsInfo.f_bsize;
4208 pFile->deviceCharacteristics =
4209 /* full bitset of atomics from max sector size and smaller */
4210 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
4211 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4212 ** so it is ordered */
4214 }else{
4215 pFile->deviceCharacteristics =
4216 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
4217 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4218 ** the write succeeds */
4222 /* Last chance verification. If the sector size isn't a multiple of 512
4223 ** then it isn't valid.*/
4224 if( pFile->sectorSize % 512 != 0 ){
4225 pFile->deviceCharacteristics = 0;
4226 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4229 #endif
4232 ** Return the sector size in bytes of the underlying block device for
4233 ** the specified file. This is almost always 512 bytes, but may be
4234 ** larger for some devices.
4236 ** SQLite code assumes this function cannot fail. It also assumes that
4237 ** if two files are created in the same file-system directory (i.e.
4238 ** a database and its journal file) that the sector size will be the
4239 ** same for both.
4241 static int unixSectorSize(sqlite3_file *id){
4242 unixFile *pFd = (unixFile*)id;
4243 setDeviceCharacteristics(pFd);
4244 return pFd->sectorSize;
4248 ** Return the device characteristics for the file.
4250 ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
4251 ** However, that choice is controversial since technically the underlying
4252 ** file system does not always provide powersafe overwrites. (In other
4253 ** words, after a power-loss event, parts of the file that were never
4254 ** written might end up being altered.) However, non-PSOW behavior is very,
4255 ** very rare. And asserting PSOW makes a large reduction in the amount
4256 ** of required I/O for journaling, since a lot of padding is eliminated.
4257 ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
4258 ** available to turn it off and URI query parameter available to turn it off.
4260 static int unixDeviceCharacteristics(sqlite3_file *id){
4261 unixFile *pFd = (unixFile*)id;
4262 setDeviceCharacteristics(pFd);
4263 return pFd->deviceCharacteristics;
4266 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
4269 ** Return the system page size.
4271 ** This function should not be called directly by other code in this file.
4272 ** Instead, it should be called via macro osGetpagesize().
4274 static int unixGetpagesize(void){
4275 #if OS_VXWORKS
4276 return 1024;
4277 #elif defined(_BSD_SOURCE)
4278 return getpagesize();
4279 #else
4280 return (int)sysconf(_SC_PAGESIZE);
4281 #endif
4284 #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
4286 #ifndef SQLITE_OMIT_WAL
4289 ** Object used to represent an shared memory buffer.
4291 ** When multiple threads all reference the same wal-index, each thread
4292 ** has its own unixShm object, but they all point to a single instance
4293 ** of this unixShmNode object. In other words, each wal-index is opened
4294 ** only once per process.
4296 ** Each unixShmNode object is connected to a single unixInodeInfo object.
4297 ** We could coalesce this object into unixInodeInfo, but that would mean
4298 ** every open file that does not use shared memory (in other words, most
4299 ** open files) would have to carry around this extra information. So
4300 ** the unixInodeInfo object contains a pointer to this unixShmNode object
4301 ** and the unixShmNode object is created only when needed.
4303 ** unixMutexHeld() must be true when creating or destroying
4304 ** this object or while reading or writing the following fields:
4306 ** nRef
4308 ** The following fields are read-only after the object is created:
4310 ** hShm
4311 ** zFilename
4313 ** Either unixShmNode.pShmMutex must be held or unixShmNode.nRef==0 and
4314 ** unixMutexHeld() is true when reading or writing any other field
4315 ** in this structure.
4317 ** aLock[SQLITE_SHM_NLOCK]:
4318 ** This array records the various locks held by clients on each of the
4319 ** SQLITE_SHM_NLOCK slots. If the aLock[] entry is set to 0, then no
4320 ** locks are held by the process on this slot. If it is set to -1, then
4321 ** some client holds an EXCLUSIVE lock on the locking slot. If the aLock[]
4322 ** value is set to a positive value, then it is the number of shared
4323 ** locks currently held on the slot.
4325 ** aMutex[SQLITE_SHM_NLOCK]:
4326 ** Normally, when SQLITE_ENABLE_SETLK_TIMEOUT is not defined, mutex
4327 ** pShmMutex is used to protect the aLock[] array and the right to
4328 ** call fcntl() on unixShmNode.hShm to obtain or release locks.
4330 ** If SQLITE_ENABLE_SETLK_TIMEOUT is defined though, we use an array
4331 ** of mutexes - one for each locking slot. To read or write locking
4332 ** slot aLock[iSlot], the caller must hold the corresponding mutex
4333 ** aMutex[iSlot]. Similarly, to call fcntl() to obtain or release a
4334 ** lock corresponding to slot iSlot, mutex aMutex[iSlot] must be held.
4336 struct unixShmNode {
4337 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
4338 sqlite3_mutex *pShmMutex; /* Mutex to access this object */
4339 char *zFilename; /* Name of the mmapped file */
4340 int hShm; /* Open file descriptor */
4341 int szRegion; /* Size of shared-memory regions */
4342 u16 nRegion; /* Size of array apRegion */
4343 u8 isReadonly; /* True if read-only */
4344 u8 isUnlocked; /* True if no DMS lock held */
4345 char **apRegion; /* Array of mapped shared-memory regions */
4346 int nRef; /* Number of unixShm objects pointing to this */
4347 unixShm *pFirst; /* All unixShm objects pointing to this */
4348 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
4349 sqlite3_mutex *aMutex[SQLITE_SHM_NLOCK];
4350 #endif
4351 int aLock[SQLITE_SHM_NLOCK]; /* # shared locks on slot, -1==excl lock */
4352 #ifdef SQLITE_DEBUG
4353 u8 nextShmId; /* Next available unixShm.id value */
4354 #endif
4358 ** Structure used internally by this VFS to record the state of an
4359 ** open shared memory connection.
4361 ** The following fields are initialized when this object is created and
4362 ** are read-only thereafter:
4364 ** unixShm.pShmNode
4365 ** unixShm.id
4367 ** All other fields are read/write. The unixShm.pShmNode->pShmMutex must
4368 ** be held while accessing any read/write fields.
4370 struct unixShm {
4371 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4372 unixShm *pNext; /* Next unixShm with the same unixShmNode */
4373 u8 hasMutex; /* True if holding the unixShmNode->pShmMutex */
4374 u8 id; /* Id of this connection within its unixShmNode */
4375 u16 sharedMask; /* Mask of shared locks held */
4376 u16 exclMask; /* Mask of exclusive locks held */
4380 ** Constants used for locking
4382 #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
4383 #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
4386 ** Use F_GETLK to check whether or not there are any readers with open
4387 ** wal-mode transactions in other processes on database file pFile. If
4388 ** no error occurs, return SQLITE_OK and set (*piOut) to 1 if there are
4389 ** such transactions, or 0 otherwise. If an error occurs, return an
4390 ** SQLite error code. The final value of *piOut is undefined in this
4391 ** case.
4393 static int unixFcntlExternalReader(unixFile *pFile, int *piOut){
4394 int rc = SQLITE_OK;
4395 *piOut = 0;
4396 if( pFile->pShm){
4397 unixShmNode *pShmNode = pFile->pShm->pShmNode;
4398 struct flock f;
4400 memset(&f, 0, sizeof(f));
4401 f.l_type = F_WRLCK;
4402 f.l_whence = SEEK_SET;
4403 f.l_start = UNIX_SHM_BASE + 3;
4404 f.l_len = SQLITE_SHM_NLOCK - 3;
4406 sqlite3_mutex_enter(pShmNode->pShmMutex);
4407 if( osFcntl(pShmNode->hShm, F_GETLK, &f)<0 ){
4408 rc = SQLITE_IOERR_LOCK;
4409 }else{
4410 *piOut = (f.l_type!=F_UNLCK);
4412 sqlite3_mutex_leave(pShmNode->pShmMutex);
4415 return rc;
4420 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
4422 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4423 ** otherwise.
4425 static int unixShmSystemLock(
4426 unixFile *pFile, /* Open connection to the WAL file */
4427 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
4428 int ofst, /* First byte of the locking range */
4429 int n /* Number of bytes to lock */
4431 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4432 struct flock f; /* The posix advisory locking structure */
4433 int rc = SQLITE_OK; /* Result code form fcntl() */
4435 pShmNode = pFile->pInode->pShmNode;
4437 /* Assert that the parameters are within expected range and that the
4438 ** correct mutex or mutexes are held. */
4439 assert( pShmNode->nRef>=0 );
4440 assert( (ofst==UNIX_SHM_DMS && n==1)
4441 || (ofst>=UNIX_SHM_BASE && ofst+n<=(UNIX_SHM_BASE+SQLITE_SHM_NLOCK))
4443 if( ofst==UNIX_SHM_DMS ){
4444 assert( pShmNode->nRef>0 || unixMutexHeld() );
4445 assert( pShmNode->nRef==0 || sqlite3_mutex_held(pShmNode->pShmMutex) );
4446 }else{
4447 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
4448 int ii;
4449 for(ii=ofst-UNIX_SHM_BASE; ii<ofst-UNIX_SHM_BASE+n; ii++){
4450 assert( sqlite3_mutex_held(pShmNode->aMutex[ii]) );
4452 #else
4453 assert( sqlite3_mutex_held(pShmNode->pShmMutex) );
4454 assert( pShmNode->nRef>0 );
4455 #endif
4458 /* Shared locks never span more than one byte */
4459 assert( n==1 || lockType!=F_RDLCK );
4461 /* Locks are within range */
4462 assert( n>=1 && n<=SQLITE_SHM_NLOCK );
4463 assert( ofst>=UNIX_SHM_BASE && ofst<=(UNIX_SHM_DMS+SQLITE_SHM_NLOCK) );
4465 if( pShmNode->hShm>=0 ){
4466 int res;
4467 /* Initialize the locking parameters */
4468 f.l_type = lockType;
4469 f.l_whence = SEEK_SET;
4470 f.l_start = ofst;
4471 f.l_len = n;
4472 res = osSetPosixAdvisoryLock(pShmNode->hShm, &f, pFile);
4473 if( res==-1 ){
4474 #if defined(SQLITE_ENABLE_SETLK_TIMEOUT) && SQLITE_ENABLE_SETLK_TIMEOUT==1
4475 rc = (pFile->iBusyTimeout ? SQLITE_BUSY_TIMEOUT : SQLITE_BUSY);
4476 #else
4477 rc = SQLITE_BUSY;
4478 #endif
4482 /* Do debug tracing */
4483 #ifdef SQLITE_DEBUG
4484 OSTRACE(("SHM-LOCK "));
4485 if( rc==SQLITE_OK ){
4486 if( lockType==F_UNLCK ){
4487 OSTRACE(("unlock %d..%d ok\n", ofst, ofst+n-1));
4488 }else if( lockType==F_RDLCK ){
4489 OSTRACE(("read-lock %d..%d ok\n", ofst, ofst+n-1));
4490 }else{
4491 assert( lockType==F_WRLCK );
4492 OSTRACE(("write-lock %d..%d ok\n", ofst, ofst+n-1));
4494 }else{
4495 if( lockType==F_UNLCK ){
4496 OSTRACE(("unlock %d..%d failed\n", ofst, ofst+n-1));
4497 }else if( lockType==F_RDLCK ){
4498 OSTRACE(("read-lock %d..%d failed\n", ofst, ofst+n-1));
4499 }else{
4500 assert( lockType==F_WRLCK );
4501 OSTRACE(("write-lock %d..%d failed\n", ofst, ofst+n-1));
4504 #endif
4506 return rc;
4510 ** Return the minimum number of 32KB shm regions that should be mapped at
4511 ** a time, assuming that each mapping must be an integer multiple of the
4512 ** current system page-size.
4514 ** Usually, this is 1. The exception seems to be systems that are configured
4515 ** to use 64KB pages - in this case each mapping must cover at least two
4516 ** shm regions.
4518 static int unixShmRegionPerMap(void){
4519 int shmsz = 32*1024; /* SHM region size */
4520 int pgsz = osGetpagesize(); /* System page size */
4521 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4522 if( pgsz<shmsz ) return 1;
4523 return pgsz/shmsz;
4527 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
4529 ** This is not a VFS shared-memory method; it is a utility function called
4530 ** by VFS shared-memory methods.
4532 static void unixShmPurge(unixFile *pFd){
4533 unixShmNode *p = pFd->pInode->pShmNode;
4534 assert( unixMutexHeld() );
4535 if( p && ALWAYS(p->nRef==0) ){
4536 int nShmPerMap = unixShmRegionPerMap();
4537 int i;
4538 assert( p->pInode==pFd->pInode );
4539 sqlite3_mutex_free(p->pShmMutex);
4540 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
4541 for(i=0; i<SQLITE_SHM_NLOCK; i++){
4542 sqlite3_mutex_free(p->aMutex[i]);
4544 #endif
4545 for(i=0; i<p->nRegion; i+=nShmPerMap){
4546 if( p->hShm>=0 ){
4547 osMunmap(p->apRegion[i], p->szRegion);
4548 }else{
4549 sqlite3_free(p->apRegion[i]);
4552 sqlite3_free(p->apRegion);
4553 if( p->hShm>=0 ){
4554 robust_close(pFd, p->hShm, __LINE__);
4555 p->hShm = -1;
4557 p->pInode->pShmNode = 0;
4558 sqlite3_free(p);
4563 ** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
4564 ** take it now. Return SQLITE_OK if successful, or an SQLite error
4565 ** code otherwise.
4567 ** If the DMS cannot be locked because this is a readonly_shm=1
4568 ** connection and no other process already holds a lock, return
4569 ** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
4571 static int unixLockSharedMemory(unixFile *pDbFd, unixShmNode *pShmNode){
4572 struct flock lock;
4573 int rc = SQLITE_OK;
4575 /* Use F_GETLK to determine the locks other processes are holding
4576 ** on the DMS byte. If it indicates that another process is holding
4577 ** a SHARED lock, then this process may also take a SHARED lock
4578 ** and proceed with opening the *-shm file.
4580 ** Or, if no other process is holding any lock, then this process
4581 ** is the first to open it. In this case take an EXCLUSIVE lock on the
4582 ** DMS byte and truncate the *-shm file to zero bytes in size. Then
4583 ** downgrade to a SHARED lock on the DMS byte.
4585 ** If another process is holding an EXCLUSIVE lock on the DMS byte,
4586 ** return SQLITE_BUSY to the caller (it will try again). An earlier
4587 ** version of this code attempted the SHARED lock at this point. But
4588 ** this introduced a subtle race condition: if the process holding
4589 ** EXCLUSIVE failed just before truncating the *-shm file, then this
4590 ** process might open and use the *-shm file without truncating it.
4591 ** And if the *-shm file has been corrupted by a power failure or
4592 ** system crash, the database itself may also become corrupt. */
4593 lock.l_whence = SEEK_SET;
4594 lock.l_start = UNIX_SHM_DMS;
4595 lock.l_len = 1;
4596 lock.l_type = F_WRLCK;
4597 if( osFcntl(pShmNode->hShm, F_GETLK, &lock)!=0 ) {
4598 rc = SQLITE_IOERR_LOCK;
4599 }else if( lock.l_type==F_UNLCK ){
4600 if( pShmNode->isReadonly ){
4601 pShmNode->isUnlocked = 1;
4602 rc = SQLITE_READONLY_CANTINIT;
4603 }else{
4604 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
4605 /* Do not use a blocking lock here. If the lock cannot be obtained
4606 ** immediately, it means some other connection is truncating the
4607 ** *-shm file. And after it has done so, it will not release its
4608 ** lock, but only downgrade it to a shared lock. So no point in
4609 ** blocking here. The call below to obtain the shared DMS lock may
4610 ** use a blocking lock. */
4611 int iSaveTimeout = pDbFd->iBusyTimeout;
4612 pDbFd->iBusyTimeout = 0;
4613 #endif
4614 rc = unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1);
4615 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
4616 pDbFd->iBusyTimeout = iSaveTimeout;
4617 #endif
4618 /* The first connection to attach must truncate the -shm file. We
4619 ** truncate to 3 bytes (an arbitrary small number, less than the
4620 ** -shm header size) rather than 0 as a system debugging aid, to
4621 ** help detect if a -shm file truncation is legitimate or is the work
4622 ** or a rogue process. */
4623 if( rc==SQLITE_OK && robust_ftruncate(pShmNode->hShm, 3) ){
4624 rc = unixLogError(SQLITE_IOERR_SHMOPEN,"ftruncate",pShmNode->zFilename);
4627 }else if( lock.l_type==F_WRLCK ){
4628 rc = SQLITE_BUSY;
4631 if( rc==SQLITE_OK ){
4632 assert( lock.l_type==F_UNLCK || lock.l_type==F_RDLCK );
4633 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
4635 return rc;
4639 ** Open a shared-memory area associated with open database file pDbFd.
4640 ** This particular implementation uses mmapped files.
4642 ** The file used to implement shared-memory is in the same directory
4643 ** as the open database file and has the same name as the open database
4644 ** file with the "-shm" suffix added. For example, if the database file
4645 ** is "/home/user1/config.db" then the file that is created and mmapped
4646 ** for shared memory will be called "/home/user1/config.db-shm".
4648 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
4649 ** some other tmpfs mount. But if a file in a different directory
4650 ** from the database file is used, then differing access permissions
4651 ** or a chroot() might cause two different processes on the same
4652 ** database to end up using different files for shared memory -
4653 ** meaning that their memory would not really be shared - resulting
4654 ** in database corruption. Nevertheless, this tmpfs file usage
4655 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4656 ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4657 ** option results in an incompatible build of SQLite; builds of SQLite
4658 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4659 ** same database file at the same time, database corruption will likely
4660 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4661 ** "unsupported" and may go away in a future SQLite release.
4663 ** When opening a new shared-memory file, if no other instances of that
4664 ** file are currently open, in this process or in other processes, then
4665 ** the file must be truncated to zero length or have its header cleared.
4667 ** If the original database file (pDbFd) is using the "unix-excl" VFS
4668 ** that means that an exclusive lock is held on the database file and
4669 ** that no other processes are able to read or write the database. In
4670 ** that case, we do not really need shared memory. No shared memory
4671 ** file is created. The shared memory will be simulated with heap memory.
4673 static int unixOpenSharedMemory(unixFile *pDbFd){
4674 struct unixShm *p = 0; /* The connection to be opened */
4675 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4676 int rc = SQLITE_OK; /* Result code */
4677 unixInodeInfo *pInode; /* The inode of fd */
4678 char *zShm; /* Name of the file used for SHM */
4679 int nShmFilename; /* Size of the SHM filename in bytes */
4681 /* Allocate space for the new unixShm object. */
4682 p = sqlite3_malloc64( sizeof(*p) );
4683 if( p==0 ) return SQLITE_NOMEM_BKPT;
4684 memset(p, 0, sizeof(*p));
4685 assert( pDbFd->pShm==0 );
4687 /* Check to see if a unixShmNode object already exists. Reuse an existing
4688 ** one if present. Create a new one if necessary.
4690 assert( unixFileMutexNotheld(pDbFd) );
4691 unixEnterMutex();
4692 pInode = pDbFd->pInode;
4693 pShmNode = pInode->pShmNode;
4694 if( pShmNode==0 ){
4695 struct stat sStat; /* fstat() info for database file */
4696 #ifndef SQLITE_SHM_DIRECTORY
4697 const char *zBasePath = pDbFd->zPath;
4698 #endif
4700 /* Call fstat() to figure out the permissions on the database file. If
4701 ** a new *-shm file is created, an attempt will be made to create it
4702 ** with the same permissions.
4704 if( osFstat(pDbFd->h, &sStat) ){
4705 rc = SQLITE_IOERR_FSTAT;
4706 goto shm_open_err;
4709 #ifdef SQLITE_SHM_DIRECTORY
4710 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
4711 #else
4712 nShmFilename = 6 + (int)strlen(zBasePath);
4713 #endif
4714 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
4715 if( pShmNode==0 ){
4716 rc = SQLITE_NOMEM_BKPT;
4717 goto shm_open_err;
4719 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
4720 zShm = pShmNode->zFilename = (char*)&pShmNode[1];
4721 #ifdef SQLITE_SHM_DIRECTORY
4722 sqlite3_snprintf(nShmFilename, zShm,
4723 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4724 (u32)sStat.st_ino, (u32)sStat.st_dev);
4725 #else
4726 sqlite3_snprintf(nShmFilename, zShm, "%s-shm", zBasePath);
4727 sqlite3FileSuffix3(pDbFd->zPath, zShm);
4728 #endif
4729 pShmNode->hShm = -1;
4730 pDbFd->pInode->pShmNode = pShmNode;
4731 pShmNode->pInode = pDbFd->pInode;
4732 if( sqlite3GlobalConfig.bCoreMutex ){
4733 pShmNode->pShmMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4734 if( pShmNode->pShmMutex==0 ){
4735 rc = SQLITE_NOMEM_BKPT;
4736 goto shm_open_err;
4738 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
4740 int ii;
4741 for(ii=0; ii<SQLITE_SHM_NLOCK; ii++){
4742 pShmNode->aMutex[ii] = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4743 if( pShmNode->aMutex[ii]==0 ){
4744 rc = SQLITE_NOMEM_BKPT;
4745 goto shm_open_err;
4749 #endif
4752 if( pInode->bProcessLock==0 ){
4753 if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
4754 pShmNode->hShm = robust_open(zShm, O_RDWR|O_CREAT|O_NOFOLLOW,
4755 (sStat.st_mode&0777));
4757 if( pShmNode->hShm<0 ){
4758 pShmNode->hShm = robust_open(zShm, O_RDONLY|O_NOFOLLOW,
4759 (sStat.st_mode&0777));
4760 if( pShmNode->hShm<0 ){
4761 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShm);
4762 goto shm_open_err;
4764 pShmNode->isReadonly = 1;
4767 /* If this process is running as root, make sure that the SHM file
4768 ** is owned by the same user that owns the original database. Otherwise,
4769 ** the original owner will not be able to connect.
4771 robustFchown(pShmNode->hShm, sStat.st_uid, sStat.st_gid);
4773 rc = unixLockSharedMemory(pDbFd, pShmNode);
4774 if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
4778 /* Make the new connection a child of the unixShmNode */
4779 p->pShmNode = pShmNode;
4780 #ifdef SQLITE_DEBUG
4781 p->id = pShmNode->nextShmId++;
4782 #endif
4783 pShmNode->nRef++;
4784 pDbFd->pShm = p;
4785 unixLeaveMutex();
4787 /* The reference count on pShmNode has already been incremented under
4788 ** the cover of the unixEnterMutex() mutex and the pointer from the
4789 ** new (struct unixShm) object to the pShmNode has been set. All that is
4790 ** left to do is to link the new object into the linked list starting
4791 ** at pShmNode->pFirst. This must be done while holding the
4792 ** pShmNode->pShmMutex.
4794 sqlite3_mutex_enter(pShmNode->pShmMutex);
4795 p->pNext = pShmNode->pFirst;
4796 pShmNode->pFirst = p;
4797 sqlite3_mutex_leave(pShmNode->pShmMutex);
4798 return rc;
4800 /* Jump here on any error */
4801 shm_open_err:
4802 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
4803 sqlite3_free(p);
4804 unixLeaveMutex();
4805 return rc;
4809 ** This function is called to obtain a pointer to region iRegion of the
4810 ** shared-memory associated with the database file fd. Shared-memory regions
4811 ** are numbered starting from zero. Each shared-memory region is szRegion
4812 ** bytes in size.
4814 ** If an error occurs, an error code is returned and *pp is set to NULL.
4816 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4817 ** region has not been allocated (by any client, including one running in a
4818 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4819 ** bExtend is non-zero and the requested shared-memory region has not yet
4820 ** been allocated, it is allocated by this function.
4822 ** If the shared-memory region has already been allocated or is allocated by
4823 ** this call as described above, then it is mapped into this processes
4824 ** address space (if it is not already), *pp is set to point to the mapped
4825 ** memory and SQLITE_OK returned.
4827 static int unixShmMap(
4828 sqlite3_file *fd, /* Handle open on database file */
4829 int iRegion, /* Region to retrieve */
4830 int szRegion, /* Size of regions */
4831 int bExtend, /* True to extend file if necessary */
4832 void volatile **pp /* OUT: Mapped memory */
4834 unixFile *pDbFd = (unixFile*)fd;
4835 unixShm *p;
4836 unixShmNode *pShmNode;
4837 int rc = SQLITE_OK;
4838 int nShmPerMap = unixShmRegionPerMap();
4839 int nReqRegion;
4841 /* If the shared-memory file has not yet been opened, open it now. */
4842 if( pDbFd->pShm==0 ){
4843 rc = unixOpenSharedMemory(pDbFd);
4844 if( rc!=SQLITE_OK ) return rc;
4847 p = pDbFd->pShm;
4848 pShmNode = p->pShmNode;
4849 sqlite3_mutex_enter(pShmNode->pShmMutex);
4850 if( pShmNode->isUnlocked ){
4851 rc = unixLockSharedMemory(pDbFd, pShmNode);
4852 if( rc!=SQLITE_OK ) goto shmpage_out;
4853 pShmNode->isUnlocked = 0;
4855 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
4856 assert( pShmNode->pInode==pDbFd->pInode );
4857 assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );
4858 assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );
4860 /* Minimum number of regions required to be mapped. */
4861 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4863 if( pShmNode->nRegion<nReqRegion ){
4864 char **apNew; /* New apRegion[] array */
4865 int nByte = nReqRegion*szRegion; /* Minimum required file size */
4866 struct stat sStat; /* Used by fstat() */
4868 pShmNode->szRegion = szRegion;
4870 if( pShmNode->hShm>=0 ){
4871 /* The requested region is not mapped into this processes address space.
4872 ** Check to see if it has been allocated (i.e. if the wal-index file is
4873 ** large enough to contain the requested region).
4875 if( osFstat(pShmNode->hShm, &sStat) ){
4876 rc = SQLITE_IOERR_SHMSIZE;
4877 goto shmpage_out;
4880 if( sStat.st_size<nByte ){
4881 /* The requested memory region does not exist. If bExtend is set to
4882 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
4884 if( !bExtend ){
4885 goto shmpage_out;
4888 /* Alternatively, if bExtend is true, extend the file. Do this by
4889 ** writing a single byte to the end of each (OS) page being
4890 ** allocated or extended. Technically, we need only write to the
4891 ** last page in order to extend the file. But writing to all new
4892 ** pages forces the OS to allocate them immediately, which reduces
4893 ** the chances of SIGBUS while accessing the mapped region later on.
4895 else{
4896 static const int pgsz = 4096;
4897 int iPg;
4899 /* Write to the last byte of each newly allocated or extended page */
4900 assert( (nByte % pgsz)==0 );
4901 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
4902 int x = 0;
4903 if( seekAndWriteFd(pShmNode->hShm, iPg*pgsz + pgsz-1,"",1,&x)!=1 ){
4904 const char *zFile = pShmNode->zFilename;
4905 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4906 goto shmpage_out;
4913 /* Map the requested memory region into this processes address space. */
4914 apNew = (char **)sqlite3_realloc(
4915 pShmNode->apRegion, nReqRegion*sizeof(char *)
4917 if( !apNew ){
4918 rc = SQLITE_IOERR_NOMEM_BKPT;
4919 goto shmpage_out;
4921 pShmNode->apRegion = apNew;
4922 while( pShmNode->nRegion<nReqRegion ){
4923 int nMap = szRegion*nShmPerMap;
4924 int i;
4925 void *pMem;
4926 if( pShmNode->hShm>=0 ){
4927 pMem = osMmap(0, nMap,
4928 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
4929 MAP_SHARED, pShmNode->hShm, szRegion*(i64)pShmNode->nRegion
4931 if( pMem==MAP_FAILED ){
4932 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
4933 goto shmpage_out;
4935 }else{
4936 pMem = sqlite3_malloc64(nMap);
4937 if( pMem==0 ){
4938 rc = SQLITE_NOMEM_BKPT;
4939 goto shmpage_out;
4941 memset(pMem, 0, nMap);
4944 for(i=0; i<nShmPerMap; i++){
4945 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4947 pShmNode->nRegion += nShmPerMap;
4951 shmpage_out:
4952 if( pShmNode->nRegion>iRegion ){
4953 *pp = pShmNode->apRegion[iRegion];
4954 }else{
4955 *pp = 0;
4957 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
4958 sqlite3_mutex_leave(pShmNode->pShmMutex);
4959 return rc;
4963 ** Check that the pShmNode->aLock[] array comports with the locking bitmasks
4964 ** held by each client. Return true if it does, or false otherwise. This
4965 ** is to be used in an assert(). e.g.
4967 ** assert( assertLockingArrayOk(pShmNode) );
4969 #ifdef SQLITE_DEBUG
4970 static int assertLockingArrayOk(unixShmNode *pShmNode){
4971 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
4972 return 1;
4973 #else
4974 unixShm *pX;
4975 int aLock[SQLITE_SHM_NLOCK];
4977 memset(aLock, 0, sizeof(aLock));
4978 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4979 int i;
4980 for(i=0; i<SQLITE_SHM_NLOCK; i++){
4981 if( pX->exclMask & (1<<i) ){
4982 assert( aLock[i]==0 );
4983 aLock[i] = -1;
4984 }else if( pX->sharedMask & (1<<i) ){
4985 assert( aLock[i]>=0 );
4986 aLock[i]++;
4991 assert( 0==memcmp(pShmNode->aLock, aLock, sizeof(aLock)) );
4992 return (memcmp(pShmNode->aLock, aLock, sizeof(aLock))==0);
4993 #endif
4995 #endif
4998 ** Change the lock state for a shared-memory segment.
5000 ** Note that the relationship between SHARED and EXCLUSIVE locks is a little
5001 ** different here than in posix. In xShmLock(), one can go from unlocked
5002 ** to shared and back or from unlocked to exclusive and back. But one may
5003 ** not go from shared to exclusive or from exclusive to shared.
5005 static int unixShmLock(
5006 sqlite3_file *fd, /* Database file holding the shared memory */
5007 int ofst, /* First lock to acquire or release */
5008 int n, /* Number of locks to acquire or release */
5009 int flags /* What to do with the lock */
5011 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
5012 unixShm *p; /* The shared memory being locked */
5013 unixShmNode *pShmNode; /* The underlying file iNode */
5014 int rc = SQLITE_OK; /* Result code */
5015 u16 mask = (1<<(ofst+n)) - (1<<ofst); /* Mask of locks to take or release */
5016 int *aLock;
5018 p = pDbFd->pShm;
5019 if( p==0 ) return SQLITE_IOERR_SHMLOCK;
5020 pShmNode = p->pShmNode;
5021 if( NEVER(pShmNode==0) ) return SQLITE_IOERR_SHMLOCK;
5022 aLock = pShmNode->aLock;
5024 assert( pShmNode==pDbFd->pInode->pShmNode );
5025 assert( pShmNode->pInode==pDbFd->pInode );
5026 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
5027 assert( n>=1 );
5028 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
5029 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
5030 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
5031 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
5032 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
5033 assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );
5034 assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );
5036 /* Check that, if this to be a blocking lock, no locks that occur later
5037 ** in the following list than the lock being obtained are already held:
5039 ** 1. Checkpointer lock (ofst==1).
5040 ** 2. Write lock (ofst==0).
5041 ** 3. Read locks (ofst>=3 && ofst<SQLITE_SHM_NLOCK).
5043 ** In other words, if this is a blocking lock, none of the locks that
5044 ** occur later in the above list than the lock being obtained may be
5045 ** held.
5047 ** It is not permitted to block on the RECOVER lock.
5049 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
5051 u16 lockMask = (p->exclMask|p->sharedMask);
5052 assert( (flags & SQLITE_SHM_UNLOCK) || pDbFd->iBusyTimeout==0 || (
5053 (ofst!=2) /* not RECOVER */
5054 && (ofst!=1 || lockMask==0 || lockMask==2)
5055 && (ofst!=0 || lockMask<3)
5056 && (ofst<3 || lockMask<(1<<ofst))
5059 #endif
5061 /* Check if there is any work to do. There are three cases:
5063 ** a) An unlock operation where there are locks to unlock,
5064 ** b) An shared lock where the requested lock is not already held
5065 ** c) An exclusive lock where the requested lock is not already held
5067 ** The SQLite core never requests an exclusive lock that it already holds.
5068 ** This is assert()ed below.
5070 assert( flags!=(SQLITE_SHM_EXCLUSIVE|SQLITE_SHM_LOCK)
5071 || 0==(p->exclMask & mask)
5073 if( ((flags & SQLITE_SHM_UNLOCK) && ((p->exclMask|p->sharedMask) & mask))
5074 || (flags==(SQLITE_SHM_SHARED|SQLITE_SHM_LOCK) && 0==(p->sharedMask & mask))
5075 || (flags==(SQLITE_SHM_EXCLUSIVE|SQLITE_SHM_LOCK))
5078 /* Take the required mutexes. In SETLK_TIMEOUT mode (blocking locks), if
5079 ** this is an attempt on an exclusive lock use sqlite3_mutex_try(). If any
5080 ** other thread is holding this mutex, then it is either holding or about
5081 ** to hold a lock exclusive to the one being requested, and we may
5082 ** therefore return SQLITE_BUSY to the caller.
5084 ** Doing this prevents some deadlock scenarios. For example, thread 1 may
5085 ** be a checkpointer blocked waiting on the WRITER lock. And thread 2
5086 ** may be a normal SQL client upgrading to a write transaction. In this
5087 ** case thread 2 does a non-blocking request for the WRITER lock. But -
5088 ** if it were to use sqlite3_mutex_enter() then it would effectively
5089 ** become a (doomed) blocking request, as thread 2 would block until thread
5090 ** 1 obtained WRITER and released the mutex. Since thread 2 already holds
5091 ** a lock on a read-locking slot at this point, this breaks the
5092 ** anti-deadlock rules (see above). */
5093 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
5094 int iMutex;
5095 for(iMutex=ofst; iMutex<ofst+n; iMutex++){
5096 if( flags==(SQLITE_SHM_LOCK|SQLITE_SHM_EXCLUSIVE) ){
5097 rc = sqlite3_mutex_try(pShmNode->aMutex[iMutex]);
5098 if( rc!=SQLITE_OK ) goto leave_shmnode_mutexes;
5099 }else{
5100 sqlite3_mutex_enter(pShmNode->aMutex[iMutex]);
5103 #else
5104 sqlite3_mutex_enter(pShmNode->pShmMutex);
5105 #endif
5107 if( ALWAYS(rc==SQLITE_OK) ){
5108 if( flags & SQLITE_SHM_UNLOCK ){
5109 /* Case (a) - unlock. */
5110 int bUnlock = 1;
5111 assert( (p->exclMask & p->sharedMask)==0 );
5112 assert( !(flags & SQLITE_SHM_EXCLUSIVE) || (p->exclMask & mask)==mask );
5113 assert( !(flags & SQLITE_SHM_SHARED) || (p->sharedMask & mask)==mask );
5115 /* If this is a SHARED lock being unlocked, it is possible that other
5116 ** clients within this process are holding the same SHARED lock. In
5117 ** this case, set bUnlock to 0 so that the posix lock is not removed
5118 ** from the file-descriptor below. */
5119 if( flags & SQLITE_SHM_SHARED ){
5120 assert( n==1 );
5121 assert( aLock[ofst]>=1 );
5122 if( aLock[ofst]>1 ){
5123 bUnlock = 0;
5124 aLock[ofst]--;
5125 p->sharedMask &= ~mask;
5129 if( bUnlock ){
5130 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
5131 if( rc==SQLITE_OK ){
5132 memset(&aLock[ofst], 0, sizeof(int)*n);
5133 p->sharedMask &= ~mask;
5134 p->exclMask &= ~mask;
5137 }else if( flags & SQLITE_SHM_SHARED ){
5138 /* Case (b) - a shared lock. */
5140 if( aLock[ofst]<0 ){
5141 /* An exclusive lock is held by some other connection. BUSY. */
5142 rc = SQLITE_BUSY;
5143 }else if( aLock[ofst]==0 ){
5144 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
5147 /* Get the local shared locks */
5148 if( rc==SQLITE_OK ){
5149 p->sharedMask |= mask;
5150 aLock[ofst]++;
5152 }else{
5153 /* Case (c) - an exclusive lock. */
5154 int ii;
5156 assert( flags==(SQLITE_SHM_LOCK|SQLITE_SHM_EXCLUSIVE) );
5157 assert( (p->sharedMask & mask)==0 );
5158 assert( (p->exclMask & mask)==0 );
5160 /* Make sure no sibling connections hold locks that will block this
5161 ** lock. If any do, return SQLITE_BUSY right away. */
5162 for(ii=ofst; ii<ofst+n; ii++){
5163 if( aLock[ii] ){
5164 rc = SQLITE_BUSY;
5165 break;
5169 /* Get the exclusive locks at the system level. Then if successful
5170 ** also update the in-memory values. */
5171 if( rc==SQLITE_OK ){
5172 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
5173 if( rc==SQLITE_OK ){
5174 p->exclMask |= mask;
5175 for(ii=ofst; ii<ofst+n; ii++){
5176 aLock[ii] = -1;
5181 assert( assertLockingArrayOk(pShmNode) );
5184 /* Drop the mutexes acquired above. */
5185 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
5186 leave_shmnode_mutexes:
5187 for(iMutex--; iMutex>=ofst; iMutex--){
5188 sqlite3_mutex_leave(pShmNode->aMutex[iMutex]);
5190 #else
5191 sqlite3_mutex_leave(pShmNode->pShmMutex);
5192 #endif
5195 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
5196 p->id, osGetpid(0), p->sharedMask, p->exclMask));
5197 return rc;
5201 ** Implement a memory barrier or memory fence on shared memory.
5203 ** All loads and stores begun before the barrier must complete before
5204 ** any load or store begun after the barrier.
5206 static void unixShmBarrier(
5207 sqlite3_file *fd /* Database file holding the shared memory */
5209 UNUSED_PARAMETER(fd);
5210 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
5211 assert( fd->pMethods->xLock==nolockLock
5212 || unixFileMutexNotheld((unixFile*)fd)
5214 unixEnterMutex(); /* Also mutex, for redundancy */
5215 unixLeaveMutex();
5219 ** Close a connection to shared-memory. Delete the underlying
5220 ** storage if deleteFlag is true.
5222 ** If there is no shared memory associated with the connection then this
5223 ** routine is a harmless no-op.
5225 static int unixShmUnmap(
5226 sqlite3_file *fd, /* The underlying database file */
5227 int deleteFlag /* Delete shared-memory if true */
5229 unixShm *p; /* The connection to be closed */
5230 unixShmNode *pShmNode; /* The underlying shared-memory file */
5231 unixShm **pp; /* For looping over sibling connections */
5232 unixFile *pDbFd; /* The underlying database file */
5234 pDbFd = (unixFile*)fd;
5235 p = pDbFd->pShm;
5236 if( p==0 ) return SQLITE_OK;
5237 pShmNode = p->pShmNode;
5239 assert( pShmNode==pDbFd->pInode->pShmNode );
5240 assert( pShmNode->pInode==pDbFd->pInode );
5242 /* Remove connection p from the set of connections associated
5243 ** with pShmNode */
5244 sqlite3_mutex_enter(pShmNode->pShmMutex);
5245 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
5246 *pp = p->pNext;
5248 /* Free the connection p */
5249 sqlite3_free(p);
5250 pDbFd->pShm = 0;
5251 sqlite3_mutex_leave(pShmNode->pShmMutex);
5253 /* If pShmNode->nRef has reached 0, then close the underlying
5254 ** shared-memory file, too */
5255 assert( unixFileMutexNotheld(pDbFd) );
5256 unixEnterMutex();
5257 assert( pShmNode->nRef>0 );
5258 pShmNode->nRef--;
5259 if( pShmNode->nRef==0 ){
5260 if( deleteFlag && pShmNode->hShm>=0 ){
5261 osUnlink(pShmNode->zFilename);
5263 unixShmPurge(pDbFd);
5265 unixLeaveMutex();
5267 return SQLITE_OK;
5271 #else
5272 # define unixShmMap 0
5273 # define unixShmLock 0
5274 # define unixShmBarrier 0
5275 # define unixShmUnmap 0
5276 #endif /* #ifndef SQLITE_OMIT_WAL */
5278 #if SQLITE_MAX_MMAP_SIZE>0
5280 ** If it is currently memory mapped, unmap file pFd.
5282 static void unixUnmapfile(unixFile *pFd){
5283 assert( pFd->nFetchOut==0 );
5284 if( pFd->pMapRegion ){
5285 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
5286 pFd->pMapRegion = 0;
5287 pFd->mmapSize = 0;
5288 pFd->mmapSizeActual = 0;
5293 ** Attempt to set the size of the memory mapping maintained by file
5294 ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
5296 ** If successful, this function sets the following variables:
5298 ** unixFile.pMapRegion
5299 ** unixFile.mmapSize
5300 ** unixFile.mmapSizeActual
5302 ** If unsuccessful, an error message is logged via sqlite3_log() and
5303 ** the three variables above are zeroed. In this case SQLite should
5304 ** continue accessing the database using the xRead() and xWrite()
5305 ** methods.
5307 static void unixRemapfile(
5308 unixFile *pFd, /* File descriptor object */
5309 i64 nNew /* Required mapping size */
5311 const char *zErr = "mmap";
5312 int h = pFd->h; /* File descriptor open on db file */
5313 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
5314 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
5315 u8 *pNew = 0; /* Location of new mapping */
5316 int flags = PROT_READ; /* Flags to pass to mmap() */
5318 assert( pFd->nFetchOut==0 );
5319 assert( nNew>pFd->mmapSize );
5320 assert( nNew<=pFd->mmapSizeMax );
5321 assert( nNew>0 );
5322 assert( pFd->mmapSizeActual>=pFd->mmapSize );
5323 assert( MAP_FAILED!=0 );
5325 #ifdef SQLITE_MMAP_READWRITE
5326 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
5327 #endif
5329 if( pOrig ){
5330 #if HAVE_MREMAP
5331 i64 nReuse = pFd->mmapSize;
5332 #else
5333 const int szSyspage = osGetpagesize();
5334 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
5335 #endif
5336 u8 *pReq = &pOrig[nReuse];
5338 /* Unmap any pages of the existing mapping that cannot be reused. */
5339 if( nReuse!=nOrig ){
5340 osMunmap(pReq, nOrig-nReuse);
5343 #if HAVE_MREMAP
5344 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
5345 zErr = "mremap";
5346 #else
5347 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
5348 if( pNew!=MAP_FAILED ){
5349 if( pNew!=pReq ){
5350 osMunmap(pNew, nNew - nReuse);
5351 pNew = 0;
5352 }else{
5353 pNew = pOrig;
5356 #endif
5358 /* The attempt to extend the existing mapping failed. Free it. */
5359 if( pNew==MAP_FAILED || pNew==0 ){
5360 osMunmap(pOrig, nReuse);
5364 /* If pNew is still NULL, try to create an entirely new mapping. */
5365 if( pNew==0 ){
5366 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
5369 if( pNew==MAP_FAILED ){
5370 pNew = 0;
5371 nNew = 0;
5372 unixLogError(SQLITE_OK, zErr, pFd->zPath);
5374 /* If the mmap() above failed, assume that all subsequent mmap() calls
5375 ** will probably fail too. Fall back to using xRead/xWrite exclusively
5376 ** in this case. */
5377 pFd->mmapSizeMax = 0;
5379 pFd->pMapRegion = (void *)pNew;
5380 pFd->mmapSize = pFd->mmapSizeActual = nNew;
5384 ** Memory map or remap the file opened by file-descriptor pFd (if the file
5385 ** is already mapped, the existing mapping is replaced by the new). Or, if
5386 ** there already exists a mapping for this file, and there are still
5387 ** outstanding xFetch() references to it, this function is a no-op.
5389 ** If parameter nByte is non-negative, then it is the requested size of
5390 ** the mapping to create. Otherwise, if nByte is less than zero, then the
5391 ** requested size is the size of the file on disk. The actual size of the
5392 ** created mapping is either the requested size or the value configured
5393 ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
5395 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
5396 ** recreated as a result of outstanding references) or an SQLite error
5397 ** code otherwise.
5399 static int unixMapfile(unixFile *pFd, i64 nMap){
5400 assert( nMap>=0 || pFd->nFetchOut==0 );
5401 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
5402 if( pFd->nFetchOut>0 ) return SQLITE_OK;
5404 if( nMap<0 ){
5405 struct stat statbuf; /* Low-level file information */
5406 if( osFstat(pFd->h, &statbuf) ){
5407 return SQLITE_IOERR_FSTAT;
5409 nMap = statbuf.st_size;
5411 if( nMap>pFd->mmapSizeMax ){
5412 nMap = pFd->mmapSizeMax;
5415 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
5416 if( nMap!=pFd->mmapSize ){
5417 unixRemapfile(pFd, nMap);
5420 return SQLITE_OK;
5422 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
5425 ** If possible, return a pointer to a mapping of file fd starting at offset
5426 ** iOff. The mapping must be valid for at least nAmt bytes.
5428 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
5429 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
5430 ** Finally, if an error does occur, return an SQLite error code. The final
5431 ** value of *pp is undefined in this case.
5433 ** If this function does return a pointer, the caller must eventually
5434 ** release the reference by calling unixUnfetch().
5436 static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
5437 #if SQLITE_MAX_MMAP_SIZE>0
5438 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
5439 #endif
5440 *pp = 0;
5442 #if SQLITE_MAX_MMAP_SIZE>0
5443 if( pFd->mmapSizeMax>0 ){
5444 /* Ensure that there is always at least a 256 byte buffer of addressable
5445 ** memory following the returned page. If the database is corrupt,
5446 ** SQLite may overread the page slightly (in practice only a few bytes,
5447 ** but 256 is safe, round, number). */
5448 const int nEofBuffer = 256;
5449 if( pFd->pMapRegion==0 ){
5450 int rc = unixMapfile(pFd, -1);
5451 if( rc!=SQLITE_OK ) return rc;
5453 if( pFd->mmapSize >= (iOff+nAmt+nEofBuffer) ){
5454 *pp = &((u8 *)pFd->pMapRegion)[iOff];
5455 pFd->nFetchOut++;
5458 #endif
5459 return SQLITE_OK;
5463 ** If the third argument is non-NULL, then this function releases a
5464 ** reference obtained by an earlier call to unixFetch(). The second
5465 ** argument passed to this function must be the same as the corresponding
5466 ** argument that was passed to the unixFetch() invocation.
5468 ** Or, if the third argument is NULL, then this function is being called
5469 ** to inform the VFS layer that, according to POSIX, any existing mapping
5470 ** may now be invalid and should be unmapped.
5472 static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
5473 #if SQLITE_MAX_MMAP_SIZE>0
5474 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
5475 UNUSED_PARAMETER(iOff);
5477 /* If p==0 (unmap the entire file) then there must be no outstanding
5478 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
5479 ** then there must be at least one outstanding. */
5480 assert( (p==0)==(pFd->nFetchOut==0) );
5482 /* If p!=0, it must match the iOff value. */
5483 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
5485 if( p ){
5486 pFd->nFetchOut--;
5487 }else{
5488 unixUnmapfile(pFd);
5491 assert( pFd->nFetchOut>=0 );
5492 #else
5493 UNUSED_PARAMETER(fd);
5494 UNUSED_PARAMETER(p);
5495 UNUSED_PARAMETER(iOff);
5496 #endif
5497 return SQLITE_OK;
5501 ** Here ends the implementation of all sqlite3_file methods.
5503 ********************** End sqlite3_file Methods *******************************
5504 ******************************************************************************/
5507 ** This division contains definitions of sqlite3_io_methods objects that
5508 ** implement various file locking strategies. It also contains definitions
5509 ** of "finder" functions. A finder-function is used to locate the appropriate
5510 ** sqlite3_io_methods object for a particular database file. The pAppData
5511 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
5512 ** the correct finder-function for that VFS.
5514 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
5515 ** object. The only interesting finder-function is autolockIoFinder, which
5516 ** looks at the filesystem type and tries to guess the best locking
5517 ** strategy from that.
5519 ** For finder-function F, two objects are created:
5521 ** (1) The real finder-function named "FImpt()".
5523 ** (2) A constant pointer to this function named just "F".
5526 ** A pointer to the F pointer is used as the pAppData value for VFS
5527 ** objects. We have to do this instead of letting pAppData point
5528 ** directly at the finder-function since C90 rules prevent a void*
5529 ** from be cast into a function pointer.
5532 ** Each instance of this macro generates two objects:
5534 ** * A constant sqlite3_io_methods object call METHOD that has locking
5535 ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
5537 ** * An I/O method finder function called FINDER that returns a pointer
5538 ** to the METHOD object in the previous bullet.
5540 #define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
5541 static const sqlite3_io_methods METHOD = { \
5542 VERSION, /* iVersion */ \
5543 CLOSE, /* xClose */ \
5544 unixRead, /* xRead */ \
5545 unixWrite, /* xWrite */ \
5546 unixTruncate, /* xTruncate */ \
5547 unixSync, /* xSync */ \
5548 unixFileSize, /* xFileSize */ \
5549 LOCK, /* xLock */ \
5550 UNLOCK, /* xUnlock */ \
5551 CKLOCK, /* xCheckReservedLock */ \
5552 unixFileControl, /* xFileControl */ \
5553 unixSectorSize, /* xSectorSize */ \
5554 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
5555 SHMMAP, /* xShmMap */ \
5556 unixShmLock, /* xShmLock */ \
5557 unixShmBarrier, /* xShmBarrier */ \
5558 unixShmUnmap, /* xShmUnmap */ \
5559 unixFetch, /* xFetch */ \
5560 unixUnfetch, /* xUnfetch */ \
5561 }; \
5562 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
5563 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
5564 return &METHOD; \
5566 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
5567 = FINDER##Impl;
5570 ** Here are all of the sqlite3_io_methods objects for each of the
5571 ** locking strategies. Functions that return pointers to these methods
5572 ** are also created.
5574 IOMETHODS(
5575 posixIoFinder, /* Finder function name */
5576 posixIoMethods, /* sqlite3_io_methods object name */
5577 3, /* shared memory and mmap are enabled */
5578 unixClose, /* xClose method */
5579 unixLock, /* xLock method */
5580 unixUnlock, /* xUnlock method */
5581 unixCheckReservedLock, /* xCheckReservedLock method */
5582 unixShmMap /* xShmMap method */
5584 IOMETHODS(
5585 nolockIoFinder, /* Finder function name */
5586 nolockIoMethods, /* sqlite3_io_methods object name */
5587 3, /* shared memory and mmap are enabled */
5588 nolockClose, /* xClose method */
5589 nolockLock, /* xLock method */
5590 nolockUnlock, /* xUnlock method */
5591 nolockCheckReservedLock, /* xCheckReservedLock method */
5592 0 /* xShmMap method */
5594 IOMETHODS(
5595 dotlockIoFinder, /* Finder function name */
5596 dotlockIoMethods, /* sqlite3_io_methods object name */
5597 1, /* shared memory is disabled */
5598 dotlockClose, /* xClose method */
5599 dotlockLock, /* xLock method */
5600 dotlockUnlock, /* xUnlock method */
5601 dotlockCheckReservedLock, /* xCheckReservedLock method */
5602 0 /* xShmMap method */
5605 #if SQLITE_ENABLE_LOCKING_STYLE
5606 IOMETHODS(
5607 flockIoFinder, /* Finder function name */
5608 flockIoMethods, /* sqlite3_io_methods object name */
5609 1, /* shared memory is disabled */
5610 flockClose, /* xClose method */
5611 flockLock, /* xLock method */
5612 flockUnlock, /* xUnlock method */
5613 flockCheckReservedLock, /* xCheckReservedLock method */
5614 0 /* xShmMap method */
5616 #endif
5618 #if OS_VXWORKS
5619 IOMETHODS(
5620 semIoFinder, /* Finder function name */
5621 semIoMethods, /* sqlite3_io_methods object name */
5622 1, /* shared memory is disabled */
5623 semXClose, /* xClose method */
5624 semXLock, /* xLock method */
5625 semXUnlock, /* xUnlock method */
5626 semXCheckReservedLock, /* xCheckReservedLock method */
5627 0 /* xShmMap method */
5629 #endif
5631 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5632 IOMETHODS(
5633 afpIoFinder, /* Finder function name */
5634 afpIoMethods, /* sqlite3_io_methods object name */
5635 1, /* shared memory is disabled */
5636 afpClose, /* xClose method */
5637 afpLock, /* xLock method */
5638 afpUnlock, /* xUnlock method */
5639 afpCheckReservedLock, /* xCheckReservedLock method */
5640 0 /* xShmMap method */
5642 #endif
5645 ** The proxy locking method is a "super-method" in the sense that it
5646 ** opens secondary file descriptors for the conch and lock files and
5647 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
5648 ** secondary files. For this reason, the division that implements
5649 ** proxy locking is located much further down in the file. But we need
5650 ** to go ahead and define the sqlite3_io_methods and finder function
5651 ** for proxy locking here. So we forward declare the I/O methods.
5653 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5654 static int proxyClose(sqlite3_file*);
5655 static int proxyLock(sqlite3_file*, int);
5656 static int proxyUnlock(sqlite3_file*, int);
5657 static int proxyCheckReservedLock(sqlite3_file*, int*);
5658 IOMETHODS(
5659 proxyIoFinder, /* Finder function name */
5660 proxyIoMethods, /* sqlite3_io_methods object name */
5661 1, /* shared memory is disabled */
5662 proxyClose, /* xClose method */
5663 proxyLock, /* xLock method */
5664 proxyUnlock, /* xUnlock method */
5665 proxyCheckReservedLock, /* xCheckReservedLock method */
5666 0 /* xShmMap method */
5668 #endif
5670 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5671 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5672 IOMETHODS(
5673 nfsIoFinder, /* Finder function name */
5674 nfsIoMethods, /* sqlite3_io_methods object name */
5675 1, /* shared memory is disabled */
5676 unixClose, /* xClose method */
5677 unixLock, /* xLock method */
5678 nfsUnlock, /* xUnlock method */
5679 unixCheckReservedLock, /* xCheckReservedLock method */
5680 0 /* xShmMap method */
5682 #endif
5684 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5686 ** This "finder" function attempts to determine the best locking strategy
5687 ** for the database file "filePath". It then returns the sqlite3_io_methods
5688 ** object that implements that strategy.
5690 ** This is for MacOSX only.
5692 static const sqlite3_io_methods *autolockIoFinderImpl(
5693 const char *filePath, /* name of the database file */
5694 unixFile *pNew /* open file object for the database file */
5696 static const struct Mapping {
5697 const char *zFilesystem; /* Filesystem type name */
5698 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
5699 } aMap[] = {
5700 { "hfs", &posixIoMethods },
5701 { "ufs", &posixIoMethods },
5702 { "afpfs", &afpIoMethods },
5703 { "smbfs", &afpIoMethods },
5704 { "webdav", &nolockIoMethods },
5705 { 0, 0 }
5707 int i;
5708 struct statfs fsInfo;
5709 struct flock lockInfo;
5711 if( !filePath ){
5712 /* If filePath==NULL that means we are dealing with a transient file
5713 ** that does not need to be locked. */
5714 return &nolockIoMethods;
5716 if( statfs(filePath, &fsInfo) != -1 ){
5717 if( fsInfo.f_flags & MNT_RDONLY ){
5718 return &nolockIoMethods;
5720 for(i=0; aMap[i].zFilesystem; i++){
5721 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5722 return aMap[i].pMethods;
5727 /* Default case. Handles, amongst others, "nfs".
5728 ** Test byte-range lock using fcntl(). If the call succeeds,
5729 ** assume that the file-system supports POSIX style locks.
5731 lockInfo.l_len = 1;
5732 lockInfo.l_start = 0;
5733 lockInfo.l_whence = SEEK_SET;
5734 lockInfo.l_type = F_RDLCK;
5735 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
5736 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5737 return &nfsIoMethods;
5738 } else {
5739 return &posixIoMethods;
5741 }else{
5742 return &dotlockIoMethods;
5745 static const sqlite3_io_methods
5746 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
5748 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
5750 #if OS_VXWORKS
5752 ** This "finder" function for VxWorks checks to see if posix advisory
5753 ** locking works. If it does, then that is what is used. If it does not
5754 ** work, then fallback to named semaphore locking.
5756 static const sqlite3_io_methods *vxworksIoFinderImpl(
5757 const char *filePath, /* name of the database file */
5758 unixFile *pNew /* the open file object */
5760 struct flock lockInfo;
5762 if( !filePath ){
5763 /* If filePath==NULL that means we are dealing with a transient file
5764 ** that does not need to be locked. */
5765 return &nolockIoMethods;
5768 /* Test if fcntl() is supported and use POSIX style locks.
5769 ** Otherwise fall back to the named semaphore method.
5771 lockInfo.l_len = 1;
5772 lockInfo.l_start = 0;
5773 lockInfo.l_whence = SEEK_SET;
5774 lockInfo.l_type = F_RDLCK;
5775 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
5776 return &posixIoMethods;
5777 }else{
5778 return &semIoMethods;
5781 static const sqlite3_io_methods
5782 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
5784 #endif /* OS_VXWORKS */
5787 ** An abstract type for a pointer to an IO method finder function:
5789 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
5792 /****************************************************************************
5793 **************************** sqlite3_vfs methods ****************************
5795 ** This division contains the implementation of methods on the
5796 ** sqlite3_vfs object.
5800 ** Initialize the contents of the unixFile structure pointed to by pId.
5802 static int fillInUnixFile(
5803 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5804 int h, /* Open file descriptor of file being opened */
5805 sqlite3_file *pId, /* Write to the unixFile structure here */
5806 const char *zFilename, /* Name of the file being opened */
5807 int ctrlFlags /* Zero or more UNIXFILE_* values */
5809 const sqlite3_io_methods *pLockingStyle;
5810 unixFile *pNew = (unixFile *)pId;
5811 int rc = SQLITE_OK;
5813 assert( pNew->pInode==NULL );
5815 /* No locking occurs in temporary files */
5816 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
5818 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
5819 pNew->h = h;
5820 pNew->pVfs = pVfs;
5821 pNew->zPath = zFilename;
5822 pNew->ctrlFlags = (u8)ctrlFlags;
5823 #if SQLITE_MAX_MMAP_SIZE>0
5824 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
5825 #endif
5826 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5827 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
5828 pNew->ctrlFlags |= UNIXFILE_PSOW;
5830 if( strcmp(pVfs->zName,"unix-excl")==0 ){
5831 pNew->ctrlFlags |= UNIXFILE_EXCL;
5834 #if OS_VXWORKS
5835 pNew->pId = vxworksFindFileId(zFilename);
5836 if( pNew->pId==0 ){
5837 ctrlFlags |= UNIXFILE_NOLOCK;
5838 rc = SQLITE_NOMEM_BKPT;
5840 #endif
5842 if( ctrlFlags & UNIXFILE_NOLOCK ){
5843 pLockingStyle = &nolockIoMethods;
5844 }else{
5845 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
5846 #if SQLITE_ENABLE_LOCKING_STYLE
5847 /* Cache zFilename in the locking context (AFP and dotlock override) for
5848 ** proxyLock activation is possible (remote proxy is based on db name)
5849 ** zFilename remains valid until file is closed, to support */
5850 pNew->lockingContext = (void*)zFilename;
5851 #endif
5854 if( pLockingStyle == &posixIoMethods
5855 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5856 || pLockingStyle == &nfsIoMethods
5857 #endif
5859 unixEnterMutex();
5860 rc = findInodeInfo(pNew, &pNew->pInode);
5861 if( rc!=SQLITE_OK ){
5862 /* If an error occurred in findInodeInfo(), close the file descriptor
5863 ** immediately, before releasing the mutex. findInodeInfo() may fail
5864 ** in two scenarios:
5866 ** (a) A call to fstat() failed.
5867 ** (b) A malloc failed.
5869 ** Scenario (b) may only occur if the process is holding no other
5870 ** file descriptors open on the same file. If there were other file
5871 ** descriptors on this file, then no malloc would be required by
5872 ** findInodeInfo(). If this is the case, it is quite safe to close
5873 ** handle h - as it is guaranteed that no posix locks will be released
5874 ** by doing so.
5876 ** If scenario (a) caused the error then things are not so safe. The
5877 ** implicit assumption here is that if fstat() fails, things are in
5878 ** such bad shape that dropping a lock or two doesn't matter much.
5880 robust_close(pNew, h, __LINE__);
5881 h = -1;
5883 unixLeaveMutex();
5886 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
5887 else if( pLockingStyle == &afpIoMethods ){
5888 /* AFP locking uses the file path so it needs to be included in
5889 ** the afpLockingContext.
5891 afpLockingContext *pCtx;
5892 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
5893 if( pCtx==0 ){
5894 rc = SQLITE_NOMEM_BKPT;
5895 }else{
5896 /* NB: zFilename exists and remains valid until the file is closed
5897 ** according to requirement F11141. So we do not need to make a
5898 ** copy of the filename. */
5899 pCtx->dbPath = zFilename;
5900 pCtx->reserved = 0;
5901 srandomdev();
5902 unixEnterMutex();
5903 rc = findInodeInfo(pNew, &pNew->pInode);
5904 if( rc!=SQLITE_OK ){
5905 sqlite3_free(pNew->lockingContext);
5906 robust_close(pNew, h, __LINE__);
5907 h = -1;
5909 unixLeaveMutex();
5912 #endif
5914 else if( pLockingStyle == &dotlockIoMethods ){
5915 /* Dotfile locking uses the file path so it needs to be included in
5916 ** the dotlockLockingContext
5918 char *zLockFile;
5919 int nFilename;
5920 assert( zFilename!=0 );
5921 nFilename = (int)strlen(zFilename) + 6;
5922 zLockFile = (char *)sqlite3_malloc64(nFilename);
5923 if( zLockFile==0 ){
5924 rc = SQLITE_NOMEM_BKPT;
5925 }else{
5926 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
5928 pNew->lockingContext = zLockFile;
5931 #if OS_VXWORKS
5932 else if( pLockingStyle == &semIoMethods ){
5933 /* Named semaphore locking uses the file path so it needs to be
5934 ** included in the semLockingContext
5936 unixEnterMutex();
5937 rc = findInodeInfo(pNew, &pNew->pInode);
5938 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5939 char *zSemName = pNew->pInode->aSemName;
5940 int n;
5941 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
5942 pNew->pId->zCanonicalName);
5943 for( n=1; zSemName[n]; n++ )
5944 if( zSemName[n]=='/' ) zSemName[n] = '_';
5945 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5946 if( pNew->pInode->pSem == SEM_FAILED ){
5947 rc = SQLITE_NOMEM_BKPT;
5948 pNew->pInode->aSemName[0] = '\0';
5951 unixLeaveMutex();
5953 #endif
5955 storeLastErrno(pNew, 0);
5956 #if OS_VXWORKS
5957 if( rc!=SQLITE_OK ){
5958 if( h>=0 ) robust_close(pNew, h, __LINE__);
5959 h = -1;
5960 osUnlink(zFilename);
5961 pNew->ctrlFlags |= UNIXFILE_DELETE;
5963 #endif
5964 if( rc!=SQLITE_OK ){
5965 if( h>=0 ) robust_close(pNew, h, __LINE__);
5966 }else{
5967 pId->pMethods = pLockingStyle;
5968 OpenCounter(+1);
5969 verifyDbFile(pNew);
5971 return rc;
5975 ** Directories to consider for temp files.
5977 static const char *azTempDirs[] = {
5980 "/var/tmp",
5981 "/usr/tmp",
5982 "/tmp",
5987 ** Initialize first two members of azTempDirs[] array.
5989 static void unixTempFileInit(void){
5990 azTempDirs[0] = getenv("SQLITE_TMPDIR");
5991 azTempDirs[1] = getenv("TMPDIR");
5995 ** Return the name of a directory in which to put temporary files.
5996 ** If no suitable temporary file directory can be found, return NULL.
5998 static const char *unixTempFileDir(void){
5999 unsigned int i = 0;
6000 struct stat buf;
6001 const char *zDir = sqlite3_temp_directory;
6003 while(1){
6004 if( zDir!=0
6005 && osStat(zDir, &buf)==0
6006 && S_ISDIR(buf.st_mode)
6007 && osAccess(zDir, 03)==0
6009 return zDir;
6011 if( i>=sizeof(azTempDirs)/sizeof(azTempDirs[0]) ) break;
6012 zDir = azTempDirs[i++];
6014 return 0;
6018 ** Create a temporary file name in zBuf. zBuf must be allocated
6019 ** by the calling process and must be big enough to hold at least
6020 ** pVfs->mxPathname bytes.
6022 static int unixGetTempname(int nBuf, char *zBuf){
6023 const char *zDir;
6024 int iLimit = 0;
6025 int rc = SQLITE_OK;
6027 /* It's odd to simulate an io-error here, but really this is just
6028 ** using the io-error infrastructure to test that SQLite handles this
6029 ** function failing.
6031 zBuf[0] = 0;
6032 SimulateIOError( return SQLITE_IOERR );
6034 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
6035 zDir = unixTempFileDir();
6036 if( zDir==0 ){
6037 rc = SQLITE_IOERR_GETTEMPPATH;
6038 }else{
6040 u64 r;
6041 sqlite3_randomness(sizeof(r), &r);
6042 assert( nBuf>2 );
6043 zBuf[nBuf-2] = 0;
6044 sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
6045 zDir, r, 0);
6046 if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ){
6047 rc = SQLITE_ERROR;
6048 break;
6050 }while( osAccess(zBuf,0)==0 );
6052 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
6053 return rc;
6056 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
6058 ** Routine to transform a unixFile into a proxy-locking unixFile.
6059 ** Implementation in the proxy-lock division, but used by unixOpen()
6060 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
6062 static int proxyTransformUnixFile(unixFile*, const char*);
6063 #endif
6066 ** Search for an unused file descriptor that was opened on the database
6067 ** file (not a journal or super-journal file) identified by pathname
6068 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
6069 ** argument to this function.
6071 ** Such a file descriptor may exist if a database connection was closed
6072 ** but the associated file descriptor could not be closed because some
6073 ** other file descriptor open on the same file is holding a file-lock.
6074 ** Refer to comments in the unixClose() function and the lengthy comment
6075 ** describing "Posix Advisory Locking" at the start of this file for
6076 ** further details. Also, ticket #4018.
6078 ** If a suitable file descriptor is found, then it is returned. If no
6079 ** such file descriptor is located, -1 is returned.
6081 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
6082 UnixUnusedFd *pUnused = 0;
6084 /* Do not search for an unused file descriptor on vxworks. Not because
6085 ** vxworks would not benefit from the change (it might, we're not sure),
6086 ** but because no way to test it is currently available. It is better
6087 ** not to risk breaking vxworks support for the sake of such an obscure
6088 ** feature. */
6089 #if !OS_VXWORKS
6090 struct stat sStat; /* Results of stat() call */
6092 unixEnterMutex();
6094 /* A stat() call may fail for various reasons. If this happens, it is
6095 ** almost certain that an open() call on the same path will also fail.
6096 ** For this reason, if an error occurs in the stat() call here, it is
6097 ** ignored and -1 is returned. The caller will try to open a new file
6098 ** descriptor on the same path, fail, and return an error to SQLite.
6100 ** Even if a subsequent open() call does succeed, the consequences of
6101 ** not searching for a reusable file descriptor are not dire. */
6102 if( inodeList!=0 && 0==osStat(zPath, &sStat) ){
6103 unixInodeInfo *pInode;
6105 pInode = inodeList;
6106 while( pInode && (pInode->fileId.dev!=sStat.st_dev
6107 || pInode->fileId.ino!=(u64)sStat.st_ino) ){
6108 pInode = pInode->pNext;
6110 if( pInode ){
6111 UnixUnusedFd **pp;
6112 assert( sqlite3_mutex_notheld(pInode->pLockMutex) );
6113 sqlite3_mutex_enter(pInode->pLockMutex);
6114 flags &= (SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE);
6115 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
6116 pUnused = *pp;
6117 if( pUnused ){
6118 *pp = pUnused->pNext;
6120 sqlite3_mutex_leave(pInode->pLockMutex);
6123 unixLeaveMutex();
6124 #endif /* if !OS_VXWORKS */
6125 return pUnused;
6129 ** Find the mode, uid and gid of file zFile.
6131 static int getFileMode(
6132 const char *zFile, /* File name */
6133 mode_t *pMode, /* OUT: Permissions of zFile */
6134 uid_t *pUid, /* OUT: uid of zFile. */
6135 gid_t *pGid /* OUT: gid of zFile. */
6137 struct stat sStat; /* Output of stat() on database file */
6138 int rc = SQLITE_OK;
6139 if( 0==osStat(zFile, &sStat) ){
6140 *pMode = sStat.st_mode & 0777;
6141 *pUid = sStat.st_uid;
6142 *pGid = sStat.st_gid;
6143 }else{
6144 rc = SQLITE_IOERR_FSTAT;
6146 return rc;
6150 ** This function is called by unixOpen() to determine the unix permissions
6151 ** to create new files with. If no error occurs, then SQLITE_OK is returned
6152 ** and a value suitable for passing as the third argument to open(2) is
6153 ** written to *pMode. If an IO error occurs, an SQLite error code is
6154 ** returned and the value of *pMode is not modified.
6156 ** In most cases, this routine sets *pMode to 0, which will become
6157 ** an indication to robust_open() to create the file using
6158 ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
6159 ** But if the file being opened is a WAL or regular journal file, then
6160 ** this function queries the file-system for the permissions on the
6161 ** corresponding database file and sets *pMode to this value. Whenever
6162 ** possible, WAL and journal files are created using the same permissions
6163 ** as the associated database file.
6165 ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
6166 ** original filename is unavailable. But 8_3_NAMES is only used for
6167 ** FAT filesystems and permissions do not matter there, so just use
6168 ** the default permissions. In 8_3_NAMES mode, leave *pMode set to zero.
6170 static int findCreateFileMode(
6171 const char *zPath, /* Path of file (possibly) being created */
6172 int flags, /* Flags passed as 4th argument to xOpen() */
6173 mode_t *pMode, /* OUT: Permissions to open file with */
6174 uid_t *pUid, /* OUT: uid to set on the file */
6175 gid_t *pGid /* OUT: gid to set on the file */
6177 int rc = SQLITE_OK; /* Return Code */
6178 *pMode = 0;
6179 *pUid = 0;
6180 *pGid = 0;
6181 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
6182 char zDb[MAX_PATHNAME+1]; /* Database file path */
6183 int nDb; /* Number of valid bytes in zDb */
6185 /* zPath is a path to a WAL or journal file. The following block derives
6186 ** the path to the associated database file from zPath. This block handles
6187 ** the following naming conventions:
6189 ** "<path to db>-journal"
6190 ** "<path to db>-wal"
6191 ** "<path to db>-journalNN"
6192 ** "<path to db>-walNN"
6194 ** where NN is a decimal number. The NN naming schemes are
6195 ** used by the test_multiplex.c module.
6197 ** In normal operation, the journal file name will always contain
6198 ** a '-' character. However in 8+3 filename mode, or if a corrupt
6199 ** rollback journal specifies a super-journal with a goofy name, then
6200 ** the '-' might be missing or the '-' might be the first character in
6201 ** the filename. In that case, just return SQLITE_OK with *pMode==0.
6203 nDb = sqlite3Strlen30(zPath) - 1;
6204 while( nDb>0 && zPath[nDb]!='.' ){
6205 if( zPath[nDb]=='-' ){
6206 memcpy(zDb, zPath, nDb);
6207 zDb[nDb] = '\0';
6208 rc = getFileMode(zDb, pMode, pUid, pGid);
6209 break;
6211 nDb--;
6213 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
6214 *pMode = 0600;
6215 }else if( flags & SQLITE_OPEN_URI ){
6216 /* If this is a main database file and the file was opened using a URI
6217 ** filename, check for the "modeof" parameter. If present, interpret
6218 ** its value as a filename and try to copy the mode, uid and gid from
6219 ** that file. */
6220 const char *z = sqlite3_uri_parameter(zPath, "modeof");
6221 if( z ){
6222 rc = getFileMode(z, pMode, pUid, pGid);
6225 return rc;
6229 ** Open the file zPath.
6231 ** Previously, the SQLite OS layer used three functions in place of this
6232 ** one:
6234 ** sqlite3OsOpenReadWrite();
6235 ** sqlite3OsOpenReadOnly();
6236 ** sqlite3OsOpenExclusive();
6238 ** These calls correspond to the following combinations of flags:
6240 ** ReadWrite() -> (READWRITE | CREATE)
6241 ** ReadOnly() -> (READONLY)
6242 ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
6244 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
6245 ** true, the file was configured to be automatically deleted when the
6246 ** file handle closed. To achieve the same effect using this new
6247 ** interface, add the DELETEONCLOSE flag to those specified above for
6248 ** OpenExclusive().
6250 static int unixOpen(
6251 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
6252 const char *zPath, /* Pathname of file to be opened */
6253 sqlite3_file *pFile, /* The file descriptor to be filled in */
6254 int flags, /* Input flags to control the opening */
6255 int *pOutFlags /* Output flags returned to SQLite core */
6257 unixFile *p = (unixFile *)pFile;
6258 int fd = -1; /* File descriptor returned by open() */
6259 int openFlags = 0; /* Flags to pass to open() */
6260 int eType = flags&0x0FFF00; /* Type of file to open */
6261 int noLock; /* True to omit locking primitives */
6262 int rc = SQLITE_OK; /* Function Return Code */
6263 int ctrlFlags = 0; /* UNIXFILE_* flags */
6265 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
6266 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
6267 int isCreate = (flags & SQLITE_OPEN_CREATE);
6268 int isReadonly = (flags & SQLITE_OPEN_READONLY);
6269 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
6270 #if SQLITE_ENABLE_LOCKING_STYLE
6271 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
6272 #endif
6273 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
6274 struct statfs fsInfo;
6275 #endif
6277 /* If creating a super- or main-file journal, this function will open
6278 ** a file-descriptor on the directory too. The first time unixSync()
6279 ** is called the directory file descriptor will be fsync()ed and close()d.
6281 int isNewJrnl = (isCreate && (
6282 eType==SQLITE_OPEN_SUPER_JOURNAL
6283 || eType==SQLITE_OPEN_MAIN_JOURNAL
6284 || eType==SQLITE_OPEN_WAL
6287 /* If argument zPath is a NULL pointer, this function is required to open
6288 ** a temporary file. Use this buffer to store the file name in.
6290 char zTmpname[MAX_PATHNAME+2];
6291 const char *zName = zPath;
6293 /* Check the following statements are true:
6295 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
6296 ** (b) if CREATE is set, then READWRITE must also be set, and
6297 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
6298 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
6300 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
6301 assert(isCreate==0 || isReadWrite);
6302 assert(isExclusive==0 || isCreate);
6303 assert(isDelete==0 || isCreate);
6305 /* The main DB, main journal, WAL file and super-journal are never
6306 ** automatically deleted. Nor are they ever temporary files. */
6307 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
6308 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
6309 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_SUPER_JOURNAL );
6310 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
6312 /* Assert that the upper layer has set one of the "file-type" flags. */
6313 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
6314 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
6315 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_SUPER_JOURNAL
6316 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
6319 /* Detect a pid change and reset the PRNG. There is a race condition
6320 ** here such that two or more threads all trying to open databases at
6321 ** the same instant might all reset the PRNG. But multiple resets
6322 ** are harmless.
6324 if( randomnessPid!=osGetpid(0) ){
6325 randomnessPid = osGetpid(0);
6326 sqlite3_randomness(0,0);
6328 memset(p, 0, sizeof(unixFile));
6330 #ifdef SQLITE_ASSERT_NO_FILES
6331 /* Applications that never read or write a persistent disk files */
6332 assert( zName==0 );
6333 #endif
6335 if( eType==SQLITE_OPEN_MAIN_DB ){
6336 UnixUnusedFd *pUnused;
6337 pUnused = findReusableFd(zName, flags);
6338 if( pUnused ){
6339 fd = pUnused->fd;
6340 }else{
6341 pUnused = sqlite3_malloc64(sizeof(*pUnused));
6342 if( !pUnused ){
6343 return SQLITE_NOMEM_BKPT;
6346 p->pPreallocatedUnused = pUnused;
6348 /* Database filenames are double-zero terminated if they are not
6349 ** URIs with parameters. Hence, they can always be passed into
6350 ** sqlite3_uri_parameter(). */
6351 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
6353 }else if( !zName ){
6354 /* If zName is NULL, the upper layer is requesting a temp file. */
6355 assert(isDelete && !isNewJrnl);
6356 rc = unixGetTempname(pVfs->mxPathname, zTmpname);
6357 if( rc!=SQLITE_OK ){
6358 return rc;
6360 zName = zTmpname;
6362 /* Generated temporary filenames are always double-zero terminated
6363 ** for use by sqlite3_uri_parameter(). */
6364 assert( zName[strlen(zName)+1]==0 );
6367 /* Determine the value of the flags parameter passed to POSIX function
6368 ** open(). These must be calculated even if open() is not called, as
6369 ** they may be stored as part of the file handle and used by the
6370 ** 'conch file' locking functions later on. */
6371 if( isReadonly ) openFlags |= O_RDONLY;
6372 if( isReadWrite ) openFlags |= O_RDWR;
6373 if( isCreate ) openFlags |= O_CREAT;
6374 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
6375 openFlags |= (O_LARGEFILE|O_BINARY|O_NOFOLLOW);
6377 if( fd<0 ){
6378 mode_t openMode; /* Permissions to create file with */
6379 uid_t uid; /* Userid for the file */
6380 gid_t gid; /* Groupid for the file */
6381 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
6382 if( rc!=SQLITE_OK ){
6383 assert( !p->pPreallocatedUnused );
6384 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
6385 return rc;
6387 fd = robust_open(zName, openFlags, openMode);
6388 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
6389 assert( !isExclusive || (openFlags & O_CREAT)!=0 );
6390 if( fd<0 ){
6391 if( isNewJrnl && errno==EACCES && osAccess(zName, F_OK) ){
6392 /* If unable to create a journal because the directory is not
6393 ** writable, change the error code to indicate that. */
6394 rc = SQLITE_READONLY_DIRECTORY;
6395 }else if( errno!=EISDIR && isReadWrite ){
6396 /* Failed to open the file for read/write access. Try read-only. */
6397 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
6398 openFlags &= ~(O_RDWR|O_CREAT);
6399 flags |= SQLITE_OPEN_READONLY;
6400 openFlags |= O_RDONLY;
6401 isReadonly = 1;
6402 fd = robust_open(zName, openFlags, openMode);
6405 if( fd<0 ){
6406 int rc2 = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
6407 if( rc==SQLITE_OK ) rc = rc2;
6408 goto open_finished;
6411 /* The owner of the rollback journal or WAL file should always be the
6412 ** same as the owner of the database file. Try to ensure that this is
6413 ** the case. The chown() system call will be a no-op if the current
6414 ** process lacks root privileges, be we should at least try. Without
6415 ** this step, if a root process opens a database file, it can leave
6416 ** behinds a journal/WAL that is owned by root and hence make the
6417 ** database inaccessible to unprivileged processes.
6419 ** If openMode==0, then that means uid and gid are not set correctly
6420 ** (probably because SQLite is configured to use 8+3 filename mode) and
6421 ** in that case we do not want to attempt the chown().
6423 if( openMode && (flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL))!=0 ){
6424 robustFchown(fd, uid, gid);
6427 assert( fd>=0 );
6428 if( pOutFlags ){
6429 *pOutFlags = flags;
6432 if( p->pPreallocatedUnused ){
6433 p->pPreallocatedUnused->fd = fd;
6434 p->pPreallocatedUnused->flags =
6435 flags & (SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE);
6438 if( isDelete ){
6439 #if OS_VXWORKS
6440 zPath = zName;
6441 #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
6442 zPath = sqlite3_mprintf("%s", zName);
6443 if( zPath==0 ){
6444 robust_close(p, fd, __LINE__);
6445 return SQLITE_NOMEM_BKPT;
6447 #else
6448 osUnlink(zName);
6449 #endif
6451 #if SQLITE_ENABLE_LOCKING_STYLE
6452 else{
6453 p->openFlags = openFlags;
6455 #endif
6457 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
6458 if( fstatfs(fd, &fsInfo) == -1 ){
6459 storeLastErrno(p, errno);
6460 robust_close(p, fd, __LINE__);
6461 return SQLITE_IOERR_ACCESS;
6463 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
6464 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
6466 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
6467 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
6469 #endif
6471 /* Set up appropriate ctrlFlags */
6472 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
6473 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
6474 noLock = eType!=SQLITE_OPEN_MAIN_DB;
6475 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
6476 if( isNewJrnl ) ctrlFlags |= UNIXFILE_DIRSYNC;
6477 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
6479 #if SQLITE_ENABLE_LOCKING_STYLE
6480 #if SQLITE_PREFER_PROXY_LOCKING
6481 isAutoProxy = 1;
6482 #endif
6483 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
6484 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
6485 int useProxy = 0;
6487 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
6488 ** never use proxy, NULL means use proxy for non-local files only. */
6489 if( envforce!=NULL ){
6490 useProxy = atoi(envforce)>0;
6491 }else{
6492 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
6494 if( useProxy ){
6495 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
6496 if( rc==SQLITE_OK ){
6497 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
6498 if( rc!=SQLITE_OK ){
6499 /* Use unixClose to clean up the resources added in fillInUnixFile
6500 ** and clear all the structure's references. Specifically,
6501 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
6503 unixClose(pFile);
6504 return rc;
6507 goto open_finished;
6510 #endif
6512 assert( zPath==0 || zPath[0]=='/'
6513 || eType==SQLITE_OPEN_SUPER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL
6515 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
6517 open_finished:
6518 if( rc!=SQLITE_OK ){
6519 sqlite3_free(p->pPreallocatedUnused);
6521 return rc;
6526 ** Delete the file at zPath. If the dirSync argument is true, fsync()
6527 ** the directory after deleting the file.
6529 static int unixDelete(
6530 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
6531 const char *zPath, /* Name of file to be deleted */
6532 int dirSync /* If true, fsync() directory after deleting file */
6534 int rc = SQLITE_OK;
6535 UNUSED_PARAMETER(NotUsed);
6536 SimulateIOError(return SQLITE_IOERR_DELETE);
6537 if( osUnlink(zPath)==(-1) ){
6538 if( errno==ENOENT
6539 #if OS_VXWORKS
6540 || osAccess(zPath,0)!=0
6541 #endif
6543 rc = SQLITE_IOERR_DELETE_NOENT;
6544 }else{
6545 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
6547 return rc;
6549 #ifndef SQLITE_DISABLE_DIRSYNC
6550 if( (dirSync & 1)!=0 ){
6551 int fd;
6552 rc = osOpenDirectory(zPath, &fd);
6553 if( rc==SQLITE_OK ){
6554 if( full_fsync(fd,0,0) ){
6555 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
6557 robust_close(0, fd, __LINE__);
6558 }else{
6559 assert( rc==SQLITE_CANTOPEN );
6560 rc = SQLITE_OK;
6563 #endif
6564 return rc;
6568 ** Test the existence of or access permissions of file zPath. The
6569 ** test performed depends on the value of flags:
6571 ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
6572 ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
6573 ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
6575 ** Otherwise return 0.
6577 static int unixAccess(
6578 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
6579 const char *zPath, /* Path of the file to examine */
6580 int flags, /* What do we want to learn about the zPath file? */
6581 int *pResOut /* Write result boolean here */
6583 UNUSED_PARAMETER(NotUsed);
6584 SimulateIOError( return SQLITE_IOERR_ACCESS; );
6585 assert( pResOut!=0 );
6587 /* The spec says there are three possible values for flags. But only
6588 ** two of them are actually used */
6589 assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
6591 if( flags==SQLITE_ACCESS_EXISTS ){
6592 struct stat buf;
6593 *pResOut = 0==osStat(zPath, &buf) &&
6594 (!S_ISREG(buf.st_mode) || buf.st_size>0);
6595 }else{
6596 *pResOut = osAccess(zPath, W_OK|R_OK)==0;
6598 return SQLITE_OK;
6602 ** A pathname under construction
6604 typedef struct DbPath DbPath;
6605 struct DbPath {
6606 int rc; /* Non-zero following any error */
6607 int nSymlink; /* Number of symlinks resolved */
6608 char *zOut; /* Write the pathname here */
6609 int nOut; /* Bytes of space available to zOut[] */
6610 int nUsed; /* Bytes of zOut[] currently being used */
6613 /* Forward reference */
6614 static void appendAllPathElements(DbPath*,const char*);
6617 ** Append a single path element to the DbPath under construction
6619 static void appendOnePathElement(
6620 DbPath *pPath, /* Path under construction, to which to append zName */
6621 const char *zName, /* Name to append to pPath. Not zero-terminated */
6622 int nName /* Number of significant bytes in zName */
6624 assert( nName>0 );
6625 assert( zName!=0 );
6626 if( zName[0]=='.' ){
6627 if( nName==1 ) return;
6628 if( zName[1]=='.' && nName==2 ){
6629 if( pPath->nUsed>1 ){
6630 assert( pPath->zOut[0]=='/' );
6631 while( pPath->zOut[--pPath->nUsed]!='/' ){}
6633 return;
6636 if( pPath->nUsed + nName + 2 >= pPath->nOut ){
6637 pPath->rc = SQLITE_ERROR;
6638 return;
6640 pPath->zOut[pPath->nUsed++] = '/';
6641 memcpy(&pPath->zOut[pPath->nUsed], zName, nName);
6642 pPath->nUsed += nName;
6643 #if defined(HAVE_READLINK) && defined(HAVE_LSTAT)
6644 if( pPath->rc==SQLITE_OK ){
6645 const char *zIn;
6646 struct stat buf;
6647 pPath->zOut[pPath->nUsed] = 0;
6648 zIn = pPath->zOut;
6649 if( osLstat(zIn, &buf)!=0 ){
6650 if( errno!=ENOENT ){
6651 pPath->rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
6653 }else if( S_ISLNK(buf.st_mode) ){
6654 ssize_t got;
6655 char zLnk[SQLITE_MAX_PATHLEN+2];
6656 if( pPath->nSymlink++ > SQLITE_MAX_SYMLINK ){
6657 pPath->rc = SQLITE_CANTOPEN_BKPT;
6658 return;
6660 got = osReadlink(zIn, zLnk, sizeof(zLnk)-2);
6661 if( got<=0 || got>=(ssize_t)sizeof(zLnk)-2 ){
6662 pPath->rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
6663 return;
6665 zLnk[got] = 0;
6666 if( zLnk[0]=='/' ){
6667 pPath->nUsed = 0;
6668 }else{
6669 pPath->nUsed -= nName + 1;
6671 appendAllPathElements(pPath, zLnk);
6674 #endif
6678 ** Append all path elements in zPath to the DbPath under construction.
6680 static void appendAllPathElements(
6681 DbPath *pPath, /* Path under construction, to which to append zName */
6682 const char *zPath /* Path to append to pPath. Is zero-terminated */
6684 int i = 0;
6685 int j = 0;
6687 while( zPath[i] && zPath[i]!='/' ){ i++; }
6688 if( i>j ){
6689 appendOnePathElement(pPath, &zPath[j], i-j);
6691 j = i+1;
6692 }while( zPath[i++] );
6696 ** Turn a relative pathname into a full pathname. The relative path
6697 ** is stored as a nul-terminated string in the buffer pointed to by
6698 ** zPath.
6700 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
6701 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
6702 ** this buffer before returning.
6704 static int unixFullPathname(
6705 sqlite3_vfs *pVfs, /* Pointer to vfs object */
6706 const char *zPath, /* Possibly relative input path */
6707 int nOut, /* Size of output buffer in bytes */
6708 char *zOut /* Output buffer */
6710 DbPath path;
6711 UNUSED_PARAMETER(pVfs);
6712 path.rc = 0;
6713 path.nUsed = 0;
6714 path.nSymlink = 0;
6715 path.nOut = nOut;
6716 path.zOut = zOut;
6717 if( zPath[0]!='/' ){
6718 char zPwd[SQLITE_MAX_PATHLEN+2];
6719 if( osGetcwd(zPwd, sizeof(zPwd)-2)==0 ){
6720 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
6722 appendAllPathElements(&path, zPwd);
6724 appendAllPathElements(&path, zPath);
6725 zOut[path.nUsed] = 0;
6726 if( path.rc || path.nUsed<2 ) return SQLITE_CANTOPEN_BKPT;
6727 if( path.nSymlink ) return SQLITE_OK_SYMLINK;
6728 return SQLITE_OK;
6731 #ifndef SQLITE_OMIT_LOAD_EXTENSION
6733 ** Interfaces for opening a shared library, finding entry points
6734 ** within the shared library, and closing the shared library.
6736 #include <dlfcn.h>
6737 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6738 UNUSED_PARAMETER(NotUsed);
6739 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6743 ** SQLite calls this function immediately after a call to unixDlSym() or
6744 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
6745 ** message is available, it is written to zBufOut. If no error message
6746 ** is available, zBufOut is left unmodified and SQLite uses a default
6747 ** error message.
6749 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
6750 const char *zErr;
6751 UNUSED_PARAMETER(NotUsed);
6752 unixEnterMutex();
6753 zErr = dlerror();
6754 if( zErr ){
6755 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
6757 unixLeaveMutex();
6759 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6761 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6762 ** cast into a pointer to a function. And yet the library dlsym() routine
6763 ** returns a void* which is really a pointer to a function. So how do we
6764 ** use dlsym() with -pedantic-errors?
6766 ** Variable x below is defined to be a pointer to a function taking
6767 ** parameters void* and const char* and returning a pointer to a function.
6768 ** We initialize x by assigning it a pointer to the dlsym() function.
6769 ** (That assignment requires a cast.) Then we call the function that
6770 ** x points to.
6772 ** This work-around is unlikely to work correctly on any system where
6773 ** you really cannot cast a function pointer into void*. But then, on the
6774 ** other hand, dlsym() will not work on such a system either, so we have
6775 ** not really lost anything.
6777 void (*(*x)(void*,const char*))(void);
6778 UNUSED_PARAMETER(NotUsed);
6779 x = (void(*(*)(void*,const char*))(void))dlsym;
6780 return (*x)(p, zSym);
6782 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6783 UNUSED_PARAMETER(NotUsed);
6784 dlclose(pHandle);
6786 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6787 #define unixDlOpen 0
6788 #define unixDlError 0
6789 #define unixDlSym 0
6790 #define unixDlClose 0
6791 #endif
6794 ** Write nBuf bytes of random data to the supplied buffer zBuf.
6796 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6797 UNUSED_PARAMETER(NotUsed);
6798 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
6800 /* We have to initialize zBuf to prevent valgrind from reporting
6801 ** errors. The reports issued by valgrind are incorrect - we would
6802 ** prefer that the randomness be increased by making use of the
6803 ** uninitialized space in zBuf - but valgrind errors tend to worry
6804 ** some users. Rather than argue, it seems easier just to initialize
6805 ** the whole array and silence valgrind, even if that means less randomness
6806 ** in the random seed.
6808 ** When testing, initializing zBuf[] to zero is all we do. That means
6809 ** that we always use the same random number sequence. This makes the
6810 ** tests repeatable.
6812 memset(zBuf, 0, nBuf);
6813 randomnessPid = osGetpid(0);
6814 #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
6816 int fd, got;
6817 fd = robust_open("/dev/urandom", O_RDONLY, 0);
6818 if( fd<0 ){
6819 time_t t;
6820 time(&t);
6821 memcpy(zBuf, &t, sizeof(t));
6822 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6823 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6824 nBuf = sizeof(t) + sizeof(randomnessPid);
6825 }else{
6826 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
6827 robust_close(0, fd, __LINE__);
6830 #endif
6831 return nBuf;
6836 ** Sleep for a little while. Return the amount of time slept.
6837 ** The argument is the number of microseconds we want to sleep.
6838 ** The return value is the number of microseconds of sleep actually
6839 ** requested from the underlying operating system, a number which
6840 ** might be greater than or equal to the argument, but not less
6841 ** than the argument.
6843 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
6844 #if !defined(HAVE_NANOSLEEP) || HAVE_NANOSLEEP+0
6845 struct timespec sp;
6846 sp.tv_sec = microseconds / 1000000;
6847 sp.tv_nsec = (microseconds % 1000000) * 1000;
6849 /* Almost all modern unix systems support nanosleep(). But if you are
6850 ** compiling for one of the rare exceptions, you can use
6851 ** -DHAVE_NANOSLEEP=0 (perhaps in conjuction with -DHAVE_USLEEP if
6852 ** usleep() is available) in order to bypass the use of nanosleep() */
6853 nanosleep(&sp, NULL);
6855 UNUSED_PARAMETER(NotUsed);
6856 return microseconds;
6857 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
6858 if( microseconds>=1000000 ) sleep(microseconds/1000000);
6859 if( microseconds%1000000 ) usleep(microseconds%1000000);
6860 UNUSED_PARAMETER(NotUsed);
6861 return microseconds;
6862 #else
6863 int seconds = (microseconds+999999)/1000000;
6864 sleep(seconds);
6865 UNUSED_PARAMETER(NotUsed);
6866 return seconds*1000000;
6867 #endif
6871 ** The following variable, if set to a non-zero value, is interpreted as
6872 ** the number of seconds since 1970 and is used to set the result of
6873 ** sqlite3OsCurrentTime() during testing.
6875 #ifdef SQLITE_TEST
6876 int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
6877 #endif
6880 ** Find the current time (in Universal Coordinated Time). Write into *piNow
6881 ** the current time and date as a Julian Day number times 86_400_000. In
6882 ** other words, write into *piNow the number of milliseconds since the Julian
6883 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6884 ** proleptic Gregorian calendar.
6886 ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6887 ** cannot be found.
6889 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6890 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
6891 int rc = SQLITE_OK;
6892 #if defined(NO_GETTOD)
6893 time_t t;
6894 time(&t);
6895 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
6896 #elif OS_VXWORKS
6897 struct timespec sNow;
6898 clock_gettime(CLOCK_REALTIME, &sNow);
6899 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6900 #else
6901 struct timeval sNow;
6902 (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
6903 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
6904 #endif
6906 #ifdef SQLITE_TEST
6907 if( sqlite3_current_time ){
6908 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6910 #endif
6911 UNUSED_PARAMETER(NotUsed);
6912 return rc;
6915 #ifndef SQLITE_OMIT_DEPRECATED
6917 ** Find the current time (in Universal Coordinated Time). Write the
6918 ** current time and date as a Julian Day number into *prNow and
6919 ** return 0. Return 1 if the time and date cannot be found.
6921 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
6922 sqlite3_int64 i = 0;
6923 int rc;
6924 UNUSED_PARAMETER(NotUsed);
6925 rc = unixCurrentTimeInt64(0, &i);
6926 *prNow = i/86400000.0;
6927 return rc;
6929 #else
6930 # define unixCurrentTime 0
6931 #endif
6934 ** The xGetLastError() method is designed to return a better
6935 ** low-level error message when operating-system problems come up
6936 ** during SQLite operation. Only the integer return code is currently
6937 ** used.
6939 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6940 UNUSED_PARAMETER(NotUsed);
6941 UNUSED_PARAMETER(NotUsed2);
6942 UNUSED_PARAMETER(NotUsed3);
6943 return errno;
6948 ************************ End of sqlite3_vfs methods ***************************
6949 ******************************************************************************/
6951 /******************************************************************************
6952 ************************** Begin Proxy Locking ********************************
6954 ** Proxy locking is a "uber-locking-method" in this sense: It uses the
6955 ** other locking methods on secondary lock files. Proxy locking is a
6956 ** meta-layer over top of the primitive locking implemented above. For
6957 ** this reason, the division that implements of proxy locking is deferred
6958 ** until late in the file (here) after all of the other I/O methods have
6959 ** been defined - so that the primitive locking methods are available
6960 ** as services to help with the implementation of proxy locking.
6962 ****
6964 ** The default locking schemes in SQLite use byte-range locks on the
6965 ** database file to coordinate safe, concurrent access by multiple readers
6966 ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6967 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6968 ** as POSIX read & write locks over fixed set of locations (via fsctl),
6969 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
6970 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6971 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6972 ** address in the shared range is taken for a SHARED lock, the entire
6973 ** shared range is taken for an EXCLUSIVE lock):
6975 ** PENDING_BYTE 0x40000000
6976 ** RESERVED_BYTE 0x40000001
6977 ** SHARED_RANGE 0x40000002 -> 0x40000200
6979 ** This works well on the local file system, but shows a nearly 100x
6980 ** slowdown in read performance on AFP because the AFP client disables
6981 ** the read cache when byte-range locks are present. Enabling the read
6982 ** cache exposes a cache coherency problem that is present on all OS X
6983 ** supported network file systems. NFS and AFP both observe the
6984 ** close-to-open semantics for ensuring cache coherency
6985 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6986 ** address the requirements for concurrent database access by multiple
6987 ** readers and writers
6988 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6990 ** To address the performance and cache coherency issues, proxy file locking
6991 ** changes the way database access is controlled by limiting access to a
6992 ** single host at a time and moving file locks off of the database file
6993 ** and onto a proxy file on the local file system.
6996 ** Using proxy locks
6997 ** -----------------
6999 ** C APIs
7001 ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
7002 ** <proxy_path> | ":auto:");
7003 ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
7004 ** &<proxy_path>);
7007 ** SQL pragmas
7009 ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
7010 ** PRAGMA [database.]lock_proxy_file
7012 ** Specifying ":auto:" means that if there is a conch file with a matching
7013 ** host ID in it, the proxy path in the conch file will be used, otherwise
7014 ** a proxy path based on the user's temp dir
7015 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
7016 ** actual proxy file name is generated from the name and path of the
7017 ** database file. For example:
7019 ** For database path "/Users/me/foo.db"
7020 ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
7022 ** Once a lock proxy is configured for a database connection, it can not
7023 ** be removed, however it may be switched to a different proxy path via
7024 ** the above APIs (assuming the conch file is not being held by another
7025 ** connection or process).
7028 ** How proxy locking works
7029 ** -----------------------
7031 ** Proxy file locking relies primarily on two new supporting files:
7033 ** * conch file to limit access to the database file to a single host
7034 ** at a time
7036 ** * proxy file to act as a proxy for the advisory locks normally
7037 ** taken on the database
7039 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
7040 ** by taking an sqlite-style shared lock on the conch file, reading the
7041 ** contents and comparing the host's unique host ID (see below) and lock
7042 ** proxy path against the values stored in the conch. The conch file is
7043 ** stored in the same directory as the database file and the file name
7044 ** is patterned after the database file name as ".<databasename>-conch".
7045 ** If the conch file does not exist, or its contents do not match the
7046 ** host ID and/or proxy path, then the lock is escalated to an exclusive
7047 ** lock and the conch file contents is updated with the host ID and proxy
7048 ** path and the lock is downgraded to a shared lock again. If the conch
7049 ** is held by another process (with a shared lock), the exclusive lock
7050 ** will fail and SQLITE_BUSY is returned.
7052 ** The proxy file - a single-byte file used for all advisory file locks
7053 ** normally taken on the database file. This allows for safe sharing
7054 ** of the database file for multiple readers and writers on the same
7055 ** host (the conch ensures that they all use the same local lock file).
7057 ** Requesting the lock proxy does not immediately take the conch, it is
7058 ** only taken when the first request to lock database file is made.
7059 ** This matches the semantics of the traditional locking behavior, where
7060 ** opening a connection to a database file does not take a lock on it.
7061 ** The shared lock and an open file descriptor are maintained until
7062 ** the connection to the database is closed.
7064 ** The proxy file and the lock file are never deleted so they only need
7065 ** to be created the first time they are used.
7067 ** Configuration options
7068 ** ---------------------
7070 ** SQLITE_PREFER_PROXY_LOCKING
7072 ** Database files accessed on non-local file systems are
7073 ** automatically configured for proxy locking, lock files are
7074 ** named automatically using the same logic as
7075 ** PRAGMA lock_proxy_file=":auto:"
7077 ** SQLITE_PROXY_DEBUG
7079 ** Enables the logging of error messages during host id file
7080 ** retrieval and creation
7082 ** LOCKPROXYDIR
7084 ** Overrides the default directory used for lock proxy files that
7085 ** are named automatically via the ":auto:" setting
7087 ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
7089 ** Permissions to use when creating a directory for storing the
7090 ** lock proxy files, only used when LOCKPROXYDIR is not set.
7093 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
7094 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
7095 ** force proxy locking to be used for every database file opened, and 0
7096 ** will force automatic proxy locking to be disabled for all database
7097 ** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
7098 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
7102 ** Proxy locking is only available on MacOSX
7104 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
7107 ** The proxyLockingContext has the path and file structures for the remote
7108 ** and local proxy files in it
7110 typedef struct proxyLockingContext proxyLockingContext;
7111 struct proxyLockingContext {
7112 unixFile *conchFile; /* Open conch file */
7113 char *conchFilePath; /* Name of the conch file */
7114 unixFile *lockProxy; /* Open proxy lock file */
7115 char *lockProxyPath; /* Name of the proxy lock file */
7116 char *dbPath; /* Name of the open file */
7117 int conchHeld; /* 1 if the conch is held, -1 if lockless */
7118 int nFails; /* Number of conch taking failures */
7119 void *oldLockingContext; /* Original lockingcontext to restore on close */
7120 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
7124 ** The proxy lock file path for the database at dbPath is written into lPath,
7125 ** which must point to valid, writable memory large enough for a maxLen length
7126 ** file path.
7128 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
7129 int len;
7130 int dbLen;
7131 int i;
7133 #ifdef LOCKPROXYDIR
7134 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
7135 #else
7136 # ifdef _CS_DARWIN_USER_TEMP_DIR
7138 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
7139 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
7140 lPath, errno, osGetpid(0)));
7141 return SQLITE_IOERR_LOCK;
7143 len = strlcat(lPath, "sqliteplocks", maxLen);
7145 # else
7146 len = strlcpy(lPath, "/tmp/", maxLen);
7147 # endif
7148 #endif
7150 if( lPath[len-1]!='/' ){
7151 len = strlcat(lPath, "/", maxLen);
7154 /* transform the db path to a unique cache name */
7155 dbLen = (int)strlen(dbPath);
7156 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
7157 char c = dbPath[i];
7158 lPath[i+len] = (c=='/')?'_':c;
7160 lPath[i+len]='\0';
7161 strlcat(lPath, ":auto:", maxLen);
7162 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
7163 return SQLITE_OK;
7167 ** Creates the lock file and any missing directories in lockPath
7169 static int proxyCreateLockPath(const char *lockPath){
7170 int i, len;
7171 char buf[MAXPATHLEN];
7172 int start = 0;
7174 assert(lockPath!=NULL);
7175 /* try to create all the intermediate directories */
7176 len = (int)strlen(lockPath);
7177 buf[0] = lockPath[0];
7178 for( i=1; i<len; i++ ){
7179 if( lockPath[i] == '/' && (i - start > 0) ){
7180 /* only mkdir if leaf dir != "." or "/" or ".." */
7181 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
7182 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
7183 buf[i]='\0';
7184 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
7185 int err=errno;
7186 if( err!=EEXIST ) {
7187 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
7188 "'%s' proxy lock path=%s pid=%d\n",
7189 buf, strerror(err), lockPath, osGetpid(0)));
7190 return err;
7194 start=i+1;
7196 buf[i] = lockPath[i];
7198 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
7199 return 0;
7203 ** Create a new VFS file descriptor (stored in memory obtained from
7204 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
7206 ** The caller is responsible not only for closing the file descriptor
7207 ** but also for freeing the memory associated with the file descriptor.
7209 static int proxyCreateUnixFile(
7210 const char *path, /* path for the new unixFile */
7211 unixFile **ppFile, /* unixFile created and returned by ref */
7212 int islockfile /* if non zero missing dirs will be created */
7214 int fd = -1;
7215 unixFile *pNew;
7216 int rc = SQLITE_OK;
7217 int openFlags = O_RDWR | O_CREAT | O_NOFOLLOW;
7218 sqlite3_vfs dummyVfs;
7219 int terrno = 0;
7220 UnixUnusedFd *pUnused = NULL;
7222 /* 1. first try to open/create the file
7223 ** 2. if that fails, and this is a lock file (not-conch), try creating
7224 ** the parent directories and then try again.
7225 ** 3. if that fails, try to open the file read-only
7226 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
7228 pUnused = findReusableFd(path, openFlags);
7229 if( pUnused ){
7230 fd = pUnused->fd;
7231 }else{
7232 pUnused = sqlite3_malloc64(sizeof(*pUnused));
7233 if( !pUnused ){
7234 return SQLITE_NOMEM_BKPT;
7237 if( fd<0 ){
7238 fd = robust_open(path, openFlags, 0);
7239 terrno = errno;
7240 if( fd<0 && errno==ENOENT && islockfile ){
7241 if( proxyCreateLockPath(path) == SQLITE_OK ){
7242 fd = robust_open(path, openFlags, 0);
7246 if( fd<0 ){
7247 openFlags = O_RDONLY | O_NOFOLLOW;
7248 fd = robust_open(path, openFlags, 0);
7249 terrno = errno;
7251 if( fd<0 ){
7252 if( islockfile ){
7253 return SQLITE_BUSY;
7255 switch (terrno) {
7256 case EACCES:
7257 return SQLITE_PERM;
7258 case EIO:
7259 return SQLITE_IOERR_LOCK; /* even though it is the conch */
7260 default:
7261 return SQLITE_CANTOPEN_BKPT;
7265 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
7266 if( pNew==NULL ){
7267 rc = SQLITE_NOMEM_BKPT;
7268 goto end_create_proxy;
7270 memset(pNew, 0, sizeof(unixFile));
7271 pNew->openFlags = openFlags;
7272 memset(&dummyVfs, 0, sizeof(dummyVfs));
7273 dummyVfs.pAppData = (void*)&autolockIoFinder;
7274 dummyVfs.zName = "dummy";
7275 pUnused->fd = fd;
7276 pUnused->flags = openFlags;
7277 pNew->pPreallocatedUnused = pUnused;
7279 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
7280 if( rc==SQLITE_OK ){
7281 *ppFile = pNew;
7282 return SQLITE_OK;
7284 end_create_proxy:
7285 robust_close(pNew, fd, __LINE__);
7286 sqlite3_free(pNew);
7287 sqlite3_free(pUnused);
7288 return rc;
7291 #ifdef SQLITE_TEST
7292 /* simulate multiple hosts by creating unique hostid file paths */
7293 int sqlite3_hostid_num = 0;
7294 #endif
7296 #define PROXY_HOSTIDLEN 16 /* conch file host id length */
7298 #if HAVE_GETHOSTUUID
7299 /* Not always defined in the headers as it ought to be */
7300 extern int gethostuuid(uuid_t id, const struct timespec *wait);
7301 #endif
7303 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
7304 ** bytes of writable memory.
7306 static int proxyGetHostID(unsigned char *pHostID, int *pError){
7307 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
7308 memset(pHostID, 0, PROXY_HOSTIDLEN);
7309 #if HAVE_GETHOSTUUID
7311 struct timespec timeout = {1, 0}; /* 1 sec timeout */
7312 if( gethostuuid(pHostID, &timeout) ){
7313 int err = errno;
7314 if( pError ){
7315 *pError = err;
7317 return SQLITE_IOERR;
7320 #else
7321 UNUSED_PARAMETER(pError);
7322 #endif
7323 #ifdef SQLITE_TEST
7324 /* simulate multiple hosts by creating unique hostid file paths */
7325 if( sqlite3_hostid_num != 0){
7326 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
7328 #endif
7330 return SQLITE_OK;
7333 /* The conch file contains the header, host id and lock file path
7335 #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
7336 #define PROXY_HEADERLEN 1 /* conch file header length */
7337 #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
7338 #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
7341 ** Takes an open conch file, copies the contents to a new path and then moves
7342 ** it back. The newly created file's file descriptor is assigned to the
7343 ** conch file structure and finally the original conch file descriptor is
7344 ** closed. Returns zero if successful.
7346 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
7347 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7348 unixFile *conchFile = pCtx->conchFile;
7349 char tPath[MAXPATHLEN];
7350 char buf[PROXY_MAXCONCHLEN];
7351 char *cPath = pCtx->conchFilePath;
7352 size_t readLen = 0;
7353 size_t pathLen = 0;
7354 char errmsg[64] = "";
7355 int fd = -1;
7356 int rc = -1;
7357 UNUSED_PARAMETER(myHostID);
7359 /* create a new path by replace the trailing '-conch' with '-break' */
7360 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
7361 if( pathLen>MAXPATHLEN || pathLen<6 ||
7362 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
7363 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
7364 goto end_breaklock;
7366 /* read the conch content */
7367 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
7368 if( readLen<PROXY_PATHINDEX ){
7369 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
7370 goto end_breaklock;
7372 /* write it out to the temporary break file */
7373 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW), 0);
7374 if( fd<0 ){
7375 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
7376 goto end_breaklock;
7378 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
7379 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
7380 goto end_breaklock;
7382 if( rename(tPath, cPath) ){
7383 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
7384 goto end_breaklock;
7386 rc = 0;
7387 fprintf(stderr, "broke stale lock on %s\n", cPath);
7388 robust_close(pFile, conchFile->h, __LINE__);
7389 conchFile->h = fd;
7390 conchFile->openFlags = O_RDWR | O_CREAT;
7392 end_breaklock:
7393 if( rc ){
7394 if( fd>=0 ){
7395 osUnlink(tPath);
7396 robust_close(pFile, fd, __LINE__);
7398 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
7400 return rc;
7403 /* Take the requested lock on the conch file and break a stale lock if the
7404 ** host id matches.
7406 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
7407 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7408 unixFile *conchFile = pCtx->conchFile;
7409 int rc = SQLITE_OK;
7410 int nTries = 0;
7411 struct timespec conchModTime;
7413 memset(&conchModTime, 0, sizeof(conchModTime));
7414 do {
7415 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
7416 nTries ++;
7417 if( rc==SQLITE_BUSY ){
7418 /* If the lock failed (busy):
7419 * 1st try: get the mod time of the conch, wait 0.5s and try again.
7420 * 2nd try: fail if the mod time changed or host id is different, wait
7421 * 10 sec and try again
7422 * 3rd try: break the lock unless the mod time has changed.
7424 struct stat buf;
7425 if( osFstat(conchFile->h, &buf) ){
7426 storeLastErrno(pFile, errno);
7427 return SQLITE_IOERR_LOCK;
7430 if( nTries==1 ){
7431 conchModTime = buf.st_mtimespec;
7432 unixSleep(0,500000); /* wait 0.5 sec and try the lock again*/
7433 continue;
7436 assert( nTries>1 );
7437 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
7438 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
7439 return SQLITE_BUSY;
7442 if( nTries==2 ){
7443 char tBuf[PROXY_MAXCONCHLEN];
7444 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
7445 if( len<0 ){
7446 storeLastErrno(pFile, errno);
7447 return SQLITE_IOERR_LOCK;
7449 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
7450 /* don't break the lock if the host id doesn't match */
7451 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
7452 return SQLITE_BUSY;
7454 }else{
7455 /* don't break the lock on short read or a version mismatch */
7456 return SQLITE_BUSY;
7458 unixSleep(0,10000000); /* wait 10 sec and try the lock again */
7459 continue;
7462 assert( nTries==3 );
7463 if( 0==proxyBreakConchLock(pFile, myHostID) ){
7464 rc = SQLITE_OK;
7465 if( lockType==EXCLUSIVE_LOCK ){
7466 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
7468 if( !rc ){
7469 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
7473 } while( rc==SQLITE_BUSY && nTries<3 );
7475 return rc;
7478 /* Takes the conch by taking a shared lock and read the contents conch, if
7479 ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
7480 ** lockPath means that the lockPath in the conch file will be used if the
7481 ** host IDs match, or a new lock path will be generated automatically
7482 ** and written to the conch file.
7484 static int proxyTakeConch(unixFile *pFile){
7485 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7487 if( pCtx->conchHeld!=0 ){
7488 return SQLITE_OK;
7489 }else{
7490 unixFile *conchFile = pCtx->conchFile;
7491 uuid_t myHostID;
7492 int pError = 0;
7493 char readBuf[PROXY_MAXCONCHLEN];
7494 char lockPath[MAXPATHLEN];
7495 char *tempLockPath = NULL;
7496 int rc = SQLITE_OK;
7497 int createConch = 0;
7498 int hostIdMatch = 0;
7499 int readLen = 0;
7500 int tryOldLockPath = 0;
7501 int forceNewLockPath = 0;
7503 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
7504 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
7505 osGetpid(0)));
7507 rc = proxyGetHostID(myHostID, &pError);
7508 if( (rc&0xff)==SQLITE_IOERR ){
7509 storeLastErrno(pFile, pError);
7510 goto end_takeconch;
7512 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
7513 if( rc!=SQLITE_OK ){
7514 goto end_takeconch;
7516 /* read the existing conch file */
7517 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
7518 if( readLen<0 ){
7519 /* I/O error: lastErrno set by seekAndRead */
7520 storeLastErrno(pFile, conchFile->lastErrno);
7521 rc = SQLITE_IOERR_READ;
7522 goto end_takeconch;
7523 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
7524 readBuf[0]!=(char)PROXY_CONCHVERSION ){
7525 /* a short read or version format mismatch means we need to create a new
7526 ** conch file.
7528 createConch = 1;
7530 /* if the host id matches and the lock path already exists in the conch
7531 ** we'll try to use the path there, if we can't open that path, we'll
7532 ** retry with a new auto-generated path
7534 do { /* in case we need to try again for an :auto: named lock file */
7536 if( !createConch && !forceNewLockPath ){
7537 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
7538 PROXY_HOSTIDLEN);
7539 /* if the conch has data compare the contents */
7540 if( !pCtx->lockProxyPath ){
7541 /* for auto-named local lock file, just check the host ID and we'll
7542 ** use the local lock file path that's already in there
7544 if( hostIdMatch ){
7545 size_t pathLen = (readLen - PROXY_PATHINDEX);
7547 if( pathLen>=MAXPATHLEN ){
7548 pathLen=MAXPATHLEN-1;
7550 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
7551 lockPath[pathLen] = 0;
7552 tempLockPath = lockPath;
7553 tryOldLockPath = 1;
7554 /* create a copy of the lock path if the conch is taken */
7555 goto end_takeconch;
7557 }else if( hostIdMatch
7558 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
7559 readLen-PROXY_PATHINDEX)
7561 /* conch host and lock path match */
7562 goto end_takeconch;
7566 /* if the conch isn't writable and doesn't match, we can't take it */
7567 if( (conchFile->openFlags&O_RDWR) == 0 ){
7568 rc = SQLITE_BUSY;
7569 goto end_takeconch;
7572 /* either the conch didn't match or we need to create a new one */
7573 if( !pCtx->lockProxyPath ){
7574 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
7575 tempLockPath = lockPath;
7576 /* create a copy of the lock path _only_ if the conch is taken */
7579 /* update conch with host and path (this will fail if other process
7580 ** has a shared lock already), if the host id matches, use the big
7581 ** stick.
7583 futimes(conchFile->h, NULL);
7584 if( hostIdMatch && !createConch ){
7585 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
7586 /* We are trying for an exclusive lock but another thread in this
7587 ** same process is still holding a shared lock. */
7588 rc = SQLITE_BUSY;
7589 } else {
7590 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
7592 }else{
7593 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
7595 if( rc==SQLITE_OK ){
7596 char writeBuffer[PROXY_MAXCONCHLEN];
7597 int writeSize = 0;
7599 writeBuffer[0] = (char)PROXY_CONCHVERSION;
7600 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
7601 if( pCtx->lockProxyPath!=NULL ){
7602 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
7603 MAXPATHLEN);
7604 }else{
7605 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
7607 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
7608 robust_ftruncate(conchFile->h, writeSize);
7609 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
7610 full_fsync(conchFile->h,0,0);
7611 /* If we created a new conch file (not just updated the contents of a
7612 ** valid conch file), try to match the permissions of the database
7614 if( rc==SQLITE_OK && createConch ){
7615 struct stat buf;
7616 int err = osFstat(pFile->h, &buf);
7617 if( err==0 ){
7618 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
7619 S_IROTH|S_IWOTH);
7620 /* try to match the database file R/W permissions, ignore failure */
7621 #ifndef SQLITE_PROXY_DEBUG
7622 osFchmod(conchFile->h, cmode);
7623 #else
7625 rc = osFchmod(conchFile->h, cmode);
7626 }while( rc==(-1) && errno==EINTR );
7627 if( rc!=0 ){
7628 int code = errno;
7629 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
7630 cmode, code, strerror(code));
7631 } else {
7632 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
7634 }else{
7635 int code = errno;
7636 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
7637 err, code, strerror(code));
7638 #endif
7642 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
7644 end_takeconch:
7645 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
7646 if( rc==SQLITE_OK && pFile->openFlags ){
7647 int fd;
7648 if( pFile->h>=0 ){
7649 robust_close(pFile, pFile->h, __LINE__);
7651 pFile->h = -1;
7652 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
7653 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
7654 if( fd>=0 ){
7655 pFile->h = fd;
7656 }else{
7657 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
7658 during locking */
7661 if( rc==SQLITE_OK && !pCtx->lockProxy ){
7662 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
7663 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
7664 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
7665 /* we couldn't create the proxy lock file with the old lock file path
7666 ** so try again via auto-naming
7668 forceNewLockPath = 1;
7669 tryOldLockPath = 0;
7670 continue; /* go back to the do {} while start point, try again */
7673 if( rc==SQLITE_OK ){
7674 /* Need to make a copy of path if we extracted the value
7675 ** from the conch file or the path was allocated on the stack
7677 if( tempLockPath ){
7678 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
7679 if( !pCtx->lockProxyPath ){
7680 rc = SQLITE_NOMEM_BKPT;
7684 if( rc==SQLITE_OK ){
7685 pCtx->conchHeld = 1;
7687 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
7688 afpLockingContext *afpCtx;
7689 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
7690 afpCtx->dbPath = pCtx->lockProxyPath;
7692 } else {
7693 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7695 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
7696 rc==SQLITE_OK?"ok":"failed"));
7697 return rc;
7698 } while (1); /* in case we need to retry the :auto: lock file -
7699 ** we should never get here except via the 'continue' call. */
7704 ** If pFile holds a lock on a conch file, then release that lock.
7706 static int proxyReleaseConch(unixFile *pFile){
7707 int rc = SQLITE_OK; /* Subroutine return code */
7708 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
7709 unixFile *conchFile; /* Name of the conch file */
7711 pCtx = (proxyLockingContext *)pFile->lockingContext;
7712 conchFile = pCtx->conchFile;
7713 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
7714 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
7715 osGetpid(0)));
7716 if( pCtx->conchHeld>0 ){
7717 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7719 pCtx->conchHeld = 0;
7720 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
7721 (rc==SQLITE_OK ? "ok" : "failed")));
7722 return rc;
7726 ** Given the name of a database file, compute the name of its conch file.
7727 ** Store the conch filename in memory obtained from sqlite3_malloc64().
7728 ** Make *pConchPath point to the new name. Return SQLITE_OK on success
7729 ** or SQLITE_NOMEM if unable to obtain memory.
7731 ** The caller is responsible for ensuring that the allocated memory
7732 ** space is eventually freed.
7734 ** *pConchPath is set to NULL if a memory allocation error occurs.
7736 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7737 int i; /* Loop counter */
7738 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
7739 char *conchPath; /* buffer in which to construct conch name */
7741 /* Allocate space for the conch filename and initialize the name to
7742 ** the name of the original database file. */
7743 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
7744 if( conchPath==0 ){
7745 return SQLITE_NOMEM_BKPT;
7747 memcpy(conchPath, dbPath, len+1);
7749 /* now insert a "." before the last / character */
7750 for( i=(len-1); i>=0; i-- ){
7751 if( conchPath[i]=='/' ){
7752 i++;
7753 break;
7756 conchPath[i]='.';
7757 while ( i<len ){
7758 conchPath[i+1]=dbPath[i];
7759 i++;
7762 /* append the "-conch" suffix to the file */
7763 memcpy(&conchPath[i+1], "-conch", 7);
7764 assert( (int)strlen(conchPath) == len+7 );
7766 return SQLITE_OK;
7770 /* Takes a fully configured proxy locking-style unix file and switches
7771 ** the local lock file path
7773 static int switchLockProxyPath(unixFile *pFile, const char *path) {
7774 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7775 char *oldPath = pCtx->lockProxyPath;
7776 int rc = SQLITE_OK;
7778 if( pFile->eFileLock!=NO_LOCK ){
7779 return SQLITE_BUSY;
7782 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7783 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7784 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7785 return SQLITE_OK;
7786 }else{
7787 unixFile *lockProxy = pCtx->lockProxy;
7788 pCtx->lockProxy=NULL;
7789 pCtx->conchHeld = 0;
7790 if( lockProxy!=NULL ){
7791 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7792 if( rc ) return rc;
7793 sqlite3_free(lockProxy);
7795 sqlite3_free(oldPath);
7796 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7799 return rc;
7803 ** pFile is a file that has been opened by a prior xOpen call. dbPath
7804 ** is a string buffer at least MAXPATHLEN+1 characters in size.
7806 ** This routine find the filename associated with pFile and writes it
7807 ** int dbPath.
7809 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
7810 #if defined(__APPLE__)
7811 if( pFile->pMethod == &afpIoMethods ){
7812 /* afp style keeps a reference to the db path in the filePath field
7813 ** of the struct */
7814 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
7815 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7816 MAXPATHLEN);
7817 } else
7818 #endif
7819 if( pFile->pMethod == &dotlockIoMethods ){
7820 /* dot lock style uses the locking context to store the dot lock
7821 ** file path */
7822 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7823 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7824 }else{
7825 /* all other styles use the locking context to store the db file path */
7826 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
7827 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
7829 return SQLITE_OK;
7833 ** Takes an already filled in unix file and alters it so all file locking
7834 ** will be performed on the local proxy lock file. The following fields
7835 ** are preserved in the locking context so that they can be restored and
7836 ** the unix structure properly cleaned up at close time:
7837 ** ->lockingContext
7838 ** ->pMethod
7840 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7841 proxyLockingContext *pCtx;
7842 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7843 char *lockPath=NULL;
7844 int rc = SQLITE_OK;
7846 if( pFile->eFileLock!=NO_LOCK ){
7847 return SQLITE_BUSY;
7849 proxyGetDbPathForUnixFile(pFile, dbPath);
7850 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7851 lockPath=NULL;
7852 }else{
7853 lockPath=(char *)path;
7856 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
7857 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
7859 pCtx = sqlite3_malloc64( sizeof(*pCtx) );
7860 if( pCtx==0 ){
7861 return SQLITE_NOMEM_BKPT;
7863 memset(pCtx, 0, sizeof(*pCtx));
7865 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7866 if( rc==SQLITE_OK ){
7867 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7868 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7869 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7870 ** (c) the file system is read-only, then enable no-locking access.
7871 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7872 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7874 struct statfs fsInfo;
7875 struct stat conchInfo;
7876 int goLockless = 0;
7878 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
7879 int err = errno;
7880 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7881 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7884 if( goLockless ){
7885 pCtx->conchHeld = -1; /* read only FS/ lockless */
7886 rc = SQLITE_OK;
7890 if( rc==SQLITE_OK && lockPath ){
7891 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7894 if( rc==SQLITE_OK ){
7895 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7896 if( pCtx->dbPath==NULL ){
7897 rc = SQLITE_NOMEM_BKPT;
7900 if( rc==SQLITE_OK ){
7901 /* all memory is allocated, proxys are created and assigned,
7902 ** switch the locking context and pMethod then return.
7904 pCtx->oldLockingContext = pFile->lockingContext;
7905 pFile->lockingContext = pCtx;
7906 pCtx->pOldMethod = pFile->pMethod;
7907 pFile->pMethod = &proxyIoMethods;
7908 }else{
7909 if( pCtx->conchFile ){
7910 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
7911 sqlite3_free(pCtx->conchFile);
7913 sqlite3DbFree(0, pCtx->lockProxyPath);
7914 sqlite3_free(pCtx->conchFilePath);
7915 sqlite3_free(pCtx);
7917 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7918 (rc==SQLITE_OK ? "ok" : "failed")));
7919 return rc;
7924 ** This routine handles sqlite3_file_control() calls that are specific
7925 ** to proxy locking.
7927 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7928 switch( op ){
7929 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
7930 unixFile *pFile = (unixFile*)id;
7931 if( pFile->pMethod == &proxyIoMethods ){
7932 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7933 proxyTakeConch(pFile);
7934 if( pCtx->lockProxyPath ){
7935 *(const char **)pArg = pCtx->lockProxyPath;
7936 }else{
7937 *(const char **)pArg = ":auto: (not held)";
7939 } else {
7940 *(const char **)pArg = NULL;
7942 return SQLITE_OK;
7944 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
7945 unixFile *pFile = (unixFile*)id;
7946 int rc = SQLITE_OK;
7947 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7948 if( pArg==NULL || (const char *)pArg==0 ){
7949 if( isProxyStyle ){
7950 /* turn off proxy locking - not supported. If support is added for
7951 ** switching proxy locking mode off then it will need to fail if
7952 ** the journal mode is WAL mode.
7954 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7955 }else{
7956 /* turn off proxy locking - already off - NOOP */
7957 rc = SQLITE_OK;
7959 }else{
7960 const char *proxyPath = (const char *)pArg;
7961 if( isProxyStyle ){
7962 proxyLockingContext *pCtx =
7963 (proxyLockingContext*)pFile->lockingContext;
7964 if( !strcmp(pArg, ":auto:")
7965 || (pCtx->lockProxyPath &&
7966 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7968 rc = SQLITE_OK;
7969 }else{
7970 rc = switchLockProxyPath(pFile, proxyPath);
7972 }else{
7973 /* turn on proxy file locking */
7974 rc = proxyTransformUnixFile(pFile, proxyPath);
7977 return rc;
7979 default: {
7980 assert( 0 ); /* The call assures that only valid opcodes are sent */
7983 /*NOTREACHED*/ assert(0);
7984 return SQLITE_ERROR;
7988 ** Within this division (the proxying locking implementation) the procedures
7989 ** above this point are all utilities. The lock-related methods of the
7990 ** proxy-locking sqlite3_io_method object follow.
7995 ** This routine checks if there is a RESERVED lock held on the specified
7996 ** file by this or any other process. If such a lock is held, set *pResOut
7997 ** to a non-zero value otherwise *pResOut is set to zero. The return value
7998 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
8000 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
8001 unixFile *pFile = (unixFile*)id;
8002 int rc = proxyTakeConch(pFile);
8003 if( rc==SQLITE_OK ){
8004 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
8005 if( pCtx->conchHeld>0 ){
8006 unixFile *proxy = pCtx->lockProxy;
8007 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
8008 }else{ /* conchHeld < 0 is lockless */
8009 pResOut=0;
8012 return rc;
8016 ** Lock the file with the lock specified by parameter eFileLock - one
8017 ** of the following:
8019 ** (1) SHARED_LOCK
8020 ** (2) RESERVED_LOCK
8021 ** (3) PENDING_LOCK
8022 ** (4) EXCLUSIVE_LOCK
8024 ** Sometimes when requesting one lock state, additional lock states
8025 ** are inserted in between. The locking might fail on one of the later
8026 ** transitions leaving the lock state different from what it started but
8027 ** still short of its goal. The following chart shows the allowed
8028 ** transitions and the inserted intermediate states:
8030 ** UNLOCKED -> SHARED
8031 ** SHARED -> RESERVED
8032 ** SHARED -> (PENDING) -> EXCLUSIVE
8033 ** RESERVED -> (PENDING) -> EXCLUSIVE
8034 ** PENDING -> EXCLUSIVE
8036 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
8037 ** routine to lower a locking level.
8039 static int proxyLock(sqlite3_file *id, int eFileLock) {
8040 unixFile *pFile = (unixFile*)id;
8041 int rc = proxyTakeConch(pFile);
8042 if( rc==SQLITE_OK ){
8043 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
8044 if( pCtx->conchHeld>0 ){
8045 unixFile *proxy = pCtx->lockProxy;
8046 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
8047 pFile->eFileLock = proxy->eFileLock;
8048 }else{
8049 /* conchHeld < 0 is lockless */
8052 return rc;
8057 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
8058 ** must be either NO_LOCK or SHARED_LOCK.
8060 ** If the locking level of the file descriptor is already at or below
8061 ** the requested locking level, this routine is a no-op.
8063 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
8064 unixFile *pFile = (unixFile*)id;
8065 int rc = proxyTakeConch(pFile);
8066 if( rc==SQLITE_OK ){
8067 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
8068 if( pCtx->conchHeld>0 ){
8069 unixFile *proxy = pCtx->lockProxy;
8070 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
8071 pFile->eFileLock = proxy->eFileLock;
8072 }else{
8073 /* conchHeld < 0 is lockless */
8076 return rc;
8080 ** Close a file that uses proxy locks.
8082 static int proxyClose(sqlite3_file *id) {
8083 if( ALWAYS(id) ){
8084 unixFile *pFile = (unixFile*)id;
8085 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
8086 unixFile *lockProxy = pCtx->lockProxy;
8087 unixFile *conchFile = pCtx->conchFile;
8088 int rc = SQLITE_OK;
8090 if( lockProxy ){
8091 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
8092 if( rc ) return rc;
8093 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
8094 if( rc ) return rc;
8095 sqlite3_free(lockProxy);
8096 pCtx->lockProxy = 0;
8098 if( conchFile ){
8099 if( pCtx->conchHeld ){
8100 rc = proxyReleaseConch(pFile);
8101 if( rc ) return rc;
8103 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
8104 if( rc ) return rc;
8105 sqlite3_free(conchFile);
8107 sqlite3DbFree(0, pCtx->lockProxyPath);
8108 sqlite3_free(pCtx->conchFilePath);
8109 sqlite3DbFree(0, pCtx->dbPath);
8110 /* restore the original locking context and pMethod then close it */
8111 pFile->lockingContext = pCtx->oldLockingContext;
8112 pFile->pMethod = pCtx->pOldMethod;
8113 sqlite3_free(pCtx);
8114 return pFile->pMethod->xClose(id);
8116 return SQLITE_OK;
8121 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
8123 ** The proxy locking style is intended for use with AFP filesystems.
8124 ** And since AFP is only supported on MacOSX, the proxy locking is also
8125 ** restricted to MacOSX.
8128 ******************* End of the proxy lock implementation **********************
8129 ******************************************************************************/
8132 ** Initialize the operating system interface.
8134 ** This routine registers all VFS implementations for unix-like operating
8135 ** systems. This routine, and the sqlite3_os_end() routine that follows,
8136 ** should be the only routines in this file that are visible from other
8137 ** files.
8139 ** This routine is called once during SQLite initialization and by a
8140 ** single thread. The memory allocation and mutex subsystems have not
8141 ** necessarily been initialized when this routine is called, and so they
8142 ** should not be used.
8144 int sqlite3_os_init(void){
8146 ** The following macro defines an initializer for an sqlite3_vfs object.
8147 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
8148 ** to the "finder" function. (pAppData is a pointer to a pointer because
8149 ** silly C90 rules prohibit a void* from being cast to a function pointer
8150 ** and so we have to go through the intermediate pointer to avoid problems
8151 ** when compiling with -pedantic-errors on GCC.)
8153 ** The FINDER parameter to this macro is the name of the pointer to the
8154 ** finder-function. The finder-function returns a pointer to the
8155 ** sqlite_io_methods object that implements the desired locking
8156 ** behaviors. See the division above that contains the IOMETHODS
8157 ** macro for addition information on finder-functions.
8159 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
8160 ** object. But the "autolockIoFinder" available on MacOSX does a little
8161 ** more than that; it looks at the filesystem type that hosts the
8162 ** database file and tries to choose an locking method appropriate for
8163 ** that filesystem time.
8165 #define UNIXVFS(VFSNAME, FINDER) { \
8166 3, /* iVersion */ \
8167 sizeof(unixFile), /* szOsFile */ \
8168 MAX_PATHNAME, /* mxPathname */ \
8169 0, /* pNext */ \
8170 VFSNAME, /* zName */ \
8171 (void*)&FINDER, /* pAppData */ \
8172 unixOpen, /* xOpen */ \
8173 unixDelete, /* xDelete */ \
8174 unixAccess, /* xAccess */ \
8175 unixFullPathname, /* xFullPathname */ \
8176 unixDlOpen, /* xDlOpen */ \
8177 unixDlError, /* xDlError */ \
8178 unixDlSym, /* xDlSym */ \
8179 unixDlClose, /* xDlClose */ \
8180 unixRandomness, /* xRandomness */ \
8181 unixSleep, /* xSleep */ \
8182 unixCurrentTime, /* xCurrentTime */ \
8183 unixGetLastError, /* xGetLastError */ \
8184 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
8185 unixSetSystemCall, /* xSetSystemCall */ \
8186 unixGetSystemCall, /* xGetSystemCall */ \
8187 unixNextSystemCall, /* xNextSystemCall */ \
8191 ** All default VFSes for unix are contained in the following array.
8193 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
8194 ** by the SQLite core when the VFS is registered. So the following
8195 ** array cannot be const.
8197 static sqlite3_vfs aVfs[] = {
8198 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
8199 UNIXVFS("unix", autolockIoFinder ),
8200 #elif OS_VXWORKS
8201 UNIXVFS("unix", vxworksIoFinder ),
8202 #else
8203 UNIXVFS("unix", posixIoFinder ),
8204 #endif
8205 UNIXVFS("unix-none", nolockIoFinder ),
8206 UNIXVFS("unix-dotfile", dotlockIoFinder ),
8207 UNIXVFS("unix-excl", posixIoFinder ),
8208 #if OS_VXWORKS
8209 UNIXVFS("unix-namedsem", semIoFinder ),
8210 #endif
8211 #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
8212 UNIXVFS("unix-posix", posixIoFinder ),
8213 #endif
8214 #if SQLITE_ENABLE_LOCKING_STYLE
8215 UNIXVFS("unix-flock", flockIoFinder ),
8216 #endif
8217 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
8218 UNIXVFS("unix-afp", afpIoFinder ),
8219 UNIXVFS("unix-nfs", nfsIoFinder ),
8220 UNIXVFS("unix-proxy", proxyIoFinder ),
8221 #endif
8223 unsigned int i; /* Loop counter */
8225 /* Double-check that the aSyscall[] array has been constructed
8226 ** correctly. See ticket [bb3a86e890c8e96ab] */
8227 assert( ArraySize(aSyscall)==29 );
8229 /* Register all VFSes defined in the aVfs[] array */
8230 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
8231 #ifdef SQLITE_DEFAULT_UNIX_VFS
8232 sqlite3_vfs_register(&aVfs[i],
8233 0==strcmp(aVfs[i].zName,SQLITE_DEFAULT_UNIX_VFS));
8234 #else
8235 sqlite3_vfs_register(&aVfs[i], i==0);
8236 #endif
8238 #ifdef SQLITE_OS_KV_OPTIONAL
8239 sqlite3KvvfsInit();
8240 #endif
8241 unixBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
8243 #ifndef SQLITE_OMIT_WAL
8244 /* Validate lock assumptions */
8245 assert( SQLITE_SHM_NLOCK==8 ); /* Number of available locks */
8246 assert( UNIX_SHM_BASE==120 ); /* Start of locking area */
8247 /* Locks:
8248 ** WRITE UNIX_SHM_BASE 120
8249 ** CKPT UNIX_SHM_BASE+1 121
8250 ** RECOVER UNIX_SHM_BASE+2 122
8251 ** READ-0 UNIX_SHM_BASE+3 123
8252 ** READ-1 UNIX_SHM_BASE+4 124
8253 ** READ-2 UNIX_SHM_BASE+5 125
8254 ** READ-3 UNIX_SHM_BASE+6 126
8255 ** READ-4 UNIX_SHM_BASE+7 127
8256 ** DMS UNIX_SHM_BASE+8 128
8258 assert( UNIX_SHM_DMS==128 ); /* Byte offset of the deadman-switch */
8259 #endif
8261 /* Initialize temp file dir array. */
8262 unixTempFileInit();
8264 return SQLITE_OK;
8268 ** Shutdown the operating system interface.
8270 ** Some operating systems might need to do some cleanup in this routine,
8271 ** to release dynamically allocated objects. But not on unix.
8272 ** This routine is a no-op for unix.
8274 int sqlite3_os_end(void){
8275 unixBigLock = 0;
8276 return SQLITE_OK;
8279 #endif /* SQLITE_OS_UNIX */