blob: 6a1195041b7a2de84907d49793e03d37d0990386 [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)
dan16f39b62018-09-18 19:40:18 +0000524# ifdef __ANDROID__
525 { "ioctl", (sqlite3_syscall_ptr)(int(*)(int, int, ...))ioctl, 0 },
526# else
danefe16972017-07-20 19:49:14 +0000527 { "ioctl", (sqlite3_syscall_ptr)ioctl, 0 },
dan16f39b62018-09-18 19:40:18 +0000528# endif
drhb5d013e2017-10-25 16:14:12 +0000529#else
530 { "ioctl", (sqlite3_syscall_ptr)0, 0 },
531#endif
dan9d709542017-07-21 21:06:24 +0000532#define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent)
danefe16972017-07-20 19:49:14 +0000533
drhe562be52011-03-02 18:01:10 +0000534}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000535
drh6226ca22015-11-24 15:06:28 +0000536
537/*
538** On some systems, calls to fchown() will trigger a message in a security
539** log if they come from non-root processes. So avoid calling fchown() if
540** we are not running as root.
541*/
542static int robustFchown(int fd, uid_t uid, gid_t gid){
drhe2258a22016-01-12 00:37:55 +0000543#if defined(HAVE_FCHOWN)
drh6226ca22015-11-24 15:06:28 +0000544 return osGeteuid() ? 0 : osFchown(fd,uid,gid);
drhe2258a22016-01-12 00:37:55 +0000545#else
546 return 0;
drh6226ca22015-11-24 15:06:28 +0000547#endif
548}
549
drh99ab3b12011-03-02 15:09:07 +0000550/*
551** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000552** "unix" VFSes. Return SQLITE_OK opon successfully updating the
553** system call pointer, or SQLITE_NOTFOUND if there is no configurable
554** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000555*/
556static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000557 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
558 const char *zName, /* Name of system call to override */
559 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000560){
drh58ad5802011-03-23 22:02:23 +0000561 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000562 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000563
564 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000565 if( zName==0 ){
566 /* If no zName is given, restore all system calls to their default
567 ** settings and return NULL
568 */
dan51438a72011-04-02 17:00:47 +0000569 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000570 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
571 if( aSyscall[i].pDefault ){
572 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000573 }
574 }
575 }else{
576 /* If zName is specified, operate on only the one system call
577 ** specified.
578 */
579 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
580 if( strcmp(zName, aSyscall[i].zName)==0 ){
581 if( aSyscall[i].pDefault==0 ){
582 aSyscall[i].pDefault = aSyscall[i].pCurrent;
583 }
drh1df30962011-03-02 19:06:42 +0000584 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000585 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
586 aSyscall[i].pCurrent = pNewFunc;
587 break;
588 }
589 }
590 }
591 return rc;
592}
593
drh1df30962011-03-02 19:06:42 +0000594/*
595** Return the value of a system call. Return NULL if zName is not a
596** recognized system call name. NULL is also returned if the system call
597** is currently undefined.
598*/
drh58ad5802011-03-23 22:02:23 +0000599static sqlite3_syscall_ptr unixGetSystemCall(
600 sqlite3_vfs *pNotUsed,
601 const char *zName
602){
603 unsigned int i;
604
605 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000606 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
607 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
608 }
609 return 0;
610}
611
612/*
613** Return the name of the first system call after zName. If zName==NULL
614** then return the name of the first system call. Return NULL if zName
615** is the last system call or if zName is not the name of a valid
616** system call.
617*/
618static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000619 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000620
621 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000622 if( zName ){
623 for(i=0; i<ArraySize(aSyscall)-1; i++){
624 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000625 }
626 }
dan0fd7d862011-03-29 10:04:23 +0000627 for(i++; i<ArraySize(aSyscall); i++){
628 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000629 }
630 return 0;
631}
632
drhad4f1e52011-03-04 15:43:57 +0000633/*
drh77a3fdc2013-08-30 14:24:12 +0000634** Do not accept any file descriptor less than this value, in order to avoid
635** opening database file using file descriptors that are commonly used for
636** standard input, output, and error.
637*/
638#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
639# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
640#endif
641
642/*
drh8c815d12012-02-13 20:16:37 +0000643** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000644** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000645**
646** If the file creation mode "m" is 0 then set it to the default for
647** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
648** 0644) as modified by the system umask. If m is not 0, then
649** make the file creation mode be exactly m ignoring the umask.
650**
651** The m parameter will be non-zero only when creating -wal, -journal,
652** and -shm files. We want those files to have *exactly* the same
653** permissions as their original database, unadulterated by the umask.
654** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
655** transaction crashes and leaves behind hot journals, then any
656** process that is able to write to the database will also be able to
657** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000658*/
drh8c815d12012-02-13 20:16:37 +0000659static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000660 int fd;
drhe1186ab2013-01-04 20:45:13 +0000661 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5128d002013-08-30 06:20:23 +0000662 while(1){
drh5adc60b2012-04-14 13:25:11 +0000663#if defined(O_CLOEXEC)
664 fd = osOpen(z,f|O_CLOEXEC,m2);
665#else
666 fd = osOpen(z,f,m2);
667#endif
drh5128d002013-08-30 06:20:23 +0000668 if( fd<0 ){
669 if( errno==EINTR ) continue;
670 break;
671 }
drh77a3fdc2013-08-30 14:24:12 +0000672 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
drh5128d002013-08-30 06:20:23 +0000673 osClose(fd);
674 sqlite3_log(SQLITE_WARNING,
675 "attempt to open \"%s\" as file descriptor %d", z, fd);
676 fd = -1;
677 if( osOpen("/dev/null", f, m)<0 ) break;
678 }
drhe1186ab2013-01-04 20:45:13 +0000679 if( fd>=0 ){
680 if( m!=0 ){
681 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000682 if( osFstat(fd, &statbuf)==0
683 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000684 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000685 ){
drhe1186ab2013-01-04 20:45:13 +0000686 osFchmod(fd, m);
687 }
688 }
drh5adc60b2012-04-14 13:25:11 +0000689#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000690 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000691#endif
drhe1186ab2013-01-04 20:45:13 +0000692 }
drh5adc60b2012-04-14 13:25:11 +0000693 return fd;
drhad4f1e52011-03-04 15:43:57 +0000694}
danielk197713adf8a2004-06-03 16:08:41 +0000695
drh107886a2008-11-21 22:21:50 +0000696/*
dan9359c7b2009-08-21 08:29:10 +0000697** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000698** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000699** vxworksFileId objects used by this file, all of which may be
700** shared by multiple threads.
701**
702** Function unixMutexHeld() is used to assert() that the global mutex
703** is held when required. This function is only used as part of assert()
704** statements. e.g.
705**
706** unixEnterMutex()
707** assert( unixMutexHeld() );
708** unixEnterLeave()
drh095908e2018-08-13 20:46:18 +0000709**
710** To prevent deadlock, the global unixBigLock must must be acquired
711** before the unixInodeInfo.pLockMutex mutex, if both are held. It is
712** OK to get the pLockMutex without holding unixBigLock first, but if
713** that happens, the unixBigLock mutex must not be acquired until after
714** pLockMutex is released.
715**
716** OK: enter(unixBigLock), enter(pLockInfo)
717** OK: enter(unixBigLock)
718** OK: enter(pLockInfo)
719** ERROR: enter(pLockInfo), enter(unixBigLock)
drh107886a2008-11-21 22:21:50 +0000720*/
drh56115892018-02-05 16:39:12 +0000721static sqlite3_mutex *unixBigLock = 0;
drh107886a2008-11-21 22:21:50 +0000722static void unixEnterMutex(void){
drh095908e2018-08-13 20:46:18 +0000723 assert( sqlite3_mutex_notheld(unixBigLock) ); /* Not a recursive mutex */
drh56115892018-02-05 16:39:12 +0000724 sqlite3_mutex_enter(unixBigLock);
drh107886a2008-11-21 22:21:50 +0000725}
726static void unixLeaveMutex(void){
drh095908e2018-08-13 20:46:18 +0000727 assert( sqlite3_mutex_held(unixBigLock) );
drh56115892018-02-05 16:39:12 +0000728 sqlite3_mutex_leave(unixBigLock);
drh107886a2008-11-21 22:21:50 +0000729}
dan9359c7b2009-08-21 08:29:10 +0000730#ifdef SQLITE_DEBUG
731static int unixMutexHeld(void) {
drh56115892018-02-05 16:39:12 +0000732 return sqlite3_mutex_held(unixBigLock);
dan9359c7b2009-08-21 08:29:10 +0000733}
734#endif
drh107886a2008-11-21 22:21:50 +0000735
drh734c9862008-11-28 15:37:20 +0000736
mistachkinfb383e92015-04-16 03:24:38 +0000737#ifdef SQLITE_HAVE_OS_TRACE
drh734c9862008-11-28 15:37:20 +0000738/*
739** Helper function for printing out trace information from debugging
peter.d.reid60ec9142014-09-06 16:39:46 +0000740** binaries. This returns the string representation of the supplied
drh734c9862008-11-28 15:37:20 +0000741** integer lock-type.
742*/
drh308c2a52010-05-14 11:30:18 +0000743static const char *azFileLock(int eFileLock){
744 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000745 case NO_LOCK: return "NONE";
746 case SHARED_LOCK: return "SHARED";
747 case RESERVED_LOCK: return "RESERVED";
748 case PENDING_LOCK: return "PENDING";
749 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000750 }
751 return "ERROR";
752}
753#endif
754
755#ifdef SQLITE_LOCK_TRACE
756/*
757** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000758**
drh734c9862008-11-28 15:37:20 +0000759** This routine is used for troubleshooting locks on multithreaded
760** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
761** command-line option on the compiler. This code is normally
762** turned off.
763*/
764static int lockTrace(int fd, int op, struct flock *p){
765 char *zOpName, *zType;
766 int s;
767 int savedErrno;
768 if( op==F_GETLK ){
769 zOpName = "GETLK";
770 }else if( op==F_SETLK ){
771 zOpName = "SETLK";
772 }else{
drh99ab3b12011-03-02 15:09:07 +0000773 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000774 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
775 return s;
776 }
777 if( p->l_type==F_RDLCK ){
778 zType = "RDLCK";
779 }else if( p->l_type==F_WRLCK ){
780 zType = "WRLCK";
781 }else if( p->l_type==F_UNLCK ){
782 zType = "UNLCK";
783 }else{
784 assert( 0 );
785 }
786 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000787 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000788 savedErrno = errno;
789 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
790 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
791 (int)p->l_pid, s);
792 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
793 struct flock l2;
794 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000795 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000796 if( l2.l_type==F_RDLCK ){
797 zType = "RDLCK";
798 }else if( l2.l_type==F_WRLCK ){
799 zType = "WRLCK";
800 }else if( l2.l_type==F_UNLCK ){
801 zType = "UNLCK";
802 }else{
803 assert( 0 );
804 }
805 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
806 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
807 }
808 errno = savedErrno;
809 return s;
810}
drh99ab3b12011-03-02 15:09:07 +0000811#undef osFcntl
812#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000813#endif /* SQLITE_LOCK_TRACE */
814
drhff812312011-02-23 13:33:46 +0000815/*
816** Retry ftruncate() calls that fail due to EINTR
dan2ee53412014-09-06 16:49:40 +0000817**
drhe6d41732015-02-21 00:49:00 +0000818** All calls to ftruncate() within this file should be made through
819** this wrapper. On the Android platform, bypassing the logic below
820** could lead to a corrupt database.
drhff812312011-02-23 13:33:46 +0000821*/
drhff812312011-02-23 13:33:46 +0000822static int robust_ftruncate(int h, sqlite3_int64 sz){
823 int rc;
dan2ee53412014-09-06 16:49:40 +0000824#ifdef __ANDROID__
825 /* On Android, ftruncate() always uses 32-bit offsets, even if
826 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
dan524a7332014-09-06 17:06:13 +0000827 ** truncate a file to any size larger than 2GiB. Silently ignore any
dan2ee53412014-09-06 16:49:40 +0000828 ** such attempts. */
829 if( sz>(sqlite3_int64)0x7FFFFFFF ){
830 rc = SQLITE_OK;
831 }else
832#endif
drh99ab3b12011-03-02 15:09:07 +0000833 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000834 return rc;
835}
drh734c9862008-11-28 15:37:20 +0000836
837/*
838** This routine translates a standard POSIX errno code into something
839** useful to the clients of the sqlite3 functions. Specifically, it is
840** intended to translate a variety of "try again" errors into SQLITE_BUSY
841** and a variety of "please close the file descriptor NOW" errors into
842** SQLITE_IOERR
843**
844** Errors during initialization of locks, or file system support for locks,
845** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
846*/
847static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
drh91c4def2015-11-25 14:00:07 +0000848 assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
849 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
850 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
851 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
drh734c9862008-11-28 15:37:20 +0000852 switch (posixError) {
drh91c4def2015-11-25 14:00:07 +0000853 case EACCES:
drh734c9862008-11-28 15:37:20 +0000854 case EAGAIN:
855 case ETIMEDOUT:
856 case EBUSY:
857 case EINTR:
858 case ENOLCK:
859 /* random NFS retry error, unless during file system support
860 * introspection, in which it actually means what it says */
861 return SQLITE_BUSY;
862
drh734c9862008-11-28 15:37:20 +0000863 case EPERM:
864 return SQLITE_PERM;
865
drh734c9862008-11-28 15:37:20 +0000866 default:
867 return sqliteIOErr;
868 }
869}
870
871
drh734c9862008-11-28 15:37:20 +0000872/******************************************************************************
873****************** Begin Unique File ID Utility Used By VxWorks ***************
874**
875** On most versions of unix, we can get a unique ID for a file by concatenating
876** the device number and the inode number. But this does not work on VxWorks.
877** On VxWorks, a unique file id must be based on the canonical filename.
878**
879** A pointer to an instance of the following structure can be used as a
880** unique file ID in VxWorks. Each instance of this structure contains
881** a copy of the canonical filename. There is also a reference count.
882** The structure is reclaimed when the number of pointers to it drops to
883** zero.
884**
885** There are never very many files open at one time and lookups are not
886** a performance-critical path, so it is sufficient to put these
887** structures on a linked list.
888*/
889struct vxworksFileId {
890 struct vxworksFileId *pNext; /* Next in a list of them all */
891 int nRef; /* Number of references to this one */
892 int nName; /* Length of the zCanonicalName[] string */
893 char *zCanonicalName; /* Canonical filename */
894};
895
896#if OS_VXWORKS
897/*
drh9b35ea62008-11-29 02:20:26 +0000898** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000899** variable:
900*/
901static struct vxworksFileId *vxworksFileList = 0;
902
903/*
904** Simplify a filename into its canonical form
905** by making the following changes:
906**
907** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000908** * convert /./ into just /
909** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000910**
911** Changes are made in-place. Return the new name length.
912**
913** The original filename is in z[0..n-1]. Return the number of
914** characters in the simplified name.
915*/
916static int vxworksSimplifyName(char *z, int n){
917 int i, j;
918 while( n>1 && z[n-1]=='/' ){ n--; }
919 for(i=j=0; i<n; i++){
920 if( z[i]=='/' ){
921 if( z[i+1]=='/' ) continue;
922 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
923 i += 1;
924 continue;
925 }
926 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
927 while( j>0 && z[j-1]!='/' ){ j--; }
928 if( j>0 ){ j--; }
929 i += 2;
930 continue;
931 }
932 }
933 z[j++] = z[i];
934 }
935 z[j] = 0;
936 return j;
937}
938
939/*
940** Find a unique file ID for the given absolute pathname. Return
941** a pointer to the vxworksFileId object. This pointer is the unique
942** file ID.
943**
944** The nRef field of the vxworksFileId object is incremented before
945** the object is returned. A new vxworksFileId object is created
946** and added to the global list if necessary.
947**
948** If a memory allocation error occurs, return NULL.
949*/
950static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
951 struct vxworksFileId *pNew; /* search key and new file ID */
952 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
953 int n; /* Length of zAbsoluteName string */
954
955 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000956 n = (int)strlen(zAbsoluteName);
drhf3cdcdc2015-04-29 16:50:28 +0000957 pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
drh734c9862008-11-28 15:37:20 +0000958 if( pNew==0 ) return 0;
959 pNew->zCanonicalName = (char*)&pNew[1];
960 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
961 n = vxworksSimplifyName(pNew->zCanonicalName, n);
962
963 /* Search for an existing entry that matching the canonical name.
964 ** If found, increment the reference count and return a pointer to
965 ** the existing file ID.
966 */
967 unixEnterMutex();
968 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
969 if( pCandidate->nName==n
970 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
971 ){
972 sqlite3_free(pNew);
973 pCandidate->nRef++;
974 unixLeaveMutex();
975 return pCandidate;
976 }
977 }
978
979 /* No match was found. We will make a new file ID */
980 pNew->nRef = 1;
981 pNew->nName = n;
982 pNew->pNext = vxworksFileList;
983 vxworksFileList = pNew;
984 unixLeaveMutex();
985 return pNew;
986}
987
988/*
989** Decrement the reference count on a vxworksFileId object. Free
990** the object when the reference count reaches zero.
991*/
992static void vxworksReleaseFileId(struct vxworksFileId *pId){
993 unixEnterMutex();
994 assert( pId->nRef>0 );
995 pId->nRef--;
996 if( pId->nRef==0 ){
997 struct vxworksFileId **pp;
998 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
999 assert( *pp==pId );
1000 *pp = pId->pNext;
1001 sqlite3_free(pId);
1002 }
1003 unixLeaveMutex();
1004}
1005#endif /* OS_VXWORKS */
1006/*************** End of Unique File ID Utility Used By VxWorks ****************
1007******************************************************************************/
1008
1009
1010/******************************************************************************
1011*************************** Posix Advisory Locking ****************************
1012**
drh9b35ea62008-11-29 02:20:26 +00001013** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +00001014** section 6.5.2.2 lines 483 through 490 specify that when a process
1015** sets or clears a lock, that operation overrides any prior locks set
1016** by the same process. It does not explicitly say so, but this implies
1017** that it overrides locks set by the same process using a different
1018** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +00001019**
1020** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +00001021** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
1022**
1023** Suppose ./file1 and ./file2 are really the same file (because
1024** one is a hard or symbolic link to the other) then if you set
1025** an exclusive lock on fd1, then try to get an exclusive lock
1026** on fd2, it works. I would have expected the second lock to
1027** fail since there was already a lock on the file due to fd1.
1028** But not so. Since both locks came from the same process, the
1029** second overrides the first, even though they were on different
1030** file descriptors opened on different file names.
1031**
drh734c9862008-11-28 15:37:20 +00001032** This means that we cannot use POSIX locks to synchronize file access
1033** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +00001034** to synchronize access for threads in separate processes, but not
1035** threads within the same process.
1036**
1037** To work around the problem, SQLite has to manage file locks internally
1038** on its own. Whenever a new database is opened, we have to find the
1039** specific inode of the database file (the inode is determined by the
1040** st_dev and st_ino fields of the stat structure that fstat() fills in)
1041** and check for locks already existing on that inode. When locks are
1042** created or removed, we have to look at our own internal record of the
1043** locks to see if another thread has previously set a lock on that same
1044** inode.
1045**
drh9b35ea62008-11-29 02:20:26 +00001046** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
1047** For VxWorks, we have to use the alternative unique ID system based on
1048** canonical filename and implemented in the previous division.)
1049**
danielk1977ad94b582007-08-20 06:44:22 +00001050** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +00001051** descriptor. It is now a structure that holds the integer file
1052** descriptor and a pointer to a structure that describes the internal
1053** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +00001054** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +00001055** point to the same locking structure. The locking structure keeps
1056** a reference count (so we will know when to delete it) and a "cnt"
1057** field that tells us its internal lock status. cnt==0 means the
1058** file is unlocked. cnt==-1 means the file has an exclusive lock.
1059** cnt>0 means there are cnt shared locks on the file.
1060**
1061** Any attempt to lock or unlock a file first checks the locking
1062** structure. The fcntl() system call is only invoked to set a
1063** POSIX lock if the internal lock structure transitions between
1064** a locked and an unlocked state.
1065**
drh734c9862008-11-28 15:37:20 +00001066** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +00001067**
1068** If you close a file descriptor that points to a file that has locks,
1069** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +00001070** released. To work around this problem, each unixInodeInfo object
1071** maintains a count of the number of pending locks on tha inode.
1072** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +00001073** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +00001074** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +00001075** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +00001076** be closed and that list is walked (and cleared) when the last lock
1077** clears.
1078**
drh9b35ea62008-11-29 02:20:26 +00001079** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +00001080**
drh9b35ea62008-11-29 02:20:26 +00001081** Many older versions of linux use the LinuxThreads library which is
1082** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +00001083** A cannot be modified or overridden by a different thread B.
1084** Only thread A can modify the lock. Locking behavior is correct
1085** if the appliation uses the newer Native Posix Thread Library (NPTL)
1086** on linux - with NPTL a lock created by thread A can override locks
1087** in thread B. But there is no way to know at compile-time which
1088** threading library is being used. So there is no way to know at
1089** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001090** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001091** current process.
drh5fdae772004-06-29 03:29:00 +00001092**
drh8af6c222010-05-14 12:43:01 +00001093** SQLite used to support LinuxThreads. But support for LinuxThreads
1094** was dropped beginning with version 3.7.0. SQLite will still work with
1095** LinuxThreads provided that (1) there is no more than one connection
1096** per database file in the same process and (2) database connections
1097** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001098*/
1099
1100/*
1101** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001102** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001103*/
1104struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001105 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001106#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001107 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001108#else
drh25ef7f52016-12-05 20:06:45 +00001109 /* We are told that some versions of Android contain a bug that
1110 ** sizes ino_t at only 32-bits instead of 64-bits. (See
1111 ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
1112 ** To work around this, always allocate 64-bits for the inode number.
1113 ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
1114 ** but that should not be a big deal. */
1115 /* WAS: ino_t ino; */
1116 u64 ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001117#endif
1118};
1119
1120/*
drhbbd42a62004-05-22 17:41:58 +00001121** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001122** inode. Or, on LinuxThreads, there is one of these structures for
1123** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001124**
danielk1977ad94b582007-08-20 06:44:22 +00001125** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001126** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001127** object keeps a count of the number of unixFile pointing to it.
drhda6dc242018-07-23 21:10:37 +00001128**
1129** Mutex rules:
1130**
drh095908e2018-08-13 20:46:18 +00001131** (1) Only the pLockMutex mutex must be held in order to read or write
drhda6dc242018-07-23 21:10:37 +00001132** any of the locking fields:
drhef52b362018-08-13 22:50:34 +00001133** nShared, nLock, eFileLock, bProcessLock, pUnused
drhda6dc242018-07-23 21:10:37 +00001134**
1135** (2) When nRef>0, then the following fields are unchanging and can
1136** be read (but not written) without holding any mutex:
1137** fileId, pLockMutex
1138**
drhef52b362018-08-13 22:50:34 +00001139** (3) With the exceptions above, all the fields may only be read
drhda6dc242018-07-23 21:10:37 +00001140** or written while holding the global unixBigLock mutex.
drh095908e2018-08-13 20:46:18 +00001141**
1142** Deadlock prevention: The global unixBigLock mutex may not
1143** be acquired while holding the pLockMutex mutex. If both unixBigLock
1144** and pLockMutex are needed, then unixBigLock must be acquired first.
drhbbd42a62004-05-22 17:41:58 +00001145*/
drh8af6c222010-05-14 12:43:01 +00001146struct unixInodeInfo {
1147 struct unixFileId fileId; /* The lookup key */
drhda6dc242018-07-23 21:10:37 +00001148 sqlite3_mutex *pLockMutex; /* Hold this mutex for... */
1149 int nShared; /* Number of SHARED locks held */
1150 int nLock; /* Number of outstanding file locks */
1151 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1152 unsigned char bProcessLock; /* An exclusive process lock is held */
drhef52b362018-08-13 22:50:34 +00001153 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
drh734c9862008-11-28 15:37:20 +00001154 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001155 unixShmNode *pShmNode; /* Shared memory associated with this inode */
drhd91c68f2010-05-14 14:52:25 +00001156 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1157 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001158#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001159 unsigned long long sharedByte; /* for AFP simulated shared lock */
1160#endif
drh6c7d5c52008-11-21 20:32:33 +00001161#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001162 sem_t *pSem; /* Named POSIX semaphore */
1163 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001164#endif
drhbbd42a62004-05-22 17:41:58 +00001165};
1166
drhda0e7682008-07-30 15:27:54 +00001167/*
drh8af6c222010-05-14 12:43:01 +00001168** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001169*/
drhc68886b2017-08-18 16:09:52 +00001170static unixInodeInfo *inodeList = 0; /* All unixInodeInfo objects */
drh095908e2018-08-13 20:46:18 +00001171
1172#ifdef SQLITE_DEBUG
1173/*
1174** True if the inode mutex is held, or not. Used only within assert()
1175** to help verify correct mutex usage.
1176*/
1177int unixFileMutexHeld(unixFile *pFile){
1178 assert( pFile->pInode );
1179 return sqlite3_mutex_held(pFile->pInode->pLockMutex);
1180}
1181int unixFileMutexNotheld(unixFile *pFile){
1182 assert( pFile->pInode );
1183 return sqlite3_mutex_notheld(pFile->pInode->pLockMutex);
1184}
1185#endif
drh5fdae772004-06-29 03:29:00 +00001186
drh5fdae772004-06-29 03:29:00 +00001187/*
dane18d4952011-02-21 11:46:24 +00001188**
drhaaeaa182015-11-24 15:12:47 +00001189** This function - unixLogErrorAtLine(), is only ever called via the macro
dane18d4952011-02-21 11:46:24 +00001190** unixLogError().
1191**
1192** It is invoked after an error occurs in an OS function and errno has been
1193** set. It logs a message using sqlite3_log() containing the current value of
1194** errno and, if possible, the human-readable equivalent from strerror() or
1195** strerror_r().
1196**
1197** The first argument passed to the macro should be the error code that
1198** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1199** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001200** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001201** if any.
1202*/
drh0e9365c2011-03-02 02:08:13 +00001203#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1204static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001205 int errcode, /* SQLite error code */
1206 const char *zFunc, /* Name of OS function that failed */
1207 const char *zPath, /* File path associated with error */
1208 int iLine /* Source line number where error occurred */
1209){
1210 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001211 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001212
1213 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1214 ** the strerror() function to obtain the human-readable error message
1215 ** equivalent to errno. Otherwise, use strerror_r().
1216 */
1217#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1218 char aErr[80];
1219 memset(aErr, 0, sizeof(aErr));
1220 zErr = aErr;
1221
1222 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001223 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001224 ** returns a pointer to a buffer containing the error message. That pointer
1225 ** may point to aErr[], or it may point to some static storage somewhere.
1226 ** Otherwise, assume that the system provides the POSIX version of
1227 ** strerror_r(), which always writes an error message into aErr[].
1228 **
1229 ** If the code incorrectly assumes that it is the POSIX version that is
1230 ** available, the error message will often be an empty string. Not a
1231 ** huge problem. Incorrectly concluding that the GNU version is available
1232 ** could lead to a segfault though.
1233 */
1234#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1235 zErr =
1236# endif
drh0e9365c2011-03-02 02:08:13 +00001237 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001238
1239#elif SQLITE_THREADSAFE
1240 /* This is a threadsafe build, but strerror_r() is not available. */
1241 zErr = "";
1242#else
1243 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001244 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001245#endif
1246
drh0e9365c2011-03-02 02:08:13 +00001247 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001248 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001249 "os_unix.c:%d: (%d) %s(%s) - %s",
1250 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001251 );
1252
1253 return errcode;
1254}
1255
drh0e9365c2011-03-02 02:08:13 +00001256/*
1257** Close a file descriptor.
1258**
1259** We assume that close() almost always works, since it is only in a
1260** very sick application or on a very sick platform that it might fail.
1261** If it does fail, simply leak the file descriptor, but do log the
1262** error.
1263**
1264** Note that it is not safe to retry close() after EINTR since the
1265** file descriptor might have already been reused by another thread.
1266** So we don't even try to recover from an EINTR. Just log the error
1267** and move on.
1268*/
1269static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001270 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001271 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1272 pFile ? pFile->zPath : 0, lineno);
1273 }
1274}
dane18d4952011-02-21 11:46:24 +00001275
1276/*
drhe6d41732015-02-21 00:49:00 +00001277** Set the pFile->lastErrno. Do this in a subroutine as that provides
1278** a convenient place to set a breakpoint.
drh4bf66fd2015-02-19 02:43:02 +00001279*/
1280static void storeLastErrno(unixFile *pFile, int error){
1281 pFile->lastErrno = error;
1282}
1283
1284/*
danb0ac3e32010-06-16 10:55:42 +00001285** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001286*/
drh0e9365c2011-03-02 02:08:13 +00001287static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001288 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001289 UnixUnusedFd *p;
1290 UnixUnusedFd *pNext;
drhef52b362018-08-13 22:50:34 +00001291 assert( unixFileMutexHeld(pFile) );
danb0ac3e32010-06-16 10:55:42 +00001292 for(p=pInode->pUnused; p; p=pNext){
1293 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001294 robust_close(pFile, p->fd, __LINE__);
1295 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001296 }
drh0e9365c2011-03-02 02:08:13 +00001297 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001298}
1299
1300/*
drh8af6c222010-05-14 12:43:01 +00001301** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001302**
1303** The mutex entered using the unixEnterMutex() function must be held
1304** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001305*/
danb0ac3e32010-06-16 10:55:42 +00001306static void releaseInodeInfo(unixFile *pFile){
1307 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001308 assert( unixMutexHeld() );
drh095908e2018-08-13 20:46:18 +00001309 assert( unixFileMutexNotheld(pFile) );
dan661d71a2011-03-30 19:08:03 +00001310 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001311 pInode->nRef--;
1312 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001313 assert( pInode->pShmNode==0 );
drhef52b362018-08-13 22:50:34 +00001314 sqlite3_mutex_enter(pInode->pLockMutex);
danb0ac3e32010-06-16 10:55:42 +00001315 closePendingFds(pFile);
drhef52b362018-08-13 22:50:34 +00001316 sqlite3_mutex_leave(pInode->pLockMutex);
drh8af6c222010-05-14 12:43:01 +00001317 if( pInode->pPrev ){
1318 assert( pInode->pPrev->pNext==pInode );
1319 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001320 }else{
drh8af6c222010-05-14 12:43:01 +00001321 assert( inodeList==pInode );
1322 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001323 }
drh8af6c222010-05-14 12:43:01 +00001324 if( pInode->pNext ){
1325 assert( pInode->pNext->pPrev==pInode );
1326 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001327 }
drhda6dc242018-07-23 21:10:37 +00001328 sqlite3_mutex_free(pInode->pLockMutex);
drh8af6c222010-05-14 12:43:01 +00001329 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001330 }
drhbbd42a62004-05-22 17:41:58 +00001331 }
1332}
1333
1334/*
drh8af6c222010-05-14 12:43:01 +00001335** Given a file descriptor, locate the unixInodeInfo object that
1336** describes that file descriptor. Create a new one if necessary. The
1337** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001338**
dan9359c7b2009-08-21 08:29:10 +00001339** The mutex entered using the unixEnterMutex() function must be held
1340** when this function is called.
1341**
drh6c7d5c52008-11-21 20:32:33 +00001342** Return an appropriate error code.
1343*/
drh8af6c222010-05-14 12:43:01 +00001344static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001345 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001346 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001347){
1348 int rc; /* System call return code */
1349 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001350 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1351 struct stat statbuf; /* Low-level file information */
1352 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001353
dan9359c7b2009-08-21 08:29:10 +00001354 assert( unixMutexHeld() );
1355
drh6c7d5c52008-11-21 20:32:33 +00001356 /* Get low-level information about the file that we can used to
1357 ** create a unique name for the file.
1358 */
1359 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001360 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001361 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001362 storeLastErrno(pFile, errno);
drh40fe8d32015-11-30 20:36:26 +00001363#if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
drh6c7d5c52008-11-21 20:32:33 +00001364 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1365#endif
1366 return SQLITE_IOERR;
1367 }
1368
drheb0d74f2009-02-03 15:27:02 +00001369#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001370 /* On OS X on an msdos filesystem, the inode number is reported
1371 ** incorrectly for zero-size files. See ticket #3260. To work
1372 ** around this problem (we consider it a bug in OS X, not SQLite)
1373 ** we always increase the file size to 1 by writing a single byte
1374 ** prior to accessing the inode number. The one byte written is
1375 ** an ASCII 'S' character which also happens to be the first byte
1376 ** in the header of every SQLite database. In this way, if there
1377 ** is a race condition such that another thread has already populated
1378 ** the first page of the database, no damage is done.
1379 */
drh7ed97b92010-01-20 13:07:21 +00001380 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001381 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001382 if( rc!=1 ){
drh4bf66fd2015-02-19 02:43:02 +00001383 storeLastErrno(pFile, errno);
drheb0d74f2009-02-03 15:27:02 +00001384 return SQLITE_IOERR;
1385 }
drh99ab3b12011-03-02 15:09:07 +00001386 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001387 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001388 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001389 return SQLITE_IOERR;
1390 }
1391 }
drheb0d74f2009-02-03 15:27:02 +00001392#endif
drh6c7d5c52008-11-21 20:32:33 +00001393
drh8af6c222010-05-14 12:43:01 +00001394 memset(&fileId, 0, sizeof(fileId));
1395 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001396#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001397 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001398#else
drh25ef7f52016-12-05 20:06:45 +00001399 fileId.ino = (u64)statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001400#endif
drh8af6c222010-05-14 12:43:01 +00001401 pInode = inodeList;
1402 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1403 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001404 }
drh8af6c222010-05-14 12:43:01 +00001405 if( pInode==0 ){
drhf3cdcdc2015-04-29 16:50:28 +00001406 pInode = sqlite3_malloc64( sizeof(*pInode) );
drh8af6c222010-05-14 12:43:01 +00001407 if( pInode==0 ){
mistachkinfad30392016-02-13 23:43:46 +00001408 return SQLITE_NOMEM_BKPT;
drh6c7d5c52008-11-21 20:32:33 +00001409 }
drh8af6c222010-05-14 12:43:01 +00001410 memset(pInode, 0, sizeof(*pInode));
1411 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
drh6886d6d2018-07-23 22:55:10 +00001412 if( sqlite3GlobalConfig.bCoreMutex ){
1413 pInode->pLockMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
1414 if( pInode->pLockMutex==0 ){
1415 sqlite3_free(pInode);
1416 return SQLITE_NOMEM_BKPT;
1417 }
1418 }
drh8af6c222010-05-14 12:43:01 +00001419 pInode->nRef = 1;
1420 pInode->pNext = inodeList;
1421 pInode->pPrev = 0;
1422 if( inodeList ) inodeList->pPrev = pInode;
1423 inodeList = pInode;
1424 }else{
1425 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001426 }
drh8af6c222010-05-14 12:43:01 +00001427 *ppInode = pInode;
1428 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001429}
drh6c7d5c52008-11-21 20:32:33 +00001430
drhb959a012013-12-07 12:29:22 +00001431/*
1432** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1433*/
1434static int fileHasMoved(unixFile *pFile){
drh61ffea52014-08-12 12:19:25 +00001435#if OS_VXWORKS
1436 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1437#else
drhb959a012013-12-07 12:29:22 +00001438 struct stat buf;
1439 return pFile->pInode!=0 &&
drh25ef7f52016-12-05 20:06:45 +00001440 (osStat(pFile->zPath, &buf)!=0
1441 || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
drh91be7dc2014-08-11 13:53:30 +00001442#endif
drhb959a012013-12-07 12:29:22 +00001443}
1444
aswift5b1a2562008-08-22 00:22:35 +00001445
1446/*
drhfbc7e882013-04-11 01:16:15 +00001447** Check a unixFile that is a database. Verify the following:
1448**
1449** (1) There is exactly one hard link on the file
1450** (2) The file is not a symbolic link
1451** (3) The file has not been renamed or unlinked
1452**
1453** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1454*/
1455static void verifyDbFile(unixFile *pFile){
1456 struct stat buf;
1457 int rc;
drh86151e82015-12-08 14:37:16 +00001458
1459 /* These verifications occurs for the main database only */
1460 if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
1461
drhfbc7e882013-04-11 01:16:15 +00001462 rc = osFstat(pFile->h, &buf);
1463 if( rc!=0 ){
1464 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001465 return;
1466 }
drh6369bc32016-03-21 16:06:42 +00001467 if( buf.st_nlink==0 ){
drhfbc7e882013-04-11 01:16:15 +00001468 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001469 return;
1470 }
1471 if( buf.st_nlink>1 ){
1472 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001473 return;
1474 }
drhb959a012013-12-07 12:29:22 +00001475 if( fileHasMoved(pFile) ){
drhfbc7e882013-04-11 01:16:15 +00001476 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001477 return;
1478 }
1479}
1480
1481
1482/*
danielk197713adf8a2004-06-03 16:08:41 +00001483** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001484** file by this or any other process. If such a lock is held, set *pResOut
1485** to a non-zero value otherwise *pResOut is set to zero. The return value
1486** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001487*/
danielk1977861f7452008-06-05 11:39:11 +00001488static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001489 int rc = SQLITE_OK;
1490 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001491 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001492
danielk1977861f7452008-06-05 11:39:11 +00001493 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1494
drh054889e2005-11-30 03:20:31 +00001495 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00001496 assert( pFile->eFileLock<=SHARED_LOCK );
drhda6dc242018-07-23 21:10:37 +00001497 sqlite3_mutex_enter(pFile->pInode->pLockMutex);
danielk197713adf8a2004-06-03 16:08:41 +00001498
1499 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001500 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001501 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001502 }
1503
drh2ac3ee92004-06-07 16:27:46 +00001504 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001505 */
danielk197709480a92009-02-09 05:32:32 +00001506#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001507 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001508 struct flock lock;
1509 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001510 lock.l_start = RESERVED_BYTE;
1511 lock.l_len = 1;
1512 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001513 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1514 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001515 storeLastErrno(pFile, errno);
aswift5b1a2562008-08-22 00:22:35 +00001516 } else if( lock.l_type!=F_UNLCK ){
1517 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001518 }
1519 }
danielk197709480a92009-02-09 05:32:32 +00001520#endif
danielk197713adf8a2004-06-03 16:08:41 +00001521
drhda6dc242018-07-23 21:10:37 +00001522 sqlite3_mutex_leave(pFile->pInode->pLockMutex);
drh308c2a52010-05-14 11:30:18 +00001523 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001524
aswift5b1a2562008-08-22 00:22:35 +00001525 *pResOut = reserved;
1526 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001527}
1528
1529/*
drhf0119b22018-03-26 17:40:53 +00001530** Set a posix-advisory-lock.
1531**
1532** There are two versions of this routine. If compiled with
1533** SQLITE_ENABLE_SETLK_TIMEOUT then the routine has an extra parameter
1534** which is a pointer to a unixFile. If the unixFile->iBusyTimeout
1535** value is set, then it is the number of milliseconds to wait before
1536** failing the lock. The iBusyTimeout value is always reset back to
1537** zero on each call.
1538**
1539** If SQLITE_ENABLE_SETLK_TIMEOUT is not defined, then do a non-blocking
1540** attempt to set the lock.
1541*/
1542#ifndef SQLITE_ENABLE_SETLK_TIMEOUT
1543# define osSetPosixAdvisoryLock(h,x,t) osFcntl(h,F_SETLK,x)
1544#else
1545static int osSetPosixAdvisoryLock(
1546 int h, /* The file descriptor on which to take the lock */
1547 struct flock *pLock, /* The description of the lock */
1548 unixFile *pFile /* Structure holding timeout value */
1549){
1550 int rc = osFcntl(h,F_SETLK,pLock);
drhfd725632018-03-26 20:43:05 +00001551 while( rc<0 && pFile->iBusyTimeout>0 ){
drhf0119b22018-03-26 17:40:53 +00001552 /* On systems that support some kind of blocking file lock with a timeout,
1553 ** make appropriate changes here to invoke that blocking file lock. On
1554 ** generic posix, however, there is no such API. So we simply try the
1555 ** lock once every millisecond until either the timeout expires, or until
1556 ** the lock is obtained. */
drhfd725632018-03-26 20:43:05 +00001557 usleep(1000);
1558 rc = osFcntl(h,F_SETLK,pLock);
1559 pFile->iBusyTimeout--;
drhf0119b22018-03-26 17:40:53 +00001560 }
1561 return rc;
1562}
1563#endif /* SQLITE_ENABLE_SETLK_TIMEOUT */
1564
1565
1566/*
drha7e61d82011-03-12 17:02:57 +00001567** Attempt to set a system-lock on the file pFile. The lock is
1568** described by pLock.
1569**
drh77197112011-03-15 19:08:48 +00001570** If the pFile was opened read/write from unix-excl, then the only lock
1571** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001572** the first time any lock is attempted. All subsequent system locking
1573** operations become no-ops. Locking operations still happen internally,
1574** in order to coordinate access between separate database connections
1575** within this process, but all of that is handled in memory and the
1576** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001577**
1578** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1579** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1580** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001581**
1582** Zero is returned if the call completes successfully, or -1 if a call
1583** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001584*/
1585static int unixFileLock(unixFile *pFile, struct flock *pLock){
1586 int rc;
drh3cb93392011-03-12 18:10:44 +00001587 unixInodeInfo *pInode = pFile->pInode;
drh3cb93392011-03-12 18:10:44 +00001588 assert( pInode!=0 );
drhda6dc242018-07-23 21:10:37 +00001589 assert( sqlite3_mutex_held(pInode->pLockMutex) );
drh50358ad2015-12-02 01:04:33 +00001590 if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
drh3cb93392011-03-12 18:10:44 +00001591 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001592 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001593 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001594 lock.l_whence = SEEK_SET;
1595 lock.l_start = SHARED_FIRST;
1596 lock.l_len = SHARED_SIZE;
1597 lock.l_type = F_WRLCK;
drhf0119b22018-03-26 17:40:53 +00001598 rc = osSetPosixAdvisoryLock(pFile->h, &lock, pFile);
drha7e61d82011-03-12 17:02:57 +00001599 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001600 pInode->bProcessLock = 1;
1601 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001602 }else{
1603 rc = 0;
1604 }
1605 }else{
drhf0119b22018-03-26 17:40:53 +00001606 rc = osSetPosixAdvisoryLock(pFile->h, pLock, pFile);
drha7e61d82011-03-12 17:02:57 +00001607 }
1608 return rc;
1609}
1610
1611/*
drh308c2a52010-05-14 11:30:18 +00001612** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001613** of the following:
1614**
drh2ac3ee92004-06-07 16:27:46 +00001615** (1) SHARED_LOCK
1616** (2) RESERVED_LOCK
1617** (3) PENDING_LOCK
1618** (4) EXCLUSIVE_LOCK
1619**
drhb3e04342004-06-08 00:47:47 +00001620** Sometimes when requesting one lock state, additional lock states
1621** are inserted in between. The locking might fail on one of the later
1622** transitions leaving the lock state different from what it started but
1623** still short of its goal. The following chart shows the allowed
1624** transitions and the inserted intermediate states:
1625**
1626** UNLOCKED -> SHARED
1627** SHARED -> RESERVED
1628** SHARED -> (PENDING) -> EXCLUSIVE
1629** RESERVED -> (PENDING) -> EXCLUSIVE
1630** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001631**
drha6abd042004-06-09 17:37:22 +00001632** This routine will only increase a lock. Use the sqlite3OsUnlock()
1633** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001634*/
drh308c2a52010-05-14 11:30:18 +00001635static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001636 /* The following describes the implementation of the various locks and
1637 ** lock transitions in terms of the POSIX advisory shared and exclusive
1638 ** lock primitives (called read-locks and write-locks below, to avoid
1639 ** confusion with SQLite lock names). The algorithms are complicated
drhf878e6e2016-04-07 13:45:20 +00001640 ** slightly in order to be compatible with Windows95 systems simultaneously
danielk1977f42f25c2004-06-25 07:21:28 +00001641 ** accessing the same database file, in case that is ever required.
1642 **
1643 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1644 ** byte', each single bytes at well known offsets, and the 'shared byte
1645 ** range', a range of 510 bytes at a well known offset.
1646 **
1647 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
drhf878e6e2016-04-07 13:45:20 +00001648 ** byte'. If this is successful, 'shared byte range' is read-locked
1649 ** and the lock on the 'pending byte' released. (Legacy note: When
1650 ** SQLite was first developed, Windows95 systems were still very common,
1651 ** and Widnows95 lacks a shared-lock capability. So on Windows95, a
1652 ** single randomly selected by from the 'shared byte range' is locked.
1653 ** Windows95 is now pretty much extinct, but this work-around for the
1654 ** lack of shared-locks on Windows95 lives on, for backwards
1655 ** compatibility.)
danielk1977f42f25c2004-06-25 07:21:28 +00001656 **
danielk197790ba3bd2004-06-25 08:32:25 +00001657 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1658 ** A RESERVED lock is implemented by grabbing a write-lock on the
1659 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001660 **
1661 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001662 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1663 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1664 ** obtained, but existing SHARED locks are allowed to persist. A process
1665 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1666 ** This property is used by the algorithm for rolling back a journal file
1667 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001668 **
danielk197790ba3bd2004-06-25 08:32:25 +00001669 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1670 ** implemented by obtaining a write-lock on the entire 'shared byte
1671 ** range'. Since all other locks require a read-lock on one of the bytes
1672 ** within this range, this ensures that no other locks are held on the
1673 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001674 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001675 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001676 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001677 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001678 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001679 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001680
drh054889e2005-11-30 03:20:31 +00001681 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001682 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1683 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh91eb93c2015-03-03 19:56:20 +00001684 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001685 osGetpid(0)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001686
1687 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001688 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001689 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001690 */
drh308c2a52010-05-14 11:30:18 +00001691 if( pFile->eFileLock>=eFileLock ){
1692 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1693 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001694 return SQLITE_OK;
1695 }
1696
drh0c2694b2009-09-03 16:23:44 +00001697 /* Make sure the locking sequence is correct.
1698 ** (1) We never move from unlocked to anything higher than shared lock.
1699 ** (2) SQLite never explicitly requests a pendig lock.
1700 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001701 */
drh308c2a52010-05-14 11:30:18 +00001702 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1703 assert( eFileLock!=PENDING_LOCK );
1704 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001705
drh8af6c222010-05-14 12:43:01 +00001706 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001707 */
drh8af6c222010-05-14 12:43:01 +00001708 pInode = pFile->pInode;
drhda6dc242018-07-23 21:10:37 +00001709 sqlite3_mutex_enter(pInode->pLockMutex);
drh029b44b2006-01-15 00:13:15 +00001710
danielk1977ad94b582007-08-20 06:44:22 +00001711 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001712 ** handle that precludes the requested lock, return BUSY.
1713 */
drh8af6c222010-05-14 12:43:01 +00001714 if( (pFile->eFileLock!=pInode->eFileLock &&
1715 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001716 ){
1717 rc = SQLITE_BUSY;
1718 goto end_lock;
1719 }
1720
1721 /* If a SHARED lock is requested, and some thread using this PID already
1722 ** has a SHARED or RESERVED lock, then increment reference counts and
1723 ** return SQLITE_OK.
1724 */
drh308c2a52010-05-14 11:30:18 +00001725 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001726 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001727 assert( eFileLock==SHARED_LOCK );
1728 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001729 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001730 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001731 pInode->nShared++;
1732 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001733 goto end_lock;
1734 }
1735
danielk19779a1d0ab2004-06-01 14:09:28 +00001736
drh3cde3bb2004-06-12 02:17:14 +00001737 /* A PENDING lock is needed before acquiring a SHARED lock and before
1738 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1739 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001740 */
drh0c2694b2009-09-03 16:23:44 +00001741 lock.l_len = 1L;
1742 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001743 if( eFileLock==SHARED_LOCK
1744 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001745 ){
drh308c2a52010-05-14 11:30:18 +00001746 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001747 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001748 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001749 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001750 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001751 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001752 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001753 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001754 goto end_lock;
1755 }
drh3cde3bb2004-06-12 02:17:14 +00001756 }
1757
1758
1759 /* If control gets to this point, then actually go ahead and make
1760 ** operating system calls for the specified lock.
1761 */
drh308c2a52010-05-14 11:30:18 +00001762 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001763 assert( pInode->nShared==0 );
1764 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001765 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001766
drh2ac3ee92004-06-07 16:27:46 +00001767 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001768 lock.l_start = SHARED_FIRST;
1769 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001770 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001771 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001772 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001773 }
dan661d71a2011-03-30 19:08:03 +00001774
drh2ac3ee92004-06-07 16:27:46 +00001775 /* Drop the temporary PENDING lock */
1776 lock.l_start = PENDING_BYTE;
1777 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001778 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001779 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1780 /* This could happen with a network mount */
1781 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001782 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001783 }
dan661d71a2011-03-30 19:08:03 +00001784
1785 if( rc ){
1786 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001787 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001788 }
dan661d71a2011-03-30 19:08:03 +00001789 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001790 }else{
drh308c2a52010-05-14 11:30:18 +00001791 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001792 pInode->nLock++;
1793 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001794 }
drh8af6c222010-05-14 12:43:01 +00001795 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001796 /* We are trying for an exclusive lock but another thread in this
1797 ** same process is still holding a shared lock. */
1798 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001799 }else{
drh3cde3bb2004-06-12 02:17:14 +00001800 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001801 ** assumed that there is a SHARED or greater lock on the file
1802 ** already.
1803 */
drh308c2a52010-05-14 11:30:18 +00001804 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001805 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001806
1807 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1808 if( eFileLock==RESERVED_LOCK ){
1809 lock.l_start = RESERVED_BYTE;
1810 lock.l_len = 1L;
1811 }else{
1812 lock.l_start = SHARED_FIRST;
1813 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001814 }
dan661d71a2011-03-30 19:08:03 +00001815
1816 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001817 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001818 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001819 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001820 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001821 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001822 }
drhbbd42a62004-05-22 17:41:58 +00001823 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001824
drh8f941bc2009-01-14 23:03:40 +00001825
drhd3d8c042012-05-29 17:02:40 +00001826#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001827 /* Set up the transaction-counter change checking flags when
1828 ** transitioning from a SHARED to a RESERVED lock. The change
1829 ** from SHARED to RESERVED marks the beginning of a normal
1830 ** write operation (not a hot journal rollback).
1831 */
1832 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001833 && pFile->eFileLock<=SHARED_LOCK
1834 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001835 ){
1836 pFile->transCntrChng = 0;
1837 pFile->dbUpdate = 0;
1838 pFile->inNormalWrite = 1;
1839 }
1840#endif
1841
1842
danielk1977ecb2a962004-06-02 06:30:16 +00001843 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001844 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001845 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001846 }else if( eFileLock==EXCLUSIVE_LOCK ){
1847 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001848 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001849 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001850
1851end_lock:
drhda6dc242018-07-23 21:10:37 +00001852 sqlite3_mutex_leave(pInode->pLockMutex);
drh308c2a52010-05-14 11:30:18 +00001853 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1854 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001855 return rc;
1856}
1857
1858/*
dan08da86a2009-08-21 17:18:03 +00001859** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001860** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001861*/
1862static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001863 unixInodeInfo *pInode = pFile->pInode;
drhc68886b2017-08-18 16:09:52 +00001864 UnixUnusedFd *p = pFile->pPreallocatedUnused;
drhef52b362018-08-13 22:50:34 +00001865 assert( unixFileMutexHeld(pFile) );
drh8af6c222010-05-14 12:43:01 +00001866 p->pNext = pInode->pUnused;
1867 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001868 pFile->h = -1;
drhc68886b2017-08-18 16:09:52 +00001869 pFile->pPreallocatedUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001870}
1871
1872/*
drh308c2a52010-05-14 11:30:18 +00001873** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001874** must be either NO_LOCK or SHARED_LOCK.
1875**
1876** If the locking level of the file descriptor is already at or below
1877** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001878**
1879** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1880** the byte range is divided into 2 parts and the first part is unlocked then
1881** set to a read lock, then the other part is simply unlocked. This works
1882** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1883** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001884*/
drha7e61d82011-03-12 17:02:57 +00001885static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001886 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001887 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001888 struct flock lock;
1889 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001890
drh054889e2005-11-30 03:20:31 +00001891 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001892 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001893 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001894 osGetpid(0)));
drha6abd042004-06-09 17:37:22 +00001895
drh308c2a52010-05-14 11:30:18 +00001896 assert( eFileLock<=SHARED_LOCK );
1897 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001898 return SQLITE_OK;
1899 }
drh8af6c222010-05-14 12:43:01 +00001900 pInode = pFile->pInode;
drhda6dc242018-07-23 21:10:37 +00001901 sqlite3_mutex_enter(pInode->pLockMutex);
drh8af6c222010-05-14 12:43:01 +00001902 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001903 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001904 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001905
drhd3d8c042012-05-29 17:02:40 +00001906#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001907 /* When reducing a lock such that other processes can start
1908 ** reading the database file again, make sure that the
1909 ** transaction counter was updated if any part of the database
1910 ** file changed. If the transaction counter is not updated,
1911 ** other connections to the same file might not realize that
1912 ** the file has changed and hence might not know to flush their
1913 ** cache. The use of a stale cache can lead to database corruption.
1914 */
drh8f941bc2009-01-14 23:03:40 +00001915 pFile->inNormalWrite = 0;
1916#endif
1917
drh7ed97b92010-01-20 13:07:21 +00001918 /* downgrading to a shared lock on NFS involves clearing the write lock
1919 ** before establishing the readlock - to avoid a race condition we downgrade
1920 ** the lock in 2 blocks, so that part of the range will be covered by a
1921 ** write lock until the rest is covered by a read lock:
1922 ** 1: [WWWWW]
1923 ** 2: [....W]
1924 ** 3: [RRRRW]
1925 ** 4: [RRRR.]
1926 */
drh308c2a52010-05-14 11:30:18 +00001927 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001928#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001929 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001930 assert( handleNFSUnlock==0 );
1931#endif
1932#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001933 if( handleNFSUnlock ){
drha712b4b2015-02-19 16:12:04 +00001934 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001935 off_t divSize = SHARED_SIZE - 1;
1936
1937 lock.l_type = F_UNLCK;
1938 lock.l_whence = SEEK_SET;
1939 lock.l_start = SHARED_FIRST;
1940 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001941 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001942 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001943 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001944 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001945 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001946 }
drh7ed97b92010-01-20 13:07:21 +00001947 lock.l_type = F_RDLCK;
1948 lock.l_whence = SEEK_SET;
1949 lock.l_start = SHARED_FIRST;
1950 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001951 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001952 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001953 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1954 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001955 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001956 }
1957 goto end_unlock;
1958 }
1959 lock.l_type = F_UNLCK;
1960 lock.l_whence = SEEK_SET;
1961 lock.l_start = SHARED_FIRST+divSize;
1962 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001963 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001964 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001965 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001966 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001967 goto end_unlock;
1968 }
drh30f776f2011-02-25 03:25:07 +00001969 }else
1970#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1971 {
drh7ed97b92010-01-20 13:07:21 +00001972 lock.l_type = F_RDLCK;
1973 lock.l_whence = SEEK_SET;
1974 lock.l_start = SHARED_FIRST;
1975 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001976 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001977 /* In theory, the call to unixFileLock() cannot fail because another
1978 ** process is holding an incompatible lock. If it does, this
1979 ** indicates that the other process is not following the locking
1980 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1981 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1982 ** an assert to fail). */
1983 rc = SQLITE_IOERR_RDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001984 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00001985 goto end_unlock;
1986 }
drh9c105bb2004-10-02 20:38:28 +00001987 }
1988 }
drhbbd42a62004-05-22 17:41:58 +00001989 lock.l_type = F_UNLCK;
1990 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001991 lock.l_start = PENDING_BYTE;
1992 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001993 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001994 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001995 }else{
danea83bc62011-04-01 11:56:32 +00001996 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001997 storeLastErrno(pFile, errno);
drhcd731cf2009-03-28 23:23:02 +00001998 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001999 }
drhbbd42a62004-05-22 17:41:58 +00002000 }
drh308c2a52010-05-14 11:30:18 +00002001 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00002002 /* Decrement the shared lock counter. Release the lock using an
2003 ** OS call only when all threads in this same process have released
2004 ** the lock.
2005 */
drh8af6c222010-05-14 12:43:01 +00002006 pInode->nShared--;
2007 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00002008 lock.l_type = F_UNLCK;
2009 lock.l_whence = SEEK_SET;
2010 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00002011 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00002012 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00002013 }else{
danea83bc62011-04-01 11:56:32 +00002014 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002015 storeLastErrno(pFile, errno);
drh8af6c222010-05-14 12:43:01 +00002016 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002017 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00002018 }
drha6abd042004-06-09 17:37:22 +00002019 }
2020
drhbbd42a62004-05-22 17:41:58 +00002021 /* Decrement the count of locks against this same file. When the
2022 ** count reaches zero, close any other file descriptors whose close
2023 ** was deferred because of outstanding locks.
2024 */
drh8af6c222010-05-14 12:43:01 +00002025 pInode->nLock--;
2026 assert( pInode->nLock>=0 );
drhef52b362018-08-13 22:50:34 +00002027 if( pInode->nLock==0 ) closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00002028 }
drhf2f105d2012-08-20 15:53:54 +00002029
aswift5b1a2562008-08-22 00:22:35 +00002030end_unlock:
drhda6dc242018-07-23 21:10:37 +00002031 sqlite3_mutex_leave(pInode->pLockMutex);
drh095908e2018-08-13 20:46:18 +00002032 if( rc==SQLITE_OK ){
2033 pFile->eFileLock = eFileLock;
drh095908e2018-08-13 20:46:18 +00002034 }
drh9c105bb2004-10-02 20:38:28 +00002035 return rc;
drhbbd42a62004-05-22 17:41:58 +00002036}
2037
2038/*
drh308c2a52010-05-14 11:30:18 +00002039** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002040** must be either NO_LOCK or SHARED_LOCK.
2041**
2042** If the locking level of the file descriptor is already at or below
2043** the requested locking level, this routine is a no-op.
2044*/
drh308c2a52010-05-14 11:30:18 +00002045static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00002046#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00002047 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00002048#endif
drha7e61d82011-03-12 17:02:57 +00002049 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00002050}
2051
mistachkine98844f2013-08-24 00:59:24 +00002052#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00002053static int unixMapfile(unixFile *pFd, i64 nByte);
2054static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00002055#endif
danf23da962013-03-23 21:00:41 +00002056
drh7ed97b92010-01-20 13:07:21 +00002057/*
danielk1977e339d652008-06-28 11:23:00 +00002058** This function performs the parts of the "close file" operation
2059** common to all locking schemes. It closes the directory and file
2060** handles, if they are valid, and sets all fields of the unixFile
2061** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00002062**
2063** It is *not* necessary to hold the mutex when this routine is called,
2064** even on VxWorks. A mutex will be acquired on VxWorks by the
2065** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00002066*/
2067static int closeUnixFile(sqlite3_file *id){
2068 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00002069#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00002070 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00002071#endif
dan661d71a2011-03-30 19:08:03 +00002072 if( pFile->h>=0 ){
2073 robust_close(pFile, pFile->h, __LINE__);
2074 pFile->h = -1;
2075 }
2076#if OS_VXWORKS
2077 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00002078 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00002079 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00002080 }
2081 vxworksReleaseFileId(pFile->pId);
2082 pFile->pId = 0;
2083 }
2084#endif
drh0bdbc902014-06-16 18:35:06 +00002085#ifdef SQLITE_UNLINK_AFTER_CLOSE
2086 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
2087 osUnlink(pFile->zPath);
2088 sqlite3_free(*(char**)&pFile->zPath);
2089 pFile->zPath = 0;
2090 }
2091#endif
dan661d71a2011-03-30 19:08:03 +00002092 OSTRACE(("CLOSE %-3d\n", pFile->h));
2093 OpenCounter(-1);
drhc68886b2017-08-18 16:09:52 +00002094 sqlite3_free(pFile->pPreallocatedUnused);
dan661d71a2011-03-30 19:08:03 +00002095 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00002096 return SQLITE_OK;
2097}
2098
2099/*
danielk1977e3026632004-06-22 11:29:02 +00002100** Close a file.
2101*/
danielk197762079062007-08-15 17:08:46 +00002102static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00002103 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00002104 unixFile *pFile = (unixFile *)id;
drhef52b362018-08-13 22:50:34 +00002105 unixInodeInfo *pInode = pFile->pInode;
2106
2107 assert( pInode!=0 );
drhfbc7e882013-04-11 01:16:15 +00002108 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00002109 unixUnlock(id, NO_LOCK);
drh095908e2018-08-13 20:46:18 +00002110 assert( unixFileMutexNotheld(pFile) );
dan661d71a2011-03-30 19:08:03 +00002111 unixEnterMutex();
2112
2113 /* unixFile.pInode is always valid here. Otherwise, a different close
2114 ** routine (e.g. nolockClose()) would be called instead.
2115 */
2116 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
drhef52b362018-08-13 22:50:34 +00002117 sqlite3_mutex_enter(pInode->pLockMutex);
drh3fcef1a2018-08-16 16:24:24 +00002118 if( pInode->nLock ){
dan661d71a2011-03-30 19:08:03 +00002119 /* If there are outstanding locks, do not actually close the file just
2120 ** yet because that would clear those locks. Instead, add the file
2121 ** descriptor to pInode->pUnused list. It will be automatically closed
2122 ** when the last lock is cleared.
2123 */
2124 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00002125 }
drhef52b362018-08-13 22:50:34 +00002126 sqlite3_mutex_leave(pInode->pLockMutex);
dan661d71a2011-03-30 19:08:03 +00002127 releaseInodeInfo(pFile);
2128 rc = closeUnixFile(id);
2129 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00002130 return rc;
danielk1977e3026632004-06-22 11:29:02 +00002131}
2132
drh734c9862008-11-28 15:37:20 +00002133/************** End of the posix advisory lock implementation *****************
2134******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002135
drh734c9862008-11-28 15:37:20 +00002136/******************************************************************************
2137****************************** No-op Locking **********************************
2138**
2139** Of the various locking implementations available, this is by far the
2140** simplest: locking is ignored. No attempt is made to lock the database
2141** file for reading or writing.
2142**
2143** This locking mode is appropriate for use on read-only databases
2144** (ex: databases that are burned into CD-ROM, for example.) It can
2145** also be used if the application employs some external mechanism to
2146** prevent simultaneous access of the same database by two or more
2147** database connections. But there is a serious risk of database
2148** corruption if this locking mode is used in situations where multiple
2149** database connections are accessing the same database file at the same
2150** time and one or more of those connections are writing.
2151*/
drhbfe66312006-10-03 17:40:40 +00002152
drh734c9862008-11-28 15:37:20 +00002153static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
2154 UNUSED_PARAMETER(NotUsed);
2155 *pResOut = 0;
2156 return SQLITE_OK;
2157}
drh734c9862008-11-28 15:37:20 +00002158static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
2159 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2160 return SQLITE_OK;
2161}
drh734c9862008-11-28 15:37:20 +00002162static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
2163 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2164 return SQLITE_OK;
2165}
2166
2167/*
drh9b35ea62008-11-29 02:20:26 +00002168** Close the file.
drh734c9862008-11-28 15:37:20 +00002169*/
2170static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00002171 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002172}
2173
2174/******************* End of the no-op lock implementation *********************
2175******************************************************************************/
2176
2177/******************************************************************************
2178************************* Begin dot-file Locking ******************************
2179**
mistachkin48864df2013-03-21 21:20:32 +00002180** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00002181** files (really a directory) to control access to the database. This works
2182** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002183**
2184** (1) There is zero concurrency. A single reader blocks all other
2185** connections from reading or writing the database.
2186**
2187** (2) An application crash or power loss can leave stale lock files
2188** sitting around that need to be cleared manually.
2189**
2190** Nevertheless, a dotlock is an appropriate locking mode for use if no
2191** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002192**
drh9ef6bc42011-11-04 02:24:02 +00002193** Dotfile locking works by creating a subdirectory in the same directory as
2194** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002195** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002196** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002197*/
2198
2199/*
2200** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002201** lock directory.
drh734c9862008-11-28 15:37:20 +00002202*/
2203#define DOTLOCK_SUFFIX ".lock"
2204
drh7708e972008-11-29 00:56:52 +00002205/*
2206** This routine checks if there is a RESERVED lock held on the specified
2207** file by this or any other process. If such a lock is held, set *pResOut
2208** to a non-zero value otherwise *pResOut is set to zero. The return value
2209** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2210**
2211** In dotfile locking, either a lock exists or it does not. So in this
2212** variation of CheckReservedLock(), *pResOut is set to true if any lock
2213** is held on the file and false if the file is unlocked.
2214*/
drh734c9862008-11-28 15:37:20 +00002215static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2216 int rc = SQLITE_OK;
2217 int reserved = 0;
2218 unixFile *pFile = (unixFile*)id;
2219
2220 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2221
2222 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00002223 reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
drh308c2a52010-05-14 11:30:18 +00002224 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002225 *pResOut = reserved;
2226 return rc;
2227}
2228
drh7708e972008-11-29 00:56:52 +00002229/*
drh308c2a52010-05-14 11:30:18 +00002230** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002231** of the following:
2232**
2233** (1) SHARED_LOCK
2234** (2) RESERVED_LOCK
2235** (3) PENDING_LOCK
2236** (4) EXCLUSIVE_LOCK
2237**
2238** Sometimes when requesting one lock state, additional lock states
2239** are inserted in between. The locking might fail on one of the later
2240** transitions leaving the lock state different from what it started but
2241** still short of its goal. The following chart shows the allowed
2242** transitions and the inserted intermediate states:
2243**
2244** UNLOCKED -> SHARED
2245** SHARED -> RESERVED
2246** SHARED -> (PENDING) -> EXCLUSIVE
2247** RESERVED -> (PENDING) -> EXCLUSIVE
2248** PENDING -> EXCLUSIVE
2249**
2250** This routine will only increase a lock. Use the sqlite3OsUnlock()
2251** routine to lower a locking level.
2252**
2253** With dotfile locking, we really only support state (4): EXCLUSIVE.
2254** But we track the other locking levels internally.
2255*/
drh308c2a52010-05-14 11:30:18 +00002256static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002257 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002258 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002259 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002260
drh7708e972008-11-29 00:56:52 +00002261
2262 /* If we have any lock, then the lock file already exists. All we have
2263 ** to do is adjust our internal record of the lock level.
2264 */
drh308c2a52010-05-14 11:30:18 +00002265 if( pFile->eFileLock > NO_LOCK ){
2266 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002267 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002268#ifdef HAVE_UTIME
2269 utime(zLockFile, NULL);
2270#else
drh734c9862008-11-28 15:37:20 +00002271 utimes(zLockFile, NULL);
2272#endif
drh7708e972008-11-29 00:56:52 +00002273 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002274 }
2275
2276 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002277 rc = osMkdir(zLockFile, 0777);
2278 if( rc<0 ){
2279 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002280 int tErrno = errno;
2281 if( EEXIST == tErrno ){
2282 rc = SQLITE_BUSY;
2283 } else {
2284 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drha8de1e12015-11-30 00:05:39 +00002285 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00002286 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002287 }
2288 }
drh7708e972008-11-29 00:56:52 +00002289 return rc;
drh734c9862008-11-28 15:37:20 +00002290 }
drh734c9862008-11-28 15:37:20 +00002291
2292 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002293 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002294 return rc;
2295}
2296
drh7708e972008-11-29 00:56:52 +00002297/*
drh308c2a52010-05-14 11:30:18 +00002298** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002299** must be either NO_LOCK or SHARED_LOCK.
2300**
2301** If the locking level of the file descriptor is already at or below
2302** the requested locking level, this routine is a no-op.
2303**
2304** When the locking level reaches NO_LOCK, delete the lock file.
2305*/
drh308c2a52010-05-14 11:30:18 +00002306static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002307 unixFile *pFile = (unixFile*)id;
2308 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002309 int rc;
drh734c9862008-11-28 15:37:20 +00002310
2311 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002312 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002313 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002314 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002315
2316 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002317 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002318 return SQLITE_OK;
2319 }
drh7708e972008-11-29 00:56:52 +00002320
2321 /* To downgrade to shared, simply update our internal notion of the
2322 ** lock state. No need to mess with the file on disk.
2323 */
drh308c2a52010-05-14 11:30:18 +00002324 if( eFileLock==SHARED_LOCK ){
2325 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002326 return SQLITE_OK;
2327 }
2328
drh7708e972008-11-29 00:56:52 +00002329 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002330 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002331 rc = osRmdir(zLockFile);
drh9ef6bc42011-11-04 02:24:02 +00002332 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002333 int tErrno = errno;
drha8de1e12015-11-30 00:05:39 +00002334 if( tErrno==ENOENT ){
2335 rc = SQLITE_OK;
2336 }else{
danea83bc62011-04-01 11:56:32 +00002337 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002338 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002339 }
2340 return rc;
2341 }
drh308c2a52010-05-14 11:30:18 +00002342 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002343 return SQLITE_OK;
2344}
2345
2346/*
drh9b35ea62008-11-29 02:20:26 +00002347** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002348*/
2349static int dotlockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002350 unixFile *pFile = (unixFile*)id;
2351 assert( id!=0 );
2352 dotlockUnlock(id, NO_LOCK);
2353 sqlite3_free(pFile->lockingContext);
2354 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002355}
2356/****************** End of the dot-file lock implementation *******************
2357******************************************************************************/
2358
2359/******************************************************************************
2360************************** Begin flock Locking ********************************
2361**
2362** Use the flock() system call to do file locking.
2363**
drh6b9d6dd2008-12-03 19:34:47 +00002364** flock() locking is like dot-file locking in that the various
2365** fine-grain locking levels supported by SQLite are collapsed into
2366** a single exclusive lock. In other words, SHARED, RESERVED, and
2367** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2368** still works when you do this, but concurrency is reduced since
2369** only a single process can be reading the database at a time.
2370**
drhe89b2912015-03-03 20:42:01 +00002371** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
drh734c9862008-11-28 15:37:20 +00002372*/
drhe89b2912015-03-03 20:42:01 +00002373#if SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002374
drh6b9d6dd2008-12-03 19:34:47 +00002375/*
drhff812312011-02-23 13:33:46 +00002376** Retry flock() calls that fail with EINTR
2377*/
2378#ifdef EINTR
2379static int robust_flock(int fd, int op){
2380 int rc;
2381 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2382 return rc;
2383}
2384#else
drh5c819272011-02-23 14:00:12 +00002385# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002386#endif
2387
2388
2389/*
drh6b9d6dd2008-12-03 19:34:47 +00002390** This routine checks if there is a RESERVED lock held on the specified
2391** file by this or any other process. If such a lock is held, set *pResOut
2392** to a non-zero value otherwise *pResOut is set to zero. The return value
2393** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2394*/
drh734c9862008-11-28 15:37:20 +00002395static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2396 int rc = SQLITE_OK;
2397 int reserved = 0;
2398 unixFile *pFile = (unixFile*)id;
2399
2400 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2401
2402 assert( pFile );
2403
2404 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002405 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002406 reserved = 1;
2407 }
2408
2409 /* Otherwise see if some other process holds it. */
2410 if( !reserved ){
2411 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002412 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002413 if( !lrc ){
2414 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002415 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002416 if ( lrc ) {
2417 int tErrno = errno;
2418 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002419 lrc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00002420 storeLastErrno(pFile, tErrno);
2421 rc = lrc;
drh734c9862008-11-28 15:37:20 +00002422 }
2423 } else {
2424 int tErrno = errno;
2425 reserved = 1;
2426 /* someone else might have it reserved */
2427 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2428 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002429 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002430 rc = lrc;
2431 }
2432 }
2433 }
drh308c2a52010-05-14 11:30:18 +00002434 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002435
2436#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
drh2e233812017-08-22 15:21:54 +00002437 if( (rc & 0xff) == SQLITE_IOERR ){
drh734c9862008-11-28 15:37:20 +00002438 rc = SQLITE_OK;
2439 reserved=1;
2440 }
2441#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2442 *pResOut = reserved;
2443 return rc;
2444}
2445
drh6b9d6dd2008-12-03 19:34:47 +00002446/*
drh308c2a52010-05-14 11:30:18 +00002447** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002448** of the following:
2449**
2450** (1) SHARED_LOCK
2451** (2) RESERVED_LOCK
2452** (3) PENDING_LOCK
2453** (4) EXCLUSIVE_LOCK
2454**
2455** Sometimes when requesting one lock state, additional lock states
2456** are inserted in between. The locking might fail on one of the later
2457** transitions leaving the lock state different from what it started but
2458** still short of its goal. The following chart shows the allowed
2459** transitions and the inserted intermediate states:
2460**
2461** UNLOCKED -> SHARED
2462** SHARED -> RESERVED
2463** SHARED -> (PENDING) -> EXCLUSIVE
2464** RESERVED -> (PENDING) -> EXCLUSIVE
2465** PENDING -> EXCLUSIVE
2466**
2467** flock() only really support EXCLUSIVE locks. We track intermediate
2468** lock states in the sqlite3_file structure, but all locks SHARED or
2469** above are really EXCLUSIVE locks and exclude all other processes from
2470** access the file.
2471**
2472** This routine will only increase a lock. Use the sqlite3OsUnlock()
2473** routine to lower a locking level.
2474*/
drh308c2a52010-05-14 11:30:18 +00002475static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002476 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002477 unixFile *pFile = (unixFile*)id;
2478
2479 assert( pFile );
2480
2481 /* if we already have a lock, it is exclusive.
2482 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002483 if (pFile->eFileLock > NO_LOCK) {
2484 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002485 return SQLITE_OK;
2486 }
2487
2488 /* grab an exclusive lock */
2489
drhff812312011-02-23 13:33:46 +00002490 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002491 int tErrno = errno;
2492 /* didn't get, must be busy */
2493 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2494 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002495 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002496 }
2497 } else {
2498 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002499 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002500 }
drh308c2a52010-05-14 11:30:18 +00002501 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2502 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002503#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
drh2e233812017-08-22 15:21:54 +00002504 if( (rc & 0xff) == SQLITE_IOERR ){
drh734c9862008-11-28 15:37:20 +00002505 rc = SQLITE_BUSY;
2506 }
2507#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2508 return rc;
2509}
2510
drh6b9d6dd2008-12-03 19:34:47 +00002511
2512/*
drh308c2a52010-05-14 11:30:18 +00002513** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002514** must be either NO_LOCK or SHARED_LOCK.
2515**
2516** If the locking level of the file descriptor is already at or below
2517** the requested locking level, this routine is a no-op.
2518*/
drh308c2a52010-05-14 11:30:18 +00002519static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002520 unixFile *pFile = (unixFile*)id;
2521
2522 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002523 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002524 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002525 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002526
2527 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002528 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002529 return SQLITE_OK;
2530 }
2531
2532 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002533 if (eFileLock==SHARED_LOCK) {
2534 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002535 return SQLITE_OK;
2536 }
2537
2538 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002539 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002540#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002541 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002542#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002543 return SQLITE_IOERR_UNLOCK;
2544 }else{
drh308c2a52010-05-14 11:30:18 +00002545 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002546 return SQLITE_OK;
2547 }
2548}
2549
2550/*
2551** Close a file.
2552*/
2553static int flockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002554 assert( id!=0 );
2555 flockUnlock(id, NO_LOCK);
2556 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002557}
2558
2559#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2560
2561/******************* End of the flock lock implementation *********************
2562******************************************************************************/
2563
2564/******************************************************************************
2565************************ Begin Named Semaphore Locking ************************
2566**
2567** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002568**
2569** Semaphore locking is like dot-lock and flock in that it really only
2570** supports EXCLUSIVE locking. Only a single process can read or write
2571** the database file at a time. This reduces potential concurrency, but
2572** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002573*/
2574#if OS_VXWORKS
2575
drh6b9d6dd2008-12-03 19:34:47 +00002576/*
2577** This routine checks if there is a RESERVED lock held on the specified
2578** file by this or any other process. If such a lock is held, set *pResOut
2579** to a non-zero value otherwise *pResOut is set to zero. The return value
2580** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2581*/
drh8cd5b252015-03-02 22:06:43 +00002582static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
drh734c9862008-11-28 15:37:20 +00002583 int rc = SQLITE_OK;
2584 int reserved = 0;
2585 unixFile *pFile = (unixFile*)id;
2586
2587 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2588
2589 assert( pFile );
2590
2591 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002592 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002593 reserved = 1;
2594 }
2595
2596 /* Otherwise see if some other process holds it. */
2597 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002598 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002599
2600 if( sem_trywait(pSem)==-1 ){
2601 int tErrno = errno;
2602 if( EAGAIN != tErrno ){
2603 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
drh4bf66fd2015-02-19 02:43:02 +00002604 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002605 } else {
2606 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002607 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002608 }
2609 }else{
2610 /* we could have it if we want it */
2611 sem_post(pSem);
2612 }
2613 }
drh308c2a52010-05-14 11:30:18 +00002614 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002615
2616 *pResOut = reserved;
2617 return rc;
2618}
2619
drh6b9d6dd2008-12-03 19:34:47 +00002620/*
drh308c2a52010-05-14 11:30:18 +00002621** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002622** of the following:
2623**
2624** (1) SHARED_LOCK
2625** (2) RESERVED_LOCK
2626** (3) PENDING_LOCK
2627** (4) EXCLUSIVE_LOCK
2628**
2629** Sometimes when requesting one lock state, additional lock states
2630** are inserted in between. The locking might fail on one of the later
2631** transitions leaving the lock state different from what it started but
2632** still short of its goal. The following chart shows the allowed
2633** transitions and the inserted intermediate states:
2634**
2635** UNLOCKED -> SHARED
2636** SHARED -> RESERVED
2637** SHARED -> (PENDING) -> EXCLUSIVE
2638** RESERVED -> (PENDING) -> EXCLUSIVE
2639** PENDING -> EXCLUSIVE
2640**
2641** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2642** lock states in the sqlite3_file structure, but all locks SHARED or
2643** above are really EXCLUSIVE locks and exclude all other processes from
2644** access the file.
2645**
2646** This routine will only increase a lock. Use the sqlite3OsUnlock()
2647** routine to lower a locking level.
2648*/
drh8cd5b252015-03-02 22:06:43 +00002649static int semXLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002650 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002651 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002652 int rc = SQLITE_OK;
2653
2654 /* if we already have a lock, it is exclusive.
2655 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002656 if (pFile->eFileLock > NO_LOCK) {
2657 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002658 rc = SQLITE_OK;
2659 goto sem_end_lock;
2660 }
2661
2662 /* lock semaphore now but bail out when already locked. */
2663 if( sem_trywait(pSem)==-1 ){
2664 rc = SQLITE_BUSY;
2665 goto sem_end_lock;
2666 }
2667
2668 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002669 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002670
2671 sem_end_lock:
2672 return rc;
2673}
2674
drh6b9d6dd2008-12-03 19:34:47 +00002675/*
drh308c2a52010-05-14 11:30:18 +00002676** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002677** must be either NO_LOCK or SHARED_LOCK.
2678**
2679** If the locking level of the file descriptor is already at or below
2680** the requested locking level, this routine is a no-op.
2681*/
drh8cd5b252015-03-02 22:06:43 +00002682static int semXUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002683 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002684 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002685
2686 assert( pFile );
2687 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002688 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002689 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002690 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002691
2692 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002693 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002694 return SQLITE_OK;
2695 }
2696
2697 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002698 if (eFileLock==SHARED_LOCK) {
2699 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002700 return SQLITE_OK;
2701 }
2702
2703 /* no, really unlock. */
2704 if ( sem_post(pSem)==-1 ) {
2705 int rc, tErrno = errno;
2706 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2707 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002708 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002709 }
2710 return rc;
2711 }
drh308c2a52010-05-14 11:30:18 +00002712 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002713 return SQLITE_OK;
2714}
2715
2716/*
2717 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002718 */
drh8cd5b252015-03-02 22:06:43 +00002719static int semXClose(sqlite3_file *id) {
drh734c9862008-11-28 15:37:20 +00002720 if( id ){
2721 unixFile *pFile = (unixFile*)id;
drh8cd5b252015-03-02 22:06:43 +00002722 semXUnlock(id, NO_LOCK);
drh734c9862008-11-28 15:37:20 +00002723 assert( pFile );
drh095908e2018-08-13 20:46:18 +00002724 assert( unixFileMutexNotheld(pFile) );
drh734c9862008-11-28 15:37:20 +00002725 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002726 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002727 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002728 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002729 }
2730 return SQLITE_OK;
2731}
2732
2733#endif /* OS_VXWORKS */
2734/*
2735** Named semaphore locking is only available on VxWorks.
2736**
2737*************** End of the named semaphore lock implementation ****************
2738******************************************************************************/
2739
2740
2741/******************************************************************************
2742*************************** Begin AFP Locking *********************************
2743**
2744** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2745** on Apple Macintosh computers - both OS9 and OSX.
2746**
2747** Third-party implementations of AFP are available. But this code here
2748** only works on OSX.
2749*/
2750
drhd2cb50b2009-01-09 21:41:17 +00002751#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002752/*
2753** The afpLockingContext structure contains all afp lock specific state
2754*/
drhbfe66312006-10-03 17:40:40 +00002755typedef struct afpLockingContext afpLockingContext;
2756struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002757 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002758 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002759};
2760
2761struct ByteRangeLockPB2
2762{
2763 unsigned long long offset; /* offset to first byte to lock */
2764 unsigned long long length; /* nbr of bytes to lock */
2765 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2766 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2767 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2768 int fd; /* file desc to assoc this lock with */
2769};
2770
drhfd131da2007-08-07 17:13:03 +00002771#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002772
drh6b9d6dd2008-12-03 19:34:47 +00002773/*
2774** This is a utility for setting or clearing a bit-range lock on an
2775** AFP filesystem.
2776**
2777** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2778*/
2779static int afpSetLock(
2780 const char *path, /* Name of the file to be locked or unlocked */
2781 unixFile *pFile, /* Open file descriptor on path */
2782 unsigned long long offset, /* First byte to be locked */
2783 unsigned long long length, /* Number of bytes to lock */
2784 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002785){
drh6b9d6dd2008-12-03 19:34:47 +00002786 struct ByteRangeLockPB2 pb;
2787 int err;
drhbfe66312006-10-03 17:40:40 +00002788
2789 pb.unLockFlag = setLockFlag ? 0 : 1;
2790 pb.startEndFlag = 0;
2791 pb.offset = offset;
2792 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002793 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002794
drh308c2a52010-05-14 11:30:18 +00002795 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002796 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002797 offset, length));
drhbfe66312006-10-03 17:40:40 +00002798 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2799 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002800 int rc;
2801 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002802 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2803 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002804#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2805 rc = SQLITE_BUSY;
2806#else
drh734c9862008-11-28 15:37:20 +00002807 rc = sqliteErrorFromPosixError(tErrno,
2808 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002809#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002810 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002811 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00002812 }
2813 return rc;
drhbfe66312006-10-03 17:40:40 +00002814 } else {
aswift5b1a2562008-08-22 00:22:35 +00002815 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002816 }
2817}
2818
drh6b9d6dd2008-12-03 19:34:47 +00002819/*
2820** This routine checks if there is a RESERVED lock held on the specified
2821** file by this or any other process. If such a lock is held, set *pResOut
2822** to a non-zero value otherwise *pResOut is set to zero. The return value
2823** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2824*/
danielk1977e339d652008-06-28 11:23:00 +00002825static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002826 int rc = SQLITE_OK;
2827 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002828 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002829 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002830
aswift5b1a2562008-08-22 00:22:35 +00002831 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2832
2833 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002834 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002835 if( context->reserved ){
2836 *pResOut = 1;
2837 return SQLITE_OK;
2838 }
drhda6dc242018-07-23 21:10:37 +00002839 sqlite3_mutex_enter(pFile->pInode->pLockMutex);
drhbfe66312006-10-03 17:40:40 +00002840 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002841 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002842 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002843 }
2844
2845 /* Otherwise see if some other process holds it.
2846 */
aswift5b1a2562008-08-22 00:22:35 +00002847 if( !reserved ){
2848 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002849 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002850 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002851 /* if we succeeded in taking the reserved lock, unlock it to restore
2852 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002853 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002854 } else {
2855 /* if we failed to get the lock then someone else must have it */
2856 reserved = 1;
2857 }
2858 if( IS_LOCK_ERROR(lrc) ){
2859 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002860 }
2861 }
drhbfe66312006-10-03 17:40:40 +00002862
drhda6dc242018-07-23 21:10:37 +00002863 sqlite3_mutex_leave(pFile->pInode->pLockMutex);
drh308c2a52010-05-14 11:30:18 +00002864 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002865
2866 *pResOut = reserved;
2867 return rc;
drhbfe66312006-10-03 17:40:40 +00002868}
2869
drh6b9d6dd2008-12-03 19:34:47 +00002870/*
drh308c2a52010-05-14 11:30:18 +00002871** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002872** of the following:
2873**
2874** (1) SHARED_LOCK
2875** (2) RESERVED_LOCK
2876** (3) PENDING_LOCK
2877** (4) EXCLUSIVE_LOCK
2878**
2879** Sometimes when requesting one lock state, additional lock states
2880** are inserted in between. The locking might fail on one of the later
2881** transitions leaving the lock state different from what it started but
2882** still short of its goal. The following chart shows the allowed
2883** transitions and the inserted intermediate states:
2884**
2885** UNLOCKED -> SHARED
2886** SHARED -> RESERVED
2887** SHARED -> (PENDING) -> EXCLUSIVE
2888** RESERVED -> (PENDING) -> EXCLUSIVE
2889** PENDING -> EXCLUSIVE
2890**
2891** This routine will only increase a lock. Use the sqlite3OsUnlock()
2892** routine to lower a locking level.
2893*/
drh308c2a52010-05-14 11:30:18 +00002894static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002895 int rc = SQLITE_OK;
2896 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002897 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002898 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002899
2900 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002901 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2902 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh5ac93652015-03-21 20:59:43 +00002903 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
drh339eb0b2008-03-07 15:34:11 +00002904
drhbfe66312006-10-03 17:40:40 +00002905 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002906 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002907 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002908 */
drh308c2a52010-05-14 11:30:18 +00002909 if( pFile->eFileLock>=eFileLock ){
2910 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2911 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002912 return SQLITE_OK;
2913 }
2914
2915 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002916 ** (1) We never move from unlocked to anything higher than shared lock.
2917 ** (2) SQLite never explicitly requests a pendig lock.
2918 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002919 */
drh308c2a52010-05-14 11:30:18 +00002920 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2921 assert( eFileLock!=PENDING_LOCK );
2922 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002923
drh8af6c222010-05-14 12:43:01 +00002924 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002925 */
drh8af6c222010-05-14 12:43:01 +00002926 pInode = pFile->pInode;
drhda6dc242018-07-23 21:10:37 +00002927 sqlite3_mutex_enter(pInode->pLockMutex);
drh7ed97b92010-01-20 13:07:21 +00002928
2929 /* If some thread using this PID has a lock via a different unixFile*
2930 ** handle that precludes the requested lock, return BUSY.
2931 */
drh8af6c222010-05-14 12:43:01 +00002932 if( (pFile->eFileLock!=pInode->eFileLock &&
2933 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002934 ){
2935 rc = SQLITE_BUSY;
2936 goto afp_end_lock;
2937 }
2938
2939 /* If a SHARED lock is requested, and some thread using this PID already
2940 ** has a SHARED or RESERVED lock, then increment reference counts and
2941 ** return SQLITE_OK.
2942 */
drh308c2a52010-05-14 11:30:18 +00002943 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002944 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002945 assert( eFileLock==SHARED_LOCK );
2946 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002947 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002948 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002949 pInode->nShared++;
2950 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002951 goto afp_end_lock;
2952 }
drhbfe66312006-10-03 17:40:40 +00002953
2954 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002955 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2956 ** be released.
2957 */
drh308c2a52010-05-14 11:30:18 +00002958 if( eFileLock==SHARED_LOCK
2959 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002960 ){
2961 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002962 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002963 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002964 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002965 goto afp_end_lock;
2966 }
2967 }
2968
2969 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002970 ** operating system calls for the specified lock.
2971 */
drh308c2a52010-05-14 11:30:18 +00002972 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002973 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002974 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002975
drh8af6c222010-05-14 12:43:01 +00002976 assert( pInode->nShared==0 );
2977 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002978
2979 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002980 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002981 /* note that the quality of the randomness doesn't matter that much */
2982 lk = random();
drh8af6c222010-05-14 12:43:01 +00002983 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002984 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002985 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002986 if( IS_LOCK_ERROR(lrc1) ){
2987 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002988 }
aswift5b1a2562008-08-22 00:22:35 +00002989 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002990 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002991
aswift5b1a2562008-08-22 00:22:35 +00002992 if( IS_LOCK_ERROR(lrc1) ) {
drh4bf66fd2015-02-19 02:43:02 +00002993 storeLastErrno(pFile, lrc1Errno);
aswift5b1a2562008-08-22 00:22:35 +00002994 rc = lrc1;
2995 goto afp_end_lock;
2996 } else if( IS_LOCK_ERROR(lrc2) ){
2997 rc = lrc2;
2998 goto afp_end_lock;
2999 } else if( lrc1 != SQLITE_OK ) {
3000 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00003001 } else {
drh308c2a52010-05-14 11:30:18 +00003002 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00003003 pInode->nLock++;
3004 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00003005 }
drh8af6c222010-05-14 12:43:01 +00003006 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00003007 /* We are trying for an exclusive lock but another thread in this
3008 ** same process is still holding a shared lock. */
3009 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00003010 }else{
3011 /* The request was for a RESERVED or EXCLUSIVE lock. It is
3012 ** assumed that there is a SHARED or greater lock on the file
3013 ** already.
3014 */
3015 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00003016 assert( 0!=pFile->eFileLock );
3017 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00003018 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00003019 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00003020 if( !failed ){
3021 context->reserved = 1;
3022 }
drhbfe66312006-10-03 17:40:40 +00003023 }
drh308c2a52010-05-14 11:30:18 +00003024 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00003025 /* Acquire an EXCLUSIVE lock */
3026
3027 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00003028 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00003029 */
drh6b9d6dd2008-12-03 19:34:47 +00003030 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00003031 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00003032 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00003033 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00003034 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00003035 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00003036 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00003037 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00003038 /* Can't reestablish the shared lock. Sqlite can't deal, this is
3039 ** a critical I/O error
3040 */
drh2e233812017-08-22 15:21:54 +00003041 rc = ((failed & 0xff) == SQLITE_IOERR) ? failed2 :
aswiftaebf4132008-11-21 00:10:35 +00003042 SQLITE_IOERR_LOCK;
3043 goto afp_end_lock;
3044 }
3045 }else{
aswift5b1a2562008-08-22 00:22:35 +00003046 rc = failed;
drhbfe66312006-10-03 17:40:40 +00003047 }
3048 }
aswift5b1a2562008-08-22 00:22:35 +00003049 if( failed ){
3050 rc = failed;
drhbfe66312006-10-03 17:40:40 +00003051 }
3052 }
3053
3054 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00003055 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00003056 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00003057 }else if( eFileLock==EXCLUSIVE_LOCK ){
3058 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00003059 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00003060 }
3061
3062afp_end_lock:
drhda6dc242018-07-23 21:10:37 +00003063 sqlite3_mutex_leave(pInode->pLockMutex);
drh308c2a52010-05-14 11:30:18 +00003064 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
3065 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00003066 return rc;
3067}
3068
3069/*
drh308c2a52010-05-14 11:30:18 +00003070** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00003071** must be either NO_LOCK or SHARED_LOCK.
3072**
3073** If the locking level of the file descriptor is already at or below
3074** the requested locking level, this routine is a no-op.
3075*/
drh308c2a52010-05-14 11:30:18 +00003076static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00003077 int rc = SQLITE_OK;
3078 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00003079 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00003080 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
3081 int skipShared = 0;
3082#ifdef SQLITE_TEST
3083 int h = pFile->h;
3084#endif
drhbfe66312006-10-03 17:40:40 +00003085
3086 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003087 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00003088 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00003089 osGetpid(0)));
aswift5b1a2562008-08-22 00:22:35 +00003090
drh308c2a52010-05-14 11:30:18 +00003091 assert( eFileLock<=SHARED_LOCK );
3092 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00003093 return SQLITE_OK;
3094 }
drh8af6c222010-05-14 12:43:01 +00003095 pInode = pFile->pInode;
drhda6dc242018-07-23 21:10:37 +00003096 sqlite3_mutex_enter(pInode->pLockMutex);
drh8af6c222010-05-14 12:43:01 +00003097 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00003098 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00003099 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00003100 SimulateIOErrorBenign(1);
3101 SimulateIOError( h=(-1) )
3102 SimulateIOErrorBenign(0);
3103
drhd3d8c042012-05-29 17:02:40 +00003104#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00003105 /* When reducing a lock such that other processes can start
3106 ** reading the database file again, make sure that the
3107 ** transaction counter was updated if any part of the database
3108 ** file changed. If the transaction counter is not updated,
3109 ** other connections to the same file might not realize that
3110 ** the file has changed and hence might not know to flush their
3111 ** cache. The use of a stale cache can lead to database corruption.
3112 */
3113 assert( pFile->inNormalWrite==0
3114 || pFile->dbUpdate==0
3115 || pFile->transCntrChng==1 );
3116 pFile->inNormalWrite = 0;
3117#endif
aswiftaebf4132008-11-21 00:10:35 +00003118
drh308c2a52010-05-14 11:30:18 +00003119 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00003120 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00003121 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00003122 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00003123 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00003124 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
3125 } else {
3126 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00003127 }
3128 }
drh308c2a52010-05-14 11:30:18 +00003129 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00003130 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00003131 }
drh308c2a52010-05-14 11:30:18 +00003132 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00003133 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
3134 if( !rc ){
3135 context->reserved = 0;
3136 }
aswiftaebf4132008-11-21 00:10:35 +00003137 }
drh8af6c222010-05-14 12:43:01 +00003138 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
3139 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003140 }
aswiftaebf4132008-11-21 00:10:35 +00003141 }
drh308c2a52010-05-14 11:30:18 +00003142 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00003143
drh7ed97b92010-01-20 13:07:21 +00003144 /* Decrement the shared lock counter. Release the lock using an
3145 ** OS call only when all threads in this same process have released
3146 ** the lock.
3147 */
drh8af6c222010-05-14 12:43:01 +00003148 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3149 pInode->nShared--;
3150 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00003151 SimulateIOErrorBenign(1);
3152 SimulateIOError( h=(-1) )
3153 SimulateIOErrorBenign(0);
3154 if( !skipShared ){
3155 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
3156 }
3157 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00003158 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00003159 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003160 }
3161 }
3162 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00003163 pInode->nLock--;
3164 assert( pInode->nLock>=0 );
drhef52b362018-08-13 22:50:34 +00003165 if( pInode->nLock==0 ) closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00003166 }
drhbfe66312006-10-03 17:40:40 +00003167 }
drh7ed97b92010-01-20 13:07:21 +00003168
drhda6dc242018-07-23 21:10:37 +00003169 sqlite3_mutex_leave(pInode->pLockMutex);
drh095908e2018-08-13 20:46:18 +00003170 if( rc==SQLITE_OK ){
3171 pFile->eFileLock = eFileLock;
drh095908e2018-08-13 20:46:18 +00003172 }
drhbfe66312006-10-03 17:40:40 +00003173 return rc;
3174}
3175
3176/*
drh339eb0b2008-03-07 15:34:11 +00003177** Close a file & cleanup AFP specific locking context
3178*/
danielk1977e339d652008-06-28 11:23:00 +00003179static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003180 int rc = SQLITE_OK;
drha8de1e12015-11-30 00:05:39 +00003181 unixFile *pFile = (unixFile*)id;
3182 assert( id!=0 );
3183 afpUnlock(id, NO_LOCK);
drh095908e2018-08-13 20:46:18 +00003184 assert( unixFileMutexNotheld(pFile) );
drha8de1e12015-11-30 00:05:39 +00003185 unixEnterMutex();
drhef52b362018-08-13 22:50:34 +00003186 if( pFile->pInode ){
3187 unixInodeInfo *pInode = pFile->pInode;
3188 sqlite3_mutex_enter(pInode->pLockMutex);
drhcb4e4b02018-09-06 19:36:29 +00003189 if( pInode->nLock ){
drhef52b362018-08-13 22:50:34 +00003190 /* If there are outstanding locks, do not actually close the file just
3191 ** yet because that would clear those locks. Instead, add the file
3192 ** descriptor to pInode->aPending. It will be automatically closed when
3193 ** the last lock is cleared.
3194 */
3195 setPendingFd(pFile);
3196 }
3197 sqlite3_mutex_leave(pInode->pLockMutex);
danielk1977e339d652008-06-28 11:23:00 +00003198 }
drha8de1e12015-11-30 00:05:39 +00003199 releaseInodeInfo(pFile);
3200 sqlite3_free(pFile->lockingContext);
3201 rc = closeUnixFile(id);
3202 unixLeaveMutex();
drh7ed97b92010-01-20 13:07:21 +00003203 return rc;
drhbfe66312006-10-03 17:40:40 +00003204}
3205
drhd2cb50b2009-01-09 21:41:17 +00003206#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003207/*
3208** The code above is the AFP lock implementation. The code is specific
3209** to MacOSX and does not work on other unix platforms. No alternative
3210** is available. If you don't compile for a mac, then the "unix-afp"
3211** VFS is not available.
3212**
3213********************* End of the AFP lock implementation **********************
3214******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003215
drh7ed97b92010-01-20 13:07:21 +00003216/******************************************************************************
3217*************************** Begin NFS Locking ********************************/
3218
3219#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3220/*
drh308c2a52010-05-14 11:30:18 +00003221 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003222 ** must be either NO_LOCK or SHARED_LOCK.
3223 **
3224 ** If the locking level of the file descriptor is already at or below
3225 ** the requested locking level, this routine is a no-op.
3226 */
drh308c2a52010-05-14 11:30:18 +00003227static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003228 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003229}
3230
3231#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3232/*
3233** The code above is the NFS lock implementation. The code is specific
3234** to MacOSX and does not work on other unix platforms. No alternative
3235** is available.
3236**
3237********************* End of the NFS lock implementation **********************
3238******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003239
3240/******************************************************************************
3241**************** Non-locking sqlite3_file methods *****************************
3242**
3243** The next division contains implementations for all methods of the
3244** sqlite3_file object other than the locking methods. The locking
3245** methods were defined in divisions above (one locking method per
3246** division). Those methods that are common to all locking modes
3247** are gather together into this division.
3248*/
drhbfe66312006-10-03 17:40:40 +00003249
3250/*
drh734c9862008-11-28 15:37:20 +00003251** Seek to the offset passed as the second argument, then read cnt
3252** bytes into pBuf. Return the number of bytes actually read.
3253**
3254** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3255** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3256** one system to another. Since SQLite does not define USE_PREAD
peter.d.reid60ec9142014-09-06 16:39:46 +00003257** in any form by default, we will not attempt to define _XOPEN_SOURCE.
drh734c9862008-11-28 15:37:20 +00003258** See tickets #2741 and #2681.
3259**
3260** To avoid stomping the errno value on a failed read the lastErrno value
3261** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003262*/
drh734c9862008-11-28 15:37:20 +00003263static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3264 int got;
drh58024642011-11-07 18:16:00 +00003265 int prior = 0;
drha46cadc2016-03-04 03:02:06 +00003266#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
3267 i64 newOffset;
3268#endif
drh734c9862008-11-28 15:37:20 +00003269 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003270 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003271 assert( id->h>2 );
drh58024642011-11-07 18:16:00 +00003272 do{
drh734c9862008-11-28 15:37:20 +00003273#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003274 got = osPread(id->h, pBuf, cnt, offset);
3275 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003276#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003277 got = osPread64(id->h, pBuf, cnt, offset);
3278 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003279#else
drha46cadc2016-03-04 03:02:06 +00003280 newOffset = lseek(id->h, offset, SEEK_SET);
3281 SimulateIOError( newOffset = -1 );
3282 if( newOffset<0 ){
3283 storeLastErrno((unixFile*)id, errno);
3284 return -1;
3285 }
3286 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003287#endif
drh58024642011-11-07 18:16:00 +00003288 if( got==cnt ) break;
3289 if( got<0 ){
3290 if( errno==EINTR ){ got = 1; continue; }
3291 prior = 0;
drh4bf66fd2015-02-19 02:43:02 +00003292 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003293 break;
3294 }else if( got>0 ){
3295 cnt -= got;
3296 offset += got;
3297 prior += got;
3298 pBuf = (void*)(got + (char*)pBuf);
3299 }
3300 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003301 TIMER_END;
drh58024642011-11-07 18:16:00 +00003302 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3303 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3304 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003305}
3306
3307/*
drh734c9862008-11-28 15:37:20 +00003308** Read data from a file into a buffer. Return SQLITE_OK if all
3309** bytes were read successfully and SQLITE_IOERR if anything goes
3310** wrong.
drh339eb0b2008-03-07 15:34:11 +00003311*/
drh734c9862008-11-28 15:37:20 +00003312static int unixRead(
3313 sqlite3_file *id,
3314 void *pBuf,
3315 int amt,
3316 sqlite3_int64 offset
3317){
dan08da86a2009-08-21 17:18:03 +00003318 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003319 int got;
3320 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003321 assert( offset>=0 );
3322 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003323
dan08da86a2009-08-21 17:18:03 +00003324 /* If this is a database file (not a journal, master-journal or temp
3325 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003326#if 0
drhc68886b2017-08-18 16:09:52 +00003327 assert( pFile->pPreallocatedUnused==0
dan08da86a2009-08-21 17:18:03 +00003328 || offset>=PENDING_BYTE+512
3329 || offset+amt<=PENDING_BYTE
3330 );
dan7c246102010-04-12 19:00:29 +00003331#endif
drh08c6d442009-02-09 17:34:07 +00003332
drh9b4c59f2013-04-15 17:03:42 +00003333#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003334 /* Deal with as much of this read request as possible by transfering
3335 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003336 if( offset<pFile->mmapSize ){
3337 if( offset+amt <= pFile->mmapSize ){
3338 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3339 return SQLITE_OK;
3340 }else{
3341 int nCopy = pFile->mmapSize - offset;
3342 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3343 pBuf = &((u8 *)pBuf)[nCopy];
3344 amt -= nCopy;
3345 offset += nCopy;
3346 }
3347 }
drh6e0b6d52013-04-09 16:19:20 +00003348#endif
danf23da962013-03-23 21:00:41 +00003349
dan08da86a2009-08-21 17:18:03 +00003350 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003351 if( got==amt ){
3352 return SQLITE_OK;
3353 }else if( got<0 ){
3354 /* lastErrno set by seekAndRead */
3355 return SQLITE_IOERR_READ;
3356 }else{
drh4bf66fd2015-02-19 02:43:02 +00003357 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003358 /* Unread parts of the buffer must be zero-filled */
3359 memset(&((char*)pBuf)[got], 0, amt-got);
3360 return SQLITE_IOERR_SHORT_READ;
3361 }
3362}
3363
3364/*
dan47a2b4a2013-04-26 16:09:29 +00003365** Attempt to seek the file-descriptor passed as the first argument to
3366** absolute offset iOff, then attempt to write nBuf bytes of data from
3367** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3368** return the actual number of bytes written (which may be less than
3369** nBuf).
3370*/
3371static int seekAndWriteFd(
3372 int fd, /* File descriptor to write to */
3373 i64 iOff, /* File offset to begin writing at */
3374 const void *pBuf, /* Copy data from this buffer to the file */
3375 int nBuf, /* Size of buffer pBuf in bytes */
3376 int *piErrno /* OUT: Error number if error occurs */
3377){
3378 int rc = 0; /* Value returned by system call */
3379
3380 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003381 assert( fd>2 );
drhe1818ec2015-12-01 16:21:35 +00003382 assert( piErrno!=0 );
dan47a2b4a2013-04-26 16:09:29 +00003383 nBuf &= 0x1ffff;
3384 TIMER_START;
3385
3386#if defined(USE_PREAD)
drh2da47d32015-02-21 00:56:05 +00003387 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
dan47a2b4a2013-04-26 16:09:29 +00003388#elif defined(USE_PREAD64)
drh2da47d32015-02-21 00:56:05 +00003389 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
dan47a2b4a2013-04-26 16:09:29 +00003390#else
3391 do{
3392 i64 iSeek = lseek(fd, iOff, SEEK_SET);
drhe1818ec2015-12-01 16:21:35 +00003393 SimulateIOError( iSeek = -1 );
3394 if( iSeek<0 ){
3395 rc = -1;
3396 break;
dan47a2b4a2013-04-26 16:09:29 +00003397 }
3398 rc = osWrite(fd, pBuf, nBuf);
3399 }while( rc<0 && errno==EINTR );
3400#endif
3401
3402 TIMER_END;
3403 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3404
drhe1818ec2015-12-01 16:21:35 +00003405 if( rc<0 ) *piErrno = errno;
dan47a2b4a2013-04-26 16:09:29 +00003406 return rc;
3407}
3408
3409
3410/*
drh734c9862008-11-28 15:37:20 +00003411** Seek to the offset in id->offset then read cnt bytes into pBuf.
3412** Return the number of bytes actually read. Update the offset.
3413**
3414** To avoid stomping the errno value on a failed write the lastErrno value
3415** is set before returning.
3416*/
3417static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003418 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003419}
3420
3421
3422/*
3423** Write data from a buffer into a file. Return SQLITE_OK on success
3424** or some other error code on failure.
3425*/
3426static int unixWrite(
3427 sqlite3_file *id,
3428 const void *pBuf,
3429 int amt,
3430 sqlite3_int64 offset
3431){
dan08da86a2009-08-21 17:18:03 +00003432 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003433 int wrote = 0;
3434 assert( id );
3435 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003436
dan08da86a2009-08-21 17:18:03 +00003437 /* If this is a database file (not a journal, master-journal or temp
3438 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003439#if 0
drhc68886b2017-08-18 16:09:52 +00003440 assert( pFile->pPreallocatedUnused==0
dan08da86a2009-08-21 17:18:03 +00003441 || offset>=PENDING_BYTE+512
3442 || offset+amt<=PENDING_BYTE
3443 );
dan7c246102010-04-12 19:00:29 +00003444#endif
drh08c6d442009-02-09 17:34:07 +00003445
drhd3d8c042012-05-29 17:02:40 +00003446#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003447 /* If we are doing a normal write to a database file (as opposed to
3448 ** doing a hot-journal rollback or a write to some file other than a
3449 ** normal database file) then record the fact that the database
3450 ** has changed. If the transaction counter is modified, record that
3451 ** fact too.
3452 */
dan08da86a2009-08-21 17:18:03 +00003453 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003454 pFile->dbUpdate = 1; /* The database has been modified */
3455 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003456 int rc;
drh8f941bc2009-01-14 23:03:40 +00003457 char oldCntr[4];
3458 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003459 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003460 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003461 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003462 pFile->transCntrChng = 1; /* The transaction counter has changed */
3463 }
3464 }
3465 }
3466#endif
3467
danfe33e392015-11-17 20:56:06 +00003468#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003469 /* Deal with as much of this write request as possible by transfering
3470 ** data from the memory mapping using memcpy(). */
3471 if( offset<pFile->mmapSize ){
3472 if( offset+amt <= pFile->mmapSize ){
3473 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3474 return SQLITE_OK;
3475 }else{
3476 int nCopy = pFile->mmapSize - offset;
3477 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3478 pBuf = &((u8 *)pBuf)[nCopy];
3479 amt -= nCopy;
3480 offset += nCopy;
3481 }
3482 }
drh6e0b6d52013-04-09 16:19:20 +00003483#endif
drh02bf8b42015-09-01 23:51:53 +00003484
3485 while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
drh734c9862008-11-28 15:37:20 +00003486 amt -= wrote;
3487 offset += wrote;
3488 pBuf = &((char*)pBuf)[wrote];
3489 }
3490 SimulateIOError(( wrote=(-1), amt=1 ));
3491 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003492
drh02bf8b42015-09-01 23:51:53 +00003493 if( amt>wrote ){
drha21b83b2011-04-15 12:36:10 +00003494 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003495 /* lastErrno set by seekAndWrite */
3496 return SQLITE_IOERR_WRITE;
3497 }else{
drh4bf66fd2015-02-19 02:43:02 +00003498 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003499 return SQLITE_FULL;
3500 }
3501 }
dan6e09d692010-07-27 18:34:15 +00003502
drh734c9862008-11-28 15:37:20 +00003503 return SQLITE_OK;
3504}
3505
3506#ifdef SQLITE_TEST
3507/*
3508** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003509** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003510*/
3511int sqlite3_sync_count = 0;
3512int sqlite3_fullsync_count = 0;
3513#endif
3514
3515/*
drh89240432009-03-25 01:06:01 +00003516** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003517** Others do no. To be safe, we will stick with the (slightly slower)
3518** fsync(). If you know that your system does support fdatasync() correctly,
drhf7a4a1b2015-01-10 18:02:45 +00003519** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003520*/
drhf7a4a1b2015-01-10 18:02:45 +00003521#if !defined(fdatasync) && !HAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003522# define fdatasync fsync
3523#endif
3524
3525/*
3526** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3527** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3528** only available on Mac OS X. But that could change.
3529*/
3530#ifdef F_FULLFSYNC
3531# define HAVE_FULLFSYNC 1
3532#else
3533# define HAVE_FULLFSYNC 0
3534#endif
3535
3536
3537/*
3538** The fsync() system call does not work as advertised on many
3539** unix systems. The following procedure is an attempt to make
3540** it work better.
3541**
3542** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3543** for testing when we want to run through the test suite quickly.
3544** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3545** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3546** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003547**
3548** SQLite sets the dataOnly flag if the size of the file is unchanged.
3549** The idea behind dataOnly is that it should only write the file content
3550** to disk, not the inode. We only set dataOnly if the file size is
3551** unchanged since the file size is part of the inode. However,
3552** Ted Ts'o tells us that fdatasync() will also write the inode if the
3553** file size has changed. The only real difference between fdatasync()
3554** and fsync(), Ted tells us, is that fdatasync() will not flush the
3555** inode if the mtime or owner or other inode attributes have changed.
3556** We only care about the file size, not the other file attributes, so
3557** as far as SQLite is concerned, an fdatasync() is always adequate.
3558** So, we always use fdatasync() if it is available, regardless of
3559** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003560*/
3561static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003562 int rc;
drh734c9862008-11-28 15:37:20 +00003563
3564 /* The following "ifdef/elif/else/" block has the same structure as
3565 ** the one below. It is replicated here solely to avoid cluttering
3566 ** up the real code with the UNUSED_PARAMETER() macros.
3567 */
3568#ifdef SQLITE_NO_SYNC
3569 UNUSED_PARAMETER(fd);
3570 UNUSED_PARAMETER(fullSync);
3571 UNUSED_PARAMETER(dataOnly);
3572#elif HAVE_FULLFSYNC
3573 UNUSED_PARAMETER(dataOnly);
3574#else
3575 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003576 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003577#endif
3578
3579 /* Record the number of times that we do a normal fsync() and
3580 ** FULLSYNC. This is used during testing to verify that this procedure
3581 ** gets called with the correct arguments.
3582 */
3583#ifdef SQLITE_TEST
3584 if( fullSync ) sqlite3_fullsync_count++;
3585 sqlite3_sync_count++;
3586#endif
3587
3588 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
drh2c8fd122015-12-02 02:33:36 +00003589 ** no-op. But go ahead and call fstat() to validate the file
3590 ** descriptor as we need a method to provoke a failure during
3591 ** coverate testing.
drh734c9862008-11-28 15:37:20 +00003592 */
3593#ifdef SQLITE_NO_SYNC
drh2c8fd122015-12-02 02:33:36 +00003594 {
3595 struct stat buf;
3596 rc = osFstat(fd, &buf);
3597 }
drh734c9862008-11-28 15:37:20 +00003598#elif HAVE_FULLFSYNC
3599 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003600 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003601 }else{
3602 rc = 1;
3603 }
3604 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003605 ** It shouldn't be possible for fullfsync to fail on the local
3606 ** file system (on OSX), so failure indicates that FULLFSYNC
3607 ** isn't supported for this file system. So, attempt an fsync
3608 ** and (for now) ignore the overhead of a superfluous fcntl call.
3609 ** It'd be better to detect fullfsync support once and avoid
3610 ** the fcntl call every time sync is called.
3611 */
drh734c9862008-11-28 15:37:20 +00003612 if( rc ) rc = fsync(fd);
3613
drh7ed97b92010-01-20 13:07:21 +00003614#elif defined(__APPLE__)
3615 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3616 ** so currently we default to the macro that redefines fdatasync to fsync
3617 */
3618 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003619#else
drh0b647ff2009-03-21 14:41:04 +00003620 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003621#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003622 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003623 rc = fsync(fd);
3624 }
drh0b647ff2009-03-21 14:41:04 +00003625#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003626#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3627
3628 if( OS_VXWORKS && rc!= -1 ){
3629 rc = 0;
3630 }
chw97185482008-11-17 08:05:31 +00003631 return rc;
drhbfe66312006-10-03 17:40:40 +00003632}
3633
drh734c9862008-11-28 15:37:20 +00003634/*
drh0059eae2011-08-08 23:48:40 +00003635** Open a file descriptor to the directory containing file zFilename.
3636** If successful, *pFd is set to the opened file descriptor and
3637** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3638** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3639** value.
3640**
drh90315a22011-08-10 01:52:12 +00003641** The directory file descriptor is used for only one thing - to
3642** fsync() a directory to make sure file creation and deletion events
3643** are flushed to disk. Such fsyncs are not needed on newer
3644** journaling filesystems, but are required on older filesystems.
3645**
3646** This routine can be overridden using the xSetSysCall interface.
3647** The ability to override this routine was added in support of the
3648** chromium sandbox. Opening a directory is a security risk (we are
3649** told) so making it overrideable allows the chromium sandbox to
3650** replace this routine with a harmless no-op. To make this routine
3651** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3652** *pFd set to a negative number.
3653**
drh0059eae2011-08-08 23:48:40 +00003654** If SQLITE_OK is returned, the caller is responsible for closing
3655** the file descriptor *pFd using close().
3656*/
3657static int openDirectory(const char *zFilename, int *pFd){
3658 int ii;
3659 int fd = -1;
3660 char zDirname[MAX_PATHNAME+1];
3661
3662 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drhdc278512015-12-07 18:18:33 +00003663 for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
3664 if( ii>0 ){
drh0059eae2011-08-08 23:48:40 +00003665 zDirname[ii] = '\0';
drhdc278512015-12-07 18:18:33 +00003666 }else{
3667 if( zDirname[0]!='/' ) zDirname[0] = '.';
3668 zDirname[1] = 0;
3669 }
3670 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3671 if( fd>=0 ){
3672 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
drh0059eae2011-08-08 23:48:40 +00003673 }
3674 *pFd = fd;
drhacb6b282015-11-26 10:37:05 +00003675 if( fd>=0 ) return SQLITE_OK;
3676 return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
drh0059eae2011-08-08 23:48:40 +00003677}
3678
3679/*
drh734c9862008-11-28 15:37:20 +00003680** Make sure all writes to a particular file are committed to disk.
3681**
3682** If dataOnly==0 then both the file itself and its metadata (file
3683** size, access time, etc) are synced. If dataOnly!=0 then only the
3684** file data is synced.
3685**
3686** Under Unix, also make sure that the directory entry for the file
3687** has been created by fsync-ing the directory that contains the file.
3688** If we do not do this and we encounter a power failure, the directory
3689** entry for the journal might not exist after we reboot. The next
3690** SQLite to access the file will not know that the journal exists (because
3691** the directory entry for the journal was never created) and the transaction
3692** will not roll back - possibly leading to database corruption.
3693*/
3694static int unixSync(sqlite3_file *id, int flags){
3695 int rc;
3696 unixFile *pFile = (unixFile*)id;
3697
3698 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3699 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3700
3701 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3702 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3703 || (flags&0x0F)==SQLITE_SYNC_FULL
3704 );
3705
3706 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3707 ** line is to test that doing so does not cause any problems.
3708 */
3709 SimulateDiskfullError( return SQLITE_FULL );
3710
3711 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003712 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003713 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3714 SimulateIOError( rc=1 );
3715 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003716 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003717 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003718 }
drh0059eae2011-08-08 23:48:40 +00003719
3720 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003721 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003722 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003723 */
3724 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3725 int dirfd;
3726 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003727 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003728 rc = osOpenDirectory(pFile->zPath, &dirfd);
drhacb6b282015-11-26 10:37:05 +00003729 if( rc==SQLITE_OK ){
drh0059eae2011-08-08 23:48:40 +00003730 full_fsync(dirfd, 0, 0);
3731 robust_close(pFile, dirfd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00003732 }else{
3733 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00003734 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003735 }
drh0059eae2011-08-08 23:48:40 +00003736 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003737 }
3738 return rc;
3739}
3740
3741/*
3742** Truncate an open file to a specified size
3743*/
3744static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003745 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003746 int rc;
dan6e09d692010-07-27 18:34:15 +00003747 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003748 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003749
3750 /* If the user has configured a chunk-size for this file, truncate the
3751 ** file so that it consists of an integer number of chunks (i.e. the
3752 ** actual file size after the operation may be larger than the requested
3753 ** size).
3754 */
drhb8af4b72012-04-05 20:04:39 +00003755 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003756 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3757 }
3758
dan2ee53412014-09-06 16:49:40 +00003759 rc = robust_ftruncate(pFile->h, nByte);
drh734c9862008-11-28 15:37:20 +00003760 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003761 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003762 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003763 }else{
drhd3d8c042012-05-29 17:02:40 +00003764#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003765 /* If we are doing a normal write to a database file (as opposed to
3766 ** doing a hot-journal rollback or a write to some file other than a
3767 ** normal database file) and we truncate the file to zero length,
3768 ** that effectively updates the change counter. This might happen
3769 ** when restoring a database using the backup API from a zero-length
3770 ** source.
3771 */
dan6e09d692010-07-27 18:34:15 +00003772 if( pFile->inNormalWrite && nByte==0 ){
3773 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003774 }
danf23da962013-03-23 21:00:41 +00003775#endif
danc0003312013-03-22 17:46:11 +00003776
mistachkine98844f2013-08-24 00:59:24 +00003777#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003778 /* If the file was just truncated to a size smaller than the currently
3779 ** mapped region, reduce the effective mapping size as well. SQLite will
3780 ** use read() and write() to access data beyond this point from now on.
3781 */
3782 if( nByte<pFile->mmapSize ){
3783 pFile->mmapSize = nByte;
3784 }
mistachkine98844f2013-08-24 00:59:24 +00003785#endif
drh3313b142009-11-06 04:13:18 +00003786
drh734c9862008-11-28 15:37:20 +00003787 return SQLITE_OK;
3788 }
3789}
3790
3791/*
3792** Determine the current size of a file in bytes
3793*/
3794static int unixFileSize(sqlite3_file *id, i64 *pSize){
3795 int rc;
3796 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003797 assert( id );
3798 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003799 SimulateIOError( rc=1 );
3800 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00003801 storeLastErrno((unixFile*)id, errno);
drh734c9862008-11-28 15:37:20 +00003802 return SQLITE_IOERR_FSTAT;
3803 }
3804 *pSize = buf.st_size;
3805
drh8af6c222010-05-14 12:43:01 +00003806 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003807 ** writes a single byte into that file in order to work around a bug
3808 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3809 ** layers, we need to report this file size as zero even though it is
3810 ** really 1. Ticket #3260.
3811 */
3812 if( *pSize==1 ) *pSize = 0;
3813
3814
3815 return SQLITE_OK;
3816}
3817
drhd2cb50b2009-01-09 21:41:17 +00003818#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003819/*
3820** Handler for proxy-locking file-control verbs. Defined below in the
3821** proxying locking division.
3822*/
3823static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003824#endif
drh715ff302008-12-03 22:32:44 +00003825
dan502019c2010-07-28 14:26:17 +00003826/*
3827** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003828** file-control operation. Enlarge the database to nBytes in size
3829** (rounded up to the next chunk-size). If the database is already
3830** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003831*/
3832static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003833 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003834 i64 nSize; /* Required file size */
3835 struct stat buf; /* Used to hold return values of fstat() */
3836
drh4bf66fd2015-02-19 02:43:02 +00003837 if( osFstat(pFile->h, &buf) ){
3838 return SQLITE_IOERR_FSTAT;
3839 }
dan502019c2010-07-28 14:26:17 +00003840
3841 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3842 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003843
dan502019c2010-07-28 14:26:17 +00003844#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003845 /* The code below is handling the return value of osFallocate()
3846 ** correctly. posix_fallocate() is defined to "returns zero on success,
3847 ** or an error number on failure". See the manpage for details. */
3848 int err;
drhff812312011-02-23 13:33:46 +00003849 do{
dan661d71a2011-03-30 19:08:03 +00003850 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3851 }while( err==EINTR );
drh789df142018-06-02 14:37:39 +00003852 if( err && err!=EINVAL ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003853#else
dan592bf7f2014-12-30 19:58:31 +00003854 /* If the OS does not have posix_fallocate(), fake it. Write a
3855 ** single byte to the last byte in each block that falls entirely
3856 ** within the extended region. Then, if required, a single byte
3857 ** at offset (nSize-1), to set the size of the file correctly.
3858 ** This is a similar technique to that used by glibc on systems
3859 ** that do not have a real fallocate() call.
dan502019c2010-07-28 14:26:17 +00003860 */
3861 int nBlk = buf.st_blksize; /* File-system block size */
danef3d66c2015-01-06 21:31:47 +00003862 int nWrite = 0; /* Number of bytes written by seekAndWrite */
dan502019c2010-07-28 14:26:17 +00003863 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003864
drh053378d2015-12-01 22:09:42 +00003865 iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
dan592bf7f2014-12-30 19:58:31 +00003866 assert( iWrite>=buf.st_size );
dan592bf7f2014-12-30 19:58:31 +00003867 assert( ((iWrite+1)%nBlk)==0 );
drh053378d2015-12-01 22:09:42 +00003868 for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
3869 if( iWrite>=nSize ) iWrite = nSize - 1;
danef3d66c2015-01-06 21:31:47 +00003870 nWrite = seekAndWrite(pFile, iWrite, "", 1);
dandc5df0f2011-04-06 19:15:45 +00003871 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dandc5df0f2011-04-06 19:15:45 +00003872 }
dan502019c2010-07-28 14:26:17 +00003873#endif
3874 }
3875 }
3876
mistachkine98844f2013-08-24 00:59:24 +00003877#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003878 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003879 int rc;
3880 if( pFile->szChunk<=0 ){
3881 if( robust_ftruncate(pFile->h, nByte) ){
drh4bf66fd2015-02-19 02:43:02 +00003882 storeLastErrno(pFile, errno);
danf23da962013-03-23 21:00:41 +00003883 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3884 }
3885 }
3886
3887 rc = unixMapfile(pFile, nByte);
3888 return rc;
3889 }
mistachkine98844f2013-08-24 00:59:24 +00003890#endif
danf23da962013-03-23 21:00:41 +00003891
dan502019c2010-07-28 14:26:17 +00003892 return SQLITE_OK;
3893}
danielk1977ad94b582007-08-20 06:44:22 +00003894
danielk1977e3026632004-06-22 11:29:02 +00003895/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003896** If *pArg is initially negative then this is a query. Set *pArg to
drhf12b3f62011-12-21 14:42:29 +00003897** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3898**
3899** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3900*/
3901static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3902 if( *pArg<0 ){
3903 *pArg = (pFile->ctrlFlags & mask)!=0;
3904 }else if( (*pArg)==0 ){
3905 pFile->ctrlFlags &= ~mask;
3906 }else{
3907 pFile->ctrlFlags |= mask;
3908 }
3909}
3910
drh696b33e2012-12-06 19:01:42 +00003911/* Forward declaration */
3912static int unixGetTempname(int nBuf, char *zBuf);
3913
drhf12b3f62011-12-21 14:42:29 +00003914/*
drh9e33c2c2007-08-31 18:34:59 +00003915** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003916*/
drhcc6bb3e2007-08-31 16:11:35 +00003917static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003918 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003919 switch( op ){
drhd76dba72017-07-22 16:00:34 +00003920#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
danefe16972017-07-20 19:49:14 +00003921 case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: {
3922 int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE);
drh344f7632017-07-28 13:18:35 +00003923 return rc ? SQLITE_IOERR_BEGIN_ATOMIC : SQLITE_OK;
danefe16972017-07-20 19:49:14 +00003924 }
3925 case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: {
3926 int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE);
drh344f7632017-07-28 13:18:35 +00003927 return rc ? SQLITE_IOERR_COMMIT_ATOMIC : SQLITE_OK;
danefe16972017-07-20 19:49:14 +00003928 }
3929 case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: {
3930 int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE);
drh344f7632017-07-28 13:18:35 +00003931 return rc ? SQLITE_IOERR_ROLLBACK_ATOMIC : SQLITE_OK;
danefe16972017-07-20 19:49:14 +00003932 }
drhd76dba72017-07-22 16:00:34 +00003933#endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
danefe16972017-07-20 19:49:14 +00003934
drh9e33c2c2007-08-31 18:34:59 +00003935 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003936 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003937 return SQLITE_OK;
3938 }
drh4bf66fd2015-02-19 02:43:02 +00003939 case SQLITE_FCNTL_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003940 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003941 return SQLITE_OK;
3942 }
dan6e09d692010-07-27 18:34:15 +00003943 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003944 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003945 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003946 }
drh9ff27ec2010-05-19 19:26:05 +00003947 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003948 int rc;
3949 SimulateIOErrorBenign(1);
3950 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3951 SimulateIOErrorBenign(0);
3952 return rc;
drhf0b190d2011-07-26 16:03:07 +00003953 }
3954 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003955 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3956 return SQLITE_OK;
3957 }
drhcb15f352011-12-23 01:04:17 +00003958 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3959 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003960 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003961 }
drhde60fc22011-12-14 17:53:36 +00003962 case SQLITE_FCNTL_VFSNAME: {
3963 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3964 return SQLITE_OK;
3965 }
drh696b33e2012-12-06 19:01:42 +00003966 case SQLITE_FCNTL_TEMPFILENAME: {
drhf3cdcdc2015-04-29 16:50:28 +00003967 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
drh696b33e2012-12-06 19:01:42 +00003968 if( zTFile ){
3969 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3970 *(char**)pArg = zTFile;
3971 }
3972 return SQLITE_OK;
3973 }
drhb959a012013-12-07 12:29:22 +00003974 case SQLITE_FCNTL_HAS_MOVED: {
3975 *(int*)pArg = fileHasMoved(pFile);
3976 return SQLITE_OK;
3977 }
drhf0119b22018-03-26 17:40:53 +00003978#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
3979 case SQLITE_FCNTL_LOCK_TIMEOUT: {
3980 pFile->iBusyTimeout = *(int*)pArg;
3981 return SQLITE_OK;
3982 }
3983#endif
mistachkine98844f2013-08-24 00:59:24 +00003984#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003985 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003986 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003987 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003988 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3989 newLimit = sqlite3GlobalConfig.mxMmap;
3990 }
dan43c1e622017-08-07 18:13:28 +00003991
3992 /* The value of newLimit may be eventually cast to (size_t) and passed
mistachkine35395a2017-08-07 19:06:54 +00003993 ** to mmap(). Restrict its value to 2GB if (size_t) is not at least a
3994 ** 64-bit type. */
dan089df502017-08-07 18:54:10 +00003995 if( newLimit>0 && sizeof(size_t)<8 ){
dan43c1e622017-08-07 18:13:28 +00003996 newLimit = (newLimit & 0x7FFFFFFF);
3997 }
3998
drh9b4c59f2013-04-15 17:03:42 +00003999 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00004000 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00004001 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00004002 if( pFile->mmapSize>0 ){
4003 unixUnmapfile(pFile);
4004 rc = unixMapfile(pFile, -1);
4005 }
danbcb8a862013-04-08 15:30:41 +00004006 }
drh34e258c2013-05-23 01:40:53 +00004007 return rc;
danb2d3de32013-03-14 18:34:37 +00004008 }
mistachkine98844f2013-08-24 00:59:24 +00004009#endif
drhd3d8c042012-05-29 17:02:40 +00004010#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00004011 /* The pager calls this method to signal that it has done
4012 ** a rollback and that the database is therefore unchanged and
4013 ** it hence it is OK for the transaction change counter to be
4014 ** unchanged.
4015 */
4016 case SQLITE_FCNTL_DB_UNCHANGED: {
4017 ((unixFile*)id)->dbUpdate = 0;
4018 return SQLITE_OK;
4019 }
4020#endif
drhd2cb50b2009-01-09 21:41:17 +00004021#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh4bf66fd2015-02-19 02:43:02 +00004022 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
4023 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00004024 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00004025 }
drhd2cb50b2009-01-09 21:41:17 +00004026#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00004027 }
drh0b52b7d2011-01-26 19:46:22 +00004028 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00004029}
4030
4031/*
danefe16972017-07-20 19:49:14 +00004032** If pFd->sectorSize is non-zero when this function is called, it is a
4033** no-op. Otherwise, the values of pFd->sectorSize and
4034** pFd->deviceCharacteristics are set according to the file-system
4035** characteristics.
danielk1977a3d4c882007-03-23 10:08:38 +00004036**
danefe16972017-07-20 19:49:14 +00004037** There are two versions of this function. One for QNX and one for all
4038** other systems.
danielk1977a3d4c882007-03-23 10:08:38 +00004039*/
danefe16972017-07-20 19:49:14 +00004040#ifndef __QNXNTO__
4041static void setDeviceCharacteristics(unixFile *pFd){
drhd76dba72017-07-22 16:00:34 +00004042 assert( pFd->deviceCharacteristics==0 || pFd->sectorSize!=0 );
danefe16972017-07-20 19:49:14 +00004043 if( pFd->sectorSize==0 ){
drhd76dba72017-07-22 16:00:34 +00004044#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
danefe16972017-07-20 19:49:14 +00004045 int res;
dan9d709542017-07-21 21:06:24 +00004046 u32 f = 0;
drh537dddf2012-10-26 13:46:24 +00004047
danefe16972017-07-20 19:49:14 +00004048 /* Check for support for F2FS atomic batch writes. */
dan9d709542017-07-21 21:06:24 +00004049 res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES, &f);
4050 if( res==0 && (f & F2FS_FEATURE_ATOMIC_WRITE) ){
dan77b4f522017-07-27 18:34:00 +00004051 pFd->deviceCharacteristics = SQLITE_IOCAP_BATCH_ATOMIC;
danefe16972017-07-20 19:49:14 +00004052 }
drhd76dba72017-07-22 16:00:34 +00004053#endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
danefe16972017-07-20 19:49:14 +00004054
4055 /* Set the POWERSAFE_OVERWRITE flag if requested. */
4056 if( pFd->ctrlFlags & UNIXFILE_PSOW ){
4057 pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
4058 }
4059
4060 pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4061 }
4062}
4063#else
drh537dddf2012-10-26 13:46:24 +00004064#include <sys/dcmd_blk.h>
4065#include <sys/statvfs.h>
danefe16972017-07-20 19:49:14 +00004066static void setDeviceCharacteristics(unixFile *pFile){
drh537dddf2012-10-26 13:46:24 +00004067 if( pFile->sectorSize == 0 ){
4068 struct statvfs fsInfo;
4069
4070 /* Set defaults for non-supported filesystems */
4071 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4072 pFile->deviceCharacteristics = 0;
4073 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
drha9be5082018-01-15 14:32:37 +00004074 return;
drh537dddf2012-10-26 13:46:24 +00004075 }
4076
4077 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
4078 pFile->sectorSize = fsInfo.f_bsize;
4079 pFile->deviceCharacteristics =
4080 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
4081 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4082 ** the write succeeds */
4083 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4084 ** so it is ordered */
4085 0;
4086 }else if( strstr(fsInfo.f_basetype, "etfs") ){
4087 pFile->sectorSize = fsInfo.f_bsize;
4088 pFile->deviceCharacteristics =
4089 /* etfs cluster size writes are atomic */
4090 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
4091 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4092 ** the write succeeds */
4093 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4094 ** so it is ordered */
4095 0;
4096 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
4097 pFile->sectorSize = fsInfo.f_bsize;
4098 pFile->deviceCharacteristics =
4099 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
4100 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4101 ** the write succeeds */
4102 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4103 ** so it is ordered */
4104 0;
4105 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
4106 pFile->sectorSize = fsInfo.f_bsize;
4107 pFile->deviceCharacteristics =
4108 /* full bitset of atomics from max sector size and smaller */
4109 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
4110 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4111 ** so it is ordered */
4112 0;
4113 }else if( strstr(fsInfo.f_basetype, "dos") ){
4114 pFile->sectorSize = fsInfo.f_bsize;
4115 pFile->deviceCharacteristics =
4116 /* full bitset of atomics from max sector size and smaller */
4117 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
4118 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4119 ** so it is ordered */
4120 0;
4121 }else{
4122 pFile->deviceCharacteristics =
4123 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
4124 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4125 ** the write succeeds */
4126 0;
4127 }
4128 }
4129 /* Last chance verification. If the sector size isn't a multiple of 512
4130 ** then it isn't valid.*/
4131 if( pFile->sectorSize % 512 != 0 ){
4132 pFile->deviceCharacteristics = 0;
4133 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4134 }
drh537dddf2012-10-26 13:46:24 +00004135}
danefe16972017-07-20 19:49:14 +00004136#endif
4137
4138/*
4139** Return the sector size in bytes of the underlying block device for
4140** the specified file. This is almost always 512 bytes, but may be
4141** larger for some devices.
4142**
4143** SQLite code assumes this function cannot fail. It also assumes that
4144** if two files are created in the same file-system directory (i.e.
4145** a database and its journal file) that the sector size will be the
4146** same for both.
4147*/
4148static int unixSectorSize(sqlite3_file *id){
4149 unixFile *pFd = (unixFile*)id;
4150 setDeviceCharacteristics(pFd);
4151 return pFd->sectorSize;
4152}
danielk1977a3d4c882007-03-23 10:08:38 +00004153
danielk197790949c22007-08-17 16:50:38 +00004154/*
drhf12b3f62011-12-21 14:42:29 +00004155** Return the device characteristics for the file.
4156**
drhcb15f352011-12-23 01:04:17 +00004157** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
peter.d.reid60ec9142014-09-06 16:39:46 +00004158** However, that choice is controversial since technically the underlying
drhcb15f352011-12-23 01:04:17 +00004159** file system does not always provide powersafe overwrites. (In other
4160** words, after a power-loss event, parts of the file that were never
4161** written might end up being altered.) However, non-PSOW behavior is very,
4162** very rare. And asserting PSOW makes a large reduction in the amount
4163** of required I/O for journaling, since a lot of padding is eliminated.
4164** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
4165** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00004166*/
drhf12b3f62011-12-21 14:42:29 +00004167static int unixDeviceCharacteristics(sqlite3_file *id){
danefe16972017-07-20 19:49:14 +00004168 unixFile *pFd = (unixFile*)id;
4169 setDeviceCharacteristics(pFd);
4170 return pFd->deviceCharacteristics;
danielk197762079062007-08-15 17:08:46 +00004171}
4172
dan702eec12014-06-23 10:04:58 +00004173#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00004174
dan702eec12014-06-23 10:04:58 +00004175/*
4176** Return the system page size.
4177**
4178** This function should not be called directly by other code in this file.
4179** Instead, it should be called via macro osGetpagesize().
4180*/
4181static int unixGetpagesize(void){
drh8cd5b252015-03-02 22:06:43 +00004182#if OS_VXWORKS
4183 return 1024;
4184#elif defined(_BSD_SOURCE)
dan702eec12014-06-23 10:04:58 +00004185 return getpagesize();
4186#else
4187 return (int)sysconf(_SC_PAGESIZE);
4188#endif
4189}
4190
4191#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
4192
4193#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00004194
4195/*
drhd91c68f2010-05-14 14:52:25 +00004196** Object used to represent an shared memory buffer.
4197**
4198** When multiple threads all reference the same wal-index, each thread
4199** has its own unixShm object, but they all point to a single instance
4200** of this unixShmNode object. In other words, each wal-index is opened
4201** only once per process.
4202**
4203** Each unixShmNode object is connected to a single unixInodeInfo object.
4204** We could coalesce this object into unixInodeInfo, but that would mean
4205** every open file that does not use shared memory (in other words, most
4206** open files) would have to carry around this extra information. So
4207** the unixInodeInfo object contains a pointer to this unixShmNode object
4208** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00004209**
4210** unixMutexHeld() must be true when creating or destroying
4211** this object or while reading or writing the following fields:
4212**
4213** nRef
drhd9e5c4f2010-05-12 18:01:39 +00004214**
4215** The following fields are read-only after the object is created:
4216**
4217** fid
4218** zFilename
4219**
drhd91c68f2010-05-14 14:52:25 +00004220** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00004221** unixMutexHeld() is true when reading or writing any other field
4222** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00004223*/
drhd91c68f2010-05-14 14:52:25 +00004224struct unixShmNode {
4225 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00004226 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00004227 char *zFilename; /* Name of the mmapped file */
4228 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00004229 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00004230 u16 nRegion; /* Size of array apRegion */
4231 u8 isReadonly; /* True if read-only */
dan92c02da2017-11-01 20:59:28 +00004232 u8 isUnlocked; /* True if no DMS lock held */
dan18801912010-06-14 14:07:50 +00004233 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00004234 int nRef; /* Number of unixShm objects pointing to this */
4235 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00004236#ifdef SQLITE_DEBUG
4237 u8 exclMask; /* Mask of exclusive locks held */
4238 u8 sharedMask; /* Mask of shared locks held */
4239 u8 nextShmId; /* Next available unixShm.id value */
4240#endif
4241};
4242
4243/*
drhd9e5c4f2010-05-12 18:01:39 +00004244** Structure used internally by this VFS to record the state of an
4245** open shared memory connection.
4246**
drhd91c68f2010-05-14 14:52:25 +00004247** The following fields are initialized when this object is created and
4248** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004249**
drhd91c68f2010-05-14 14:52:25 +00004250** unixShm.pFile
4251** unixShm.id
4252**
4253** All other fields are read/write. The unixShm.pFile->mutex must be held
4254** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004255*/
4256struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004257 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4258 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004259 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004260 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004261 u16 sharedMask; /* Mask of shared locks held */
4262 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004263};
4264
4265/*
drhd9e5c4f2010-05-12 18:01:39 +00004266** Constants used for locking
4267*/
drhbd9676c2010-06-23 17:58:38 +00004268#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004269#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004270
drhd9e5c4f2010-05-12 18:01:39 +00004271/*
drh73b64e42010-05-30 19:55:15 +00004272** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004273**
4274** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4275** otherwise.
4276*/
4277static int unixShmSystemLock(
drhbbf76ee2015-03-10 20:22:35 +00004278 unixFile *pFile, /* Open connection to the WAL file */
drhd91c68f2010-05-14 14:52:25 +00004279 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004280 int ofst, /* First byte of the locking range */
4281 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004282){
drhbbf76ee2015-03-10 20:22:35 +00004283 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4284 struct flock f; /* The posix advisory locking structure */
4285 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004286
drhd91c68f2010-05-14 14:52:25 +00004287 /* Access to the unixShmNode object is serialized by the caller */
drhbbf76ee2015-03-10 20:22:35 +00004288 pShmNode = pFile->pInode->pShmNode;
drh37874b52017-12-13 10:11:09 +00004289 assert( pShmNode->nRef==0 || sqlite3_mutex_held(pShmNode->mutex) );
drhd9e5c4f2010-05-12 18:01:39 +00004290
dan9181ae92017-10-26 17:05:22 +00004291 /* Shared locks never span more than one byte */
4292 assert( n==1 || lockType!=F_RDLCK );
4293
4294 /* Locks are within range */
4295 assert( n>=1 && n<=SQLITE_SHM_NLOCK );
4296
drh3cb93392011-03-12 18:10:44 +00004297 if( pShmNode->h>=0 ){
4298 /* Initialize the locking parameters */
drh3cb93392011-03-12 18:10:44 +00004299 f.l_type = lockType;
4300 f.l_whence = SEEK_SET;
4301 f.l_start = ofst;
4302 f.l_len = n;
drhf0119b22018-03-26 17:40:53 +00004303 rc = osSetPosixAdvisoryLock(pShmNode->h, &f, pFile);
drh3cb93392011-03-12 18:10:44 +00004304 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4305 }
drhd9e5c4f2010-05-12 18:01:39 +00004306
4307 /* Update the global lock state and do debug tracing */
4308#ifdef SQLITE_DEBUG
dan9181ae92017-10-26 17:05:22 +00004309 { u16 mask;
4310 OSTRACE(("SHM-LOCK "));
4311 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
4312 if( rc==SQLITE_OK ){
4313 if( lockType==F_UNLCK ){
4314 OSTRACE(("unlock %d ok", ofst));
4315 pShmNode->exclMask &= ~mask;
4316 pShmNode->sharedMask &= ~mask;
4317 }else if( lockType==F_RDLCK ){
4318 OSTRACE(("read-lock %d ok", ofst));
4319 pShmNode->exclMask &= ~mask;
4320 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004321 }else{
dan9181ae92017-10-26 17:05:22 +00004322 assert( lockType==F_WRLCK );
4323 OSTRACE(("write-lock %d ok", ofst));
4324 pShmNode->exclMask |= mask;
4325 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004326 }
dan9181ae92017-10-26 17:05:22 +00004327 }else{
4328 if( lockType==F_UNLCK ){
4329 OSTRACE(("unlock %d failed", ofst));
4330 }else if( lockType==F_RDLCK ){
4331 OSTRACE(("read-lock failed"));
4332 }else{
4333 assert( lockType==F_WRLCK );
4334 OSTRACE(("write-lock %d failed", ofst));
4335 }
4336 }
4337 OSTRACE((" - afterwards %03x,%03x\n",
4338 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004339 }
drhd9e5c4f2010-05-12 18:01:39 +00004340#endif
4341
4342 return rc;
4343}
4344
dan781e34c2014-03-20 08:59:47 +00004345/*
dan781e34c2014-03-20 08:59:47 +00004346** Return the minimum number of 32KB shm regions that should be mapped at
4347** a time, assuming that each mapping must be an integer multiple of the
4348** current system page-size.
4349**
4350** Usually, this is 1. The exception seems to be systems that are configured
4351** to use 64KB pages - in this case each mapping must cover at least two
4352** shm regions.
4353*/
4354static int unixShmRegionPerMap(void){
4355 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004356 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004357 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4358 if( pgsz<shmsz ) return 1;
4359 return pgsz/shmsz;
4360}
drhd9e5c4f2010-05-12 18:01:39 +00004361
4362/*
drhd91c68f2010-05-14 14:52:25 +00004363** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004364**
4365** This is not a VFS shared-memory method; it is a utility function called
4366** by VFS shared-memory methods.
4367*/
drhd91c68f2010-05-14 14:52:25 +00004368static void unixShmPurge(unixFile *pFd){
4369 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004370 assert( unixMutexHeld() );
drhf3b1ed02015-12-02 13:11:03 +00004371 if( p && ALWAYS(p->nRef==0) ){
dan781e34c2014-03-20 08:59:47 +00004372 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004373 int i;
drhd91c68f2010-05-14 14:52:25 +00004374 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004375 sqlite3_mutex_free(p->mutex);
dan781e34c2014-03-20 08:59:47 +00004376 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh3cb93392011-03-12 18:10:44 +00004377 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004378 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004379 }else{
4380 sqlite3_free(p->apRegion[i]);
4381 }
dan13a3cb82010-06-11 19:04:21 +00004382 }
dan18801912010-06-14 14:07:50 +00004383 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004384 if( p->h>=0 ){
4385 robust_close(pFd, p->h, __LINE__);
4386 p->h = -1;
4387 }
drhd91c68f2010-05-14 14:52:25 +00004388 p->pInode->pShmNode = 0;
4389 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004390 }
4391}
4392
4393/*
dan92c02da2017-11-01 20:59:28 +00004394** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
4395** take it now. Return SQLITE_OK if successful, or an SQLite error
4396** code otherwise.
4397**
4398** If the DMS cannot be locked because this is a readonly_shm=1
4399** connection and no other process already holds a lock, return
drh7e45e3a2017-11-08 17:32:12 +00004400** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
dan92c02da2017-11-01 20:59:28 +00004401*/
4402static int unixLockSharedMemory(unixFile *pDbFd, unixShmNode *pShmNode){
4403 struct flock lock;
4404 int rc = SQLITE_OK;
4405
4406 /* Use F_GETLK to determine the locks other processes are holding
4407 ** on the DMS byte. If it indicates that another process is holding
4408 ** a SHARED lock, then this process may also take a SHARED lock
4409 ** and proceed with opening the *-shm file.
4410 **
4411 ** Or, if no other process is holding any lock, then this process
4412 ** is the first to open it. In this case take an EXCLUSIVE lock on the
4413 ** DMS byte and truncate the *-shm file to zero bytes in size. Then
4414 ** downgrade to a SHARED lock on the DMS byte.
4415 **
4416 ** If another process is holding an EXCLUSIVE lock on the DMS byte,
4417 ** return SQLITE_BUSY to the caller (it will try again). An earlier
4418 ** version of this code attempted the SHARED lock at this point. But
4419 ** this introduced a subtle race condition: if the process holding
4420 ** EXCLUSIVE failed just before truncating the *-shm file, then this
4421 ** process might open and use the *-shm file without truncating it.
4422 ** And if the *-shm file has been corrupted by a power failure or
4423 ** system crash, the database itself may also become corrupt. */
4424 lock.l_whence = SEEK_SET;
4425 lock.l_start = UNIX_SHM_DMS;
4426 lock.l_len = 1;
4427 lock.l_type = F_WRLCK;
4428 if( osFcntl(pShmNode->h, F_GETLK, &lock)!=0 ) {
4429 rc = SQLITE_IOERR_LOCK;
4430 }else if( lock.l_type==F_UNLCK ){
4431 if( pShmNode->isReadonly ){
4432 pShmNode->isUnlocked = 1;
drh7e45e3a2017-11-08 17:32:12 +00004433 rc = SQLITE_READONLY_CANTINIT;
dan92c02da2017-11-01 20:59:28 +00004434 }else{
4435 rc = unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1);
4436 if( rc==SQLITE_OK && robust_ftruncate(pShmNode->h, 0) ){
4437 rc = unixLogError(SQLITE_IOERR_SHMOPEN,"ftruncate",pShmNode->zFilename);
4438 }
4439 }
4440 }else if( lock.l_type==F_WRLCK ){
4441 rc = SQLITE_BUSY;
4442 }
4443
4444 if( rc==SQLITE_OK ){
4445 assert( lock.l_type==F_UNLCK || lock.l_type==F_RDLCK );
4446 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
4447 }
4448 return rc;
4449}
4450
4451/*
danda9fe0c2010-07-13 18:44:03 +00004452** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004453** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004454**
drh7234c6d2010-06-19 15:10:09 +00004455** The file used to implement shared-memory is in the same directory
4456** as the open database file and has the same name as the open database
4457** file with the "-shm" suffix added. For example, if the database file
4458** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004459** for shared memory will be called "/home/user1/config.db-shm".
4460**
4461** Another approach to is to use files in /dev/shm or /dev/tmp or an
4462** some other tmpfs mount. But if a file in a different directory
4463** from the database file is used, then differing access permissions
4464** or a chroot() might cause two different processes on the same
4465** database to end up using different files for shared memory -
4466** meaning that their memory would not really be shared - resulting
4467** in database corruption. Nevertheless, this tmpfs file usage
4468** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4469** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4470** option results in an incompatible build of SQLite; builds of SQLite
4471** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4472** same database file at the same time, database corruption will likely
4473** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4474** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004475**
4476** When opening a new shared-memory file, if no other instances of that
4477** file are currently open, in this process or in other processes, then
4478** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004479**
4480** If the original database file (pDbFd) is using the "unix-excl" VFS
4481** that means that an exclusive lock is held on the database file and
4482** that no other processes are able to read or write the database. In
4483** that case, we do not really need shared memory. No shared memory
4484** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004485*/
danda9fe0c2010-07-13 18:44:03 +00004486static int unixOpenSharedMemory(unixFile *pDbFd){
4487 struct unixShm *p = 0; /* The connection to be opened */
4488 struct unixShmNode *pShmNode; /* The underlying mmapped file */
dan92c02da2017-11-01 20:59:28 +00004489 int rc = SQLITE_OK; /* Result code */
danda9fe0c2010-07-13 18:44:03 +00004490 unixInodeInfo *pInode; /* The inode of fd */
danf12ba662017-11-07 15:43:52 +00004491 char *zShm; /* Name of the file used for SHM */
danda9fe0c2010-07-13 18:44:03 +00004492 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004493
danda9fe0c2010-07-13 18:44:03 +00004494 /* Allocate space for the new unixShm object. */
drhf3cdcdc2015-04-29 16:50:28 +00004495 p = sqlite3_malloc64( sizeof(*p) );
mistachkinfad30392016-02-13 23:43:46 +00004496 if( p==0 ) return SQLITE_NOMEM_BKPT;
drhd9e5c4f2010-05-12 18:01:39 +00004497 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004498 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004499
danda9fe0c2010-07-13 18:44:03 +00004500 /* Check to see if a unixShmNode object already exists. Reuse an existing
4501 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004502 */
drh095908e2018-08-13 20:46:18 +00004503 assert( unixFileMutexNotheld(pDbFd) );
drhd9e5c4f2010-05-12 18:01:39 +00004504 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004505 pInode = pDbFd->pInode;
4506 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004507 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004508 struct stat sStat; /* fstat() info for database file */
drh4bf66fd2015-02-19 02:43:02 +00004509#ifndef SQLITE_SHM_DIRECTORY
4510 const char *zBasePath = pDbFd->zPath;
4511#endif
danddb0ac42010-07-14 14:48:58 +00004512
4513 /* Call fstat() to figure out the permissions on the database file. If
4514 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004515 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004516 */
drhf3b1ed02015-12-02 13:11:03 +00004517 if( osFstat(pDbFd->h, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004518 rc = SQLITE_IOERR_FSTAT;
4519 goto shm_open_err;
4520 }
4521
drha4ced192010-07-15 18:32:40 +00004522#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004523 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004524#else
drh4bf66fd2015-02-19 02:43:02 +00004525 nShmFilename = 6 + (int)strlen(zBasePath);
drha4ced192010-07-15 18:32:40 +00004526#endif
drhf3cdcdc2015-04-29 16:50:28 +00004527 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004528 if( pShmNode==0 ){
mistachkinfad30392016-02-13 23:43:46 +00004529 rc = SQLITE_NOMEM_BKPT;
drhd9e5c4f2010-05-12 18:01:39 +00004530 goto shm_open_err;
4531 }
drh9cb5a0d2012-01-05 21:19:54 +00004532 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
danf12ba662017-11-07 15:43:52 +00004533 zShm = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004534#ifdef SQLITE_SHM_DIRECTORY
danf12ba662017-11-07 15:43:52 +00004535 sqlite3_snprintf(nShmFilename, zShm,
drha4ced192010-07-15 18:32:40 +00004536 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4537 (u32)sStat.st_ino, (u32)sStat.st_dev);
4538#else
danf12ba662017-11-07 15:43:52 +00004539 sqlite3_snprintf(nShmFilename, zShm, "%s-shm", zBasePath);
4540 sqlite3FileSuffix3(pDbFd->zPath, zShm);
drha4ced192010-07-15 18:32:40 +00004541#endif
drhd91c68f2010-05-14 14:52:25 +00004542 pShmNode->h = -1;
4543 pDbFd->pInode->pShmNode = pShmNode;
4544 pShmNode->pInode = pDbFd->pInode;
drh97a7e5e2016-04-26 18:58:54 +00004545 if( sqlite3GlobalConfig.bCoreMutex ){
4546 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4547 if( pShmNode->mutex==0 ){
4548 rc = SQLITE_NOMEM_BKPT;
4549 goto shm_open_err;
4550 }
drhd91c68f2010-05-14 14:52:25 +00004551 }
drhd9e5c4f2010-05-12 18:01:39 +00004552
drh3cb93392011-03-12 18:10:44 +00004553 if( pInode->bProcessLock==0 ){
danf12ba662017-11-07 15:43:52 +00004554 if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
4555 pShmNode->h = robust_open(zShm, O_RDWR|O_CREAT, (sStat.st_mode&0777));
drh3ec4a0c2011-10-11 18:18:54 +00004556 }
drh3cb93392011-03-12 18:10:44 +00004557 if( pShmNode->h<0 ){
danf12ba662017-11-07 15:43:52 +00004558 pShmNode->h = robust_open(zShm, O_RDONLY, (sStat.st_mode&0777));
4559 if( pShmNode->h<0 ){
4560 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShm);
4561 goto shm_open_err;
4562 }
4563 pShmNode->isReadonly = 1;
drhd9e5c4f2010-05-12 18:01:39 +00004564 }
drhac7c3ac2012-02-11 19:23:48 +00004565
4566 /* If this process is running as root, make sure that the SHM file
4567 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004568 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004569 */
drh6226ca22015-11-24 15:06:28 +00004570 robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
dan176b2a92017-11-01 06:59:19 +00004571
dan92c02da2017-11-01 20:59:28 +00004572 rc = unixLockSharedMemory(pDbFd, pShmNode);
drh7e45e3a2017-11-08 17:32:12 +00004573 if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004574 }
drhd9e5c4f2010-05-12 18:01:39 +00004575 }
4576
drhd91c68f2010-05-14 14:52:25 +00004577 /* Make the new connection a child of the unixShmNode */
4578 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004579#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004580 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004581#endif
drhd91c68f2010-05-14 14:52:25 +00004582 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004583 pDbFd->pShm = p;
4584 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004585
4586 /* The reference count on pShmNode has already been incremented under
4587 ** the cover of the unixEnterMutex() mutex and the pointer from the
4588 ** new (struct unixShm) object to the pShmNode has been set. All that is
4589 ** left to do is to link the new object into the linked list starting
4590 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4591 ** mutex.
4592 */
4593 sqlite3_mutex_enter(pShmNode->mutex);
4594 p->pNext = pShmNode->pFirst;
4595 pShmNode->pFirst = p;
4596 sqlite3_mutex_leave(pShmNode->mutex);
dan92c02da2017-11-01 20:59:28 +00004597 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004598
4599 /* Jump here on any error */
4600shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004601 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004602 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004603 unixLeaveMutex();
4604 return rc;
4605}
4606
4607/*
danda9fe0c2010-07-13 18:44:03 +00004608** This function is called to obtain a pointer to region iRegion of the
4609** shared-memory associated with the database file fd. Shared-memory regions
4610** are numbered starting from zero. Each shared-memory region is szRegion
4611** bytes in size.
4612**
4613** If an error occurs, an error code is returned and *pp is set to NULL.
4614**
4615** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4616** region has not been allocated (by any client, including one running in a
4617** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4618** bExtend is non-zero and the requested shared-memory region has not yet
4619** been allocated, it is allocated by this function.
4620**
4621** If the shared-memory region has already been allocated or is allocated by
4622** this call as described above, then it is mapped into this processes
4623** address space (if it is not already), *pp is set to point to the mapped
4624** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004625*/
danda9fe0c2010-07-13 18:44:03 +00004626static int unixShmMap(
4627 sqlite3_file *fd, /* Handle open on database file */
4628 int iRegion, /* Region to retrieve */
4629 int szRegion, /* Size of regions */
4630 int bExtend, /* True to extend file if necessary */
4631 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004632){
danda9fe0c2010-07-13 18:44:03 +00004633 unixFile *pDbFd = (unixFile*)fd;
4634 unixShm *p;
4635 unixShmNode *pShmNode;
4636 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004637 int nShmPerMap = unixShmRegionPerMap();
4638 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004639
danda9fe0c2010-07-13 18:44:03 +00004640 /* If the shared-memory file has not yet been opened, open it now. */
4641 if( pDbFd->pShm==0 ){
4642 rc = unixOpenSharedMemory(pDbFd);
4643 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004644 }
drhd9e5c4f2010-05-12 18:01:39 +00004645
danda9fe0c2010-07-13 18:44:03 +00004646 p = pDbFd->pShm;
4647 pShmNode = p->pShmNode;
4648 sqlite3_mutex_enter(pShmNode->mutex);
dan92c02da2017-11-01 20:59:28 +00004649 if( pShmNode->isUnlocked ){
4650 rc = unixLockSharedMemory(pDbFd, pShmNode);
4651 if( rc!=SQLITE_OK ) goto shmpage_out;
4652 pShmNode->isUnlocked = 0;
4653 }
danda9fe0c2010-07-13 18:44:03 +00004654 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004655 assert( pShmNode->pInode==pDbFd->pInode );
4656 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4657 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004658
dan781e34c2014-03-20 08:59:47 +00004659 /* Minimum number of regions required to be mapped. */
4660 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4661
4662 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004663 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004664 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004665 struct stat sStat; /* Used by fstat() */
4666
4667 pShmNode->szRegion = szRegion;
4668
drh3cb93392011-03-12 18:10:44 +00004669 if( pShmNode->h>=0 ){
4670 /* The requested region is not mapped into this processes address space.
4671 ** Check to see if it has been allocated (i.e. if the wal-index file is
4672 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004673 */
drh3cb93392011-03-12 18:10:44 +00004674 if( osFstat(pShmNode->h, &sStat) ){
4675 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004676 goto shmpage_out;
4677 }
drh3cb93392011-03-12 18:10:44 +00004678
4679 if( sStat.st_size<nByte ){
4680 /* The requested memory region does not exist. If bExtend is set to
4681 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004682 */
dan47a2b4a2013-04-26 16:09:29 +00004683 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004684 goto shmpage_out;
4685 }
dan47a2b4a2013-04-26 16:09:29 +00004686
4687 /* Alternatively, if bExtend is true, extend the file. Do this by
4688 ** writing a single byte to the end of each (OS) page being
4689 ** allocated or extended. Technically, we need only write to the
4690 ** last page in order to extend the file. But writing to all new
4691 ** pages forces the OS to allocate them immediately, which reduces
4692 ** the chances of SIGBUS while accessing the mapped region later on.
4693 */
4694 else{
4695 static const int pgsz = 4096;
4696 int iPg;
4697
4698 /* Write to the last byte of each newly allocated or extended page */
4699 assert( (nByte % pgsz)==0 );
4700 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
drhe1818ec2015-12-01 16:21:35 +00004701 int x = 0;
4702 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
dan47a2b4a2013-04-26 16:09:29 +00004703 const char *zFile = pShmNode->zFilename;
4704 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4705 goto shmpage_out;
4706 }
4707 }
drh3cb93392011-03-12 18:10:44 +00004708 }
4709 }
danda9fe0c2010-07-13 18:44:03 +00004710 }
4711
4712 /* Map the requested memory region into this processes address space. */
4713 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004714 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004715 );
4716 if( !apNew ){
mistachkinfad30392016-02-13 23:43:46 +00004717 rc = SQLITE_IOERR_NOMEM_BKPT;
danda9fe0c2010-07-13 18:44:03 +00004718 goto shmpage_out;
4719 }
4720 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004721 while( pShmNode->nRegion<nReqRegion ){
4722 int nMap = szRegion*nShmPerMap;
4723 int i;
drh3cb93392011-03-12 18:10:44 +00004724 void *pMem;
4725 if( pShmNode->h>=0 ){
dan781e34c2014-03-20 08:59:47 +00004726 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004727 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004728 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004729 );
4730 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004731 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004732 goto shmpage_out;
4733 }
4734 }else{
drhf3cdcdc2015-04-29 16:50:28 +00004735 pMem = sqlite3_malloc64(szRegion);
drh3cb93392011-03-12 18:10:44 +00004736 if( pMem==0 ){
mistachkinfad30392016-02-13 23:43:46 +00004737 rc = SQLITE_NOMEM_BKPT;
drh3cb93392011-03-12 18:10:44 +00004738 goto shmpage_out;
4739 }
4740 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004741 }
dan781e34c2014-03-20 08:59:47 +00004742
4743 for(i=0; i<nShmPerMap; i++){
4744 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4745 }
4746 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004747 }
4748 }
4749
4750shmpage_out:
4751 if( pShmNode->nRegion>iRegion ){
4752 *pp = pShmNode->apRegion[iRegion];
4753 }else{
4754 *pp = 0;
4755 }
drh66dfec8b2011-06-01 20:01:49 +00004756 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004757 sqlite3_mutex_leave(pShmNode->mutex);
4758 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004759}
4760
4761/*
drhd9e5c4f2010-05-12 18:01:39 +00004762** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004763**
4764** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4765** different here than in posix. In xShmLock(), one can go from unlocked
4766** to shared and back or from unlocked to exclusive and back. But one may
4767** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004768*/
4769static int unixShmLock(
4770 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004771 int ofst, /* First lock to acquire or release */
4772 int n, /* Number of locks to acquire or release */
4773 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004774){
drh73b64e42010-05-30 19:55:15 +00004775 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4776 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4777 unixShm *pX; /* For looping over all siblings */
4778 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4779 int rc = SQLITE_OK; /* Result code */
4780 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004781
drhd91c68f2010-05-14 14:52:25 +00004782 assert( pShmNode==pDbFd->pInode->pShmNode );
4783 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004784 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004785 assert( n>=1 );
4786 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4787 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4788 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4789 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4790 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004791 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4792 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004793
drhc99597c2010-05-31 01:41:15 +00004794 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004795 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004796 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004797 if( flags & SQLITE_SHM_UNLOCK ){
4798 u16 allMask = 0; /* Mask of locks held by siblings */
4799
4800 /* See if any siblings hold this same lock */
4801 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4802 if( pX==p ) continue;
4803 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4804 allMask |= pX->sharedMask;
4805 }
4806
4807 /* Unlock the system-level locks */
4808 if( (mask & allMask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004809 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004810 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004811 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004812 }
drh73b64e42010-05-30 19:55:15 +00004813
4814 /* Undo the local locks */
4815 if( rc==SQLITE_OK ){
4816 p->exclMask &= ~mask;
4817 p->sharedMask &= ~mask;
4818 }
4819 }else if( flags & SQLITE_SHM_SHARED ){
4820 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4821
4822 /* Find out which shared locks are already held by sibling connections.
4823 ** If any sibling already holds an exclusive lock, go ahead and return
4824 ** SQLITE_BUSY.
4825 */
4826 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004827 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004828 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004829 break;
4830 }
4831 allShared |= pX->sharedMask;
4832 }
4833
4834 /* Get shared locks at the system level, if necessary */
4835 if( rc==SQLITE_OK ){
4836 if( (allShared & mask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004837 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004838 }else{
drh73b64e42010-05-30 19:55:15 +00004839 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004840 }
drhd9e5c4f2010-05-12 18:01:39 +00004841 }
drh73b64e42010-05-30 19:55:15 +00004842
4843 /* Get the local shared locks */
4844 if( rc==SQLITE_OK ){
4845 p->sharedMask |= mask;
4846 }
4847 }else{
4848 /* Make sure no sibling connections hold locks that will block this
4849 ** lock. If any do, return SQLITE_BUSY right away.
4850 */
4851 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004852 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4853 rc = SQLITE_BUSY;
4854 break;
4855 }
4856 }
4857
4858 /* Get the exclusive locks at the system level. Then if successful
4859 ** also mark the local connection as being locked.
4860 */
4861 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004862 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004863 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004864 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004865 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004866 }
drhd9e5c4f2010-05-12 18:01:39 +00004867 }
4868 }
drhd91c68f2010-05-14 14:52:25 +00004869 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004870 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
drh5ac93652015-03-21 20:59:43 +00004871 p->id, osGetpid(0), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004872 return rc;
4873}
4874
drh286a2882010-05-20 23:51:06 +00004875/*
4876** Implement a memory barrier or memory fence on shared memory.
4877**
4878** All loads and stores begun before the barrier must complete before
4879** any load or store begun after the barrier.
4880*/
4881static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004882 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004883){
drhff828942010-06-26 21:34:06 +00004884 UNUSED_PARAMETER(fd);
drh22c733d2015-09-24 12:40:43 +00004885 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
dana86acc22018-09-12 20:32:19 +00004886 assert( fd->pMethods->xLock==nolockLock
4887 || unixFileMutexNotheld((unixFile*)fd)
4888 );
drh22c733d2015-09-24 12:40:43 +00004889 unixEnterMutex(); /* Also mutex, for redundancy */
drhb29ad852010-06-01 00:03:57 +00004890 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004891}
4892
dan18801912010-06-14 14:07:50 +00004893/*
danda9fe0c2010-07-13 18:44:03 +00004894** Close a connection to shared-memory. Delete the underlying
4895** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004896**
4897** If there is no shared memory associated with the connection then this
4898** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004899*/
danda9fe0c2010-07-13 18:44:03 +00004900static int unixShmUnmap(
4901 sqlite3_file *fd, /* The underlying database file */
4902 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004903){
danda9fe0c2010-07-13 18:44:03 +00004904 unixShm *p; /* The connection to be closed */
4905 unixShmNode *pShmNode; /* The underlying shared-memory file */
4906 unixShm **pp; /* For looping over sibling connections */
4907 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004908
danda9fe0c2010-07-13 18:44:03 +00004909 pDbFd = (unixFile*)fd;
4910 p = pDbFd->pShm;
4911 if( p==0 ) return SQLITE_OK;
4912 pShmNode = p->pShmNode;
4913
4914 assert( pShmNode==pDbFd->pInode->pShmNode );
4915 assert( pShmNode->pInode==pDbFd->pInode );
4916
4917 /* Remove connection p from the set of connections associated
4918 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004919 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004920 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4921 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004922
danda9fe0c2010-07-13 18:44:03 +00004923 /* Free the connection p */
4924 sqlite3_free(p);
4925 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004926 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004927
4928 /* If pShmNode->nRef has reached 0, then close the underlying
4929 ** shared-memory file, too */
drh095908e2018-08-13 20:46:18 +00004930 assert( unixFileMutexNotheld(pDbFd) );
danda9fe0c2010-07-13 18:44:03 +00004931 unixEnterMutex();
4932 assert( pShmNode->nRef>0 );
4933 pShmNode->nRef--;
4934 if( pShmNode->nRef==0 ){
drh4bf66fd2015-02-19 02:43:02 +00004935 if( deleteFlag && pShmNode->h>=0 ){
4936 osUnlink(pShmNode->zFilename);
4937 }
danda9fe0c2010-07-13 18:44:03 +00004938 unixShmPurge(pDbFd);
4939 }
4940 unixLeaveMutex();
4941
4942 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004943}
drh286a2882010-05-20 23:51:06 +00004944
danda9fe0c2010-07-13 18:44:03 +00004945
drhd9e5c4f2010-05-12 18:01:39 +00004946#else
drh6b017cc2010-06-14 18:01:46 +00004947# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004948# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004949# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004950# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004951#endif /* #ifndef SQLITE_OMIT_WAL */
4952
mistachkine98844f2013-08-24 00:59:24 +00004953#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004954/*
danaef49d72013-03-25 16:28:54 +00004955** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004956*/
danf23da962013-03-23 21:00:41 +00004957static void unixUnmapfile(unixFile *pFd){
4958 assert( pFd->nFetchOut==0 );
4959 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004960 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004961 pFd->pMapRegion = 0;
4962 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004963 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004964 }
4965}
dan5d8a1372013-03-19 19:28:06 +00004966
danaef49d72013-03-25 16:28:54 +00004967/*
dane6ecd662013-04-01 17:56:59 +00004968** Attempt to set the size of the memory mapping maintained by file
4969** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4970**
4971** If successful, this function sets the following variables:
4972**
4973** unixFile.pMapRegion
4974** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004975** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004976**
4977** If unsuccessful, an error message is logged via sqlite3_log() and
4978** the three variables above are zeroed. In this case SQLite should
4979** continue accessing the database using the xRead() and xWrite()
4980** methods.
4981*/
4982static void unixRemapfile(
4983 unixFile *pFd, /* File descriptor object */
4984 i64 nNew /* Required mapping size */
4985){
dan4ff7bc42013-04-02 12:04:09 +00004986 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004987 int h = pFd->h; /* File descriptor open on db file */
4988 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004989 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004990 u8 *pNew = 0; /* Location of new mapping */
4991 int flags = PROT_READ; /* Flags to pass to mmap() */
4992
4993 assert( pFd->nFetchOut==0 );
4994 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004995 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004996 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004997 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004998 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004999
danfe33e392015-11-17 20:56:06 +00005000#ifdef SQLITE_MMAP_READWRITE
dane6ecd662013-04-01 17:56:59 +00005001 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
danfe33e392015-11-17 20:56:06 +00005002#endif
dane6ecd662013-04-01 17:56:59 +00005003
5004 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00005005#if HAVE_MREMAP
5006 i64 nReuse = pFd->mmapSize;
5007#else
danbc760632014-03-20 09:42:09 +00005008 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00005009 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00005010#endif
dane6ecd662013-04-01 17:56:59 +00005011 u8 *pReq = &pOrig[nReuse];
5012
5013 /* Unmap any pages of the existing mapping that cannot be reused. */
5014 if( nReuse!=nOrig ){
5015 osMunmap(pReq, nOrig-nReuse);
5016 }
5017
5018#if HAVE_MREMAP
5019 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00005020 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00005021#else
5022 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
5023 if( pNew!=MAP_FAILED ){
5024 if( pNew!=pReq ){
5025 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00005026 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00005027 }else{
5028 pNew = pOrig;
5029 }
5030 }
5031#endif
5032
dan48ccef82013-04-02 20:55:01 +00005033 /* The attempt to extend the existing mapping failed. Free it. */
5034 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00005035 osMunmap(pOrig, nReuse);
5036 }
5037 }
5038
5039 /* If pNew is still NULL, try to create an entirely new mapping. */
5040 if( pNew==0 ){
5041 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00005042 }
5043
dan4ff7bc42013-04-02 12:04:09 +00005044 if( pNew==MAP_FAILED ){
5045 pNew = 0;
5046 nNew = 0;
5047 unixLogError(SQLITE_OK, zErr, pFd->zPath);
5048
5049 /* If the mmap() above failed, assume that all subsequent mmap() calls
5050 ** will probably fail too. Fall back to using xRead/xWrite exclusively
5051 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00005052 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00005053 }
dane6ecd662013-04-01 17:56:59 +00005054 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00005055 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00005056}
5057
5058/*
danaef49d72013-03-25 16:28:54 +00005059** Memory map or remap the file opened by file-descriptor pFd (if the file
5060** is already mapped, the existing mapping is replaced by the new). Or, if
5061** there already exists a mapping for this file, and there are still
5062** outstanding xFetch() references to it, this function is a no-op.
5063**
5064** If parameter nByte is non-negative, then it is the requested size of
5065** the mapping to create. Otherwise, if nByte is less than zero, then the
5066** requested size is the size of the file on disk. The actual size of the
5067** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00005068** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00005069**
5070** SQLITE_OK is returned if no error occurs (even if the mapping is not
5071** recreated as a result of outstanding references) or an SQLite error
5072** code otherwise.
5073*/
drhf3b1ed02015-12-02 13:11:03 +00005074static int unixMapfile(unixFile *pFd, i64 nMap){
danf23da962013-03-23 21:00:41 +00005075 assert( nMap>=0 || pFd->nFetchOut==0 );
drh333e6ca2015-12-02 15:44:39 +00005076 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00005077 if( pFd->nFetchOut>0 ) return SQLITE_OK;
5078
5079 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00005080 struct stat statbuf; /* Low-level file information */
drhf3b1ed02015-12-02 13:11:03 +00005081 if( osFstat(pFd->h, &statbuf) ){
danf23da962013-03-23 21:00:41 +00005082 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00005083 }
drh3044b512014-06-16 16:41:52 +00005084 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00005085 }
drh9b4c59f2013-04-15 17:03:42 +00005086 if( nMap>pFd->mmapSizeMax ){
5087 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00005088 }
5089
drh333e6ca2015-12-02 15:44:39 +00005090 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00005091 if( nMap!=pFd->mmapSize ){
drh333e6ca2015-12-02 15:44:39 +00005092 unixRemapfile(pFd, nMap);
dan5d8a1372013-03-19 19:28:06 +00005093 }
5094
danf23da962013-03-23 21:00:41 +00005095 return SQLITE_OK;
5096}
mistachkine98844f2013-08-24 00:59:24 +00005097#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00005098
danaef49d72013-03-25 16:28:54 +00005099/*
5100** If possible, return a pointer to a mapping of file fd starting at offset
5101** iOff. The mapping must be valid for at least nAmt bytes.
5102**
5103** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
5104** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
5105** Finally, if an error does occur, return an SQLite error code. The final
5106** value of *pp is undefined in this case.
5107**
5108** If this function does return a pointer, the caller must eventually
5109** release the reference by calling unixUnfetch().
5110*/
danf23da962013-03-23 21:00:41 +00005111static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00005112#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00005113 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00005114#endif
danf23da962013-03-23 21:00:41 +00005115 *pp = 0;
5116
drh9b4c59f2013-04-15 17:03:42 +00005117#if SQLITE_MAX_MMAP_SIZE>0
5118 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00005119 if( pFd->pMapRegion==0 ){
5120 int rc = unixMapfile(pFd, -1);
5121 if( rc!=SQLITE_OK ) return rc;
5122 }
5123 if( pFd->mmapSize >= iOff+nAmt ){
5124 *pp = &((u8 *)pFd->pMapRegion)[iOff];
5125 pFd->nFetchOut++;
5126 }
5127 }
drh6e0b6d52013-04-09 16:19:20 +00005128#endif
danf23da962013-03-23 21:00:41 +00005129 return SQLITE_OK;
5130}
5131
danaef49d72013-03-25 16:28:54 +00005132/*
dandf737fe2013-03-25 17:00:24 +00005133** If the third argument is non-NULL, then this function releases a
5134** reference obtained by an earlier call to unixFetch(). The second
5135** argument passed to this function must be the same as the corresponding
5136** argument that was passed to the unixFetch() invocation.
5137**
5138** Or, if the third argument is NULL, then this function is being called
5139** to inform the VFS layer that, according to POSIX, any existing mapping
5140** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00005141*/
dandf737fe2013-03-25 17:00:24 +00005142static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00005143#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00005144 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00005145 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00005146
danaef49d72013-03-25 16:28:54 +00005147 /* If p==0 (unmap the entire file) then there must be no outstanding
5148 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
5149 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00005150 assert( (p==0)==(pFd->nFetchOut==0) );
5151
dandf737fe2013-03-25 17:00:24 +00005152 /* If p!=0, it must match the iOff value. */
5153 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
5154
danf23da962013-03-23 21:00:41 +00005155 if( p ){
5156 pFd->nFetchOut--;
5157 }else{
5158 unixUnmapfile(pFd);
5159 }
5160
5161 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00005162#else
5163 UNUSED_PARAMETER(fd);
5164 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00005165 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00005166#endif
danf23da962013-03-23 21:00:41 +00005167 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00005168}
5169
5170/*
drh734c9862008-11-28 15:37:20 +00005171** Here ends the implementation of all sqlite3_file methods.
5172**
5173********************** End sqlite3_file Methods *******************************
5174******************************************************************************/
5175
5176/*
drh6b9d6dd2008-12-03 19:34:47 +00005177** This division contains definitions of sqlite3_io_methods objects that
5178** implement various file locking strategies. It also contains definitions
5179** of "finder" functions. A finder-function is used to locate the appropriate
5180** sqlite3_io_methods object for a particular database file. The pAppData
5181** field of the sqlite3_vfs VFS objects are initialized to be pointers to
5182** the correct finder-function for that VFS.
5183**
5184** Most finder functions return a pointer to a fixed sqlite3_io_methods
5185** object. The only interesting finder-function is autolockIoFinder, which
5186** looks at the filesystem type and tries to guess the best locking
5187** strategy from that.
5188**
peter.d.reid60ec9142014-09-06 16:39:46 +00005189** For finder-function F, two objects are created:
drh1875f7a2008-12-08 18:19:17 +00005190**
5191** (1) The real finder-function named "FImpt()".
5192**
dane946c392009-08-22 11:39:46 +00005193** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00005194**
5195**
5196** A pointer to the F pointer is used as the pAppData value for VFS
5197** objects. We have to do this instead of letting pAppData point
5198** directly at the finder-function since C90 rules prevent a void*
5199** from be cast into a function pointer.
5200**
drh6b9d6dd2008-12-03 19:34:47 +00005201**
drh7708e972008-11-29 00:56:52 +00005202** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00005203**
drh7708e972008-11-29 00:56:52 +00005204** * A constant sqlite3_io_methods object call METHOD that has locking
5205** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
5206**
5207** * An I/O method finder function called FINDER that returns a pointer
5208** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00005209*/
drhe6d41732015-02-21 00:49:00 +00005210#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
drh7708e972008-11-29 00:56:52 +00005211static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00005212 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00005213 CLOSE, /* xClose */ \
5214 unixRead, /* xRead */ \
5215 unixWrite, /* xWrite */ \
5216 unixTruncate, /* xTruncate */ \
5217 unixSync, /* xSync */ \
5218 unixFileSize, /* xFileSize */ \
5219 LOCK, /* xLock */ \
5220 UNLOCK, /* xUnlock */ \
5221 CKLOCK, /* xCheckReservedLock */ \
5222 unixFileControl, /* xFileControl */ \
5223 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00005224 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drhd9f94412014-09-22 03:22:27 +00005225 SHMMAP, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00005226 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00005227 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00005228 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00005229 unixFetch, /* xFetch */ \
5230 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00005231}; \
drh0c2694b2009-09-03 16:23:44 +00005232static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
5233 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00005234 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00005235} \
drh0c2694b2009-09-03 16:23:44 +00005236static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00005237 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00005238
5239/*
5240** Here are all of the sqlite3_io_methods objects for each of the
5241** locking strategies. Functions that return pointers to these methods
5242** are also created.
5243*/
5244IOMETHODS(
5245 posixIoFinder, /* Finder function name */
5246 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00005247 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00005248 unixClose, /* xClose method */
5249 unixLock, /* xLock method */
5250 unixUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005251 unixCheckReservedLock, /* xCheckReservedLock method */
5252 unixShmMap /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005253)
drh7708e972008-11-29 00:56:52 +00005254IOMETHODS(
5255 nolockIoFinder, /* Finder function name */
5256 nolockIoMethods, /* sqlite3_io_methods object name */
drh3e2c8422018-08-13 11:32:07 +00005257 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00005258 nolockClose, /* xClose method */
5259 nolockLock, /* xLock method */
5260 nolockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005261 nolockCheckReservedLock, /* xCheckReservedLock method */
5262 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005263)
drh7708e972008-11-29 00:56:52 +00005264IOMETHODS(
5265 dotlockIoFinder, /* Finder function name */
5266 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005267 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005268 dotlockClose, /* xClose method */
5269 dotlockLock, /* xLock method */
5270 dotlockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005271 dotlockCheckReservedLock, /* xCheckReservedLock method */
5272 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005273)
drh7708e972008-11-29 00:56:52 +00005274
drhe89b2912015-03-03 20:42:01 +00005275#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005276IOMETHODS(
5277 flockIoFinder, /* Finder function name */
5278 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005279 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005280 flockClose, /* xClose method */
5281 flockLock, /* xLock method */
5282 flockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005283 flockCheckReservedLock, /* xCheckReservedLock method */
5284 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005285)
drh7708e972008-11-29 00:56:52 +00005286#endif
5287
drh6c7d5c52008-11-21 20:32:33 +00005288#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005289IOMETHODS(
5290 semIoFinder, /* Finder function name */
5291 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005292 1, /* shared memory is disabled */
drh8cd5b252015-03-02 22:06:43 +00005293 semXClose, /* xClose method */
5294 semXLock, /* xLock method */
5295 semXUnlock, /* xUnlock method */
5296 semXCheckReservedLock, /* xCheckReservedLock method */
drhd9f94412014-09-22 03:22:27 +00005297 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005298)
aswiftaebf4132008-11-21 00:10:35 +00005299#endif
drh7708e972008-11-29 00:56:52 +00005300
drhd2cb50b2009-01-09 21:41:17 +00005301#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005302IOMETHODS(
5303 afpIoFinder, /* Finder function name */
5304 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005305 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005306 afpClose, /* xClose method */
5307 afpLock, /* xLock method */
5308 afpUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005309 afpCheckReservedLock, /* xCheckReservedLock method */
5310 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005311)
drh715ff302008-12-03 22:32:44 +00005312#endif
5313
5314/*
5315** The proxy locking method is a "super-method" in the sense that it
5316** opens secondary file descriptors for the conch and lock files and
5317** it uses proxy, dot-file, AFP, and flock() locking methods on those
5318** secondary files. For this reason, the division that implements
5319** proxy locking is located much further down in the file. But we need
5320** to go ahead and define the sqlite3_io_methods and finder function
5321** for proxy locking here. So we forward declare the I/O methods.
5322*/
drhd2cb50b2009-01-09 21:41:17 +00005323#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005324static int proxyClose(sqlite3_file*);
5325static int proxyLock(sqlite3_file*, int);
5326static int proxyUnlock(sqlite3_file*, int);
5327static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005328IOMETHODS(
5329 proxyIoFinder, /* Finder function name */
5330 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005331 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005332 proxyClose, /* xClose method */
5333 proxyLock, /* xLock method */
5334 proxyUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005335 proxyCheckReservedLock, /* xCheckReservedLock method */
5336 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005337)
aswiftaebf4132008-11-21 00:10:35 +00005338#endif
drh7708e972008-11-29 00:56:52 +00005339
drh7ed97b92010-01-20 13:07:21 +00005340/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5341#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5342IOMETHODS(
5343 nfsIoFinder, /* Finder function name */
5344 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005345 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005346 unixClose, /* xClose method */
5347 unixLock, /* xLock method */
5348 nfsUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005349 unixCheckReservedLock, /* xCheckReservedLock method */
5350 0 /* xShmMap method */
drh7ed97b92010-01-20 13:07:21 +00005351)
5352#endif
drh7708e972008-11-29 00:56:52 +00005353
drhd2cb50b2009-01-09 21:41:17 +00005354#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005355/*
drh6b9d6dd2008-12-03 19:34:47 +00005356** This "finder" function attempts to determine the best locking strategy
5357** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005358** object that implements that strategy.
5359**
5360** This is for MacOSX only.
5361*/
drh1875f7a2008-12-08 18:19:17 +00005362static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005363 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005364 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005365){
5366 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005367 const char *zFilesystem; /* Filesystem type name */
5368 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005369 } aMap[] = {
5370 { "hfs", &posixIoMethods },
5371 { "ufs", &posixIoMethods },
5372 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005373 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005374 { "webdav", &nolockIoMethods },
5375 { 0, 0 }
5376 };
5377 int i;
5378 struct statfs fsInfo;
5379 struct flock lockInfo;
5380
5381 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005382 /* If filePath==NULL that means we are dealing with a transient file
5383 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005384 return &nolockIoMethods;
5385 }
5386 if( statfs(filePath, &fsInfo) != -1 ){
5387 if( fsInfo.f_flags & MNT_RDONLY ){
5388 return &nolockIoMethods;
5389 }
5390 for(i=0; aMap[i].zFilesystem; i++){
5391 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5392 return aMap[i].pMethods;
5393 }
5394 }
5395 }
5396
5397 /* Default case. Handles, amongst others, "nfs".
5398 ** Test byte-range lock using fcntl(). If the call succeeds,
5399 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005400 */
drh7708e972008-11-29 00:56:52 +00005401 lockInfo.l_len = 1;
5402 lockInfo.l_start = 0;
5403 lockInfo.l_whence = SEEK_SET;
5404 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005405 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005406 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5407 return &nfsIoMethods;
5408 } else {
5409 return &posixIoMethods;
5410 }
drh7708e972008-11-29 00:56:52 +00005411 }else{
5412 return &dotlockIoMethods;
5413 }
5414}
drh0c2694b2009-09-03 16:23:44 +00005415static const sqlite3_io_methods
5416 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005417
drhd2cb50b2009-01-09 21:41:17 +00005418#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005419
drhe89b2912015-03-03 20:42:01 +00005420#if OS_VXWORKS
5421/*
5422** This "finder" function for VxWorks checks to see if posix advisory
5423** locking works. If it does, then that is what is used. If it does not
5424** work, then fallback to named semaphore locking.
chw78a13182009-04-07 05:35:03 +00005425*/
drhe89b2912015-03-03 20:42:01 +00005426static const sqlite3_io_methods *vxworksIoFinderImpl(
chw78a13182009-04-07 05:35:03 +00005427 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005428 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005429){
5430 struct flock lockInfo;
5431
5432 if( !filePath ){
5433 /* If filePath==NULL that means we are dealing with a transient file
5434 ** that does not need to be locked. */
5435 return &nolockIoMethods;
5436 }
5437
5438 /* Test if fcntl() is supported and use POSIX style locks.
5439 ** Otherwise fall back to the named semaphore method.
5440 */
5441 lockInfo.l_len = 1;
5442 lockInfo.l_start = 0;
5443 lockInfo.l_whence = SEEK_SET;
5444 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005445 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005446 return &posixIoMethods;
5447 }else{
5448 return &semIoMethods;
5449 }
5450}
drh0c2694b2009-09-03 16:23:44 +00005451static const sqlite3_io_methods
drhe89b2912015-03-03 20:42:01 +00005452 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005453
drhe89b2912015-03-03 20:42:01 +00005454#endif /* OS_VXWORKS */
chw78a13182009-04-07 05:35:03 +00005455
drh7708e972008-11-29 00:56:52 +00005456/*
peter.d.reid60ec9142014-09-06 16:39:46 +00005457** An abstract type for a pointer to an IO method finder function:
drh7708e972008-11-29 00:56:52 +00005458*/
drh0c2694b2009-09-03 16:23:44 +00005459typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005460
aswiftaebf4132008-11-21 00:10:35 +00005461
drh734c9862008-11-28 15:37:20 +00005462/****************************************************************************
5463**************************** sqlite3_vfs methods ****************************
5464**
5465** This division contains the implementation of methods on the
5466** sqlite3_vfs object.
5467*/
5468
danielk1977a3d4c882007-03-23 10:08:38 +00005469/*
danielk1977e339d652008-06-28 11:23:00 +00005470** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005471*/
5472static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005473 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005474 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005475 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005476 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005477 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005478){
drh7708e972008-11-29 00:56:52 +00005479 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005480 unixFile *pNew = (unixFile *)pId;
5481 int rc = SQLITE_OK;
5482
drh8af6c222010-05-14 12:43:01 +00005483 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005484
drhb07028f2011-10-14 21:49:18 +00005485 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005486 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005487
drh308c2a52010-05-14 11:30:18 +00005488 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005489 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005490 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005491 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005492 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005493#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005494 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005495#endif
drhc02a43a2012-01-10 23:18:38 +00005496 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5497 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005498 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005499 }
drh503a6862013-03-01 01:07:17 +00005500 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005501 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005502 }
drh339eb0b2008-03-07 15:34:11 +00005503
drh6c7d5c52008-11-21 20:32:33 +00005504#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005505 pNew->pId = vxworksFindFileId(zFilename);
5506 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005507 ctrlFlags |= UNIXFILE_NOLOCK;
mistachkinfad30392016-02-13 23:43:46 +00005508 rc = SQLITE_NOMEM_BKPT;
chw97185482008-11-17 08:05:31 +00005509 }
5510#endif
5511
drhc02a43a2012-01-10 23:18:38 +00005512 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005513 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005514 }else{
drh0c2694b2009-09-03 16:23:44 +00005515 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005516#if SQLITE_ENABLE_LOCKING_STYLE
5517 /* Cache zFilename in the locking context (AFP and dotlock override) for
5518 ** proxyLock activation is possible (remote proxy is based on db name)
5519 ** zFilename remains valid until file is closed, to support */
5520 pNew->lockingContext = (void*)zFilename;
5521#endif
drhda0e7682008-07-30 15:27:54 +00005522 }
danielk1977e339d652008-06-28 11:23:00 +00005523
drh7ed97b92010-01-20 13:07:21 +00005524 if( pLockingStyle == &posixIoMethods
5525#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5526 || pLockingStyle == &nfsIoMethods
5527#endif
5528 ){
drh7708e972008-11-29 00:56:52 +00005529 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005530 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005531 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005532 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005533 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005534 ** in two scenarios:
5535 **
5536 ** (a) A call to fstat() failed.
5537 ** (b) A malloc failed.
5538 **
5539 ** Scenario (b) may only occur if the process is holding no other
5540 ** file descriptors open on the same file. If there were other file
5541 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005542 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005543 ** handle h - as it is guaranteed that no posix locks will be released
5544 ** by doing so.
5545 **
5546 ** If scenario (a) caused the error then things are not so safe. The
5547 ** implicit assumption here is that if fstat() fails, things are in
5548 ** such bad shape that dropping a lock or two doesn't matter much.
5549 */
drh0e9365c2011-03-02 02:08:13 +00005550 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005551 h = -1;
5552 }
drh7708e972008-11-29 00:56:52 +00005553 unixLeaveMutex();
5554 }
danielk1977e339d652008-06-28 11:23:00 +00005555
drhd2cb50b2009-01-09 21:41:17 +00005556#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005557 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005558 /* AFP locking uses the file path so it needs to be included in
5559 ** the afpLockingContext.
5560 */
5561 afpLockingContext *pCtx;
drhf3cdcdc2015-04-29 16:50:28 +00005562 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh7708e972008-11-29 00:56:52 +00005563 if( pCtx==0 ){
mistachkinfad30392016-02-13 23:43:46 +00005564 rc = SQLITE_NOMEM_BKPT;
drh7708e972008-11-29 00:56:52 +00005565 }else{
5566 /* NB: zFilename exists and remains valid until the file is closed
5567 ** according to requirement F11141. So we do not need to make a
5568 ** copy of the filename. */
5569 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005570 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005571 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005572 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005573 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005574 if( rc!=SQLITE_OK ){
5575 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005576 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005577 h = -1;
5578 }
drh7708e972008-11-29 00:56:52 +00005579 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005580 }
drh7708e972008-11-29 00:56:52 +00005581 }
5582#endif
danielk1977e339d652008-06-28 11:23:00 +00005583
drh7708e972008-11-29 00:56:52 +00005584 else if( pLockingStyle == &dotlockIoMethods ){
5585 /* Dotfile locking uses the file path so it needs to be included in
5586 ** the dotlockLockingContext
5587 */
5588 char *zLockFile;
5589 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005590 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005591 nFilename = (int)strlen(zFilename) + 6;
drhf3cdcdc2015-04-29 16:50:28 +00005592 zLockFile = (char *)sqlite3_malloc64(nFilename);
drh7708e972008-11-29 00:56:52 +00005593 if( zLockFile==0 ){
mistachkinfad30392016-02-13 23:43:46 +00005594 rc = SQLITE_NOMEM_BKPT;
drh7708e972008-11-29 00:56:52 +00005595 }else{
5596 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005597 }
drh7708e972008-11-29 00:56:52 +00005598 pNew->lockingContext = zLockFile;
5599 }
danielk1977e339d652008-06-28 11:23:00 +00005600
drh6c7d5c52008-11-21 20:32:33 +00005601#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005602 else if( pLockingStyle == &semIoMethods ){
5603 /* Named semaphore locking uses the file path so it needs to be
5604 ** included in the semLockingContext
5605 */
5606 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005607 rc = findInodeInfo(pNew, &pNew->pInode);
5608 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5609 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005610 int n;
drh2238dcc2009-08-27 17:56:20 +00005611 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005612 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005613 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005614 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005615 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5616 if( pNew->pInode->pSem == SEM_FAILED ){
mistachkinfad30392016-02-13 23:43:46 +00005617 rc = SQLITE_NOMEM_BKPT;
drh8af6c222010-05-14 12:43:01 +00005618 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005619 }
chw97185482008-11-17 08:05:31 +00005620 }
drh7708e972008-11-29 00:56:52 +00005621 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005622 }
drh7708e972008-11-29 00:56:52 +00005623#endif
aswift5b1a2562008-08-22 00:22:35 +00005624
drh4bf66fd2015-02-19 02:43:02 +00005625 storeLastErrno(pNew, 0);
drh6c7d5c52008-11-21 20:32:33 +00005626#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005627 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005628 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005629 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005630 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005631 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005632 }
chw97185482008-11-17 08:05:31 +00005633#endif
danielk1977e339d652008-06-28 11:23:00 +00005634 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005635 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005636 }else{
drh7708e972008-11-29 00:56:52 +00005637 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005638 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005639 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005640 }
danielk1977e339d652008-06-28 11:23:00 +00005641 return rc;
drh054889e2005-11-30 03:20:31 +00005642}
drh9c06c952005-11-26 00:25:00 +00005643
danielk1977ad94b582007-08-20 06:44:22 +00005644/*
drh8b3cf822010-06-01 21:02:51 +00005645** Return the name of a directory in which to put temporary files.
5646** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005647*/
drh7234c6d2010-06-19 15:10:09 +00005648static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005649 static const char *azDirs[] = {
5650 0,
aswiftaebf4132008-11-21 00:10:35 +00005651 0,
danielk197717b90b52008-06-06 11:11:25 +00005652 "/var/tmp",
5653 "/usr/tmp",
5654 "/tmp",
drhb7e50ad2015-11-28 21:49:53 +00005655 "."
danielk197717b90b52008-06-06 11:11:25 +00005656 };
drh2aab11f2016-04-29 20:30:56 +00005657 unsigned int i = 0;
drh8b3cf822010-06-01 21:02:51 +00005658 struct stat buf;
drhb7e50ad2015-11-28 21:49:53 +00005659 const char *zDir = sqlite3_temp_directory;
drh8b3cf822010-06-01 21:02:51 +00005660
drhb7e50ad2015-11-28 21:49:53 +00005661 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
5662 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh2aab11f2016-04-29 20:30:56 +00005663 while(1){
5664 if( zDir!=0
5665 && osStat(zDir, &buf)==0
5666 && S_ISDIR(buf.st_mode)
5667 && osAccess(zDir, 03)==0
5668 ){
5669 return zDir;
5670 }
5671 if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
5672 zDir = azDirs[i++];
drh8b3cf822010-06-01 21:02:51 +00005673 }
drh7694e062016-04-21 23:37:24 +00005674 return 0;
drh8b3cf822010-06-01 21:02:51 +00005675}
5676
5677/*
5678** Create a temporary file name in zBuf. zBuf must be allocated
5679** by the calling process and must be big enough to hold at least
5680** pVfs->mxPathname bytes.
5681*/
5682static int unixGetTempname(int nBuf, char *zBuf){
drh8b3cf822010-06-01 21:02:51 +00005683 const char *zDir;
drhb7e50ad2015-11-28 21:49:53 +00005684 int iLimit = 0;
danielk197717b90b52008-06-06 11:11:25 +00005685
5686 /* It's odd to simulate an io-error here, but really this is just
5687 ** using the io-error infrastructure to test that SQLite handles this
5688 ** function failing.
5689 */
drh7694e062016-04-21 23:37:24 +00005690 zBuf[0] = 0;
danielk197717b90b52008-06-06 11:11:25 +00005691 SimulateIOError( return SQLITE_IOERR );
5692
drh7234c6d2010-06-19 15:10:09 +00005693 zDir = unixTempFileDir();
drh7694e062016-04-21 23:37:24 +00005694 if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
danielk197717b90b52008-06-06 11:11:25 +00005695 do{
drh970942e2015-11-25 23:13:14 +00005696 u64 r;
5697 sqlite3_randomness(sizeof(r), &r);
5698 assert( nBuf>2 );
5699 zBuf[nBuf-2] = 0;
5700 sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
5701 zDir, r, 0);
drhb7e50ad2015-11-28 21:49:53 +00005702 if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
drh99ab3b12011-03-02 15:09:07 +00005703 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005704 return SQLITE_OK;
5705}
5706
drhd2cb50b2009-01-09 21:41:17 +00005707#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005708/*
5709** Routine to transform a unixFile into a proxy-locking unixFile.
5710** Implementation in the proxy-lock division, but used by unixOpen()
5711** if SQLITE_PREFER_PROXY_LOCKING is defined.
5712*/
5713static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005714#endif
drhc66d5b62008-12-03 22:48:32 +00005715
dan08da86a2009-08-21 17:18:03 +00005716/*
5717** Search for an unused file descriptor that was opened on the database
5718** file (not a journal or master-journal file) identified by pathname
5719** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5720** argument to this function.
5721**
5722** Such a file descriptor may exist if a database connection was closed
5723** but the associated file descriptor could not be closed because some
5724** other file descriptor open on the same file is holding a file-lock.
5725** Refer to comments in the unixClose() function and the lengthy comment
5726** describing "Posix Advisory Locking" at the start of this file for
5727** further details. Also, ticket #4018.
5728**
5729** If a suitable file descriptor is found, then it is returned. If no
5730** such file descriptor is located, -1 is returned.
5731*/
dane946c392009-08-22 11:39:46 +00005732static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5733 UnixUnusedFd *pUnused = 0;
5734
5735 /* Do not search for an unused file descriptor on vxworks. Not because
5736 ** vxworks would not benefit from the change (it might, we're not sure),
5737 ** but because no way to test it is currently available. It is better
5738 ** not to risk breaking vxworks support for the sake of such an obscure
5739 ** feature. */
5740#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005741 struct stat sStat; /* Results of stat() call */
5742
drhc68886b2017-08-18 16:09:52 +00005743 unixEnterMutex();
5744
dan08da86a2009-08-21 17:18:03 +00005745 /* A stat() call may fail for various reasons. If this happens, it is
5746 ** almost certain that an open() call on the same path will also fail.
5747 ** For this reason, if an error occurs in the stat() call here, it is
5748 ** ignored and -1 is returned. The caller will try to open a new file
5749 ** descriptor on the same path, fail, and return an error to SQLite.
5750 **
5751 ** Even if a subsequent open() call does succeed, the consequences of
peter.d.reid60ec9142014-09-06 16:39:46 +00005752 ** not searching for a reusable file descriptor are not dire. */
drh095908e2018-08-13 20:46:18 +00005753 if( inodeList!=0 && 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005754 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005755
drh8af6c222010-05-14 12:43:01 +00005756 pInode = inodeList;
5757 while( pInode && (pInode->fileId.dev!=sStat.st_dev
drh25ef7f52016-12-05 20:06:45 +00005758 || pInode->fileId.ino!=(u64)sStat.st_ino) ){
drh8af6c222010-05-14 12:43:01 +00005759 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005760 }
drh8af6c222010-05-14 12:43:01 +00005761 if( pInode ){
dane946c392009-08-22 11:39:46 +00005762 UnixUnusedFd **pp;
drh095908e2018-08-13 20:46:18 +00005763 assert( sqlite3_mutex_notheld(pInode->pLockMutex) );
5764 sqlite3_mutex_enter(pInode->pLockMutex);
drh8af6c222010-05-14 12:43:01 +00005765 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005766 pUnused = *pp;
5767 if( pUnused ){
5768 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005769 }
drh095908e2018-08-13 20:46:18 +00005770 sqlite3_mutex_leave(pInode->pLockMutex);
dan08da86a2009-08-21 17:18:03 +00005771 }
dan08da86a2009-08-21 17:18:03 +00005772 }
drhc68886b2017-08-18 16:09:52 +00005773 unixLeaveMutex();
dane946c392009-08-22 11:39:46 +00005774#endif /* if !OS_VXWORKS */
5775 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005776}
danielk197717b90b52008-06-06 11:11:25 +00005777
5778/*
dan1bf4ca72016-08-11 18:05:47 +00005779** Find the mode, uid and gid of file zFile.
5780*/
5781static int getFileMode(
5782 const char *zFile, /* File name */
5783 mode_t *pMode, /* OUT: Permissions of zFile */
5784 uid_t *pUid, /* OUT: uid of zFile. */
5785 gid_t *pGid /* OUT: gid of zFile. */
5786){
5787 struct stat sStat; /* Output of stat() on database file */
5788 int rc = SQLITE_OK;
5789 if( 0==osStat(zFile, &sStat) ){
5790 *pMode = sStat.st_mode & 0777;
5791 *pUid = sStat.st_uid;
5792 *pGid = sStat.st_gid;
5793 }else{
5794 rc = SQLITE_IOERR_FSTAT;
5795 }
5796 return rc;
5797}
5798
5799/*
danddb0ac42010-07-14 14:48:58 +00005800** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005801** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005802** and a value suitable for passing as the third argument to open(2) is
5803** written to *pMode. If an IO error occurs, an SQLite error code is
5804** returned and the value of *pMode is not modified.
5805**
peter.d.reid60ec9142014-09-06 16:39:46 +00005806** In most cases, this routine sets *pMode to 0, which will become
drh8c815d12012-02-13 20:16:37 +00005807** an indication to robust_open() to create the file using
5808** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5809** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005810** this function queries the file-system for the permissions on the
5811** corresponding database file and sets *pMode to this value. Whenever
5812** possible, WAL and journal files are created using the same permissions
5813** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005814**
5815** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5816** original filename is unavailable. But 8_3_NAMES is only used for
5817** FAT filesystems and permissions do not matter there, so just use
5818** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005819*/
5820static int findCreateFileMode(
5821 const char *zPath, /* Path of file (possibly) being created */
5822 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005823 mode_t *pMode, /* OUT: Permissions to open file with */
5824 uid_t *pUid, /* OUT: uid to set on the file */
5825 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005826){
5827 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005828 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005829 *pUid = 0;
5830 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005831 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005832 char zDb[MAX_PATHNAME+1]; /* Database file path */
5833 int nDb; /* Number of valid bytes in zDb */
danddb0ac42010-07-14 14:48:58 +00005834
dana0c989d2010-11-05 18:07:37 +00005835 /* zPath is a path to a WAL or journal file. The following block derives
5836 ** the path to the associated database file from zPath. This block handles
5837 ** the following naming conventions:
5838 **
5839 ** "<path to db>-journal"
5840 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005841 ** "<path to db>-journalNN"
5842 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005843 **
drhd337c5b2011-10-20 18:23:35 +00005844 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005845 ** used by the test_multiplex.c module.
5846 */
5847 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005848 while( zPath[nDb]!='-' ){
dan629ec142017-09-14 20:41:17 +00005849 /* In normal operation, the journal file name will always contain
5850 ** a '-' character. However in 8+3 filename mode, or if a corrupt
5851 ** rollback journal specifies a master journal with a goofy name, then
5852 ** the '-' might be missing. */
drh90e5dda2015-12-03 20:42:28 +00005853 if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005854 nDb--;
5855 }
danddb0ac42010-07-14 14:48:58 +00005856 memcpy(zDb, zPath, nDb);
5857 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005858
dan1bf4ca72016-08-11 18:05:47 +00005859 rc = getFileMode(zDb, pMode, pUid, pGid);
danddb0ac42010-07-14 14:48:58 +00005860 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5861 *pMode = 0600;
dan1bf4ca72016-08-11 18:05:47 +00005862 }else if( flags & SQLITE_OPEN_URI ){
5863 /* If this is a main database file and the file was opened using a URI
5864 ** filename, check for the "modeof" parameter. If present, interpret
5865 ** its value as a filename and try to copy the mode, uid and gid from
5866 ** that file. */
5867 const char *z = sqlite3_uri_parameter(zPath, "modeof");
5868 if( z ){
5869 rc = getFileMode(z, pMode, pUid, pGid);
5870 }
danddb0ac42010-07-14 14:48:58 +00005871 }
5872 return rc;
5873}
5874
5875/*
danielk1977ad94b582007-08-20 06:44:22 +00005876** Open the file zPath.
5877**
danielk1977b4b47412007-08-17 15:53:36 +00005878** Previously, the SQLite OS layer used three functions in place of this
5879** one:
5880**
5881** sqlite3OsOpenReadWrite();
5882** sqlite3OsOpenReadOnly();
5883** sqlite3OsOpenExclusive();
5884**
5885** These calls correspond to the following combinations of flags:
5886**
5887** ReadWrite() -> (READWRITE | CREATE)
5888** ReadOnly() -> (READONLY)
5889** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5890**
5891** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5892** true, the file was configured to be automatically deleted when the
5893** file handle closed. To achieve the same effect using this new
5894** interface, add the DELETEONCLOSE flag to those specified above for
5895** OpenExclusive().
5896*/
5897static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005898 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5899 const char *zPath, /* Pathname of file to be opened */
5900 sqlite3_file *pFile, /* The file descriptor to be filled in */
5901 int flags, /* Input flags to control the opening */
5902 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005903){
dan08da86a2009-08-21 17:18:03 +00005904 unixFile *p = (unixFile *)pFile;
5905 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005906 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005907 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005908 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005909 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005910 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005911
5912 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5913 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5914 int isCreate = (flags & SQLITE_OPEN_CREATE);
5915 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5916 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005917#if SQLITE_ENABLE_LOCKING_STYLE
5918 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5919#endif
drh3d4435b2011-08-26 20:55:50 +00005920#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5921 struct statfs fsInfo;
5922#endif
danielk1977b4b47412007-08-17 15:53:36 +00005923
danielk1977fee2d252007-08-18 10:59:19 +00005924 /* If creating a master or main-file journal, this function will open
5925 ** a file-descriptor on the directory too. The first time unixSync()
5926 ** is called the directory file descriptor will be fsync()ed and close()d.
5927 */
drha803a2c2017-12-13 20:02:29 +00005928 int isNewJrnl = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005929 eType==SQLITE_OPEN_MASTER_JOURNAL
5930 || eType==SQLITE_OPEN_MAIN_JOURNAL
5931 || eType==SQLITE_OPEN_WAL
5932 ));
danielk1977fee2d252007-08-18 10:59:19 +00005933
danielk197717b90b52008-06-06 11:11:25 +00005934 /* If argument zPath is a NULL pointer, this function is required to open
5935 ** a temporary file. Use this buffer to store the file name in.
5936 */
drhc02a43a2012-01-10 23:18:38 +00005937 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005938 const char *zName = zPath;
5939
danielk1977fee2d252007-08-18 10:59:19 +00005940 /* Check the following statements are true:
5941 **
5942 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5943 ** (b) if CREATE is set, then READWRITE must also be set, and
5944 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005945 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005946 */
danielk1977b4b47412007-08-17 15:53:36 +00005947 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005948 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005949 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005950 assert(isDelete==0 || isCreate);
5951
danddb0ac42010-07-14 14:48:58 +00005952 /* The main DB, main journal, WAL file and master journal are never
5953 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005954 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5955 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5956 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005957 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005958
danielk1977fee2d252007-08-18 10:59:19 +00005959 /* Assert that the upper layer has set one of the "file-type" flags. */
5960 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5961 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5962 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005963 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005964 );
5965
drhb00d8622014-01-01 15:18:36 +00005966 /* Detect a pid change and reset the PRNG. There is a race condition
5967 ** here such that two or more threads all trying to open databases at
5968 ** the same instant might all reset the PRNG. But multiple resets
5969 ** are harmless.
5970 */
drh5ac93652015-03-21 20:59:43 +00005971 if( randomnessPid!=osGetpid(0) ){
5972 randomnessPid = osGetpid(0);
drhb00d8622014-01-01 15:18:36 +00005973 sqlite3_randomness(0,0);
5974 }
dan08da86a2009-08-21 17:18:03 +00005975 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005976
dan08da86a2009-08-21 17:18:03 +00005977 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005978 UnixUnusedFd *pUnused;
5979 pUnused = findReusableFd(zName, flags);
5980 if( pUnused ){
5981 fd = pUnused->fd;
5982 }else{
drhf3cdcdc2015-04-29 16:50:28 +00005983 pUnused = sqlite3_malloc64(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005984 if( !pUnused ){
mistachkinfad30392016-02-13 23:43:46 +00005985 return SQLITE_NOMEM_BKPT;
dane946c392009-08-22 11:39:46 +00005986 }
5987 }
drhc68886b2017-08-18 16:09:52 +00005988 p->pPreallocatedUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005989
5990 /* Database filenames are double-zero terminated if they are not
5991 ** URIs with parameters. Hence, they can always be passed into
5992 ** sqlite3_uri_parameter(). */
5993 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5994
dan08da86a2009-08-21 17:18:03 +00005995 }else if( !zName ){
5996 /* If zName is NULL, the upper layer is requesting a temp file. */
drha803a2c2017-12-13 20:02:29 +00005997 assert(isDelete && !isNewJrnl);
drhb7e50ad2015-11-28 21:49:53 +00005998 rc = unixGetTempname(pVfs->mxPathname, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005999 if( rc!=SQLITE_OK ){
6000 return rc;
6001 }
6002 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00006003
6004 /* Generated temporary filenames are always double-zero terminated
6005 ** for use by sqlite3_uri_parameter(). */
6006 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00006007 }
6008
dan08da86a2009-08-21 17:18:03 +00006009 /* Determine the value of the flags parameter passed to POSIX function
6010 ** open(). These must be calculated even if open() is not called, as
6011 ** they may be stored as part of the file handle and used by the
6012 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00006013 if( isReadonly ) openFlags |= O_RDONLY;
6014 if( isReadWrite ) openFlags |= O_RDWR;
6015 if( isCreate ) openFlags |= O_CREAT;
6016 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
6017 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00006018
danielk1977b4b47412007-08-17 15:53:36 +00006019 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00006020 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00006021 uid_t uid; /* Userid for the file */
6022 gid_t gid; /* Groupid for the file */
6023 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00006024 if( rc!=SQLITE_OK ){
drhc68886b2017-08-18 16:09:52 +00006025 assert( !p->pPreallocatedUnused );
drh8ab58662010-07-15 18:38:39 +00006026 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00006027 return rc;
6028 }
drhad4f1e52011-03-04 15:43:57 +00006029 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00006030 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
drh5a2d9702015-11-26 02:21:05 +00006031 assert( !isExclusive || (openFlags & O_CREAT)!=0 );
dana688ca52018-01-10 11:56:03 +00006032 if( fd<0 ){
6033 if( isNewJrnl && errno==EACCES && osAccess(zName, F_OK) ){
6034 /* If unable to create a journal because the directory is not
6035 ** writable, change the error code to indicate that. */
6036 rc = SQLITE_READONLY_DIRECTORY;
6037 }else if( errno!=EISDIR && isReadWrite ){
6038 /* Failed to open the file for read/write access. Try read-only. */
6039 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
6040 openFlags &= ~(O_RDWR|O_CREAT);
6041 flags |= SQLITE_OPEN_READONLY;
6042 openFlags |= O_RDONLY;
6043 isReadonly = 1;
6044 fd = robust_open(zName, openFlags, openMode);
6045 }
dan08da86a2009-08-21 17:18:03 +00006046 }
6047 if( fd<0 ){
dana688ca52018-01-10 11:56:03 +00006048 int rc2 = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
6049 if( rc==SQLITE_OK ) rc = rc2;
dane946c392009-08-22 11:39:46 +00006050 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00006051 }
drhac7c3ac2012-02-11 19:23:48 +00006052
6053 /* If this process is running as root and if creating a new rollback
6054 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00006055 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00006056 */
6057 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drh6226ca22015-11-24 15:06:28 +00006058 robustFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00006059 }
danielk1977b4b47412007-08-17 15:53:36 +00006060 }
dan08da86a2009-08-21 17:18:03 +00006061 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00006062 if( pOutFlags ){
6063 *pOutFlags = flags;
6064 }
6065
drhc68886b2017-08-18 16:09:52 +00006066 if( p->pPreallocatedUnused ){
6067 p->pPreallocatedUnused->fd = fd;
6068 p->pPreallocatedUnused->flags = flags;
dane946c392009-08-22 11:39:46 +00006069 }
6070
danielk1977b4b47412007-08-17 15:53:36 +00006071 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00006072#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006073 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00006074#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
6075 zPath = sqlite3_mprintf("%s", zName);
6076 if( zPath==0 ){
6077 robust_close(p, fd, __LINE__);
mistachkinfad30392016-02-13 23:43:46 +00006078 return SQLITE_NOMEM_BKPT;
drh0bdbc902014-06-16 18:35:06 +00006079 }
chw97185482008-11-17 08:05:31 +00006080#else
drh036ac7f2011-08-08 23:18:05 +00006081 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00006082#endif
danielk1977b4b47412007-08-17 15:53:36 +00006083 }
drh41022642008-11-21 00:24:42 +00006084#if SQLITE_ENABLE_LOCKING_STYLE
6085 else{
dan08da86a2009-08-21 17:18:03 +00006086 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00006087 }
6088#endif
drh7ed97b92010-01-20 13:07:21 +00006089
6090#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00006091 if( fstatfs(fd, &fsInfo) == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00006092 storeLastErrno(p, errno);
drh0e9365c2011-03-02 02:08:13 +00006093 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006094 return SQLITE_IOERR_ACCESS;
6095 }
6096 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
6097 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
6098 }
drh4bf66fd2015-02-19 02:43:02 +00006099 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
6100 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
6101 }
drh7ed97b92010-01-20 13:07:21 +00006102#endif
drhc02a43a2012-01-10 23:18:38 +00006103
6104 /* Set up appropriate ctrlFlags */
6105 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
6106 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
drh86151e82015-12-08 14:37:16 +00006107 noLock = eType!=SQLITE_OPEN_MAIN_DB;
drhc02a43a2012-01-10 23:18:38 +00006108 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
drha803a2c2017-12-13 20:02:29 +00006109 if( isNewJrnl ) ctrlFlags |= UNIXFILE_DIRSYNC;
drhc02a43a2012-01-10 23:18:38 +00006110 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
6111
drh7ed97b92010-01-20 13:07:21 +00006112#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00006113#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00006114 isAutoProxy = 1;
6115#endif
6116 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00006117 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
6118 int useProxy = 0;
6119
dan08da86a2009-08-21 17:18:03 +00006120 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
6121 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00006122 if( envforce!=NULL ){
6123 useProxy = atoi(envforce)>0;
6124 }else{
aswiftaebf4132008-11-21 00:10:35 +00006125 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
6126 }
6127 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00006128 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00006129 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006130 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00006131 if( rc!=SQLITE_OK ){
6132 /* Use unixClose to clean up the resources added in fillInUnixFile
6133 ** and clear all the structure's references. Specifically,
6134 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
6135 */
6136 unixClose(pFile);
6137 return rc;
6138 }
aswiftaebf4132008-11-21 00:10:35 +00006139 }
dane946c392009-08-22 11:39:46 +00006140 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00006141 }
6142 }
6143#endif
6144
dan3ed0f1c2017-09-14 21:12:07 +00006145 assert( zPath==0 || zPath[0]=='/'
6146 || eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL
6147 );
drhc02a43a2012-01-10 23:18:38 +00006148 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
6149
dane946c392009-08-22 11:39:46 +00006150open_finished:
6151 if( rc!=SQLITE_OK ){
drhc68886b2017-08-18 16:09:52 +00006152 sqlite3_free(p->pPreallocatedUnused);
dane946c392009-08-22 11:39:46 +00006153 }
6154 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00006155}
6156
dane946c392009-08-22 11:39:46 +00006157
danielk1977b4b47412007-08-17 15:53:36 +00006158/*
danielk1977fee2d252007-08-18 10:59:19 +00006159** Delete the file at zPath. If the dirSync argument is true, fsync()
6160** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00006161*/
drh6b9d6dd2008-12-03 19:34:47 +00006162static int unixDelete(
6163 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
6164 const char *zPath, /* Name of file to be deleted */
6165 int dirSync /* If true, fsync() directory after deleting file */
6166){
danielk1977fee2d252007-08-18 10:59:19 +00006167 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00006168 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006169 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00006170 if( osUnlink(zPath)==(-1) ){
drhbd945542014-08-13 11:39:42 +00006171 if( errno==ENOENT
6172#if OS_VXWORKS
drh19541f32014-09-01 13:37:55 +00006173 || osAccess(zPath,0)!=0
drhbd945542014-08-13 11:39:42 +00006174#endif
6175 ){
dan9fc5b4a2012-11-09 20:17:26 +00006176 rc = SQLITE_IOERR_DELETE_NOENT;
6177 }else{
drhb4308162012-11-09 21:40:02 +00006178 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00006179 }
drhb4308162012-11-09 21:40:02 +00006180 return rc;
drh5d4feff2010-07-14 01:45:22 +00006181 }
danielk1977d39fa702008-10-16 13:27:40 +00006182#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00006183 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00006184 int fd;
drh90315a22011-08-10 01:52:12 +00006185 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00006186 if( rc==SQLITE_OK ){
drh6d258992016-02-04 09:48:12 +00006187 if( full_fsync(fd,0,0) ){
dane18d4952011-02-21 11:46:24 +00006188 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00006189 }
drh0e9365c2011-03-02 02:08:13 +00006190 robust_close(0, fd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00006191 }else{
6192 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00006193 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00006194 }
6195 }
danielk1977d138dd82008-10-15 16:02:48 +00006196#endif
danielk1977fee2d252007-08-18 10:59:19 +00006197 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00006198}
6199
danielk197790949c22007-08-17 16:50:38 +00006200/*
mistachkin48864df2013-03-21 21:20:32 +00006201** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00006202** test performed depends on the value of flags:
6203**
6204** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
6205** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
6206** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
6207**
6208** Otherwise return 0.
6209*/
danielk1977861f7452008-06-05 11:39:11 +00006210static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00006211 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
6212 const char *zPath, /* Path of the file to examine */
6213 int flags, /* What do we want to learn about the zPath file? */
6214 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00006215){
danielk1977397d65f2008-11-19 11:35:39 +00006216 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00006217 SimulateIOError( return SQLITE_IOERR_ACCESS; );
drhd260b5b2015-11-25 18:03:33 +00006218 assert( pResOut!=0 );
danielk1977b4b47412007-08-17 15:53:36 +00006219
drhd260b5b2015-11-25 18:03:33 +00006220 /* The spec says there are three possible values for flags. But only
6221 ** two of them are actually used */
6222 assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
6223
6224 if( flags==SQLITE_ACCESS_EXISTS ){
dan83acd422010-06-18 11:10:06 +00006225 struct stat buf;
drhd260b5b2015-11-25 18:03:33 +00006226 *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
6227 }else{
6228 *pResOut = osAccess(zPath, W_OK|R_OK)==0;
dan83acd422010-06-18 11:10:06 +00006229 }
danielk1977861f7452008-06-05 11:39:11 +00006230 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006231}
6232
danielk1977b4b47412007-08-17 15:53:36 +00006233/*
danielk1977b4b47412007-08-17 15:53:36 +00006234**
danielk1977b4b47412007-08-17 15:53:36 +00006235*/
dane88ec182016-01-25 17:04:48 +00006236static int mkFullPathname(
dancaf6b152016-01-25 18:05:49 +00006237 const char *zPath, /* Input path */
6238 char *zOut, /* Output buffer */
dane88ec182016-01-25 17:04:48 +00006239 int nOut /* Allocated size of buffer zOut */
danielk1977adfb9b02007-09-17 07:02:56 +00006240){
dancaf6b152016-01-25 18:05:49 +00006241 int nPath = sqlite3Strlen30(zPath);
6242 int iOff = 0;
6243 if( zPath[0]!='/' ){
6244 if( osGetcwd(zOut, nOut-2)==0 ){
dane18d4952011-02-21 11:46:24 +00006245 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006246 }
dancaf6b152016-01-25 18:05:49 +00006247 iOff = sqlite3Strlen30(zOut);
6248 zOut[iOff++] = '/';
danielk1977b4b47412007-08-17 15:53:36 +00006249 }
dan23496702016-01-26 13:56:42 +00006250 if( (iOff+nPath+1)>nOut ){
6251 /* SQLite assumes that xFullPathname() nul-terminates the output buffer
6252 ** even if it returns an error. */
6253 zOut[iOff] = '\0';
6254 return SQLITE_CANTOPEN_BKPT;
6255 }
dancaf6b152016-01-25 18:05:49 +00006256 sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006257 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006258}
6259
dane88ec182016-01-25 17:04:48 +00006260/*
6261** Turn a relative pathname into a full pathname. The relative path
6262** is stored as a nul-terminated string in the buffer pointed to by
6263** zPath.
6264**
6265** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
6266** (in this case, MAX_PATHNAME bytes). The full-path is written to
6267** this buffer before returning.
6268*/
6269static int unixFullPathname(
6270 sqlite3_vfs *pVfs, /* Pointer to vfs object */
6271 const char *zPath, /* Possibly relative input path */
6272 int nOut, /* Size of output buffer in bytes */
6273 char *zOut /* Output buffer */
6274){
danaf1b36b2016-01-25 18:43:05 +00006275#if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
dancaf6b152016-01-25 18:05:49 +00006276 return mkFullPathname(zPath, zOut, nOut);
dane88ec182016-01-25 17:04:48 +00006277#else
6278 int rc = SQLITE_OK;
6279 int nByte;
dancaf6b152016-01-25 18:05:49 +00006280 int nLink = 1; /* Number of symbolic links followed so far */
dane88ec182016-01-25 17:04:48 +00006281 const char *zIn = zPath; /* Input path for each iteration of loop */
6282 char *zDel = 0;
6283
6284 assert( pVfs->mxPathname==MAX_PATHNAME );
6285 UNUSED_PARAMETER(pVfs);
6286
6287 /* It's odd to simulate an io-error here, but really this is just
6288 ** using the io-error infrastructure to test that SQLite handles this
6289 ** function failing. This function could fail if, for example, the
6290 ** current working directory has been unlinked.
6291 */
6292 SimulateIOError( return SQLITE_ERROR );
6293
6294 do {
6295
dancaf6b152016-01-25 18:05:49 +00006296 /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
6297 ** link, or false otherwise. */
6298 int bLink = 0;
6299 struct stat buf;
6300 if( osLstat(zIn, &buf)!=0 ){
6301 if( errno!=ENOENT ){
danaf1b36b2016-01-25 18:43:05 +00006302 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
dane88ec182016-01-25 17:04:48 +00006303 }
dane88ec182016-01-25 17:04:48 +00006304 }else{
dancaf6b152016-01-25 18:05:49 +00006305 bLink = S_ISLNK(buf.st_mode);
6306 }
6307
6308 if( bLink ){
dane88ec182016-01-25 17:04:48 +00006309 if( zDel==0 ){
6310 zDel = sqlite3_malloc(nOut);
mistachkinfad30392016-02-13 23:43:46 +00006311 if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
dancaf6b152016-01-25 18:05:49 +00006312 }else if( ++nLink>SQLITE_MAX_SYMLINKS ){
6313 rc = SQLITE_CANTOPEN_BKPT;
dane88ec182016-01-25 17:04:48 +00006314 }
dancaf6b152016-01-25 18:05:49 +00006315
6316 if( rc==SQLITE_OK ){
6317 nByte = osReadlink(zIn, zDel, nOut-1);
6318 if( nByte<0 ){
6319 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
dan23496702016-01-26 13:56:42 +00006320 }else{
6321 if( zDel[0]!='/' ){
6322 int n;
6323 for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
6324 if( nByte+n+1>nOut ){
6325 rc = SQLITE_CANTOPEN_BKPT;
6326 }else{
6327 memmove(&zDel[n], zDel, nByte+1);
6328 memcpy(zDel, zIn, n);
6329 nByte += n;
6330 }
dancaf6b152016-01-25 18:05:49 +00006331 }
6332 zDel[nByte] = '\0';
6333 }
6334 }
6335
6336 zIn = zDel;
dane88ec182016-01-25 17:04:48 +00006337 }
6338
dan23496702016-01-26 13:56:42 +00006339 assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
6340 if( rc==SQLITE_OK && zIn!=zOut ){
dancaf6b152016-01-25 18:05:49 +00006341 rc = mkFullPathname(zIn, zOut, nOut);
dane88ec182016-01-25 17:04:48 +00006342 }
dancaf6b152016-01-25 18:05:49 +00006343 if( bLink==0 ) break;
6344 zIn = zOut;
6345 }while( rc==SQLITE_OK );
dane88ec182016-01-25 17:04:48 +00006346
6347 sqlite3_free(zDel);
6348 return rc;
danaf1b36b2016-01-25 18:43:05 +00006349#endif /* HAVE_READLINK && HAVE_LSTAT */
dane88ec182016-01-25 17:04:48 +00006350}
6351
drh0ccebe72005-06-07 22:22:50 +00006352
drh761df872006-12-21 01:29:22 +00006353#ifndef SQLITE_OMIT_LOAD_EXTENSION
6354/*
6355** Interfaces for opening a shared library, finding entry points
6356** within the shared library, and closing the shared library.
6357*/
6358#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00006359static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6360 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00006361 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6362}
danielk197795c8a542007-09-01 06:51:27 +00006363
6364/*
6365** SQLite calls this function immediately after a call to unixDlSym() or
6366** unixDlOpen() fails (returns a null pointer). If a more detailed error
6367** message is available, it is written to zBufOut. If no error message
6368** is available, zBufOut is left unmodified and SQLite uses a default
6369** error message.
6370*/
danielk1977397d65f2008-11-19 11:35:39 +00006371static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006372 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006373 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006374 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006375 zErr = dlerror();
6376 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006377 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006378 }
drh6c7d5c52008-11-21 20:32:33 +00006379 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006380}
drh1875f7a2008-12-08 18:19:17 +00006381static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6382 /*
6383 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6384 ** cast into a pointer to a function. And yet the library dlsym() routine
6385 ** returns a void* which is really a pointer to a function. So how do we
6386 ** use dlsym() with -pedantic-errors?
6387 **
6388 ** Variable x below is defined to be a pointer to a function taking
6389 ** parameters void* and const char* and returning a pointer to a function.
6390 ** We initialize x by assigning it a pointer to the dlsym() function.
6391 ** (That assignment requires a cast.) Then we call the function that
6392 ** x points to.
6393 **
6394 ** This work-around is unlikely to work correctly on any system where
6395 ** you really cannot cast a function pointer into void*. But then, on the
6396 ** other hand, dlsym() will not work on such a system either, so we have
6397 ** not really lost anything.
6398 */
6399 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006400 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006401 x = (void(*(*)(void*,const char*))(void))dlsym;
6402 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006403}
danielk1977397d65f2008-11-19 11:35:39 +00006404static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6405 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006406 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006407}
danielk1977b4b47412007-08-17 15:53:36 +00006408#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6409 #define unixDlOpen 0
6410 #define unixDlError 0
6411 #define unixDlSym 0
6412 #define unixDlClose 0
6413#endif
6414
6415/*
danielk197790949c22007-08-17 16:50:38 +00006416** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006417*/
danielk1977397d65f2008-11-19 11:35:39 +00006418static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6419 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006420 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006421
drhbbd42a62004-05-22 17:41:58 +00006422 /* We have to initialize zBuf to prevent valgrind from reporting
6423 ** errors. The reports issued by valgrind are incorrect - we would
6424 ** prefer that the randomness be increased by making use of the
6425 ** uninitialized space in zBuf - but valgrind errors tend to worry
6426 ** some users. Rather than argue, it seems easier just to initialize
6427 ** the whole array and silence valgrind, even if that means less randomness
6428 ** in the random seed.
6429 **
6430 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006431 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006432 ** tests repeatable.
6433 */
danielk1977b4b47412007-08-17 15:53:36 +00006434 memset(zBuf, 0, nBuf);
drh5ac93652015-03-21 20:59:43 +00006435 randomnessPid = osGetpid(0);
drh6a412b82015-04-30 12:31:49 +00006436#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
drhbbd42a62004-05-22 17:41:58 +00006437 {
drhb00d8622014-01-01 15:18:36 +00006438 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006439 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006440 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006441 time_t t;
6442 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006443 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006444 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6445 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6446 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006447 }else{
drhc18b4042012-02-10 03:10:27 +00006448 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006449 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006450 }
drhbbd42a62004-05-22 17:41:58 +00006451 }
6452#endif
drh72cbd072008-10-14 17:58:38 +00006453 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006454}
6455
danielk1977b4b47412007-08-17 15:53:36 +00006456
drhbbd42a62004-05-22 17:41:58 +00006457/*
6458** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006459** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006460** The return value is the number of microseconds of sleep actually
6461** requested from the underlying operating system, a number which
6462** might be greater than or equal to the argument, but not less
6463** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006464*/
danielk1977397d65f2008-11-19 11:35:39 +00006465static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006466#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006467 struct timespec sp;
6468
6469 sp.tv_sec = microseconds / 1000000;
6470 sp.tv_nsec = (microseconds % 1000000) * 1000;
6471 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006472 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006473 return microseconds;
6474#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006475 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006476 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006477 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006478#else
danielk1977b4b47412007-08-17 15:53:36 +00006479 int seconds = (microseconds+999999)/1000000;
6480 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006481 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006482 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006483#endif
drh88f474a2006-01-02 20:00:12 +00006484}
6485
6486/*
drh6b9d6dd2008-12-03 19:34:47 +00006487** The following variable, if set to a non-zero value, is interpreted as
6488** the number of seconds since 1970 and is used to set the result of
6489** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006490*/
6491#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006492int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006493#endif
6494
6495/*
drhb7e8ea22010-05-03 14:32:30 +00006496** Find the current time (in Universal Coordinated Time). Write into *piNow
6497** the current time and date as a Julian Day number times 86_400_000. In
6498** other words, write into *piNow the number of milliseconds since the Julian
6499** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6500** proleptic Gregorian calendar.
6501**
drh31702252011-10-12 23:13:43 +00006502** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6503** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006504*/
6505static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6506 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006507 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006508#if defined(NO_GETTOD)
6509 time_t t;
6510 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006511 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006512#elif OS_VXWORKS
6513 struct timespec sNow;
6514 clock_gettime(CLOCK_REALTIME, &sNow);
6515 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6516#else
6517 struct timeval sNow;
drh970942e2015-11-25 23:13:14 +00006518 (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
6519 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
drhb7e8ea22010-05-03 14:32:30 +00006520#endif
6521
6522#ifdef SQLITE_TEST
6523 if( sqlite3_current_time ){
6524 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6525 }
6526#endif
6527 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006528 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006529}
6530
drhc3dfa5e2016-01-22 19:44:03 +00006531#ifndef SQLITE_OMIT_DEPRECATED
drhb7e8ea22010-05-03 14:32:30 +00006532/*
drhbbd42a62004-05-22 17:41:58 +00006533** Find the current time (in Universal Coordinated Time). Write the
6534** current time and date as a Julian Day number into *prNow and
6535** return 0. Return 1 if the time and date cannot be found.
6536*/
danielk1977397d65f2008-11-19 11:35:39 +00006537static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006538 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006539 int rc;
drhff828942010-06-26 21:34:06 +00006540 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006541 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006542 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006543 return rc;
drhbbd42a62004-05-22 17:41:58 +00006544}
drh5337dac2015-11-25 15:15:03 +00006545#else
6546# define unixCurrentTime 0
6547#endif
danielk1977b4b47412007-08-17 15:53:36 +00006548
drh6b9d6dd2008-12-03 19:34:47 +00006549/*
drh1b9f2142016-03-17 16:01:23 +00006550** The xGetLastError() method is designed to return a better
6551** low-level error message when operating-system problems come up
6552** during SQLite operation. Only the integer return code is currently
6553** used.
drh6b9d6dd2008-12-03 19:34:47 +00006554*/
danielk1977397d65f2008-11-19 11:35:39 +00006555static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6556 UNUSED_PARAMETER(NotUsed);
6557 UNUSED_PARAMETER(NotUsed2);
6558 UNUSED_PARAMETER(NotUsed3);
drh1b9f2142016-03-17 16:01:23 +00006559 return errno;
danielk1977bcb97fe2008-06-06 15:49:29 +00006560}
6561
drhf2424c52010-04-26 00:04:55 +00006562
6563/*
drh734c9862008-11-28 15:37:20 +00006564************************ End of sqlite3_vfs methods ***************************
6565******************************************************************************/
6566
drh715ff302008-12-03 22:32:44 +00006567/******************************************************************************
6568************************** Begin Proxy Locking ********************************
6569**
6570** Proxy locking is a "uber-locking-method" in this sense: It uses the
6571** other locking methods on secondary lock files. Proxy locking is a
6572** meta-layer over top of the primitive locking implemented above. For
6573** this reason, the division that implements of proxy locking is deferred
6574** until late in the file (here) after all of the other I/O methods have
6575** been defined - so that the primitive locking methods are available
6576** as services to help with the implementation of proxy locking.
6577**
6578****
6579**
6580** The default locking schemes in SQLite use byte-range locks on the
6581** database file to coordinate safe, concurrent access by multiple readers
6582** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6583** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6584** as POSIX read & write locks over fixed set of locations (via fsctl),
6585** on AFP and SMB only exclusive byte-range locks are available via fsctl
6586** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6587** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6588** address in the shared range is taken for a SHARED lock, the entire
6589** shared range is taken for an EXCLUSIVE lock):
6590**
drhf2f105d2012-08-20 15:53:54 +00006591** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006592** RESERVED_BYTE 0x40000001
6593** SHARED_RANGE 0x40000002 -> 0x40000200
6594**
6595** This works well on the local file system, but shows a nearly 100x
6596** slowdown in read performance on AFP because the AFP client disables
6597** the read cache when byte-range locks are present. Enabling the read
6598** cache exposes a cache coherency problem that is present on all OS X
6599** supported network file systems. NFS and AFP both observe the
6600** close-to-open semantics for ensuring cache coherency
6601** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6602** address the requirements for concurrent database access by multiple
6603** readers and writers
6604** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6605**
6606** To address the performance and cache coherency issues, proxy file locking
6607** changes the way database access is controlled by limiting access to a
6608** single host at a time and moving file locks off of the database file
6609** and onto a proxy file on the local file system.
6610**
6611**
6612** Using proxy locks
6613** -----------------
6614**
6615** C APIs
6616**
drh4bf66fd2015-02-19 02:43:02 +00006617** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
drh715ff302008-12-03 22:32:44 +00006618** <proxy_path> | ":auto:");
drh4bf66fd2015-02-19 02:43:02 +00006619** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6620** &<proxy_path>);
drh715ff302008-12-03 22:32:44 +00006621**
6622**
6623** SQL pragmas
6624**
6625** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6626** PRAGMA [database.]lock_proxy_file
6627**
6628** Specifying ":auto:" means that if there is a conch file with a matching
6629** host ID in it, the proxy path in the conch file will be used, otherwise
6630** a proxy path based on the user's temp dir
6631** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6632** actual proxy file name is generated from the name and path of the
6633** database file. For example:
6634**
6635** For database path "/Users/me/foo.db"
6636** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6637**
6638** Once a lock proxy is configured for a database connection, it can not
6639** be removed, however it may be switched to a different proxy path via
6640** the above APIs (assuming the conch file is not being held by another
6641** connection or process).
6642**
6643**
6644** How proxy locking works
6645** -----------------------
6646**
6647** Proxy file locking relies primarily on two new supporting files:
6648**
6649** * conch file to limit access to the database file to a single host
6650** at a time
6651**
6652** * proxy file to act as a proxy for the advisory locks normally
6653** taken on the database
6654**
6655** The conch file - to use a proxy file, sqlite must first "hold the conch"
6656** by taking an sqlite-style shared lock on the conch file, reading the
6657** contents and comparing the host's unique host ID (see below) and lock
6658** proxy path against the values stored in the conch. The conch file is
6659** stored in the same directory as the database file and the file name
6660** is patterned after the database file name as ".<databasename>-conch".
peter.d.reid60ec9142014-09-06 16:39:46 +00006661** If the conch file does not exist, or its contents do not match the
drh715ff302008-12-03 22:32:44 +00006662** host ID and/or proxy path, then the lock is escalated to an exclusive
6663** lock and the conch file contents is updated with the host ID and proxy
6664** path and the lock is downgraded to a shared lock again. If the conch
6665** is held by another process (with a shared lock), the exclusive lock
6666** will fail and SQLITE_BUSY is returned.
6667**
6668** The proxy file - a single-byte file used for all advisory file locks
6669** normally taken on the database file. This allows for safe sharing
6670** of the database file for multiple readers and writers on the same
6671** host (the conch ensures that they all use the same local lock file).
6672**
drh715ff302008-12-03 22:32:44 +00006673** Requesting the lock proxy does not immediately take the conch, it is
6674** only taken when the first request to lock database file is made.
6675** This matches the semantics of the traditional locking behavior, where
6676** opening a connection to a database file does not take a lock on it.
6677** The shared lock and an open file descriptor are maintained until
6678** the connection to the database is closed.
6679**
6680** The proxy file and the lock file are never deleted so they only need
6681** to be created the first time they are used.
6682**
6683** Configuration options
6684** ---------------------
6685**
6686** SQLITE_PREFER_PROXY_LOCKING
6687**
6688** Database files accessed on non-local file systems are
6689** automatically configured for proxy locking, lock files are
6690** named automatically using the same logic as
6691** PRAGMA lock_proxy_file=":auto:"
6692**
6693** SQLITE_PROXY_DEBUG
6694**
6695** Enables the logging of error messages during host id file
6696** retrieval and creation
6697**
drh715ff302008-12-03 22:32:44 +00006698** LOCKPROXYDIR
6699**
6700** Overrides the default directory used for lock proxy files that
6701** are named automatically via the ":auto:" setting
6702**
6703** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6704**
6705** Permissions to use when creating a directory for storing the
6706** lock proxy files, only used when LOCKPROXYDIR is not set.
6707**
6708**
6709** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6710** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6711** force proxy locking to be used for every database file opened, and 0
6712** will force automatic proxy locking to be disabled for all database
drh4bf66fd2015-02-19 02:43:02 +00006713** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
drh715ff302008-12-03 22:32:44 +00006714** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6715*/
6716
6717/*
6718** Proxy locking is only available on MacOSX
6719*/
drhd2cb50b2009-01-09 21:41:17 +00006720#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006721
drh715ff302008-12-03 22:32:44 +00006722/*
6723** The proxyLockingContext has the path and file structures for the remote
6724** and local proxy files in it
6725*/
6726typedef struct proxyLockingContext proxyLockingContext;
6727struct proxyLockingContext {
6728 unixFile *conchFile; /* Open conch file */
6729 char *conchFilePath; /* Name of the conch file */
6730 unixFile *lockProxy; /* Open proxy lock file */
6731 char *lockProxyPath; /* Name of the proxy lock file */
6732 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006733 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh4bf66fd2015-02-19 02:43:02 +00006734 int nFails; /* Number of conch taking failures */
drh715ff302008-12-03 22:32:44 +00006735 void *oldLockingContext; /* Original lockingcontext to restore on close */
6736 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6737};
6738
drh7ed97b92010-01-20 13:07:21 +00006739/*
6740** The proxy lock file path for the database at dbPath is written into lPath,
6741** which must point to valid, writable memory large enough for a maxLen length
6742** file path.
drh715ff302008-12-03 22:32:44 +00006743*/
drh715ff302008-12-03 22:32:44 +00006744static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6745 int len;
6746 int dbLen;
6747 int i;
6748
6749#ifdef LOCKPROXYDIR
6750 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6751#else
6752# ifdef _CS_DARWIN_USER_TEMP_DIR
6753 {
drh7ed97b92010-01-20 13:07:21 +00006754 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006755 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006756 lPath, errno, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006757 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006758 }
drh7ed97b92010-01-20 13:07:21 +00006759 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006760 }
6761# else
6762 len = strlcpy(lPath, "/tmp/", maxLen);
6763# endif
6764#endif
6765
6766 if( lPath[len-1]!='/' ){
6767 len = strlcat(lPath, "/", maxLen);
6768 }
6769
6770 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006771 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006772 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006773 char c = dbPath[i];
6774 lPath[i+len] = (c=='/')?'_':c;
6775 }
6776 lPath[i+len]='\0';
6777 strlcat(lPath, ":auto:", maxLen);
drh5ac93652015-03-21 20:59:43 +00006778 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006779 return SQLITE_OK;
6780}
6781
drh7ed97b92010-01-20 13:07:21 +00006782/*
6783 ** Creates the lock file and any missing directories in lockPath
6784 */
6785static int proxyCreateLockPath(const char *lockPath){
6786 int i, len;
6787 char buf[MAXPATHLEN];
6788 int start = 0;
6789
6790 assert(lockPath!=NULL);
6791 /* try to create all the intermediate directories */
6792 len = (int)strlen(lockPath);
6793 buf[0] = lockPath[0];
6794 for( i=1; i<len; i++ ){
6795 if( lockPath[i] == '/' && (i - start > 0) ){
6796 /* only mkdir if leaf dir != "." or "/" or ".." */
6797 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6798 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6799 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006800 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006801 int err=errno;
6802 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006803 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006804 "'%s' proxy lock path=%s pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006805 buf, strerror(err), lockPath, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006806 return err;
6807 }
6808 }
6809 }
6810 start=i+1;
6811 }
6812 buf[i] = lockPath[i];
6813 }
drh62aaa6c2015-11-21 17:27:42 +00006814 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006815 return 0;
6816}
6817
drh715ff302008-12-03 22:32:44 +00006818/*
6819** Create a new VFS file descriptor (stored in memory obtained from
6820** sqlite3_malloc) and open the file named "path" in the file descriptor.
6821**
6822** The caller is responsible not only for closing the file descriptor
6823** but also for freeing the memory associated with the file descriptor.
6824*/
drh7ed97b92010-01-20 13:07:21 +00006825static int proxyCreateUnixFile(
6826 const char *path, /* path for the new unixFile */
6827 unixFile **ppFile, /* unixFile created and returned by ref */
6828 int islockfile /* if non zero missing dirs will be created */
6829) {
6830 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006831 unixFile *pNew;
6832 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006833 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006834 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006835 int terrno = 0;
6836 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006837
drh7ed97b92010-01-20 13:07:21 +00006838 /* 1. first try to open/create the file
6839 ** 2. if that fails, and this is a lock file (not-conch), try creating
6840 ** the parent directories and then try again.
6841 ** 3. if that fails, try to open the file read-only
6842 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6843 */
6844 pUnused = findReusableFd(path, openFlags);
6845 if( pUnused ){
6846 fd = pUnused->fd;
6847 }else{
drhf3cdcdc2015-04-29 16:50:28 +00006848 pUnused = sqlite3_malloc64(sizeof(*pUnused));
drh7ed97b92010-01-20 13:07:21 +00006849 if( !pUnused ){
mistachkinfad30392016-02-13 23:43:46 +00006850 return SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006851 }
6852 }
6853 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006854 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006855 terrno = errno;
6856 if( fd<0 && errno==ENOENT && islockfile ){
6857 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006858 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006859 }
6860 }
6861 }
6862 if( fd<0 ){
6863 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006864 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006865 terrno = errno;
6866 }
6867 if( fd<0 ){
6868 if( islockfile ){
6869 return SQLITE_BUSY;
6870 }
6871 switch (terrno) {
6872 case EACCES:
6873 return SQLITE_PERM;
6874 case EIO:
6875 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6876 default:
drh9978c972010-02-23 17:36:32 +00006877 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006878 }
6879 }
6880
drhf3cdcdc2015-04-29 16:50:28 +00006881 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
drh7ed97b92010-01-20 13:07:21 +00006882 if( pNew==NULL ){
mistachkinfad30392016-02-13 23:43:46 +00006883 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006884 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006885 }
6886 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006887 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006888 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006889 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006890 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006891 pUnused->fd = fd;
6892 pUnused->flags = openFlags;
drhc68886b2017-08-18 16:09:52 +00006893 pNew->pPreallocatedUnused = pUnused;
drh7ed97b92010-01-20 13:07:21 +00006894
drhc02a43a2012-01-10 23:18:38 +00006895 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006896 if( rc==SQLITE_OK ){
6897 *ppFile = pNew;
6898 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006899 }
drh7ed97b92010-01-20 13:07:21 +00006900end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006901 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006902 sqlite3_free(pNew);
6903 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006904 return rc;
6905}
6906
drh7ed97b92010-01-20 13:07:21 +00006907#ifdef SQLITE_TEST
6908/* simulate multiple hosts by creating unique hostid file paths */
6909int sqlite3_hostid_num = 0;
6910#endif
6911
6912#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6913
drh6bca6512015-04-13 23:05:28 +00006914#ifdef HAVE_GETHOSTUUID
drh0ab216a2010-07-02 17:10:40 +00006915/* Not always defined in the headers as it ought to be */
6916extern int gethostuuid(uuid_t id, const struct timespec *wait);
drh6bca6512015-04-13 23:05:28 +00006917#endif
drh0ab216a2010-07-02 17:10:40 +00006918
drh7ed97b92010-01-20 13:07:21 +00006919/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6920** bytes of writable memory.
6921*/
6922static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006923 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6924 memset(pHostID, 0, PROXY_HOSTIDLEN);
drh6bca6512015-04-13 23:05:28 +00006925#ifdef HAVE_GETHOSTUUID
drh29ecd8a2010-12-21 00:16:40 +00006926 {
drh4bf66fd2015-02-19 02:43:02 +00006927 struct timespec timeout = {1, 0}; /* 1 sec timeout */
drh29ecd8a2010-12-21 00:16:40 +00006928 if( gethostuuid(pHostID, &timeout) ){
6929 int err = errno;
6930 if( pError ){
6931 *pError = err;
6932 }
6933 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006934 }
drh7ed97b92010-01-20 13:07:21 +00006935 }
drh3d4435b2011-08-26 20:55:50 +00006936#else
6937 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006938#endif
drh7ed97b92010-01-20 13:07:21 +00006939#ifdef SQLITE_TEST
6940 /* simulate multiple hosts by creating unique hostid file paths */
6941 if( sqlite3_hostid_num != 0){
6942 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6943 }
6944#endif
6945
6946 return SQLITE_OK;
6947}
6948
6949/* The conch file contains the header, host id and lock file path
6950 */
6951#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6952#define PROXY_HEADERLEN 1 /* conch file header length */
6953#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6954#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6955
6956/*
6957** Takes an open conch file, copies the contents to a new path and then moves
6958** it back. The newly created file's file descriptor is assigned to the
6959** conch file structure and finally the original conch file descriptor is
6960** closed. Returns zero if successful.
6961*/
6962static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6963 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6964 unixFile *conchFile = pCtx->conchFile;
6965 char tPath[MAXPATHLEN];
6966 char buf[PROXY_MAXCONCHLEN];
6967 char *cPath = pCtx->conchFilePath;
6968 size_t readLen = 0;
6969 size_t pathLen = 0;
6970 char errmsg[64] = "";
6971 int fd = -1;
6972 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006973 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006974
6975 /* create a new path by replace the trailing '-conch' with '-break' */
6976 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6977 if( pathLen>MAXPATHLEN || pathLen<6 ||
6978 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006979 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006980 goto end_breaklock;
6981 }
6982 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006983 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006984 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006985 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006986 goto end_breaklock;
6987 }
6988 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006989 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006990 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006991 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006992 goto end_breaklock;
6993 }
drhe562be52011-03-02 18:01:10 +00006994 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006995 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006996 goto end_breaklock;
6997 }
6998 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006999 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00007000 goto end_breaklock;
7001 }
7002 rc = 0;
7003 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00007004 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00007005 conchFile->h = fd;
7006 conchFile->openFlags = O_RDWR | O_CREAT;
7007
7008end_breaklock:
7009 if( rc ){
7010 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00007011 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00007012 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00007013 }
7014 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
7015 }
7016 return rc;
7017}
7018
7019/* Take the requested lock on the conch file and break a stale lock if the
7020** host id matches.
7021*/
7022static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
7023 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7024 unixFile *conchFile = pCtx->conchFile;
7025 int rc = SQLITE_OK;
7026 int nTries = 0;
7027 struct timespec conchModTime;
7028
drh3d4435b2011-08-26 20:55:50 +00007029 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00007030 do {
7031 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
7032 nTries ++;
7033 if( rc==SQLITE_BUSY ){
7034 /* If the lock failed (busy):
7035 * 1st try: get the mod time of the conch, wait 0.5s and try again.
7036 * 2nd try: fail if the mod time changed or host id is different, wait
7037 * 10 sec and try again
7038 * 3rd try: break the lock unless the mod time has changed.
7039 */
7040 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00007041 if( osFstat(conchFile->h, &buf) ){
drh4bf66fd2015-02-19 02:43:02 +00007042 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00007043 return SQLITE_IOERR_LOCK;
7044 }
7045
7046 if( nTries==1 ){
7047 conchModTime = buf.st_mtimespec;
7048 usleep(500000); /* wait 0.5 sec and try the lock again*/
7049 continue;
7050 }
7051
7052 assert( nTries>1 );
7053 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
7054 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
7055 return SQLITE_BUSY;
7056 }
7057
7058 if( nTries==2 ){
7059 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00007060 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00007061 if( len<0 ){
drh4bf66fd2015-02-19 02:43:02 +00007062 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00007063 return SQLITE_IOERR_LOCK;
7064 }
7065 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
7066 /* don't break the lock if the host id doesn't match */
7067 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
7068 return SQLITE_BUSY;
7069 }
7070 }else{
7071 /* don't break the lock on short read or a version mismatch */
7072 return SQLITE_BUSY;
7073 }
7074 usleep(10000000); /* wait 10 sec and try the lock again */
7075 continue;
7076 }
7077
7078 assert( nTries==3 );
7079 if( 0==proxyBreakConchLock(pFile, myHostID) ){
7080 rc = SQLITE_OK;
7081 if( lockType==EXCLUSIVE_LOCK ){
drhe6d41732015-02-21 00:49:00 +00007082 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
drh7ed97b92010-01-20 13:07:21 +00007083 }
7084 if( !rc ){
7085 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
7086 }
7087 }
7088 }
7089 } while( rc==SQLITE_BUSY && nTries<3 );
7090
7091 return rc;
7092}
7093
7094/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00007095** lockPath is non-NULL, the host ID and lock file path must match. A NULL
7096** lockPath means that the lockPath in the conch file will be used if the
7097** host IDs match, or a new lock path will be generated automatically
7098** and written to the conch file.
7099*/
7100static int proxyTakeConch(unixFile *pFile){
7101 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7102
drh7ed97b92010-01-20 13:07:21 +00007103 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00007104 return SQLITE_OK;
7105 }else{
7106 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00007107 uuid_t myHostID;
7108 int pError = 0;
7109 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00007110 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00007111 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00007112 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00007113 int createConch = 0;
7114 int hostIdMatch = 0;
7115 int readLen = 0;
7116 int tryOldLockPath = 0;
7117 int forceNewLockPath = 0;
7118
drh308c2a52010-05-14 11:30:18 +00007119 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
drh91eb93c2015-03-03 19:56:20 +00007120 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00007121 osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007122
drh7ed97b92010-01-20 13:07:21 +00007123 rc = proxyGetHostID(myHostID, &pError);
7124 if( (rc&0xff)==SQLITE_IOERR ){
drh4bf66fd2015-02-19 02:43:02 +00007125 storeLastErrno(pFile, pError);
drh7ed97b92010-01-20 13:07:21 +00007126 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00007127 }
drh7ed97b92010-01-20 13:07:21 +00007128 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00007129 if( rc!=SQLITE_OK ){
7130 goto end_takeconch;
7131 }
drh7ed97b92010-01-20 13:07:21 +00007132 /* read the existing conch file */
7133 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
7134 if( readLen<0 ){
7135 /* I/O error: lastErrno set by seekAndRead */
drh4bf66fd2015-02-19 02:43:02 +00007136 storeLastErrno(pFile, conchFile->lastErrno);
drh7ed97b92010-01-20 13:07:21 +00007137 rc = SQLITE_IOERR_READ;
7138 goto end_takeconch;
7139 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
7140 readBuf[0]!=(char)PROXY_CONCHVERSION ){
7141 /* a short read or version format mismatch means we need to create a new
7142 ** conch file.
7143 */
7144 createConch = 1;
7145 }
7146 /* if the host id matches and the lock path already exists in the conch
7147 ** we'll try to use the path there, if we can't open that path, we'll
7148 ** retry with a new auto-generated path
7149 */
7150 do { /* in case we need to try again for an :auto: named lock file */
7151
7152 if( !createConch && !forceNewLockPath ){
7153 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
7154 PROXY_HOSTIDLEN);
7155 /* if the conch has data compare the contents */
7156 if( !pCtx->lockProxyPath ){
7157 /* for auto-named local lock file, just check the host ID and we'll
7158 ** use the local lock file path that's already in there
7159 */
7160 if( hostIdMatch ){
7161 size_t pathLen = (readLen - PROXY_PATHINDEX);
7162
7163 if( pathLen>=MAXPATHLEN ){
7164 pathLen=MAXPATHLEN-1;
7165 }
7166 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
7167 lockPath[pathLen] = 0;
7168 tempLockPath = lockPath;
7169 tryOldLockPath = 1;
7170 /* create a copy of the lock path if the conch is taken */
7171 goto end_takeconch;
7172 }
7173 }else if( hostIdMatch
7174 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
7175 readLen-PROXY_PATHINDEX)
7176 ){
7177 /* conch host and lock path match */
7178 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00007179 }
drh7ed97b92010-01-20 13:07:21 +00007180 }
7181
7182 /* if the conch isn't writable and doesn't match, we can't take it */
7183 if( (conchFile->openFlags&O_RDWR) == 0 ){
7184 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00007185 goto end_takeconch;
7186 }
drh7ed97b92010-01-20 13:07:21 +00007187
7188 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00007189 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00007190 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
7191 tempLockPath = lockPath;
7192 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00007193 }
drh7ed97b92010-01-20 13:07:21 +00007194
7195 /* update conch with host and path (this will fail if other process
7196 ** has a shared lock already), if the host id matches, use the big
7197 ** stick.
drh715ff302008-12-03 22:32:44 +00007198 */
drh7ed97b92010-01-20 13:07:21 +00007199 futimes(conchFile->h, NULL);
7200 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00007201 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00007202 /* We are trying for an exclusive lock but another thread in this
7203 ** same process is still holding a shared lock. */
7204 rc = SQLITE_BUSY;
7205 } else {
7206 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00007207 }
drh715ff302008-12-03 22:32:44 +00007208 }else{
drh4bf66fd2015-02-19 02:43:02 +00007209 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00007210 }
drh7ed97b92010-01-20 13:07:21 +00007211 if( rc==SQLITE_OK ){
7212 char writeBuffer[PROXY_MAXCONCHLEN];
7213 int writeSize = 0;
7214
7215 writeBuffer[0] = (char)PROXY_CONCHVERSION;
7216 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
7217 if( pCtx->lockProxyPath!=NULL ){
drh4bf66fd2015-02-19 02:43:02 +00007218 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
7219 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007220 }else{
7221 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
7222 }
7223 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00007224 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00007225 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
drh6d258992016-02-04 09:48:12 +00007226 full_fsync(conchFile->h,0,0);
drh7ed97b92010-01-20 13:07:21 +00007227 /* If we created a new conch file (not just updated the contents of a
7228 ** valid conch file), try to match the permissions of the database
7229 */
7230 if( rc==SQLITE_OK && createConch ){
7231 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00007232 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00007233 if( err==0 ){
7234 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
7235 S_IROTH|S_IWOTH);
7236 /* try to match the database file R/W permissions, ignore failure */
7237#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00007238 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00007239#else
drhff812312011-02-23 13:33:46 +00007240 do{
drhe562be52011-03-02 18:01:10 +00007241 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00007242 }while( rc==(-1) && errno==EINTR );
7243 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00007244 int code = errno;
7245 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
7246 cmode, code, strerror(code));
7247 } else {
7248 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
7249 }
7250 }else{
7251 int code = errno;
7252 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
7253 err, code, strerror(code));
7254#endif
7255 }
drh715ff302008-12-03 22:32:44 +00007256 }
7257 }
drh7ed97b92010-01-20 13:07:21 +00007258 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
7259
7260 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00007261 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00007262 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00007263 int fd;
drh7ed97b92010-01-20 13:07:21 +00007264 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00007265 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00007266 }
7267 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00007268 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00007269 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00007270 if( fd>=0 ){
7271 pFile->h = fd;
7272 }else{
drh9978c972010-02-23 17:36:32 +00007273 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00007274 during locking */
7275 }
7276 }
7277 if( rc==SQLITE_OK && !pCtx->lockProxy ){
7278 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
7279 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
7280 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
7281 /* we couldn't create the proxy lock file with the old lock file path
7282 ** so try again via auto-naming
7283 */
7284 forceNewLockPath = 1;
7285 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00007286 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00007287 }
7288 }
7289 if( rc==SQLITE_OK ){
7290 /* Need to make a copy of path if we extracted the value
7291 ** from the conch file or the path was allocated on the stack
7292 */
7293 if( tempLockPath ){
7294 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
7295 if( !pCtx->lockProxyPath ){
mistachkinfad30392016-02-13 23:43:46 +00007296 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00007297 }
7298 }
7299 }
7300 if( rc==SQLITE_OK ){
7301 pCtx->conchHeld = 1;
7302
7303 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
7304 afpLockingContext *afpCtx;
7305 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
7306 afpCtx->dbPath = pCtx->lockProxyPath;
7307 }
7308 } else {
7309 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7310 }
drh308c2a52010-05-14 11:30:18 +00007311 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
7312 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00007313 return rc;
drh308c2a52010-05-14 11:30:18 +00007314 } while (1); /* in case we need to retry the :auto: lock file -
7315 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00007316 }
7317}
7318
7319/*
7320** If pFile holds a lock on a conch file, then release that lock.
7321*/
7322static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00007323 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00007324 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
7325 unixFile *conchFile; /* Name of the conch file */
7326
7327 pCtx = (proxyLockingContext *)pFile->lockingContext;
7328 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00007329 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00007330 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00007331 osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00007332 if( pCtx->conchHeld>0 ){
7333 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7334 }
drh715ff302008-12-03 22:32:44 +00007335 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00007336 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
7337 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007338 return rc;
7339}
7340
7341/*
7342** Given the name of a database file, compute the name of its conch file.
drhf3cdcdc2015-04-29 16:50:28 +00007343** Store the conch filename in memory obtained from sqlite3_malloc64().
drh715ff302008-12-03 22:32:44 +00007344** Make *pConchPath point to the new name. Return SQLITE_OK on success
7345** or SQLITE_NOMEM if unable to obtain memory.
7346**
7347** The caller is responsible for ensuring that the allocated memory
7348** space is eventually freed.
7349**
7350** *pConchPath is set to NULL if a memory allocation error occurs.
7351*/
7352static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7353 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00007354 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00007355 char *conchPath; /* buffer in which to construct conch name */
7356
7357 /* Allocate space for the conch filename and initialize the name to
7358 ** the name of the original database file. */
drhf3cdcdc2015-04-29 16:50:28 +00007359 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
drh715ff302008-12-03 22:32:44 +00007360 if( conchPath==0 ){
mistachkinfad30392016-02-13 23:43:46 +00007361 return SQLITE_NOMEM_BKPT;
drh715ff302008-12-03 22:32:44 +00007362 }
7363 memcpy(conchPath, dbPath, len+1);
7364
7365 /* now insert a "." before the last / character */
7366 for( i=(len-1); i>=0; i-- ){
7367 if( conchPath[i]=='/' ){
7368 i++;
7369 break;
7370 }
7371 }
7372 conchPath[i]='.';
7373 while ( i<len ){
7374 conchPath[i+1]=dbPath[i];
7375 i++;
7376 }
7377
7378 /* append the "-conch" suffix to the file */
7379 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007380 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007381
7382 return SQLITE_OK;
7383}
7384
7385
7386/* Takes a fully configured proxy locking-style unix file and switches
7387** the local lock file path
7388*/
7389static int switchLockProxyPath(unixFile *pFile, const char *path) {
7390 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7391 char *oldPath = pCtx->lockProxyPath;
7392 int rc = SQLITE_OK;
7393
drh308c2a52010-05-14 11:30:18 +00007394 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007395 return SQLITE_BUSY;
7396 }
7397
7398 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7399 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7400 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7401 return SQLITE_OK;
7402 }else{
7403 unixFile *lockProxy = pCtx->lockProxy;
7404 pCtx->lockProxy=NULL;
7405 pCtx->conchHeld = 0;
7406 if( lockProxy!=NULL ){
7407 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7408 if( rc ) return rc;
7409 sqlite3_free(lockProxy);
7410 }
7411 sqlite3_free(oldPath);
7412 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7413 }
7414
7415 return rc;
7416}
7417
7418/*
7419** pFile is a file that has been opened by a prior xOpen call. dbPath
7420** is a string buffer at least MAXPATHLEN+1 characters in size.
7421**
7422** This routine find the filename associated with pFile and writes it
7423** int dbPath.
7424*/
7425static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007426#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007427 if( pFile->pMethod == &afpIoMethods ){
7428 /* afp style keeps a reference to the db path in the filePath field
7429 ** of the struct */
drhea678832008-12-10 19:26:22 +00007430 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh4bf66fd2015-02-19 02:43:02 +00007431 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7432 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007433 } else
drh715ff302008-12-03 22:32:44 +00007434#endif
7435 if( pFile->pMethod == &dotlockIoMethods ){
7436 /* dot lock style uses the locking context to store the dot lock
7437 ** file path */
7438 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7439 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7440 }else{
7441 /* all other styles use the locking context to store the db file path */
7442 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007443 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007444 }
7445 return SQLITE_OK;
7446}
7447
7448/*
7449** Takes an already filled in unix file and alters it so all file locking
7450** will be performed on the local proxy lock file. The following fields
7451** are preserved in the locking context so that they can be restored and
7452** the unix structure properly cleaned up at close time:
7453** ->lockingContext
7454** ->pMethod
7455*/
7456static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7457 proxyLockingContext *pCtx;
7458 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7459 char *lockPath=NULL;
7460 int rc = SQLITE_OK;
7461
drh308c2a52010-05-14 11:30:18 +00007462 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007463 return SQLITE_BUSY;
7464 }
7465 proxyGetDbPathForUnixFile(pFile, dbPath);
7466 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7467 lockPath=NULL;
7468 }else{
7469 lockPath=(char *)path;
7470 }
7471
drh308c2a52010-05-14 11:30:18 +00007472 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
drh5ac93652015-03-21 20:59:43 +00007473 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007474
drhf3cdcdc2015-04-29 16:50:28 +00007475 pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh715ff302008-12-03 22:32:44 +00007476 if( pCtx==0 ){
mistachkinfad30392016-02-13 23:43:46 +00007477 return SQLITE_NOMEM_BKPT;
drh715ff302008-12-03 22:32:44 +00007478 }
7479 memset(pCtx, 0, sizeof(*pCtx));
7480
7481 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7482 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007483 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7484 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7485 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7486 ** (c) the file system is read-only, then enable no-locking access.
7487 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7488 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7489 */
7490 struct statfs fsInfo;
7491 struct stat conchInfo;
7492 int goLockless = 0;
7493
drh99ab3b12011-03-02 15:09:07 +00007494 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007495 int err = errno;
7496 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7497 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7498 }
7499 }
7500 if( goLockless ){
7501 pCtx->conchHeld = -1; /* read only FS/ lockless */
7502 rc = SQLITE_OK;
7503 }
7504 }
drh715ff302008-12-03 22:32:44 +00007505 }
7506 if( rc==SQLITE_OK && lockPath ){
7507 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7508 }
7509
7510 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007511 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7512 if( pCtx->dbPath==NULL ){
mistachkinfad30392016-02-13 23:43:46 +00007513 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00007514 }
7515 }
7516 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007517 /* all memory is allocated, proxys are created and assigned,
7518 ** switch the locking context and pMethod then return.
7519 */
drh715ff302008-12-03 22:32:44 +00007520 pCtx->oldLockingContext = pFile->lockingContext;
7521 pFile->lockingContext = pCtx;
7522 pCtx->pOldMethod = pFile->pMethod;
7523 pFile->pMethod = &proxyIoMethods;
7524 }else{
7525 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007526 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007527 sqlite3_free(pCtx->conchFile);
7528 }
drhd56b1212010-08-11 06:14:15 +00007529 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007530 sqlite3_free(pCtx->conchFilePath);
7531 sqlite3_free(pCtx);
7532 }
drh308c2a52010-05-14 11:30:18 +00007533 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7534 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007535 return rc;
7536}
7537
7538
7539/*
7540** This routine handles sqlite3_file_control() calls that are specific
7541** to proxy locking.
7542*/
7543static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7544 switch( op ){
drh4bf66fd2015-02-19 02:43:02 +00007545 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007546 unixFile *pFile = (unixFile*)id;
7547 if( pFile->pMethod == &proxyIoMethods ){
7548 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7549 proxyTakeConch(pFile);
7550 if( pCtx->lockProxyPath ){
7551 *(const char **)pArg = pCtx->lockProxyPath;
7552 }else{
7553 *(const char **)pArg = ":auto: (not held)";
7554 }
7555 } else {
7556 *(const char **)pArg = NULL;
7557 }
7558 return SQLITE_OK;
7559 }
drh4bf66fd2015-02-19 02:43:02 +00007560 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007561 unixFile *pFile = (unixFile*)id;
7562 int rc = SQLITE_OK;
7563 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7564 if( pArg==NULL || (const char *)pArg==0 ){
7565 if( isProxyStyle ){
drh4bf66fd2015-02-19 02:43:02 +00007566 /* turn off proxy locking - not supported. If support is added for
7567 ** switching proxy locking mode off then it will need to fail if
7568 ** the journal mode is WAL mode.
7569 */
drh715ff302008-12-03 22:32:44 +00007570 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7571 }else{
7572 /* turn off proxy locking - already off - NOOP */
7573 rc = SQLITE_OK;
7574 }
7575 }else{
7576 const char *proxyPath = (const char *)pArg;
7577 if( isProxyStyle ){
7578 proxyLockingContext *pCtx =
7579 (proxyLockingContext*)pFile->lockingContext;
7580 if( !strcmp(pArg, ":auto:")
7581 || (pCtx->lockProxyPath &&
7582 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7583 ){
7584 rc = SQLITE_OK;
7585 }else{
7586 rc = switchLockProxyPath(pFile, proxyPath);
7587 }
7588 }else{
7589 /* turn on proxy file locking */
7590 rc = proxyTransformUnixFile(pFile, proxyPath);
7591 }
7592 }
7593 return rc;
7594 }
7595 default: {
7596 assert( 0 ); /* The call assures that only valid opcodes are sent */
7597 }
7598 }
7599 /*NOTREACHED*/
7600 return SQLITE_ERROR;
7601}
7602
7603/*
7604** Within this division (the proxying locking implementation) the procedures
7605** above this point are all utilities. The lock-related methods of the
7606** proxy-locking sqlite3_io_method object follow.
7607*/
7608
7609
7610/*
7611** This routine checks if there is a RESERVED lock held on the specified
7612** file by this or any other process. If such a lock is held, set *pResOut
7613** to a non-zero value otherwise *pResOut is set to zero. The return value
7614** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7615*/
7616static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7617 unixFile *pFile = (unixFile*)id;
7618 int rc = proxyTakeConch(pFile);
7619 if( rc==SQLITE_OK ){
7620 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007621 if( pCtx->conchHeld>0 ){
7622 unixFile *proxy = pCtx->lockProxy;
7623 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7624 }else{ /* conchHeld < 0 is lockless */
7625 pResOut=0;
7626 }
drh715ff302008-12-03 22:32:44 +00007627 }
7628 return rc;
7629}
7630
7631/*
drh308c2a52010-05-14 11:30:18 +00007632** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007633** of the following:
7634**
7635** (1) SHARED_LOCK
7636** (2) RESERVED_LOCK
7637** (3) PENDING_LOCK
7638** (4) EXCLUSIVE_LOCK
7639**
7640** Sometimes when requesting one lock state, additional lock states
7641** are inserted in between. The locking might fail on one of the later
7642** transitions leaving the lock state different from what it started but
7643** still short of its goal. The following chart shows the allowed
7644** transitions and the inserted intermediate states:
7645**
7646** UNLOCKED -> SHARED
7647** SHARED -> RESERVED
7648** SHARED -> (PENDING) -> EXCLUSIVE
7649** RESERVED -> (PENDING) -> EXCLUSIVE
7650** PENDING -> EXCLUSIVE
7651**
7652** This routine will only increase a lock. Use the sqlite3OsUnlock()
7653** routine to lower a locking level.
7654*/
drh308c2a52010-05-14 11:30:18 +00007655static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007656 unixFile *pFile = (unixFile*)id;
7657 int rc = proxyTakeConch(pFile);
7658 if( rc==SQLITE_OK ){
7659 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007660 if( pCtx->conchHeld>0 ){
7661 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007662 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7663 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007664 }else{
7665 /* conchHeld < 0 is lockless */
7666 }
drh715ff302008-12-03 22:32:44 +00007667 }
7668 return rc;
7669}
7670
7671
7672/*
drh308c2a52010-05-14 11:30:18 +00007673** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007674** must be either NO_LOCK or SHARED_LOCK.
7675**
7676** If the locking level of the file descriptor is already at or below
7677** the requested locking level, this routine is a no-op.
7678*/
drh308c2a52010-05-14 11:30:18 +00007679static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007680 unixFile *pFile = (unixFile*)id;
7681 int rc = proxyTakeConch(pFile);
7682 if( rc==SQLITE_OK ){
7683 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007684 if( pCtx->conchHeld>0 ){
7685 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007686 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7687 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007688 }else{
7689 /* conchHeld < 0 is lockless */
7690 }
drh715ff302008-12-03 22:32:44 +00007691 }
7692 return rc;
7693}
7694
7695/*
7696** Close a file that uses proxy locks.
7697*/
7698static int proxyClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00007699 if( ALWAYS(id) ){
drh715ff302008-12-03 22:32:44 +00007700 unixFile *pFile = (unixFile*)id;
7701 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7702 unixFile *lockProxy = pCtx->lockProxy;
7703 unixFile *conchFile = pCtx->conchFile;
7704 int rc = SQLITE_OK;
7705
7706 if( lockProxy ){
7707 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7708 if( rc ) return rc;
7709 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7710 if( rc ) return rc;
7711 sqlite3_free(lockProxy);
7712 pCtx->lockProxy = 0;
7713 }
7714 if( conchFile ){
7715 if( pCtx->conchHeld ){
7716 rc = proxyReleaseConch(pFile);
7717 if( rc ) return rc;
7718 }
7719 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7720 if( rc ) return rc;
7721 sqlite3_free(conchFile);
7722 }
drhd56b1212010-08-11 06:14:15 +00007723 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007724 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007725 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007726 /* restore the original locking context and pMethod then close it */
7727 pFile->lockingContext = pCtx->oldLockingContext;
7728 pFile->pMethod = pCtx->pOldMethod;
7729 sqlite3_free(pCtx);
7730 return pFile->pMethod->xClose(id);
7731 }
7732 return SQLITE_OK;
7733}
7734
7735
7736
drhd2cb50b2009-01-09 21:41:17 +00007737#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007738/*
7739** The proxy locking style is intended for use with AFP filesystems.
7740** And since AFP is only supported on MacOSX, the proxy locking is also
7741** restricted to MacOSX.
7742**
7743**
7744******************* End of the proxy lock implementation **********************
7745******************************************************************************/
7746
drh734c9862008-11-28 15:37:20 +00007747/*
danielk1977e339d652008-06-28 11:23:00 +00007748** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007749**
7750** This routine registers all VFS implementations for unix-like operating
7751** systems. This routine, and the sqlite3_os_end() routine that follows,
7752** should be the only routines in this file that are visible from other
7753** files.
drh6b9d6dd2008-12-03 19:34:47 +00007754**
7755** This routine is called once during SQLite initialization and by a
7756** single thread. The memory allocation and mutex subsystems have not
7757** necessarily been initialized when this routine is called, and so they
7758** should not be used.
drh153c62c2007-08-24 03:51:33 +00007759*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007760int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007761 /*
7762 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007763 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7764 ** to the "finder" function. (pAppData is a pointer to a pointer because
7765 ** silly C90 rules prohibit a void* from being cast to a function pointer
7766 ** and so we have to go through the intermediate pointer to avoid problems
7767 ** when compiling with -pedantic-errors on GCC.)
7768 **
7769 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007770 ** finder-function. The finder-function returns a pointer to the
7771 ** sqlite_io_methods object that implements the desired locking
7772 ** behaviors. See the division above that contains the IOMETHODS
7773 ** macro for addition information on finder-functions.
7774 **
7775 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7776 ** object. But the "autolockIoFinder" available on MacOSX does a little
7777 ** more than that; it looks at the filesystem type that hosts the
7778 ** database file and tries to choose an locking method appropriate for
7779 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007780 */
drh7708e972008-11-29 00:56:52 +00007781 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007782 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007783 sizeof(unixFile), /* szOsFile */ \
7784 MAX_PATHNAME, /* mxPathname */ \
7785 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007786 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007787 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007788 unixOpen, /* xOpen */ \
7789 unixDelete, /* xDelete */ \
7790 unixAccess, /* xAccess */ \
7791 unixFullPathname, /* xFullPathname */ \
7792 unixDlOpen, /* xDlOpen */ \
7793 unixDlError, /* xDlError */ \
7794 unixDlSym, /* xDlSym */ \
7795 unixDlClose, /* xDlClose */ \
7796 unixRandomness, /* xRandomness */ \
7797 unixSleep, /* xSleep */ \
7798 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007799 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007800 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007801 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007802 unixGetSystemCall, /* xGetSystemCall */ \
7803 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007804 }
7805
drh6b9d6dd2008-12-03 19:34:47 +00007806 /*
7807 ** All default VFSes for unix are contained in the following array.
7808 **
7809 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7810 ** by the SQLite core when the VFS is registered. So the following
7811 ** array cannot be const.
7812 */
danielk1977e339d652008-06-28 11:23:00 +00007813 static sqlite3_vfs aVfs[] = {
drhe89b2912015-03-03 20:42:01 +00007814#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007815 UNIXVFS("unix", autolockIoFinder ),
drhe89b2912015-03-03 20:42:01 +00007816#elif OS_VXWORKS
7817 UNIXVFS("unix", vxworksIoFinder ),
drh7708e972008-11-29 00:56:52 +00007818#else
7819 UNIXVFS("unix", posixIoFinder ),
7820#endif
7821 UNIXVFS("unix-none", nolockIoFinder ),
7822 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007823 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007824#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007825 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007826#endif
drhe89b2912015-03-03 20:42:01 +00007827#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007828 UNIXVFS("unix-posix", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007829#endif
drhe89b2912015-03-03 20:42:01 +00007830#if SQLITE_ENABLE_LOCKING_STYLE
7831 UNIXVFS("unix-flock", flockIoFinder ),
chw78a13182009-04-07 05:35:03 +00007832#endif
drhd2cb50b2009-01-09 21:41:17 +00007833#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007834 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007835 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007836 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007837#endif
drh153c62c2007-08-24 03:51:33 +00007838 };
drh6b9d6dd2008-12-03 19:34:47 +00007839 unsigned int i; /* Loop counter */
7840
drh2aa5a002011-04-13 13:42:25 +00007841 /* Double-check that the aSyscall[] array has been constructed
7842 ** correctly. See ticket [bb3a86e890c8e96ab] */
danefe16972017-07-20 19:49:14 +00007843 assert( ArraySize(aSyscall)==29 );
drh2aa5a002011-04-13 13:42:25 +00007844
drh6b9d6dd2008-12-03 19:34:47 +00007845 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007846 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007847 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007848 }
drh56115892018-02-05 16:39:12 +00007849 unixBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
danielk1977c0fa4c52008-06-25 17:19:00 +00007850 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007851}
danielk1977e339d652008-06-28 11:23:00 +00007852
7853/*
drh6b9d6dd2008-12-03 19:34:47 +00007854** Shutdown the operating system interface.
7855**
7856** Some operating systems might need to do some cleanup in this routine,
7857** to release dynamically allocated objects. But not on unix.
7858** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007859*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007860int sqlite3_os_end(void){
drh56115892018-02-05 16:39:12 +00007861 unixBigLock = 0;
danielk1977c0fa4c52008-06-25 17:19:00 +00007862 return SQLITE_OK;
7863}
drhdce8bdb2007-08-16 13:01:44 +00007864
danielk197729bafea2008-06-26 10:41:19 +00007865#endif /* SQLITE_OS_UNIX */