blob: 2b9c117e30c9fcfeb4b1bf2f584753d17a6b8663 [file] [log] [blame]
drhbbd42a62004-05-22 17:41:58 +00001/*
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.
10**
11******************************************************************************
12**
drh734c9862008-11-28 15:37:20 +000013** This file contains the VFS implementation for unix-like operating systems
14** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
danielk1977822a5162008-05-16 04:51:54 +000015**
drh734c9862008-11-28 15:37:20 +000016** 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.
21**
drh9b35ea62008-11-29 02:20:26 +000022** This source file is organized into divisions where the logic for various
drh734c9862008-11-28 15:37:20 +000023** subfunctions is contained within the appropriate division. PLEASE
24** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
25** in the correct division and should be clearly labeled.
26**
drh6b9d6dd2008-12-03 19:34:47 +000027** The layout of divisions is as follows:
drh734c9862008-11-28 15:37:20 +000028**
29** * General-purpose declarations and utility functions.
30** * Unique file ID logic used by VxWorks.
drh715ff302008-12-03 22:32:44 +000031** * Various locking primitive implementations (all except proxy locking):
drh734c9862008-11-28 15:37:20 +000032** + 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)
drh9b35ea62008-11-29 02:20:26 +000038** * 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.
drh6b9d6dd2008-12-03 19:34:47 +000041** * sqlite3_vfs method implementations.
drh715ff302008-12-03 22:32:44 +000042** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000043** * Definitions of sqlite3_vfs objects for all locking methods
44** plus implementations of sqlite3_os_init() and sqlite3_os_end().
drhbbd42a62004-05-22 17:41:58 +000045*/
drhbbd42a62004-05-22 17:41:58 +000046#include "sqliteInt.h"
danielk197729bafea2008-06-26 10:41:19 +000047#if SQLITE_OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000048
danielk1977e339d652008-06-28 11:23:00 +000049/*
drh6b9d6dd2008-12-03 19:34:47 +000050** There are various methods for file locking used for concurrency
51** control:
danielk1977e339d652008-06-28 11:23:00 +000052**
drh734c9862008-11-28 15:37:20 +000053** 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)
60**
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.
danielk1977e339d652008-06-28 11:23:00 +000065*/
drh40bbb0a2008-09-23 10:23:26 +000066#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
drhd2cb50b2009-01-09 21:41:17 +000067# if defined(__APPLE__)
drh40bbb0a2008-09-23 10:23:26 +000068# define SQLITE_ENABLE_LOCKING_STYLE 1
69# else
70# define SQLITE_ENABLE_LOCKING_STYLE 0
71# endif
72#endif
drhbfe66312006-10-03 17:40:40 +000073
drhe32a2562016-03-04 02:38:00 +000074/* Use pread() and pwrite() if they are available */
drh79a2ca32016-03-04 03:14:39 +000075#if defined(__APPLE__)
76# define HAVE_PREAD 1
77# define HAVE_PWRITE 1
78#endif
drhe32a2562016-03-04 02:38:00 +000079#if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
80# undef USE_PREAD
drhe32a2562016-03-04 02:38:00 +000081# define USE_PREAD64 1
drhe32a2562016-03-04 02:38:00 +000082#elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)
drh79a2ca32016-03-04 03:14:39 +000083# undef USE_PREAD64
84# define USE_PREAD 1
drhe32a2562016-03-04 02:38:00 +000085#endif
86
drh9cbe6352005-11-29 03:13:21 +000087/*
drh9cbe6352005-11-29 03:13:21 +000088** standard include files.
89*/
90#include <sys/types.h>
91#include <sys/stat.h>
92#include <fcntl.h>
danefe16972017-07-20 19:49:14 +000093#include <sys/ioctl.h>
drh9cbe6352005-11-29 03:13:21 +000094#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +000095#include <time.h>
drh19e2d372005-08-29 23:00:03 +000096#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +000097#include <errno.h>
dan32c12fe2013-05-02 17:37:31 +000098#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drh91be7dc2014-08-11 13:53:30 +000099# include <sys/mman.h>
drhb469f462010-12-22 21:48:50 +0000100#endif
drh1da88f02011-12-17 16:09:16 +0000101
drhe89b2912015-03-03 20:42:01 +0000102#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000103# include <sys/ioctl.h>
drhe89b2912015-03-03 20:42:01 +0000104# include <sys/file.h>
105# include <sys/param.h>
drhbfe66312006-10-03 17:40:40 +0000106#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000107
drh6bca6512015-04-13 23:05:28 +0000108#if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
109 (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
110# if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
111 && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
112# define HAVE_GETHOSTUUID 1
113# else
114# warning "gethostuuid() is disabled."
115# endif
116#endif
117
118
drhe89b2912015-03-03 20:42:01 +0000119#if OS_VXWORKS
120# include <sys/ioctl.h>
121# include <semaphore.h>
122# include <limits.h>
123#endif /* OS_VXWORKS */
124
125#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh84a2bf62010-03-05 13:41:06 +0000126# include <sys/mount.h>
127#endif
128
drhdbe4b882011-06-20 18:00:17 +0000129#ifdef HAVE_UTIME
130# include <utime.h>
131#endif
132
drh9cbe6352005-11-29 03:13:21 +0000133/*
drh7ed97b92010-01-20 13:07:21 +0000134** Allowed values of unixFile.fsFlags
135*/
136#define SQLITE_FSFLAGS_IS_MSDOS 0x1
137
138/*
drhf1a221e2006-01-15 17:27:17 +0000139** If we are to be thread-safe, include the pthreads header and define
140** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000141*/
drhd677b3d2007-08-20 22:48:41 +0000142#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000143# include <pthread.h>
144# define SQLITE_UNIX_THREADS 1
145#endif
146
147/*
148** Default permissions when creating a new file
149*/
150#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
151# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
152#endif
153
danielk1977b4b47412007-08-17 15:53:36 +0000154/*
drh5adc60b2012-04-14 13:25:11 +0000155** Default permissions when creating auto proxy dir
156*/
aswiftaebf4132008-11-21 00:10:35 +0000157#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
158# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
159#endif
160
161/*
danielk1977b4b47412007-08-17 15:53:36 +0000162** Maximum supported path-length.
163*/
164#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000165
dane88ec182016-01-25 17:04:48 +0000166/*
167** Maximum supported symbolic links
168*/
169#define SQLITE_MAX_SYMLINKS 100
170
drh91eb93c2015-03-03 19:56:20 +0000171/* Always cast the getpid() return type for compatibility with
172** kernel modules in VxWorks. */
173#define osGetpid(X) (pid_t)getpid()
174
drh734c9862008-11-28 15:37:20 +0000175/*
drh734c9862008-11-28 15:37:20 +0000176** Only set the lastErrno if the error code is a real error and not
177** a normal expected return code of SQLITE_BUSY or SQLITE_OK
178*/
179#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
180
drhd91c68f2010-05-14 14:52:25 +0000181/* Forward references */
182typedef struct unixShm unixShm; /* Connection shared memory */
183typedef struct unixShmNode unixShmNode; /* Shared memory instance */
184typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
185typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000186
187/*
dane946c392009-08-22 11:39:46 +0000188** Sometimes, after a file handle is closed by SQLite, the file descriptor
189** cannot be closed immediately. In these cases, instances of the following
190** structure are used to store the file descriptor while waiting for an
191** opportunity to either close or reuse it.
192*/
dane946c392009-08-22 11:39:46 +0000193struct UnixUnusedFd {
194 int fd; /* File descriptor to close */
195 int flags; /* Flags this file descriptor was opened with */
196 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
197};
198
199/*
drh9b35ea62008-11-29 02:20:26 +0000200** The unixFile structure is subclass of sqlite3_file specific to the unix
201** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000202*/
drh054889e2005-11-30 03:20:31 +0000203typedef struct unixFile unixFile;
204struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000205 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhde60fc22011-12-14 17:53:36 +0000206 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
drhd91c68f2010-05-14 14:52:25 +0000207 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000208 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000209 unsigned char eFileLock; /* The type of lock held on this fd */
drh3ee34842012-02-11 21:21:17 +0000210 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000211 int lastErrno; /* The unix errno from last I/O error */
212 void *lockingContext; /* Locking style specific state */
drhc68886b2017-08-18 16:09:52 +0000213 UnixUnusedFd *pPreallocatedUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000214 const char *zPath; /* Name of the file */
215 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000216 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
mistachkine98844f2013-08-24 00:59:24 +0000217#if SQLITE_MAX_MMAP_SIZE>0
drh0d0614b2013-03-25 23:09:28 +0000218 int nFetchOut; /* Number of outstanding xFetch refs */
219 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
drh9b4c59f2013-04-15 17:03:42 +0000220 sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
221 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
drh0d0614b2013-03-25 23:09:28 +0000222 void *pMapRegion; /* Memory mapped region */
mistachkine98844f2013-08-24 00:59:24 +0000223#endif
drh537dddf2012-10-26 13:46:24 +0000224 int sectorSize; /* Device sector size */
225 int deviceCharacteristics; /* Precomputed device characteristics */
drh08c6d442009-02-09 17:34:07 +0000226#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000227 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000228#endif
drh7ed97b92010-01-20 13:07:21 +0000229#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000230 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000231#endif
drhf0119b22018-03-26 17:40:53 +0000232#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
233 unsigned iBusyTimeout; /* Wait this many millisec on locks */
234#endif
drh6c7d5c52008-11-21 20:32:33 +0000235#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000236 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000237#endif
drhd3d8c042012-05-29 17:02:40 +0000238#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +0000239 /* The next group of variables are used to track whether or not the
240 ** transaction counter in bytes 24-27 of database files are updated
241 ** whenever any part of the database changes. An assertion fault will
242 ** occur if a file is updated without also updating the transaction
243 ** counter. This test is made to avoid new problems similar to the
244 ** one described by ticket #3584.
245 */
246 unsigned char transCntrChng; /* True if the transaction counter changed */
247 unsigned char dbUpdate; /* True if any part of database file changed */
248 unsigned char inNormalWrite; /* True if in a normal write operation */
danf23da962013-03-23 21:00:41 +0000249
drh8f941bc2009-01-14 23:03:40 +0000250#endif
danf23da962013-03-23 21:00:41 +0000251
danielk1977967a4a12007-08-20 14:23:44 +0000252#ifdef SQLITE_TEST
253 /* In test mode, increase the size of this structure a bit so that
254 ** it is larger than the struct CrashFile defined in test6.c.
255 */
256 char aPadding[32];
257#endif
drh9cbe6352005-11-29 03:13:21 +0000258};
259
drhb00d8622014-01-01 15:18:36 +0000260/* This variable holds the process id (pid) from when the xRandomness()
261** method was called. If xOpen() is called from a different process id,
262** indicating that a fork() has occurred, the PRNG will be reset.
263*/
drh8cd5b252015-03-02 22:06:43 +0000264static pid_t randomnessPid = 0;
drhb00d8622014-01-01 15:18:36 +0000265
drh0ccebe72005-06-07 22:22:50 +0000266/*
drha7e61d82011-03-12 17:02:57 +0000267** Allowed values for the unixFile.ctrlFlags bitmask:
268*/
drhf0b190d2011-07-26 16:03:07 +0000269#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
270#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
271#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000272#ifndef SQLITE_DISABLE_DIRSYNC
273# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
274#else
275# define UNIXFILE_DIRSYNC 0x00
276#endif
drhcb15f352011-12-23 01:04:17 +0000277#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
drhc02a43a2012-01-10 23:18:38 +0000278#define UNIXFILE_DELETE 0x20 /* Delete on close */
279#define UNIXFILE_URI 0x40 /* Filename might have query parameters */
280#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
drha7e61d82011-03-12 17:02:57 +0000281
282/*
drh198bf392006-01-06 21:52:49 +0000283** Include code that is common to all os_*.c files
284*/
285#include "os_common.h"
286
287/*
drh0ccebe72005-06-07 22:22:50 +0000288** Define various macros that are missing from some systems.
289*/
drhbbd42a62004-05-22 17:41:58 +0000290#ifndef O_LARGEFILE
291# define O_LARGEFILE 0
292#endif
293#ifdef SQLITE_DISABLE_LFS
294# undef O_LARGEFILE
295# define O_LARGEFILE 0
296#endif
297#ifndef O_NOFOLLOW
298# define O_NOFOLLOW 0
299#endif
300#ifndef O_BINARY
301# define O_BINARY 0
302#endif
303
304/*
drh2b4b5962005-06-15 17:47:55 +0000305** The threadid macro resolves to the thread-id or to 0. Used for
306** testing and debugging only.
307*/
drhd677b3d2007-08-20 22:48:41 +0000308#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000309#define threadid pthread_self()
310#else
311#define threadid 0
312#endif
313
drh99ab3b12011-03-02 15:09:07 +0000314/*
dane6ecd662013-04-01 17:56:59 +0000315** HAVE_MREMAP defaults to true on Linux and false everywhere else.
316*/
317#if !defined(HAVE_MREMAP)
318# if defined(__linux__) && defined(_GNU_SOURCE)
319# define HAVE_MREMAP 1
320# else
321# define HAVE_MREMAP 0
322# endif
323#endif
324
325/*
dan2ee53412014-09-06 16:49:40 +0000326** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
327** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
328*/
329#ifdef __ANDROID__
330# define lseek lseek64
331#endif
332
drhd76dba72017-07-22 16:00:34 +0000333#ifdef __linux__
334/*
335** Linux-specific IOCTL magic numbers used for controlling F2FS
336*/
danefe16972017-07-20 19:49:14 +0000337#define F2FS_IOCTL_MAGIC 0xf5
338#define F2FS_IOC_START_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 1)
339#define F2FS_IOC_COMMIT_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 2)
340#define F2FS_IOC_START_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 3)
341#define F2FS_IOC_ABORT_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 5)
dan9d709542017-07-21 21:06:24 +0000342#define F2FS_IOC_GET_FEATURES _IOR(F2FS_IOCTL_MAGIC, 12, u32)
dan9d709542017-07-21 21:06:24 +0000343#define F2FS_FEATURE_ATOMIC_WRITE 0x0004
drhd76dba72017-07-22 16:00:34 +0000344#endif /* __linux__ */
danefe16972017-07-20 19:49:14 +0000345
346
dan2ee53412014-09-06 16:49:40 +0000347/*
drh9a3baf12011-04-25 18:01:27 +0000348** Different Unix systems declare open() in different ways. Same use
349** open(const char*,int,mode_t). Others use open(const char*,int,...).
350** The difference is important when using a pointer to the function.
351**
352** The safest way to deal with the problem is to always use this wrapper
353** which always has the same well-defined interface.
354*/
355static int posixOpen(const char *zFile, int flags, int mode){
356 return open(zFile, flags, mode);
357}
358
drh90315a22011-08-10 01:52:12 +0000359/* Forward reference */
360static int openDirectory(const char*, int*);
danbc760632014-03-20 09:42:09 +0000361static int unixGetpagesize(void);
drh90315a22011-08-10 01:52:12 +0000362
drh9a3baf12011-04-25 18:01:27 +0000363/*
drh99ab3b12011-03-02 15:09:07 +0000364** Many system calls are accessed through pointer-to-functions so that
365** they may be overridden at runtime to facilitate fault injection during
366** testing and sandboxing. The following array holds the names and pointers
367** to all overrideable system calls.
368*/
369static struct unix_syscall {
mistachkin48864df2013-03-21 21:20:32 +0000370 const char *zName; /* Name of the system call */
drh58ad5802011-03-23 22:02:23 +0000371 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
372 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000373} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000374 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
375#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000376
drh58ad5802011-03-23 22:02:23 +0000377 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000378#define osClose ((int(*)(int))aSyscall[1].pCurrent)
379
drh58ad5802011-03-23 22:02:23 +0000380 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000381#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
382
drh58ad5802011-03-23 22:02:23 +0000383 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000384#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
385
drh58ad5802011-03-23 22:02:23 +0000386 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000387#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
388
389/*
390** The DJGPP compiler environment looks mostly like Unix, but it
391** lacks the fcntl() system call. So redefine fcntl() to be something
392** that always succeeds. This means that locking does not occur under
393** DJGPP. But it is DOS - what did you expect?
394*/
395#ifdef __DJGPP__
396 { "fstat", 0, 0 },
397#define osFstat(a,b,c) 0
398#else
drh58ad5802011-03-23 22:02:23 +0000399 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000400#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
401#endif
402
drh58ad5802011-03-23 22:02:23 +0000403 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000404#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
405
drh58ad5802011-03-23 22:02:23 +0000406 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000407#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000408
drh58ad5802011-03-23 22:02:23 +0000409 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000410#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
411
drhe89b2912015-03-03 20:42:01 +0000412#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000413 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000414#else
drh58ad5802011-03-23 22:02:23 +0000415 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000416#endif
417#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
418
419#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000420 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000421#else
drh58ad5802011-03-23 22:02:23 +0000422 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000423#endif
drhf9986d92016-04-18 13:09:55 +0000424#define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
drhe562be52011-03-02 18:01:10 +0000425
drh58ad5802011-03-23 22:02:23 +0000426 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000427#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
428
drhe89b2912015-03-03 20:42:01 +0000429#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000430 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000431#else
drh58ad5802011-03-23 22:02:23 +0000432 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000433#endif
434#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
435 aSyscall[12].pCurrent)
436
437#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000438 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000439#else
drh58ad5802011-03-23 22:02:23 +0000440 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000441#endif
drhf9986d92016-04-18 13:09:55 +0000442#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off64_t))\
drhe562be52011-03-02 18:01:10 +0000443 aSyscall[13].pCurrent)
444
drh6226ca22015-11-24 15:06:28 +0000445 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000446#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000447
448#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000449 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000450#else
drh58ad5802011-03-23 22:02:23 +0000451 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000452#endif
dan0fd7d862011-03-29 10:04:23 +0000453#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000454
drh036ac7f2011-08-08 23:18:05 +0000455 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
456#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
457
drh90315a22011-08-10 01:52:12 +0000458 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
459#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
460
drh9ef6bc42011-11-04 02:24:02 +0000461 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
462#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
463
464 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
465#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
466
drhe2258a22016-01-12 00:37:55 +0000467#if defined(HAVE_FCHOWN)
drh6226ca22015-11-24 15:06:28 +0000468 { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
drhe2258a22016-01-12 00:37:55 +0000469#else
470 { "fchown", (sqlite3_syscall_ptr)0, 0 },
471#endif
dand3eaebd2012-02-13 08:50:23 +0000472#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000473
drh26f625f2018-02-19 16:34:31 +0000474#if defined(HAVE_FCHOWN)
drh6226ca22015-11-24 15:06:28 +0000475 { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
drh26f625f2018-02-19 16:34:31 +0000476#else
477 { "geteuid", (sqlite3_syscall_ptr)0, 0 },
478#endif
drh6226ca22015-11-24 15:06:28 +0000479#define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
480
dan4dd51442013-08-26 14:30:25 +0000481#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhe4a08f92016-01-08 19:17:30 +0000482 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
483#else
484 { "mmap", (sqlite3_syscall_ptr)0, 0 },
485#endif
drh6226ca22015-11-24 15:06:28 +0000486#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
dan893c0ff2013-03-25 19:05:07 +0000487
drhe4a08f92016-01-08 19:17:30 +0000488#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd1ab8062013-03-25 20:50:25 +0000489 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
drhe4a08f92016-01-08 19:17:30 +0000490#else
drha8299922016-01-08 22:31:00 +0000491 { "munmap", (sqlite3_syscall_ptr)0, 0 },
drhe4a08f92016-01-08 19:17:30 +0000492#endif
drh62be1fa2017-12-09 01:02:33 +0000493#define osMunmap ((int(*)(void*,size_t))aSyscall[23].pCurrent)
drhd1ab8062013-03-25 20:50:25 +0000494
drhe4a08f92016-01-08 19:17:30 +0000495#if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
drhd1ab8062013-03-25 20:50:25 +0000496 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
497#else
498 { "mremap", (sqlite3_syscall_ptr)0, 0 },
499#endif
drh6226ca22015-11-24 15:06:28 +0000500#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
501
drh24dbeae2016-01-08 22:18:00 +0000502#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
danbc760632014-03-20 09:42:09 +0000503 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
drh24dbeae2016-01-08 22:18:00 +0000504#else
505 { "getpagesize", (sqlite3_syscall_ptr)0, 0 },
506#endif
drh6226ca22015-11-24 15:06:28 +0000507#define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
danbc760632014-03-20 09:42:09 +0000508
drhe2258a22016-01-12 00:37:55 +0000509#if defined(HAVE_READLINK)
dan245fdc62015-10-31 17:58:33 +0000510 { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
drhe2258a22016-01-12 00:37:55 +0000511#else
512 { "readlink", (sqlite3_syscall_ptr)0, 0 },
513#endif
drh6226ca22015-11-24 15:06:28 +0000514#define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
dan245fdc62015-10-31 17:58:33 +0000515
danaf1b36b2016-01-25 18:43:05 +0000516#if defined(HAVE_LSTAT)
517 { "lstat", (sqlite3_syscall_ptr)lstat, 0 },
518#else
519 { "lstat", (sqlite3_syscall_ptr)0, 0 },
520#endif
dancaf6b152016-01-25 18:05:49 +0000521#define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
dan702eec12014-06-23 10:04:58 +0000522
drhb5d013e2017-10-25 16:14:12 +0000523#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
danefe16972017-07-20 19:49:14 +0000524 { "ioctl", (sqlite3_syscall_ptr)ioctl, 0 },
drhb5d013e2017-10-25 16:14:12 +0000525#else
526 { "ioctl", (sqlite3_syscall_ptr)0, 0 },
527#endif
dan9d709542017-07-21 21:06:24 +0000528#define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent)
danefe16972017-07-20 19:49:14 +0000529
drhe562be52011-03-02 18:01:10 +0000530}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000531
drh6226ca22015-11-24 15:06:28 +0000532
533/*
534** On some systems, calls to fchown() will trigger a message in a security
535** log if they come from non-root processes. So avoid calling fchown() if
536** we are not running as root.
537*/
538static int robustFchown(int fd, uid_t uid, gid_t gid){
drhe2258a22016-01-12 00:37:55 +0000539#if defined(HAVE_FCHOWN)
drh6226ca22015-11-24 15:06:28 +0000540 return osGeteuid() ? 0 : osFchown(fd,uid,gid);
drhe2258a22016-01-12 00:37:55 +0000541#else
542 return 0;
drh6226ca22015-11-24 15:06:28 +0000543#endif
544}
545
drh99ab3b12011-03-02 15:09:07 +0000546/*
547** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000548** "unix" VFSes. Return SQLITE_OK opon successfully updating the
549** system call pointer, or SQLITE_NOTFOUND if there is no configurable
550** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000551*/
552static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000553 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
554 const char *zName, /* Name of system call to override */
555 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000556){
drh58ad5802011-03-23 22:02:23 +0000557 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000558 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000559
560 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000561 if( zName==0 ){
562 /* If no zName is given, restore all system calls to their default
563 ** settings and return NULL
564 */
dan51438a72011-04-02 17:00:47 +0000565 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000566 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
567 if( aSyscall[i].pDefault ){
568 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000569 }
570 }
571 }else{
572 /* If zName is specified, operate on only the one system call
573 ** specified.
574 */
575 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
576 if( strcmp(zName, aSyscall[i].zName)==0 ){
577 if( aSyscall[i].pDefault==0 ){
578 aSyscall[i].pDefault = aSyscall[i].pCurrent;
579 }
drh1df30962011-03-02 19:06:42 +0000580 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000581 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
582 aSyscall[i].pCurrent = pNewFunc;
583 break;
584 }
585 }
586 }
587 return rc;
588}
589
drh1df30962011-03-02 19:06:42 +0000590/*
591** Return the value of a system call. Return NULL if zName is not a
592** recognized system call name. NULL is also returned if the system call
593** is currently undefined.
594*/
drh58ad5802011-03-23 22:02:23 +0000595static sqlite3_syscall_ptr unixGetSystemCall(
596 sqlite3_vfs *pNotUsed,
597 const char *zName
598){
599 unsigned int i;
600
601 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000602 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
603 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
604 }
605 return 0;
606}
607
608/*
609** Return the name of the first system call after zName. If zName==NULL
610** then return the name of the first system call. Return NULL if zName
611** is the last system call or if zName is not the name of a valid
612** system call.
613*/
614static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000615 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000616
617 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000618 if( zName ){
619 for(i=0; i<ArraySize(aSyscall)-1; i++){
620 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000621 }
622 }
dan0fd7d862011-03-29 10:04:23 +0000623 for(i++; i<ArraySize(aSyscall); i++){
624 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000625 }
626 return 0;
627}
628
drhad4f1e52011-03-04 15:43:57 +0000629/*
drh77a3fdc2013-08-30 14:24:12 +0000630** Do not accept any file descriptor less than this value, in order to avoid
631** opening database file using file descriptors that are commonly used for
632** standard input, output, and error.
633*/
634#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
635# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
636#endif
637
638/*
drh8c815d12012-02-13 20:16:37 +0000639** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000640** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000641**
642** If the file creation mode "m" is 0 then set it to the default for
643** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
644** 0644) as modified by the system umask. If m is not 0, then
645** make the file creation mode be exactly m ignoring the umask.
646**
647** The m parameter will be non-zero only when creating -wal, -journal,
648** and -shm files. We want those files to have *exactly* the same
649** permissions as their original database, unadulterated by the umask.
650** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
651** transaction crashes and leaves behind hot journals, then any
652** process that is able to write to the database will also be able to
653** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000654*/
drh8c815d12012-02-13 20:16:37 +0000655static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000656 int fd;
drhe1186ab2013-01-04 20:45:13 +0000657 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5128d002013-08-30 06:20:23 +0000658 while(1){
drh5adc60b2012-04-14 13:25:11 +0000659#if defined(O_CLOEXEC)
660 fd = osOpen(z,f|O_CLOEXEC,m2);
661#else
662 fd = osOpen(z,f,m2);
663#endif
drh5128d002013-08-30 06:20:23 +0000664 if( fd<0 ){
665 if( errno==EINTR ) continue;
666 break;
667 }
drh77a3fdc2013-08-30 14:24:12 +0000668 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
drh5128d002013-08-30 06:20:23 +0000669 osClose(fd);
670 sqlite3_log(SQLITE_WARNING,
671 "attempt to open \"%s\" as file descriptor %d", z, fd);
672 fd = -1;
673 if( osOpen("/dev/null", f, m)<0 ) break;
674 }
drhe1186ab2013-01-04 20:45:13 +0000675 if( fd>=0 ){
676 if( m!=0 ){
677 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000678 if( osFstat(fd, &statbuf)==0
679 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000680 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000681 ){
drhe1186ab2013-01-04 20:45:13 +0000682 osFchmod(fd, m);
683 }
684 }
drh5adc60b2012-04-14 13:25:11 +0000685#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000686 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000687#endif
drhe1186ab2013-01-04 20:45:13 +0000688 }
drh5adc60b2012-04-14 13:25:11 +0000689 return fd;
drhad4f1e52011-03-04 15:43:57 +0000690}
danielk197713adf8a2004-06-03 16:08:41 +0000691
drh107886a2008-11-21 22:21:50 +0000692/*
dan9359c7b2009-08-21 08:29:10 +0000693** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000694** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000695** vxworksFileId objects used by this file, all of which may be
696** shared by multiple threads.
697**
698** Function unixMutexHeld() is used to assert() that the global mutex
699** is held when required. This function is only used as part of assert()
700** statements. e.g.
701**
702** unixEnterMutex()
703** assert( unixMutexHeld() );
704** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000705*/
drh56115892018-02-05 16:39:12 +0000706static sqlite3_mutex *unixBigLock = 0;
drh107886a2008-11-21 22:21:50 +0000707static void unixEnterMutex(void){
drh56115892018-02-05 16:39:12 +0000708 sqlite3_mutex_enter(unixBigLock);
drh107886a2008-11-21 22:21:50 +0000709}
710static void unixLeaveMutex(void){
drh56115892018-02-05 16:39:12 +0000711 sqlite3_mutex_leave(unixBigLock);
drh107886a2008-11-21 22:21:50 +0000712}
dan9359c7b2009-08-21 08:29:10 +0000713#ifdef SQLITE_DEBUG
714static int unixMutexHeld(void) {
drh56115892018-02-05 16:39:12 +0000715 return sqlite3_mutex_held(unixBigLock);
dan9359c7b2009-08-21 08:29:10 +0000716}
717#endif
drh107886a2008-11-21 22:21:50 +0000718
drh734c9862008-11-28 15:37:20 +0000719
mistachkinfb383e92015-04-16 03:24:38 +0000720#ifdef SQLITE_HAVE_OS_TRACE
drh734c9862008-11-28 15:37:20 +0000721/*
722** Helper function for printing out trace information from debugging
peter.d.reid60ec9142014-09-06 16:39:46 +0000723** binaries. This returns the string representation of the supplied
drh734c9862008-11-28 15:37:20 +0000724** integer lock-type.
725*/
drh308c2a52010-05-14 11:30:18 +0000726static const char *azFileLock(int eFileLock){
727 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000728 case NO_LOCK: return "NONE";
729 case SHARED_LOCK: return "SHARED";
730 case RESERVED_LOCK: return "RESERVED";
731 case PENDING_LOCK: return "PENDING";
732 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000733 }
734 return "ERROR";
735}
736#endif
737
738#ifdef SQLITE_LOCK_TRACE
739/*
740** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000741**
drh734c9862008-11-28 15:37:20 +0000742** This routine is used for troubleshooting locks on multithreaded
743** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
744** command-line option on the compiler. This code is normally
745** turned off.
746*/
747static int lockTrace(int fd, int op, struct flock *p){
748 char *zOpName, *zType;
749 int s;
750 int savedErrno;
751 if( op==F_GETLK ){
752 zOpName = "GETLK";
753 }else if( op==F_SETLK ){
754 zOpName = "SETLK";
755 }else{
drh99ab3b12011-03-02 15:09:07 +0000756 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000757 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
758 return s;
759 }
760 if( p->l_type==F_RDLCK ){
761 zType = "RDLCK";
762 }else if( p->l_type==F_WRLCK ){
763 zType = "WRLCK";
764 }else if( p->l_type==F_UNLCK ){
765 zType = "UNLCK";
766 }else{
767 assert( 0 );
768 }
769 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000770 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000771 savedErrno = errno;
772 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
773 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
774 (int)p->l_pid, s);
775 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
776 struct flock l2;
777 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000778 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000779 if( l2.l_type==F_RDLCK ){
780 zType = "RDLCK";
781 }else if( l2.l_type==F_WRLCK ){
782 zType = "WRLCK";
783 }else if( l2.l_type==F_UNLCK ){
784 zType = "UNLCK";
785 }else{
786 assert( 0 );
787 }
788 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
789 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
790 }
791 errno = savedErrno;
792 return s;
793}
drh99ab3b12011-03-02 15:09:07 +0000794#undef osFcntl
795#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000796#endif /* SQLITE_LOCK_TRACE */
797
drhff812312011-02-23 13:33:46 +0000798/*
799** Retry ftruncate() calls that fail due to EINTR
dan2ee53412014-09-06 16:49:40 +0000800**
drhe6d41732015-02-21 00:49:00 +0000801** All calls to ftruncate() within this file should be made through
802** this wrapper. On the Android platform, bypassing the logic below
803** could lead to a corrupt database.
drhff812312011-02-23 13:33:46 +0000804*/
drhff812312011-02-23 13:33:46 +0000805static int robust_ftruncate(int h, sqlite3_int64 sz){
806 int rc;
dan2ee53412014-09-06 16:49:40 +0000807#ifdef __ANDROID__
808 /* On Android, ftruncate() always uses 32-bit offsets, even if
809 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
dan524a7332014-09-06 17:06:13 +0000810 ** truncate a file to any size larger than 2GiB. Silently ignore any
dan2ee53412014-09-06 16:49:40 +0000811 ** such attempts. */
812 if( sz>(sqlite3_int64)0x7FFFFFFF ){
813 rc = SQLITE_OK;
814 }else
815#endif
drh99ab3b12011-03-02 15:09:07 +0000816 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000817 return rc;
818}
drh734c9862008-11-28 15:37:20 +0000819
820/*
821** This routine translates a standard POSIX errno code into something
822** useful to the clients of the sqlite3 functions. Specifically, it is
823** intended to translate a variety of "try again" errors into SQLITE_BUSY
824** and a variety of "please close the file descriptor NOW" errors into
825** SQLITE_IOERR
826**
827** Errors during initialization of locks, or file system support for locks,
828** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
829*/
830static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
drh91c4def2015-11-25 14:00:07 +0000831 assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
832 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
833 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
834 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
drh734c9862008-11-28 15:37:20 +0000835 switch (posixError) {
drh91c4def2015-11-25 14:00:07 +0000836 case EACCES:
drh734c9862008-11-28 15:37:20 +0000837 case EAGAIN:
838 case ETIMEDOUT:
839 case EBUSY:
840 case EINTR:
841 case ENOLCK:
842 /* random NFS retry error, unless during file system support
843 * introspection, in which it actually means what it says */
844 return SQLITE_BUSY;
845
drh734c9862008-11-28 15:37:20 +0000846 case EPERM:
847 return SQLITE_PERM;
848
drh734c9862008-11-28 15:37:20 +0000849 default:
850 return sqliteIOErr;
851 }
852}
853
854
drh734c9862008-11-28 15:37:20 +0000855/******************************************************************************
856****************** Begin Unique File ID Utility Used By VxWorks ***************
857**
858** On most versions of unix, we can get a unique ID for a file by concatenating
859** the device number and the inode number. But this does not work on VxWorks.
860** On VxWorks, a unique file id must be based on the canonical filename.
861**
862** A pointer to an instance of the following structure can be used as a
863** unique file ID in VxWorks. Each instance of this structure contains
864** a copy of the canonical filename. There is also a reference count.
865** The structure is reclaimed when the number of pointers to it drops to
866** zero.
867**
868** There are never very many files open at one time and lookups are not
869** a performance-critical path, so it is sufficient to put these
870** structures on a linked list.
871*/
872struct vxworksFileId {
873 struct vxworksFileId *pNext; /* Next in a list of them all */
874 int nRef; /* Number of references to this one */
875 int nName; /* Length of the zCanonicalName[] string */
876 char *zCanonicalName; /* Canonical filename */
877};
878
879#if OS_VXWORKS
880/*
drh9b35ea62008-11-29 02:20:26 +0000881** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000882** variable:
883*/
884static struct vxworksFileId *vxworksFileList = 0;
885
886/*
887** Simplify a filename into its canonical form
888** by making the following changes:
889**
890** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000891** * convert /./ into just /
892** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000893**
894** Changes are made in-place. Return the new name length.
895**
896** The original filename is in z[0..n-1]. Return the number of
897** characters in the simplified name.
898*/
899static int vxworksSimplifyName(char *z, int n){
900 int i, j;
901 while( n>1 && z[n-1]=='/' ){ n--; }
902 for(i=j=0; i<n; i++){
903 if( z[i]=='/' ){
904 if( z[i+1]=='/' ) continue;
905 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
906 i += 1;
907 continue;
908 }
909 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
910 while( j>0 && z[j-1]!='/' ){ j--; }
911 if( j>0 ){ j--; }
912 i += 2;
913 continue;
914 }
915 }
916 z[j++] = z[i];
917 }
918 z[j] = 0;
919 return j;
920}
921
922/*
923** Find a unique file ID for the given absolute pathname. Return
924** a pointer to the vxworksFileId object. This pointer is the unique
925** file ID.
926**
927** The nRef field of the vxworksFileId object is incremented before
928** the object is returned. A new vxworksFileId object is created
929** and added to the global list if necessary.
930**
931** If a memory allocation error occurs, return NULL.
932*/
933static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
934 struct vxworksFileId *pNew; /* search key and new file ID */
935 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
936 int n; /* Length of zAbsoluteName string */
937
938 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000939 n = (int)strlen(zAbsoluteName);
drhf3cdcdc2015-04-29 16:50:28 +0000940 pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
drh734c9862008-11-28 15:37:20 +0000941 if( pNew==0 ) return 0;
942 pNew->zCanonicalName = (char*)&pNew[1];
943 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
944 n = vxworksSimplifyName(pNew->zCanonicalName, n);
945
946 /* Search for an existing entry that matching the canonical name.
947 ** If found, increment the reference count and return a pointer to
948 ** the existing file ID.
949 */
950 unixEnterMutex();
951 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
952 if( pCandidate->nName==n
953 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
954 ){
955 sqlite3_free(pNew);
956 pCandidate->nRef++;
957 unixLeaveMutex();
958 return pCandidate;
959 }
960 }
961
962 /* No match was found. We will make a new file ID */
963 pNew->nRef = 1;
964 pNew->nName = n;
965 pNew->pNext = vxworksFileList;
966 vxworksFileList = pNew;
967 unixLeaveMutex();
968 return pNew;
969}
970
971/*
972** Decrement the reference count on a vxworksFileId object. Free
973** the object when the reference count reaches zero.
974*/
975static void vxworksReleaseFileId(struct vxworksFileId *pId){
976 unixEnterMutex();
977 assert( pId->nRef>0 );
978 pId->nRef--;
979 if( pId->nRef==0 ){
980 struct vxworksFileId **pp;
981 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
982 assert( *pp==pId );
983 *pp = pId->pNext;
984 sqlite3_free(pId);
985 }
986 unixLeaveMutex();
987}
988#endif /* OS_VXWORKS */
989/*************** End of Unique File ID Utility Used By VxWorks ****************
990******************************************************************************/
991
992
993/******************************************************************************
994*************************** Posix Advisory Locking ****************************
995**
drh9b35ea62008-11-29 02:20:26 +0000996** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000997** section 6.5.2.2 lines 483 through 490 specify that when a process
998** sets or clears a lock, that operation overrides any prior locks set
999** by the same process. It does not explicitly say so, but this implies
1000** that it overrides locks set by the same process using a different
1001** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +00001002**
1003** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +00001004** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
1005**
1006** Suppose ./file1 and ./file2 are really the same file (because
1007** one is a hard or symbolic link to the other) then if you set
1008** an exclusive lock on fd1, then try to get an exclusive lock
1009** on fd2, it works. I would have expected the second lock to
1010** fail since there was already a lock on the file due to fd1.
1011** But not so. Since both locks came from the same process, the
1012** second overrides the first, even though they were on different
1013** file descriptors opened on different file names.
1014**
drh734c9862008-11-28 15:37:20 +00001015** This means that we cannot use POSIX locks to synchronize file access
1016** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +00001017** to synchronize access for threads in separate processes, but not
1018** threads within the same process.
1019**
1020** To work around the problem, SQLite has to manage file locks internally
1021** on its own. Whenever a new database is opened, we have to find the
1022** specific inode of the database file (the inode is determined by the
1023** st_dev and st_ino fields of the stat structure that fstat() fills in)
1024** and check for locks already existing on that inode. When locks are
1025** created or removed, we have to look at our own internal record of the
1026** locks to see if another thread has previously set a lock on that same
1027** inode.
1028**
drh9b35ea62008-11-29 02:20:26 +00001029** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
1030** For VxWorks, we have to use the alternative unique ID system based on
1031** canonical filename and implemented in the previous division.)
1032**
danielk1977ad94b582007-08-20 06:44:22 +00001033** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +00001034** descriptor. It is now a structure that holds the integer file
1035** descriptor and a pointer to a structure that describes the internal
1036** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +00001037** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +00001038** point to the same locking structure. The locking structure keeps
1039** a reference count (so we will know when to delete it) and a "cnt"
1040** field that tells us its internal lock status. cnt==0 means the
1041** file is unlocked. cnt==-1 means the file has an exclusive lock.
1042** cnt>0 means there are cnt shared locks on the file.
1043**
1044** Any attempt to lock or unlock a file first checks the locking
1045** structure. The fcntl() system call is only invoked to set a
1046** POSIX lock if the internal lock structure transitions between
1047** a locked and an unlocked state.
1048**
drh734c9862008-11-28 15:37:20 +00001049** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +00001050**
1051** If you close a file descriptor that points to a file that has locks,
1052** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +00001053** released. To work around this problem, each unixInodeInfo object
1054** maintains a count of the number of pending locks on tha inode.
1055** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +00001056** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +00001057** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +00001058** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +00001059** be closed and that list is walked (and cleared) when the last lock
1060** clears.
1061**
drh9b35ea62008-11-29 02:20:26 +00001062** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +00001063**
drh9b35ea62008-11-29 02:20:26 +00001064** Many older versions of linux use the LinuxThreads library which is
1065** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +00001066** A cannot be modified or overridden by a different thread B.
1067** Only thread A can modify the lock. Locking behavior is correct
1068** if the appliation uses the newer Native Posix Thread Library (NPTL)
1069** on linux - with NPTL a lock created by thread A can override locks
1070** in thread B. But there is no way to know at compile-time which
1071** threading library is being used. So there is no way to know at
1072** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001073** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001074** current process.
drh5fdae772004-06-29 03:29:00 +00001075**
drh8af6c222010-05-14 12:43:01 +00001076** SQLite used to support LinuxThreads. But support for LinuxThreads
1077** was dropped beginning with version 3.7.0. SQLite will still work with
1078** LinuxThreads provided that (1) there is no more than one connection
1079** per database file in the same process and (2) database connections
1080** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001081*/
1082
1083/*
1084** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001085** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001086*/
1087struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001088 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001089#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001090 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001091#else
drh25ef7f52016-12-05 20:06:45 +00001092 /* We are told that some versions of Android contain a bug that
1093 ** sizes ino_t at only 32-bits instead of 64-bits. (See
1094 ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
1095 ** To work around this, always allocate 64-bits for the inode number.
1096 ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
1097 ** but that should not be a big deal. */
1098 /* WAS: ino_t ino; */
1099 u64 ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001100#endif
1101};
1102
1103/*
drhbbd42a62004-05-22 17:41:58 +00001104** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001105** inode. Or, on LinuxThreads, there is one of these structures for
1106** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001107**
danielk1977ad94b582007-08-20 06:44:22 +00001108** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001109** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001110** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001111*/
drh8af6c222010-05-14 12:43:01 +00001112struct unixInodeInfo {
1113 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001114 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001115 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1116 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001117 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001118 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1119 int nLock; /* Number of outstanding file locks */
1120 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1121 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1122 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001123#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001124 unsigned long long sharedByte; /* for AFP simulated shared lock */
1125#endif
drh6c7d5c52008-11-21 20:32:33 +00001126#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001127 sem_t *pSem; /* Named POSIX semaphore */
1128 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001129#endif
drhbbd42a62004-05-22 17:41:58 +00001130};
1131
drhda0e7682008-07-30 15:27:54 +00001132/*
drh8af6c222010-05-14 12:43:01 +00001133** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001134*/
drhc68886b2017-08-18 16:09:52 +00001135static unixInodeInfo *inodeList = 0; /* All unixInodeInfo objects */
1136static unsigned int nUnusedFd = 0; /* Total unused file descriptors */
drh5fdae772004-06-29 03:29:00 +00001137
drh5fdae772004-06-29 03:29:00 +00001138/*
dane18d4952011-02-21 11:46:24 +00001139**
drhaaeaa182015-11-24 15:12:47 +00001140** This function - unixLogErrorAtLine(), is only ever called via the macro
dane18d4952011-02-21 11:46:24 +00001141** unixLogError().
1142**
1143** It is invoked after an error occurs in an OS function and errno has been
1144** set. It logs a message using sqlite3_log() containing the current value of
1145** errno and, if possible, the human-readable equivalent from strerror() or
1146** strerror_r().
1147**
1148** The first argument passed to the macro should be the error code that
1149** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1150** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001151** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001152** if any.
1153*/
drh0e9365c2011-03-02 02:08:13 +00001154#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1155static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001156 int errcode, /* SQLite error code */
1157 const char *zFunc, /* Name of OS function that failed */
1158 const char *zPath, /* File path associated with error */
1159 int iLine /* Source line number where error occurred */
1160){
1161 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001162 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001163
1164 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1165 ** the strerror() function to obtain the human-readable error message
1166 ** equivalent to errno. Otherwise, use strerror_r().
1167 */
1168#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1169 char aErr[80];
1170 memset(aErr, 0, sizeof(aErr));
1171 zErr = aErr;
1172
1173 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001174 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001175 ** returns a pointer to a buffer containing the error message. That pointer
1176 ** may point to aErr[], or it may point to some static storage somewhere.
1177 ** Otherwise, assume that the system provides the POSIX version of
1178 ** strerror_r(), which always writes an error message into aErr[].
1179 **
1180 ** If the code incorrectly assumes that it is the POSIX version that is
1181 ** available, the error message will often be an empty string. Not a
1182 ** huge problem. Incorrectly concluding that the GNU version is available
1183 ** could lead to a segfault though.
1184 */
1185#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1186 zErr =
1187# endif
drh0e9365c2011-03-02 02:08:13 +00001188 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001189
1190#elif SQLITE_THREADSAFE
1191 /* This is a threadsafe build, but strerror_r() is not available. */
1192 zErr = "";
1193#else
1194 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001195 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001196#endif
1197
drh0e9365c2011-03-02 02:08:13 +00001198 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001199 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001200 "os_unix.c:%d: (%d) %s(%s) - %s",
1201 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001202 );
1203
1204 return errcode;
1205}
1206
drh0e9365c2011-03-02 02:08:13 +00001207/*
1208** Close a file descriptor.
1209**
1210** We assume that close() almost always works, since it is only in a
1211** very sick application or on a very sick platform that it might fail.
1212** If it does fail, simply leak the file descriptor, but do log the
1213** error.
1214**
1215** Note that it is not safe to retry close() after EINTR since the
1216** file descriptor might have already been reused by another thread.
1217** So we don't even try to recover from an EINTR. Just log the error
1218** and move on.
1219*/
1220static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001221 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001222 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1223 pFile ? pFile->zPath : 0, lineno);
1224 }
1225}
dane18d4952011-02-21 11:46:24 +00001226
1227/*
drhe6d41732015-02-21 00:49:00 +00001228** Set the pFile->lastErrno. Do this in a subroutine as that provides
1229** a convenient place to set a breakpoint.
drh4bf66fd2015-02-19 02:43:02 +00001230*/
1231static void storeLastErrno(unixFile *pFile, int error){
1232 pFile->lastErrno = error;
1233}
1234
1235/*
danb0ac3e32010-06-16 10:55:42 +00001236** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001237*/
drh0e9365c2011-03-02 02:08:13 +00001238static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001239 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001240 UnixUnusedFd *p;
1241 UnixUnusedFd *pNext;
1242 for(p=pInode->pUnused; p; p=pNext){
1243 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001244 robust_close(pFile, p->fd, __LINE__);
1245 sqlite3_free(p);
drhc68886b2017-08-18 16:09:52 +00001246 nUnusedFd--;
danb0ac3e32010-06-16 10:55:42 +00001247 }
drh0e9365c2011-03-02 02:08:13 +00001248 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001249}
1250
1251/*
drh8af6c222010-05-14 12:43:01 +00001252** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001253**
1254** The mutex entered using the unixEnterMutex() function must be held
1255** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001256*/
danb0ac3e32010-06-16 10:55:42 +00001257static void releaseInodeInfo(unixFile *pFile){
1258 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001259 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001260 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001261 pInode->nRef--;
1262 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001263 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001264 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001265 if( pInode->pPrev ){
1266 assert( pInode->pPrev->pNext==pInode );
1267 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001268 }else{
drh8af6c222010-05-14 12:43:01 +00001269 assert( inodeList==pInode );
1270 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001271 }
drh8af6c222010-05-14 12:43:01 +00001272 if( pInode->pNext ){
1273 assert( pInode->pNext->pPrev==pInode );
1274 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001275 }
drh8af6c222010-05-14 12:43:01 +00001276 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001277 }
drhbbd42a62004-05-22 17:41:58 +00001278 }
drhc68886b2017-08-18 16:09:52 +00001279 assert( inodeList!=0 || nUnusedFd==0 );
drhbbd42a62004-05-22 17:41:58 +00001280}
1281
1282/*
drh8af6c222010-05-14 12:43:01 +00001283** Given a file descriptor, locate the unixInodeInfo object that
1284** describes that file descriptor. Create a new one if necessary. The
1285** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001286**
dan9359c7b2009-08-21 08:29:10 +00001287** The mutex entered using the unixEnterMutex() function must be held
1288** when this function is called.
1289**
drh6c7d5c52008-11-21 20:32:33 +00001290** Return an appropriate error code.
1291*/
drh8af6c222010-05-14 12:43:01 +00001292static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001293 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001294 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001295){
1296 int rc; /* System call return code */
1297 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001298 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1299 struct stat statbuf; /* Low-level file information */
1300 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001301
dan9359c7b2009-08-21 08:29:10 +00001302 assert( unixMutexHeld() );
1303
drh6c7d5c52008-11-21 20:32:33 +00001304 /* Get low-level information about the file that we can used to
1305 ** create a unique name for the file.
1306 */
1307 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001308 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001309 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001310 storeLastErrno(pFile, errno);
drh40fe8d32015-11-30 20:36:26 +00001311#if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
drh6c7d5c52008-11-21 20:32:33 +00001312 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1313#endif
1314 return SQLITE_IOERR;
1315 }
1316
drheb0d74f2009-02-03 15:27:02 +00001317#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001318 /* On OS X on an msdos filesystem, the inode number is reported
1319 ** incorrectly for zero-size files. See ticket #3260. To work
1320 ** around this problem (we consider it a bug in OS X, not SQLite)
1321 ** we always increase the file size to 1 by writing a single byte
1322 ** prior to accessing the inode number. The one byte written is
1323 ** an ASCII 'S' character which also happens to be the first byte
1324 ** in the header of every SQLite database. In this way, if there
1325 ** is a race condition such that another thread has already populated
1326 ** the first page of the database, no damage is done.
1327 */
drh7ed97b92010-01-20 13:07:21 +00001328 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001329 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001330 if( rc!=1 ){
drh4bf66fd2015-02-19 02:43:02 +00001331 storeLastErrno(pFile, errno);
drheb0d74f2009-02-03 15:27:02 +00001332 return SQLITE_IOERR;
1333 }
drh99ab3b12011-03-02 15:09:07 +00001334 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001335 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001336 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001337 return SQLITE_IOERR;
1338 }
1339 }
drheb0d74f2009-02-03 15:27:02 +00001340#endif
drh6c7d5c52008-11-21 20:32:33 +00001341
drh8af6c222010-05-14 12:43:01 +00001342 memset(&fileId, 0, sizeof(fileId));
1343 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001344#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001345 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001346#else
drh25ef7f52016-12-05 20:06:45 +00001347 fileId.ino = (u64)statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001348#endif
drhc68886b2017-08-18 16:09:52 +00001349 assert( inodeList!=0 || nUnusedFd==0 );
drh8af6c222010-05-14 12:43:01 +00001350 pInode = inodeList;
1351 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1352 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001353 }
drh8af6c222010-05-14 12:43:01 +00001354 if( pInode==0 ){
drhf3cdcdc2015-04-29 16:50:28 +00001355 pInode = sqlite3_malloc64( sizeof(*pInode) );
drh8af6c222010-05-14 12:43:01 +00001356 if( pInode==0 ){
mistachkinfad30392016-02-13 23:43:46 +00001357 return SQLITE_NOMEM_BKPT;
drh6c7d5c52008-11-21 20:32:33 +00001358 }
drh8af6c222010-05-14 12:43:01 +00001359 memset(pInode, 0, sizeof(*pInode));
1360 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1361 pInode->nRef = 1;
1362 pInode->pNext = inodeList;
1363 pInode->pPrev = 0;
1364 if( inodeList ) inodeList->pPrev = pInode;
1365 inodeList = pInode;
1366 }else{
1367 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001368 }
drh8af6c222010-05-14 12:43:01 +00001369 *ppInode = pInode;
1370 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001371}
drh6c7d5c52008-11-21 20:32:33 +00001372
drhb959a012013-12-07 12:29:22 +00001373/*
1374** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1375*/
1376static int fileHasMoved(unixFile *pFile){
drh61ffea52014-08-12 12:19:25 +00001377#if OS_VXWORKS
1378 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1379#else
drhb959a012013-12-07 12:29:22 +00001380 struct stat buf;
1381 return pFile->pInode!=0 &&
drh25ef7f52016-12-05 20:06:45 +00001382 (osStat(pFile->zPath, &buf)!=0
1383 || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
drh91be7dc2014-08-11 13:53:30 +00001384#endif
drhb959a012013-12-07 12:29:22 +00001385}
1386
aswift5b1a2562008-08-22 00:22:35 +00001387
1388/*
drhfbc7e882013-04-11 01:16:15 +00001389** Check a unixFile that is a database. Verify the following:
1390**
1391** (1) There is exactly one hard link on the file
1392** (2) The file is not a symbolic link
1393** (3) The file has not been renamed or unlinked
1394**
1395** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1396*/
1397static void verifyDbFile(unixFile *pFile){
1398 struct stat buf;
1399 int rc;
drh86151e82015-12-08 14:37:16 +00001400
1401 /* These verifications occurs for the main database only */
1402 if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
1403
drhfbc7e882013-04-11 01:16:15 +00001404 rc = osFstat(pFile->h, &buf);
1405 if( rc!=0 ){
1406 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001407 return;
1408 }
drh6369bc32016-03-21 16:06:42 +00001409 if( buf.st_nlink==0 ){
drhfbc7e882013-04-11 01:16:15 +00001410 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001411 return;
1412 }
1413 if( buf.st_nlink>1 ){
1414 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001415 return;
1416 }
drhb959a012013-12-07 12:29:22 +00001417 if( fileHasMoved(pFile) ){
drhfbc7e882013-04-11 01:16:15 +00001418 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001419 return;
1420 }
1421}
1422
1423
1424/*
danielk197713adf8a2004-06-03 16:08:41 +00001425** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001426** file by this or any other process. If such a lock is held, set *pResOut
1427** to a non-zero value otherwise *pResOut is set to zero. The return value
1428** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001429*/
danielk1977861f7452008-06-05 11:39:11 +00001430static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001431 int rc = SQLITE_OK;
1432 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001433 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001434
danielk1977861f7452008-06-05 11:39:11 +00001435 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1436
drh054889e2005-11-30 03:20:31 +00001437 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00001438 assert( pFile->eFileLock<=SHARED_LOCK );
drh8af6c222010-05-14 12:43:01 +00001439 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001440
1441 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001442 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001443 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001444 }
1445
drh2ac3ee92004-06-07 16:27:46 +00001446 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001447 */
danielk197709480a92009-02-09 05:32:32 +00001448#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001449 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001450 struct flock lock;
1451 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001452 lock.l_start = RESERVED_BYTE;
1453 lock.l_len = 1;
1454 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001455 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1456 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001457 storeLastErrno(pFile, errno);
aswift5b1a2562008-08-22 00:22:35 +00001458 } else if( lock.l_type!=F_UNLCK ){
1459 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001460 }
1461 }
danielk197709480a92009-02-09 05:32:32 +00001462#endif
danielk197713adf8a2004-06-03 16:08:41 +00001463
drh6c7d5c52008-11-21 20:32:33 +00001464 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001465 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001466
aswift5b1a2562008-08-22 00:22:35 +00001467 *pResOut = reserved;
1468 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001469}
1470
1471/*
drhf0119b22018-03-26 17:40:53 +00001472** Set a posix-advisory-lock.
1473**
1474** There are two versions of this routine. If compiled with
1475** SQLITE_ENABLE_SETLK_TIMEOUT then the routine has an extra parameter
1476** which is a pointer to a unixFile. If the unixFile->iBusyTimeout
1477** value is set, then it is the number of milliseconds to wait before
1478** failing the lock. The iBusyTimeout value is always reset back to
1479** zero on each call.
1480**
1481** If SQLITE_ENABLE_SETLK_TIMEOUT is not defined, then do a non-blocking
1482** attempt to set the lock.
1483*/
1484#ifndef SQLITE_ENABLE_SETLK_TIMEOUT
1485# define osSetPosixAdvisoryLock(h,x,t) osFcntl(h,F_SETLK,x)
1486#else
1487static int osSetPosixAdvisoryLock(
1488 int h, /* The file descriptor on which to take the lock */
1489 struct flock *pLock, /* The description of the lock */
1490 unixFile *pFile /* Structure holding timeout value */
1491){
1492 int rc = osFcntl(h,F_SETLK,pLock);
drhfd725632018-03-26 20:43:05 +00001493 while( rc<0 && pFile->iBusyTimeout>0 ){
drhf0119b22018-03-26 17:40:53 +00001494 /* On systems that support some kind of blocking file lock with a timeout,
1495 ** make appropriate changes here to invoke that blocking file lock. On
1496 ** generic posix, however, there is no such API. So we simply try the
1497 ** lock once every millisecond until either the timeout expires, or until
1498 ** the lock is obtained. */
drhfd725632018-03-26 20:43:05 +00001499 usleep(1000);
1500 rc = osFcntl(h,F_SETLK,pLock);
1501 pFile->iBusyTimeout--;
drhf0119b22018-03-26 17:40:53 +00001502 }
1503 return rc;
1504}
1505#endif /* SQLITE_ENABLE_SETLK_TIMEOUT */
1506
1507
1508/*
drha7e61d82011-03-12 17:02:57 +00001509** Attempt to set a system-lock on the file pFile. The lock is
1510** described by pLock.
1511**
drh77197112011-03-15 19:08:48 +00001512** If the pFile was opened read/write from unix-excl, then the only lock
1513** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001514** the first time any lock is attempted. All subsequent system locking
1515** operations become no-ops. Locking operations still happen internally,
1516** in order to coordinate access between separate database connections
1517** within this process, but all of that is handled in memory and the
1518** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001519**
1520** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1521** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1522** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001523**
1524** Zero is returned if the call completes successfully, or -1 if a call
1525** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001526*/
1527static int unixFileLock(unixFile *pFile, struct flock *pLock){
1528 int rc;
drh3cb93392011-03-12 18:10:44 +00001529 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001530 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001531 assert( pInode!=0 );
drh50358ad2015-12-02 01:04:33 +00001532 if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
drh3cb93392011-03-12 18:10:44 +00001533 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001534 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001535 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001536 lock.l_whence = SEEK_SET;
1537 lock.l_start = SHARED_FIRST;
1538 lock.l_len = SHARED_SIZE;
1539 lock.l_type = F_WRLCK;
drhf0119b22018-03-26 17:40:53 +00001540 rc = osSetPosixAdvisoryLock(pFile->h, &lock, pFile);
drha7e61d82011-03-12 17:02:57 +00001541 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001542 pInode->bProcessLock = 1;
1543 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001544 }else{
1545 rc = 0;
1546 }
1547 }else{
drhf0119b22018-03-26 17:40:53 +00001548 rc = osSetPosixAdvisoryLock(pFile->h, pLock, pFile);
drha7e61d82011-03-12 17:02:57 +00001549 }
1550 return rc;
1551}
1552
1553/*
drh308c2a52010-05-14 11:30:18 +00001554** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001555** of the following:
1556**
drh2ac3ee92004-06-07 16:27:46 +00001557** (1) SHARED_LOCK
1558** (2) RESERVED_LOCK
1559** (3) PENDING_LOCK
1560** (4) EXCLUSIVE_LOCK
1561**
drhb3e04342004-06-08 00:47:47 +00001562** Sometimes when requesting one lock state, additional lock states
1563** are inserted in between. The locking might fail on one of the later
1564** transitions leaving the lock state different from what it started but
1565** still short of its goal. The following chart shows the allowed
1566** transitions and the inserted intermediate states:
1567**
1568** UNLOCKED -> SHARED
1569** SHARED -> RESERVED
1570** SHARED -> (PENDING) -> EXCLUSIVE
1571** RESERVED -> (PENDING) -> EXCLUSIVE
1572** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001573**
drha6abd042004-06-09 17:37:22 +00001574** This routine will only increase a lock. Use the sqlite3OsUnlock()
1575** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001576*/
drh308c2a52010-05-14 11:30:18 +00001577static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001578 /* The following describes the implementation of the various locks and
1579 ** lock transitions in terms of the POSIX advisory shared and exclusive
1580 ** lock primitives (called read-locks and write-locks below, to avoid
1581 ** confusion with SQLite lock names). The algorithms are complicated
drhf878e6e2016-04-07 13:45:20 +00001582 ** slightly in order to be compatible with Windows95 systems simultaneously
danielk1977f42f25c2004-06-25 07:21:28 +00001583 ** accessing the same database file, in case that is ever required.
1584 **
1585 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1586 ** byte', each single bytes at well known offsets, and the 'shared byte
1587 ** range', a range of 510 bytes at a well known offset.
1588 **
1589 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
drhf878e6e2016-04-07 13:45:20 +00001590 ** byte'. If this is successful, 'shared byte range' is read-locked
1591 ** and the lock on the 'pending byte' released. (Legacy note: When
1592 ** SQLite was first developed, Windows95 systems were still very common,
1593 ** and Widnows95 lacks a shared-lock capability. So on Windows95, a
1594 ** single randomly selected by from the 'shared byte range' is locked.
1595 ** Windows95 is now pretty much extinct, but this work-around for the
1596 ** lack of shared-locks on Windows95 lives on, for backwards
1597 ** compatibility.)
danielk1977f42f25c2004-06-25 07:21:28 +00001598 **
danielk197790ba3bd2004-06-25 08:32:25 +00001599 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1600 ** A RESERVED lock is implemented by grabbing a write-lock on the
1601 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001602 **
1603 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001604 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1605 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1606 ** obtained, but existing SHARED locks are allowed to persist. A process
1607 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1608 ** This property is used by the algorithm for rolling back a journal file
1609 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001610 **
danielk197790ba3bd2004-06-25 08:32:25 +00001611 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1612 ** implemented by obtaining a write-lock on the entire 'shared byte
1613 ** range'. Since all other locks require a read-lock on one of the bytes
1614 ** within this range, this ensures that no other locks are held on the
1615 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001616 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001617 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001618 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001619 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001620 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001621 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001622
drh054889e2005-11-30 03:20:31 +00001623 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001624 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1625 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh91eb93c2015-03-03 19:56:20 +00001626 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001627 osGetpid(0)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001628
1629 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001630 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001631 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001632 */
drh308c2a52010-05-14 11:30:18 +00001633 if( pFile->eFileLock>=eFileLock ){
1634 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1635 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001636 return SQLITE_OK;
1637 }
1638
drh0c2694b2009-09-03 16:23:44 +00001639 /* Make sure the locking sequence is correct.
1640 ** (1) We never move from unlocked to anything higher than shared lock.
1641 ** (2) SQLite never explicitly requests a pendig lock.
1642 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001643 */
drh308c2a52010-05-14 11:30:18 +00001644 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1645 assert( eFileLock!=PENDING_LOCK );
1646 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001647
drh8af6c222010-05-14 12:43:01 +00001648 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001649 */
drh6c7d5c52008-11-21 20:32:33 +00001650 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001651 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001652
danielk1977ad94b582007-08-20 06:44:22 +00001653 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001654 ** handle that precludes the requested lock, return BUSY.
1655 */
drh8af6c222010-05-14 12:43:01 +00001656 if( (pFile->eFileLock!=pInode->eFileLock &&
1657 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001658 ){
1659 rc = SQLITE_BUSY;
1660 goto end_lock;
1661 }
1662
1663 /* If a SHARED lock is requested, and some thread using this PID already
1664 ** has a SHARED or RESERVED lock, then increment reference counts and
1665 ** return SQLITE_OK.
1666 */
drh308c2a52010-05-14 11:30:18 +00001667 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001668 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001669 assert( eFileLock==SHARED_LOCK );
1670 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001671 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001672 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001673 pInode->nShared++;
1674 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001675 goto end_lock;
1676 }
1677
danielk19779a1d0ab2004-06-01 14:09:28 +00001678
drh3cde3bb2004-06-12 02:17:14 +00001679 /* A PENDING lock is needed before acquiring a SHARED lock and before
1680 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1681 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001682 */
drh0c2694b2009-09-03 16:23:44 +00001683 lock.l_len = 1L;
1684 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001685 if( eFileLock==SHARED_LOCK
1686 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001687 ){
drh308c2a52010-05-14 11:30:18 +00001688 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001689 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001690 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001691 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001692 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001693 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001694 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001695 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001696 goto end_lock;
1697 }
drh3cde3bb2004-06-12 02:17:14 +00001698 }
1699
1700
1701 /* If control gets to this point, then actually go ahead and make
1702 ** operating system calls for the specified lock.
1703 */
drh308c2a52010-05-14 11:30:18 +00001704 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001705 assert( pInode->nShared==0 );
1706 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001707 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001708
drh2ac3ee92004-06-07 16:27:46 +00001709 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001710 lock.l_start = SHARED_FIRST;
1711 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001712 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001713 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001714 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001715 }
dan661d71a2011-03-30 19:08:03 +00001716
drh2ac3ee92004-06-07 16:27:46 +00001717 /* Drop the temporary PENDING lock */
1718 lock.l_start = PENDING_BYTE;
1719 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001720 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001721 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1722 /* This could happen with a network mount */
1723 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001724 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001725 }
dan661d71a2011-03-30 19:08:03 +00001726
1727 if( rc ){
1728 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001729 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001730 }
dan661d71a2011-03-30 19:08:03 +00001731 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001732 }else{
drh308c2a52010-05-14 11:30:18 +00001733 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001734 pInode->nLock++;
1735 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001736 }
drh8af6c222010-05-14 12:43:01 +00001737 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001738 /* We are trying for an exclusive lock but another thread in this
1739 ** same process is still holding a shared lock. */
1740 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001741 }else{
drh3cde3bb2004-06-12 02:17:14 +00001742 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001743 ** assumed that there is a SHARED or greater lock on the file
1744 ** already.
1745 */
drh308c2a52010-05-14 11:30:18 +00001746 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001747 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001748
1749 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1750 if( eFileLock==RESERVED_LOCK ){
1751 lock.l_start = RESERVED_BYTE;
1752 lock.l_len = 1L;
1753 }else{
1754 lock.l_start = SHARED_FIRST;
1755 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001756 }
dan661d71a2011-03-30 19:08:03 +00001757
1758 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001759 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001760 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001761 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001762 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001763 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001764 }
drhbbd42a62004-05-22 17:41:58 +00001765 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001766
drh8f941bc2009-01-14 23:03:40 +00001767
drhd3d8c042012-05-29 17:02:40 +00001768#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001769 /* Set up the transaction-counter change checking flags when
1770 ** transitioning from a SHARED to a RESERVED lock. The change
1771 ** from SHARED to RESERVED marks the beginning of a normal
1772 ** write operation (not a hot journal rollback).
1773 */
1774 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001775 && pFile->eFileLock<=SHARED_LOCK
1776 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001777 ){
1778 pFile->transCntrChng = 0;
1779 pFile->dbUpdate = 0;
1780 pFile->inNormalWrite = 1;
1781 }
1782#endif
1783
1784
danielk1977ecb2a962004-06-02 06:30:16 +00001785 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001786 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001787 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001788 }else if( eFileLock==EXCLUSIVE_LOCK ){
1789 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001790 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001791 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001792
1793end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001794 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001795 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1796 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001797 return rc;
1798}
1799
1800/*
dan08da86a2009-08-21 17:18:03 +00001801** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001802** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001803*/
1804static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001805 unixInodeInfo *pInode = pFile->pInode;
drhc68886b2017-08-18 16:09:52 +00001806 UnixUnusedFd *p = pFile->pPreallocatedUnused;
drh8af6c222010-05-14 12:43:01 +00001807 p->pNext = pInode->pUnused;
1808 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001809 pFile->h = -1;
drhc68886b2017-08-18 16:09:52 +00001810 pFile->pPreallocatedUnused = 0;
1811 nUnusedFd++;
dan08da86a2009-08-21 17:18:03 +00001812}
1813
1814/*
drh308c2a52010-05-14 11:30:18 +00001815** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001816** must be either NO_LOCK or SHARED_LOCK.
1817**
1818** If the locking level of the file descriptor is already at or below
1819** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001820**
1821** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1822** the byte range is divided into 2 parts and the first part is unlocked then
1823** set to a read lock, then the other part is simply unlocked. This works
1824** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1825** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001826*/
drha7e61d82011-03-12 17:02:57 +00001827static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001828 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001829 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001830 struct flock lock;
1831 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001832
drh054889e2005-11-30 03:20:31 +00001833 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001834 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001835 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001836 osGetpid(0)));
drha6abd042004-06-09 17:37:22 +00001837
drh308c2a52010-05-14 11:30:18 +00001838 assert( eFileLock<=SHARED_LOCK );
1839 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001840 return SQLITE_OK;
1841 }
drh6c7d5c52008-11-21 20:32:33 +00001842 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001843 pInode = pFile->pInode;
1844 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001845 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001846 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001847
drhd3d8c042012-05-29 17:02:40 +00001848#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001849 /* When reducing a lock such that other processes can start
1850 ** reading the database file again, make sure that the
1851 ** transaction counter was updated if any part of the database
1852 ** file changed. If the transaction counter is not updated,
1853 ** other connections to the same file might not realize that
1854 ** the file has changed and hence might not know to flush their
1855 ** cache. The use of a stale cache can lead to database corruption.
1856 */
drh8f941bc2009-01-14 23:03:40 +00001857 pFile->inNormalWrite = 0;
1858#endif
1859
drh7ed97b92010-01-20 13:07:21 +00001860 /* downgrading to a shared lock on NFS involves clearing the write lock
1861 ** before establishing the readlock - to avoid a race condition we downgrade
1862 ** the lock in 2 blocks, so that part of the range will be covered by a
1863 ** write lock until the rest is covered by a read lock:
1864 ** 1: [WWWWW]
1865 ** 2: [....W]
1866 ** 3: [RRRRW]
1867 ** 4: [RRRR.]
1868 */
drh308c2a52010-05-14 11:30:18 +00001869 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001870#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001871 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001872 assert( handleNFSUnlock==0 );
1873#endif
1874#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001875 if( handleNFSUnlock ){
drha712b4b2015-02-19 16:12:04 +00001876 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001877 off_t divSize = SHARED_SIZE - 1;
1878
1879 lock.l_type = F_UNLCK;
1880 lock.l_whence = SEEK_SET;
1881 lock.l_start = SHARED_FIRST;
1882 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001883 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001884 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001885 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001886 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001887 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001888 }
drh7ed97b92010-01-20 13:07:21 +00001889 lock.l_type = F_RDLCK;
1890 lock.l_whence = SEEK_SET;
1891 lock.l_start = SHARED_FIRST;
1892 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001893 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001894 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001895 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1896 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001897 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001898 }
1899 goto end_unlock;
1900 }
1901 lock.l_type = F_UNLCK;
1902 lock.l_whence = SEEK_SET;
1903 lock.l_start = SHARED_FIRST+divSize;
1904 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001905 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001906 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001907 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001908 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001909 goto end_unlock;
1910 }
drh30f776f2011-02-25 03:25:07 +00001911 }else
1912#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1913 {
drh7ed97b92010-01-20 13:07:21 +00001914 lock.l_type = F_RDLCK;
1915 lock.l_whence = SEEK_SET;
1916 lock.l_start = SHARED_FIRST;
1917 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001918 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001919 /* In theory, the call to unixFileLock() cannot fail because another
1920 ** process is holding an incompatible lock. If it does, this
1921 ** indicates that the other process is not following the locking
1922 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1923 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1924 ** an assert to fail). */
1925 rc = SQLITE_IOERR_RDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001926 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00001927 goto end_unlock;
1928 }
drh9c105bb2004-10-02 20:38:28 +00001929 }
1930 }
drhbbd42a62004-05-22 17:41:58 +00001931 lock.l_type = F_UNLCK;
1932 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001933 lock.l_start = PENDING_BYTE;
1934 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001935 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001936 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001937 }else{
danea83bc62011-04-01 11:56:32 +00001938 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001939 storeLastErrno(pFile, errno);
drhcd731cf2009-03-28 23:23:02 +00001940 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001941 }
drhbbd42a62004-05-22 17:41:58 +00001942 }
drh308c2a52010-05-14 11:30:18 +00001943 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001944 /* Decrement the shared lock counter. Release the lock using an
1945 ** OS call only when all threads in this same process have released
1946 ** the lock.
1947 */
drh8af6c222010-05-14 12:43:01 +00001948 pInode->nShared--;
1949 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001950 lock.l_type = F_UNLCK;
1951 lock.l_whence = SEEK_SET;
1952 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001953 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001954 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001955 }else{
danea83bc62011-04-01 11:56:32 +00001956 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001957 storeLastErrno(pFile, errno);
drh8af6c222010-05-14 12:43:01 +00001958 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001959 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001960 }
drha6abd042004-06-09 17:37:22 +00001961 }
1962
drhbbd42a62004-05-22 17:41:58 +00001963 /* Decrement the count of locks against this same file. When the
1964 ** count reaches zero, close any other file descriptors whose close
1965 ** was deferred because of outstanding locks.
1966 */
drh8af6c222010-05-14 12:43:01 +00001967 pInode->nLock--;
1968 assert( pInode->nLock>=0 );
1969 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001970 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001971 }
1972 }
drhf2f105d2012-08-20 15:53:54 +00001973
aswift5b1a2562008-08-22 00:22:35 +00001974end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001975 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001976 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001977 return rc;
drhbbd42a62004-05-22 17:41:58 +00001978}
1979
1980/*
drh308c2a52010-05-14 11:30:18 +00001981** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001982** must be either NO_LOCK or SHARED_LOCK.
1983**
1984** If the locking level of the file descriptor is already at or below
1985** the requested locking level, this routine is a no-op.
1986*/
drh308c2a52010-05-14 11:30:18 +00001987static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00001988#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00001989 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00001990#endif
drha7e61d82011-03-12 17:02:57 +00001991 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001992}
1993
mistachkine98844f2013-08-24 00:59:24 +00001994#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001995static int unixMapfile(unixFile *pFd, i64 nByte);
1996static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00001997#endif
danf23da962013-03-23 21:00:41 +00001998
drh7ed97b92010-01-20 13:07:21 +00001999/*
danielk1977e339d652008-06-28 11:23:00 +00002000** This function performs the parts of the "close file" operation
2001** common to all locking schemes. It closes the directory and file
2002** handles, if they are valid, and sets all fields of the unixFile
2003** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00002004**
2005** It is *not* necessary to hold the mutex when this routine is called,
2006** even on VxWorks. A mutex will be acquired on VxWorks by the
2007** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00002008*/
2009static int closeUnixFile(sqlite3_file *id){
2010 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00002011#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00002012 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00002013#endif
dan661d71a2011-03-30 19:08:03 +00002014 if( pFile->h>=0 ){
2015 robust_close(pFile, pFile->h, __LINE__);
2016 pFile->h = -1;
2017 }
2018#if OS_VXWORKS
2019 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00002020 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00002021 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00002022 }
2023 vxworksReleaseFileId(pFile->pId);
2024 pFile->pId = 0;
2025 }
2026#endif
drh0bdbc902014-06-16 18:35:06 +00002027#ifdef SQLITE_UNLINK_AFTER_CLOSE
2028 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
2029 osUnlink(pFile->zPath);
2030 sqlite3_free(*(char**)&pFile->zPath);
2031 pFile->zPath = 0;
2032 }
2033#endif
dan661d71a2011-03-30 19:08:03 +00002034 OSTRACE(("CLOSE %-3d\n", pFile->h));
2035 OpenCounter(-1);
drhc68886b2017-08-18 16:09:52 +00002036 sqlite3_free(pFile->pPreallocatedUnused);
dan661d71a2011-03-30 19:08:03 +00002037 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00002038 return SQLITE_OK;
2039}
2040
2041/*
danielk1977e3026632004-06-22 11:29:02 +00002042** Close a file.
2043*/
danielk197762079062007-08-15 17:08:46 +00002044static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00002045 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00002046 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00002047 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00002048 unixUnlock(id, NO_LOCK);
2049 unixEnterMutex();
2050
2051 /* unixFile.pInode is always valid here. Otherwise, a different close
2052 ** routine (e.g. nolockClose()) would be called instead.
2053 */
2054 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
2055 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
2056 /* If there are outstanding locks, do not actually close the file just
2057 ** yet because that would clear those locks. Instead, add the file
2058 ** descriptor to pInode->pUnused list. It will be automatically closed
2059 ** when the last lock is cleared.
2060 */
2061 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00002062 }
dan661d71a2011-03-30 19:08:03 +00002063 releaseInodeInfo(pFile);
2064 rc = closeUnixFile(id);
2065 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00002066 return rc;
danielk1977e3026632004-06-22 11:29:02 +00002067}
2068
drh734c9862008-11-28 15:37:20 +00002069/************** End of the posix advisory lock implementation *****************
2070******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002071
drh734c9862008-11-28 15:37:20 +00002072/******************************************************************************
2073****************************** No-op Locking **********************************
2074**
2075** Of the various locking implementations available, this is by far the
2076** simplest: locking is ignored. No attempt is made to lock the database
2077** file for reading or writing.
2078**
2079** This locking mode is appropriate for use on read-only databases
2080** (ex: databases that are burned into CD-ROM, for example.) It can
2081** also be used if the application employs some external mechanism to
2082** prevent simultaneous access of the same database by two or more
2083** database connections. But there is a serious risk of database
2084** corruption if this locking mode is used in situations where multiple
2085** database connections are accessing the same database file at the same
2086** time and one or more of those connections are writing.
2087*/
drhbfe66312006-10-03 17:40:40 +00002088
drh734c9862008-11-28 15:37:20 +00002089static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
2090 UNUSED_PARAMETER(NotUsed);
2091 *pResOut = 0;
2092 return SQLITE_OK;
2093}
drh734c9862008-11-28 15:37:20 +00002094static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
2095 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2096 return SQLITE_OK;
2097}
drh734c9862008-11-28 15:37:20 +00002098static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
2099 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2100 return SQLITE_OK;
2101}
2102
2103/*
drh9b35ea62008-11-29 02:20:26 +00002104** Close the file.
drh734c9862008-11-28 15:37:20 +00002105*/
2106static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00002107 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002108}
2109
2110/******************* End of the no-op lock implementation *********************
2111******************************************************************************/
2112
2113/******************************************************************************
2114************************* Begin dot-file Locking ******************************
2115**
mistachkin48864df2013-03-21 21:20:32 +00002116** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00002117** files (really a directory) to control access to the database. This works
2118** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002119**
2120** (1) There is zero concurrency. A single reader blocks all other
2121** connections from reading or writing the database.
2122**
2123** (2) An application crash or power loss can leave stale lock files
2124** sitting around that need to be cleared manually.
2125**
2126** Nevertheless, a dotlock is an appropriate locking mode for use if no
2127** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002128**
drh9ef6bc42011-11-04 02:24:02 +00002129** Dotfile locking works by creating a subdirectory in the same directory as
2130** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002131** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002132** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002133*/
2134
2135/*
2136** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002137** lock directory.
drh734c9862008-11-28 15:37:20 +00002138*/
2139#define DOTLOCK_SUFFIX ".lock"
2140
drh7708e972008-11-29 00:56:52 +00002141/*
2142** This routine checks if there is a RESERVED lock held on the specified
2143** file by this or any other process. If such a lock is held, set *pResOut
2144** to a non-zero value otherwise *pResOut is set to zero. The return value
2145** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2146**
2147** In dotfile locking, either a lock exists or it does not. So in this
2148** variation of CheckReservedLock(), *pResOut is set to true if any lock
2149** is held on the file and false if the file is unlocked.
2150*/
drh734c9862008-11-28 15:37:20 +00002151static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2152 int rc = SQLITE_OK;
2153 int reserved = 0;
2154 unixFile *pFile = (unixFile*)id;
2155
2156 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2157
2158 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00002159 reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
drh308c2a52010-05-14 11:30:18 +00002160 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002161 *pResOut = reserved;
2162 return rc;
2163}
2164
drh7708e972008-11-29 00:56:52 +00002165/*
drh308c2a52010-05-14 11:30:18 +00002166** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002167** of the following:
2168**
2169** (1) SHARED_LOCK
2170** (2) RESERVED_LOCK
2171** (3) PENDING_LOCK
2172** (4) EXCLUSIVE_LOCK
2173**
2174** Sometimes when requesting one lock state, additional lock states
2175** are inserted in between. The locking might fail on one of the later
2176** transitions leaving the lock state different from what it started but
2177** still short of its goal. The following chart shows the allowed
2178** transitions and the inserted intermediate states:
2179**
2180** UNLOCKED -> SHARED
2181** SHARED -> RESERVED
2182** SHARED -> (PENDING) -> EXCLUSIVE
2183** RESERVED -> (PENDING) -> EXCLUSIVE
2184** PENDING -> EXCLUSIVE
2185**
2186** This routine will only increase a lock. Use the sqlite3OsUnlock()
2187** routine to lower a locking level.
2188**
2189** With dotfile locking, we really only support state (4): EXCLUSIVE.
2190** But we track the other locking levels internally.
2191*/
drh308c2a52010-05-14 11:30:18 +00002192static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002193 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002194 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002195 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002196
drh7708e972008-11-29 00:56:52 +00002197
2198 /* If we have any lock, then the lock file already exists. All we have
2199 ** to do is adjust our internal record of the lock level.
2200 */
drh308c2a52010-05-14 11:30:18 +00002201 if( pFile->eFileLock > NO_LOCK ){
2202 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002203 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002204#ifdef HAVE_UTIME
2205 utime(zLockFile, NULL);
2206#else
drh734c9862008-11-28 15:37:20 +00002207 utimes(zLockFile, NULL);
2208#endif
drh7708e972008-11-29 00:56:52 +00002209 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002210 }
2211
2212 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002213 rc = osMkdir(zLockFile, 0777);
2214 if( rc<0 ){
2215 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002216 int tErrno = errno;
2217 if( EEXIST == tErrno ){
2218 rc = SQLITE_BUSY;
2219 } else {
2220 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drha8de1e12015-11-30 00:05:39 +00002221 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00002222 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002223 }
2224 }
drh7708e972008-11-29 00:56:52 +00002225 return rc;
drh734c9862008-11-28 15:37:20 +00002226 }
drh734c9862008-11-28 15:37:20 +00002227
2228 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002229 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002230 return rc;
2231}
2232
drh7708e972008-11-29 00:56:52 +00002233/*
drh308c2a52010-05-14 11:30:18 +00002234** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002235** must be either NO_LOCK or SHARED_LOCK.
2236**
2237** If the locking level of the file descriptor is already at or below
2238** the requested locking level, this routine is a no-op.
2239**
2240** When the locking level reaches NO_LOCK, delete the lock file.
2241*/
drh308c2a52010-05-14 11:30:18 +00002242static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002243 unixFile *pFile = (unixFile*)id;
2244 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002245 int rc;
drh734c9862008-11-28 15:37:20 +00002246
2247 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002248 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002249 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002250 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002251
2252 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002253 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002254 return SQLITE_OK;
2255 }
drh7708e972008-11-29 00:56:52 +00002256
2257 /* To downgrade to shared, simply update our internal notion of the
2258 ** lock state. No need to mess with the file on disk.
2259 */
drh308c2a52010-05-14 11:30:18 +00002260 if( eFileLock==SHARED_LOCK ){
2261 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002262 return SQLITE_OK;
2263 }
2264
drh7708e972008-11-29 00:56:52 +00002265 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002266 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002267 rc = osRmdir(zLockFile);
drh9ef6bc42011-11-04 02:24:02 +00002268 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002269 int tErrno = errno;
drha8de1e12015-11-30 00:05:39 +00002270 if( tErrno==ENOENT ){
2271 rc = SQLITE_OK;
2272 }else{
danea83bc62011-04-01 11:56:32 +00002273 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002274 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002275 }
2276 return rc;
2277 }
drh308c2a52010-05-14 11:30:18 +00002278 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002279 return SQLITE_OK;
2280}
2281
2282/*
drh9b35ea62008-11-29 02:20:26 +00002283** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002284*/
2285static int dotlockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002286 unixFile *pFile = (unixFile*)id;
2287 assert( id!=0 );
2288 dotlockUnlock(id, NO_LOCK);
2289 sqlite3_free(pFile->lockingContext);
2290 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002291}
2292/****************** End of the dot-file lock implementation *******************
2293******************************************************************************/
2294
2295/******************************************************************************
2296************************** Begin flock Locking ********************************
2297**
2298** Use the flock() system call to do file locking.
2299**
drh6b9d6dd2008-12-03 19:34:47 +00002300** flock() locking is like dot-file locking in that the various
2301** fine-grain locking levels supported by SQLite are collapsed into
2302** a single exclusive lock. In other words, SHARED, RESERVED, and
2303** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2304** still works when you do this, but concurrency is reduced since
2305** only a single process can be reading the database at a time.
2306**
drhe89b2912015-03-03 20:42:01 +00002307** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
drh734c9862008-11-28 15:37:20 +00002308*/
drhe89b2912015-03-03 20:42:01 +00002309#if SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002310
drh6b9d6dd2008-12-03 19:34:47 +00002311/*
drhff812312011-02-23 13:33:46 +00002312** Retry flock() calls that fail with EINTR
2313*/
2314#ifdef EINTR
2315static int robust_flock(int fd, int op){
2316 int rc;
2317 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2318 return rc;
2319}
2320#else
drh5c819272011-02-23 14:00:12 +00002321# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002322#endif
2323
2324
2325/*
drh6b9d6dd2008-12-03 19:34:47 +00002326** This routine checks if there is a RESERVED lock held on the specified
2327** file by this or any other process. If such a lock is held, set *pResOut
2328** to a non-zero value otherwise *pResOut is set to zero. The return value
2329** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2330*/
drh734c9862008-11-28 15:37:20 +00002331static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2332 int rc = SQLITE_OK;
2333 int reserved = 0;
2334 unixFile *pFile = (unixFile*)id;
2335
2336 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2337
2338 assert( pFile );
2339
2340 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002341 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002342 reserved = 1;
2343 }
2344
2345 /* Otherwise see if some other process holds it. */
2346 if( !reserved ){
2347 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002348 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002349 if( !lrc ){
2350 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002351 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002352 if ( lrc ) {
2353 int tErrno = errno;
2354 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002355 lrc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00002356 storeLastErrno(pFile, tErrno);
2357 rc = lrc;
drh734c9862008-11-28 15:37:20 +00002358 }
2359 } else {
2360 int tErrno = errno;
2361 reserved = 1;
2362 /* someone else might have it reserved */
2363 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2364 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002365 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002366 rc = lrc;
2367 }
2368 }
2369 }
drh308c2a52010-05-14 11:30:18 +00002370 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002371
2372#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
drh2e233812017-08-22 15:21:54 +00002373 if( (rc & 0xff) == SQLITE_IOERR ){
drh734c9862008-11-28 15:37:20 +00002374 rc = SQLITE_OK;
2375 reserved=1;
2376 }
2377#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2378 *pResOut = reserved;
2379 return rc;
2380}
2381
drh6b9d6dd2008-12-03 19:34:47 +00002382/*
drh308c2a52010-05-14 11:30:18 +00002383** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002384** of the following:
2385**
2386** (1) SHARED_LOCK
2387** (2) RESERVED_LOCK
2388** (3) PENDING_LOCK
2389** (4) EXCLUSIVE_LOCK
2390**
2391** Sometimes when requesting one lock state, additional lock states
2392** are inserted in between. The locking might fail on one of the later
2393** transitions leaving the lock state different from what it started but
2394** still short of its goal. The following chart shows the allowed
2395** transitions and the inserted intermediate states:
2396**
2397** UNLOCKED -> SHARED
2398** SHARED -> RESERVED
2399** SHARED -> (PENDING) -> EXCLUSIVE
2400** RESERVED -> (PENDING) -> EXCLUSIVE
2401** PENDING -> EXCLUSIVE
2402**
2403** flock() only really support EXCLUSIVE locks. We track intermediate
2404** lock states in the sqlite3_file structure, but all locks SHARED or
2405** above are really EXCLUSIVE locks and exclude all other processes from
2406** access the file.
2407**
2408** This routine will only increase a lock. Use the sqlite3OsUnlock()
2409** routine to lower a locking level.
2410*/
drh308c2a52010-05-14 11:30:18 +00002411static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002412 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002413 unixFile *pFile = (unixFile*)id;
2414
2415 assert( pFile );
2416
2417 /* if we already have a lock, it is exclusive.
2418 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002419 if (pFile->eFileLock > NO_LOCK) {
2420 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002421 return SQLITE_OK;
2422 }
2423
2424 /* grab an exclusive lock */
2425
drhff812312011-02-23 13:33:46 +00002426 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002427 int tErrno = errno;
2428 /* didn't get, must be busy */
2429 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2430 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002431 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002432 }
2433 } else {
2434 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002435 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002436 }
drh308c2a52010-05-14 11:30:18 +00002437 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2438 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002439#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
drh2e233812017-08-22 15:21:54 +00002440 if( (rc & 0xff) == SQLITE_IOERR ){
drh734c9862008-11-28 15:37:20 +00002441 rc = SQLITE_BUSY;
2442 }
2443#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2444 return rc;
2445}
2446
drh6b9d6dd2008-12-03 19:34:47 +00002447
2448/*
drh308c2a52010-05-14 11:30:18 +00002449** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002450** must be either NO_LOCK or SHARED_LOCK.
2451**
2452** If the locking level of the file descriptor is already at or below
2453** the requested locking level, this routine is a no-op.
2454*/
drh308c2a52010-05-14 11:30:18 +00002455static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002456 unixFile *pFile = (unixFile*)id;
2457
2458 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002459 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002460 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002461 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002462
2463 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002464 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002465 return SQLITE_OK;
2466 }
2467
2468 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002469 if (eFileLock==SHARED_LOCK) {
2470 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002471 return SQLITE_OK;
2472 }
2473
2474 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002475 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002476#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002477 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002478#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002479 return SQLITE_IOERR_UNLOCK;
2480 }else{
drh308c2a52010-05-14 11:30:18 +00002481 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002482 return SQLITE_OK;
2483 }
2484}
2485
2486/*
2487** Close a file.
2488*/
2489static int flockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002490 assert( id!=0 );
2491 flockUnlock(id, NO_LOCK);
2492 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002493}
2494
2495#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2496
2497/******************* End of the flock lock implementation *********************
2498******************************************************************************/
2499
2500/******************************************************************************
2501************************ Begin Named Semaphore Locking ************************
2502**
2503** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002504**
2505** Semaphore locking is like dot-lock and flock in that it really only
2506** supports EXCLUSIVE locking. Only a single process can read or write
2507** the database file at a time. This reduces potential concurrency, but
2508** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002509*/
2510#if OS_VXWORKS
2511
drh6b9d6dd2008-12-03 19:34:47 +00002512/*
2513** This routine checks if there is a RESERVED lock held on the specified
2514** file by this or any other process. If such a lock is held, set *pResOut
2515** to a non-zero value otherwise *pResOut is set to zero. The return value
2516** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2517*/
drh8cd5b252015-03-02 22:06:43 +00002518static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
drh734c9862008-11-28 15:37:20 +00002519 int rc = SQLITE_OK;
2520 int reserved = 0;
2521 unixFile *pFile = (unixFile*)id;
2522
2523 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2524
2525 assert( pFile );
2526
2527 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002528 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002529 reserved = 1;
2530 }
2531
2532 /* Otherwise see if some other process holds it. */
2533 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002534 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002535
2536 if( sem_trywait(pSem)==-1 ){
2537 int tErrno = errno;
2538 if( EAGAIN != tErrno ){
2539 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
drh4bf66fd2015-02-19 02:43:02 +00002540 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002541 } else {
2542 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002543 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002544 }
2545 }else{
2546 /* we could have it if we want it */
2547 sem_post(pSem);
2548 }
2549 }
drh308c2a52010-05-14 11:30:18 +00002550 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002551
2552 *pResOut = reserved;
2553 return rc;
2554}
2555
drh6b9d6dd2008-12-03 19:34:47 +00002556/*
drh308c2a52010-05-14 11:30:18 +00002557** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002558** of the following:
2559**
2560** (1) SHARED_LOCK
2561** (2) RESERVED_LOCK
2562** (3) PENDING_LOCK
2563** (4) EXCLUSIVE_LOCK
2564**
2565** Sometimes when requesting one lock state, additional lock states
2566** are inserted in between. The locking might fail on one of the later
2567** transitions leaving the lock state different from what it started but
2568** still short of its goal. The following chart shows the allowed
2569** transitions and the inserted intermediate states:
2570**
2571** UNLOCKED -> SHARED
2572** SHARED -> RESERVED
2573** SHARED -> (PENDING) -> EXCLUSIVE
2574** RESERVED -> (PENDING) -> EXCLUSIVE
2575** PENDING -> EXCLUSIVE
2576**
2577** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2578** lock states in the sqlite3_file structure, but all locks SHARED or
2579** above are really EXCLUSIVE locks and exclude all other processes from
2580** access the file.
2581**
2582** This routine will only increase a lock. Use the sqlite3OsUnlock()
2583** routine to lower a locking level.
2584*/
drh8cd5b252015-03-02 22:06:43 +00002585static int semXLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002586 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002587 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002588 int rc = SQLITE_OK;
2589
2590 /* if we already have a lock, it is exclusive.
2591 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002592 if (pFile->eFileLock > NO_LOCK) {
2593 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002594 rc = SQLITE_OK;
2595 goto sem_end_lock;
2596 }
2597
2598 /* lock semaphore now but bail out when already locked. */
2599 if( sem_trywait(pSem)==-1 ){
2600 rc = SQLITE_BUSY;
2601 goto sem_end_lock;
2602 }
2603
2604 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002605 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002606
2607 sem_end_lock:
2608 return rc;
2609}
2610
drh6b9d6dd2008-12-03 19:34:47 +00002611/*
drh308c2a52010-05-14 11:30:18 +00002612** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002613** must be either NO_LOCK or SHARED_LOCK.
2614**
2615** If the locking level of the file descriptor is already at or below
2616** the requested locking level, this routine is a no-op.
2617*/
drh8cd5b252015-03-02 22:06:43 +00002618static int semXUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002619 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002620 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002621
2622 assert( pFile );
2623 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002624 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002625 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002626 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002627
2628 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002629 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002630 return SQLITE_OK;
2631 }
2632
2633 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002634 if (eFileLock==SHARED_LOCK) {
2635 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002636 return SQLITE_OK;
2637 }
2638
2639 /* no, really unlock. */
2640 if ( sem_post(pSem)==-1 ) {
2641 int rc, tErrno = errno;
2642 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2643 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002644 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002645 }
2646 return rc;
2647 }
drh308c2a52010-05-14 11:30:18 +00002648 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002649 return SQLITE_OK;
2650}
2651
2652/*
2653 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002654 */
drh8cd5b252015-03-02 22:06:43 +00002655static int semXClose(sqlite3_file *id) {
drh734c9862008-11-28 15:37:20 +00002656 if( id ){
2657 unixFile *pFile = (unixFile*)id;
drh8cd5b252015-03-02 22:06:43 +00002658 semXUnlock(id, NO_LOCK);
drh734c9862008-11-28 15:37:20 +00002659 assert( pFile );
2660 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002661 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002662 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002663 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002664 }
2665 return SQLITE_OK;
2666}
2667
2668#endif /* OS_VXWORKS */
2669/*
2670** Named semaphore locking is only available on VxWorks.
2671**
2672*************** End of the named semaphore lock implementation ****************
2673******************************************************************************/
2674
2675
2676/******************************************************************************
2677*************************** Begin AFP Locking *********************************
2678**
2679** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2680** on Apple Macintosh computers - both OS9 and OSX.
2681**
2682** Third-party implementations of AFP are available. But this code here
2683** only works on OSX.
2684*/
2685
drhd2cb50b2009-01-09 21:41:17 +00002686#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002687/*
2688** The afpLockingContext structure contains all afp lock specific state
2689*/
drhbfe66312006-10-03 17:40:40 +00002690typedef struct afpLockingContext afpLockingContext;
2691struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002692 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002693 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002694};
2695
2696struct ByteRangeLockPB2
2697{
2698 unsigned long long offset; /* offset to first byte to lock */
2699 unsigned long long length; /* nbr of bytes to lock */
2700 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2701 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2702 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2703 int fd; /* file desc to assoc this lock with */
2704};
2705
drhfd131da2007-08-07 17:13:03 +00002706#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002707
drh6b9d6dd2008-12-03 19:34:47 +00002708/*
2709** This is a utility for setting or clearing a bit-range lock on an
2710** AFP filesystem.
2711**
2712** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2713*/
2714static int afpSetLock(
2715 const char *path, /* Name of the file to be locked or unlocked */
2716 unixFile *pFile, /* Open file descriptor on path */
2717 unsigned long long offset, /* First byte to be locked */
2718 unsigned long long length, /* Number of bytes to lock */
2719 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002720){
drh6b9d6dd2008-12-03 19:34:47 +00002721 struct ByteRangeLockPB2 pb;
2722 int err;
drhbfe66312006-10-03 17:40:40 +00002723
2724 pb.unLockFlag = setLockFlag ? 0 : 1;
2725 pb.startEndFlag = 0;
2726 pb.offset = offset;
2727 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002728 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002729
drh308c2a52010-05-14 11:30:18 +00002730 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002731 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002732 offset, length));
drhbfe66312006-10-03 17:40:40 +00002733 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2734 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002735 int rc;
2736 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002737 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2738 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002739#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2740 rc = SQLITE_BUSY;
2741#else
drh734c9862008-11-28 15:37:20 +00002742 rc = sqliteErrorFromPosixError(tErrno,
2743 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002744#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002745 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002746 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00002747 }
2748 return rc;
drhbfe66312006-10-03 17:40:40 +00002749 } else {
aswift5b1a2562008-08-22 00:22:35 +00002750 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002751 }
2752}
2753
drh6b9d6dd2008-12-03 19:34:47 +00002754/*
2755** This routine checks if there is a RESERVED lock held on the specified
2756** file by this or any other process. If such a lock is held, set *pResOut
2757** to a non-zero value otherwise *pResOut is set to zero. The return value
2758** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2759*/
danielk1977e339d652008-06-28 11:23:00 +00002760static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002761 int rc = SQLITE_OK;
2762 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002763 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002764 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002765
aswift5b1a2562008-08-22 00:22:35 +00002766 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2767
2768 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002769 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002770 if( context->reserved ){
2771 *pResOut = 1;
2772 return SQLITE_OK;
2773 }
drh8af6c222010-05-14 12:43:01 +00002774 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002775
2776 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002777 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002778 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002779 }
2780
2781 /* Otherwise see if some other process holds it.
2782 */
aswift5b1a2562008-08-22 00:22:35 +00002783 if( !reserved ){
2784 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002785 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002786 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002787 /* if we succeeded in taking the reserved lock, unlock it to restore
2788 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002789 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002790 } else {
2791 /* if we failed to get the lock then someone else must have it */
2792 reserved = 1;
2793 }
2794 if( IS_LOCK_ERROR(lrc) ){
2795 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002796 }
2797 }
drhbfe66312006-10-03 17:40:40 +00002798
drh7ed97b92010-01-20 13:07:21 +00002799 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002800 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002801
2802 *pResOut = reserved;
2803 return rc;
drhbfe66312006-10-03 17:40:40 +00002804}
2805
drh6b9d6dd2008-12-03 19:34:47 +00002806/*
drh308c2a52010-05-14 11:30:18 +00002807** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002808** of the following:
2809**
2810** (1) SHARED_LOCK
2811** (2) RESERVED_LOCK
2812** (3) PENDING_LOCK
2813** (4) EXCLUSIVE_LOCK
2814**
2815** Sometimes when requesting one lock state, additional lock states
2816** are inserted in between. The locking might fail on one of the later
2817** transitions leaving the lock state different from what it started but
2818** still short of its goal. The following chart shows the allowed
2819** transitions and the inserted intermediate states:
2820**
2821** UNLOCKED -> SHARED
2822** SHARED -> RESERVED
2823** SHARED -> (PENDING) -> EXCLUSIVE
2824** RESERVED -> (PENDING) -> EXCLUSIVE
2825** PENDING -> EXCLUSIVE
2826**
2827** This routine will only increase a lock. Use the sqlite3OsUnlock()
2828** routine to lower a locking level.
2829*/
drh308c2a52010-05-14 11:30:18 +00002830static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002831 int rc = SQLITE_OK;
2832 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002833 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002834 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002835
2836 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002837 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2838 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh5ac93652015-03-21 20:59:43 +00002839 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
drh339eb0b2008-03-07 15:34:11 +00002840
drhbfe66312006-10-03 17:40:40 +00002841 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002842 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002843 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002844 */
drh308c2a52010-05-14 11:30:18 +00002845 if( pFile->eFileLock>=eFileLock ){
2846 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2847 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002848 return SQLITE_OK;
2849 }
2850
2851 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002852 ** (1) We never move from unlocked to anything higher than shared lock.
2853 ** (2) SQLite never explicitly requests a pendig lock.
2854 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002855 */
drh308c2a52010-05-14 11:30:18 +00002856 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2857 assert( eFileLock!=PENDING_LOCK );
2858 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002859
drh8af6c222010-05-14 12:43:01 +00002860 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002861 */
drh6c7d5c52008-11-21 20:32:33 +00002862 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002863 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002864
2865 /* If some thread using this PID has a lock via a different unixFile*
2866 ** handle that precludes the requested lock, return BUSY.
2867 */
drh8af6c222010-05-14 12:43:01 +00002868 if( (pFile->eFileLock!=pInode->eFileLock &&
2869 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002870 ){
2871 rc = SQLITE_BUSY;
2872 goto afp_end_lock;
2873 }
2874
2875 /* If a SHARED lock is requested, and some thread using this PID already
2876 ** has a SHARED or RESERVED lock, then increment reference counts and
2877 ** return SQLITE_OK.
2878 */
drh308c2a52010-05-14 11:30:18 +00002879 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002880 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002881 assert( eFileLock==SHARED_LOCK );
2882 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002883 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002884 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002885 pInode->nShared++;
2886 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002887 goto afp_end_lock;
2888 }
drhbfe66312006-10-03 17:40:40 +00002889
2890 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002891 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2892 ** be released.
2893 */
drh308c2a52010-05-14 11:30:18 +00002894 if( eFileLock==SHARED_LOCK
2895 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002896 ){
2897 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002898 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002899 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002900 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002901 goto afp_end_lock;
2902 }
2903 }
2904
2905 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002906 ** operating system calls for the specified lock.
2907 */
drh308c2a52010-05-14 11:30:18 +00002908 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002909 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002910 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002911
drh8af6c222010-05-14 12:43:01 +00002912 assert( pInode->nShared==0 );
2913 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002914
2915 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002916 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002917 /* note that the quality of the randomness doesn't matter that much */
2918 lk = random();
drh8af6c222010-05-14 12:43:01 +00002919 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002920 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002921 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002922 if( IS_LOCK_ERROR(lrc1) ){
2923 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002924 }
aswift5b1a2562008-08-22 00:22:35 +00002925 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002926 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002927
aswift5b1a2562008-08-22 00:22:35 +00002928 if( IS_LOCK_ERROR(lrc1) ) {
drh4bf66fd2015-02-19 02:43:02 +00002929 storeLastErrno(pFile, lrc1Errno);
aswift5b1a2562008-08-22 00:22:35 +00002930 rc = lrc1;
2931 goto afp_end_lock;
2932 } else if( IS_LOCK_ERROR(lrc2) ){
2933 rc = lrc2;
2934 goto afp_end_lock;
2935 } else if( lrc1 != SQLITE_OK ) {
2936 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002937 } else {
drh308c2a52010-05-14 11:30:18 +00002938 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002939 pInode->nLock++;
2940 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002941 }
drh8af6c222010-05-14 12:43:01 +00002942 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002943 /* We are trying for an exclusive lock but another thread in this
2944 ** same process is still holding a shared lock. */
2945 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002946 }else{
2947 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2948 ** assumed that there is a SHARED or greater lock on the file
2949 ** already.
2950 */
2951 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002952 assert( 0!=pFile->eFileLock );
2953 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002954 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002955 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002956 if( !failed ){
2957 context->reserved = 1;
2958 }
drhbfe66312006-10-03 17:40:40 +00002959 }
drh308c2a52010-05-14 11:30:18 +00002960 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002961 /* Acquire an EXCLUSIVE lock */
2962
2963 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002964 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002965 */
drh6b9d6dd2008-12-03 19:34:47 +00002966 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002967 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002968 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002969 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002970 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002971 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002972 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002973 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002974 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2975 ** a critical I/O error
2976 */
drh2e233812017-08-22 15:21:54 +00002977 rc = ((failed & 0xff) == SQLITE_IOERR) ? failed2 :
aswiftaebf4132008-11-21 00:10:35 +00002978 SQLITE_IOERR_LOCK;
2979 goto afp_end_lock;
2980 }
2981 }else{
aswift5b1a2562008-08-22 00:22:35 +00002982 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002983 }
2984 }
aswift5b1a2562008-08-22 00:22:35 +00002985 if( failed ){
2986 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002987 }
2988 }
2989
2990 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002991 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002992 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002993 }else if( eFileLock==EXCLUSIVE_LOCK ){
2994 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002995 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002996 }
2997
2998afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002999 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00003000 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
3001 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00003002 return rc;
3003}
3004
3005/*
drh308c2a52010-05-14 11:30:18 +00003006** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00003007** must be either NO_LOCK or SHARED_LOCK.
3008**
3009** If the locking level of the file descriptor is already at or below
3010** the requested locking level, this routine is a no-op.
3011*/
drh308c2a52010-05-14 11:30:18 +00003012static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00003013 int rc = SQLITE_OK;
3014 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00003015 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00003016 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
3017 int skipShared = 0;
3018#ifdef SQLITE_TEST
3019 int h = pFile->h;
3020#endif
drhbfe66312006-10-03 17:40:40 +00003021
3022 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003023 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00003024 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00003025 osGetpid(0)));
aswift5b1a2562008-08-22 00:22:35 +00003026
drh308c2a52010-05-14 11:30:18 +00003027 assert( eFileLock<=SHARED_LOCK );
3028 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00003029 return SQLITE_OK;
3030 }
drh6c7d5c52008-11-21 20:32:33 +00003031 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00003032 pInode = pFile->pInode;
3033 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00003034 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00003035 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00003036 SimulateIOErrorBenign(1);
3037 SimulateIOError( h=(-1) )
3038 SimulateIOErrorBenign(0);
3039
drhd3d8c042012-05-29 17:02:40 +00003040#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00003041 /* When reducing a lock such that other processes can start
3042 ** reading the database file again, make sure that the
3043 ** transaction counter was updated if any part of the database
3044 ** file changed. If the transaction counter is not updated,
3045 ** other connections to the same file might not realize that
3046 ** the file has changed and hence might not know to flush their
3047 ** cache. The use of a stale cache can lead to database corruption.
3048 */
3049 assert( pFile->inNormalWrite==0
3050 || pFile->dbUpdate==0
3051 || pFile->transCntrChng==1 );
3052 pFile->inNormalWrite = 0;
3053#endif
aswiftaebf4132008-11-21 00:10:35 +00003054
drh308c2a52010-05-14 11:30:18 +00003055 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00003056 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00003057 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00003058 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00003059 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00003060 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
3061 } else {
3062 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00003063 }
3064 }
drh308c2a52010-05-14 11:30:18 +00003065 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00003066 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00003067 }
drh308c2a52010-05-14 11:30:18 +00003068 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00003069 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
3070 if( !rc ){
3071 context->reserved = 0;
3072 }
aswiftaebf4132008-11-21 00:10:35 +00003073 }
drh8af6c222010-05-14 12:43:01 +00003074 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
3075 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003076 }
aswiftaebf4132008-11-21 00:10:35 +00003077 }
drh308c2a52010-05-14 11:30:18 +00003078 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00003079
drh7ed97b92010-01-20 13:07:21 +00003080 /* Decrement the shared lock counter. Release the lock using an
3081 ** OS call only when all threads in this same process have released
3082 ** the lock.
3083 */
drh8af6c222010-05-14 12:43:01 +00003084 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3085 pInode->nShared--;
3086 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00003087 SimulateIOErrorBenign(1);
3088 SimulateIOError( h=(-1) )
3089 SimulateIOErrorBenign(0);
3090 if( !skipShared ){
3091 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
3092 }
3093 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00003094 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00003095 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003096 }
3097 }
3098 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00003099 pInode->nLock--;
3100 assert( pInode->nLock>=0 );
3101 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00003102 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00003103 }
3104 }
drhbfe66312006-10-03 17:40:40 +00003105 }
drh7ed97b92010-01-20 13:07:21 +00003106
drh6c7d5c52008-11-21 20:32:33 +00003107 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00003108 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00003109 return rc;
3110}
3111
3112/*
drh339eb0b2008-03-07 15:34:11 +00003113** Close a file & cleanup AFP specific locking context
3114*/
danielk1977e339d652008-06-28 11:23:00 +00003115static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003116 int rc = SQLITE_OK;
drha8de1e12015-11-30 00:05:39 +00003117 unixFile *pFile = (unixFile*)id;
3118 assert( id!=0 );
3119 afpUnlock(id, NO_LOCK);
3120 unixEnterMutex();
3121 if( pFile->pInode && pFile->pInode->nLock ){
3122 /* If there are outstanding locks, do not actually close the file just
3123 ** yet because that would clear those locks. Instead, add the file
3124 ** descriptor to pInode->aPending. It will be automatically closed when
3125 ** the last lock is cleared.
3126 */
3127 setPendingFd(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003128 }
drha8de1e12015-11-30 00:05:39 +00003129 releaseInodeInfo(pFile);
3130 sqlite3_free(pFile->lockingContext);
3131 rc = closeUnixFile(id);
3132 unixLeaveMutex();
drh7ed97b92010-01-20 13:07:21 +00003133 return rc;
drhbfe66312006-10-03 17:40:40 +00003134}
3135
drhd2cb50b2009-01-09 21:41:17 +00003136#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003137/*
3138** The code above is the AFP lock implementation. The code is specific
3139** to MacOSX and does not work on other unix platforms. No alternative
3140** is available. If you don't compile for a mac, then the "unix-afp"
3141** VFS is not available.
3142**
3143********************* End of the AFP lock implementation **********************
3144******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003145
drh7ed97b92010-01-20 13:07:21 +00003146/******************************************************************************
3147*************************** Begin NFS Locking ********************************/
3148
3149#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3150/*
drh308c2a52010-05-14 11:30:18 +00003151 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003152 ** must be either NO_LOCK or SHARED_LOCK.
3153 **
3154 ** If the locking level of the file descriptor is already at or below
3155 ** the requested locking level, this routine is a no-op.
3156 */
drh308c2a52010-05-14 11:30:18 +00003157static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003158 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003159}
3160
3161#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3162/*
3163** The code above is the NFS lock implementation. The code is specific
3164** to MacOSX and does not work on other unix platforms. No alternative
3165** is available.
3166**
3167********************* End of the NFS lock implementation **********************
3168******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003169
3170/******************************************************************************
3171**************** Non-locking sqlite3_file methods *****************************
3172**
3173** The next division contains implementations for all methods of the
3174** sqlite3_file object other than the locking methods. The locking
3175** methods were defined in divisions above (one locking method per
3176** division). Those methods that are common to all locking modes
3177** are gather together into this division.
3178*/
drhbfe66312006-10-03 17:40:40 +00003179
3180/*
drh734c9862008-11-28 15:37:20 +00003181** Seek to the offset passed as the second argument, then read cnt
3182** bytes into pBuf. Return the number of bytes actually read.
3183**
3184** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3185** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3186** one system to another. Since SQLite does not define USE_PREAD
peter.d.reid60ec9142014-09-06 16:39:46 +00003187** in any form by default, we will not attempt to define _XOPEN_SOURCE.
drh734c9862008-11-28 15:37:20 +00003188** See tickets #2741 and #2681.
3189**
3190** To avoid stomping the errno value on a failed read the lastErrno value
3191** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003192*/
drh734c9862008-11-28 15:37:20 +00003193static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3194 int got;
drh58024642011-11-07 18:16:00 +00003195 int prior = 0;
drha46cadc2016-03-04 03:02:06 +00003196#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
3197 i64 newOffset;
3198#endif
drh734c9862008-11-28 15:37:20 +00003199 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003200 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003201 assert( id->h>2 );
drh58024642011-11-07 18:16:00 +00003202 do{
drh734c9862008-11-28 15:37:20 +00003203#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003204 got = osPread(id->h, pBuf, cnt, offset);
3205 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003206#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003207 got = osPread64(id->h, pBuf, cnt, offset);
3208 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003209#else
drha46cadc2016-03-04 03:02:06 +00003210 newOffset = lseek(id->h, offset, SEEK_SET);
3211 SimulateIOError( newOffset = -1 );
3212 if( newOffset<0 ){
3213 storeLastErrno((unixFile*)id, errno);
3214 return -1;
3215 }
3216 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003217#endif
drh58024642011-11-07 18:16:00 +00003218 if( got==cnt ) break;
3219 if( got<0 ){
3220 if( errno==EINTR ){ got = 1; continue; }
3221 prior = 0;
drh4bf66fd2015-02-19 02:43:02 +00003222 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003223 break;
3224 }else if( got>0 ){
3225 cnt -= got;
3226 offset += got;
3227 prior += got;
3228 pBuf = (void*)(got + (char*)pBuf);
3229 }
3230 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003231 TIMER_END;
drh58024642011-11-07 18:16:00 +00003232 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3233 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3234 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003235}
3236
3237/*
drh734c9862008-11-28 15:37:20 +00003238** Read data from a file into a buffer. Return SQLITE_OK if all
3239** bytes were read successfully and SQLITE_IOERR if anything goes
3240** wrong.
drh339eb0b2008-03-07 15:34:11 +00003241*/
drh734c9862008-11-28 15:37:20 +00003242static int unixRead(
3243 sqlite3_file *id,
3244 void *pBuf,
3245 int amt,
3246 sqlite3_int64 offset
3247){
dan08da86a2009-08-21 17:18:03 +00003248 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003249 int got;
3250 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003251 assert( offset>=0 );
3252 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003253
dan08da86a2009-08-21 17:18:03 +00003254 /* If this is a database file (not a journal, master-journal or temp
3255 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003256#if 0
drhc68886b2017-08-18 16:09:52 +00003257 assert( pFile->pPreallocatedUnused==0
dan08da86a2009-08-21 17:18:03 +00003258 || offset>=PENDING_BYTE+512
3259 || offset+amt<=PENDING_BYTE
3260 );
dan7c246102010-04-12 19:00:29 +00003261#endif
drh08c6d442009-02-09 17:34:07 +00003262
drh9b4c59f2013-04-15 17:03:42 +00003263#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003264 /* Deal with as much of this read request as possible by transfering
3265 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003266 if( offset<pFile->mmapSize ){
3267 if( offset+amt <= pFile->mmapSize ){
3268 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3269 return SQLITE_OK;
3270 }else{
3271 int nCopy = pFile->mmapSize - offset;
3272 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3273 pBuf = &((u8 *)pBuf)[nCopy];
3274 amt -= nCopy;
3275 offset += nCopy;
3276 }
3277 }
drh6e0b6d52013-04-09 16:19:20 +00003278#endif
danf23da962013-03-23 21:00:41 +00003279
dan08da86a2009-08-21 17:18:03 +00003280 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003281 if( got==amt ){
3282 return SQLITE_OK;
3283 }else if( got<0 ){
3284 /* lastErrno set by seekAndRead */
3285 return SQLITE_IOERR_READ;
3286 }else{
drh4bf66fd2015-02-19 02:43:02 +00003287 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003288 /* Unread parts of the buffer must be zero-filled */
3289 memset(&((char*)pBuf)[got], 0, amt-got);
3290 return SQLITE_IOERR_SHORT_READ;
3291 }
3292}
3293
3294/*
dan47a2b4a2013-04-26 16:09:29 +00003295** Attempt to seek the file-descriptor passed as the first argument to
3296** absolute offset iOff, then attempt to write nBuf bytes of data from
3297** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3298** return the actual number of bytes written (which may be less than
3299** nBuf).
3300*/
3301static int seekAndWriteFd(
3302 int fd, /* File descriptor to write to */
3303 i64 iOff, /* File offset to begin writing at */
3304 const void *pBuf, /* Copy data from this buffer to the file */
3305 int nBuf, /* Size of buffer pBuf in bytes */
3306 int *piErrno /* OUT: Error number if error occurs */
3307){
3308 int rc = 0; /* Value returned by system call */
3309
3310 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003311 assert( fd>2 );
drhe1818ec2015-12-01 16:21:35 +00003312 assert( piErrno!=0 );
dan47a2b4a2013-04-26 16:09:29 +00003313 nBuf &= 0x1ffff;
3314 TIMER_START;
3315
3316#if defined(USE_PREAD)
drh2da47d32015-02-21 00:56:05 +00003317 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
dan47a2b4a2013-04-26 16:09:29 +00003318#elif defined(USE_PREAD64)
drh2da47d32015-02-21 00:56:05 +00003319 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
dan47a2b4a2013-04-26 16:09:29 +00003320#else
3321 do{
3322 i64 iSeek = lseek(fd, iOff, SEEK_SET);
drhe1818ec2015-12-01 16:21:35 +00003323 SimulateIOError( iSeek = -1 );
3324 if( iSeek<0 ){
3325 rc = -1;
3326 break;
dan47a2b4a2013-04-26 16:09:29 +00003327 }
3328 rc = osWrite(fd, pBuf, nBuf);
3329 }while( rc<0 && errno==EINTR );
3330#endif
3331
3332 TIMER_END;
3333 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3334
drhe1818ec2015-12-01 16:21:35 +00003335 if( rc<0 ) *piErrno = errno;
dan47a2b4a2013-04-26 16:09:29 +00003336 return rc;
3337}
3338
3339
3340/*
drh734c9862008-11-28 15:37:20 +00003341** Seek to the offset in id->offset then read cnt bytes into pBuf.
3342** Return the number of bytes actually read. Update the offset.
3343**
3344** To avoid stomping the errno value on a failed write the lastErrno value
3345** is set before returning.
3346*/
3347static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003348 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003349}
3350
3351
3352/*
3353** Write data from a buffer into a file. Return SQLITE_OK on success
3354** or some other error code on failure.
3355*/
3356static int unixWrite(
3357 sqlite3_file *id,
3358 const void *pBuf,
3359 int amt,
3360 sqlite3_int64 offset
3361){
dan08da86a2009-08-21 17:18:03 +00003362 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003363 int wrote = 0;
3364 assert( id );
3365 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003366
dan08da86a2009-08-21 17:18:03 +00003367 /* If this is a database file (not a journal, master-journal or temp
3368 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003369#if 0
drhc68886b2017-08-18 16:09:52 +00003370 assert( pFile->pPreallocatedUnused==0
dan08da86a2009-08-21 17:18:03 +00003371 || offset>=PENDING_BYTE+512
3372 || offset+amt<=PENDING_BYTE
3373 );
dan7c246102010-04-12 19:00:29 +00003374#endif
drh08c6d442009-02-09 17:34:07 +00003375
drhd3d8c042012-05-29 17:02:40 +00003376#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003377 /* If we are doing a normal write to a database file (as opposed to
3378 ** doing a hot-journal rollback or a write to some file other than a
3379 ** normal database file) then record the fact that the database
3380 ** has changed. If the transaction counter is modified, record that
3381 ** fact too.
3382 */
dan08da86a2009-08-21 17:18:03 +00003383 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003384 pFile->dbUpdate = 1; /* The database has been modified */
3385 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003386 int rc;
drh8f941bc2009-01-14 23:03:40 +00003387 char oldCntr[4];
3388 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003389 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003390 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003391 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003392 pFile->transCntrChng = 1; /* The transaction counter has changed */
3393 }
3394 }
3395 }
3396#endif
3397
danfe33e392015-11-17 20:56:06 +00003398#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003399 /* Deal with as much of this write request as possible by transfering
3400 ** data from the memory mapping using memcpy(). */
3401 if( offset<pFile->mmapSize ){
3402 if( offset+amt <= pFile->mmapSize ){
3403 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3404 return SQLITE_OK;
3405 }else{
3406 int nCopy = pFile->mmapSize - offset;
3407 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3408 pBuf = &((u8 *)pBuf)[nCopy];
3409 amt -= nCopy;
3410 offset += nCopy;
3411 }
3412 }
drh6e0b6d52013-04-09 16:19:20 +00003413#endif
drh02bf8b42015-09-01 23:51:53 +00003414
3415 while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
drh734c9862008-11-28 15:37:20 +00003416 amt -= wrote;
3417 offset += wrote;
3418 pBuf = &((char*)pBuf)[wrote];
3419 }
3420 SimulateIOError(( wrote=(-1), amt=1 ));
3421 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003422
drh02bf8b42015-09-01 23:51:53 +00003423 if( amt>wrote ){
drha21b83b2011-04-15 12:36:10 +00003424 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003425 /* lastErrno set by seekAndWrite */
3426 return SQLITE_IOERR_WRITE;
3427 }else{
drh4bf66fd2015-02-19 02:43:02 +00003428 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003429 return SQLITE_FULL;
3430 }
3431 }
dan6e09d692010-07-27 18:34:15 +00003432
drh734c9862008-11-28 15:37:20 +00003433 return SQLITE_OK;
3434}
3435
3436#ifdef SQLITE_TEST
3437/*
3438** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003439** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003440*/
3441int sqlite3_sync_count = 0;
3442int sqlite3_fullsync_count = 0;
3443#endif
3444
3445/*
drh89240432009-03-25 01:06:01 +00003446** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003447** Others do no. To be safe, we will stick with the (slightly slower)
3448** fsync(). If you know that your system does support fdatasync() correctly,
drhf7a4a1b2015-01-10 18:02:45 +00003449** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003450*/
drhf7a4a1b2015-01-10 18:02:45 +00003451#if !defined(fdatasync) && !HAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003452# define fdatasync fsync
3453#endif
3454
3455/*
3456** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3457** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3458** only available on Mac OS X. But that could change.
3459*/
3460#ifdef F_FULLFSYNC
3461# define HAVE_FULLFSYNC 1
3462#else
3463# define HAVE_FULLFSYNC 0
3464#endif
3465
3466
3467/*
3468** The fsync() system call does not work as advertised on many
3469** unix systems. The following procedure is an attempt to make
3470** it work better.
3471**
3472** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3473** for testing when we want to run through the test suite quickly.
3474** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3475** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3476** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003477**
3478** SQLite sets the dataOnly flag if the size of the file is unchanged.
3479** The idea behind dataOnly is that it should only write the file content
3480** to disk, not the inode. We only set dataOnly if the file size is
3481** unchanged since the file size is part of the inode. However,
3482** Ted Ts'o tells us that fdatasync() will also write the inode if the
3483** file size has changed. The only real difference between fdatasync()
3484** and fsync(), Ted tells us, is that fdatasync() will not flush the
3485** inode if the mtime or owner or other inode attributes have changed.
3486** We only care about the file size, not the other file attributes, so
3487** as far as SQLite is concerned, an fdatasync() is always adequate.
3488** So, we always use fdatasync() if it is available, regardless of
3489** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003490*/
3491static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003492 int rc;
drh734c9862008-11-28 15:37:20 +00003493
3494 /* The following "ifdef/elif/else/" block has the same structure as
3495 ** the one below. It is replicated here solely to avoid cluttering
3496 ** up the real code with the UNUSED_PARAMETER() macros.
3497 */
3498#ifdef SQLITE_NO_SYNC
3499 UNUSED_PARAMETER(fd);
3500 UNUSED_PARAMETER(fullSync);
3501 UNUSED_PARAMETER(dataOnly);
3502#elif HAVE_FULLFSYNC
3503 UNUSED_PARAMETER(dataOnly);
3504#else
3505 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003506 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003507#endif
3508
3509 /* Record the number of times that we do a normal fsync() and
3510 ** FULLSYNC. This is used during testing to verify that this procedure
3511 ** gets called with the correct arguments.
3512 */
3513#ifdef SQLITE_TEST
3514 if( fullSync ) sqlite3_fullsync_count++;
3515 sqlite3_sync_count++;
3516#endif
3517
3518 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
drh2c8fd122015-12-02 02:33:36 +00003519 ** no-op. But go ahead and call fstat() to validate the file
3520 ** descriptor as we need a method to provoke a failure during
3521 ** coverate testing.
drh734c9862008-11-28 15:37:20 +00003522 */
3523#ifdef SQLITE_NO_SYNC
drh2c8fd122015-12-02 02:33:36 +00003524 {
3525 struct stat buf;
3526 rc = osFstat(fd, &buf);
3527 }
drh734c9862008-11-28 15:37:20 +00003528#elif HAVE_FULLFSYNC
3529 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003530 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003531 }else{
3532 rc = 1;
3533 }
3534 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003535 ** It shouldn't be possible for fullfsync to fail on the local
3536 ** file system (on OSX), so failure indicates that FULLFSYNC
3537 ** isn't supported for this file system. So, attempt an fsync
3538 ** and (for now) ignore the overhead of a superfluous fcntl call.
3539 ** It'd be better to detect fullfsync support once and avoid
3540 ** the fcntl call every time sync is called.
3541 */
drh734c9862008-11-28 15:37:20 +00003542 if( rc ) rc = fsync(fd);
3543
drh7ed97b92010-01-20 13:07:21 +00003544#elif defined(__APPLE__)
3545 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3546 ** so currently we default to the macro that redefines fdatasync to fsync
3547 */
3548 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003549#else
drh0b647ff2009-03-21 14:41:04 +00003550 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003551#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003552 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003553 rc = fsync(fd);
3554 }
drh0b647ff2009-03-21 14:41:04 +00003555#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003556#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3557
3558 if( OS_VXWORKS && rc!= -1 ){
3559 rc = 0;
3560 }
chw97185482008-11-17 08:05:31 +00003561 return rc;
drhbfe66312006-10-03 17:40:40 +00003562}
3563
drh734c9862008-11-28 15:37:20 +00003564/*
drh0059eae2011-08-08 23:48:40 +00003565** Open a file descriptor to the directory containing file zFilename.
3566** If successful, *pFd is set to the opened file descriptor and
3567** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3568** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3569** value.
3570**
drh90315a22011-08-10 01:52:12 +00003571** The directory file descriptor is used for only one thing - to
3572** fsync() a directory to make sure file creation and deletion events
3573** are flushed to disk. Such fsyncs are not needed on newer
3574** journaling filesystems, but are required on older filesystems.
3575**
3576** This routine can be overridden using the xSetSysCall interface.
3577** The ability to override this routine was added in support of the
3578** chromium sandbox. Opening a directory is a security risk (we are
3579** told) so making it overrideable allows the chromium sandbox to
3580** replace this routine with a harmless no-op. To make this routine
3581** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3582** *pFd set to a negative number.
3583**
drh0059eae2011-08-08 23:48:40 +00003584** If SQLITE_OK is returned, the caller is responsible for closing
3585** the file descriptor *pFd using close().
3586*/
3587static int openDirectory(const char *zFilename, int *pFd){
3588 int ii;
3589 int fd = -1;
3590 char zDirname[MAX_PATHNAME+1];
3591
3592 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drhdc278512015-12-07 18:18:33 +00003593 for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
3594 if( ii>0 ){
drh0059eae2011-08-08 23:48:40 +00003595 zDirname[ii] = '\0';
drhdc278512015-12-07 18:18:33 +00003596 }else{
3597 if( zDirname[0]!='/' ) zDirname[0] = '.';
3598 zDirname[1] = 0;
3599 }
3600 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3601 if( fd>=0 ){
3602 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
drh0059eae2011-08-08 23:48:40 +00003603 }
3604 *pFd = fd;
drhacb6b282015-11-26 10:37:05 +00003605 if( fd>=0 ) return SQLITE_OK;
3606 return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
drh0059eae2011-08-08 23:48:40 +00003607}
3608
3609/*
drh734c9862008-11-28 15:37:20 +00003610** Make sure all writes to a particular file are committed to disk.
3611**
3612** If dataOnly==0 then both the file itself and its metadata (file
3613** size, access time, etc) are synced. If dataOnly!=0 then only the
3614** file data is synced.
3615**
3616** Under Unix, also make sure that the directory entry for the file
3617** has been created by fsync-ing the directory that contains the file.
3618** If we do not do this and we encounter a power failure, the directory
3619** entry for the journal might not exist after we reboot. The next
3620** SQLite to access the file will not know that the journal exists (because
3621** the directory entry for the journal was never created) and the transaction
3622** will not roll back - possibly leading to database corruption.
3623*/
3624static int unixSync(sqlite3_file *id, int flags){
3625 int rc;
3626 unixFile *pFile = (unixFile*)id;
3627
3628 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3629 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3630
3631 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3632 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3633 || (flags&0x0F)==SQLITE_SYNC_FULL
3634 );
3635
3636 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3637 ** line is to test that doing so does not cause any problems.
3638 */
3639 SimulateDiskfullError( return SQLITE_FULL );
3640
3641 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003642 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003643 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3644 SimulateIOError( rc=1 );
3645 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003646 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003647 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003648 }
drh0059eae2011-08-08 23:48:40 +00003649
3650 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003651 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003652 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003653 */
3654 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3655 int dirfd;
3656 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003657 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003658 rc = osOpenDirectory(pFile->zPath, &dirfd);
drhacb6b282015-11-26 10:37:05 +00003659 if( rc==SQLITE_OK ){
drh0059eae2011-08-08 23:48:40 +00003660 full_fsync(dirfd, 0, 0);
3661 robust_close(pFile, dirfd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00003662 }else{
3663 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00003664 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003665 }
drh0059eae2011-08-08 23:48:40 +00003666 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003667 }
3668 return rc;
3669}
3670
3671/*
3672** Truncate an open file to a specified size
3673*/
3674static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003675 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003676 int rc;
dan6e09d692010-07-27 18:34:15 +00003677 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003678 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003679
3680 /* If the user has configured a chunk-size for this file, truncate the
3681 ** file so that it consists of an integer number of chunks (i.e. the
3682 ** actual file size after the operation may be larger than the requested
3683 ** size).
3684 */
drhb8af4b72012-04-05 20:04:39 +00003685 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003686 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3687 }
3688
dan2ee53412014-09-06 16:49:40 +00003689 rc = robust_ftruncate(pFile->h, nByte);
drh734c9862008-11-28 15:37:20 +00003690 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003691 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003692 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003693 }else{
drhd3d8c042012-05-29 17:02:40 +00003694#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003695 /* If we are doing a normal write to a database file (as opposed to
3696 ** doing a hot-journal rollback or a write to some file other than a
3697 ** normal database file) and we truncate the file to zero length,
3698 ** that effectively updates the change counter. This might happen
3699 ** when restoring a database using the backup API from a zero-length
3700 ** source.
3701 */
dan6e09d692010-07-27 18:34:15 +00003702 if( pFile->inNormalWrite && nByte==0 ){
3703 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003704 }
danf23da962013-03-23 21:00:41 +00003705#endif
danc0003312013-03-22 17:46:11 +00003706
mistachkine98844f2013-08-24 00:59:24 +00003707#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003708 /* If the file was just truncated to a size smaller than the currently
3709 ** mapped region, reduce the effective mapping size as well. SQLite will
3710 ** use read() and write() to access data beyond this point from now on.
3711 */
3712 if( nByte<pFile->mmapSize ){
3713 pFile->mmapSize = nByte;
3714 }
mistachkine98844f2013-08-24 00:59:24 +00003715#endif
drh3313b142009-11-06 04:13:18 +00003716
drh734c9862008-11-28 15:37:20 +00003717 return SQLITE_OK;
3718 }
3719}
3720
3721/*
3722** Determine the current size of a file in bytes
3723*/
3724static int unixFileSize(sqlite3_file *id, i64 *pSize){
3725 int rc;
3726 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003727 assert( id );
3728 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003729 SimulateIOError( rc=1 );
3730 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00003731 storeLastErrno((unixFile*)id, errno);
drh734c9862008-11-28 15:37:20 +00003732 return SQLITE_IOERR_FSTAT;
3733 }
3734 *pSize = buf.st_size;
3735
drh8af6c222010-05-14 12:43:01 +00003736 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003737 ** writes a single byte into that file in order to work around a bug
3738 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3739 ** layers, we need to report this file size as zero even though it is
3740 ** really 1. Ticket #3260.
3741 */
3742 if( *pSize==1 ) *pSize = 0;
3743
3744
3745 return SQLITE_OK;
3746}
3747
drhd2cb50b2009-01-09 21:41:17 +00003748#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003749/*
3750** Handler for proxy-locking file-control verbs. Defined below in the
3751** proxying locking division.
3752*/
3753static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003754#endif
drh715ff302008-12-03 22:32:44 +00003755
dan502019c2010-07-28 14:26:17 +00003756/*
3757** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003758** file-control operation. Enlarge the database to nBytes in size
3759** (rounded up to the next chunk-size). If the database is already
3760** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003761*/
3762static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003763 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003764 i64 nSize; /* Required file size */
3765 struct stat buf; /* Used to hold return values of fstat() */
3766
drh4bf66fd2015-02-19 02:43:02 +00003767 if( osFstat(pFile->h, &buf) ){
3768 return SQLITE_IOERR_FSTAT;
3769 }
dan502019c2010-07-28 14:26:17 +00003770
3771 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3772 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003773
dan502019c2010-07-28 14:26:17 +00003774#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003775 /* The code below is handling the return value of osFallocate()
3776 ** correctly. posix_fallocate() is defined to "returns zero on success,
3777 ** or an error number on failure". See the manpage for details. */
3778 int err;
drhff812312011-02-23 13:33:46 +00003779 do{
dan661d71a2011-03-30 19:08:03 +00003780 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3781 }while( err==EINTR );
3782 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003783#else
dan592bf7f2014-12-30 19:58:31 +00003784 /* If the OS does not have posix_fallocate(), fake it. Write a
3785 ** single byte to the last byte in each block that falls entirely
3786 ** within the extended region. Then, if required, a single byte
3787 ** at offset (nSize-1), to set the size of the file correctly.
3788 ** This is a similar technique to that used by glibc on systems
3789 ** that do not have a real fallocate() call.
dan502019c2010-07-28 14:26:17 +00003790 */
3791 int nBlk = buf.st_blksize; /* File-system block size */
danef3d66c2015-01-06 21:31:47 +00003792 int nWrite = 0; /* Number of bytes written by seekAndWrite */
dan502019c2010-07-28 14:26:17 +00003793 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003794
drh053378d2015-12-01 22:09:42 +00003795 iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
dan592bf7f2014-12-30 19:58:31 +00003796 assert( iWrite>=buf.st_size );
dan592bf7f2014-12-30 19:58:31 +00003797 assert( ((iWrite+1)%nBlk)==0 );
drh053378d2015-12-01 22:09:42 +00003798 for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
3799 if( iWrite>=nSize ) iWrite = nSize - 1;
danef3d66c2015-01-06 21:31:47 +00003800 nWrite = seekAndWrite(pFile, iWrite, "", 1);
dandc5df0f2011-04-06 19:15:45 +00003801 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dandc5df0f2011-04-06 19:15:45 +00003802 }
dan502019c2010-07-28 14:26:17 +00003803#endif
3804 }
3805 }
3806
mistachkine98844f2013-08-24 00:59:24 +00003807#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003808 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003809 int rc;
3810 if( pFile->szChunk<=0 ){
3811 if( robust_ftruncate(pFile->h, nByte) ){
drh4bf66fd2015-02-19 02:43:02 +00003812 storeLastErrno(pFile, errno);
danf23da962013-03-23 21:00:41 +00003813 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3814 }
3815 }
3816
3817 rc = unixMapfile(pFile, nByte);
3818 return rc;
3819 }
mistachkine98844f2013-08-24 00:59:24 +00003820#endif
danf23da962013-03-23 21:00:41 +00003821
dan502019c2010-07-28 14:26:17 +00003822 return SQLITE_OK;
3823}
danielk1977ad94b582007-08-20 06:44:22 +00003824
danielk1977e3026632004-06-22 11:29:02 +00003825/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003826** If *pArg is initially negative then this is a query. Set *pArg to
drhf12b3f62011-12-21 14:42:29 +00003827** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3828**
3829** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3830*/
3831static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3832 if( *pArg<0 ){
3833 *pArg = (pFile->ctrlFlags & mask)!=0;
3834 }else if( (*pArg)==0 ){
3835 pFile->ctrlFlags &= ~mask;
3836 }else{
3837 pFile->ctrlFlags |= mask;
3838 }
3839}
3840
drh696b33e2012-12-06 19:01:42 +00003841/* Forward declaration */
3842static int unixGetTempname(int nBuf, char *zBuf);
3843
drhf12b3f62011-12-21 14:42:29 +00003844/*
drh9e33c2c2007-08-31 18:34:59 +00003845** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003846*/
drhcc6bb3e2007-08-31 16:11:35 +00003847static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003848 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003849 switch( op ){
drhd76dba72017-07-22 16:00:34 +00003850#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
danefe16972017-07-20 19:49:14 +00003851 case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: {
3852 int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE);
drh344f7632017-07-28 13:18:35 +00003853 return rc ? SQLITE_IOERR_BEGIN_ATOMIC : SQLITE_OK;
danefe16972017-07-20 19:49:14 +00003854 }
3855 case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: {
3856 int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE);
drh344f7632017-07-28 13:18:35 +00003857 return rc ? SQLITE_IOERR_COMMIT_ATOMIC : SQLITE_OK;
danefe16972017-07-20 19:49:14 +00003858 }
3859 case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: {
3860 int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE);
drh344f7632017-07-28 13:18:35 +00003861 return rc ? SQLITE_IOERR_ROLLBACK_ATOMIC : SQLITE_OK;
danefe16972017-07-20 19:49:14 +00003862 }
drhd76dba72017-07-22 16:00:34 +00003863#endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
danefe16972017-07-20 19:49:14 +00003864
drh9e33c2c2007-08-31 18:34:59 +00003865 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003866 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003867 return SQLITE_OK;
3868 }
drh4bf66fd2015-02-19 02:43:02 +00003869 case SQLITE_FCNTL_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003870 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003871 return SQLITE_OK;
3872 }
dan6e09d692010-07-27 18:34:15 +00003873 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003874 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003875 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003876 }
drh9ff27ec2010-05-19 19:26:05 +00003877 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003878 int rc;
3879 SimulateIOErrorBenign(1);
3880 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3881 SimulateIOErrorBenign(0);
3882 return rc;
drhf0b190d2011-07-26 16:03:07 +00003883 }
3884 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003885 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3886 return SQLITE_OK;
3887 }
drhcb15f352011-12-23 01:04:17 +00003888 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3889 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003890 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003891 }
drhde60fc22011-12-14 17:53:36 +00003892 case SQLITE_FCNTL_VFSNAME: {
3893 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3894 return SQLITE_OK;
3895 }
drh696b33e2012-12-06 19:01:42 +00003896 case SQLITE_FCNTL_TEMPFILENAME: {
drhf3cdcdc2015-04-29 16:50:28 +00003897 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
drh696b33e2012-12-06 19:01:42 +00003898 if( zTFile ){
3899 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3900 *(char**)pArg = zTFile;
3901 }
3902 return SQLITE_OK;
3903 }
drhb959a012013-12-07 12:29:22 +00003904 case SQLITE_FCNTL_HAS_MOVED: {
3905 *(int*)pArg = fileHasMoved(pFile);
3906 return SQLITE_OK;
3907 }
drhf0119b22018-03-26 17:40:53 +00003908#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
3909 case SQLITE_FCNTL_LOCK_TIMEOUT: {
3910 pFile->iBusyTimeout = *(int*)pArg;
3911 return SQLITE_OK;
3912 }
3913#endif
mistachkine98844f2013-08-24 00:59:24 +00003914#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003915 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003916 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003917 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003918 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3919 newLimit = sqlite3GlobalConfig.mxMmap;
3920 }
dan43c1e622017-08-07 18:13:28 +00003921
3922 /* The value of newLimit may be eventually cast to (size_t) and passed
mistachkine35395a2017-08-07 19:06:54 +00003923 ** to mmap(). Restrict its value to 2GB if (size_t) is not at least a
3924 ** 64-bit type. */
dan089df502017-08-07 18:54:10 +00003925 if( newLimit>0 && sizeof(size_t)<8 ){
dan43c1e622017-08-07 18:13:28 +00003926 newLimit = (newLimit & 0x7FFFFFFF);
3927 }
3928
drh9b4c59f2013-04-15 17:03:42 +00003929 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003930 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003931 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003932 if( pFile->mmapSize>0 ){
3933 unixUnmapfile(pFile);
3934 rc = unixMapfile(pFile, -1);
3935 }
danbcb8a862013-04-08 15:30:41 +00003936 }
drh34e258c2013-05-23 01:40:53 +00003937 return rc;
danb2d3de32013-03-14 18:34:37 +00003938 }
mistachkine98844f2013-08-24 00:59:24 +00003939#endif
drhd3d8c042012-05-29 17:02:40 +00003940#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003941 /* The pager calls this method to signal that it has done
3942 ** a rollback and that the database is therefore unchanged and
3943 ** it hence it is OK for the transaction change counter to be
3944 ** unchanged.
3945 */
3946 case SQLITE_FCNTL_DB_UNCHANGED: {
3947 ((unixFile*)id)->dbUpdate = 0;
3948 return SQLITE_OK;
3949 }
3950#endif
drhd2cb50b2009-01-09 21:41:17 +00003951#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh4bf66fd2015-02-19 02:43:02 +00003952 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
3953 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003954 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003955 }
drhd2cb50b2009-01-09 21:41:17 +00003956#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003957 }
drh0b52b7d2011-01-26 19:46:22 +00003958 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003959}
3960
3961/*
danefe16972017-07-20 19:49:14 +00003962** If pFd->sectorSize is non-zero when this function is called, it is a
3963** no-op. Otherwise, the values of pFd->sectorSize and
3964** pFd->deviceCharacteristics are set according to the file-system
3965** characteristics.
danielk1977a3d4c882007-03-23 10:08:38 +00003966**
danefe16972017-07-20 19:49:14 +00003967** There are two versions of this function. One for QNX and one for all
3968** other systems.
danielk1977a3d4c882007-03-23 10:08:38 +00003969*/
danefe16972017-07-20 19:49:14 +00003970#ifndef __QNXNTO__
3971static void setDeviceCharacteristics(unixFile *pFd){
drhd76dba72017-07-22 16:00:34 +00003972 assert( pFd->deviceCharacteristics==0 || pFd->sectorSize!=0 );
danefe16972017-07-20 19:49:14 +00003973 if( pFd->sectorSize==0 ){
drhd76dba72017-07-22 16:00:34 +00003974#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
danefe16972017-07-20 19:49:14 +00003975 int res;
dan9d709542017-07-21 21:06:24 +00003976 u32 f = 0;
drh537dddf2012-10-26 13:46:24 +00003977
danefe16972017-07-20 19:49:14 +00003978 /* Check for support for F2FS atomic batch writes. */
dan9d709542017-07-21 21:06:24 +00003979 res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES, &f);
3980 if( res==0 && (f & F2FS_FEATURE_ATOMIC_WRITE) ){
dan77b4f522017-07-27 18:34:00 +00003981 pFd->deviceCharacteristics = SQLITE_IOCAP_BATCH_ATOMIC;
danefe16972017-07-20 19:49:14 +00003982 }
drhd76dba72017-07-22 16:00:34 +00003983#endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
danefe16972017-07-20 19:49:14 +00003984
3985 /* Set the POWERSAFE_OVERWRITE flag if requested. */
3986 if( pFd->ctrlFlags & UNIXFILE_PSOW ){
3987 pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
3988 }
3989
3990 pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3991 }
3992}
3993#else
drh537dddf2012-10-26 13:46:24 +00003994#include <sys/dcmd_blk.h>
3995#include <sys/statvfs.h>
danefe16972017-07-20 19:49:14 +00003996static void setDeviceCharacteristics(unixFile *pFile){
drh537dddf2012-10-26 13:46:24 +00003997 if( pFile->sectorSize == 0 ){
3998 struct statvfs fsInfo;
3999
4000 /* Set defaults for non-supported filesystems */
4001 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4002 pFile->deviceCharacteristics = 0;
4003 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
drha9be5082018-01-15 14:32:37 +00004004 return;
drh537dddf2012-10-26 13:46:24 +00004005 }
4006
4007 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
4008 pFile->sectorSize = fsInfo.f_bsize;
4009 pFile->deviceCharacteristics =
4010 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
4011 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4012 ** the write succeeds */
4013 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4014 ** so it is ordered */
4015 0;
4016 }else if( strstr(fsInfo.f_basetype, "etfs") ){
4017 pFile->sectorSize = fsInfo.f_bsize;
4018 pFile->deviceCharacteristics =
4019 /* etfs cluster size writes are atomic */
4020 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
4021 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4022 ** the write succeeds */
4023 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4024 ** so it is ordered */
4025 0;
4026 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
4027 pFile->sectorSize = fsInfo.f_bsize;
4028 pFile->deviceCharacteristics =
4029 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
4030 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4031 ** the write succeeds */
4032 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4033 ** so it is ordered */
4034 0;
4035 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
4036 pFile->sectorSize = fsInfo.f_bsize;
4037 pFile->deviceCharacteristics =
4038 /* full bitset of atomics from max sector size and smaller */
4039 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
4040 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4041 ** so it is ordered */
4042 0;
4043 }else if( strstr(fsInfo.f_basetype, "dos") ){
4044 pFile->sectorSize = fsInfo.f_bsize;
4045 pFile->deviceCharacteristics =
4046 /* full bitset of atomics from max sector size and smaller */
4047 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
4048 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4049 ** so it is ordered */
4050 0;
4051 }else{
4052 pFile->deviceCharacteristics =
4053 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
4054 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4055 ** the write succeeds */
4056 0;
4057 }
4058 }
4059 /* Last chance verification. If the sector size isn't a multiple of 512
4060 ** then it isn't valid.*/
4061 if( pFile->sectorSize % 512 != 0 ){
4062 pFile->deviceCharacteristics = 0;
4063 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4064 }
drh537dddf2012-10-26 13:46:24 +00004065}
danefe16972017-07-20 19:49:14 +00004066#endif
4067
4068/*
4069** Return the sector size in bytes of the underlying block device for
4070** the specified file. This is almost always 512 bytes, but may be
4071** larger for some devices.
4072**
4073** SQLite code assumes this function cannot fail. It also assumes that
4074** if two files are created in the same file-system directory (i.e.
4075** a database and its journal file) that the sector size will be the
4076** same for both.
4077*/
4078static int unixSectorSize(sqlite3_file *id){
4079 unixFile *pFd = (unixFile*)id;
4080 setDeviceCharacteristics(pFd);
4081 return pFd->sectorSize;
4082}
danielk1977a3d4c882007-03-23 10:08:38 +00004083
danielk197790949c22007-08-17 16:50:38 +00004084/*
drhf12b3f62011-12-21 14:42:29 +00004085** Return the device characteristics for the file.
4086**
drhcb15f352011-12-23 01:04:17 +00004087** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
peter.d.reid60ec9142014-09-06 16:39:46 +00004088** However, that choice is controversial since technically the underlying
drhcb15f352011-12-23 01:04:17 +00004089** file system does not always provide powersafe overwrites. (In other
4090** words, after a power-loss event, parts of the file that were never
4091** written might end up being altered.) However, non-PSOW behavior is very,
4092** very rare. And asserting PSOW makes a large reduction in the amount
4093** of required I/O for journaling, since a lot of padding is eliminated.
4094** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
4095** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00004096*/
drhf12b3f62011-12-21 14:42:29 +00004097static int unixDeviceCharacteristics(sqlite3_file *id){
danefe16972017-07-20 19:49:14 +00004098 unixFile *pFd = (unixFile*)id;
4099 setDeviceCharacteristics(pFd);
4100 return pFd->deviceCharacteristics;
danielk197762079062007-08-15 17:08:46 +00004101}
4102
dan702eec12014-06-23 10:04:58 +00004103#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00004104
dan702eec12014-06-23 10:04:58 +00004105/*
4106** Return the system page size.
4107**
4108** This function should not be called directly by other code in this file.
4109** Instead, it should be called via macro osGetpagesize().
4110*/
4111static int unixGetpagesize(void){
drh8cd5b252015-03-02 22:06:43 +00004112#if OS_VXWORKS
4113 return 1024;
4114#elif defined(_BSD_SOURCE)
dan702eec12014-06-23 10:04:58 +00004115 return getpagesize();
4116#else
4117 return (int)sysconf(_SC_PAGESIZE);
4118#endif
4119}
4120
4121#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
4122
4123#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00004124
4125/*
drhd91c68f2010-05-14 14:52:25 +00004126** Object used to represent an shared memory buffer.
4127**
4128** When multiple threads all reference the same wal-index, each thread
4129** has its own unixShm object, but they all point to a single instance
4130** of this unixShmNode object. In other words, each wal-index is opened
4131** only once per process.
4132**
4133** Each unixShmNode object is connected to a single unixInodeInfo object.
4134** We could coalesce this object into unixInodeInfo, but that would mean
4135** every open file that does not use shared memory (in other words, most
4136** open files) would have to carry around this extra information. So
4137** the unixInodeInfo object contains a pointer to this unixShmNode object
4138** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00004139**
4140** unixMutexHeld() must be true when creating or destroying
4141** this object or while reading or writing the following fields:
4142**
4143** nRef
drhd9e5c4f2010-05-12 18:01:39 +00004144**
4145** The following fields are read-only after the object is created:
4146**
4147** fid
4148** zFilename
4149**
drhd91c68f2010-05-14 14:52:25 +00004150** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00004151** unixMutexHeld() is true when reading or writing any other field
4152** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00004153*/
drhd91c68f2010-05-14 14:52:25 +00004154struct unixShmNode {
4155 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00004156 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00004157 char *zFilename; /* Name of the mmapped file */
4158 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00004159 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00004160 u16 nRegion; /* Size of array apRegion */
4161 u8 isReadonly; /* True if read-only */
dan92c02da2017-11-01 20:59:28 +00004162 u8 isUnlocked; /* True if no DMS lock held */
dan18801912010-06-14 14:07:50 +00004163 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00004164 int nRef; /* Number of unixShm objects pointing to this */
4165 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00004166#ifdef SQLITE_DEBUG
4167 u8 exclMask; /* Mask of exclusive locks held */
4168 u8 sharedMask; /* Mask of shared locks held */
4169 u8 nextShmId; /* Next available unixShm.id value */
4170#endif
4171};
4172
4173/*
drhd9e5c4f2010-05-12 18:01:39 +00004174** Structure used internally by this VFS to record the state of an
4175** open shared memory connection.
4176**
drhd91c68f2010-05-14 14:52:25 +00004177** The following fields are initialized when this object is created and
4178** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004179**
drhd91c68f2010-05-14 14:52:25 +00004180** unixShm.pFile
4181** unixShm.id
4182**
4183** All other fields are read/write. The unixShm.pFile->mutex must be held
4184** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004185*/
4186struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004187 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4188 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004189 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004190 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004191 u16 sharedMask; /* Mask of shared locks held */
4192 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004193};
4194
4195/*
drhd9e5c4f2010-05-12 18:01:39 +00004196** Constants used for locking
4197*/
drhbd9676c2010-06-23 17:58:38 +00004198#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004199#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004200
drhd9e5c4f2010-05-12 18:01:39 +00004201/*
drh73b64e42010-05-30 19:55:15 +00004202** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004203**
4204** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4205** otherwise.
4206*/
4207static int unixShmSystemLock(
drhbbf76ee2015-03-10 20:22:35 +00004208 unixFile *pFile, /* Open connection to the WAL file */
drhd91c68f2010-05-14 14:52:25 +00004209 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004210 int ofst, /* First byte of the locking range */
4211 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004212){
drhbbf76ee2015-03-10 20:22:35 +00004213 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4214 struct flock f; /* The posix advisory locking structure */
4215 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004216
drhd91c68f2010-05-14 14:52:25 +00004217 /* Access to the unixShmNode object is serialized by the caller */
drhbbf76ee2015-03-10 20:22:35 +00004218 pShmNode = pFile->pInode->pShmNode;
drh37874b52017-12-13 10:11:09 +00004219 assert( pShmNode->nRef==0 || sqlite3_mutex_held(pShmNode->mutex) );
drhd9e5c4f2010-05-12 18:01:39 +00004220
dan9181ae92017-10-26 17:05:22 +00004221 /* Shared locks never span more than one byte */
4222 assert( n==1 || lockType!=F_RDLCK );
4223
4224 /* Locks are within range */
4225 assert( n>=1 && n<=SQLITE_SHM_NLOCK );
4226
drh3cb93392011-03-12 18:10:44 +00004227 if( pShmNode->h>=0 ){
4228 /* Initialize the locking parameters */
drh3cb93392011-03-12 18:10:44 +00004229 f.l_type = lockType;
4230 f.l_whence = SEEK_SET;
4231 f.l_start = ofst;
4232 f.l_len = n;
drhf0119b22018-03-26 17:40:53 +00004233 rc = osSetPosixAdvisoryLock(pShmNode->h, &f, pFile);
drh3cb93392011-03-12 18:10:44 +00004234 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4235 }
drhd9e5c4f2010-05-12 18:01:39 +00004236
4237 /* Update the global lock state and do debug tracing */
4238#ifdef SQLITE_DEBUG
dan9181ae92017-10-26 17:05:22 +00004239 { u16 mask;
4240 OSTRACE(("SHM-LOCK "));
4241 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
4242 if( rc==SQLITE_OK ){
4243 if( lockType==F_UNLCK ){
4244 OSTRACE(("unlock %d ok", ofst));
4245 pShmNode->exclMask &= ~mask;
4246 pShmNode->sharedMask &= ~mask;
4247 }else if( lockType==F_RDLCK ){
4248 OSTRACE(("read-lock %d ok", ofst));
4249 pShmNode->exclMask &= ~mask;
4250 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004251 }else{
dan9181ae92017-10-26 17:05:22 +00004252 assert( lockType==F_WRLCK );
4253 OSTRACE(("write-lock %d ok", ofst));
4254 pShmNode->exclMask |= mask;
4255 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004256 }
dan9181ae92017-10-26 17:05:22 +00004257 }else{
4258 if( lockType==F_UNLCK ){
4259 OSTRACE(("unlock %d failed", ofst));
4260 }else if( lockType==F_RDLCK ){
4261 OSTRACE(("read-lock failed"));
4262 }else{
4263 assert( lockType==F_WRLCK );
4264 OSTRACE(("write-lock %d failed", ofst));
4265 }
4266 }
4267 OSTRACE((" - afterwards %03x,%03x\n",
4268 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004269 }
drhd9e5c4f2010-05-12 18:01:39 +00004270#endif
4271
4272 return rc;
4273}
4274
dan781e34c2014-03-20 08:59:47 +00004275/*
dan781e34c2014-03-20 08:59:47 +00004276** Return the minimum number of 32KB shm regions that should be mapped at
4277** a time, assuming that each mapping must be an integer multiple of the
4278** current system page-size.
4279**
4280** Usually, this is 1. The exception seems to be systems that are configured
4281** to use 64KB pages - in this case each mapping must cover at least two
4282** shm regions.
4283*/
4284static int unixShmRegionPerMap(void){
4285 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004286 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004287 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4288 if( pgsz<shmsz ) return 1;
4289 return pgsz/shmsz;
4290}
drhd9e5c4f2010-05-12 18:01:39 +00004291
4292/*
drhd91c68f2010-05-14 14:52:25 +00004293** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004294**
4295** This is not a VFS shared-memory method; it is a utility function called
4296** by VFS shared-memory methods.
4297*/
drhd91c68f2010-05-14 14:52:25 +00004298static void unixShmPurge(unixFile *pFd){
4299 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004300 assert( unixMutexHeld() );
drhf3b1ed02015-12-02 13:11:03 +00004301 if( p && ALWAYS(p->nRef==0) ){
dan781e34c2014-03-20 08:59:47 +00004302 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004303 int i;
drhd91c68f2010-05-14 14:52:25 +00004304 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004305 sqlite3_mutex_free(p->mutex);
dan781e34c2014-03-20 08:59:47 +00004306 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh3cb93392011-03-12 18:10:44 +00004307 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004308 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004309 }else{
4310 sqlite3_free(p->apRegion[i]);
4311 }
dan13a3cb82010-06-11 19:04:21 +00004312 }
dan18801912010-06-14 14:07:50 +00004313 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004314 if( p->h>=0 ){
4315 robust_close(pFd, p->h, __LINE__);
4316 p->h = -1;
4317 }
drhd91c68f2010-05-14 14:52:25 +00004318 p->pInode->pShmNode = 0;
4319 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004320 }
4321}
4322
4323/*
dan92c02da2017-11-01 20:59:28 +00004324** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
4325** take it now. Return SQLITE_OK if successful, or an SQLite error
4326** code otherwise.
4327**
4328** If the DMS cannot be locked because this is a readonly_shm=1
4329** connection and no other process already holds a lock, return
drh7e45e3a2017-11-08 17:32:12 +00004330** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
dan92c02da2017-11-01 20:59:28 +00004331*/
4332static int unixLockSharedMemory(unixFile *pDbFd, unixShmNode *pShmNode){
4333 struct flock lock;
4334 int rc = SQLITE_OK;
4335
4336 /* Use F_GETLK to determine the locks other processes are holding
4337 ** on the DMS byte. If it indicates that another process is holding
4338 ** a SHARED lock, then this process may also take a SHARED lock
4339 ** and proceed with opening the *-shm file.
4340 **
4341 ** Or, if no other process is holding any lock, then this process
4342 ** is the first to open it. In this case take an EXCLUSIVE lock on the
4343 ** DMS byte and truncate the *-shm file to zero bytes in size. Then
4344 ** downgrade to a SHARED lock on the DMS byte.
4345 **
4346 ** If another process is holding an EXCLUSIVE lock on the DMS byte,
4347 ** return SQLITE_BUSY to the caller (it will try again). An earlier
4348 ** version of this code attempted the SHARED lock at this point. But
4349 ** this introduced a subtle race condition: if the process holding
4350 ** EXCLUSIVE failed just before truncating the *-shm file, then this
4351 ** process might open and use the *-shm file without truncating it.
4352 ** And if the *-shm file has been corrupted by a power failure or
4353 ** system crash, the database itself may also become corrupt. */
4354 lock.l_whence = SEEK_SET;
4355 lock.l_start = UNIX_SHM_DMS;
4356 lock.l_len = 1;
4357 lock.l_type = F_WRLCK;
4358 if( osFcntl(pShmNode->h, F_GETLK, &lock)!=0 ) {
4359 rc = SQLITE_IOERR_LOCK;
4360 }else if( lock.l_type==F_UNLCK ){
4361 if( pShmNode->isReadonly ){
4362 pShmNode->isUnlocked = 1;
drh7e45e3a2017-11-08 17:32:12 +00004363 rc = SQLITE_READONLY_CANTINIT;
dan92c02da2017-11-01 20:59:28 +00004364 }else{
4365 rc = unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1);
4366 if( rc==SQLITE_OK && robust_ftruncate(pShmNode->h, 0) ){
4367 rc = unixLogError(SQLITE_IOERR_SHMOPEN,"ftruncate",pShmNode->zFilename);
4368 }
4369 }
4370 }else if( lock.l_type==F_WRLCK ){
4371 rc = SQLITE_BUSY;
4372 }
4373
4374 if( rc==SQLITE_OK ){
4375 assert( lock.l_type==F_UNLCK || lock.l_type==F_RDLCK );
4376 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
4377 }
4378 return rc;
4379}
4380
4381/*
danda9fe0c2010-07-13 18:44:03 +00004382** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004383** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004384**
drh7234c6d2010-06-19 15:10:09 +00004385** The file used to implement shared-memory is in the same directory
4386** as the open database file and has the same name as the open database
4387** file with the "-shm" suffix added. For example, if the database file
4388** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004389** for shared memory will be called "/home/user1/config.db-shm".
4390**
4391** Another approach to is to use files in /dev/shm or /dev/tmp or an
4392** some other tmpfs mount. But if a file in a different directory
4393** from the database file is used, then differing access permissions
4394** or a chroot() might cause two different processes on the same
4395** database to end up using different files for shared memory -
4396** meaning that their memory would not really be shared - resulting
4397** in database corruption. Nevertheless, this tmpfs file usage
4398** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4399** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4400** option results in an incompatible build of SQLite; builds of SQLite
4401** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4402** same database file at the same time, database corruption will likely
4403** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4404** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004405**
4406** When opening a new shared-memory file, if no other instances of that
4407** file are currently open, in this process or in other processes, then
4408** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004409**
4410** If the original database file (pDbFd) is using the "unix-excl" VFS
4411** that means that an exclusive lock is held on the database file and
4412** that no other processes are able to read or write the database. In
4413** that case, we do not really need shared memory. No shared memory
4414** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004415*/
danda9fe0c2010-07-13 18:44:03 +00004416static int unixOpenSharedMemory(unixFile *pDbFd){
4417 struct unixShm *p = 0; /* The connection to be opened */
4418 struct unixShmNode *pShmNode; /* The underlying mmapped file */
dan92c02da2017-11-01 20:59:28 +00004419 int rc = SQLITE_OK; /* Result code */
danda9fe0c2010-07-13 18:44:03 +00004420 unixInodeInfo *pInode; /* The inode of fd */
danf12ba662017-11-07 15:43:52 +00004421 char *zShm; /* Name of the file used for SHM */
danda9fe0c2010-07-13 18:44:03 +00004422 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004423
danda9fe0c2010-07-13 18:44:03 +00004424 /* Allocate space for the new unixShm object. */
drhf3cdcdc2015-04-29 16:50:28 +00004425 p = sqlite3_malloc64( sizeof(*p) );
mistachkinfad30392016-02-13 23:43:46 +00004426 if( p==0 ) return SQLITE_NOMEM_BKPT;
drhd9e5c4f2010-05-12 18:01:39 +00004427 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004428 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004429
danda9fe0c2010-07-13 18:44:03 +00004430 /* Check to see if a unixShmNode object already exists. Reuse an existing
4431 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004432 */
4433 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004434 pInode = pDbFd->pInode;
4435 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004436 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004437 struct stat sStat; /* fstat() info for database file */
drh4bf66fd2015-02-19 02:43:02 +00004438#ifndef SQLITE_SHM_DIRECTORY
4439 const char *zBasePath = pDbFd->zPath;
4440#endif
danddb0ac42010-07-14 14:48:58 +00004441
4442 /* Call fstat() to figure out the permissions on the database file. If
4443 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004444 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004445 */
drhf3b1ed02015-12-02 13:11:03 +00004446 if( osFstat(pDbFd->h, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004447 rc = SQLITE_IOERR_FSTAT;
4448 goto shm_open_err;
4449 }
4450
drha4ced192010-07-15 18:32:40 +00004451#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004452 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004453#else
drh4bf66fd2015-02-19 02:43:02 +00004454 nShmFilename = 6 + (int)strlen(zBasePath);
drha4ced192010-07-15 18:32:40 +00004455#endif
drhf3cdcdc2015-04-29 16:50:28 +00004456 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004457 if( pShmNode==0 ){
mistachkinfad30392016-02-13 23:43:46 +00004458 rc = SQLITE_NOMEM_BKPT;
drhd9e5c4f2010-05-12 18:01:39 +00004459 goto shm_open_err;
4460 }
drh9cb5a0d2012-01-05 21:19:54 +00004461 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
danf12ba662017-11-07 15:43:52 +00004462 zShm = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004463#ifdef SQLITE_SHM_DIRECTORY
danf12ba662017-11-07 15:43:52 +00004464 sqlite3_snprintf(nShmFilename, zShm,
drha4ced192010-07-15 18:32:40 +00004465 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4466 (u32)sStat.st_ino, (u32)sStat.st_dev);
4467#else
danf12ba662017-11-07 15:43:52 +00004468 sqlite3_snprintf(nShmFilename, zShm, "%s-shm", zBasePath);
4469 sqlite3FileSuffix3(pDbFd->zPath, zShm);
drha4ced192010-07-15 18:32:40 +00004470#endif
drhd91c68f2010-05-14 14:52:25 +00004471 pShmNode->h = -1;
4472 pDbFd->pInode->pShmNode = pShmNode;
4473 pShmNode->pInode = pDbFd->pInode;
drh97a7e5e2016-04-26 18:58:54 +00004474 if( sqlite3GlobalConfig.bCoreMutex ){
4475 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4476 if( pShmNode->mutex==0 ){
4477 rc = SQLITE_NOMEM_BKPT;
4478 goto shm_open_err;
4479 }
drhd91c68f2010-05-14 14:52:25 +00004480 }
drhd9e5c4f2010-05-12 18:01:39 +00004481
drh3cb93392011-03-12 18:10:44 +00004482 if( pInode->bProcessLock==0 ){
danf12ba662017-11-07 15:43:52 +00004483 if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
4484 pShmNode->h = robust_open(zShm, O_RDWR|O_CREAT, (sStat.st_mode&0777));
drh3ec4a0c2011-10-11 18:18:54 +00004485 }
drh3cb93392011-03-12 18:10:44 +00004486 if( pShmNode->h<0 ){
danf12ba662017-11-07 15:43:52 +00004487 pShmNode->h = robust_open(zShm, O_RDONLY, (sStat.st_mode&0777));
4488 if( pShmNode->h<0 ){
4489 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShm);
4490 goto shm_open_err;
4491 }
4492 pShmNode->isReadonly = 1;
drhd9e5c4f2010-05-12 18:01:39 +00004493 }
drhac7c3ac2012-02-11 19:23:48 +00004494
4495 /* If this process is running as root, make sure that the SHM file
4496 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004497 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004498 */
drh6226ca22015-11-24 15:06:28 +00004499 robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
dan176b2a92017-11-01 06:59:19 +00004500
dan92c02da2017-11-01 20:59:28 +00004501 rc = unixLockSharedMemory(pDbFd, pShmNode);
drh7e45e3a2017-11-08 17:32:12 +00004502 if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004503 }
drhd9e5c4f2010-05-12 18:01:39 +00004504 }
4505
drhd91c68f2010-05-14 14:52:25 +00004506 /* Make the new connection a child of the unixShmNode */
4507 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004508#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004509 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004510#endif
drhd91c68f2010-05-14 14:52:25 +00004511 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004512 pDbFd->pShm = p;
4513 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004514
4515 /* The reference count on pShmNode has already been incremented under
4516 ** the cover of the unixEnterMutex() mutex and the pointer from the
4517 ** new (struct unixShm) object to the pShmNode has been set. All that is
4518 ** left to do is to link the new object into the linked list starting
4519 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4520 ** mutex.
4521 */
4522 sqlite3_mutex_enter(pShmNode->mutex);
4523 p->pNext = pShmNode->pFirst;
4524 pShmNode->pFirst = p;
4525 sqlite3_mutex_leave(pShmNode->mutex);
dan92c02da2017-11-01 20:59:28 +00004526 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004527
4528 /* Jump here on any error */
4529shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004530 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004531 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004532 unixLeaveMutex();
4533 return rc;
4534}
4535
4536/*
danda9fe0c2010-07-13 18:44:03 +00004537** This function is called to obtain a pointer to region iRegion of the
4538** shared-memory associated with the database file fd. Shared-memory regions
4539** are numbered starting from zero. Each shared-memory region is szRegion
4540** bytes in size.
4541**
4542** If an error occurs, an error code is returned and *pp is set to NULL.
4543**
4544** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4545** region has not been allocated (by any client, including one running in a
4546** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4547** bExtend is non-zero and the requested shared-memory region has not yet
4548** been allocated, it is allocated by this function.
4549**
4550** If the shared-memory region has already been allocated or is allocated by
4551** this call as described above, then it is mapped into this processes
4552** address space (if it is not already), *pp is set to point to the mapped
4553** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004554*/
danda9fe0c2010-07-13 18:44:03 +00004555static int unixShmMap(
4556 sqlite3_file *fd, /* Handle open on database file */
4557 int iRegion, /* Region to retrieve */
4558 int szRegion, /* Size of regions */
4559 int bExtend, /* True to extend file if necessary */
4560 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004561){
danda9fe0c2010-07-13 18:44:03 +00004562 unixFile *pDbFd = (unixFile*)fd;
4563 unixShm *p;
4564 unixShmNode *pShmNode;
4565 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004566 int nShmPerMap = unixShmRegionPerMap();
4567 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004568
danda9fe0c2010-07-13 18:44:03 +00004569 /* If the shared-memory file has not yet been opened, open it now. */
4570 if( pDbFd->pShm==0 ){
4571 rc = unixOpenSharedMemory(pDbFd);
4572 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004573 }
drhd9e5c4f2010-05-12 18:01:39 +00004574
danda9fe0c2010-07-13 18:44:03 +00004575 p = pDbFd->pShm;
4576 pShmNode = p->pShmNode;
4577 sqlite3_mutex_enter(pShmNode->mutex);
dan92c02da2017-11-01 20:59:28 +00004578 if( pShmNode->isUnlocked ){
4579 rc = unixLockSharedMemory(pDbFd, pShmNode);
4580 if( rc!=SQLITE_OK ) goto shmpage_out;
4581 pShmNode->isUnlocked = 0;
4582 }
danda9fe0c2010-07-13 18:44:03 +00004583 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004584 assert( pShmNode->pInode==pDbFd->pInode );
4585 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4586 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004587
dan781e34c2014-03-20 08:59:47 +00004588 /* Minimum number of regions required to be mapped. */
4589 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4590
4591 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004592 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004593 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004594 struct stat sStat; /* Used by fstat() */
4595
4596 pShmNode->szRegion = szRegion;
4597
drh3cb93392011-03-12 18:10:44 +00004598 if( pShmNode->h>=0 ){
4599 /* The requested region is not mapped into this processes address space.
4600 ** Check to see if it has been allocated (i.e. if the wal-index file is
4601 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004602 */
drh3cb93392011-03-12 18:10:44 +00004603 if( osFstat(pShmNode->h, &sStat) ){
4604 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004605 goto shmpage_out;
4606 }
drh3cb93392011-03-12 18:10:44 +00004607
4608 if( sStat.st_size<nByte ){
4609 /* The requested memory region does not exist. If bExtend is set to
4610 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004611 */
dan47a2b4a2013-04-26 16:09:29 +00004612 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004613 goto shmpage_out;
4614 }
dan47a2b4a2013-04-26 16:09:29 +00004615
4616 /* Alternatively, if bExtend is true, extend the file. Do this by
4617 ** writing a single byte to the end of each (OS) page being
4618 ** allocated or extended. Technically, we need only write to the
4619 ** last page in order to extend the file. But writing to all new
4620 ** pages forces the OS to allocate them immediately, which reduces
4621 ** the chances of SIGBUS while accessing the mapped region later on.
4622 */
4623 else{
4624 static const int pgsz = 4096;
4625 int iPg;
4626
4627 /* Write to the last byte of each newly allocated or extended page */
4628 assert( (nByte % pgsz)==0 );
4629 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
drhe1818ec2015-12-01 16:21:35 +00004630 int x = 0;
4631 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
dan47a2b4a2013-04-26 16:09:29 +00004632 const char *zFile = pShmNode->zFilename;
4633 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4634 goto shmpage_out;
4635 }
4636 }
drh3cb93392011-03-12 18:10:44 +00004637 }
4638 }
danda9fe0c2010-07-13 18:44:03 +00004639 }
4640
4641 /* Map the requested memory region into this processes address space. */
4642 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004643 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004644 );
4645 if( !apNew ){
mistachkinfad30392016-02-13 23:43:46 +00004646 rc = SQLITE_IOERR_NOMEM_BKPT;
danda9fe0c2010-07-13 18:44:03 +00004647 goto shmpage_out;
4648 }
4649 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004650 while( pShmNode->nRegion<nReqRegion ){
4651 int nMap = szRegion*nShmPerMap;
4652 int i;
drh3cb93392011-03-12 18:10:44 +00004653 void *pMem;
4654 if( pShmNode->h>=0 ){
dan781e34c2014-03-20 08:59:47 +00004655 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004656 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004657 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004658 );
4659 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004660 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004661 goto shmpage_out;
4662 }
4663 }else{
drhf3cdcdc2015-04-29 16:50:28 +00004664 pMem = sqlite3_malloc64(szRegion);
drh3cb93392011-03-12 18:10:44 +00004665 if( pMem==0 ){
mistachkinfad30392016-02-13 23:43:46 +00004666 rc = SQLITE_NOMEM_BKPT;
drh3cb93392011-03-12 18:10:44 +00004667 goto shmpage_out;
4668 }
4669 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004670 }
dan781e34c2014-03-20 08:59:47 +00004671
4672 for(i=0; i<nShmPerMap; i++){
4673 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4674 }
4675 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004676 }
4677 }
4678
4679shmpage_out:
4680 if( pShmNode->nRegion>iRegion ){
4681 *pp = pShmNode->apRegion[iRegion];
4682 }else{
4683 *pp = 0;
4684 }
drh66dfec8b2011-06-01 20:01:49 +00004685 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004686 sqlite3_mutex_leave(pShmNode->mutex);
4687 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004688}
4689
4690/*
drhd9e5c4f2010-05-12 18:01:39 +00004691** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004692**
4693** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4694** different here than in posix. In xShmLock(), one can go from unlocked
4695** to shared and back or from unlocked to exclusive and back. But one may
4696** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004697*/
4698static int unixShmLock(
4699 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004700 int ofst, /* First lock to acquire or release */
4701 int n, /* Number of locks to acquire or release */
4702 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004703){
drh73b64e42010-05-30 19:55:15 +00004704 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4705 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4706 unixShm *pX; /* For looping over all siblings */
4707 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4708 int rc = SQLITE_OK; /* Result code */
4709 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004710
drhd91c68f2010-05-14 14:52:25 +00004711 assert( pShmNode==pDbFd->pInode->pShmNode );
4712 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004713 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004714 assert( n>=1 );
4715 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4716 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4717 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4718 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4719 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004720 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4721 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004722
drhc99597c2010-05-31 01:41:15 +00004723 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004724 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004725 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004726 if( flags & SQLITE_SHM_UNLOCK ){
4727 u16 allMask = 0; /* Mask of locks held by siblings */
4728
4729 /* See if any siblings hold this same lock */
4730 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4731 if( pX==p ) continue;
4732 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4733 allMask |= pX->sharedMask;
4734 }
4735
4736 /* Unlock the system-level locks */
4737 if( (mask & allMask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004738 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004739 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004740 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004741 }
drh73b64e42010-05-30 19:55:15 +00004742
4743 /* Undo the local locks */
4744 if( rc==SQLITE_OK ){
4745 p->exclMask &= ~mask;
4746 p->sharedMask &= ~mask;
4747 }
4748 }else if( flags & SQLITE_SHM_SHARED ){
4749 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4750
4751 /* Find out which shared locks are already held by sibling connections.
4752 ** If any sibling already holds an exclusive lock, go ahead and return
4753 ** SQLITE_BUSY.
4754 */
4755 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004756 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004757 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004758 break;
4759 }
4760 allShared |= pX->sharedMask;
4761 }
4762
4763 /* Get shared locks at the system level, if necessary */
4764 if( rc==SQLITE_OK ){
4765 if( (allShared & mask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004766 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004767 }else{
drh73b64e42010-05-30 19:55:15 +00004768 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004769 }
drhd9e5c4f2010-05-12 18:01:39 +00004770 }
drh73b64e42010-05-30 19:55:15 +00004771
4772 /* Get the local shared locks */
4773 if( rc==SQLITE_OK ){
4774 p->sharedMask |= mask;
4775 }
4776 }else{
4777 /* Make sure no sibling connections hold locks that will block this
4778 ** lock. If any do, return SQLITE_BUSY right away.
4779 */
4780 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004781 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4782 rc = SQLITE_BUSY;
4783 break;
4784 }
4785 }
4786
4787 /* Get the exclusive locks at the system level. Then if successful
4788 ** also mark the local connection as being locked.
4789 */
4790 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004791 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004792 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004793 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004794 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004795 }
drhd9e5c4f2010-05-12 18:01:39 +00004796 }
4797 }
drhd91c68f2010-05-14 14:52:25 +00004798 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004799 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
drh5ac93652015-03-21 20:59:43 +00004800 p->id, osGetpid(0), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004801 return rc;
4802}
4803
drh286a2882010-05-20 23:51:06 +00004804/*
4805** Implement a memory barrier or memory fence on shared memory.
4806**
4807** All loads and stores begun before the barrier must complete before
4808** any load or store begun after the barrier.
4809*/
4810static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004811 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004812){
drhff828942010-06-26 21:34:06 +00004813 UNUSED_PARAMETER(fd);
drh22c733d2015-09-24 12:40:43 +00004814 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
4815 unixEnterMutex(); /* Also mutex, for redundancy */
drhb29ad852010-06-01 00:03:57 +00004816 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004817}
4818
dan18801912010-06-14 14:07:50 +00004819/*
danda9fe0c2010-07-13 18:44:03 +00004820** Close a connection to shared-memory. Delete the underlying
4821** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004822**
4823** If there is no shared memory associated with the connection then this
4824** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004825*/
danda9fe0c2010-07-13 18:44:03 +00004826static int unixShmUnmap(
4827 sqlite3_file *fd, /* The underlying database file */
4828 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004829){
danda9fe0c2010-07-13 18:44:03 +00004830 unixShm *p; /* The connection to be closed */
4831 unixShmNode *pShmNode; /* The underlying shared-memory file */
4832 unixShm **pp; /* For looping over sibling connections */
4833 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004834
danda9fe0c2010-07-13 18:44:03 +00004835 pDbFd = (unixFile*)fd;
4836 p = pDbFd->pShm;
4837 if( p==0 ) return SQLITE_OK;
4838 pShmNode = p->pShmNode;
4839
4840 assert( pShmNode==pDbFd->pInode->pShmNode );
4841 assert( pShmNode->pInode==pDbFd->pInode );
4842
4843 /* Remove connection p from the set of connections associated
4844 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004845 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004846 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4847 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004848
danda9fe0c2010-07-13 18:44:03 +00004849 /* Free the connection p */
4850 sqlite3_free(p);
4851 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004852 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004853
4854 /* If pShmNode->nRef has reached 0, then close the underlying
4855 ** shared-memory file, too */
4856 unixEnterMutex();
4857 assert( pShmNode->nRef>0 );
4858 pShmNode->nRef--;
4859 if( pShmNode->nRef==0 ){
drh4bf66fd2015-02-19 02:43:02 +00004860 if( deleteFlag && pShmNode->h>=0 ){
4861 osUnlink(pShmNode->zFilename);
4862 }
danda9fe0c2010-07-13 18:44:03 +00004863 unixShmPurge(pDbFd);
4864 }
4865 unixLeaveMutex();
4866
4867 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004868}
drh286a2882010-05-20 23:51:06 +00004869
danda9fe0c2010-07-13 18:44:03 +00004870
drhd9e5c4f2010-05-12 18:01:39 +00004871#else
drh6b017cc2010-06-14 18:01:46 +00004872# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004873# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004874# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004875# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004876#endif /* #ifndef SQLITE_OMIT_WAL */
4877
mistachkine98844f2013-08-24 00:59:24 +00004878#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004879/*
danaef49d72013-03-25 16:28:54 +00004880** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004881*/
danf23da962013-03-23 21:00:41 +00004882static void unixUnmapfile(unixFile *pFd){
4883 assert( pFd->nFetchOut==0 );
4884 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004885 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004886 pFd->pMapRegion = 0;
4887 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004888 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004889 }
4890}
dan5d8a1372013-03-19 19:28:06 +00004891
danaef49d72013-03-25 16:28:54 +00004892/*
dane6ecd662013-04-01 17:56:59 +00004893** Attempt to set the size of the memory mapping maintained by file
4894** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4895**
4896** If successful, this function sets the following variables:
4897**
4898** unixFile.pMapRegion
4899** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004900** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004901**
4902** If unsuccessful, an error message is logged via sqlite3_log() and
4903** the three variables above are zeroed. In this case SQLite should
4904** continue accessing the database using the xRead() and xWrite()
4905** methods.
4906*/
4907static void unixRemapfile(
4908 unixFile *pFd, /* File descriptor object */
4909 i64 nNew /* Required mapping size */
4910){
dan4ff7bc42013-04-02 12:04:09 +00004911 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004912 int h = pFd->h; /* File descriptor open on db file */
4913 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004914 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004915 u8 *pNew = 0; /* Location of new mapping */
4916 int flags = PROT_READ; /* Flags to pass to mmap() */
4917
4918 assert( pFd->nFetchOut==0 );
4919 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004920 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004921 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004922 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004923 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004924
danfe33e392015-11-17 20:56:06 +00004925#ifdef SQLITE_MMAP_READWRITE
dane6ecd662013-04-01 17:56:59 +00004926 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
danfe33e392015-11-17 20:56:06 +00004927#endif
dane6ecd662013-04-01 17:56:59 +00004928
4929 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00004930#if HAVE_MREMAP
4931 i64 nReuse = pFd->mmapSize;
4932#else
danbc760632014-03-20 09:42:09 +00004933 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00004934 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00004935#endif
dane6ecd662013-04-01 17:56:59 +00004936 u8 *pReq = &pOrig[nReuse];
4937
4938 /* Unmap any pages of the existing mapping that cannot be reused. */
4939 if( nReuse!=nOrig ){
4940 osMunmap(pReq, nOrig-nReuse);
4941 }
4942
4943#if HAVE_MREMAP
4944 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004945 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004946#else
4947 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4948 if( pNew!=MAP_FAILED ){
4949 if( pNew!=pReq ){
4950 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004951 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004952 }else{
4953 pNew = pOrig;
4954 }
4955 }
4956#endif
4957
dan48ccef82013-04-02 20:55:01 +00004958 /* The attempt to extend the existing mapping failed. Free it. */
4959 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004960 osMunmap(pOrig, nReuse);
4961 }
4962 }
4963
4964 /* If pNew is still NULL, try to create an entirely new mapping. */
4965 if( pNew==0 ){
4966 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004967 }
4968
dan4ff7bc42013-04-02 12:04:09 +00004969 if( pNew==MAP_FAILED ){
4970 pNew = 0;
4971 nNew = 0;
4972 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4973
4974 /* If the mmap() above failed, assume that all subsequent mmap() calls
4975 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4976 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004977 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004978 }
dane6ecd662013-04-01 17:56:59 +00004979 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004980 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004981}
4982
4983/*
danaef49d72013-03-25 16:28:54 +00004984** Memory map or remap the file opened by file-descriptor pFd (if the file
4985** is already mapped, the existing mapping is replaced by the new). Or, if
4986** there already exists a mapping for this file, and there are still
4987** outstanding xFetch() references to it, this function is a no-op.
4988**
4989** If parameter nByte is non-negative, then it is the requested size of
4990** the mapping to create. Otherwise, if nByte is less than zero, then the
4991** requested size is the size of the file on disk. The actual size of the
4992** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004993** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004994**
4995** SQLITE_OK is returned if no error occurs (even if the mapping is not
4996** recreated as a result of outstanding references) or an SQLite error
4997** code otherwise.
4998*/
drhf3b1ed02015-12-02 13:11:03 +00004999static int unixMapfile(unixFile *pFd, i64 nMap){
danf23da962013-03-23 21:00:41 +00005000 assert( nMap>=0 || pFd->nFetchOut==0 );
drh333e6ca2015-12-02 15:44:39 +00005001 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00005002 if( pFd->nFetchOut>0 ) return SQLITE_OK;
5003
5004 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00005005 struct stat statbuf; /* Low-level file information */
drhf3b1ed02015-12-02 13:11:03 +00005006 if( osFstat(pFd->h, &statbuf) ){
danf23da962013-03-23 21:00:41 +00005007 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00005008 }
drh3044b512014-06-16 16:41:52 +00005009 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00005010 }
drh9b4c59f2013-04-15 17:03:42 +00005011 if( nMap>pFd->mmapSizeMax ){
5012 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00005013 }
5014
drh333e6ca2015-12-02 15:44:39 +00005015 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00005016 if( nMap!=pFd->mmapSize ){
drh333e6ca2015-12-02 15:44:39 +00005017 unixRemapfile(pFd, nMap);
dan5d8a1372013-03-19 19:28:06 +00005018 }
5019
danf23da962013-03-23 21:00:41 +00005020 return SQLITE_OK;
5021}
mistachkine98844f2013-08-24 00:59:24 +00005022#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00005023
danaef49d72013-03-25 16:28:54 +00005024/*
5025** If possible, return a pointer to a mapping of file fd starting at offset
5026** iOff. The mapping must be valid for at least nAmt bytes.
5027**
5028** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
5029** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
5030** Finally, if an error does occur, return an SQLite error code. The final
5031** value of *pp is undefined in this case.
5032**
5033** If this function does return a pointer, the caller must eventually
5034** release the reference by calling unixUnfetch().
5035*/
danf23da962013-03-23 21:00:41 +00005036static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00005037#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00005038 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00005039#endif
danf23da962013-03-23 21:00:41 +00005040 *pp = 0;
5041
drh9b4c59f2013-04-15 17:03:42 +00005042#if SQLITE_MAX_MMAP_SIZE>0
5043 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00005044 if( pFd->pMapRegion==0 ){
5045 int rc = unixMapfile(pFd, -1);
5046 if( rc!=SQLITE_OK ) return rc;
5047 }
5048 if( pFd->mmapSize >= iOff+nAmt ){
5049 *pp = &((u8 *)pFd->pMapRegion)[iOff];
5050 pFd->nFetchOut++;
5051 }
5052 }
drh6e0b6d52013-04-09 16:19:20 +00005053#endif
danf23da962013-03-23 21:00:41 +00005054 return SQLITE_OK;
5055}
5056
danaef49d72013-03-25 16:28:54 +00005057/*
dandf737fe2013-03-25 17:00:24 +00005058** If the third argument is non-NULL, then this function releases a
5059** reference obtained by an earlier call to unixFetch(). The second
5060** argument passed to this function must be the same as the corresponding
5061** argument that was passed to the unixFetch() invocation.
5062**
5063** Or, if the third argument is NULL, then this function is being called
5064** to inform the VFS layer that, according to POSIX, any existing mapping
5065** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00005066*/
dandf737fe2013-03-25 17:00:24 +00005067static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00005068#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00005069 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00005070 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00005071
danaef49d72013-03-25 16:28:54 +00005072 /* If p==0 (unmap the entire file) then there must be no outstanding
5073 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
5074 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00005075 assert( (p==0)==(pFd->nFetchOut==0) );
5076
dandf737fe2013-03-25 17:00:24 +00005077 /* If p!=0, it must match the iOff value. */
5078 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
5079
danf23da962013-03-23 21:00:41 +00005080 if( p ){
5081 pFd->nFetchOut--;
5082 }else{
5083 unixUnmapfile(pFd);
5084 }
5085
5086 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00005087#else
5088 UNUSED_PARAMETER(fd);
5089 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00005090 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00005091#endif
danf23da962013-03-23 21:00:41 +00005092 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00005093}
5094
5095/*
drh734c9862008-11-28 15:37:20 +00005096** Here ends the implementation of all sqlite3_file methods.
5097**
5098********************** End sqlite3_file Methods *******************************
5099******************************************************************************/
5100
5101/*
drh6b9d6dd2008-12-03 19:34:47 +00005102** This division contains definitions of sqlite3_io_methods objects that
5103** implement various file locking strategies. It also contains definitions
5104** of "finder" functions. A finder-function is used to locate the appropriate
5105** sqlite3_io_methods object for a particular database file. The pAppData
5106** field of the sqlite3_vfs VFS objects are initialized to be pointers to
5107** the correct finder-function for that VFS.
5108**
5109** Most finder functions return a pointer to a fixed sqlite3_io_methods
5110** object. The only interesting finder-function is autolockIoFinder, which
5111** looks at the filesystem type and tries to guess the best locking
5112** strategy from that.
5113**
peter.d.reid60ec9142014-09-06 16:39:46 +00005114** For finder-function F, two objects are created:
drh1875f7a2008-12-08 18:19:17 +00005115**
5116** (1) The real finder-function named "FImpt()".
5117**
dane946c392009-08-22 11:39:46 +00005118** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00005119**
5120**
5121** A pointer to the F pointer is used as the pAppData value for VFS
5122** objects. We have to do this instead of letting pAppData point
5123** directly at the finder-function since C90 rules prevent a void*
5124** from be cast into a function pointer.
5125**
drh6b9d6dd2008-12-03 19:34:47 +00005126**
drh7708e972008-11-29 00:56:52 +00005127** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00005128**
drh7708e972008-11-29 00:56:52 +00005129** * A constant sqlite3_io_methods object call METHOD that has locking
5130** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
5131**
5132** * An I/O method finder function called FINDER that returns a pointer
5133** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00005134*/
drhe6d41732015-02-21 00:49:00 +00005135#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
drh7708e972008-11-29 00:56:52 +00005136static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00005137 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00005138 CLOSE, /* xClose */ \
5139 unixRead, /* xRead */ \
5140 unixWrite, /* xWrite */ \
5141 unixTruncate, /* xTruncate */ \
5142 unixSync, /* xSync */ \
5143 unixFileSize, /* xFileSize */ \
5144 LOCK, /* xLock */ \
5145 UNLOCK, /* xUnlock */ \
5146 CKLOCK, /* xCheckReservedLock */ \
5147 unixFileControl, /* xFileControl */ \
5148 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00005149 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drhd9f94412014-09-22 03:22:27 +00005150 SHMMAP, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00005151 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00005152 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00005153 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00005154 unixFetch, /* xFetch */ \
5155 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00005156}; \
drh0c2694b2009-09-03 16:23:44 +00005157static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
5158 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00005159 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00005160} \
drh0c2694b2009-09-03 16:23:44 +00005161static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00005162 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00005163
5164/*
5165** Here are all of the sqlite3_io_methods objects for each of the
5166** locking strategies. Functions that return pointers to these methods
5167** are also created.
5168*/
5169IOMETHODS(
5170 posixIoFinder, /* Finder function name */
5171 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00005172 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00005173 unixClose, /* xClose method */
5174 unixLock, /* xLock method */
5175 unixUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005176 unixCheckReservedLock, /* xCheckReservedLock method */
5177 unixShmMap /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005178)
drh7708e972008-11-29 00:56:52 +00005179IOMETHODS(
5180 nolockIoFinder, /* Finder function name */
5181 nolockIoMethods, /* sqlite3_io_methods object name */
drh142341c2014-09-19 19:00:48 +00005182 3, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005183 nolockClose, /* xClose method */
5184 nolockLock, /* xLock method */
5185 nolockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005186 nolockCheckReservedLock, /* xCheckReservedLock method */
5187 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005188)
drh7708e972008-11-29 00:56:52 +00005189IOMETHODS(
5190 dotlockIoFinder, /* Finder function name */
5191 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005192 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005193 dotlockClose, /* xClose method */
5194 dotlockLock, /* xLock method */
5195 dotlockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005196 dotlockCheckReservedLock, /* xCheckReservedLock method */
5197 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005198)
drh7708e972008-11-29 00:56:52 +00005199
drhe89b2912015-03-03 20:42:01 +00005200#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005201IOMETHODS(
5202 flockIoFinder, /* Finder function name */
5203 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005204 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005205 flockClose, /* xClose method */
5206 flockLock, /* xLock method */
5207 flockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005208 flockCheckReservedLock, /* xCheckReservedLock method */
5209 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005210)
drh7708e972008-11-29 00:56:52 +00005211#endif
5212
drh6c7d5c52008-11-21 20:32:33 +00005213#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005214IOMETHODS(
5215 semIoFinder, /* Finder function name */
5216 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005217 1, /* shared memory is disabled */
drh8cd5b252015-03-02 22:06:43 +00005218 semXClose, /* xClose method */
5219 semXLock, /* xLock method */
5220 semXUnlock, /* xUnlock method */
5221 semXCheckReservedLock, /* xCheckReservedLock method */
drhd9f94412014-09-22 03:22:27 +00005222 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005223)
aswiftaebf4132008-11-21 00:10:35 +00005224#endif
drh7708e972008-11-29 00:56:52 +00005225
drhd2cb50b2009-01-09 21:41:17 +00005226#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005227IOMETHODS(
5228 afpIoFinder, /* Finder function name */
5229 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005230 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005231 afpClose, /* xClose method */
5232 afpLock, /* xLock method */
5233 afpUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005234 afpCheckReservedLock, /* xCheckReservedLock method */
5235 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005236)
drh715ff302008-12-03 22:32:44 +00005237#endif
5238
5239/*
5240** The proxy locking method is a "super-method" in the sense that it
5241** opens secondary file descriptors for the conch and lock files and
5242** it uses proxy, dot-file, AFP, and flock() locking methods on those
5243** secondary files. For this reason, the division that implements
5244** proxy locking is located much further down in the file. But we need
5245** to go ahead and define the sqlite3_io_methods and finder function
5246** for proxy locking here. So we forward declare the I/O methods.
5247*/
drhd2cb50b2009-01-09 21:41:17 +00005248#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005249static int proxyClose(sqlite3_file*);
5250static int proxyLock(sqlite3_file*, int);
5251static int proxyUnlock(sqlite3_file*, int);
5252static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005253IOMETHODS(
5254 proxyIoFinder, /* Finder function name */
5255 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005256 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005257 proxyClose, /* xClose method */
5258 proxyLock, /* xLock method */
5259 proxyUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005260 proxyCheckReservedLock, /* xCheckReservedLock method */
5261 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005262)
aswiftaebf4132008-11-21 00:10:35 +00005263#endif
drh7708e972008-11-29 00:56:52 +00005264
drh7ed97b92010-01-20 13:07:21 +00005265/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5266#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5267IOMETHODS(
5268 nfsIoFinder, /* Finder function name */
5269 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005270 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005271 unixClose, /* xClose method */
5272 unixLock, /* xLock method */
5273 nfsUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005274 unixCheckReservedLock, /* xCheckReservedLock method */
5275 0 /* xShmMap method */
drh7ed97b92010-01-20 13:07:21 +00005276)
5277#endif
drh7708e972008-11-29 00:56:52 +00005278
drhd2cb50b2009-01-09 21:41:17 +00005279#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005280/*
drh6b9d6dd2008-12-03 19:34:47 +00005281** This "finder" function attempts to determine the best locking strategy
5282** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005283** object that implements that strategy.
5284**
5285** This is for MacOSX only.
5286*/
drh1875f7a2008-12-08 18:19:17 +00005287static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005288 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005289 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005290){
5291 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005292 const char *zFilesystem; /* Filesystem type name */
5293 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005294 } aMap[] = {
5295 { "hfs", &posixIoMethods },
5296 { "ufs", &posixIoMethods },
5297 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005298 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005299 { "webdav", &nolockIoMethods },
5300 { 0, 0 }
5301 };
5302 int i;
5303 struct statfs fsInfo;
5304 struct flock lockInfo;
5305
5306 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005307 /* If filePath==NULL that means we are dealing with a transient file
5308 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005309 return &nolockIoMethods;
5310 }
5311 if( statfs(filePath, &fsInfo) != -1 ){
5312 if( fsInfo.f_flags & MNT_RDONLY ){
5313 return &nolockIoMethods;
5314 }
5315 for(i=0; aMap[i].zFilesystem; i++){
5316 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5317 return aMap[i].pMethods;
5318 }
5319 }
5320 }
5321
5322 /* Default case. Handles, amongst others, "nfs".
5323 ** Test byte-range lock using fcntl(). If the call succeeds,
5324 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005325 */
drh7708e972008-11-29 00:56:52 +00005326 lockInfo.l_len = 1;
5327 lockInfo.l_start = 0;
5328 lockInfo.l_whence = SEEK_SET;
5329 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005330 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005331 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5332 return &nfsIoMethods;
5333 } else {
5334 return &posixIoMethods;
5335 }
drh7708e972008-11-29 00:56:52 +00005336 }else{
5337 return &dotlockIoMethods;
5338 }
5339}
drh0c2694b2009-09-03 16:23:44 +00005340static const sqlite3_io_methods
5341 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005342
drhd2cb50b2009-01-09 21:41:17 +00005343#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005344
drhe89b2912015-03-03 20:42:01 +00005345#if OS_VXWORKS
5346/*
5347** This "finder" function for VxWorks checks to see if posix advisory
5348** locking works. If it does, then that is what is used. If it does not
5349** work, then fallback to named semaphore locking.
chw78a13182009-04-07 05:35:03 +00005350*/
drhe89b2912015-03-03 20:42:01 +00005351static const sqlite3_io_methods *vxworksIoFinderImpl(
chw78a13182009-04-07 05:35:03 +00005352 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005353 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005354){
5355 struct flock lockInfo;
5356
5357 if( !filePath ){
5358 /* If filePath==NULL that means we are dealing with a transient file
5359 ** that does not need to be locked. */
5360 return &nolockIoMethods;
5361 }
5362
5363 /* Test if fcntl() is supported and use POSIX style locks.
5364 ** Otherwise fall back to the named semaphore method.
5365 */
5366 lockInfo.l_len = 1;
5367 lockInfo.l_start = 0;
5368 lockInfo.l_whence = SEEK_SET;
5369 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005370 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005371 return &posixIoMethods;
5372 }else{
5373 return &semIoMethods;
5374 }
5375}
drh0c2694b2009-09-03 16:23:44 +00005376static const sqlite3_io_methods
drhe89b2912015-03-03 20:42:01 +00005377 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005378
drhe89b2912015-03-03 20:42:01 +00005379#endif /* OS_VXWORKS */
chw78a13182009-04-07 05:35:03 +00005380
drh7708e972008-11-29 00:56:52 +00005381/*
peter.d.reid60ec9142014-09-06 16:39:46 +00005382** An abstract type for a pointer to an IO method finder function:
drh7708e972008-11-29 00:56:52 +00005383*/
drh0c2694b2009-09-03 16:23:44 +00005384typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005385
aswiftaebf4132008-11-21 00:10:35 +00005386
drh734c9862008-11-28 15:37:20 +00005387/****************************************************************************
5388**************************** sqlite3_vfs methods ****************************
5389**
5390** This division contains the implementation of methods on the
5391** sqlite3_vfs object.
5392*/
5393
danielk1977a3d4c882007-03-23 10:08:38 +00005394/*
danielk1977e339d652008-06-28 11:23:00 +00005395** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005396*/
5397static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005398 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005399 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005400 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005401 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005402 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005403){
drh7708e972008-11-29 00:56:52 +00005404 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005405 unixFile *pNew = (unixFile *)pId;
5406 int rc = SQLITE_OK;
5407
drh8af6c222010-05-14 12:43:01 +00005408 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005409
drhb07028f2011-10-14 21:49:18 +00005410 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005411 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005412
drh308c2a52010-05-14 11:30:18 +00005413 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005414 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005415 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005416 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005417 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005418#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005419 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005420#endif
drhc02a43a2012-01-10 23:18:38 +00005421 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5422 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005423 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005424 }
drh503a6862013-03-01 01:07:17 +00005425 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005426 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005427 }
drh339eb0b2008-03-07 15:34:11 +00005428
drh6c7d5c52008-11-21 20:32:33 +00005429#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005430 pNew->pId = vxworksFindFileId(zFilename);
5431 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005432 ctrlFlags |= UNIXFILE_NOLOCK;
mistachkinfad30392016-02-13 23:43:46 +00005433 rc = SQLITE_NOMEM_BKPT;
chw97185482008-11-17 08:05:31 +00005434 }
5435#endif
5436
drhc02a43a2012-01-10 23:18:38 +00005437 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005438 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005439 }else{
drh0c2694b2009-09-03 16:23:44 +00005440 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005441#if SQLITE_ENABLE_LOCKING_STYLE
5442 /* Cache zFilename in the locking context (AFP and dotlock override) for
5443 ** proxyLock activation is possible (remote proxy is based on db name)
5444 ** zFilename remains valid until file is closed, to support */
5445 pNew->lockingContext = (void*)zFilename;
5446#endif
drhda0e7682008-07-30 15:27:54 +00005447 }
danielk1977e339d652008-06-28 11:23:00 +00005448
drh7ed97b92010-01-20 13:07:21 +00005449 if( pLockingStyle == &posixIoMethods
5450#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5451 || pLockingStyle == &nfsIoMethods
5452#endif
5453 ){
drh7708e972008-11-29 00:56:52 +00005454 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005455 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005456 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005457 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005458 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005459 ** in two scenarios:
5460 **
5461 ** (a) A call to fstat() failed.
5462 ** (b) A malloc failed.
5463 **
5464 ** Scenario (b) may only occur if the process is holding no other
5465 ** file descriptors open on the same file. If there were other file
5466 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005467 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005468 ** handle h - as it is guaranteed that no posix locks will be released
5469 ** by doing so.
5470 **
5471 ** If scenario (a) caused the error then things are not so safe. The
5472 ** implicit assumption here is that if fstat() fails, things are in
5473 ** such bad shape that dropping a lock or two doesn't matter much.
5474 */
drh0e9365c2011-03-02 02:08:13 +00005475 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005476 h = -1;
5477 }
drh7708e972008-11-29 00:56:52 +00005478 unixLeaveMutex();
5479 }
danielk1977e339d652008-06-28 11:23:00 +00005480
drhd2cb50b2009-01-09 21:41:17 +00005481#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005482 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005483 /* AFP locking uses the file path so it needs to be included in
5484 ** the afpLockingContext.
5485 */
5486 afpLockingContext *pCtx;
drhf3cdcdc2015-04-29 16:50:28 +00005487 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh7708e972008-11-29 00:56:52 +00005488 if( pCtx==0 ){
mistachkinfad30392016-02-13 23:43:46 +00005489 rc = SQLITE_NOMEM_BKPT;
drh7708e972008-11-29 00:56:52 +00005490 }else{
5491 /* NB: zFilename exists and remains valid until the file is closed
5492 ** according to requirement F11141. So we do not need to make a
5493 ** copy of the filename. */
5494 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005495 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005496 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005497 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005498 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005499 if( rc!=SQLITE_OK ){
5500 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005501 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005502 h = -1;
5503 }
drh7708e972008-11-29 00:56:52 +00005504 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005505 }
drh7708e972008-11-29 00:56:52 +00005506 }
5507#endif
danielk1977e339d652008-06-28 11:23:00 +00005508
drh7708e972008-11-29 00:56:52 +00005509 else if( pLockingStyle == &dotlockIoMethods ){
5510 /* Dotfile locking uses the file path so it needs to be included in
5511 ** the dotlockLockingContext
5512 */
5513 char *zLockFile;
5514 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005515 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005516 nFilename = (int)strlen(zFilename) + 6;
drhf3cdcdc2015-04-29 16:50:28 +00005517 zLockFile = (char *)sqlite3_malloc64(nFilename);
drh7708e972008-11-29 00:56:52 +00005518 if( zLockFile==0 ){
mistachkinfad30392016-02-13 23:43:46 +00005519 rc = SQLITE_NOMEM_BKPT;
drh7708e972008-11-29 00:56:52 +00005520 }else{
5521 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005522 }
drh7708e972008-11-29 00:56:52 +00005523 pNew->lockingContext = zLockFile;
5524 }
danielk1977e339d652008-06-28 11:23:00 +00005525
drh6c7d5c52008-11-21 20:32:33 +00005526#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005527 else if( pLockingStyle == &semIoMethods ){
5528 /* Named semaphore locking uses the file path so it needs to be
5529 ** included in the semLockingContext
5530 */
5531 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005532 rc = findInodeInfo(pNew, &pNew->pInode);
5533 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5534 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005535 int n;
drh2238dcc2009-08-27 17:56:20 +00005536 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005537 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005538 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005539 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005540 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5541 if( pNew->pInode->pSem == SEM_FAILED ){
mistachkinfad30392016-02-13 23:43:46 +00005542 rc = SQLITE_NOMEM_BKPT;
drh8af6c222010-05-14 12:43:01 +00005543 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005544 }
chw97185482008-11-17 08:05:31 +00005545 }
drh7708e972008-11-29 00:56:52 +00005546 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005547 }
drh7708e972008-11-29 00:56:52 +00005548#endif
aswift5b1a2562008-08-22 00:22:35 +00005549
drh4bf66fd2015-02-19 02:43:02 +00005550 storeLastErrno(pNew, 0);
drh6c7d5c52008-11-21 20:32:33 +00005551#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005552 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005553 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005554 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005555 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005556 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005557 }
chw97185482008-11-17 08:05:31 +00005558#endif
danielk1977e339d652008-06-28 11:23:00 +00005559 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005560 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005561 }else{
drh7708e972008-11-29 00:56:52 +00005562 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005563 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005564 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005565 }
danielk1977e339d652008-06-28 11:23:00 +00005566 return rc;
drh054889e2005-11-30 03:20:31 +00005567}
drh9c06c952005-11-26 00:25:00 +00005568
danielk1977ad94b582007-08-20 06:44:22 +00005569/*
drh8b3cf822010-06-01 21:02:51 +00005570** Return the name of a directory in which to put temporary files.
5571** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005572*/
drh7234c6d2010-06-19 15:10:09 +00005573static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005574 static const char *azDirs[] = {
5575 0,
aswiftaebf4132008-11-21 00:10:35 +00005576 0,
danielk197717b90b52008-06-06 11:11:25 +00005577 "/var/tmp",
5578 "/usr/tmp",
5579 "/tmp",
drhb7e50ad2015-11-28 21:49:53 +00005580 "."
danielk197717b90b52008-06-06 11:11:25 +00005581 };
drh2aab11f2016-04-29 20:30:56 +00005582 unsigned int i = 0;
drh8b3cf822010-06-01 21:02:51 +00005583 struct stat buf;
drhb7e50ad2015-11-28 21:49:53 +00005584 const char *zDir = sqlite3_temp_directory;
drh8b3cf822010-06-01 21:02:51 +00005585
drhb7e50ad2015-11-28 21:49:53 +00005586 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
5587 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh2aab11f2016-04-29 20:30:56 +00005588 while(1){
5589 if( zDir!=0
5590 && osStat(zDir, &buf)==0
5591 && S_ISDIR(buf.st_mode)
5592 && osAccess(zDir, 03)==0
5593 ){
5594 return zDir;
5595 }
5596 if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
5597 zDir = azDirs[i++];
drh8b3cf822010-06-01 21:02:51 +00005598 }
drh7694e062016-04-21 23:37:24 +00005599 return 0;
drh8b3cf822010-06-01 21:02:51 +00005600}
5601
5602/*
5603** Create a temporary file name in zBuf. zBuf must be allocated
5604** by the calling process and must be big enough to hold at least
5605** pVfs->mxPathname bytes.
5606*/
5607static int unixGetTempname(int nBuf, char *zBuf){
drh8b3cf822010-06-01 21:02:51 +00005608 const char *zDir;
drhb7e50ad2015-11-28 21:49:53 +00005609 int iLimit = 0;
danielk197717b90b52008-06-06 11:11:25 +00005610
5611 /* It's odd to simulate an io-error here, but really this is just
5612 ** using the io-error infrastructure to test that SQLite handles this
5613 ** function failing.
5614 */
drh7694e062016-04-21 23:37:24 +00005615 zBuf[0] = 0;
danielk197717b90b52008-06-06 11:11:25 +00005616 SimulateIOError( return SQLITE_IOERR );
5617
drh7234c6d2010-06-19 15:10:09 +00005618 zDir = unixTempFileDir();
drh7694e062016-04-21 23:37:24 +00005619 if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
danielk197717b90b52008-06-06 11:11:25 +00005620 do{
drh970942e2015-11-25 23:13:14 +00005621 u64 r;
5622 sqlite3_randomness(sizeof(r), &r);
5623 assert( nBuf>2 );
5624 zBuf[nBuf-2] = 0;
5625 sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
5626 zDir, r, 0);
drhb7e50ad2015-11-28 21:49:53 +00005627 if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
drh99ab3b12011-03-02 15:09:07 +00005628 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005629 return SQLITE_OK;
5630}
5631
drhd2cb50b2009-01-09 21:41:17 +00005632#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005633/*
5634** Routine to transform a unixFile into a proxy-locking unixFile.
5635** Implementation in the proxy-lock division, but used by unixOpen()
5636** if SQLITE_PREFER_PROXY_LOCKING is defined.
5637*/
5638static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005639#endif
drhc66d5b62008-12-03 22:48:32 +00005640
dan08da86a2009-08-21 17:18:03 +00005641/*
5642** Search for an unused file descriptor that was opened on the database
5643** file (not a journal or master-journal file) identified by pathname
5644** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5645** argument to this function.
5646**
5647** Such a file descriptor may exist if a database connection was closed
5648** but the associated file descriptor could not be closed because some
5649** other file descriptor open on the same file is holding a file-lock.
5650** Refer to comments in the unixClose() function and the lengthy comment
5651** describing "Posix Advisory Locking" at the start of this file for
5652** further details. Also, ticket #4018.
5653**
5654** If a suitable file descriptor is found, then it is returned. If no
5655** such file descriptor is located, -1 is returned.
5656*/
dane946c392009-08-22 11:39:46 +00005657static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5658 UnixUnusedFd *pUnused = 0;
5659
5660 /* Do not search for an unused file descriptor on vxworks. Not because
5661 ** vxworks would not benefit from the change (it might, we're not sure),
5662 ** but because no way to test it is currently available. It is better
5663 ** not to risk breaking vxworks support for the sake of such an obscure
5664 ** feature. */
5665#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005666 struct stat sStat; /* Results of stat() call */
5667
drhc68886b2017-08-18 16:09:52 +00005668 unixEnterMutex();
5669
dan08da86a2009-08-21 17:18:03 +00005670 /* A stat() call may fail for various reasons. If this happens, it is
5671 ** almost certain that an open() call on the same path will also fail.
5672 ** For this reason, if an error occurs in the stat() call here, it is
5673 ** ignored and -1 is returned. The caller will try to open a new file
5674 ** descriptor on the same path, fail, and return an error to SQLite.
5675 **
5676 ** Even if a subsequent open() call does succeed, the consequences of
peter.d.reid60ec9142014-09-06 16:39:46 +00005677 ** not searching for a reusable file descriptor are not dire. */
drhc68886b2017-08-18 16:09:52 +00005678 if( nUnusedFd>0 && 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005679 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005680
drh8af6c222010-05-14 12:43:01 +00005681 pInode = inodeList;
5682 while( pInode && (pInode->fileId.dev!=sStat.st_dev
drh25ef7f52016-12-05 20:06:45 +00005683 || pInode->fileId.ino!=(u64)sStat.st_ino) ){
drh8af6c222010-05-14 12:43:01 +00005684 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005685 }
drh8af6c222010-05-14 12:43:01 +00005686 if( pInode ){
dane946c392009-08-22 11:39:46 +00005687 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005688 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005689 pUnused = *pp;
5690 if( pUnused ){
drhc68886b2017-08-18 16:09:52 +00005691 nUnusedFd--;
dane946c392009-08-22 11:39:46 +00005692 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005693 }
5694 }
dan08da86a2009-08-21 17:18:03 +00005695 }
drhc68886b2017-08-18 16:09:52 +00005696 unixLeaveMutex();
dane946c392009-08-22 11:39:46 +00005697#endif /* if !OS_VXWORKS */
5698 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005699}
danielk197717b90b52008-06-06 11:11:25 +00005700
5701/*
dan1bf4ca72016-08-11 18:05:47 +00005702** Find the mode, uid and gid of file zFile.
5703*/
5704static int getFileMode(
5705 const char *zFile, /* File name */
5706 mode_t *pMode, /* OUT: Permissions of zFile */
5707 uid_t *pUid, /* OUT: uid of zFile. */
5708 gid_t *pGid /* OUT: gid of zFile. */
5709){
5710 struct stat sStat; /* Output of stat() on database file */
5711 int rc = SQLITE_OK;
5712 if( 0==osStat(zFile, &sStat) ){
5713 *pMode = sStat.st_mode & 0777;
5714 *pUid = sStat.st_uid;
5715 *pGid = sStat.st_gid;
5716 }else{
5717 rc = SQLITE_IOERR_FSTAT;
5718 }
5719 return rc;
5720}
5721
5722/*
danddb0ac42010-07-14 14:48:58 +00005723** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005724** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005725** and a value suitable for passing as the third argument to open(2) is
5726** written to *pMode. If an IO error occurs, an SQLite error code is
5727** returned and the value of *pMode is not modified.
5728**
peter.d.reid60ec9142014-09-06 16:39:46 +00005729** In most cases, this routine sets *pMode to 0, which will become
drh8c815d12012-02-13 20:16:37 +00005730** an indication to robust_open() to create the file using
5731** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5732** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005733** this function queries the file-system for the permissions on the
5734** corresponding database file and sets *pMode to this value. Whenever
5735** possible, WAL and journal files are created using the same permissions
5736** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005737**
5738** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5739** original filename is unavailable. But 8_3_NAMES is only used for
5740** FAT filesystems and permissions do not matter there, so just use
5741** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005742*/
5743static int findCreateFileMode(
5744 const char *zPath, /* Path of file (possibly) being created */
5745 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005746 mode_t *pMode, /* OUT: Permissions to open file with */
5747 uid_t *pUid, /* OUT: uid to set on the file */
5748 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005749){
5750 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005751 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005752 *pUid = 0;
5753 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005754 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005755 char zDb[MAX_PATHNAME+1]; /* Database file path */
5756 int nDb; /* Number of valid bytes in zDb */
danddb0ac42010-07-14 14:48:58 +00005757
dana0c989d2010-11-05 18:07:37 +00005758 /* zPath is a path to a WAL or journal file. The following block derives
5759 ** the path to the associated database file from zPath. This block handles
5760 ** the following naming conventions:
5761 **
5762 ** "<path to db>-journal"
5763 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005764 ** "<path to db>-journalNN"
5765 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005766 **
drhd337c5b2011-10-20 18:23:35 +00005767 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005768 ** used by the test_multiplex.c module.
5769 */
5770 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005771 while( zPath[nDb]!='-' ){
dan629ec142017-09-14 20:41:17 +00005772 /* In normal operation, the journal file name will always contain
5773 ** a '-' character. However in 8+3 filename mode, or if a corrupt
5774 ** rollback journal specifies a master journal with a goofy name, then
5775 ** the '-' might be missing. */
drh90e5dda2015-12-03 20:42:28 +00005776 if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005777 nDb--;
5778 }
danddb0ac42010-07-14 14:48:58 +00005779 memcpy(zDb, zPath, nDb);
5780 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005781
dan1bf4ca72016-08-11 18:05:47 +00005782 rc = getFileMode(zDb, pMode, pUid, pGid);
danddb0ac42010-07-14 14:48:58 +00005783 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5784 *pMode = 0600;
dan1bf4ca72016-08-11 18:05:47 +00005785 }else if( flags & SQLITE_OPEN_URI ){
5786 /* If this is a main database file and the file was opened using a URI
5787 ** filename, check for the "modeof" parameter. If present, interpret
5788 ** its value as a filename and try to copy the mode, uid and gid from
5789 ** that file. */
5790 const char *z = sqlite3_uri_parameter(zPath, "modeof");
5791 if( z ){
5792 rc = getFileMode(z, pMode, pUid, pGid);
5793 }
danddb0ac42010-07-14 14:48:58 +00005794 }
5795 return rc;
5796}
5797
5798/*
danielk1977ad94b582007-08-20 06:44:22 +00005799** Open the file zPath.
5800**
danielk1977b4b47412007-08-17 15:53:36 +00005801** Previously, the SQLite OS layer used three functions in place of this
5802** one:
5803**
5804** sqlite3OsOpenReadWrite();
5805** sqlite3OsOpenReadOnly();
5806** sqlite3OsOpenExclusive();
5807**
5808** These calls correspond to the following combinations of flags:
5809**
5810** ReadWrite() -> (READWRITE | CREATE)
5811** ReadOnly() -> (READONLY)
5812** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5813**
5814** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5815** true, the file was configured to be automatically deleted when the
5816** file handle closed. To achieve the same effect using this new
5817** interface, add the DELETEONCLOSE flag to those specified above for
5818** OpenExclusive().
5819*/
5820static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005821 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5822 const char *zPath, /* Pathname of file to be opened */
5823 sqlite3_file *pFile, /* The file descriptor to be filled in */
5824 int flags, /* Input flags to control the opening */
5825 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005826){
dan08da86a2009-08-21 17:18:03 +00005827 unixFile *p = (unixFile *)pFile;
5828 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005829 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005830 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005831 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005832 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005833 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005834
5835 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5836 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5837 int isCreate = (flags & SQLITE_OPEN_CREATE);
5838 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5839 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005840#if SQLITE_ENABLE_LOCKING_STYLE
5841 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5842#endif
drh3d4435b2011-08-26 20:55:50 +00005843#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5844 struct statfs fsInfo;
5845#endif
danielk1977b4b47412007-08-17 15:53:36 +00005846
danielk1977fee2d252007-08-18 10:59:19 +00005847 /* If creating a master or main-file journal, this function will open
5848 ** a file-descriptor on the directory too. The first time unixSync()
5849 ** is called the directory file descriptor will be fsync()ed and close()d.
5850 */
drha803a2c2017-12-13 20:02:29 +00005851 int isNewJrnl = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005852 eType==SQLITE_OPEN_MASTER_JOURNAL
5853 || eType==SQLITE_OPEN_MAIN_JOURNAL
5854 || eType==SQLITE_OPEN_WAL
5855 ));
danielk1977fee2d252007-08-18 10:59:19 +00005856
danielk197717b90b52008-06-06 11:11:25 +00005857 /* If argument zPath is a NULL pointer, this function is required to open
5858 ** a temporary file. Use this buffer to store the file name in.
5859 */
drhc02a43a2012-01-10 23:18:38 +00005860 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005861 const char *zName = zPath;
5862
danielk1977fee2d252007-08-18 10:59:19 +00005863 /* Check the following statements are true:
5864 **
5865 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5866 ** (b) if CREATE is set, then READWRITE must also be set, and
5867 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005868 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005869 */
danielk1977b4b47412007-08-17 15:53:36 +00005870 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005871 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005872 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005873 assert(isDelete==0 || isCreate);
5874
danddb0ac42010-07-14 14:48:58 +00005875 /* The main DB, main journal, WAL file and master journal are never
5876 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005877 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5878 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5879 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005880 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005881
danielk1977fee2d252007-08-18 10:59:19 +00005882 /* Assert that the upper layer has set one of the "file-type" flags. */
5883 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5884 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5885 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005886 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005887 );
5888
drhb00d8622014-01-01 15:18:36 +00005889 /* Detect a pid change and reset the PRNG. There is a race condition
5890 ** here such that two or more threads all trying to open databases at
5891 ** the same instant might all reset the PRNG. But multiple resets
5892 ** are harmless.
5893 */
drh5ac93652015-03-21 20:59:43 +00005894 if( randomnessPid!=osGetpid(0) ){
5895 randomnessPid = osGetpid(0);
drhb00d8622014-01-01 15:18:36 +00005896 sqlite3_randomness(0,0);
5897 }
dan08da86a2009-08-21 17:18:03 +00005898 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005899
dan08da86a2009-08-21 17:18:03 +00005900 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005901 UnixUnusedFd *pUnused;
5902 pUnused = findReusableFd(zName, flags);
5903 if( pUnused ){
5904 fd = pUnused->fd;
5905 }else{
drhf3cdcdc2015-04-29 16:50:28 +00005906 pUnused = sqlite3_malloc64(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005907 if( !pUnused ){
mistachkinfad30392016-02-13 23:43:46 +00005908 return SQLITE_NOMEM_BKPT;
dane946c392009-08-22 11:39:46 +00005909 }
5910 }
drhc68886b2017-08-18 16:09:52 +00005911 p->pPreallocatedUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005912
5913 /* Database filenames are double-zero terminated if they are not
5914 ** URIs with parameters. Hence, they can always be passed into
5915 ** sqlite3_uri_parameter(). */
5916 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5917
dan08da86a2009-08-21 17:18:03 +00005918 }else if( !zName ){
5919 /* If zName is NULL, the upper layer is requesting a temp file. */
drha803a2c2017-12-13 20:02:29 +00005920 assert(isDelete && !isNewJrnl);
drhb7e50ad2015-11-28 21:49:53 +00005921 rc = unixGetTempname(pVfs->mxPathname, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005922 if( rc!=SQLITE_OK ){
5923 return rc;
5924 }
5925 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005926
5927 /* Generated temporary filenames are always double-zero terminated
5928 ** for use by sqlite3_uri_parameter(). */
5929 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005930 }
5931
dan08da86a2009-08-21 17:18:03 +00005932 /* Determine the value of the flags parameter passed to POSIX function
5933 ** open(). These must be calculated even if open() is not called, as
5934 ** they may be stored as part of the file handle and used by the
5935 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005936 if( isReadonly ) openFlags |= O_RDONLY;
5937 if( isReadWrite ) openFlags |= O_RDWR;
5938 if( isCreate ) openFlags |= O_CREAT;
5939 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5940 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005941
danielk1977b4b47412007-08-17 15:53:36 +00005942 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005943 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005944 uid_t uid; /* Userid for the file */
5945 gid_t gid; /* Groupid for the file */
5946 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005947 if( rc!=SQLITE_OK ){
drhc68886b2017-08-18 16:09:52 +00005948 assert( !p->pPreallocatedUnused );
drh8ab58662010-07-15 18:38:39 +00005949 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005950 return rc;
5951 }
drhad4f1e52011-03-04 15:43:57 +00005952 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005953 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
drh5a2d9702015-11-26 02:21:05 +00005954 assert( !isExclusive || (openFlags & O_CREAT)!=0 );
dana688ca52018-01-10 11:56:03 +00005955 if( fd<0 ){
5956 if( isNewJrnl && errno==EACCES && osAccess(zName, F_OK) ){
5957 /* If unable to create a journal because the directory is not
5958 ** writable, change the error code to indicate that. */
5959 rc = SQLITE_READONLY_DIRECTORY;
5960 }else if( errno!=EISDIR && isReadWrite ){
5961 /* Failed to open the file for read/write access. Try read-only. */
5962 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
5963 openFlags &= ~(O_RDWR|O_CREAT);
5964 flags |= SQLITE_OPEN_READONLY;
5965 openFlags |= O_RDONLY;
5966 isReadonly = 1;
5967 fd = robust_open(zName, openFlags, openMode);
5968 }
dan08da86a2009-08-21 17:18:03 +00005969 }
5970 if( fd<0 ){
dana688ca52018-01-10 11:56:03 +00005971 int rc2 = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
5972 if( rc==SQLITE_OK ) rc = rc2;
dane946c392009-08-22 11:39:46 +00005973 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005974 }
drhac7c3ac2012-02-11 19:23:48 +00005975
5976 /* If this process is running as root and if creating a new rollback
5977 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005978 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005979 */
5980 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drh6226ca22015-11-24 15:06:28 +00005981 robustFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005982 }
danielk1977b4b47412007-08-17 15:53:36 +00005983 }
dan08da86a2009-08-21 17:18:03 +00005984 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005985 if( pOutFlags ){
5986 *pOutFlags = flags;
5987 }
5988
drhc68886b2017-08-18 16:09:52 +00005989 if( p->pPreallocatedUnused ){
5990 p->pPreallocatedUnused->fd = fd;
5991 p->pPreallocatedUnused->flags = flags;
dane946c392009-08-22 11:39:46 +00005992 }
5993
danielk1977b4b47412007-08-17 15:53:36 +00005994 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005995#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005996 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00005997#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
5998 zPath = sqlite3_mprintf("%s", zName);
5999 if( zPath==0 ){
6000 robust_close(p, fd, __LINE__);
mistachkinfad30392016-02-13 23:43:46 +00006001 return SQLITE_NOMEM_BKPT;
drh0bdbc902014-06-16 18:35:06 +00006002 }
chw97185482008-11-17 08:05:31 +00006003#else
drh036ac7f2011-08-08 23:18:05 +00006004 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00006005#endif
danielk1977b4b47412007-08-17 15:53:36 +00006006 }
drh41022642008-11-21 00:24:42 +00006007#if SQLITE_ENABLE_LOCKING_STYLE
6008 else{
dan08da86a2009-08-21 17:18:03 +00006009 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00006010 }
6011#endif
drh7ed97b92010-01-20 13:07:21 +00006012
6013#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00006014 if( fstatfs(fd, &fsInfo) == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00006015 storeLastErrno(p, errno);
drh0e9365c2011-03-02 02:08:13 +00006016 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006017 return SQLITE_IOERR_ACCESS;
6018 }
6019 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
6020 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
6021 }
drh4bf66fd2015-02-19 02:43:02 +00006022 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
6023 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
6024 }
drh7ed97b92010-01-20 13:07:21 +00006025#endif
drhc02a43a2012-01-10 23:18:38 +00006026
6027 /* Set up appropriate ctrlFlags */
6028 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
6029 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
drh86151e82015-12-08 14:37:16 +00006030 noLock = eType!=SQLITE_OPEN_MAIN_DB;
drhc02a43a2012-01-10 23:18:38 +00006031 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
drha803a2c2017-12-13 20:02:29 +00006032 if( isNewJrnl ) ctrlFlags |= UNIXFILE_DIRSYNC;
drhc02a43a2012-01-10 23:18:38 +00006033 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
6034
drh7ed97b92010-01-20 13:07:21 +00006035#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00006036#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00006037 isAutoProxy = 1;
6038#endif
6039 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00006040 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
6041 int useProxy = 0;
6042
dan08da86a2009-08-21 17:18:03 +00006043 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
6044 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00006045 if( envforce!=NULL ){
6046 useProxy = atoi(envforce)>0;
6047 }else{
aswiftaebf4132008-11-21 00:10:35 +00006048 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
6049 }
6050 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00006051 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00006052 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006053 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00006054 if( rc!=SQLITE_OK ){
6055 /* Use unixClose to clean up the resources added in fillInUnixFile
6056 ** and clear all the structure's references. Specifically,
6057 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
6058 */
6059 unixClose(pFile);
6060 return rc;
6061 }
aswiftaebf4132008-11-21 00:10:35 +00006062 }
dane946c392009-08-22 11:39:46 +00006063 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00006064 }
6065 }
6066#endif
6067
dan3ed0f1c2017-09-14 21:12:07 +00006068 assert( zPath==0 || zPath[0]=='/'
6069 || eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL
6070 );
drhc02a43a2012-01-10 23:18:38 +00006071 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
6072
dane946c392009-08-22 11:39:46 +00006073open_finished:
6074 if( rc!=SQLITE_OK ){
drhc68886b2017-08-18 16:09:52 +00006075 sqlite3_free(p->pPreallocatedUnused);
dane946c392009-08-22 11:39:46 +00006076 }
6077 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00006078}
6079
dane946c392009-08-22 11:39:46 +00006080
danielk1977b4b47412007-08-17 15:53:36 +00006081/*
danielk1977fee2d252007-08-18 10:59:19 +00006082** Delete the file at zPath. If the dirSync argument is true, fsync()
6083** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00006084*/
drh6b9d6dd2008-12-03 19:34:47 +00006085static int unixDelete(
6086 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
6087 const char *zPath, /* Name of file to be deleted */
6088 int dirSync /* If true, fsync() directory after deleting file */
6089){
danielk1977fee2d252007-08-18 10:59:19 +00006090 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00006091 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006092 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00006093 if( osUnlink(zPath)==(-1) ){
drhbd945542014-08-13 11:39:42 +00006094 if( errno==ENOENT
6095#if OS_VXWORKS
drh19541f32014-09-01 13:37:55 +00006096 || osAccess(zPath,0)!=0
drhbd945542014-08-13 11:39:42 +00006097#endif
6098 ){
dan9fc5b4a2012-11-09 20:17:26 +00006099 rc = SQLITE_IOERR_DELETE_NOENT;
6100 }else{
drhb4308162012-11-09 21:40:02 +00006101 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00006102 }
drhb4308162012-11-09 21:40:02 +00006103 return rc;
drh5d4feff2010-07-14 01:45:22 +00006104 }
danielk1977d39fa702008-10-16 13:27:40 +00006105#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00006106 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00006107 int fd;
drh90315a22011-08-10 01:52:12 +00006108 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00006109 if( rc==SQLITE_OK ){
drh6d258992016-02-04 09:48:12 +00006110 if( full_fsync(fd,0,0) ){
dane18d4952011-02-21 11:46:24 +00006111 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00006112 }
drh0e9365c2011-03-02 02:08:13 +00006113 robust_close(0, fd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00006114 }else{
6115 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00006116 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00006117 }
6118 }
danielk1977d138dd82008-10-15 16:02:48 +00006119#endif
danielk1977fee2d252007-08-18 10:59:19 +00006120 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00006121}
6122
danielk197790949c22007-08-17 16:50:38 +00006123/*
mistachkin48864df2013-03-21 21:20:32 +00006124** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00006125** test performed depends on the value of flags:
6126**
6127** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
6128** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
6129** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
6130**
6131** Otherwise return 0.
6132*/
danielk1977861f7452008-06-05 11:39:11 +00006133static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00006134 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
6135 const char *zPath, /* Path of the file to examine */
6136 int flags, /* What do we want to learn about the zPath file? */
6137 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00006138){
danielk1977397d65f2008-11-19 11:35:39 +00006139 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00006140 SimulateIOError( return SQLITE_IOERR_ACCESS; );
drhd260b5b2015-11-25 18:03:33 +00006141 assert( pResOut!=0 );
danielk1977b4b47412007-08-17 15:53:36 +00006142
drhd260b5b2015-11-25 18:03:33 +00006143 /* The spec says there are three possible values for flags. But only
6144 ** two of them are actually used */
6145 assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
6146
6147 if( flags==SQLITE_ACCESS_EXISTS ){
dan83acd422010-06-18 11:10:06 +00006148 struct stat buf;
drhd260b5b2015-11-25 18:03:33 +00006149 *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
6150 }else{
6151 *pResOut = osAccess(zPath, W_OK|R_OK)==0;
dan83acd422010-06-18 11:10:06 +00006152 }
danielk1977861f7452008-06-05 11:39:11 +00006153 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006154}
6155
danielk1977b4b47412007-08-17 15:53:36 +00006156/*
danielk1977b4b47412007-08-17 15:53:36 +00006157**
danielk1977b4b47412007-08-17 15:53:36 +00006158*/
dane88ec182016-01-25 17:04:48 +00006159static int mkFullPathname(
dancaf6b152016-01-25 18:05:49 +00006160 const char *zPath, /* Input path */
6161 char *zOut, /* Output buffer */
dane88ec182016-01-25 17:04:48 +00006162 int nOut /* Allocated size of buffer zOut */
danielk1977adfb9b02007-09-17 07:02:56 +00006163){
dancaf6b152016-01-25 18:05:49 +00006164 int nPath = sqlite3Strlen30(zPath);
6165 int iOff = 0;
6166 if( zPath[0]!='/' ){
6167 if( osGetcwd(zOut, nOut-2)==0 ){
dane18d4952011-02-21 11:46:24 +00006168 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006169 }
dancaf6b152016-01-25 18:05:49 +00006170 iOff = sqlite3Strlen30(zOut);
6171 zOut[iOff++] = '/';
danielk1977b4b47412007-08-17 15:53:36 +00006172 }
dan23496702016-01-26 13:56:42 +00006173 if( (iOff+nPath+1)>nOut ){
6174 /* SQLite assumes that xFullPathname() nul-terminates the output buffer
6175 ** even if it returns an error. */
6176 zOut[iOff] = '\0';
6177 return SQLITE_CANTOPEN_BKPT;
6178 }
dancaf6b152016-01-25 18:05:49 +00006179 sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006180 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006181}
6182
dane88ec182016-01-25 17:04:48 +00006183/*
6184** Turn a relative pathname into a full pathname. The relative path
6185** is stored as a nul-terminated string in the buffer pointed to by
6186** zPath.
6187**
6188** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
6189** (in this case, MAX_PATHNAME bytes). The full-path is written to
6190** this buffer before returning.
6191*/
6192static int unixFullPathname(
6193 sqlite3_vfs *pVfs, /* Pointer to vfs object */
6194 const char *zPath, /* Possibly relative input path */
6195 int nOut, /* Size of output buffer in bytes */
6196 char *zOut /* Output buffer */
6197){
danaf1b36b2016-01-25 18:43:05 +00006198#if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
dancaf6b152016-01-25 18:05:49 +00006199 return mkFullPathname(zPath, zOut, nOut);
dane88ec182016-01-25 17:04:48 +00006200#else
6201 int rc = SQLITE_OK;
6202 int nByte;
dancaf6b152016-01-25 18:05:49 +00006203 int nLink = 1; /* Number of symbolic links followed so far */
dane88ec182016-01-25 17:04:48 +00006204 const char *zIn = zPath; /* Input path for each iteration of loop */
6205 char *zDel = 0;
6206
6207 assert( pVfs->mxPathname==MAX_PATHNAME );
6208 UNUSED_PARAMETER(pVfs);
6209
6210 /* It's odd to simulate an io-error here, but really this is just
6211 ** using the io-error infrastructure to test that SQLite handles this
6212 ** function failing. This function could fail if, for example, the
6213 ** current working directory has been unlinked.
6214 */
6215 SimulateIOError( return SQLITE_ERROR );
6216
6217 do {
6218
dancaf6b152016-01-25 18:05:49 +00006219 /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
6220 ** link, or false otherwise. */
6221 int bLink = 0;
6222 struct stat buf;
6223 if( osLstat(zIn, &buf)!=0 ){
6224 if( errno!=ENOENT ){
danaf1b36b2016-01-25 18:43:05 +00006225 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
dane88ec182016-01-25 17:04:48 +00006226 }
dane88ec182016-01-25 17:04:48 +00006227 }else{
dancaf6b152016-01-25 18:05:49 +00006228 bLink = S_ISLNK(buf.st_mode);
6229 }
6230
6231 if( bLink ){
dane88ec182016-01-25 17:04:48 +00006232 if( zDel==0 ){
6233 zDel = sqlite3_malloc(nOut);
mistachkinfad30392016-02-13 23:43:46 +00006234 if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
dancaf6b152016-01-25 18:05:49 +00006235 }else if( ++nLink>SQLITE_MAX_SYMLINKS ){
6236 rc = SQLITE_CANTOPEN_BKPT;
dane88ec182016-01-25 17:04:48 +00006237 }
dancaf6b152016-01-25 18:05:49 +00006238
6239 if( rc==SQLITE_OK ){
6240 nByte = osReadlink(zIn, zDel, nOut-1);
6241 if( nByte<0 ){
6242 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
dan23496702016-01-26 13:56:42 +00006243 }else{
6244 if( zDel[0]!='/' ){
6245 int n;
6246 for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
6247 if( nByte+n+1>nOut ){
6248 rc = SQLITE_CANTOPEN_BKPT;
6249 }else{
6250 memmove(&zDel[n], zDel, nByte+1);
6251 memcpy(zDel, zIn, n);
6252 nByte += n;
6253 }
dancaf6b152016-01-25 18:05:49 +00006254 }
6255 zDel[nByte] = '\0';
6256 }
6257 }
6258
6259 zIn = zDel;
dane88ec182016-01-25 17:04:48 +00006260 }
6261
dan23496702016-01-26 13:56:42 +00006262 assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
6263 if( rc==SQLITE_OK && zIn!=zOut ){
dancaf6b152016-01-25 18:05:49 +00006264 rc = mkFullPathname(zIn, zOut, nOut);
dane88ec182016-01-25 17:04:48 +00006265 }
dancaf6b152016-01-25 18:05:49 +00006266 if( bLink==0 ) break;
6267 zIn = zOut;
6268 }while( rc==SQLITE_OK );
dane88ec182016-01-25 17:04:48 +00006269
6270 sqlite3_free(zDel);
6271 return rc;
danaf1b36b2016-01-25 18:43:05 +00006272#endif /* HAVE_READLINK && HAVE_LSTAT */
dane88ec182016-01-25 17:04:48 +00006273}
6274
drh0ccebe72005-06-07 22:22:50 +00006275
drh761df872006-12-21 01:29:22 +00006276#ifndef SQLITE_OMIT_LOAD_EXTENSION
6277/*
6278** Interfaces for opening a shared library, finding entry points
6279** within the shared library, and closing the shared library.
6280*/
6281#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00006282static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6283 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00006284 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6285}
danielk197795c8a542007-09-01 06:51:27 +00006286
6287/*
6288** SQLite calls this function immediately after a call to unixDlSym() or
6289** unixDlOpen() fails (returns a null pointer). If a more detailed error
6290** message is available, it is written to zBufOut. If no error message
6291** is available, zBufOut is left unmodified and SQLite uses a default
6292** error message.
6293*/
danielk1977397d65f2008-11-19 11:35:39 +00006294static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006295 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006296 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006297 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006298 zErr = dlerror();
6299 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006300 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006301 }
drh6c7d5c52008-11-21 20:32:33 +00006302 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006303}
drh1875f7a2008-12-08 18:19:17 +00006304static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6305 /*
6306 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6307 ** cast into a pointer to a function. And yet the library dlsym() routine
6308 ** returns a void* which is really a pointer to a function. So how do we
6309 ** use dlsym() with -pedantic-errors?
6310 **
6311 ** Variable x below is defined to be a pointer to a function taking
6312 ** parameters void* and const char* and returning a pointer to a function.
6313 ** We initialize x by assigning it a pointer to the dlsym() function.
6314 ** (That assignment requires a cast.) Then we call the function that
6315 ** x points to.
6316 **
6317 ** This work-around is unlikely to work correctly on any system where
6318 ** you really cannot cast a function pointer into void*. But then, on the
6319 ** other hand, dlsym() will not work on such a system either, so we have
6320 ** not really lost anything.
6321 */
6322 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006323 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006324 x = (void(*(*)(void*,const char*))(void))dlsym;
6325 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006326}
danielk1977397d65f2008-11-19 11:35:39 +00006327static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6328 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006329 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006330}
danielk1977b4b47412007-08-17 15:53:36 +00006331#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6332 #define unixDlOpen 0
6333 #define unixDlError 0
6334 #define unixDlSym 0
6335 #define unixDlClose 0
6336#endif
6337
6338/*
danielk197790949c22007-08-17 16:50:38 +00006339** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006340*/
danielk1977397d65f2008-11-19 11:35:39 +00006341static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6342 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006343 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006344
drhbbd42a62004-05-22 17:41:58 +00006345 /* We have to initialize zBuf to prevent valgrind from reporting
6346 ** errors. The reports issued by valgrind are incorrect - we would
6347 ** prefer that the randomness be increased by making use of the
6348 ** uninitialized space in zBuf - but valgrind errors tend to worry
6349 ** some users. Rather than argue, it seems easier just to initialize
6350 ** the whole array and silence valgrind, even if that means less randomness
6351 ** in the random seed.
6352 **
6353 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006354 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006355 ** tests repeatable.
6356 */
danielk1977b4b47412007-08-17 15:53:36 +00006357 memset(zBuf, 0, nBuf);
drh5ac93652015-03-21 20:59:43 +00006358 randomnessPid = osGetpid(0);
drh6a412b82015-04-30 12:31:49 +00006359#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
drhbbd42a62004-05-22 17:41:58 +00006360 {
drhb00d8622014-01-01 15:18:36 +00006361 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006362 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006363 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006364 time_t t;
6365 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006366 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006367 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6368 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6369 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006370 }else{
drhc18b4042012-02-10 03:10:27 +00006371 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006372 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006373 }
drhbbd42a62004-05-22 17:41:58 +00006374 }
6375#endif
drh72cbd072008-10-14 17:58:38 +00006376 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006377}
6378
danielk1977b4b47412007-08-17 15:53:36 +00006379
drhbbd42a62004-05-22 17:41:58 +00006380/*
6381** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006382** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006383** The return value is the number of microseconds of sleep actually
6384** requested from the underlying operating system, a number which
6385** might be greater than or equal to the argument, but not less
6386** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006387*/
danielk1977397d65f2008-11-19 11:35:39 +00006388static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006389#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006390 struct timespec sp;
6391
6392 sp.tv_sec = microseconds / 1000000;
6393 sp.tv_nsec = (microseconds % 1000000) * 1000;
6394 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006395 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006396 return microseconds;
6397#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006398 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006399 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006400 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006401#else
danielk1977b4b47412007-08-17 15:53:36 +00006402 int seconds = (microseconds+999999)/1000000;
6403 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006404 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006405 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006406#endif
drh88f474a2006-01-02 20:00:12 +00006407}
6408
6409/*
drh6b9d6dd2008-12-03 19:34:47 +00006410** The following variable, if set to a non-zero value, is interpreted as
6411** the number of seconds since 1970 and is used to set the result of
6412** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006413*/
6414#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006415int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006416#endif
6417
6418/*
drhb7e8ea22010-05-03 14:32:30 +00006419** Find the current time (in Universal Coordinated Time). Write into *piNow
6420** the current time and date as a Julian Day number times 86_400_000. In
6421** other words, write into *piNow the number of milliseconds since the Julian
6422** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6423** proleptic Gregorian calendar.
6424**
drh31702252011-10-12 23:13:43 +00006425** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6426** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006427*/
6428static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6429 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006430 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006431#if defined(NO_GETTOD)
6432 time_t t;
6433 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006434 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006435#elif OS_VXWORKS
6436 struct timespec sNow;
6437 clock_gettime(CLOCK_REALTIME, &sNow);
6438 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6439#else
6440 struct timeval sNow;
drh970942e2015-11-25 23:13:14 +00006441 (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
6442 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
drhb7e8ea22010-05-03 14:32:30 +00006443#endif
6444
6445#ifdef SQLITE_TEST
6446 if( sqlite3_current_time ){
6447 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6448 }
6449#endif
6450 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006451 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006452}
6453
drhc3dfa5e2016-01-22 19:44:03 +00006454#ifndef SQLITE_OMIT_DEPRECATED
drhb7e8ea22010-05-03 14:32:30 +00006455/*
drhbbd42a62004-05-22 17:41:58 +00006456** Find the current time (in Universal Coordinated Time). Write the
6457** current time and date as a Julian Day number into *prNow and
6458** return 0. Return 1 if the time and date cannot be found.
6459*/
danielk1977397d65f2008-11-19 11:35:39 +00006460static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006461 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006462 int rc;
drhff828942010-06-26 21:34:06 +00006463 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006464 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006465 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006466 return rc;
drhbbd42a62004-05-22 17:41:58 +00006467}
drh5337dac2015-11-25 15:15:03 +00006468#else
6469# define unixCurrentTime 0
6470#endif
danielk1977b4b47412007-08-17 15:53:36 +00006471
drh6b9d6dd2008-12-03 19:34:47 +00006472/*
drh1b9f2142016-03-17 16:01:23 +00006473** The xGetLastError() method is designed to return a better
6474** low-level error message when operating-system problems come up
6475** during SQLite operation. Only the integer return code is currently
6476** used.
drh6b9d6dd2008-12-03 19:34:47 +00006477*/
danielk1977397d65f2008-11-19 11:35:39 +00006478static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6479 UNUSED_PARAMETER(NotUsed);
6480 UNUSED_PARAMETER(NotUsed2);
6481 UNUSED_PARAMETER(NotUsed3);
drh1b9f2142016-03-17 16:01:23 +00006482 return errno;
danielk1977bcb97fe2008-06-06 15:49:29 +00006483}
6484
drhf2424c52010-04-26 00:04:55 +00006485
6486/*
drh734c9862008-11-28 15:37:20 +00006487************************ End of sqlite3_vfs methods ***************************
6488******************************************************************************/
6489
drh715ff302008-12-03 22:32:44 +00006490/******************************************************************************
6491************************** Begin Proxy Locking ********************************
6492**
6493** Proxy locking is a "uber-locking-method" in this sense: It uses the
6494** other locking methods on secondary lock files. Proxy locking is a
6495** meta-layer over top of the primitive locking implemented above. For
6496** this reason, the division that implements of proxy locking is deferred
6497** until late in the file (here) after all of the other I/O methods have
6498** been defined - so that the primitive locking methods are available
6499** as services to help with the implementation of proxy locking.
6500**
6501****
6502**
6503** The default locking schemes in SQLite use byte-range locks on the
6504** database file to coordinate safe, concurrent access by multiple readers
6505** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6506** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6507** as POSIX read & write locks over fixed set of locations (via fsctl),
6508** on AFP and SMB only exclusive byte-range locks are available via fsctl
6509** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6510** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6511** address in the shared range is taken for a SHARED lock, the entire
6512** shared range is taken for an EXCLUSIVE lock):
6513**
drhf2f105d2012-08-20 15:53:54 +00006514** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006515** RESERVED_BYTE 0x40000001
6516** SHARED_RANGE 0x40000002 -> 0x40000200
6517**
6518** This works well on the local file system, but shows a nearly 100x
6519** slowdown in read performance on AFP because the AFP client disables
6520** the read cache when byte-range locks are present. Enabling the read
6521** cache exposes a cache coherency problem that is present on all OS X
6522** supported network file systems. NFS and AFP both observe the
6523** close-to-open semantics for ensuring cache coherency
6524** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6525** address the requirements for concurrent database access by multiple
6526** readers and writers
6527** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6528**
6529** To address the performance and cache coherency issues, proxy file locking
6530** changes the way database access is controlled by limiting access to a
6531** single host at a time and moving file locks off of the database file
6532** and onto a proxy file on the local file system.
6533**
6534**
6535** Using proxy locks
6536** -----------------
6537**
6538** C APIs
6539**
drh4bf66fd2015-02-19 02:43:02 +00006540** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
drh715ff302008-12-03 22:32:44 +00006541** <proxy_path> | ":auto:");
drh4bf66fd2015-02-19 02:43:02 +00006542** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6543** &<proxy_path>);
drh715ff302008-12-03 22:32:44 +00006544**
6545**
6546** SQL pragmas
6547**
6548** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6549** PRAGMA [database.]lock_proxy_file
6550**
6551** Specifying ":auto:" means that if there is a conch file with a matching
6552** host ID in it, the proxy path in the conch file will be used, otherwise
6553** a proxy path based on the user's temp dir
6554** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6555** actual proxy file name is generated from the name and path of the
6556** database file. For example:
6557**
6558** For database path "/Users/me/foo.db"
6559** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6560**
6561** Once a lock proxy is configured for a database connection, it can not
6562** be removed, however it may be switched to a different proxy path via
6563** the above APIs (assuming the conch file is not being held by another
6564** connection or process).
6565**
6566**
6567** How proxy locking works
6568** -----------------------
6569**
6570** Proxy file locking relies primarily on two new supporting files:
6571**
6572** * conch file to limit access to the database file to a single host
6573** at a time
6574**
6575** * proxy file to act as a proxy for the advisory locks normally
6576** taken on the database
6577**
6578** The conch file - to use a proxy file, sqlite must first "hold the conch"
6579** by taking an sqlite-style shared lock on the conch file, reading the
6580** contents and comparing the host's unique host ID (see below) and lock
6581** proxy path against the values stored in the conch. The conch file is
6582** stored in the same directory as the database file and the file name
6583** is patterned after the database file name as ".<databasename>-conch".
peter.d.reid60ec9142014-09-06 16:39:46 +00006584** If the conch file does not exist, or its contents do not match the
drh715ff302008-12-03 22:32:44 +00006585** host ID and/or proxy path, then the lock is escalated to an exclusive
6586** lock and the conch file contents is updated with the host ID and proxy
6587** path and the lock is downgraded to a shared lock again. If the conch
6588** is held by another process (with a shared lock), the exclusive lock
6589** will fail and SQLITE_BUSY is returned.
6590**
6591** The proxy file - a single-byte file used for all advisory file locks
6592** normally taken on the database file. This allows for safe sharing
6593** of the database file for multiple readers and writers on the same
6594** host (the conch ensures that they all use the same local lock file).
6595**
drh715ff302008-12-03 22:32:44 +00006596** Requesting the lock proxy does not immediately take the conch, it is
6597** only taken when the first request to lock database file is made.
6598** This matches the semantics of the traditional locking behavior, where
6599** opening a connection to a database file does not take a lock on it.
6600** The shared lock and an open file descriptor are maintained until
6601** the connection to the database is closed.
6602**
6603** The proxy file and the lock file are never deleted so they only need
6604** to be created the first time they are used.
6605**
6606** Configuration options
6607** ---------------------
6608**
6609** SQLITE_PREFER_PROXY_LOCKING
6610**
6611** Database files accessed on non-local file systems are
6612** automatically configured for proxy locking, lock files are
6613** named automatically using the same logic as
6614** PRAGMA lock_proxy_file=":auto:"
6615**
6616** SQLITE_PROXY_DEBUG
6617**
6618** Enables the logging of error messages during host id file
6619** retrieval and creation
6620**
drh715ff302008-12-03 22:32:44 +00006621** LOCKPROXYDIR
6622**
6623** Overrides the default directory used for lock proxy files that
6624** are named automatically via the ":auto:" setting
6625**
6626** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6627**
6628** Permissions to use when creating a directory for storing the
6629** lock proxy files, only used when LOCKPROXYDIR is not set.
6630**
6631**
6632** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6633** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6634** force proxy locking to be used for every database file opened, and 0
6635** will force automatic proxy locking to be disabled for all database
drh4bf66fd2015-02-19 02:43:02 +00006636** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
drh715ff302008-12-03 22:32:44 +00006637** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6638*/
6639
6640/*
6641** Proxy locking is only available on MacOSX
6642*/
drhd2cb50b2009-01-09 21:41:17 +00006643#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006644
drh715ff302008-12-03 22:32:44 +00006645/*
6646** The proxyLockingContext has the path and file structures for the remote
6647** and local proxy files in it
6648*/
6649typedef struct proxyLockingContext proxyLockingContext;
6650struct proxyLockingContext {
6651 unixFile *conchFile; /* Open conch file */
6652 char *conchFilePath; /* Name of the conch file */
6653 unixFile *lockProxy; /* Open proxy lock file */
6654 char *lockProxyPath; /* Name of the proxy lock file */
6655 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006656 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh4bf66fd2015-02-19 02:43:02 +00006657 int nFails; /* Number of conch taking failures */
drh715ff302008-12-03 22:32:44 +00006658 void *oldLockingContext; /* Original lockingcontext to restore on close */
6659 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6660};
6661
drh7ed97b92010-01-20 13:07:21 +00006662/*
6663** The proxy lock file path for the database at dbPath is written into lPath,
6664** which must point to valid, writable memory large enough for a maxLen length
6665** file path.
drh715ff302008-12-03 22:32:44 +00006666*/
drh715ff302008-12-03 22:32:44 +00006667static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6668 int len;
6669 int dbLen;
6670 int i;
6671
6672#ifdef LOCKPROXYDIR
6673 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6674#else
6675# ifdef _CS_DARWIN_USER_TEMP_DIR
6676 {
drh7ed97b92010-01-20 13:07:21 +00006677 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006678 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006679 lPath, errno, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006680 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006681 }
drh7ed97b92010-01-20 13:07:21 +00006682 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006683 }
6684# else
6685 len = strlcpy(lPath, "/tmp/", maxLen);
6686# endif
6687#endif
6688
6689 if( lPath[len-1]!='/' ){
6690 len = strlcat(lPath, "/", maxLen);
6691 }
6692
6693 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006694 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006695 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006696 char c = dbPath[i];
6697 lPath[i+len] = (c=='/')?'_':c;
6698 }
6699 lPath[i+len]='\0';
6700 strlcat(lPath, ":auto:", maxLen);
drh5ac93652015-03-21 20:59:43 +00006701 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006702 return SQLITE_OK;
6703}
6704
drh7ed97b92010-01-20 13:07:21 +00006705/*
6706 ** Creates the lock file and any missing directories in lockPath
6707 */
6708static int proxyCreateLockPath(const char *lockPath){
6709 int i, len;
6710 char buf[MAXPATHLEN];
6711 int start = 0;
6712
6713 assert(lockPath!=NULL);
6714 /* try to create all the intermediate directories */
6715 len = (int)strlen(lockPath);
6716 buf[0] = lockPath[0];
6717 for( i=1; i<len; i++ ){
6718 if( lockPath[i] == '/' && (i - start > 0) ){
6719 /* only mkdir if leaf dir != "." or "/" or ".." */
6720 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6721 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6722 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006723 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006724 int err=errno;
6725 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006726 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006727 "'%s' proxy lock path=%s pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006728 buf, strerror(err), lockPath, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006729 return err;
6730 }
6731 }
6732 }
6733 start=i+1;
6734 }
6735 buf[i] = lockPath[i];
6736 }
drh62aaa6c2015-11-21 17:27:42 +00006737 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006738 return 0;
6739}
6740
drh715ff302008-12-03 22:32:44 +00006741/*
6742** Create a new VFS file descriptor (stored in memory obtained from
6743** sqlite3_malloc) and open the file named "path" in the file descriptor.
6744**
6745** The caller is responsible not only for closing the file descriptor
6746** but also for freeing the memory associated with the file descriptor.
6747*/
drh7ed97b92010-01-20 13:07:21 +00006748static int proxyCreateUnixFile(
6749 const char *path, /* path for the new unixFile */
6750 unixFile **ppFile, /* unixFile created and returned by ref */
6751 int islockfile /* if non zero missing dirs will be created */
6752) {
6753 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006754 unixFile *pNew;
6755 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006756 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006757 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006758 int terrno = 0;
6759 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006760
drh7ed97b92010-01-20 13:07:21 +00006761 /* 1. first try to open/create the file
6762 ** 2. if that fails, and this is a lock file (not-conch), try creating
6763 ** the parent directories and then try again.
6764 ** 3. if that fails, try to open the file read-only
6765 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6766 */
6767 pUnused = findReusableFd(path, openFlags);
6768 if( pUnused ){
6769 fd = pUnused->fd;
6770 }else{
drhf3cdcdc2015-04-29 16:50:28 +00006771 pUnused = sqlite3_malloc64(sizeof(*pUnused));
drh7ed97b92010-01-20 13:07:21 +00006772 if( !pUnused ){
mistachkinfad30392016-02-13 23:43:46 +00006773 return SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006774 }
6775 }
6776 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006777 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006778 terrno = errno;
6779 if( fd<0 && errno==ENOENT && islockfile ){
6780 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006781 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006782 }
6783 }
6784 }
6785 if( fd<0 ){
6786 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006787 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006788 terrno = errno;
6789 }
6790 if( fd<0 ){
6791 if( islockfile ){
6792 return SQLITE_BUSY;
6793 }
6794 switch (terrno) {
6795 case EACCES:
6796 return SQLITE_PERM;
6797 case EIO:
6798 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6799 default:
drh9978c972010-02-23 17:36:32 +00006800 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006801 }
6802 }
6803
drhf3cdcdc2015-04-29 16:50:28 +00006804 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
drh7ed97b92010-01-20 13:07:21 +00006805 if( pNew==NULL ){
mistachkinfad30392016-02-13 23:43:46 +00006806 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006807 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006808 }
6809 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006810 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006811 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006812 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006813 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006814 pUnused->fd = fd;
6815 pUnused->flags = openFlags;
drhc68886b2017-08-18 16:09:52 +00006816 pNew->pPreallocatedUnused = pUnused;
drh7ed97b92010-01-20 13:07:21 +00006817
drhc02a43a2012-01-10 23:18:38 +00006818 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006819 if( rc==SQLITE_OK ){
6820 *ppFile = pNew;
6821 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006822 }
drh7ed97b92010-01-20 13:07:21 +00006823end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006824 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006825 sqlite3_free(pNew);
6826 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006827 return rc;
6828}
6829
drh7ed97b92010-01-20 13:07:21 +00006830#ifdef SQLITE_TEST
6831/* simulate multiple hosts by creating unique hostid file paths */
6832int sqlite3_hostid_num = 0;
6833#endif
6834
6835#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6836
drh6bca6512015-04-13 23:05:28 +00006837#ifdef HAVE_GETHOSTUUID
drh0ab216a2010-07-02 17:10:40 +00006838/* Not always defined in the headers as it ought to be */
6839extern int gethostuuid(uuid_t id, const struct timespec *wait);
drh6bca6512015-04-13 23:05:28 +00006840#endif
drh0ab216a2010-07-02 17:10:40 +00006841
drh7ed97b92010-01-20 13:07:21 +00006842/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6843** bytes of writable memory.
6844*/
6845static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006846 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6847 memset(pHostID, 0, PROXY_HOSTIDLEN);
drh6bca6512015-04-13 23:05:28 +00006848#ifdef HAVE_GETHOSTUUID
drh29ecd8a2010-12-21 00:16:40 +00006849 {
drh4bf66fd2015-02-19 02:43:02 +00006850 struct timespec timeout = {1, 0}; /* 1 sec timeout */
drh29ecd8a2010-12-21 00:16:40 +00006851 if( gethostuuid(pHostID, &timeout) ){
6852 int err = errno;
6853 if( pError ){
6854 *pError = err;
6855 }
6856 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006857 }
drh7ed97b92010-01-20 13:07:21 +00006858 }
drh3d4435b2011-08-26 20:55:50 +00006859#else
6860 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006861#endif
drh7ed97b92010-01-20 13:07:21 +00006862#ifdef SQLITE_TEST
6863 /* simulate multiple hosts by creating unique hostid file paths */
6864 if( sqlite3_hostid_num != 0){
6865 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6866 }
6867#endif
6868
6869 return SQLITE_OK;
6870}
6871
6872/* The conch file contains the header, host id and lock file path
6873 */
6874#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6875#define PROXY_HEADERLEN 1 /* conch file header length */
6876#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6877#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6878
6879/*
6880** Takes an open conch file, copies the contents to a new path and then moves
6881** it back. The newly created file's file descriptor is assigned to the
6882** conch file structure and finally the original conch file descriptor is
6883** closed. Returns zero if successful.
6884*/
6885static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6886 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6887 unixFile *conchFile = pCtx->conchFile;
6888 char tPath[MAXPATHLEN];
6889 char buf[PROXY_MAXCONCHLEN];
6890 char *cPath = pCtx->conchFilePath;
6891 size_t readLen = 0;
6892 size_t pathLen = 0;
6893 char errmsg[64] = "";
6894 int fd = -1;
6895 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006896 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006897
6898 /* create a new path by replace the trailing '-conch' with '-break' */
6899 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6900 if( pathLen>MAXPATHLEN || pathLen<6 ||
6901 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006902 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006903 goto end_breaklock;
6904 }
6905 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006906 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006907 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006908 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006909 goto end_breaklock;
6910 }
6911 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006912 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006913 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006914 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006915 goto end_breaklock;
6916 }
drhe562be52011-03-02 18:01:10 +00006917 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006918 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006919 goto end_breaklock;
6920 }
6921 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006922 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006923 goto end_breaklock;
6924 }
6925 rc = 0;
6926 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006927 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006928 conchFile->h = fd;
6929 conchFile->openFlags = O_RDWR | O_CREAT;
6930
6931end_breaklock:
6932 if( rc ){
6933 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006934 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006935 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006936 }
6937 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6938 }
6939 return rc;
6940}
6941
6942/* Take the requested lock on the conch file and break a stale lock if the
6943** host id matches.
6944*/
6945static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6946 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6947 unixFile *conchFile = pCtx->conchFile;
6948 int rc = SQLITE_OK;
6949 int nTries = 0;
6950 struct timespec conchModTime;
6951
drh3d4435b2011-08-26 20:55:50 +00006952 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006953 do {
6954 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6955 nTries ++;
6956 if( rc==SQLITE_BUSY ){
6957 /* If the lock failed (busy):
6958 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6959 * 2nd try: fail if the mod time changed or host id is different, wait
6960 * 10 sec and try again
6961 * 3rd try: break the lock unless the mod time has changed.
6962 */
6963 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006964 if( osFstat(conchFile->h, &buf) ){
drh4bf66fd2015-02-19 02:43:02 +00006965 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006966 return SQLITE_IOERR_LOCK;
6967 }
6968
6969 if( nTries==1 ){
6970 conchModTime = buf.st_mtimespec;
6971 usleep(500000); /* wait 0.5 sec and try the lock again*/
6972 continue;
6973 }
6974
6975 assert( nTries>1 );
6976 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6977 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6978 return SQLITE_BUSY;
6979 }
6980
6981 if( nTries==2 ){
6982 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006983 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006984 if( len<0 ){
drh4bf66fd2015-02-19 02:43:02 +00006985 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006986 return SQLITE_IOERR_LOCK;
6987 }
6988 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6989 /* don't break the lock if the host id doesn't match */
6990 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6991 return SQLITE_BUSY;
6992 }
6993 }else{
6994 /* don't break the lock on short read or a version mismatch */
6995 return SQLITE_BUSY;
6996 }
6997 usleep(10000000); /* wait 10 sec and try the lock again */
6998 continue;
6999 }
7000
7001 assert( nTries==3 );
7002 if( 0==proxyBreakConchLock(pFile, myHostID) ){
7003 rc = SQLITE_OK;
7004 if( lockType==EXCLUSIVE_LOCK ){
drhe6d41732015-02-21 00:49:00 +00007005 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
drh7ed97b92010-01-20 13:07:21 +00007006 }
7007 if( !rc ){
7008 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
7009 }
7010 }
7011 }
7012 } while( rc==SQLITE_BUSY && nTries<3 );
7013
7014 return rc;
7015}
7016
7017/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00007018** lockPath is non-NULL, the host ID and lock file path must match. A NULL
7019** lockPath means that the lockPath in the conch file will be used if the
7020** host IDs match, or a new lock path will be generated automatically
7021** and written to the conch file.
7022*/
7023static int proxyTakeConch(unixFile *pFile){
7024 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7025
drh7ed97b92010-01-20 13:07:21 +00007026 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00007027 return SQLITE_OK;
7028 }else{
7029 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00007030 uuid_t myHostID;
7031 int pError = 0;
7032 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00007033 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00007034 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00007035 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00007036 int createConch = 0;
7037 int hostIdMatch = 0;
7038 int readLen = 0;
7039 int tryOldLockPath = 0;
7040 int forceNewLockPath = 0;
7041
drh308c2a52010-05-14 11:30:18 +00007042 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
drh91eb93c2015-03-03 19:56:20 +00007043 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00007044 osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007045
drh7ed97b92010-01-20 13:07:21 +00007046 rc = proxyGetHostID(myHostID, &pError);
7047 if( (rc&0xff)==SQLITE_IOERR ){
drh4bf66fd2015-02-19 02:43:02 +00007048 storeLastErrno(pFile, pError);
drh7ed97b92010-01-20 13:07:21 +00007049 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00007050 }
drh7ed97b92010-01-20 13:07:21 +00007051 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00007052 if( rc!=SQLITE_OK ){
7053 goto end_takeconch;
7054 }
drh7ed97b92010-01-20 13:07:21 +00007055 /* read the existing conch file */
7056 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
7057 if( readLen<0 ){
7058 /* I/O error: lastErrno set by seekAndRead */
drh4bf66fd2015-02-19 02:43:02 +00007059 storeLastErrno(pFile, conchFile->lastErrno);
drh7ed97b92010-01-20 13:07:21 +00007060 rc = SQLITE_IOERR_READ;
7061 goto end_takeconch;
7062 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
7063 readBuf[0]!=(char)PROXY_CONCHVERSION ){
7064 /* a short read or version format mismatch means we need to create a new
7065 ** conch file.
7066 */
7067 createConch = 1;
7068 }
7069 /* if the host id matches and the lock path already exists in the conch
7070 ** we'll try to use the path there, if we can't open that path, we'll
7071 ** retry with a new auto-generated path
7072 */
7073 do { /* in case we need to try again for an :auto: named lock file */
7074
7075 if( !createConch && !forceNewLockPath ){
7076 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
7077 PROXY_HOSTIDLEN);
7078 /* if the conch has data compare the contents */
7079 if( !pCtx->lockProxyPath ){
7080 /* for auto-named local lock file, just check the host ID and we'll
7081 ** use the local lock file path that's already in there
7082 */
7083 if( hostIdMatch ){
7084 size_t pathLen = (readLen - PROXY_PATHINDEX);
7085
7086 if( pathLen>=MAXPATHLEN ){
7087 pathLen=MAXPATHLEN-1;
7088 }
7089 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
7090 lockPath[pathLen] = 0;
7091 tempLockPath = lockPath;
7092 tryOldLockPath = 1;
7093 /* create a copy of the lock path if the conch is taken */
7094 goto end_takeconch;
7095 }
7096 }else if( hostIdMatch
7097 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
7098 readLen-PROXY_PATHINDEX)
7099 ){
7100 /* conch host and lock path match */
7101 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00007102 }
drh7ed97b92010-01-20 13:07:21 +00007103 }
7104
7105 /* if the conch isn't writable and doesn't match, we can't take it */
7106 if( (conchFile->openFlags&O_RDWR) == 0 ){
7107 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00007108 goto end_takeconch;
7109 }
drh7ed97b92010-01-20 13:07:21 +00007110
7111 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00007112 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00007113 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
7114 tempLockPath = lockPath;
7115 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00007116 }
drh7ed97b92010-01-20 13:07:21 +00007117
7118 /* update conch with host and path (this will fail if other process
7119 ** has a shared lock already), if the host id matches, use the big
7120 ** stick.
drh715ff302008-12-03 22:32:44 +00007121 */
drh7ed97b92010-01-20 13:07:21 +00007122 futimes(conchFile->h, NULL);
7123 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00007124 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00007125 /* We are trying for an exclusive lock but another thread in this
7126 ** same process is still holding a shared lock. */
7127 rc = SQLITE_BUSY;
7128 } else {
7129 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00007130 }
drh715ff302008-12-03 22:32:44 +00007131 }else{
drh4bf66fd2015-02-19 02:43:02 +00007132 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00007133 }
drh7ed97b92010-01-20 13:07:21 +00007134 if( rc==SQLITE_OK ){
7135 char writeBuffer[PROXY_MAXCONCHLEN];
7136 int writeSize = 0;
7137
7138 writeBuffer[0] = (char)PROXY_CONCHVERSION;
7139 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
7140 if( pCtx->lockProxyPath!=NULL ){
drh4bf66fd2015-02-19 02:43:02 +00007141 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
7142 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007143 }else{
7144 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
7145 }
7146 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00007147 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00007148 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
drh6d258992016-02-04 09:48:12 +00007149 full_fsync(conchFile->h,0,0);
drh7ed97b92010-01-20 13:07:21 +00007150 /* If we created a new conch file (not just updated the contents of a
7151 ** valid conch file), try to match the permissions of the database
7152 */
7153 if( rc==SQLITE_OK && createConch ){
7154 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00007155 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00007156 if( err==0 ){
7157 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
7158 S_IROTH|S_IWOTH);
7159 /* try to match the database file R/W permissions, ignore failure */
7160#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00007161 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00007162#else
drhff812312011-02-23 13:33:46 +00007163 do{
drhe562be52011-03-02 18:01:10 +00007164 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00007165 }while( rc==(-1) && errno==EINTR );
7166 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00007167 int code = errno;
7168 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
7169 cmode, code, strerror(code));
7170 } else {
7171 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
7172 }
7173 }else{
7174 int code = errno;
7175 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
7176 err, code, strerror(code));
7177#endif
7178 }
drh715ff302008-12-03 22:32:44 +00007179 }
7180 }
drh7ed97b92010-01-20 13:07:21 +00007181 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
7182
7183 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00007184 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00007185 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00007186 int fd;
drh7ed97b92010-01-20 13:07:21 +00007187 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00007188 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00007189 }
7190 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00007191 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00007192 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00007193 if( fd>=0 ){
7194 pFile->h = fd;
7195 }else{
drh9978c972010-02-23 17:36:32 +00007196 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00007197 during locking */
7198 }
7199 }
7200 if( rc==SQLITE_OK && !pCtx->lockProxy ){
7201 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
7202 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
7203 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
7204 /* we couldn't create the proxy lock file with the old lock file path
7205 ** so try again via auto-naming
7206 */
7207 forceNewLockPath = 1;
7208 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00007209 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00007210 }
7211 }
7212 if( rc==SQLITE_OK ){
7213 /* Need to make a copy of path if we extracted the value
7214 ** from the conch file or the path was allocated on the stack
7215 */
7216 if( tempLockPath ){
7217 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
7218 if( !pCtx->lockProxyPath ){
mistachkinfad30392016-02-13 23:43:46 +00007219 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00007220 }
7221 }
7222 }
7223 if( rc==SQLITE_OK ){
7224 pCtx->conchHeld = 1;
7225
7226 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
7227 afpLockingContext *afpCtx;
7228 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
7229 afpCtx->dbPath = pCtx->lockProxyPath;
7230 }
7231 } else {
7232 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7233 }
drh308c2a52010-05-14 11:30:18 +00007234 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
7235 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00007236 return rc;
drh308c2a52010-05-14 11:30:18 +00007237 } while (1); /* in case we need to retry the :auto: lock file -
7238 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00007239 }
7240}
7241
7242/*
7243** If pFile holds a lock on a conch file, then release that lock.
7244*/
7245static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00007246 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00007247 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
7248 unixFile *conchFile; /* Name of the conch file */
7249
7250 pCtx = (proxyLockingContext *)pFile->lockingContext;
7251 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00007252 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00007253 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00007254 osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00007255 if( pCtx->conchHeld>0 ){
7256 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7257 }
drh715ff302008-12-03 22:32:44 +00007258 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00007259 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
7260 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007261 return rc;
7262}
7263
7264/*
7265** Given the name of a database file, compute the name of its conch file.
drhf3cdcdc2015-04-29 16:50:28 +00007266** Store the conch filename in memory obtained from sqlite3_malloc64().
drh715ff302008-12-03 22:32:44 +00007267** Make *pConchPath point to the new name. Return SQLITE_OK on success
7268** or SQLITE_NOMEM if unable to obtain memory.
7269**
7270** The caller is responsible for ensuring that the allocated memory
7271** space is eventually freed.
7272**
7273** *pConchPath is set to NULL if a memory allocation error occurs.
7274*/
7275static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7276 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00007277 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00007278 char *conchPath; /* buffer in which to construct conch name */
7279
7280 /* Allocate space for the conch filename and initialize the name to
7281 ** the name of the original database file. */
drhf3cdcdc2015-04-29 16:50:28 +00007282 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
drh715ff302008-12-03 22:32:44 +00007283 if( conchPath==0 ){
mistachkinfad30392016-02-13 23:43:46 +00007284 return SQLITE_NOMEM_BKPT;
drh715ff302008-12-03 22:32:44 +00007285 }
7286 memcpy(conchPath, dbPath, len+1);
7287
7288 /* now insert a "." before the last / character */
7289 for( i=(len-1); i>=0; i-- ){
7290 if( conchPath[i]=='/' ){
7291 i++;
7292 break;
7293 }
7294 }
7295 conchPath[i]='.';
7296 while ( i<len ){
7297 conchPath[i+1]=dbPath[i];
7298 i++;
7299 }
7300
7301 /* append the "-conch" suffix to the file */
7302 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007303 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007304
7305 return SQLITE_OK;
7306}
7307
7308
7309/* Takes a fully configured proxy locking-style unix file and switches
7310** the local lock file path
7311*/
7312static int switchLockProxyPath(unixFile *pFile, const char *path) {
7313 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7314 char *oldPath = pCtx->lockProxyPath;
7315 int rc = SQLITE_OK;
7316
drh308c2a52010-05-14 11:30:18 +00007317 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007318 return SQLITE_BUSY;
7319 }
7320
7321 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7322 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7323 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7324 return SQLITE_OK;
7325 }else{
7326 unixFile *lockProxy = pCtx->lockProxy;
7327 pCtx->lockProxy=NULL;
7328 pCtx->conchHeld = 0;
7329 if( lockProxy!=NULL ){
7330 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7331 if( rc ) return rc;
7332 sqlite3_free(lockProxy);
7333 }
7334 sqlite3_free(oldPath);
7335 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7336 }
7337
7338 return rc;
7339}
7340
7341/*
7342** pFile is a file that has been opened by a prior xOpen call. dbPath
7343** is a string buffer at least MAXPATHLEN+1 characters in size.
7344**
7345** This routine find the filename associated with pFile and writes it
7346** int dbPath.
7347*/
7348static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007349#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007350 if( pFile->pMethod == &afpIoMethods ){
7351 /* afp style keeps a reference to the db path in the filePath field
7352 ** of the struct */
drhea678832008-12-10 19:26:22 +00007353 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh4bf66fd2015-02-19 02:43:02 +00007354 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7355 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007356 } else
drh715ff302008-12-03 22:32:44 +00007357#endif
7358 if( pFile->pMethod == &dotlockIoMethods ){
7359 /* dot lock style uses the locking context to store the dot lock
7360 ** file path */
7361 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7362 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7363 }else{
7364 /* all other styles use the locking context to store the db file path */
7365 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007366 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007367 }
7368 return SQLITE_OK;
7369}
7370
7371/*
7372** Takes an already filled in unix file and alters it so all file locking
7373** will be performed on the local proxy lock file. The following fields
7374** are preserved in the locking context so that they can be restored and
7375** the unix structure properly cleaned up at close time:
7376** ->lockingContext
7377** ->pMethod
7378*/
7379static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7380 proxyLockingContext *pCtx;
7381 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7382 char *lockPath=NULL;
7383 int rc = SQLITE_OK;
7384
drh308c2a52010-05-14 11:30:18 +00007385 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007386 return SQLITE_BUSY;
7387 }
7388 proxyGetDbPathForUnixFile(pFile, dbPath);
7389 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7390 lockPath=NULL;
7391 }else{
7392 lockPath=(char *)path;
7393 }
7394
drh308c2a52010-05-14 11:30:18 +00007395 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
drh5ac93652015-03-21 20:59:43 +00007396 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007397
drhf3cdcdc2015-04-29 16:50:28 +00007398 pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh715ff302008-12-03 22:32:44 +00007399 if( pCtx==0 ){
mistachkinfad30392016-02-13 23:43:46 +00007400 return SQLITE_NOMEM_BKPT;
drh715ff302008-12-03 22:32:44 +00007401 }
7402 memset(pCtx, 0, sizeof(*pCtx));
7403
7404 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7405 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007406 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7407 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7408 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7409 ** (c) the file system is read-only, then enable no-locking access.
7410 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7411 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7412 */
7413 struct statfs fsInfo;
7414 struct stat conchInfo;
7415 int goLockless = 0;
7416
drh99ab3b12011-03-02 15:09:07 +00007417 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007418 int err = errno;
7419 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7420 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7421 }
7422 }
7423 if( goLockless ){
7424 pCtx->conchHeld = -1; /* read only FS/ lockless */
7425 rc = SQLITE_OK;
7426 }
7427 }
drh715ff302008-12-03 22:32:44 +00007428 }
7429 if( rc==SQLITE_OK && lockPath ){
7430 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7431 }
7432
7433 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007434 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7435 if( pCtx->dbPath==NULL ){
mistachkinfad30392016-02-13 23:43:46 +00007436 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00007437 }
7438 }
7439 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007440 /* all memory is allocated, proxys are created and assigned,
7441 ** switch the locking context and pMethod then return.
7442 */
drh715ff302008-12-03 22:32:44 +00007443 pCtx->oldLockingContext = pFile->lockingContext;
7444 pFile->lockingContext = pCtx;
7445 pCtx->pOldMethod = pFile->pMethod;
7446 pFile->pMethod = &proxyIoMethods;
7447 }else{
7448 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007449 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007450 sqlite3_free(pCtx->conchFile);
7451 }
drhd56b1212010-08-11 06:14:15 +00007452 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007453 sqlite3_free(pCtx->conchFilePath);
7454 sqlite3_free(pCtx);
7455 }
drh308c2a52010-05-14 11:30:18 +00007456 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7457 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007458 return rc;
7459}
7460
7461
7462/*
7463** This routine handles sqlite3_file_control() calls that are specific
7464** to proxy locking.
7465*/
7466static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7467 switch( op ){
drh4bf66fd2015-02-19 02:43:02 +00007468 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007469 unixFile *pFile = (unixFile*)id;
7470 if( pFile->pMethod == &proxyIoMethods ){
7471 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7472 proxyTakeConch(pFile);
7473 if( pCtx->lockProxyPath ){
7474 *(const char **)pArg = pCtx->lockProxyPath;
7475 }else{
7476 *(const char **)pArg = ":auto: (not held)";
7477 }
7478 } else {
7479 *(const char **)pArg = NULL;
7480 }
7481 return SQLITE_OK;
7482 }
drh4bf66fd2015-02-19 02:43:02 +00007483 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007484 unixFile *pFile = (unixFile*)id;
7485 int rc = SQLITE_OK;
7486 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7487 if( pArg==NULL || (const char *)pArg==0 ){
7488 if( isProxyStyle ){
drh4bf66fd2015-02-19 02:43:02 +00007489 /* turn off proxy locking - not supported. If support is added for
7490 ** switching proxy locking mode off then it will need to fail if
7491 ** the journal mode is WAL mode.
7492 */
drh715ff302008-12-03 22:32:44 +00007493 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7494 }else{
7495 /* turn off proxy locking - already off - NOOP */
7496 rc = SQLITE_OK;
7497 }
7498 }else{
7499 const char *proxyPath = (const char *)pArg;
7500 if( isProxyStyle ){
7501 proxyLockingContext *pCtx =
7502 (proxyLockingContext*)pFile->lockingContext;
7503 if( !strcmp(pArg, ":auto:")
7504 || (pCtx->lockProxyPath &&
7505 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7506 ){
7507 rc = SQLITE_OK;
7508 }else{
7509 rc = switchLockProxyPath(pFile, proxyPath);
7510 }
7511 }else{
7512 /* turn on proxy file locking */
7513 rc = proxyTransformUnixFile(pFile, proxyPath);
7514 }
7515 }
7516 return rc;
7517 }
7518 default: {
7519 assert( 0 ); /* The call assures that only valid opcodes are sent */
7520 }
7521 }
7522 /*NOTREACHED*/
7523 return SQLITE_ERROR;
7524}
7525
7526/*
7527** Within this division (the proxying locking implementation) the procedures
7528** above this point are all utilities. The lock-related methods of the
7529** proxy-locking sqlite3_io_method object follow.
7530*/
7531
7532
7533/*
7534** This routine checks if there is a RESERVED lock held on the specified
7535** file by this or any other process. If such a lock is held, set *pResOut
7536** to a non-zero value otherwise *pResOut is set to zero. The return value
7537** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7538*/
7539static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7540 unixFile *pFile = (unixFile*)id;
7541 int rc = proxyTakeConch(pFile);
7542 if( rc==SQLITE_OK ){
7543 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007544 if( pCtx->conchHeld>0 ){
7545 unixFile *proxy = pCtx->lockProxy;
7546 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7547 }else{ /* conchHeld < 0 is lockless */
7548 pResOut=0;
7549 }
drh715ff302008-12-03 22:32:44 +00007550 }
7551 return rc;
7552}
7553
7554/*
drh308c2a52010-05-14 11:30:18 +00007555** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007556** of the following:
7557**
7558** (1) SHARED_LOCK
7559** (2) RESERVED_LOCK
7560** (3) PENDING_LOCK
7561** (4) EXCLUSIVE_LOCK
7562**
7563** Sometimes when requesting one lock state, additional lock states
7564** are inserted in between. The locking might fail on one of the later
7565** transitions leaving the lock state different from what it started but
7566** still short of its goal. The following chart shows the allowed
7567** transitions and the inserted intermediate states:
7568**
7569** UNLOCKED -> SHARED
7570** SHARED -> RESERVED
7571** SHARED -> (PENDING) -> EXCLUSIVE
7572** RESERVED -> (PENDING) -> EXCLUSIVE
7573** PENDING -> EXCLUSIVE
7574**
7575** This routine will only increase a lock. Use the sqlite3OsUnlock()
7576** routine to lower a locking level.
7577*/
drh308c2a52010-05-14 11:30:18 +00007578static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007579 unixFile *pFile = (unixFile*)id;
7580 int rc = proxyTakeConch(pFile);
7581 if( rc==SQLITE_OK ){
7582 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007583 if( pCtx->conchHeld>0 ){
7584 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007585 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7586 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007587 }else{
7588 /* conchHeld < 0 is lockless */
7589 }
drh715ff302008-12-03 22:32:44 +00007590 }
7591 return rc;
7592}
7593
7594
7595/*
drh308c2a52010-05-14 11:30:18 +00007596** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007597** must be either NO_LOCK or SHARED_LOCK.
7598**
7599** If the locking level of the file descriptor is already at or below
7600** the requested locking level, this routine is a no-op.
7601*/
drh308c2a52010-05-14 11:30:18 +00007602static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007603 unixFile *pFile = (unixFile*)id;
7604 int rc = proxyTakeConch(pFile);
7605 if( rc==SQLITE_OK ){
7606 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007607 if( pCtx->conchHeld>0 ){
7608 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007609 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7610 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007611 }else{
7612 /* conchHeld < 0 is lockless */
7613 }
drh715ff302008-12-03 22:32:44 +00007614 }
7615 return rc;
7616}
7617
7618/*
7619** Close a file that uses proxy locks.
7620*/
7621static int proxyClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00007622 if( ALWAYS(id) ){
drh715ff302008-12-03 22:32:44 +00007623 unixFile *pFile = (unixFile*)id;
7624 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7625 unixFile *lockProxy = pCtx->lockProxy;
7626 unixFile *conchFile = pCtx->conchFile;
7627 int rc = SQLITE_OK;
7628
7629 if( lockProxy ){
7630 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7631 if( rc ) return rc;
7632 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7633 if( rc ) return rc;
7634 sqlite3_free(lockProxy);
7635 pCtx->lockProxy = 0;
7636 }
7637 if( conchFile ){
7638 if( pCtx->conchHeld ){
7639 rc = proxyReleaseConch(pFile);
7640 if( rc ) return rc;
7641 }
7642 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7643 if( rc ) return rc;
7644 sqlite3_free(conchFile);
7645 }
drhd56b1212010-08-11 06:14:15 +00007646 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007647 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007648 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007649 /* restore the original locking context and pMethod then close it */
7650 pFile->lockingContext = pCtx->oldLockingContext;
7651 pFile->pMethod = pCtx->pOldMethod;
7652 sqlite3_free(pCtx);
7653 return pFile->pMethod->xClose(id);
7654 }
7655 return SQLITE_OK;
7656}
7657
7658
7659
drhd2cb50b2009-01-09 21:41:17 +00007660#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007661/*
7662** The proxy locking style is intended for use with AFP filesystems.
7663** And since AFP is only supported on MacOSX, the proxy locking is also
7664** restricted to MacOSX.
7665**
7666**
7667******************* End of the proxy lock implementation **********************
7668******************************************************************************/
7669
drh734c9862008-11-28 15:37:20 +00007670/*
danielk1977e339d652008-06-28 11:23:00 +00007671** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007672**
7673** This routine registers all VFS implementations for unix-like operating
7674** systems. This routine, and the sqlite3_os_end() routine that follows,
7675** should be the only routines in this file that are visible from other
7676** files.
drh6b9d6dd2008-12-03 19:34:47 +00007677**
7678** This routine is called once during SQLite initialization and by a
7679** single thread. The memory allocation and mutex subsystems have not
7680** necessarily been initialized when this routine is called, and so they
7681** should not be used.
drh153c62c2007-08-24 03:51:33 +00007682*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007683int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007684 /*
7685 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007686 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7687 ** to the "finder" function. (pAppData is a pointer to a pointer because
7688 ** silly C90 rules prohibit a void* from being cast to a function pointer
7689 ** and so we have to go through the intermediate pointer to avoid problems
7690 ** when compiling with -pedantic-errors on GCC.)
7691 **
7692 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007693 ** finder-function. The finder-function returns a pointer to the
7694 ** sqlite_io_methods object that implements the desired locking
7695 ** behaviors. See the division above that contains the IOMETHODS
7696 ** macro for addition information on finder-functions.
7697 **
7698 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7699 ** object. But the "autolockIoFinder" available on MacOSX does a little
7700 ** more than that; it looks at the filesystem type that hosts the
7701 ** database file and tries to choose an locking method appropriate for
7702 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007703 */
drh7708e972008-11-29 00:56:52 +00007704 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007705 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007706 sizeof(unixFile), /* szOsFile */ \
7707 MAX_PATHNAME, /* mxPathname */ \
7708 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007709 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007710 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007711 unixOpen, /* xOpen */ \
7712 unixDelete, /* xDelete */ \
7713 unixAccess, /* xAccess */ \
7714 unixFullPathname, /* xFullPathname */ \
7715 unixDlOpen, /* xDlOpen */ \
7716 unixDlError, /* xDlError */ \
7717 unixDlSym, /* xDlSym */ \
7718 unixDlClose, /* xDlClose */ \
7719 unixRandomness, /* xRandomness */ \
7720 unixSleep, /* xSleep */ \
7721 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007722 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007723 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007724 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007725 unixGetSystemCall, /* xGetSystemCall */ \
7726 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007727 }
7728
drh6b9d6dd2008-12-03 19:34:47 +00007729 /*
7730 ** All default VFSes for unix are contained in the following array.
7731 **
7732 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7733 ** by the SQLite core when the VFS is registered. So the following
7734 ** array cannot be const.
7735 */
danielk1977e339d652008-06-28 11:23:00 +00007736 static sqlite3_vfs aVfs[] = {
drhe89b2912015-03-03 20:42:01 +00007737#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007738 UNIXVFS("unix", autolockIoFinder ),
drhe89b2912015-03-03 20:42:01 +00007739#elif OS_VXWORKS
7740 UNIXVFS("unix", vxworksIoFinder ),
drh7708e972008-11-29 00:56:52 +00007741#else
7742 UNIXVFS("unix", posixIoFinder ),
7743#endif
7744 UNIXVFS("unix-none", nolockIoFinder ),
7745 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007746 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007747#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007748 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007749#endif
drhe89b2912015-03-03 20:42:01 +00007750#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007751 UNIXVFS("unix-posix", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007752#endif
drhe89b2912015-03-03 20:42:01 +00007753#if SQLITE_ENABLE_LOCKING_STYLE
7754 UNIXVFS("unix-flock", flockIoFinder ),
chw78a13182009-04-07 05:35:03 +00007755#endif
drhd2cb50b2009-01-09 21:41:17 +00007756#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007757 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007758 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007759 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007760#endif
drh153c62c2007-08-24 03:51:33 +00007761 };
drh6b9d6dd2008-12-03 19:34:47 +00007762 unsigned int i; /* Loop counter */
7763
drh2aa5a002011-04-13 13:42:25 +00007764 /* Double-check that the aSyscall[] array has been constructed
7765 ** correctly. See ticket [bb3a86e890c8e96ab] */
danefe16972017-07-20 19:49:14 +00007766 assert( ArraySize(aSyscall)==29 );
drh2aa5a002011-04-13 13:42:25 +00007767
drh6b9d6dd2008-12-03 19:34:47 +00007768 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007769 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007770 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007771 }
drh56115892018-02-05 16:39:12 +00007772 unixBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
danielk1977c0fa4c52008-06-25 17:19:00 +00007773 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007774}
danielk1977e339d652008-06-28 11:23:00 +00007775
7776/*
drh6b9d6dd2008-12-03 19:34:47 +00007777** Shutdown the operating system interface.
7778**
7779** Some operating systems might need to do some cleanup in this routine,
7780** to release dynamically allocated objects. But not on unix.
7781** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007782*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007783int sqlite3_os_end(void){
drh56115892018-02-05 16:39:12 +00007784 unixBigLock = 0;
danielk1977c0fa4c52008-06-25 17:19:00 +00007785 return SQLITE_OK;
7786}
drhdce8bdb2007-08-16 13:01:44 +00007787
danielk197729bafea2008-06-26 10:41:19 +00007788#endif /* SQLITE_OS_UNIX */