blob: ab0a5d919a78a6d5a5dc925139b65927ce602abc [file] [log] [blame]
drhbbd42a62004-05-22 17:41:58 +00001/*
2** 2004 May 22
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11******************************************************************************
12**
drh734c9862008-11-28 15:37:20 +000013** This file contains the VFS implementation for unix-like operating systems
14** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
danielk1977822a5162008-05-16 04:51:54 +000015**
drh734c9862008-11-28 15:37:20 +000016** There are actually several different VFS implementations in this file.
17** The differences are in the way that file locking is done. The default
18** implementation uses Posix Advisory Locks. Alternative implementations
19** use flock(), dot-files, various proprietary locking schemas, or simply
20** skip locking all together.
21**
drh9b35ea62008-11-29 02:20:26 +000022** This source file is organized into divisions where the logic for various
drh734c9862008-11-28 15:37:20 +000023** subfunctions is contained within the appropriate division. PLEASE
24** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
25** in the correct division and should be clearly labeled.
26**
drh6b9d6dd2008-12-03 19:34:47 +000027** The layout of divisions is as follows:
drh734c9862008-11-28 15:37:20 +000028**
29** * General-purpose declarations and utility functions.
30** * Unique file ID logic used by VxWorks.
drh715ff302008-12-03 22:32:44 +000031** * Various locking primitive implementations (all except proxy locking):
drh734c9862008-11-28 15:37:20 +000032** + for Posix Advisory Locks
33** + for no-op locks
34** + for dot-file locks
35** + for flock() locking
36** + for named semaphore locks (VxWorks only)
37** + for AFP filesystem locks (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000038** * sqlite3_file methods not associated with locking.
39** * Definitions of sqlite3_io_methods objects for all locking
40** methods plus "finder" functions for each locking method.
drh6b9d6dd2008-12-03 19:34:47 +000041** * sqlite3_vfs method implementations.
drh715ff302008-12-03 22:32:44 +000042** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000043** * Definitions of sqlite3_vfs objects for all locking methods
44** plus implementations of sqlite3_os_init() and sqlite3_os_end().
drhbbd42a62004-05-22 17:41:58 +000045*/
drhbbd42a62004-05-22 17:41:58 +000046#include "sqliteInt.h"
danielk197729bafea2008-06-26 10:41:19 +000047#if SQLITE_OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000048
danielk1977e339d652008-06-28 11:23:00 +000049/*
drh6b9d6dd2008-12-03 19:34:47 +000050** There are various methods for file locking used for concurrency
51** control:
danielk1977e339d652008-06-28 11:23:00 +000052**
drh734c9862008-11-28 15:37:20 +000053** 1. POSIX locking (the default),
54** 2. No locking,
55** 3. Dot-file locking,
56** 4. flock() locking,
57** 5. AFP locking (OSX only),
58** 6. Named POSIX semaphores (VXWorks only),
59** 7. proxy locking. (OSX only)
60**
61** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
62** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
63** selection of the appropriate locking style based on the filesystem
64** where the database is located.
danielk1977e339d652008-06-28 11:23:00 +000065*/
drh40bbb0a2008-09-23 10:23:26 +000066#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
drhd2cb50b2009-01-09 21:41:17 +000067# if defined(__APPLE__)
drh40bbb0a2008-09-23 10:23:26 +000068# define SQLITE_ENABLE_LOCKING_STYLE 1
69# else
70# define SQLITE_ENABLE_LOCKING_STYLE 0
71# endif
72#endif
drhbfe66312006-10-03 17:40:40 +000073
drhe32a2562016-03-04 02:38:00 +000074/* Use pread() and pwrite() if they are available */
drh79a2ca32016-03-04 03:14:39 +000075#if defined(__APPLE__)
76# define HAVE_PREAD 1
77# define HAVE_PWRITE 1
78#endif
drhe32a2562016-03-04 02:38:00 +000079#if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
80# undef USE_PREAD
drhe32a2562016-03-04 02:38:00 +000081# define USE_PREAD64 1
drhe32a2562016-03-04 02:38:00 +000082#elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)
drh79a2ca32016-03-04 03:14:39 +000083# undef USE_PREAD64
84# define USE_PREAD 1
drhe32a2562016-03-04 02:38:00 +000085#endif
86
drh9cbe6352005-11-29 03:13:21 +000087/*
drh9cbe6352005-11-29 03:13:21 +000088** standard include files.
89*/
90#include <sys/types.h>
91#include <sys/stat.h>
92#include <fcntl.h>
danefe16972017-07-20 19:49:14 +000093#include <sys/ioctl.h>
drh9cbe6352005-11-29 03:13:21 +000094#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +000095#include <time.h>
drh19e2d372005-08-29 23:00:03 +000096#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +000097#include <errno.h>
dan32c12fe2013-05-02 17:37:31 +000098#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drh91be7dc2014-08-11 13:53:30 +000099# include <sys/mman.h>
drhb469f462010-12-22 21:48:50 +0000100#endif
drh1da88f02011-12-17 16:09:16 +0000101
drhe89b2912015-03-03 20:42:01 +0000102#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000103# include <sys/ioctl.h>
drhe89b2912015-03-03 20:42:01 +0000104# include <sys/file.h>
105# include <sys/param.h>
drhbfe66312006-10-03 17:40:40 +0000106#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000107
drh6bca6512015-04-13 23:05:28 +0000108#if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
109 (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
110# if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
111 && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
112# define HAVE_GETHOSTUUID 1
113# else
114# warning "gethostuuid() is disabled."
115# endif
116#endif
117
118
drhe89b2912015-03-03 20:42:01 +0000119#if OS_VXWORKS
120# include <sys/ioctl.h>
121# include <semaphore.h>
122# include <limits.h>
123#endif /* OS_VXWORKS */
124
125#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh84a2bf62010-03-05 13:41:06 +0000126# include <sys/mount.h>
127#endif
128
drhdbe4b882011-06-20 18:00:17 +0000129#ifdef HAVE_UTIME
130# include <utime.h>
131#endif
132
drh9cbe6352005-11-29 03:13:21 +0000133/*
drh7ed97b92010-01-20 13:07:21 +0000134** Allowed values of unixFile.fsFlags
135*/
136#define SQLITE_FSFLAGS_IS_MSDOS 0x1
137
138/*
drhf1a221e2006-01-15 17:27:17 +0000139** If we are to be thread-safe, include the pthreads header and define
140** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000141*/
drhd677b3d2007-08-20 22:48:41 +0000142#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000143# include <pthread.h>
144# define SQLITE_UNIX_THREADS 1
145#endif
146
147/*
148** Default permissions when creating a new file
149*/
150#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
151# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
152#endif
153
danielk1977b4b47412007-08-17 15:53:36 +0000154/*
drh5adc60b2012-04-14 13:25:11 +0000155** Default permissions when creating auto proxy dir
156*/
aswiftaebf4132008-11-21 00:10:35 +0000157#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
158# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
159#endif
160
161/*
danielk1977b4b47412007-08-17 15:53:36 +0000162** Maximum supported path-length.
163*/
164#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000165
dane88ec182016-01-25 17:04:48 +0000166/*
167** Maximum supported symbolic links
168*/
169#define SQLITE_MAX_SYMLINKS 100
170
drh91eb93c2015-03-03 19:56:20 +0000171/* Always cast the getpid() return type for compatibility with
172** kernel modules in VxWorks. */
173#define osGetpid(X) (pid_t)getpid()
174
drh734c9862008-11-28 15:37:20 +0000175/*
drh734c9862008-11-28 15:37:20 +0000176** Only set the lastErrno if the error code is a real error and not
177** a normal expected return code of SQLITE_BUSY or SQLITE_OK
178*/
179#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
180
drhd91c68f2010-05-14 14:52:25 +0000181/* Forward references */
182typedef struct unixShm unixShm; /* Connection shared memory */
183typedef struct unixShmNode unixShmNode; /* Shared memory instance */
184typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
185typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000186
187/*
dane946c392009-08-22 11:39:46 +0000188** Sometimes, after a file handle is closed by SQLite, the file descriptor
189** cannot be closed immediately. In these cases, instances of the following
190** structure are used to store the file descriptor while waiting for an
191** opportunity to either close or reuse it.
192*/
dane946c392009-08-22 11:39:46 +0000193struct UnixUnusedFd {
194 int fd; /* File descriptor to close */
195 int flags; /* Flags this file descriptor was opened with */
196 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
197};
198
199/*
drh9b35ea62008-11-29 02:20:26 +0000200** The unixFile structure is subclass of sqlite3_file specific to the unix
201** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000202*/
drh054889e2005-11-30 03:20:31 +0000203typedef struct unixFile unixFile;
204struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000205 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhde60fc22011-12-14 17:53:36 +0000206 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
drhd91c68f2010-05-14 14:52:25 +0000207 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000208 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000209 unsigned char eFileLock; /* The type of lock held on this fd */
drh3ee34842012-02-11 21:21:17 +0000210 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000211 int lastErrno; /* The unix errno from last I/O error */
212 void *lockingContext; /* Locking style specific state */
drhc68886b2017-08-18 16:09:52 +0000213 UnixUnusedFd *pPreallocatedUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000214 const char *zPath; /* Name of the file */
215 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000216 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
mistachkine98844f2013-08-24 00:59:24 +0000217#if SQLITE_MAX_MMAP_SIZE>0
drh0d0614b2013-03-25 23:09:28 +0000218 int nFetchOut; /* Number of outstanding xFetch refs */
219 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
drh9b4c59f2013-04-15 17:03:42 +0000220 sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
221 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
drh0d0614b2013-03-25 23:09:28 +0000222 void *pMapRegion; /* Memory mapped region */
mistachkine98844f2013-08-24 00:59:24 +0000223#endif
drh537dddf2012-10-26 13:46:24 +0000224 int sectorSize; /* Device sector size */
225 int deviceCharacteristics; /* Precomputed device characteristics */
drh08c6d442009-02-09 17:34:07 +0000226#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000227 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000228#endif
drh7ed97b92010-01-20 13:07:21 +0000229#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000230 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000231#endif
drhf0119b22018-03-26 17:40:53 +0000232#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
233 unsigned iBusyTimeout; /* Wait this many millisec on locks */
234#endif
drh6c7d5c52008-11-21 20:32:33 +0000235#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000236 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000237#endif
drhd3d8c042012-05-29 17:02:40 +0000238#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +0000239 /* The next group of variables are used to track whether or not the
240 ** transaction counter in bytes 24-27 of database files are updated
241 ** whenever any part of the database changes. An assertion fault will
242 ** occur if a file is updated without also updating the transaction
243 ** counter. This test is made to avoid new problems similar to the
244 ** one described by ticket #3584.
245 */
246 unsigned char transCntrChng; /* True if the transaction counter changed */
247 unsigned char dbUpdate; /* True if any part of database file changed */
248 unsigned char inNormalWrite; /* True if in a normal write operation */
danf23da962013-03-23 21:00:41 +0000249
drh8f941bc2009-01-14 23:03:40 +0000250#endif
danf23da962013-03-23 21:00:41 +0000251
danielk1977967a4a12007-08-20 14:23:44 +0000252#ifdef SQLITE_TEST
253 /* In test mode, increase the size of this structure a bit so that
254 ** it is larger than the struct CrashFile defined in test6.c.
255 */
256 char aPadding[32];
257#endif
drh9cbe6352005-11-29 03:13:21 +0000258};
259
drhb00d8622014-01-01 15:18:36 +0000260/* This variable holds the process id (pid) from when the xRandomness()
261** method was called. If xOpen() is called from a different process id,
262** indicating that a fork() has occurred, the PRNG will be reset.
263*/
drh8cd5b252015-03-02 22:06:43 +0000264static pid_t randomnessPid = 0;
drhb00d8622014-01-01 15:18:36 +0000265
drh0ccebe72005-06-07 22:22:50 +0000266/*
drha7e61d82011-03-12 17:02:57 +0000267** Allowed values for the unixFile.ctrlFlags bitmask:
268*/
drhf0b190d2011-07-26 16:03:07 +0000269#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
270#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
271#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000272#ifndef SQLITE_DISABLE_DIRSYNC
273# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
274#else
275# define UNIXFILE_DIRSYNC 0x00
276#endif
drhcb15f352011-12-23 01:04:17 +0000277#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
drhc02a43a2012-01-10 23:18:38 +0000278#define UNIXFILE_DELETE 0x20 /* Delete on close */
279#define UNIXFILE_URI 0x40 /* Filename might have query parameters */
280#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
drha7e61d82011-03-12 17:02:57 +0000281
282/*
drh198bf392006-01-06 21:52:49 +0000283** Include code that is common to all os_*.c files
284*/
285#include "os_common.h"
286
287/*
drh0ccebe72005-06-07 22:22:50 +0000288** Define various macros that are missing from some systems.
289*/
drhbbd42a62004-05-22 17:41:58 +0000290#ifndef O_LARGEFILE
291# define O_LARGEFILE 0
292#endif
293#ifdef SQLITE_DISABLE_LFS
294# undef O_LARGEFILE
295# define O_LARGEFILE 0
296#endif
297#ifndef O_NOFOLLOW
298# define O_NOFOLLOW 0
299#endif
300#ifndef O_BINARY
301# define O_BINARY 0
302#endif
303
304/*
drh2b4b5962005-06-15 17:47:55 +0000305** The threadid macro resolves to the thread-id or to 0. Used for
306** testing and debugging only.
307*/
drhd677b3d2007-08-20 22:48:41 +0000308#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000309#define threadid pthread_self()
310#else
311#define threadid 0
312#endif
313
drh99ab3b12011-03-02 15:09:07 +0000314/*
dane6ecd662013-04-01 17:56:59 +0000315** HAVE_MREMAP defaults to true on Linux and false everywhere else.
316*/
317#if !defined(HAVE_MREMAP)
318# if defined(__linux__) && defined(_GNU_SOURCE)
319# define HAVE_MREMAP 1
320# else
321# define HAVE_MREMAP 0
322# endif
323#endif
324
325/*
dan2ee53412014-09-06 16:49:40 +0000326** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
327** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
328*/
329#ifdef __ANDROID__
330# define lseek lseek64
331#endif
332
drhd76dba72017-07-22 16:00:34 +0000333#ifdef __linux__
334/*
335** Linux-specific IOCTL magic numbers used for controlling F2FS
336*/
danefe16972017-07-20 19:49:14 +0000337#define F2FS_IOCTL_MAGIC 0xf5
338#define F2FS_IOC_START_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 1)
339#define F2FS_IOC_COMMIT_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 2)
340#define F2FS_IOC_START_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 3)
341#define F2FS_IOC_ABORT_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 5)
dan9d709542017-07-21 21:06:24 +0000342#define F2FS_IOC_GET_FEATURES _IOR(F2FS_IOCTL_MAGIC, 12, u32)
dan9d709542017-07-21 21:06:24 +0000343#define F2FS_FEATURE_ATOMIC_WRITE 0x0004
drhd76dba72017-07-22 16:00:34 +0000344#endif /* __linux__ */
danefe16972017-07-20 19:49:14 +0000345
346
dan2ee53412014-09-06 16:49:40 +0000347/*
drh9a3baf12011-04-25 18:01:27 +0000348** Different Unix systems declare open() in different ways. Same use
349** open(const char*,int,mode_t). Others use open(const char*,int,...).
350** The difference is important when using a pointer to the function.
351**
352** The safest way to deal with the problem is to always use this wrapper
353** which always has the same well-defined interface.
354*/
355static int posixOpen(const char *zFile, int flags, int mode){
356 return open(zFile, flags, mode);
357}
358
drh90315a22011-08-10 01:52:12 +0000359/* Forward reference */
360static int openDirectory(const char*, int*);
danbc760632014-03-20 09:42:09 +0000361static int unixGetpagesize(void);
drh90315a22011-08-10 01:52:12 +0000362
drh9a3baf12011-04-25 18:01:27 +0000363/*
drh99ab3b12011-03-02 15:09:07 +0000364** Many system calls are accessed through pointer-to-functions so that
365** they may be overridden at runtime to facilitate fault injection during
366** testing and sandboxing. The following array holds the names and pointers
367** to all overrideable system calls.
368*/
369static struct unix_syscall {
mistachkin48864df2013-03-21 21:20:32 +0000370 const char *zName; /* Name of the system call */
drh58ad5802011-03-23 22:02:23 +0000371 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
372 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000373} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000374 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
375#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000376
drh58ad5802011-03-23 22:02:23 +0000377 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000378#define osClose ((int(*)(int))aSyscall[1].pCurrent)
379
drh58ad5802011-03-23 22:02:23 +0000380 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000381#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
382
drh58ad5802011-03-23 22:02:23 +0000383 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000384#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
385
drh58ad5802011-03-23 22:02:23 +0000386 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000387#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
388
389/*
390** The DJGPP compiler environment looks mostly like Unix, but it
391** lacks the fcntl() system call. So redefine fcntl() to be something
392** that always succeeds. This means that locking does not occur under
393** DJGPP. But it is DOS - what did you expect?
394*/
395#ifdef __DJGPP__
396 { "fstat", 0, 0 },
397#define osFstat(a,b,c) 0
398#else
drh58ad5802011-03-23 22:02:23 +0000399 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000400#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
401#endif
402
drh58ad5802011-03-23 22:02:23 +0000403 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000404#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
405
drh58ad5802011-03-23 22:02:23 +0000406 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000407#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000408
drh58ad5802011-03-23 22:02:23 +0000409 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000410#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
411
drhe89b2912015-03-03 20:42:01 +0000412#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000413 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000414#else
drh58ad5802011-03-23 22:02:23 +0000415 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000416#endif
417#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
418
419#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000420 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000421#else
drh58ad5802011-03-23 22:02:23 +0000422 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000423#endif
drhf9986d92016-04-18 13:09:55 +0000424#define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
drhe562be52011-03-02 18:01:10 +0000425
drh58ad5802011-03-23 22:02:23 +0000426 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000427#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
428
drhe89b2912015-03-03 20:42:01 +0000429#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000430 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000431#else
drh58ad5802011-03-23 22:02:23 +0000432 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000433#endif
434#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
435 aSyscall[12].pCurrent)
436
437#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000438 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000439#else
drh58ad5802011-03-23 22:02:23 +0000440 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000441#endif
drhf9986d92016-04-18 13:09:55 +0000442#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off64_t))\
drhe562be52011-03-02 18:01:10 +0000443 aSyscall[13].pCurrent)
444
drh6226ca22015-11-24 15:06:28 +0000445 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000446#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000447
448#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000449 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000450#else
drh58ad5802011-03-23 22:02:23 +0000451 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000452#endif
dan0fd7d862011-03-29 10:04:23 +0000453#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000454
drh036ac7f2011-08-08 23:18:05 +0000455 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
456#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
457
drh90315a22011-08-10 01:52:12 +0000458 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
459#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
460
drh9ef6bc42011-11-04 02:24:02 +0000461 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
462#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
463
464 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
465#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
466
drhe2258a22016-01-12 00:37:55 +0000467#if defined(HAVE_FCHOWN)
drh6226ca22015-11-24 15:06:28 +0000468 { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
drhe2258a22016-01-12 00:37:55 +0000469#else
470 { "fchown", (sqlite3_syscall_ptr)0, 0 },
471#endif
dand3eaebd2012-02-13 08:50:23 +0000472#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000473
drh26f625f2018-02-19 16:34:31 +0000474#if defined(HAVE_FCHOWN)
drh6226ca22015-11-24 15:06:28 +0000475 { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
drh26f625f2018-02-19 16:34:31 +0000476#else
477 { "geteuid", (sqlite3_syscall_ptr)0, 0 },
478#endif
drh6226ca22015-11-24 15:06:28 +0000479#define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
480
dan4dd51442013-08-26 14:30:25 +0000481#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhe4a08f92016-01-08 19:17:30 +0000482 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
483#else
484 { "mmap", (sqlite3_syscall_ptr)0, 0 },
485#endif
drh6226ca22015-11-24 15:06:28 +0000486#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
dan893c0ff2013-03-25 19:05:07 +0000487
drhe4a08f92016-01-08 19:17:30 +0000488#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd1ab8062013-03-25 20:50:25 +0000489 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
drhe4a08f92016-01-08 19:17:30 +0000490#else
drha8299922016-01-08 22:31:00 +0000491 { "munmap", (sqlite3_syscall_ptr)0, 0 },
drhe4a08f92016-01-08 19:17:30 +0000492#endif
drh62be1fa2017-12-09 01:02:33 +0000493#define osMunmap ((int(*)(void*,size_t))aSyscall[23].pCurrent)
drhd1ab8062013-03-25 20:50:25 +0000494
drhe4a08f92016-01-08 19:17:30 +0000495#if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
drhd1ab8062013-03-25 20:50:25 +0000496 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
497#else
498 { "mremap", (sqlite3_syscall_ptr)0, 0 },
499#endif
drh6226ca22015-11-24 15:06:28 +0000500#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
501
drh24dbeae2016-01-08 22:18:00 +0000502#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
danbc760632014-03-20 09:42:09 +0000503 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
drh24dbeae2016-01-08 22:18:00 +0000504#else
505 { "getpagesize", (sqlite3_syscall_ptr)0, 0 },
506#endif
drh6226ca22015-11-24 15:06:28 +0000507#define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
danbc760632014-03-20 09:42:09 +0000508
drhe2258a22016-01-12 00:37:55 +0000509#if defined(HAVE_READLINK)
dan245fdc62015-10-31 17:58:33 +0000510 { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
drhe2258a22016-01-12 00:37:55 +0000511#else
512 { "readlink", (sqlite3_syscall_ptr)0, 0 },
513#endif
drh6226ca22015-11-24 15:06:28 +0000514#define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
dan245fdc62015-10-31 17:58:33 +0000515
danaf1b36b2016-01-25 18:43:05 +0000516#if defined(HAVE_LSTAT)
517 { "lstat", (sqlite3_syscall_ptr)lstat, 0 },
518#else
519 { "lstat", (sqlite3_syscall_ptr)0, 0 },
520#endif
dancaf6b152016-01-25 18:05:49 +0000521#define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
dan702eec12014-06-23 10:04:58 +0000522
drhb5d013e2017-10-25 16:14:12 +0000523#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
danefe16972017-07-20 19:49:14 +0000524 { "ioctl", (sqlite3_syscall_ptr)ioctl, 0 },
drhb5d013e2017-10-25 16:14:12 +0000525#else
526 { "ioctl", (sqlite3_syscall_ptr)0, 0 },
527#endif
dan9d709542017-07-21 21:06:24 +0000528#define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent)
danefe16972017-07-20 19:49:14 +0000529
drhe562be52011-03-02 18:01:10 +0000530}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000531
drh6226ca22015-11-24 15:06:28 +0000532
533/*
534** On some systems, calls to fchown() will trigger a message in a security
535** log if they come from non-root processes. So avoid calling fchown() if
536** we are not running as root.
537*/
538static int robustFchown(int fd, uid_t uid, gid_t gid){
drhe2258a22016-01-12 00:37:55 +0000539#if defined(HAVE_FCHOWN)
drh6226ca22015-11-24 15:06:28 +0000540 return osGeteuid() ? 0 : osFchown(fd,uid,gid);
drhe2258a22016-01-12 00:37:55 +0000541#else
542 return 0;
drh6226ca22015-11-24 15:06:28 +0000543#endif
544}
545
drh99ab3b12011-03-02 15:09:07 +0000546/*
547** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000548** "unix" VFSes. Return SQLITE_OK opon successfully updating the
549** system call pointer, or SQLITE_NOTFOUND if there is no configurable
550** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000551*/
552static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000553 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
554 const char *zName, /* Name of system call to override */
555 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000556){
drh58ad5802011-03-23 22:02:23 +0000557 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000558 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000559
560 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000561 if( zName==0 ){
562 /* If no zName is given, restore all system calls to their default
563 ** settings and return NULL
564 */
dan51438a72011-04-02 17:00:47 +0000565 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000566 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
567 if( aSyscall[i].pDefault ){
568 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000569 }
570 }
571 }else{
572 /* If zName is specified, operate on only the one system call
573 ** specified.
574 */
575 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
576 if( strcmp(zName, aSyscall[i].zName)==0 ){
577 if( aSyscall[i].pDefault==0 ){
578 aSyscall[i].pDefault = aSyscall[i].pCurrent;
579 }
drh1df30962011-03-02 19:06:42 +0000580 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000581 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
582 aSyscall[i].pCurrent = pNewFunc;
583 break;
584 }
585 }
586 }
587 return rc;
588}
589
drh1df30962011-03-02 19:06:42 +0000590/*
591** Return the value of a system call. Return NULL if zName is not a
592** recognized system call name. NULL is also returned if the system call
593** is currently undefined.
594*/
drh58ad5802011-03-23 22:02:23 +0000595static sqlite3_syscall_ptr unixGetSystemCall(
596 sqlite3_vfs *pNotUsed,
597 const char *zName
598){
599 unsigned int i;
600
601 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000602 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
603 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
604 }
605 return 0;
606}
607
608/*
609** Return the name of the first system call after zName. If zName==NULL
610** then return the name of the first system call. Return NULL if zName
611** is the last system call or if zName is not the name of a valid
612** system call.
613*/
614static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000615 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000616
617 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000618 if( zName ){
619 for(i=0; i<ArraySize(aSyscall)-1; i++){
620 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000621 }
622 }
dan0fd7d862011-03-29 10:04:23 +0000623 for(i++; i<ArraySize(aSyscall); i++){
624 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000625 }
626 return 0;
627}
628
drhad4f1e52011-03-04 15:43:57 +0000629/*
drh77a3fdc2013-08-30 14:24:12 +0000630** Do not accept any file descriptor less than this value, in order to avoid
631** opening database file using file descriptors that are commonly used for
632** standard input, output, and error.
633*/
634#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
635# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
636#endif
637
638/*
drh8c815d12012-02-13 20:16:37 +0000639** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000640** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000641**
642** If the file creation mode "m" is 0 then set it to the default for
643** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
644** 0644) as modified by the system umask. If m is not 0, then
645** make the file creation mode be exactly m ignoring the umask.
646**
647** The m parameter will be non-zero only when creating -wal, -journal,
648** and -shm files. We want those files to have *exactly* the same
649** permissions as their original database, unadulterated by the umask.
650** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
651** transaction crashes and leaves behind hot journals, then any
652** process that is able to write to the database will also be able to
653** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000654*/
drh8c815d12012-02-13 20:16:37 +0000655static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000656 int fd;
drhe1186ab2013-01-04 20:45:13 +0000657 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5128d002013-08-30 06:20:23 +0000658 while(1){
drh5adc60b2012-04-14 13:25:11 +0000659#if defined(O_CLOEXEC)
660 fd = osOpen(z,f|O_CLOEXEC,m2);
661#else
662 fd = osOpen(z,f,m2);
663#endif
drh5128d002013-08-30 06:20:23 +0000664 if( fd<0 ){
665 if( errno==EINTR ) continue;
666 break;
667 }
drh77a3fdc2013-08-30 14:24:12 +0000668 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
drh5128d002013-08-30 06:20:23 +0000669 osClose(fd);
670 sqlite3_log(SQLITE_WARNING,
671 "attempt to open \"%s\" as file descriptor %d", z, fd);
672 fd = -1;
673 if( osOpen("/dev/null", f, m)<0 ) break;
674 }
drhe1186ab2013-01-04 20:45:13 +0000675 if( fd>=0 ){
676 if( m!=0 ){
677 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000678 if( osFstat(fd, &statbuf)==0
679 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000680 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000681 ){
drhe1186ab2013-01-04 20:45:13 +0000682 osFchmod(fd, m);
683 }
684 }
drh5adc60b2012-04-14 13:25:11 +0000685#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000686 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000687#endif
drhe1186ab2013-01-04 20:45:13 +0000688 }
drh5adc60b2012-04-14 13:25:11 +0000689 return fd;
drhad4f1e52011-03-04 15:43:57 +0000690}
danielk197713adf8a2004-06-03 16:08:41 +0000691
drh107886a2008-11-21 22:21:50 +0000692/*
dan9359c7b2009-08-21 08:29:10 +0000693** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000694** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000695** vxworksFileId objects used by this file, all of which may be
696** shared by multiple threads.
697**
698** Function unixMutexHeld() is used to assert() that the global mutex
699** is held when required. This function is only used as part of assert()
700** statements. e.g.
701**
702** unixEnterMutex()
703** assert( unixMutexHeld() );
704** unixEnterLeave()
drh095908e2018-08-13 20:46:18 +0000705**
706** To prevent deadlock, the global unixBigLock must must be acquired
707** before the unixInodeInfo.pLockMutex mutex, if both are held. It is
708** OK to get the pLockMutex without holding unixBigLock first, but if
709** that happens, the unixBigLock mutex must not be acquired until after
710** pLockMutex is released.
711**
712** OK: enter(unixBigLock), enter(pLockInfo)
713** OK: enter(unixBigLock)
714** OK: enter(pLockInfo)
715** ERROR: enter(pLockInfo), enter(unixBigLock)
drh107886a2008-11-21 22:21:50 +0000716*/
drh56115892018-02-05 16:39:12 +0000717static sqlite3_mutex *unixBigLock = 0;
drh107886a2008-11-21 22:21:50 +0000718static void unixEnterMutex(void){
drh095908e2018-08-13 20:46:18 +0000719 assert( sqlite3_mutex_notheld(unixBigLock) ); /* Not a recursive mutex */
drh56115892018-02-05 16:39:12 +0000720 sqlite3_mutex_enter(unixBigLock);
drh107886a2008-11-21 22:21:50 +0000721}
722static void unixLeaveMutex(void){
drh095908e2018-08-13 20:46:18 +0000723 assert( sqlite3_mutex_held(unixBigLock) );
drh56115892018-02-05 16:39:12 +0000724 sqlite3_mutex_leave(unixBigLock);
drh107886a2008-11-21 22:21:50 +0000725}
dan9359c7b2009-08-21 08:29:10 +0000726#ifdef SQLITE_DEBUG
727static int unixMutexHeld(void) {
drh56115892018-02-05 16:39:12 +0000728 return sqlite3_mutex_held(unixBigLock);
dan9359c7b2009-08-21 08:29:10 +0000729}
730#endif
drh107886a2008-11-21 22:21:50 +0000731
drh734c9862008-11-28 15:37:20 +0000732
mistachkinfb383e92015-04-16 03:24:38 +0000733#ifdef SQLITE_HAVE_OS_TRACE
drh734c9862008-11-28 15:37:20 +0000734/*
735** Helper function for printing out trace information from debugging
peter.d.reid60ec9142014-09-06 16:39:46 +0000736** binaries. This returns the string representation of the supplied
drh734c9862008-11-28 15:37:20 +0000737** integer lock-type.
738*/
drh308c2a52010-05-14 11:30:18 +0000739static const char *azFileLock(int eFileLock){
740 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000741 case NO_LOCK: return "NONE";
742 case SHARED_LOCK: return "SHARED";
743 case RESERVED_LOCK: return "RESERVED";
744 case PENDING_LOCK: return "PENDING";
745 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000746 }
747 return "ERROR";
748}
749#endif
750
751#ifdef SQLITE_LOCK_TRACE
752/*
753** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000754**
drh734c9862008-11-28 15:37:20 +0000755** This routine is used for troubleshooting locks on multithreaded
756** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
757** command-line option on the compiler. This code is normally
758** turned off.
759*/
760static int lockTrace(int fd, int op, struct flock *p){
761 char *zOpName, *zType;
762 int s;
763 int savedErrno;
764 if( op==F_GETLK ){
765 zOpName = "GETLK";
766 }else if( op==F_SETLK ){
767 zOpName = "SETLK";
768 }else{
drh99ab3b12011-03-02 15:09:07 +0000769 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000770 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
771 return s;
772 }
773 if( p->l_type==F_RDLCK ){
774 zType = "RDLCK";
775 }else if( p->l_type==F_WRLCK ){
776 zType = "WRLCK";
777 }else if( p->l_type==F_UNLCK ){
778 zType = "UNLCK";
779 }else{
780 assert( 0 );
781 }
782 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000783 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000784 savedErrno = errno;
785 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
786 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
787 (int)p->l_pid, s);
788 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
789 struct flock l2;
790 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000791 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000792 if( l2.l_type==F_RDLCK ){
793 zType = "RDLCK";
794 }else if( l2.l_type==F_WRLCK ){
795 zType = "WRLCK";
796 }else if( l2.l_type==F_UNLCK ){
797 zType = "UNLCK";
798 }else{
799 assert( 0 );
800 }
801 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
802 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
803 }
804 errno = savedErrno;
805 return s;
806}
drh99ab3b12011-03-02 15:09:07 +0000807#undef osFcntl
808#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000809#endif /* SQLITE_LOCK_TRACE */
810
drhff812312011-02-23 13:33:46 +0000811/*
812** Retry ftruncate() calls that fail due to EINTR
dan2ee53412014-09-06 16:49:40 +0000813**
drhe6d41732015-02-21 00:49:00 +0000814** All calls to ftruncate() within this file should be made through
815** this wrapper. On the Android platform, bypassing the logic below
816** could lead to a corrupt database.
drhff812312011-02-23 13:33:46 +0000817*/
drhff812312011-02-23 13:33:46 +0000818static int robust_ftruncate(int h, sqlite3_int64 sz){
819 int rc;
dan2ee53412014-09-06 16:49:40 +0000820#ifdef __ANDROID__
821 /* On Android, ftruncate() always uses 32-bit offsets, even if
822 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
dan524a7332014-09-06 17:06:13 +0000823 ** truncate a file to any size larger than 2GiB. Silently ignore any
dan2ee53412014-09-06 16:49:40 +0000824 ** such attempts. */
825 if( sz>(sqlite3_int64)0x7FFFFFFF ){
826 rc = SQLITE_OK;
827 }else
828#endif
drh99ab3b12011-03-02 15:09:07 +0000829 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000830 return rc;
831}
drh734c9862008-11-28 15:37:20 +0000832
833/*
834** This routine translates a standard POSIX errno code into something
835** useful to the clients of the sqlite3 functions. Specifically, it is
836** intended to translate a variety of "try again" errors into SQLITE_BUSY
837** and a variety of "please close the file descriptor NOW" errors into
838** SQLITE_IOERR
839**
840** Errors during initialization of locks, or file system support for locks,
841** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
842*/
843static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
drh91c4def2015-11-25 14:00:07 +0000844 assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
845 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
846 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
847 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
drh734c9862008-11-28 15:37:20 +0000848 switch (posixError) {
drh91c4def2015-11-25 14:00:07 +0000849 case EACCES:
drh734c9862008-11-28 15:37:20 +0000850 case EAGAIN:
851 case ETIMEDOUT:
852 case EBUSY:
853 case EINTR:
854 case ENOLCK:
855 /* random NFS retry error, unless during file system support
856 * introspection, in which it actually means what it says */
857 return SQLITE_BUSY;
858
drh734c9862008-11-28 15:37:20 +0000859 case EPERM:
860 return SQLITE_PERM;
861
drh734c9862008-11-28 15:37:20 +0000862 default:
863 return sqliteIOErr;
864 }
865}
866
867
drh734c9862008-11-28 15:37:20 +0000868/******************************************************************************
869****************** Begin Unique File ID Utility Used By VxWorks ***************
870**
871** On most versions of unix, we can get a unique ID for a file by concatenating
872** the device number and the inode number. But this does not work on VxWorks.
873** On VxWorks, a unique file id must be based on the canonical filename.
874**
875** A pointer to an instance of the following structure can be used as a
876** unique file ID in VxWorks. Each instance of this structure contains
877** a copy of the canonical filename. There is also a reference count.
878** The structure is reclaimed when the number of pointers to it drops to
879** zero.
880**
881** There are never very many files open at one time and lookups are not
882** a performance-critical path, so it is sufficient to put these
883** structures on a linked list.
884*/
885struct vxworksFileId {
886 struct vxworksFileId *pNext; /* Next in a list of them all */
887 int nRef; /* Number of references to this one */
888 int nName; /* Length of the zCanonicalName[] string */
889 char *zCanonicalName; /* Canonical filename */
890};
891
892#if OS_VXWORKS
893/*
drh9b35ea62008-11-29 02:20:26 +0000894** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000895** variable:
896*/
897static struct vxworksFileId *vxworksFileList = 0;
898
899/*
900** Simplify a filename into its canonical form
901** by making the following changes:
902**
903** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000904** * convert /./ into just /
905** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000906**
907** Changes are made in-place. Return the new name length.
908**
909** The original filename is in z[0..n-1]. Return the number of
910** characters in the simplified name.
911*/
912static int vxworksSimplifyName(char *z, int n){
913 int i, j;
914 while( n>1 && z[n-1]=='/' ){ n--; }
915 for(i=j=0; i<n; i++){
916 if( z[i]=='/' ){
917 if( z[i+1]=='/' ) continue;
918 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
919 i += 1;
920 continue;
921 }
922 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
923 while( j>0 && z[j-1]!='/' ){ j--; }
924 if( j>0 ){ j--; }
925 i += 2;
926 continue;
927 }
928 }
929 z[j++] = z[i];
930 }
931 z[j] = 0;
932 return j;
933}
934
935/*
936** Find a unique file ID for the given absolute pathname. Return
937** a pointer to the vxworksFileId object. This pointer is the unique
938** file ID.
939**
940** The nRef field of the vxworksFileId object is incremented before
941** the object is returned. A new vxworksFileId object is created
942** and added to the global list if necessary.
943**
944** If a memory allocation error occurs, return NULL.
945*/
946static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
947 struct vxworksFileId *pNew; /* search key and new file ID */
948 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
949 int n; /* Length of zAbsoluteName string */
950
951 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000952 n = (int)strlen(zAbsoluteName);
drhf3cdcdc2015-04-29 16:50:28 +0000953 pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
drh734c9862008-11-28 15:37:20 +0000954 if( pNew==0 ) return 0;
955 pNew->zCanonicalName = (char*)&pNew[1];
956 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
957 n = vxworksSimplifyName(pNew->zCanonicalName, n);
958
959 /* Search for an existing entry that matching the canonical name.
960 ** If found, increment the reference count and return a pointer to
961 ** the existing file ID.
962 */
963 unixEnterMutex();
964 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
965 if( pCandidate->nName==n
966 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
967 ){
968 sqlite3_free(pNew);
969 pCandidate->nRef++;
970 unixLeaveMutex();
971 return pCandidate;
972 }
973 }
974
975 /* No match was found. We will make a new file ID */
976 pNew->nRef = 1;
977 pNew->nName = n;
978 pNew->pNext = vxworksFileList;
979 vxworksFileList = pNew;
980 unixLeaveMutex();
981 return pNew;
982}
983
984/*
985** Decrement the reference count on a vxworksFileId object. Free
986** the object when the reference count reaches zero.
987*/
988static void vxworksReleaseFileId(struct vxworksFileId *pId){
989 unixEnterMutex();
990 assert( pId->nRef>0 );
991 pId->nRef--;
992 if( pId->nRef==0 ){
993 struct vxworksFileId **pp;
994 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
995 assert( *pp==pId );
996 *pp = pId->pNext;
997 sqlite3_free(pId);
998 }
999 unixLeaveMutex();
1000}
1001#endif /* OS_VXWORKS */
1002/*************** End of Unique File ID Utility Used By VxWorks ****************
1003******************************************************************************/
1004
1005
1006/******************************************************************************
1007*************************** Posix Advisory Locking ****************************
1008**
drh9b35ea62008-11-29 02:20:26 +00001009** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +00001010** section 6.5.2.2 lines 483 through 490 specify that when a process
1011** sets or clears a lock, that operation overrides any prior locks set
1012** by the same process. It does not explicitly say so, but this implies
1013** that it overrides locks set by the same process using a different
1014** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +00001015**
1016** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +00001017** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
1018**
1019** Suppose ./file1 and ./file2 are really the same file (because
1020** one is a hard or symbolic link to the other) then if you set
1021** an exclusive lock on fd1, then try to get an exclusive lock
1022** on fd2, it works. I would have expected the second lock to
1023** fail since there was already a lock on the file due to fd1.
1024** But not so. Since both locks came from the same process, the
1025** second overrides the first, even though they were on different
1026** file descriptors opened on different file names.
1027**
drh734c9862008-11-28 15:37:20 +00001028** This means that we cannot use POSIX locks to synchronize file access
1029** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +00001030** to synchronize access for threads in separate processes, but not
1031** threads within the same process.
1032**
1033** To work around the problem, SQLite has to manage file locks internally
1034** on its own. Whenever a new database is opened, we have to find the
1035** specific inode of the database file (the inode is determined by the
1036** st_dev and st_ino fields of the stat structure that fstat() fills in)
1037** and check for locks already existing on that inode. When locks are
1038** created or removed, we have to look at our own internal record of the
1039** locks to see if another thread has previously set a lock on that same
1040** inode.
1041**
drh9b35ea62008-11-29 02:20:26 +00001042** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
1043** For VxWorks, we have to use the alternative unique ID system based on
1044** canonical filename and implemented in the previous division.)
1045**
danielk1977ad94b582007-08-20 06:44:22 +00001046** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +00001047** descriptor. It is now a structure that holds the integer file
1048** descriptor and a pointer to a structure that describes the internal
1049** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +00001050** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +00001051** point to the same locking structure. The locking structure keeps
1052** a reference count (so we will know when to delete it) and a "cnt"
1053** field that tells us its internal lock status. cnt==0 means the
1054** file is unlocked. cnt==-1 means the file has an exclusive lock.
1055** cnt>0 means there are cnt shared locks on the file.
1056**
1057** Any attempt to lock or unlock a file first checks the locking
1058** structure. The fcntl() system call is only invoked to set a
1059** POSIX lock if the internal lock structure transitions between
1060** a locked and an unlocked state.
1061**
drh734c9862008-11-28 15:37:20 +00001062** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +00001063**
1064** If you close a file descriptor that points to a file that has locks,
1065** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +00001066** released. To work around this problem, each unixInodeInfo object
1067** maintains a count of the number of pending locks on tha inode.
1068** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +00001069** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +00001070** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +00001071** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +00001072** be closed and that list is walked (and cleared) when the last lock
1073** clears.
1074**
drh9b35ea62008-11-29 02:20:26 +00001075** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +00001076**
drh9b35ea62008-11-29 02:20:26 +00001077** Many older versions of linux use the LinuxThreads library which is
1078** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +00001079** A cannot be modified or overridden by a different thread B.
1080** Only thread A can modify the lock. Locking behavior is correct
1081** if the appliation uses the newer Native Posix Thread Library (NPTL)
1082** on linux - with NPTL a lock created by thread A can override locks
1083** in thread B. But there is no way to know at compile-time which
1084** threading library is being used. So there is no way to know at
1085** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001086** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001087** current process.
drh5fdae772004-06-29 03:29:00 +00001088**
drh8af6c222010-05-14 12:43:01 +00001089** SQLite used to support LinuxThreads. But support for LinuxThreads
1090** was dropped beginning with version 3.7.0. SQLite will still work with
1091** LinuxThreads provided that (1) there is no more than one connection
1092** per database file in the same process and (2) database connections
1093** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001094*/
1095
1096/*
1097** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001098** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001099*/
1100struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001101 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001102#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001103 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001104#else
drh25ef7f52016-12-05 20:06:45 +00001105 /* We are told that some versions of Android contain a bug that
1106 ** sizes ino_t at only 32-bits instead of 64-bits. (See
1107 ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
1108 ** To work around this, always allocate 64-bits for the inode number.
1109 ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
1110 ** but that should not be a big deal. */
1111 /* WAS: ino_t ino; */
1112 u64 ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001113#endif
1114};
1115
1116/*
drhbbd42a62004-05-22 17:41:58 +00001117** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001118** inode. Or, on LinuxThreads, there is one of these structures for
1119** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001120**
danielk1977ad94b582007-08-20 06:44:22 +00001121** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001122** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001123** object keeps a count of the number of unixFile pointing to it.
drhda6dc242018-07-23 21:10:37 +00001124**
1125** Mutex rules:
1126**
drh095908e2018-08-13 20:46:18 +00001127** (1) Only the pLockMutex mutex must be held in order to read or write
drhda6dc242018-07-23 21:10:37 +00001128** any of the locking fields:
drhef52b362018-08-13 22:50:34 +00001129** nShared, nLock, eFileLock, bProcessLock, pUnused
drhda6dc242018-07-23 21:10:37 +00001130**
1131** (2) When nRef>0, then the following fields are unchanging and can
1132** be read (but not written) without holding any mutex:
1133** fileId, pLockMutex
1134**
drhef52b362018-08-13 22:50:34 +00001135** (3) With the exceptions above, all the fields may only be read
drhda6dc242018-07-23 21:10:37 +00001136** or written while holding the global unixBigLock mutex.
drh095908e2018-08-13 20:46:18 +00001137**
1138** Deadlock prevention: The global unixBigLock mutex may not
1139** be acquired while holding the pLockMutex mutex. If both unixBigLock
1140** and pLockMutex are needed, then unixBigLock must be acquired first.
drhbbd42a62004-05-22 17:41:58 +00001141*/
drh8af6c222010-05-14 12:43:01 +00001142struct unixInodeInfo {
1143 struct unixFileId fileId; /* The lookup key */
drhda6dc242018-07-23 21:10:37 +00001144 sqlite3_mutex *pLockMutex; /* Hold this mutex for... */
1145 int nShared; /* Number of SHARED locks held */
1146 int nLock; /* Number of outstanding file locks */
1147 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1148 unsigned char bProcessLock; /* An exclusive process lock is held */
drhef52b362018-08-13 22:50:34 +00001149 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
drh734c9862008-11-28 15:37:20 +00001150 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001151 unixShmNode *pShmNode; /* Shared memory associated with this inode */
drhd91c68f2010-05-14 14:52:25 +00001152 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1153 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001154#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001155 unsigned long long sharedByte; /* for AFP simulated shared lock */
1156#endif
drh6c7d5c52008-11-21 20:32:33 +00001157#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001158 sem_t *pSem; /* Named POSIX semaphore */
1159 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001160#endif
drhbbd42a62004-05-22 17:41:58 +00001161};
1162
drhda0e7682008-07-30 15:27:54 +00001163/*
drh8af6c222010-05-14 12:43:01 +00001164** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001165*/
drhc68886b2017-08-18 16:09:52 +00001166static unixInodeInfo *inodeList = 0; /* All unixInodeInfo objects */
drh095908e2018-08-13 20:46:18 +00001167
1168#ifdef SQLITE_DEBUG
1169/*
1170** True if the inode mutex is held, or not. Used only within assert()
1171** to help verify correct mutex usage.
1172*/
1173int unixFileMutexHeld(unixFile *pFile){
1174 assert( pFile->pInode );
1175 return sqlite3_mutex_held(pFile->pInode->pLockMutex);
1176}
1177int unixFileMutexNotheld(unixFile *pFile){
1178 assert( pFile->pInode );
1179 return sqlite3_mutex_notheld(pFile->pInode->pLockMutex);
1180}
1181#endif
drh5fdae772004-06-29 03:29:00 +00001182
drh5fdae772004-06-29 03:29:00 +00001183/*
dane18d4952011-02-21 11:46:24 +00001184**
drhaaeaa182015-11-24 15:12:47 +00001185** This function - unixLogErrorAtLine(), is only ever called via the macro
dane18d4952011-02-21 11:46:24 +00001186** unixLogError().
1187**
1188** It is invoked after an error occurs in an OS function and errno has been
1189** set. It logs a message using sqlite3_log() containing the current value of
1190** errno and, if possible, the human-readable equivalent from strerror() or
1191** strerror_r().
1192**
1193** The first argument passed to the macro should be the error code that
1194** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1195** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001196** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001197** if any.
1198*/
drh0e9365c2011-03-02 02:08:13 +00001199#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1200static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001201 int errcode, /* SQLite error code */
1202 const char *zFunc, /* Name of OS function that failed */
1203 const char *zPath, /* File path associated with error */
1204 int iLine /* Source line number where error occurred */
1205){
1206 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001207 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001208
1209 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1210 ** the strerror() function to obtain the human-readable error message
1211 ** equivalent to errno. Otherwise, use strerror_r().
1212 */
1213#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1214 char aErr[80];
1215 memset(aErr, 0, sizeof(aErr));
1216 zErr = aErr;
1217
1218 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001219 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001220 ** returns a pointer to a buffer containing the error message. That pointer
1221 ** may point to aErr[], or it may point to some static storage somewhere.
1222 ** Otherwise, assume that the system provides the POSIX version of
1223 ** strerror_r(), which always writes an error message into aErr[].
1224 **
1225 ** If the code incorrectly assumes that it is the POSIX version that is
1226 ** available, the error message will often be an empty string. Not a
1227 ** huge problem. Incorrectly concluding that the GNU version is available
1228 ** could lead to a segfault though.
1229 */
1230#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1231 zErr =
1232# endif
drh0e9365c2011-03-02 02:08:13 +00001233 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001234
1235#elif SQLITE_THREADSAFE
1236 /* This is a threadsafe build, but strerror_r() is not available. */
1237 zErr = "";
1238#else
1239 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001240 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001241#endif
1242
drh0e9365c2011-03-02 02:08:13 +00001243 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001244 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001245 "os_unix.c:%d: (%d) %s(%s) - %s",
1246 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001247 );
1248
1249 return errcode;
1250}
1251
drh0e9365c2011-03-02 02:08:13 +00001252/*
1253** Close a file descriptor.
1254**
1255** We assume that close() almost always works, since it is only in a
1256** very sick application or on a very sick platform that it might fail.
1257** If it does fail, simply leak the file descriptor, but do log the
1258** error.
1259**
1260** Note that it is not safe to retry close() after EINTR since the
1261** file descriptor might have already been reused by another thread.
1262** So we don't even try to recover from an EINTR. Just log the error
1263** and move on.
1264*/
1265static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001266 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001267 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1268 pFile ? pFile->zPath : 0, lineno);
1269 }
1270}
dane18d4952011-02-21 11:46:24 +00001271
1272/*
drhe6d41732015-02-21 00:49:00 +00001273** Set the pFile->lastErrno. Do this in a subroutine as that provides
1274** a convenient place to set a breakpoint.
drh4bf66fd2015-02-19 02:43:02 +00001275*/
1276static void storeLastErrno(unixFile *pFile, int error){
1277 pFile->lastErrno = error;
1278}
1279
1280/*
danb0ac3e32010-06-16 10:55:42 +00001281** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001282*/
drh0e9365c2011-03-02 02:08:13 +00001283static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001284 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001285 UnixUnusedFd *p;
1286 UnixUnusedFd *pNext;
drhef52b362018-08-13 22:50:34 +00001287 assert( unixFileMutexHeld(pFile) );
danb0ac3e32010-06-16 10:55:42 +00001288 for(p=pInode->pUnused; p; p=pNext){
1289 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001290 robust_close(pFile, p->fd, __LINE__);
1291 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001292 }
drh0e9365c2011-03-02 02:08:13 +00001293 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001294}
1295
1296/*
drh8af6c222010-05-14 12:43:01 +00001297** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001298**
1299** The mutex entered using the unixEnterMutex() function must be held
1300** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001301*/
danb0ac3e32010-06-16 10:55:42 +00001302static void releaseInodeInfo(unixFile *pFile){
1303 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001304 assert( unixMutexHeld() );
drh095908e2018-08-13 20:46:18 +00001305 assert( unixFileMutexNotheld(pFile) );
dan661d71a2011-03-30 19:08:03 +00001306 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001307 pInode->nRef--;
1308 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001309 assert( pInode->pShmNode==0 );
drhef52b362018-08-13 22:50:34 +00001310 sqlite3_mutex_enter(pInode->pLockMutex);
danb0ac3e32010-06-16 10:55:42 +00001311 closePendingFds(pFile);
drhef52b362018-08-13 22:50:34 +00001312 sqlite3_mutex_leave(pInode->pLockMutex);
drh8af6c222010-05-14 12:43:01 +00001313 if( pInode->pPrev ){
1314 assert( pInode->pPrev->pNext==pInode );
1315 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001316 }else{
drh8af6c222010-05-14 12:43:01 +00001317 assert( inodeList==pInode );
1318 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001319 }
drh8af6c222010-05-14 12:43:01 +00001320 if( pInode->pNext ){
1321 assert( pInode->pNext->pPrev==pInode );
1322 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001323 }
drhda6dc242018-07-23 21:10:37 +00001324 sqlite3_mutex_free(pInode->pLockMutex);
drh8af6c222010-05-14 12:43:01 +00001325 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001326 }
drhbbd42a62004-05-22 17:41:58 +00001327 }
1328}
1329
1330/*
drh8af6c222010-05-14 12:43:01 +00001331** Given a file descriptor, locate the unixInodeInfo object that
1332** describes that file descriptor. Create a new one if necessary. The
1333** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001334**
dan9359c7b2009-08-21 08:29:10 +00001335** The mutex entered using the unixEnterMutex() function must be held
1336** when this function is called.
1337**
drh6c7d5c52008-11-21 20:32:33 +00001338** Return an appropriate error code.
1339*/
drh8af6c222010-05-14 12:43:01 +00001340static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001341 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001342 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001343){
1344 int rc; /* System call return code */
1345 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001346 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1347 struct stat statbuf; /* Low-level file information */
1348 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001349
dan9359c7b2009-08-21 08:29:10 +00001350 assert( unixMutexHeld() );
1351
drh6c7d5c52008-11-21 20:32:33 +00001352 /* Get low-level information about the file that we can used to
1353 ** create a unique name for the file.
1354 */
1355 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001356 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001357 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001358 storeLastErrno(pFile, errno);
drh40fe8d32015-11-30 20:36:26 +00001359#if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
drh6c7d5c52008-11-21 20:32:33 +00001360 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1361#endif
1362 return SQLITE_IOERR;
1363 }
1364
drheb0d74f2009-02-03 15:27:02 +00001365#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001366 /* On OS X on an msdos filesystem, the inode number is reported
1367 ** incorrectly for zero-size files. See ticket #3260. To work
1368 ** around this problem (we consider it a bug in OS X, not SQLite)
1369 ** we always increase the file size to 1 by writing a single byte
1370 ** prior to accessing the inode number. The one byte written is
1371 ** an ASCII 'S' character which also happens to be the first byte
1372 ** in the header of every SQLite database. In this way, if there
1373 ** is a race condition such that another thread has already populated
1374 ** the first page of the database, no damage is done.
1375 */
drh7ed97b92010-01-20 13:07:21 +00001376 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001377 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001378 if( rc!=1 ){
drh4bf66fd2015-02-19 02:43:02 +00001379 storeLastErrno(pFile, errno);
drheb0d74f2009-02-03 15:27:02 +00001380 return SQLITE_IOERR;
1381 }
drh99ab3b12011-03-02 15:09:07 +00001382 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001383 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001384 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001385 return SQLITE_IOERR;
1386 }
1387 }
drheb0d74f2009-02-03 15:27:02 +00001388#endif
drh6c7d5c52008-11-21 20:32:33 +00001389
drh8af6c222010-05-14 12:43:01 +00001390 memset(&fileId, 0, sizeof(fileId));
1391 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001392#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001393 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001394#else
drh25ef7f52016-12-05 20:06:45 +00001395 fileId.ino = (u64)statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001396#endif
drh8af6c222010-05-14 12:43:01 +00001397 pInode = inodeList;
1398 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1399 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001400 }
drh8af6c222010-05-14 12:43:01 +00001401 if( pInode==0 ){
drhf3cdcdc2015-04-29 16:50:28 +00001402 pInode = sqlite3_malloc64( sizeof(*pInode) );
drh8af6c222010-05-14 12:43:01 +00001403 if( pInode==0 ){
mistachkinfad30392016-02-13 23:43:46 +00001404 return SQLITE_NOMEM_BKPT;
drh6c7d5c52008-11-21 20:32:33 +00001405 }
drh8af6c222010-05-14 12:43:01 +00001406 memset(pInode, 0, sizeof(*pInode));
1407 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
drh6886d6d2018-07-23 22:55:10 +00001408 if( sqlite3GlobalConfig.bCoreMutex ){
1409 pInode->pLockMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
1410 if( pInode->pLockMutex==0 ){
1411 sqlite3_free(pInode);
1412 return SQLITE_NOMEM_BKPT;
1413 }
1414 }
drh8af6c222010-05-14 12:43:01 +00001415 pInode->nRef = 1;
1416 pInode->pNext = inodeList;
1417 pInode->pPrev = 0;
1418 if( inodeList ) inodeList->pPrev = pInode;
1419 inodeList = pInode;
1420 }else{
1421 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001422 }
drh8af6c222010-05-14 12:43:01 +00001423 *ppInode = pInode;
1424 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001425}
drh6c7d5c52008-11-21 20:32:33 +00001426
drhb959a012013-12-07 12:29:22 +00001427/*
1428** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1429*/
1430static int fileHasMoved(unixFile *pFile){
drh61ffea52014-08-12 12:19:25 +00001431#if OS_VXWORKS
1432 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1433#else
drhb959a012013-12-07 12:29:22 +00001434 struct stat buf;
1435 return pFile->pInode!=0 &&
drh25ef7f52016-12-05 20:06:45 +00001436 (osStat(pFile->zPath, &buf)!=0
1437 || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
drh91be7dc2014-08-11 13:53:30 +00001438#endif
drhb959a012013-12-07 12:29:22 +00001439}
1440
aswift5b1a2562008-08-22 00:22:35 +00001441
1442/*
drhfbc7e882013-04-11 01:16:15 +00001443** Check a unixFile that is a database. Verify the following:
1444**
1445** (1) There is exactly one hard link on the file
1446** (2) The file is not a symbolic link
1447** (3) The file has not been renamed or unlinked
1448**
1449** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1450*/
1451static void verifyDbFile(unixFile *pFile){
1452 struct stat buf;
1453 int rc;
drh86151e82015-12-08 14:37:16 +00001454
1455 /* These verifications occurs for the main database only */
1456 if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
1457
drhfbc7e882013-04-11 01:16:15 +00001458 rc = osFstat(pFile->h, &buf);
1459 if( rc!=0 ){
1460 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001461 return;
1462 }
drh6369bc32016-03-21 16:06:42 +00001463 if( buf.st_nlink==0 ){
drhfbc7e882013-04-11 01:16:15 +00001464 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001465 return;
1466 }
1467 if( buf.st_nlink>1 ){
1468 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001469 return;
1470 }
drhb959a012013-12-07 12:29:22 +00001471 if( fileHasMoved(pFile) ){
drhfbc7e882013-04-11 01:16:15 +00001472 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001473 return;
1474 }
1475}
1476
1477
1478/*
danielk197713adf8a2004-06-03 16:08:41 +00001479** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001480** file by this or any other process. If such a lock is held, set *pResOut
1481** to a non-zero value otherwise *pResOut is set to zero. The return value
1482** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001483*/
danielk1977861f7452008-06-05 11:39:11 +00001484static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001485 int rc = SQLITE_OK;
1486 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001487 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001488
danielk1977861f7452008-06-05 11:39:11 +00001489 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1490
drh054889e2005-11-30 03:20:31 +00001491 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00001492 assert( pFile->eFileLock<=SHARED_LOCK );
drhda6dc242018-07-23 21:10:37 +00001493 sqlite3_mutex_enter(pFile->pInode->pLockMutex);
danielk197713adf8a2004-06-03 16:08:41 +00001494
1495 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001496 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001497 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001498 }
1499
drh2ac3ee92004-06-07 16:27:46 +00001500 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001501 */
danielk197709480a92009-02-09 05:32:32 +00001502#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001503 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001504 struct flock lock;
1505 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001506 lock.l_start = RESERVED_BYTE;
1507 lock.l_len = 1;
1508 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001509 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1510 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001511 storeLastErrno(pFile, errno);
aswift5b1a2562008-08-22 00:22:35 +00001512 } else if( lock.l_type!=F_UNLCK ){
1513 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001514 }
1515 }
danielk197709480a92009-02-09 05:32:32 +00001516#endif
danielk197713adf8a2004-06-03 16:08:41 +00001517
drhda6dc242018-07-23 21:10:37 +00001518 sqlite3_mutex_leave(pFile->pInode->pLockMutex);
drh308c2a52010-05-14 11:30:18 +00001519 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001520
aswift5b1a2562008-08-22 00:22:35 +00001521 *pResOut = reserved;
1522 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001523}
1524
1525/*
drhf0119b22018-03-26 17:40:53 +00001526** Set a posix-advisory-lock.
1527**
1528** There are two versions of this routine. If compiled with
1529** SQLITE_ENABLE_SETLK_TIMEOUT then the routine has an extra parameter
1530** which is a pointer to a unixFile. If the unixFile->iBusyTimeout
1531** value is set, then it is the number of milliseconds to wait before
1532** failing the lock. The iBusyTimeout value is always reset back to
1533** zero on each call.
1534**
1535** If SQLITE_ENABLE_SETLK_TIMEOUT is not defined, then do a non-blocking
1536** attempt to set the lock.
1537*/
1538#ifndef SQLITE_ENABLE_SETLK_TIMEOUT
1539# define osSetPosixAdvisoryLock(h,x,t) osFcntl(h,F_SETLK,x)
1540#else
1541static int osSetPosixAdvisoryLock(
1542 int h, /* The file descriptor on which to take the lock */
1543 struct flock *pLock, /* The description of the lock */
1544 unixFile *pFile /* Structure holding timeout value */
1545){
1546 int rc = osFcntl(h,F_SETLK,pLock);
drhfd725632018-03-26 20:43:05 +00001547 while( rc<0 && pFile->iBusyTimeout>0 ){
drhf0119b22018-03-26 17:40:53 +00001548 /* On systems that support some kind of blocking file lock with a timeout,
1549 ** make appropriate changes here to invoke that blocking file lock. On
1550 ** generic posix, however, there is no such API. So we simply try the
1551 ** lock once every millisecond until either the timeout expires, or until
1552 ** the lock is obtained. */
drhfd725632018-03-26 20:43:05 +00001553 usleep(1000);
1554 rc = osFcntl(h,F_SETLK,pLock);
1555 pFile->iBusyTimeout--;
drhf0119b22018-03-26 17:40:53 +00001556 }
1557 return rc;
1558}
1559#endif /* SQLITE_ENABLE_SETLK_TIMEOUT */
1560
1561
1562/*
drha7e61d82011-03-12 17:02:57 +00001563** Attempt to set a system-lock on the file pFile. The lock is
1564** described by pLock.
1565**
drh77197112011-03-15 19:08:48 +00001566** If the pFile was opened read/write from unix-excl, then the only lock
1567** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001568** the first time any lock is attempted. All subsequent system locking
1569** operations become no-ops. Locking operations still happen internally,
1570** in order to coordinate access between separate database connections
1571** within this process, but all of that is handled in memory and the
1572** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001573**
1574** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1575** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1576** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001577**
1578** Zero is returned if the call completes successfully, or -1 if a call
1579** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001580*/
1581static int unixFileLock(unixFile *pFile, struct flock *pLock){
1582 int rc;
drh3cb93392011-03-12 18:10:44 +00001583 unixInodeInfo *pInode = pFile->pInode;
drh3cb93392011-03-12 18:10:44 +00001584 assert( pInode!=0 );
drhda6dc242018-07-23 21:10:37 +00001585 assert( sqlite3_mutex_held(pInode->pLockMutex) );
drh50358ad2015-12-02 01:04:33 +00001586 if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
drh3cb93392011-03-12 18:10:44 +00001587 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001588 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001589 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001590 lock.l_whence = SEEK_SET;
1591 lock.l_start = SHARED_FIRST;
1592 lock.l_len = SHARED_SIZE;
1593 lock.l_type = F_WRLCK;
drhf0119b22018-03-26 17:40:53 +00001594 rc = osSetPosixAdvisoryLock(pFile->h, &lock, pFile);
drha7e61d82011-03-12 17:02:57 +00001595 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001596 pInode->bProcessLock = 1;
1597 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001598 }else{
1599 rc = 0;
1600 }
1601 }else{
drhf0119b22018-03-26 17:40:53 +00001602 rc = osSetPosixAdvisoryLock(pFile->h, pLock, pFile);
drha7e61d82011-03-12 17:02:57 +00001603 }
1604 return rc;
1605}
1606
1607/*
drh308c2a52010-05-14 11:30:18 +00001608** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001609** of the following:
1610**
drh2ac3ee92004-06-07 16:27:46 +00001611** (1) SHARED_LOCK
1612** (2) RESERVED_LOCK
1613** (3) PENDING_LOCK
1614** (4) EXCLUSIVE_LOCK
1615**
drhb3e04342004-06-08 00:47:47 +00001616** Sometimes when requesting one lock state, additional lock states
1617** are inserted in between. The locking might fail on one of the later
1618** transitions leaving the lock state different from what it started but
1619** still short of its goal. The following chart shows the allowed
1620** transitions and the inserted intermediate states:
1621**
1622** UNLOCKED -> SHARED
1623** SHARED -> RESERVED
1624** SHARED -> (PENDING) -> EXCLUSIVE
1625** RESERVED -> (PENDING) -> EXCLUSIVE
1626** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001627**
drha6abd042004-06-09 17:37:22 +00001628** This routine will only increase a lock. Use the sqlite3OsUnlock()
1629** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001630*/
drh308c2a52010-05-14 11:30:18 +00001631static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001632 /* The following describes the implementation of the various locks and
1633 ** lock transitions in terms of the POSIX advisory shared and exclusive
1634 ** lock primitives (called read-locks and write-locks below, to avoid
1635 ** confusion with SQLite lock names). The algorithms are complicated
drhf878e6e2016-04-07 13:45:20 +00001636 ** slightly in order to be compatible with Windows95 systems simultaneously
danielk1977f42f25c2004-06-25 07:21:28 +00001637 ** accessing the same database file, in case that is ever required.
1638 **
1639 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1640 ** byte', each single bytes at well known offsets, and the 'shared byte
1641 ** range', a range of 510 bytes at a well known offset.
1642 **
1643 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
drhf878e6e2016-04-07 13:45:20 +00001644 ** byte'. If this is successful, 'shared byte range' is read-locked
1645 ** and the lock on the 'pending byte' released. (Legacy note: When
1646 ** SQLite was first developed, Windows95 systems were still very common,
1647 ** and Widnows95 lacks a shared-lock capability. So on Windows95, a
1648 ** single randomly selected by from the 'shared byte range' is locked.
1649 ** Windows95 is now pretty much extinct, but this work-around for the
1650 ** lack of shared-locks on Windows95 lives on, for backwards
1651 ** compatibility.)
danielk1977f42f25c2004-06-25 07:21:28 +00001652 **
danielk197790ba3bd2004-06-25 08:32:25 +00001653 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1654 ** A RESERVED lock is implemented by grabbing a write-lock on the
1655 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001656 **
1657 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001658 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1659 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1660 ** obtained, but existing SHARED locks are allowed to persist. A process
1661 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1662 ** This property is used by the algorithm for rolling back a journal file
1663 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001664 **
danielk197790ba3bd2004-06-25 08:32:25 +00001665 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1666 ** implemented by obtaining a write-lock on the entire 'shared byte
1667 ** range'. Since all other locks require a read-lock on one of the bytes
1668 ** within this range, this ensures that no other locks are held on the
1669 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001670 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001671 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001672 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001673 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001674 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001675 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001676
drh054889e2005-11-30 03:20:31 +00001677 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001678 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1679 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh91eb93c2015-03-03 19:56:20 +00001680 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001681 osGetpid(0)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001682
1683 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001684 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001685 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001686 */
drh308c2a52010-05-14 11:30:18 +00001687 if( pFile->eFileLock>=eFileLock ){
1688 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1689 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001690 return SQLITE_OK;
1691 }
1692
drh0c2694b2009-09-03 16:23:44 +00001693 /* Make sure the locking sequence is correct.
1694 ** (1) We never move from unlocked to anything higher than shared lock.
1695 ** (2) SQLite never explicitly requests a pendig lock.
1696 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001697 */
drh308c2a52010-05-14 11:30:18 +00001698 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1699 assert( eFileLock!=PENDING_LOCK );
1700 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001701
drh8af6c222010-05-14 12:43:01 +00001702 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001703 */
drh8af6c222010-05-14 12:43:01 +00001704 pInode = pFile->pInode;
drhda6dc242018-07-23 21:10:37 +00001705 sqlite3_mutex_enter(pInode->pLockMutex);
drh029b44b2006-01-15 00:13:15 +00001706
danielk1977ad94b582007-08-20 06:44:22 +00001707 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001708 ** handle that precludes the requested lock, return BUSY.
1709 */
drh8af6c222010-05-14 12:43:01 +00001710 if( (pFile->eFileLock!=pInode->eFileLock &&
1711 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001712 ){
1713 rc = SQLITE_BUSY;
1714 goto end_lock;
1715 }
1716
1717 /* If a SHARED lock is requested, and some thread using this PID already
1718 ** has a SHARED or RESERVED lock, then increment reference counts and
1719 ** return SQLITE_OK.
1720 */
drh308c2a52010-05-14 11:30:18 +00001721 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001722 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001723 assert( eFileLock==SHARED_LOCK );
1724 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001725 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001726 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001727 pInode->nShared++;
1728 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001729 goto end_lock;
1730 }
1731
danielk19779a1d0ab2004-06-01 14:09:28 +00001732
drh3cde3bb2004-06-12 02:17:14 +00001733 /* A PENDING lock is needed before acquiring a SHARED lock and before
1734 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1735 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001736 */
drh0c2694b2009-09-03 16:23:44 +00001737 lock.l_len = 1L;
1738 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001739 if( eFileLock==SHARED_LOCK
1740 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001741 ){
drh308c2a52010-05-14 11:30:18 +00001742 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001743 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001744 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001745 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001746 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001747 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001748 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001749 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001750 goto end_lock;
1751 }
drh3cde3bb2004-06-12 02:17:14 +00001752 }
1753
1754
1755 /* If control gets to this point, then actually go ahead and make
1756 ** operating system calls for the specified lock.
1757 */
drh308c2a52010-05-14 11:30:18 +00001758 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001759 assert( pInode->nShared==0 );
1760 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001761 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001762
drh2ac3ee92004-06-07 16:27:46 +00001763 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001764 lock.l_start = SHARED_FIRST;
1765 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001766 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001767 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001768 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001769 }
dan661d71a2011-03-30 19:08:03 +00001770
drh2ac3ee92004-06-07 16:27:46 +00001771 /* Drop the temporary PENDING lock */
1772 lock.l_start = PENDING_BYTE;
1773 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001774 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001775 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1776 /* This could happen with a network mount */
1777 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001778 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001779 }
dan661d71a2011-03-30 19:08:03 +00001780
1781 if( rc ){
1782 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001783 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001784 }
dan661d71a2011-03-30 19:08:03 +00001785 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001786 }else{
drh308c2a52010-05-14 11:30:18 +00001787 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001788 pInode->nLock++;
1789 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001790 }
drh8af6c222010-05-14 12:43:01 +00001791 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001792 /* We are trying for an exclusive lock but another thread in this
1793 ** same process is still holding a shared lock. */
1794 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001795 }else{
drh3cde3bb2004-06-12 02:17:14 +00001796 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001797 ** assumed that there is a SHARED or greater lock on the file
1798 ** already.
1799 */
drh308c2a52010-05-14 11:30:18 +00001800 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001801 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001802
1803 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1804 if( eFileLock==RESERVED_LOCK ){
1805 lock.l_start = RESERVED_BYTE;
1806 lock.l_len = 1L;
1807 }else{
1808 lock.l_start = SHARED_FIRST;
1809 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001810 }
dan661d71a2011-03-30 19:08:03 +00001811
1812 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001813 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001814 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001815 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001816 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001817 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001818 }
drhbbd42a62004-05-22 17:41:58 +00001819 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001820
drh8f941bc2009-01-14 23:03:40 +00001821
drhd3d8c042012-05-29 17:02:40 +00001822#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001823 /* Set up the transaction-counter change checking flags when
1824 ** transitioning from a SHARED to a RESERVED lock. The change
1825 ** from SHARED to RESERVED marks the beginning of a normal
1826 ** write operation (not a hot journal rollback).
1827 */
1828 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001829 && pFile->eFileLock<=SHARED_LOCK
1830 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001831 ){
1832 pFile->transCntrChng = 0;
1833 pFile->dbUpdate = 0;
1834 pFile->inNormalWrite = 1;
1835 }
1836#endif
1837
1838
danielk1977ecb2a962004-06-02 06:30:16 +00001839 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001840 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001841 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001842 }else if( eFileLock==EXCLUSIVE_LOCK ){
1843 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001844 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001845 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001846
1847end_lock:
drhda6dc242018-07-23 21:10:37 +00001848 sqlite3_mutex_leave(pInode->pLockMutex);
drh308c2a52010-05-14 11:30:18 +00001849 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1850 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001851 return rc;
1852}
1853
1854/*
dan08da86a2009-08-21 17:18:03 +00001855** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001856** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001857*/
1858static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001859 unixInodeInfo *pInode = pFile->pInode;
drhc68886b2017-08-18 16:09:52 +00001860 UnixUnusedFd *p = pFile->pPreallocatedUnused;
drhef52b362018-08-13 22:50:34 +00001861 assert( unixFileMutexHeld(pFile) );
drh8af6c222010-05-14 12:43:01 +00001862 p->pNext = pInode->pUnused;
1863 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001864 pFile->h = -1;
drhc68886b2017-08-18 16:09:52 +00001865 pFile->pPreallocatedUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001866}
1867
1868/*
drh308c2a52010-05-14 11:30:18 +00001869** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001870** must be either NO_LOCK or SHARED_LOCK.
1871**
1872** If the locking level of the file descriptor is already at or below
1873** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001874**
1875** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1876** the byte range is divided into 2 parts and the first part is unlocked then
1877** set to a read lock, then the other part is simply unlocked. This works
1878** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1879** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001880*/
drha7e61d82011-03-12 17:02:57 +00001881static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001882 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001883 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001884 struct flock lock;
1885 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001886
drh054889e2005-11-30 03:20:31 +00001887 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001888 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001889 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001890 osGetpid(0)));
drha6abd042004-06-09 17:37:22 +00001891
drh308c2a52010-05-14 11:30:18 +00001892 assert( eFileLock<=SHARED_LOCK );
1893 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001894 return SQLITE_OK;
1895 }
drh8af6c222010-05-14 12:43:01 +00001896 pInode = pFile->pInode;
drhda6dc242018-07-23 21:10:37 +00001897 sqlite3_mutex_enter(pInode->pLockMutex);
drh8af6c222010-05-14 12:43:01 +00001898 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001899 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001900 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001901
drhd3d8c042012-05-29 17:02:40 +00001902#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001903 /* When reducing a lock such that other processes can start
1904 ** reading the database file again, make sure that the
1905 ** transaction counter was updated if any part of the database
1906 ** file changed. If the transaction counter is not updated,
1907 ** other connections to the same file might not realize that
1908 ** the file has changed and hence might not know to flush their
1909 ** cache. The use of a stale cache can lead to database corruption.
1910 */
drh8f941bc2009-01-14 23:03:40 +00001911 pFile->inNormalWrite = 0;
1912#endif
1913
drh7ed97b92010-01-20 13:07:21 +00001914 /* downgrading to a shared lock on NFS involves clearing the write lock
1915 ** before establishing the readlock - to avoid a race condition we downgrade
1916 ** the lock in 2 blocks, so that part of the range will be covered by a
1917 ** write lock until the rest is covered by a read lock:
1918 ** 1: [WWWWW]
1919 ** 2: [....W]
1920 ** 3: [RRRRW]
1921 ** 4: [RRRR.]
1922 */
drh308c2a52010-05-14 11:30:18 +00001923 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001924#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001925 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001926 assert( handleNFSUnlock==0 );
1927#endif
1928#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001929 if( handleNFSUnlock ){
drha712b4b2015-02-19 16:12:04 +00001930 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001931 off_t divSize = SHARED_SIZE - 1;
1932
1933 lock.l_type = F_UNLCK;
1934 lock.l_whence = SEEK_SET;
1935 lock.l_start = SHARED_FIRST;
1936 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001937 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001938 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001939 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001940 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001941 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001942 }
drh7ed97b92010-01-20 13:07:21 +00001943 lock.l_type = F_RDLCK;
1944 lock.l_whence = SEEK_SET;
1945 lock.l_start = SHARED_FIRST;
1946 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001947 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001948 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001949 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1950 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001951 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001952 }
1953 goto end_unlock;
1954 }
1955 lock.l_type = F_UNLCK;
1956 lock.l_whence = SEEK_SET;
1957 lock.l_start = SHARED_FIRST+divSize;
1958 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001959 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001960 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001961 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001962 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001963 goto end_unlock;
1964 }
drh30f776f2011-02-25 03:25:07 +00001965 }else
1966#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1967 {
drh7ed97b92010-01-20 13:07:21 +00001968 lock.l_type = F_RDLCK;
1969 lock.l_whence = SEEK_SET;
1970 lock.l_start = SHARED_FIRST;
1971 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001972 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001973 /* In theory, the call to unixFileLock() cannot fail because another
1974 ** process is holding an incompatible lock. If it does, this
1975 ** indicates that the other process is not following the locking
1976 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1977 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1978 ** an assert to fail). */
1979 rc = SQLITE_IOERR_RDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001980 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00001981 goto end_unlock;
1982 }
drh9c105bb2004-10-02 20:38:28 +00001983 }
1984 }
drhbbd42a62004-05-22 17:41:58 +00001985 lock.l_type = F_UNLCK;
1986 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001987 lock.l_start = PENDING_BYTE;
1988 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001989 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001990 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001991 }else{
danea83bc62011-04-01 11:56:32 +00001992 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001993 storeLastErrno(pFile, errno);
drhcd731cf2009-03-28 23:23:02 +00001994 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001995 }
drhbbd42a62004-05-22 17:41:58 +00001996 }
drh308c2a52010-05-14 11:30:18 +00001997 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001998 /* Decrement the shared lock counter. Release the lock using an
1999 ** OS call only when all threads in this same process have released
2000 ** the lock.
2001 */
drh8af6c222010-05-14 12:43:01 +00002002 pInode->nShared--;
2003 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00002004 lock.l_type = F_UNLCK;
2005 lock.l_whence = SEEK_SET;
2006 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00002007 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00002008 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00002009 }else{
danea83bc62011-04-01 11:56:32 +00002010 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002011 storeLastErrno(pFile, errno);
drh8af6c222010-05-14 12:43:01 +00002012 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002013 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00002014 }
drha6abd042004-06-09 17:37:22 +00002015 }
2016
drhbbd42a62004-05-22 17:41:58 +00002017 /* Decrement the count of locks against this same file. When the
2018 ** count reaches zero, close any other file descriptors whose close
2019 ** was deferred because of outstanding locks.
2020 */
drh8af6c222010-05-14 12:43:01 +00002021 pInode->nLock--;
2022 assert( pInode->nLock>=0 );
drhef52b362018-08-13 22:50:34 +00002023 if( pInode->nLock==0 ) closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00002024 }
drhf2f105d2012-08-20 15:53:54 +00002025
aswift5b1a2562008-08-22 00:22:35 +00002026end_unlock:
drhda6dc242018-07-23 21:10:37 +00002027 sqlite3_mutex_leave(pInode->pLockMutex);
drh095908e2018-08-13 20:46:18 +00002028 if( rc==SQLITE_OK ){
2029 pFile->eFileLock = eFileLock;
drh095908e2018-08-13 20:46:18 +00002030 }
drh9c105bb2004-10-02 20:38:28 +00002031 return rc;
drhbbd42a62004-05-22 17:41:58 +00002032}
2033
2034/*
drh308c2a52010-05-14 11:30:18 +00002035** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002036** must be either NO_LOCK or SHARED_LOCK.
2037**
2038** If the locking level of the file descriptor is already at or below
2039** the requested locking level, this routine is a no-op.
2040*/
drh308c2a52010-05-14 11:30:18 +00002041static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00002042#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00002043 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00002044#endif
drha7e61d82011-03-12 17:02:57 +00002045 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00002046}
2047
mistachkine98844f2013-08-24 00:59:24 +00002048#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00002049static int unixMapfile(unixFile *pFd, i64 nByte);
2050static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00002051#endif
danf23da962013-03-23 21:00:41 +00002052
drh7ed97b92010-01-20 13:07:21 +00002053/*
danielk1977e339d652008-06-28 11:23:00 +00002054** This function performs the parts of the "close file" operation
2055** common to all locking schemes. It closes the directory and file
2056** handles, if they are valid, and sets all fields of the unixFile
2057** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00002058**
2059** It is *not* necessary to hold the mutex when this routine is called,
2060** even on VxWorks. A mutex will be acquired on VxWorks by the
2061** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00002062*/
2063static int closeUnixFile(sqlite3_file *id){
2064 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00002065#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00002066 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00002067#endif
dan661d71a2011-03-30 19:08:03 +00002068 if( pFile->h>=0 ){
2069 robust_close(pFile, pFile->h, __LINE__);
2070 pFile->h = -1;
2071 }
2072#if OS_VXWORKS
2073 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00002074 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00002075 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00002076 }
2077 vxworksReleaseFileId(pFile->pId);
2078 pFile->pId = 0;
2079 }
2080#endif
drh0bdbc902014-06-16 18:35:06 +00002081#ifdef SQLITE_UNLINK_AFTER_CLOSE
2082 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
2083 osUnlink(pFile->zPath);
2084 sqlite3_free(*(char**)&pFile->zPath);
2085 pFile->zPath = 0;
2086 }
2087#endif
dan661d71a2011-03-30 19:08:03 +00002088 OSTRACE(("CLOSE %-3d\n", pFile->h));
2089 OpenCounter(-1);
drhc68886b2017-08-18 16:09:52 +00002090 sqlite3_free(pFile->pPreallocatedUnused);
dan661d71a2011-03-30 19:08:03 +00002091 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00002092 return SQLITE_OK;
2093}
2094
2095/*
danielk1977e3026632004-06-22 11:29:02 +00002096** Close a file.
2097*/
danielk197762079062007-08-15 17:08:46 +00002098static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00002099 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00002100 unixFile *pFile = (unixFile *)id;
drhef52b362018-08-13 22:50:34 +00002101 unixInodeInfo *pInode = pFile->pInode;
2102
2103 assert( pInode!=0 );
drhfbc7e882013-04-11 01:16:15 +00002104 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00002105 unixUnlock(id, NO_LOCK);
drh095908e2018-08-13 20:46:18 +00002106 assert( unixFileMutexNotheld(pFile) );
dan661d71a2011-03-30 19:08:03 +00002107 unixEnterMutex();
2108
2109 /* unixFile.pInode is always valid here. Otherwise, a different close
2110 ** routine (e.g. nolockClose()) would be called instead.
2111 */
2112 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
drhef52b362018-08-13 22:50:34 +00002113 sqlite3_mutex_enter(pInode->pLockMutex);
2114 if( pFile->pInode->nLock ){
dan661d71a2011-03-30 19:08:03 +00002115 /* If there are outstanding locks, do not actually close the file just
2116 ** yet because that would clear those locks. Instead, add the file
2117 ** descriptor to pInode->pUnused list. It will be automatically closed
2118 ** when the last lock is cleared.
2119 */
2120 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00002121 }
drhef52b362018-08-13 22:50:34 +00002122 sqlite3_mutex_leave(pInode->pLockMutex);
dan661d71a2011-03-30 19:08:03 +00002123 releaseInodeInfo(pFile);
2124 rc = closeUnixFile(id);
2125 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00002126 return rc;
danielk1977e3026632004-06-22 11:29:02 +00002127}
2128
drh734c9862008-11-28 15:37:20 +00002129/************** End of the posix advisory lock implementation *****************
2130******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002131
drh734c9862008-11-28 15:37:20 +00002132/******************************************************************************
2133****************************** No-op Locking **********************************
2134**
2135** Of the various locking implementations available, this is by far the
2136** simplest: locking is ignored. No attempt is made to lock the database
2137** file for reading or writing.
2138**
2139** This locking mode is appropriate for use on read-only databases
2140** (ex: databases that are burned into CD-ROM, for example.) It can
2141** also be used if the application employs some external mechanism to
2142** prevent simultaneous access of the same database by two or more
2143** database connections. But there is a serious risk of database
2144** corruption if this locking mode is used in situations where multiple
2145** database connections are accessing the same database file at the same
2146** time and one or more of those connections are writing.
2147*/
drhbfe66312006-10-03 17:40:40 +00002148
drh734c9862008-11-28 15:37:20 +00002149static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
2150 UNUSED_PARAMETER(NotUsed);
2151 *pResOut = 0;
2152 return SQLITE_OK;
2153}
drh734c9862008-11-28 15:37:20 +00002154static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
2155 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2156 return SQLITE_OK;
2157}
drh734c9862008-11-28 15:37:20 +00002158static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
2159 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2160 return SQLITE_OK;
2161}
2162
2163/*
drh9b35ea62008-11-29 02:20:26 +00002164** Close the file.
drh734c9862008-11-28 15:37:20 +00002165*/
2166static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00002167 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002168}
2169
2170/******************* End of the no-op lock implementation *********************
2171******************************************************************************/
2172
2173/******************************************************************************
2174************************* Begin dot-file Locking ******************************
2175**
mistachkin48864df2013-03-21 21:20:32 +00002176** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00002177** files (really a directory) to control access to the database. This works
2178** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002179**
2180** (1) There is zero concurrency. A single reader blocks all other
2181** connections from reading or writing the database.
2182**
2183** (2) An application crash or power loss can leave stale lock files
2184** sitting around that need to be cleared manually.
2185**
2186** Nevertheless, a dotlock is an appropriate locking mode for use if no
2187** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002188**
drh9ef6bc42011-11-04 02:24:02 +00002189** Dotfile locking works by creating a subdirectory in the same directory as
2190** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002191** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002192** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002193*/
2194
2195/*
2196** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002197** lock directory.
drh734c9862008-11-28 15:37:20 +00002198*/
2199#define DOTLOCK_SUFFIX ".lock"
2200
drh7708e972008-11-29 00:56:52 +00002201/*
2202** This routine checks if there is a RESERVED lock held on the specified
2203** file by this or any other process. If such a lock is held, set *pResOut
2204** to a non-zero value otherwise *pResOut is set to zero. The return value
2205** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2206**
2207** In dotfile locking, either a lock exists or it does not. So in this
2208** variation of CheckReservedLock(), *pResOut is set to true if any lock
2209** is held on the file and false if the file is unlocked.
2210*/
drh734c9862008-11-28 15:37:20 +00002211static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2212 int rc = SQLITE_OK;
2213 int reserved = 0;
2214 unixFile *pFile = (unixFile*)id;
2215
2216 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2217
2218 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00002219 reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
drh308c2a52010-05-14 11:30:18 +00002220 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002221 *pResOut = reserved;
2222 return rc;
2223}
2224
drh7708e972008-11-29 00:56:52 +00002225/*
drh308c2a52010-05-14 11:30:18 +00002226** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002227** of the following:
2228**
2229** (1) SHARED_LOCK
2230** (2) RESERVED_LOCK
2231** (3) PENDING_LOCK
2232** (4) EXCLUSIVE_LOCK
2233**
2234** Sometimes when requesting one lock state, additional lock states
2235** are inserted in between. The locking might fail on one of the later
2236** transitions leaving the lock state different from what it started but
2237** still short of its goal. The following chart shows the allowed
2238** transitions and the inserted intermediate states:
2239**
2240** UNLOCKED -> SHARED
2241** SHARED -> RESERVED
2242** SHARED -> (PENDING) -> EXCLUSIVE
2243** RESERVED -> (PENDING) -> EXCLUSIVE
2244** PENDING -> EXCLUSIVE
2245**
2246** This routine will only increase a lock. Use the sqlite3OsUnlock()
2247** routine to lower a locking level.
2248**
2249** With dotfile locking, we really only support state (4): EXCLUSIVE.
2250** But we track the other locking levels internally.
2251*/
drh308c2a52010-05-14 11:30:18 +00002252static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002253 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002254 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002255 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002256
drh7708e972008-11-29 00:56:52 +00002257
2258 /* If we have any lock, then the lock file already exists. All we have
2259 ** to do is adjust our internal record of the lock level.
2260 */
drh308c2a52010-05-14 11:30:18 +00002261 if( pFile->eFileLock > NO_LOCK ){
2262 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002263 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002264#ifdef HAVE_UTIME
2265 utime(zLockFile, NULL);
2266#else
drh734c9862008-11-28 15:37:20 +00002267 utimes(zLockFile, NULL);
2268#endif
drh7708e972008-11-29 00:56:52 +00002269 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002270 }
2271
2272 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002273 rc = osMkdir(zLockFile, 0777);
2274 if( rc<0 ){
2275 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002276 int tErrno = errno;
2277 if( EEXIST == tErrno ){
2278 rc = SQLITE_BUSY;
2279 } else {
2280 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drha8de1e12015-11-30 00:05:39 +00002281 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00002282 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002283 }
2284 }
drh7708e972008-11-29 00:56:52 +00002285 return rc;
drh734c9862008-11-28 15:37:20 +00002286 }
drh734c9862008-11-28 15:37:20 +00002287
2288 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002289 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002290 return rc;
2291}
2292
drh7708e972008-11-29 00:56:52 +00002293/*
drh308c2a52010-05-14 11:30:18 +00002294** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002295** must be either NO_LOCK or SHARED_LOCK.
2296**
2297** If the locking level of the file descriptor is already at or below
2298** the requested locking level, this routine is a no-op.
2299**
2300** When the locking level reaches NO_LOCK, delete the lock file.
2301*/
drh308c2a52010-05-14 11:30:18 +00002302static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002303 unixFile *pFile = (unixFile*)id;
2304 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002305 int rc;
drh734c9862008-11-28 15:37:20 +00002306
2307 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002308 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002309 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002310 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002311
2312 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002313 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002314 return SQLITE_OK;
2315 }
drh7708e972008-11-29 00:56:52 +00002316
2317 /* To downgrade to shared, simply update our internal notion of the
2318 ** lock state. No need to mess with the file on disk.
2319 */
drh308c2a52010-05-14 11:30:18 +00002320 if( eFileLock==SHARED_LOCK ){
2321 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002322 return SQLITE_OK;
2323 }
2324
drh7708e972008-11-29 00:56:52 +00002325 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002326 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002327 rc = osRmdir(zLockFile);
drh9ef6bc42011-11-04 02:24:02 +00002328 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002329 int tErrno = errno;
drha8de1e12015-11-30 00:05:39 +00002330 if( tErrno==ENOENT ){
2331 rc = SQLITE_OK;
2332 }else{
danea83bc62011-04-01 11:56:32 +00002333 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002334 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002335 }
2336 return rc;
2337 }
drh308c2a52010-05-14 11:30:18 +00002338 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002339 return SQLITE_OK;
2340}
2341
2342/*
drh9b35ea62008-11-29 02:20:26 +00002343** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002344*/
2345static int dotlockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002346 unixFile *pFile = (unixFile*)id;
2347 assert( id!=0 );
2348 dotlockUnlock(id, NO_LOCK);
2349 sqlite3_free(pFile->lockingContext);
2350 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002351}
2352/****************** End of the dot-file lock implementation *******************
2353******************************************************************************/
2354
2355/******************************************************************************
2356************************** Begin flock Locking ********************************
2357**
2358** Use the flock() system call to do file locking.
2359**
drh6b9d6dd2008-12-03 19:34:47 +00002360** flock() locking is like dot-file locking in that the various
2361** fine-grain locking levels supported by SQLite are collapsed into
2362** a single exclusive lock. In other words, SHARED, RESERVED, and
2363** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2364** still works when you do this, but concurrency is reduced since
2365** only a single process can be reading the database at a time.
2366**
drhe89b2912015-03-03 20:42:01 +00002367** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
drh734c9862008-11-28 15:37:20 +00002368*/
drhe89b2912015-03-03 20:42:01 +00002369#if SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002370
drh6b9d6dd2008-12-03 19:34:47 +00002371/*
drhff812312011-02-23 13:33:46 +00002372** Retry flock() calls that fail with EINTR
2373*/
2374#ifdef EINTR
2375static int robust_flock(int fd, int op){
2376 int rc;
2377 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2378 return rc;
2379}
2380#else
drh5c819272011-02-23 14:00:12 +00002381# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002382#endif
2383
2384
2385/*
drh6b9d6dd2008-12-03 19:34:47 +00002386** This routine checks if there is a RESERVED lock held on the specified
2387** file by this or any other process. If such a lock is held, set *pResOut
2388** to a non-zero value otherwise *pResOut is set to zero. The return value
2389** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2390*/
drh734c9862008-11-28 15:37:20 +00002391static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2392 int rc = SQLITE_OK;
2393 int reserved = 0;
2394 unixFile *pFile = (unixFile*)id;
2395
2396 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2397
2398 assert( pFile );
2399
2400 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002401 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002402 reserved = 1;
2403 }
2404
2405 /* Otherwise see if some other process holds it. */
2406 if( !reserved ){
2407 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002408 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002409 if( !lrc ){
2410 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002411 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002412 if ( lrc ) {
2413 int tErrno = errno;
2414 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002415 lrc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00002416 storeLastErrno(pFile, tErrno);
2417 rc = lrc;
drh734c9862008-11-28 15:37:20 +00002418 }
2419 } else {
2420 int tErrno = errno;
2421 reserved = 1;
2422 /* someone else might have it reserved */
2423 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2424 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002425 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002426 rc = lrc;
2427 }
2428 }
2429 }
drh308c2a52010-05-14 11:30:18 +00002430 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002431
2432#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
drh2e233812017-08-22 15:21:54 +00002433 if( (rc & 0xff) == SQLITE_IOERR ){
drh734c9862008-11-28 15:37:20 +00002434 rc = SQLITE_OK;
2435 reserved=1;
2436 }
2437#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2438 *pResOut = reserved;
2439 return rc;
2440}
2441
drh6b9d6dd2008-12-03 19:34:47 +00002442/*
drh308c2a52010-05-14 11:30:18 +00002443** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002444** of the following:
2445**
2446** (1) SHARED_LOCK
2447** (2) RESERVED_LOCK
2448** (3) PENDING_LOCK
2449** (4) EXCLUSIVE_LOCK
2450**
2451** Sometimes when requesting one lock state, additional lock states
2452** are inserted in between. The locking might fail on one of the later
2453** transitions leaving the lock state different from what it started but
2454** still short of its goal. The following chart shows the allowed
2455** transitions and the inserted intermediate states:
2456**
2457** UNLOCKED -> SHARED
2458** SHARED -> RESERVED
2459** SHARED -> (PENDING) -> EXCLUSIVE
2460** RESERVED -> (PENDING) -> EXCLUSIVE
2461** PENDING -> EXCLUSIVE
2462**
2463** flock() only really support EXCLUSIVE locks. We track intermediate
2464** lock states in the sqlite3_file structure, but all locks SHARED or
2465** above are really EXCLUSIVE locks and exclude all other processes from
2466** access the file.
2467**
2468** This routine will only increase a lock. Use the sqlite3OsUnlock()
2469** routine to lower a locking level.
2470*/
drh308c2a52010-05-14 11:30:18 +00002471static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002472 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002473 unixFile *pFile = (unixFile*)id;
2474
2475 assert( pFile );
2476
2477 /* if we already have a lock, it is exclusive.
2478 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002479 if (pFile->eFileLock > NO_LOCK) {
2480 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002481 return SQLITE_OK;
2482 }
2483
2484 /* grab an exclusive lock */
2485
drhff812312011-02-23 13:33:46 +00002486 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002487 int tErrno = errno;
2488 /* didn't get, must be busy */
2489 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2490 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002491 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002492 }
2493 } else {
2494 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002495 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002496 }
drh308c2a52010-05-14 11:30:18 +00002497 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2498 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002499#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
drh2e233812017-08-22 15:21:54 +00002500 if( (rc & 0xff) == SQLITE_IOERR ){
drh734c9862008-11-28 15:37:20 +00002501 rc = SQLITE_BUSY;
2502 }
2503#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2504 return rc;
2505}
2506
drh6b9d6dd2008-12-03 19:34:47 +00002507
2508/*
drh308c2a52010-05-14 11:30:18 +00002509** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002510** must be either NO_LOCK or SHARED_LOCK.
2511**
2512** If the locking level of the file descriptor is already at or below
2513** the requested locking level, this routine is a no-op.
2514*/
drh308c2a52010-05-14 11:30:18 +00002515static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002516 unixFile *pFile = (unixFile*)id;
2517
2518 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002519 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002520 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002521 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002522
2523 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002524 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002525 return SQLITE_OK;
2526 }
2527
2528 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002529 if (eFileLock==SHARED_LOCK) {
2530 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002531 return SQLITE_OK;
2532 }
2533
2534 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002535 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002536#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002537 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002538#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002539 return SQLITE_IOERR_UNLOCK;
2540 }else{
drh308c2a52010-05-14 11:30:18 +00002541 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002542 return SQLITE_OK;
2543 }
2544}
2545
2546/*
2547** Close a file.
2548*/
2549static int flockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002550 assert( id!=0 );
2551 flockUnlock(id, NO_LOCK);
2552 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002553}
2554
2555#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2556
2557/******************* End of the flock lock implementation *********************
2558******************************************************************************/
2559
2560/******************************************************************************
2561************************ Begin Named Semaphore Locking ************************
2562**
2563** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002564**
2565** Semaphore locking is like dot-lock and flock in that it really only
2566** supports EXCLUSIVE locking. Only a single process can read or write
2567** the database file at a time. This reduces potential concurrency, but
2568** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002569*/
2570#if OS_VXWORKS
2571
drh6b9d6dd2008-12-03 19:34:47 +00002572/*
2573** This routine checks if there is a RESERVED lock held on the specified
2574** file by this or any other process. If such a lock is held, set *pResOut
2575** to a non-zero value otherwise *pResOut is set to zero. The return value
2576** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2577*/
drh8cd5b252015-03-02 22:06:43 +00002578static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
drh734c9862008-11-28 15:37:20 +00002579 int rc = SQLITE_OK;
2580 int reserved = 0;
2581 unixFile *pFile = (unixFile*)id;
2582
2583 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2584
2585 assert( pFile );
2586
2587 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002588 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002589 reserved = 1;
2590 }
2591
2592 /* Otherwise see if some other process holds it. */
2593 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002594 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002595
2596 if( sem_trywait(pSem)==-1 ){
2597 int tErrno = errno;
2598 if( EAGAIN != tErrno ){
2599 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
drh4bf66fd2015-02-19 02:43:02 +00002600 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002601 } else {
2602 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002603 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002604 }
2605 }else{
2606 /* we could have it if we want it */
2607 sem_post(pSem);
2608 }
2609 }
drh308c2a52010-05-14 11:30:18 +00002610 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002611
2612 *pResOut = reserved;
2613 return rc;
2614}
2615
drh6b9d6dd2008-12-03 19:34:47 +00002616/*
drh308c2a52010-05-14 11:30:18 +00002617** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002618** of the following:
2619**
2620** (1) SHARED_LOCK
2621** (2) RESERVED_LOCK
2622** (3) PENDING_LOCK
2623** (4) EXCLUSIVE_LOCK
2624**
2625** Sometimes when requesting one lock state, additional lock states
2626** are inserted in between. The locking might fail on one of the later
2627** transitions leaving the lock state different from what it started but
2628** still short of its goal. The following chart shows the allowed
2629** transitions and the inserted intermediate states:
2630**
2631** UNLOCKED -> SHARED
2632** SHARED -> RESERVED
2633** SHARED -> (PENDING) -> EXCLUSIVE
2634** RESERVED -> (PENDING) -> EXCLUSIVE
2635** PENDING -> EXCLUSIVE
2636**
2637** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2638** lock states in the sqlite3_file structure, but all locks SHARED or
2639** above are really EXCLUSIVE locks and exclude all other processes from
2640** access the file.
2641**
2642** This routine will only increase a lock. Use the sqlite3OsUnlock()
2643** routine to lower a locking level.
2644*/
drh8cd5b252015-03-02 22:06:43 +00002645static int semXLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002646 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002647 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002648 int rc = SQLITE_OK;
2649
2650 /* if we already have a lock, it is exclusive.
2651 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002652 if (pFile->eFileLock > NO_LOCK) {
2653 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002654 rc = SQLITE_OK;
2655 goto sem_end_lock;
2656 }
2657
2658 /* lock semaphore now but bail out when already locked. */
2659 if( sem_trywait(pSem)==-1 ){
2660 rc = SQLITE_BUSY;
2661 goto sem_end_lock;
2662 }
2663
2664 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002665 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002666
2667 sem_end_lock:
2668 return rc;
2669}
2670
drh6b9d6dd2008-12-03 19:34:47 +00002671/*
drh308c2a52010-05-14 11:30:18 +00002672** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002673** must be either NO_LOCK or SHARED_LOCK.
2674**
2675** If the locking level of the file descriptor is already at or below
2676** the requested locking level, this routine is a no-op.
2677*/
drh8cd5b252015-03-02 22:06:43 +00002678static int semXUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002679 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002680 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002681
2682 assert( pFile );
2683 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002684 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002685 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002686 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002687
2688 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002689 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002690 return SQLITE_OK;
2691 }
2692
2693 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002694 if (eFileLock==SHARED_LOCK) {
2695 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002696 return SQLITE_OK;
2697 }
2698
2699 /* no, really unlock. */
2700 if ( sem_post(pSem)==-1 ) {
2701 int rc, tErrno = errno;
2702 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2703 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002704 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002705 }
2706 return rc;
2707 }
drh308c2a52010-05-14 11:30:18 +00002708 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002709 return SQLITE_OK;
2710}
2711
2712/*
2713 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002714 */
drh8cd5b252015-03-02 22:06:43 +00002715static int semXClose(sqlite3_file *id) {
drh734c9862008-11-28 15:37:20 +00002716 if( id ){
2717 unixFile *pFile = (unixFile*)id;
drh8cd5b252015-03-02 22:06:43 +00002718 semXUnlock(id, NO_LOCK);
drh734c9862008-11-28 15:37:20 +00002719 assert( pFile );
drh095908e2018-08-13 20:46:18 +00002720 assert( unixFileMutexNotheld(pFile) );
drh734c9862008-11-28 15:37:20 +00002721 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002722 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002723 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002724 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002725 }
2726 return SQLITE_OK;
2727}
2728
2729#endif /* OS_VXWORKS */
2730/*
2731** Named semaphore locking is only available on VxWorks.
2732**
2733*************** End of the named semaphore lock implementation ****************
2734******************************************************************************/
2735
2736
2737/******************************************************************************
2738*************************** Begin AFP Locking *********************************
2739**
2740** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2741** on Apple Macintosh computers - both OS9 and OSX.
2742**
2743** Third-party implementations of AFP are available. But this code here
2744** only works on OSX.
2745*/
2746
drhd2cb50b2009-01-09 21:41:17 +00002747#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002748/*
2749** The afpLockingContext structure contains all afp lock specific state
2750*/
drhbfe66312006-10-03 17:40:40 +00002751typedef struct afpLockingContext afpLockingContext;
2752struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002753 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002754 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002755};
2756
2757struct ByteRangeLockPB2
2758{
2759 unsigned long long offset; /* offset to first byte to lock */
2760 unsigned long long length; /* nbr of bytes to lock */
2761 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2762 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2763 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2764 int fd; /* file desc to assoc this lock with */
2765};
2766
drhfd131da2007-08-07 17:13:03 +00002767#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002768
drh6b9d6dd2008-12-03 19:34:47 +00002769/*
2770** This is a utility for setting or clearing a bit-range lock on an
2771** AFP filesystem.
2772**
2773** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2774*/
2775static int afpSetLock(
2776 const char *path, /* Name of the file to be locked or unlocked */
2777 unixFile *pFile, /* Open file descriptor on path */
2778 unsigned long long offset, /* First byte to be locked */
2779 unsigned long long length, /* Number of bytes to lock */
2780 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002781){
drh6b9d6dd2008-12-03 19:34:47 +00002782 struct ByteRangeLockPB2 pb;
2783 int err;
drhbfe66312006-10-03 17:40:40 +00002784
2785 pb.unLockFlag = setLockFlag ? 0 : 1;
2786 pb.startEndFlag = 0;
2787 pb.offset = offset;
2788 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002789 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002790
drh308c2a52010-05-14 11:30:18 +00002791 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002792 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002793 offset, length));
drhbfe66312006-10-03 17:40:40 +00002794 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2795 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002796 int rc;
2797 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002798 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2799 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002800#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2801 rc = SQLITE_BUSY;
2802#else
drh734c9862008-11-28 15:37:20 +00002803 rc = sqliteErrorFromPosixError(tErrno,
2804 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002805#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002806 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002807 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00002808 }
2809 return rc;
drhbfe66312006-10-03 17:40:40 +00002810 } else {
aswift5b1a2562008-08-22 00:22:35 +00002811 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002812 }
2813}
2814
drh6b9d6dd2008-12-03 19:34:47 +00002815/*
2816** This routine checks if there is a RESERVED lock held on the specified
2817** file by this or any other process. If such a lock is held, set *pResOut
2818** to a non-zero value otherwise *pResOut is set to zero. The return value
2819** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2820*/
danielk1977e339d652008-06-28 11:23:00 +00002821static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002822 int rc = SQLITE_OK;
2823 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002824 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002825 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002826
aswift5b1a2562008-08-22 00:22:35 +00002827 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2828
2829 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002830 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002831 if( context->reserved ){
2832 *pResOut = 1;
2833 return SQLITE_OK;
2834 }
drhda6dc242018-07-23 21:10:37 +00002835 sqlite3_mutex_enter(pFile->pInode->pLockMutex);
drhbfe66312006-10-03 17:40:40 +00002836 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002837 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002838 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002839 }
2840
2841 /* Otherwise see if some other process holds it.
2842 */
aswift5b1a2562008-08-22 00:22:35 +00002843 if( !reserved ){
2844 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002845 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002846 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002847 /* if we succeeded in taking the reserved lock, unlock it to restore
2848 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002849 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002850 } else {
2851 /* if we failed to get the lock then someone else must have it */
2852 reserved = 1;
2853 }
2854 if( IS_LOCK_ERROR(lrc) ){
2855 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002856 }
2857 }
drhbfe66312006-10-03 17:40:40 +00002858
drhda6dc242018-07-23 21:10:37 +00002859 sqlite3_mutex_leave(pFile->pInode->pLockMutex);
drh308c2a52010-05-14 11:30:18 +00002860 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002861
2862 *pResOut = reserved;
2863 return rc;
drhbfe66312006-10-03 17:40:40 +00002864}
2865
drh6b9d6dd2008-12-03 19:34:47 +00002866/*
drh308c2a52010-05-14 11:30:18 +00002867** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002868** of the following:
2869**
2870** (1) SHARED_LOCK
2871** (2) RESERVED_LOCK
2872** (3) PENDING_LOCK
2873** (4) EXCLUSIVE_LOCK
2874**
2875** Sometimes when requesting one lock state, additional lock states
2876** are inserted in between. The locking might fail on one of the later
2877** transitions leaving the lock state different from what it started but
2878** still short of its goal. The following chart shows the allowed
2879** transitions and the inserted intermediate states:
2880**
2881** UNLOCKED -> SHARED
2882** SHARED -> RESERVED
2883** SHARED -> (PENDING) -> EXCLUSIVE
2884** RESERVED -> (PENDING) -> EXCLUSIVE
2885** PENDING -> EXCLUSIVE
2886**
2887** This routine will only increase a lock. Use the sqlite3OsUnlock()
2888** routine to lower a locking level.
2889*/
drh308c2a52010-05-14 11:30:18 +00002890static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002891 int rc = SQLITE_OK;
2892 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002893 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002894 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002895
2896 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002897 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2898 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh5ac93652015-03-21 20:59:43 +00002899 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
drh339eb0b2008-03-07 15:34:11 +00002900
drhbfe66312006-10-03 17:40:40 +00002901 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002902 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002903 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002904 */
drh308c2a52010-05-14 11:30:18 +00002905 if( pFile->eFileLock>=eFileLock ){
2906 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2907 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002908 return SQLITE_OK;
2909 }
2910
2911 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002912 ** (1) We never move from unlocked to anything higher than shared lock.
2913 ** (2) SQLite never explicitly requests a pendig lock.
2914 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002915 */
drh308c2a52010-05-14 11:30:18 +00002916 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2917 assert( eFileLock!=PENDING_LOCK );
2918 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002919
drh8af6c222010-05-14 12:43:01 +00002920 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002921 */
drh8af6c222010-05-14 12:43:01 +00002922 pInode = pFile->pInode;
drhda6dc242018-07-23 21:10:37 +00002923 sqlite3_mutex_enter(pInode->pLockMutex);
drh7ed97b92010-01-20 13:07:21 +00002924
2925 /* If some thread using this PID has a lock via a different unixFile*
2926 ** handle that precludes the requested lock, return BUSY.
2927 */
drh8af6c222010-05-14 12:43:01 +00002928 if( (pFile->eFileLock!=pInode->eFileLock &&
2929 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002930 ){
2931 rc = SQLITE_BUSY;
2932 goto afp_end_lock;
2933 }
2934
2935 /* If a SHARED lock is requested, and some thread using this PID already
2936 ** has a SHARED or RESERVED lock, then increment reference counts and
2937 ** return SQLITE_OK.
2938 */
drh308c2a52010-05-14 11:30:18 +00002939 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002940 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002941 assert( eFileLock==SHARED_LOCK );
2942 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002943 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002944 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002945 pInode->nShared++;
2946 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002947 goto afp_end_lock;
2948 }
drhbfe66312006-10-03 17:40:40 +00002949
2950 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002951 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2952 ** be released.
2953 */
drh308c2a52010-05-14 11:30:18 +00002954 if( eFileLock==SHARED_LOCK
2955 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002956 ){
2957 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002958 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002959 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002960 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002961 goto afp_end_lock;
2962 }
2963 }
2964
2965 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002966 ** operating system calls for the specified lock.
2967 */
drh308c2a52010-05-14 11:30:18 +00002968 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002969 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002970 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002971
drh8af6c222010-05-14 12:43:01 +00002972 assert( pInode->nShared==0 );
2973 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002974
2975 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002976 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002977 /* note that the quality of the randomness doesn't matter that much */
2978 lk = random();
drh8af6c222010-05-14 12:43:01 +00002979 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002980 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002981 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002982 if( IS_LOCK_ERROR(lrc1) ){
2983 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002984 }
aswift5b1a2562008-08-22 00:22:35 +00002985 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002986 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002987
aswift5b1a2562008-08-22 00:22:35 +00002988 if( IS_LOCK_ERROR(lrc1) ) {
drh4bf66fd2015-02-19 02:43:02 +00002989 storeLastErrno(pFile, lrc1Errno);
aswift5b1a2562008-08-22 00:22:35 +00002990 rc = lrc1;
2991 goto afp_end_lock;
2992 } else if( IS_LOCK_ERROR(lrc2) ){
2993 rc = lrc2;
2994 goto afp_end_lock;
2995 } else if( lrc1 != SQLITE_OK ) {
2996 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002997 } else {
drh308c2a52010-05-14 11:30:18 +00002998 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002999 pInode->nLock++;
3000 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00003001 }
drh8af6c222010-05-14 12:43:01 +00003002 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00003003 /* We are trying for an exclusive lock but another thread in this
3004 ** same process is still holding a shared lock. */
3005 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00003006 }else{
3007 /* The request was for a RESERVED or EXCLUSIVE lock. It is
3008 ** assumed that there is a SHARED or greater lock on the file
3009 ** already.
3010 */
3011 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00003012 assert( 0!=pFile->eFileLock );
3013 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00003014 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00003015 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00003016 if( !failed ){
3017 context->reserved = 1;
3018 }
drhbfe66312006-10-03 17:40:40 +00003019 }
drh308c2a52010-05-14 11:30:18 +00003020 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00003021 /* Acquire an EXCLUSIVE lock */
3022
3023 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00003024 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00003025 */
drh6b9d6dd2008-12-03 19:34:47 +00003026 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00003027 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00003028 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00003029 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00003030 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00003031 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00003032 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00003033 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00003034 /* Can't reestablish the shared lock. Sqlite can't deal, this is
3035 ** a critical I/O error
3036 */
drh2e233812017-08-22 15:21:54 +00003037 rc = ((failed & 0xff) == SQLITE_IOERR) ? failed2 :
aswiftaebf4132008-11-21 00:10:35 +00003038 SQLITE_IOERR_LOCK;
3039 goto afp_end_lock;
3040 }
3041 }else{
aswift5b1a2562008-08-22 00:22:35 +00003042 rc = failed;
drhbfe66312006-10-03 17:40:40 +00003043 }
3044 }
aswift5b1a2562008-08-22 00:22:35 +00003045 if( failed ){
3046 rc = failed;
drhbfe66312006-10-03 17:40:40 +00003047 }
3048 }
3049
3050 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00003051 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00003052 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00003053 }else if( eFileLock==EXCLUSIVE_LOCK ){
3054 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00003055 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00003056 }
3057
3058afp_end_lock:
drhda6dc242018-07-23 21:10:37 +00003059 sqlite3_mutex_leave(pInode->pLockMutex);
drh308c2a52010-05-14 11:30:18 +00003060 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
3061 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00003062 return rc;
3063}
3064
3065/*
drh308c2a52010-05-14 11:30:18 +00003066** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00003067** must be either NO_LOCK or SHARED_LOCK.
3068**
3069** If the locking level of the file descriptor is already at or below
3070** the requested locking level, this routine is a no-op.
3071*/
drh308c2a52010-05-14 11:30:18 +00003072static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00003073 int rc = SQLITE_OK;
3074 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00003075 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00003076 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
3077 int skipShared = 0;
3078#ifdef SQLITE_TEST
3079 int h = pFile->h;
3080#endif
drhbfe66312006-10-03 17:40:40 +00003081
3082 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003083 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00003084 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00003085 osGetpid(0)));
aswift5b1a2562008-08-22 00:22:35 +00003086
drh308c2a52010-05-14 11:30:18 +00003087 assert( eFileLock<=SHARED_LOCK );
3088 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00003089 return SQLITE_OK;
3090 }
drh8af6c222010-05-14 12:43:01 +00003091 pInode = pFile->pInode;
drhda6dc242018-07-23 21:10:37 +00003092 sqlite3_mutex_enter(pInode->pLockMutex);
drh8af6c222010-05-14 12:43:01 +00003093 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00003094 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00003095 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00003096 SimulateIOErrorBenign(1);
3097 SimulateIOError( h=(-1) )
3098 SimulateIOErrorBenign(0);
3099
drhd3d8c042012-05-29 17:02:40 +00003100#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00003101 /* When reducing a lock such that other processes can start
3102 ** reading the database file again, make sure that the
3103 ** transaction counter was updated if any part of the database
3104 ** file changed. If the transaction counter is not updated,
3105 ** other connections to the same file might not realize that
3106 ** the file has changed and hence might not know to flush their
3107 ** cache. The use of a stale cache can lead to database corruption.
3108 */
3109 assert( pFile->inNormalWrite==0
3110 || pFile->dbUpdate==0
3111 || pFile->transCntrChng==1 );
3112 pFile->inNormalWrite = 0;
3113#endif
aswiftaebf4132008-11-21 00:10:35 +00003114
drh308c2a52010-05-14 11:30:18 +00003115 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00003116 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00003117 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00003118 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00003119 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00003120 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
3121 } else {
3122 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00003123 }
3124 }
drh308c2a52010-05-14 11:30:18 +00003125 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00003126 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00003127 }
drh308c2a52010-05-14 11:30:18 +00003128 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00003129 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
3130 if( !rc ){
3131 context->reserved = 0;
3132 }
aswiftaebf4132008-11-21 00:10:35 +00003133 }
drh8af6c222010-05-14 12:43:01 +00003134 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
3135 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003136 }
aswiftaebf4132008-11-21 00:10:35 +00003137 }
drh308c2a52010-05-14 11:30:18 +00003138 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00003139
drh7ed97b92010-01-20 13:07:21 +00003140 /* Decrement the shared lock counter. Release the lock using an
3141 ** OS call only when all threads in this same process have released
3142 ** the lock.
3143 */
drh8af6c222010-05-14 12:43:01 +00003144 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3145 pInode->nShared--;
3146 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00003147 SimulateIOErrorBenign(1);
3148 SimulateIOError( h=(-1) )
3149 SimulateIOErrorBenign(0);
3150 if( !skipShared ){
3151 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
3152 }
3153 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00003154 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00003155 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003156 }
3157 }
3158 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00003159 pInode->nLock--;
3160 assert( pInode->nLock>=0 );
drhef52b362018-08-13 22:50:34 +00003161 if( pInode->nLock==0 ) closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00003162 }
drhbfe66312006-10-03 17:40:40 +00003163 }
drh7ed97b92010-01-20 13:07:21 +00003164
drhda6dc242018-07-23 21:10:37 +00003165 sqlite3_mutex_leave(pInode->pLockMutex);
drh095908e2018-08-13 20:46:18 +00003166 if( rc==SQLITE_OK ){
3167 pFile->eFileLock = eFileLock;
drh095908e2018-08-13 20:46:18 +00003168 }
drhbfe66312006-10-03 17:40:40 +00003169 return rc;
3170}
3171
3172/*
drh339eb0b2008-03-07 15:34:11 +00003173** Close a file & cleanup AFP specific locking context
3174*/
danielk1977e339d652008-06-28 11:23:00 +00003175static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003176 int rc = SQLITE_OK;
drha8de1e12015-11-30 00:05:39 +00003177 unixFile *pFile = (unixFile*)id;
3178 assert( id!=0 );
3179 afpUnlock(id, NO_LOCK);
drh095908e2018-08-13 20:46:18 +00003180 assert( unixFileMutexNotheld(pFile) );
drha8de1e12015-11-30 00:05:39 +00003181 unixEnterMutex();
drhef52b362018-08-13 22:50:34 +00003182 if( pFile->pInode ){
3183 unixInodeInfo *pInode = pFile->pInode;
3184 sqlite3_mutex_enter(pInode->pLockMutex);
3185 if( pFile->pInode->nLock ){
3186 /* If there are outstanding locks, do not actually close the file just
3187 ** yet because that would clear those locks. Instead, add the file
3188 ** descriptor to pInode->aPending. It will be automatically closed when
3189 ** the last lock is cleared.
3190 */
3191 setPendingFd(pFile);
3192 }
3193 sqlite3_mutex_leave(pInode->pLockMutex);
danielk1977e339d652008-06-28 11:23:00 +00003194 }
drha8de1e12015-11-30 00:05:39 +00003195 releaseInodeInfo(pFile);
3196 sqlite3_free(pFile->lockingContext);
3197 rc = closeUnixFile(id);
3198 unixLeaveMutex();
drh7ed97b92010-01-20 13:07:21 +00003199 return rc;
drhbfe66312006-10-03 17:40:40 +00003200}
3201
drhd2cb50b2009-01-09 21:41:17 +00003202#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003203/*
3204** The code above is the AFP lock implementation. The code is specific
3205** to MacOSX and does not work on other unix platforms. No alternative
3206** is available. If you don't compile for a mac, then the "unix-afp"
3207** VFS is not available.
3208**
3209********************* End of the AFP lock implementation **********************
3210******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003211
drh7ed97b92010-01-20 13:07:21 +00003212/******************************************************************************
3213*************************** Begin NFS Locking ********************************/
3214
3215#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3216/*
drh308c2a52010-05-14 11:30:18 +00003217 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003218 ** must be either NO_LOCK or SHARED_LOCK.
3219 **
3220 ** If the locking level of the file descriptor is already at or below
3221 ** the requested locking level, this routine is a no-op.
3222 */
drh308c2a52010-05-14 11:30:18 +00003223static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003224 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003225}
3226
3227#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3228/*
3229** The code above is the NFS lock implementation. The code is specific
3230** to MacOSX and does not work on other unix platforms. No alternative
3231** is available.
3232**
3233********************* End of the NFS lock implementation **********************
3234******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003235
3236/******************************************************************************
3237**************** Non-locking sqlite3_file methods *****************************
3238**
3239** The next division contains implementations for all methods of the
3240** sqlite3_file object other than the locking methods. The locking
3241** methods were defined in divisions above (one locking method per
3242** division). Those methods that are common to all locking modes
3243** are gather together into this division.
3244*/
drhbfe66312006-10-03 17:40:40 +00003245
3246/*
drh734c9862008-11-28 15:37:20 +00003247** Seek to the offset passed as the second argument, then read cnt
3248** bytes into pBuf. Return the number of bytes actually read.
3249**
3250** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3251** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3252** one system to another. Since SQLite does not define USE_PREAD
peter.d.reid60ec9142014-09-06 16:39:46 +00003253** in any form by default, we will not attempt to define _XOPEN_SOURCE.
drh734c9862008-11-28 15:37:20 +00003254** See tickets #2741 and #2681.
3255**
3256** To avoid stomping the errno value on a failed read the lastErrno value
3257** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003258*/
drh734c9862008-11-28 15:37:20 +00003259static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3260 int got;
drh58024642011-11-07 18:16:00 +00003261 int prior = 0;
drha46cadc2016-03-04 03:02:06 +00003262#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
3263 i64 newOffset;
3264#endif
drh734c9862008-11-28 15:37:20 +00003265 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003266 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003267 assert( id->h>2 );
drh58024642011-11-07 18:16:00 +00003268 do{
drh734c9862008-11-28 15:37:20 +00003269#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003270 got = osPread(id->h, pBuf, cnt, offset);
3271 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003272#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003273 got = osPread64(id->h, pBuf, cnt, offset);
3274 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003275#else
drha46cadc2016-03-04 03:02:06 +00003276 newOffset = lseek(id->h, offset, SEEK_SET);
3277 SimulateIOError( newOffset = -1 );
3278 if( newOffset<0 ){
3279 storeLastErrno((unixFile*)id, errno);
3280 return -1;
3281 }
3282 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003283#endif
drh58024642011-11-07 18:16:00 +00003284 if( got==cnt ) break;
3285 if( got<0 ){
3286 if( errno==EINTR ){ got = 1; continue; }
3287 prior = 0;
drh4bf66fd2015-02-19 02:43:02 +00003288 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003289 break;
3290 }else if( got>0 ){
3291 cnt -= got;
3292 offset += got;
3293 prior += got;
3294 pBuf = (void*)(got + (char*)pBuf);
3295 }
3296 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003297 TIMER_END;
drh58024642011-11-07 18:16:00 +00003298 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3299 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3300 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003301}
3302
3303/*
drh734c9862008-11-28 15:37:20 +00003304** Read data from a file into a buffer. Return SQLITE_OK if all
3305** bytes were read successfully and SQLITE_IOERR if anything goes
3306** wrong.
drh339eb0b2008-03-07 15:34:11 +00003307*/
drh734c9862008-11-28 15:37:20 +00003308static int unixRead(
3309 sqlite3_file *id,
3310 void *pBuf,
3311 int amt,
3312 sqlite3_int64 offset
3313){
dan08da86a2009-08-21 17:18:03 +00003314 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003315 int got;
3316 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003317 assert( offset>=0 );
3318 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003319
dan08da86a2009-08-21 17:18:03 +00003320 /* If this is a database file (not a journal, master-journal or temp
3321 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003322#if 0
drhc68886b2017-08-18 16:09:52 +00003323 assert( pFile->pPreallocatedUnused==0
dan08da86a2009-08-21 17:18:03 +00003324 || offset>=PENDING_BYTE+512
3325 || offset+amt<=PENDING_BYTE
3326 );
dan7c246102010-04-12 19:00:29 +00003327#endif
drh08c6d442009-02-09 17:34:07 +00003328
drh9b4c59f2013-04-15 17:03:42 +00003329#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003330 /* Deal with as much of this read request as possible by transfering
3331 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003332 if( offset<pFile->mmapSize ){
3333 if( offset+amt <= pFile->mmapSize ){
3334 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3335 return SQLITE_OK;
3336 }else{
3337 int nCopy = pFile->mmapSize - offset;
3338 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3339 pBuf = &((u8 *)pBuf)[nCopy];
3340 amt -= nCopy;
3341 offset += nCopy;
3342 }
3343 }
drh6e0b6d52013-04-09 16:19:20 +00003344#endif
danf23da962013-03-23 21:00:41 +00003345
dan08da86a2009-08-21 17:18:03 +00003346 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003347 if( got==amt ){
3348 return SQLITE_OK;
3349 }else if( got<0 ){
3350 /* lastErrno set by seekAndRead */
3351 return SQLITE_IOERR_READ;
3352 }else{
drh4bf66fd2015-02-19 02:43:02 +00003353 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003354 /* Unread parts of the buffer must be zero-filled */
3355 memset(&((char*)pBuf)[got], 0, amt-got);
3356 return SQLITE_IOERR_SHORT_READ;
3357 }
3358}
3359
3360/*
dan47a2b4a2013-04-26 16:09:29 +00003361** Attempt to seek the file-descriptor passed as the first argument to
3362** absolute offset iOff, then attempt to write nBuf bytes of data from
3363** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3364** return the actual number of bytes written (which may be less than
3365** nBuf).
3366*/
3367static int seekAndWriteFd(
3368 int fd, /* File descriptor to write to */
3369 i64 iOff, /* File offset to begin writing at */
3370 const void *pBuf, /* Copy data from this buffer to the file */
3371 int nBuf, /* Size of buffer pBuf in bytes */
3372 int *piErrno /* OUT: Error number if error occurs */
3373){
3374 int rc = 0; /* Value returned by system call */
3375
3376 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003377 assert( fd>2 );
drhe1818ec2015-12-01 16:21:35 +00003378 assert( piErrno!=0 );
dan47a2b4a2013-04-26 16:09:29 +00003379 nBuf &= 0x1ffff;
3380 TIMER_START;
3381
3382#if defined(USE_PREAD)
drh2da47d32015-02-21 00:56:05 +00003383 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
dan47a2b4a2013-04-26 16:09:29 +00003384#elif defined(USE_PREAD64)
drh2da47d32015-02-21 00:56:05 +00003385 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
dan47a2b4a2013-04-26 16:09:29 +00003386#else
3387 do{
3388 i64 iSeek = lseek(fd, iOff, SEEK_SET);
drhe1818ec2015-12-01 16:21:35 +00003389 SimulateIOError( iSeek = -1 );
3390 if( iSeek<0 ){
3391 rc = -1;
3392 break;
dan47a2b4a2013-04-26 16:09:29 +00003393 }
3394 rc = osWrite(fd, pBuf, nBuf);
3395 }while( rc<0 && errno==EINTR );
3396#endif
3397
3398 TIMER_END;
3399 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3400
drhe1818ec2015-12-01 16:21:35 +00003401 if( rc<0 ) *piErrno = errno;
dan47a2b4a2013-04-26 16:09:29 +00003402 return rc;
3403}
3404
3405
3406/*
drh734c9862008-11-28 15:37:20 +00003407** Seek to the offset in id->offset then read cnt bytes into pBuf.
3408** Return the number of bytes actually read. Update the offset.
3409**
3410** To avoid stomping the errno value on a failed write the lastErrno value
3411** is set before returning.
3412*/
3413static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003414 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003415}
3416
3417
3418/*
3419** Write data from a buffer into a file. Return SQLITE_OK on success
3420** or some other error code on failure.
3421*/
3422static int unixWrite(
3423 sqlite3_file *id,
3424 const void *pBuf,
3425 int amt,
3426 sqlite3_int64 offset
3427){
dan08da86a2009-08-21 17:18:03 +00003428 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003429 int wrote = 0;
3430 assert( id );
3431 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003432
dan08da86a2009-08-21 17:18:03 +00003433 /* If this is a database file (not a journal, master-journal or temp
3434 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003435#if 0
drhc68886b2017-08-18 16:09:52 +00003436 assert( pFile->pPreallocatedUnused==0
dan08da86a2009-08-21 17:18:03 +00003437 || offset>=PENDING_BYTE+512
3438 || offset+amt<=PENDING_BYTE
3439 );
dan7c246102010-04-12 19:00:29 +00003440#endif
drh08c6d442009-02-09 17:34:07 +00003441
drhd3d8c042012-05-29 17:02:40 +00003442#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003443 /* If we are doing a normal write to a database file (as opposed to
3444 ** doing a hot-journal rollback or a write to some file other than a
3445 ** normal database file) then record the fact that the database
3446 ** has changed. If the transaction counter is modified, record that
3447 ** fact too.
3448 */
dan08da86a2009-08-21 17:18:03 +00003449 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003450 pFile->dbUpdate = 1; /* The database has been modified */
3451 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003452 int rc;
drh8f941bc2009-01-14 23:03:40 +00003453 char oldCntr[4];
3454 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003455 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003456 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003457 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003458 pFile->transCntrChng = 1; /* The transaction counter has changed */
3459 }
3460 }
3461 }
3462#endif
3463
danfe33e392015-11-17 20:56:06 +00003464#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003465 /* Deal with as much of this write request as possible by transfering
3466 ** data from the memory mapping using memcpy(). */
3467 if( offset<pFile->mmapSize ){
3468 if( offset+amt <= pFile->mmapSize ){
3469 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3470 return SQLITE_OK;
3471 }else{
3472 int nCopy = pFile->mmapSize - offset;
3473 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3474 pBuf = &((u8 *)pBuf)[nCopy];
3475 amt -= nCopy;
3476 offset += nCopy;
3477 }
3478 }
drh6e0b6d52013-04-09 16:19:20 +00003479#endif
drh02bf8b42015-09-01 23:51:53 +00003480
3481 while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
drh734c9862008-11-28 15:37:20 +00003482 amt -= wrote;
3483 offset += wrote;
3484 pBuf = &((char*)pBuf)[wrote];
3485 }
3486 SimulateIOError(( wrote=(-1), amt=1 ));
3487 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003488
drh02bf8b42015-09-01 23:51:53 +00003489 if( amt>wrote ){
drha21b83b2011-04-15 12:36:10 +00003490 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003491 /* lastErrno set by seekAndWrite */
3492 return SQLITE_IOERR_WRITE;
3493 }else{
drh4bf66fd2015-02-19 02:43:02 +00003494 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003495 return SQLITE_FULL;
3496 }
3497 }
dan6e09d692010-07-27 18:34:15 +00003498
drh734c9862008-11-28 15:37:20 +00003499 return SQLITE_OK;
3500}
3501
3502#ifdef SQLITE_TEST
3503/*
3504** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003505** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003506*/
3507int sqlite3_sync_count = 0;
3508int sqlite3_fullsync_count = 0;
3509#endif
3510
3511/*
drh89240432009-03-25 01:06:01 +00003512** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003513** Others do no. To be safe, we will stick with the (slightly slower)
3514** fsync(). If you know that your system does support fdatasync() correctly,
drhf7a4a1b2015-01-10 18:02:45 +00003515** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003516*/
drhf7a4a1b2015-01-10 18:02:45 +00003517#if !defined(fdatasync) && !HAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003518# define fdatasync fsync
3519#endif
3520
3521/*
3522** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3523** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3524** only available on Mac OS X. But that could change.
3525*/
3526#ifdef F_FULLFSYNC
3527# define HAVE_FULLFSYNC 1
3528#else
3529# define HAVE_FULLFSYNC 0
3530#endif
3531
3532
3533/*
3534** The fsync() system call does not work as advertised on many
3535** unix systems. The following procedure is an attempt to make
3536** it work better.
3537**
3538** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3539** for testing when we want to run through the test suite quickly.
3540** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3541** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3542** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003543**
3544** SQLite sets the dataOnly flag if the size of the file is unchanged.
3545** The idea behind dataOnly is that it should only write the file content
3546** to disk, not the inode. We only set dataOnly if the file size is
3547** unchanged since the file size is part of the inode. However,
3548** Ted Ts'o tells us that fdatasync() will also write the inode if the
3549** file size has changed. The only real difference between fdatasync()
3550** and fsync(), Ted tells us, is that fdatasync() will not flush the
3551** inode if the mtime or owner or other inode attributes have changed.
3552** We only care about the file size, not the other file attributes, so
3553** as far as SQLite is concerned, an fdatasync() is always adequate.
3554** So, we always use fdatasync() if it is available, regardless of
3555** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003556*/
3557static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003558 int rc;
drh734c9862008-11-28 15:37:20 +00003559
3560 /* The following "ifdef/elif/else/" block has the same structure as
3561 ** the one below. It is replicated here solely to avoid cluttering
3562 ** up the real code with the UNUSED_PARAMETER() macros.
3563 */
3564#ifdef SQLITE_NO_SYNC
3565 UNUSED_PARAMETER(fd);
3566 UNUSED_PARAMETER(fullSync);
3567 UNUSED_PARAMETER(dataOnly);
3568#elif HAVE_FULLFSYNC
3569 UNUSED_PARAMETER(dataOnly);
3570#else
3571 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003572 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003573#endif
3574
3575 /* Record the number of times that we do a normal fsync() and
3576 ** FULLSYNC. This is used during testing to verify that this procedure
3577 ** gets called with the correct arguments.
3578 */
3579#ifdef SQLITE_TEST
3580 if( fullSync ) sqlite3_fullsync_count++;
3581 sqlite3_sync_count++;
3582#endif
3583
3584 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
drh2c8fd122015-12-02 02:33:36 +00003585 ** no-op. But go ahead and call fstat() to validate the file
3586 ** descriptor as we need a method to provoke a failure during
3587 ** coverate testing.
drh734c9862008-11-28 15:37:20 +00003588 */
3589#ifdef SQLITE_NO_SYNC
drh2c8fd122015-12-02 02:33:36 +00003590 {
3591 struct stat buf;
3592 rc = osFstat(fd, &buf);
3593 }
drh734c9862008-11-28 15:37:20 +00003594#elif HAVE_FULLFSYNC
3595 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003596 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003597 }else{
3598 rc = 1;
3599 }
3600 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003601 ** It shouldn't be possible for fullfsync to fail on the local
3602 ** file system (on OSX), so failure indicates that FULLFSYNC
3603 ** isn't supported for this file system. So, attempt an fsync
3604 ** and (for now) ignore the overhead of a superfluous fcntl call.
3605 ** It'd be better to detect fullfsync support once and avoid
3606 ** the fcntl call every time sync is called.
3607 */
drh734c9862008-11-28 15:37:20 +00003608 if( rc ) rc = fsync(fd);
3609
drh7ed97b92010-01-20 13:07:21 +00003610#elif defined(__APPLE__)
3611 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3612 ** so currently we default to the macro that redefines fdatasync to fsync
3613 */
3614 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003615#else
drh0b647ff2009-03-21 14:41:04 +00003616 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003617#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003618 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003619 rc = fsync(fd);
3620 }
drh0b647ff2009-03-21 14:41:04 +00003621#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003622#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3623
3624 if( OS_VXWORKS && rc!= -1 ){
3625 rc = 0;
3626 }
chw97185482008-11-17 08:05:31 +00003627 return rc;
drhbfe66312006-10-03 17:40:40 +00003628}
3629
drh734c9862008-11-28 15:37:20 +00003630/*
drh0059eae2011-08-08 23:48:40 +00003631** Open a file descriptor to the directory containing file zFilename.
3632** If successful, *pFd is set to the opened file descriptor and
3633** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3634** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3635** value.
3636**
drh90315a22011-08-10 01:52:12 +00003637** The directory file descriptor is used for only one thing - to
3638** fsync() a directory to make sure file creation and deletion events
3639** are flushed to disk. Such fsyncs are not needed on newer
3640** journaling filesystems, but are required on older filesystems.
3641**
3642** This routine can be overridden using the xSetSysCall interface.
3643** The ability to override this routine was added in support of the
3644** chromium sandbox. Opening a directory is a security risk (we are
3645** told) so making it overrideable allows the chromium sandbox to
3646** replace this routine with a harmless no-op. To make this routine
3647** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3648** *pFd set to a negative number.
3649**
drh0059eae2011-08-08 23:48:40 +00003650** If SQLITE_OK is returned, the caller is responsible for closing
3651** the file descriptor *pFd using close().
3652*/
3653static int openDirectory(const char *zFilename, int *pFd){
3654 int ii;
3655 int fd = -1;
3656 char zDirname[MAX_PATHNAME+1];
3657
3658 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drhdc278512015-12-07 18:18:33 +00003659 for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
3660 if( ii>0 ){
drh0059eae2011-08-08 23:48:40 +00003661 zDirname[ii] = '\0';
drhdc278512015-12-07 18:18:33 +00003662 }else{
3663 if( zDirname[0]!='/' ) zDirname[0] = '.';
3664 zDirname[1] = 0;
3665 }
3666 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3667 if( fd>=0 ){
3668 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
drh0059eae2011-08-08 23:48:40 +00003669 }
3670 *pFd = fd;
drhacb6b282015-11-26 10:37:05 +00003671 if( fd>=0 ) return SQLITE_OK;
3672 return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
drh0059eae2011-08-08 23:48:40 +00003673}
3674
3675/*
drh734c9862008-11-28 15:37:20 +00003676** Make sure all writes to a particular file are committed to disk.
3677**
3678** If dataOnly==0 then both the file itself and its metadata (file
3679** size, access time, etc) are synced. If dataOnly!=0 then only the
3680** file data is synced.
3681**
3682** Under Unix, also make sure that the directory entry for the file
3683** has been created by fsync-ing the directory that contains the file.
3684** If we do not do this and we encounter a power failure, the directory
3685** entry for the journal might not exist after we reboot. The next
3686** SQLite to access the file will not know that the journal exists (because
3687** the directory entry for the journal was never created) and the transaction
3688** will not roll back - possibly leading to database corruption.
3689*/
3690static int unixSync(sqlite3_file *id, int flags){
3691 int rc;
3692 unixFile *pFile = (unixFile*)id;
3693
3694 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3695 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3696
3697 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3698 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3699 || (flags&0x0F)==SQLITE_SYNC_FULL
3700 );
3701
3702 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3703 ** line is to test that doing so does not cause any problems.
3704 */
3705 SimulateDiskfullError( return SQLITE_FULL );
3706
3707 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003708 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003709 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3710 SimulateIOError( rc=1 );
3711 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003712 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003713 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003714 }
drh0059eae2011-08-08 23:48:40 +00003715
3716 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003717 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003718 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003719 */
3720 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3721 int dirfd;
3722 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003723 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003724 rc = osOpenDirectory(pFile->zPath, &dirfd);
drhacb6b282015-11-26 10:37:05 +00003725 if( rc==SQLITE_OK ){
drh0059eae2011-08-08 23:48:40 +00003726 full_fsync(dirfd, 0, 0);
3727 robust_close(pFile, dirfd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00003728 }else{
3729 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00003730 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003731 }
drh0059eae2011-08-08 23:48:40 +00003732 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003733 }
3734 return rc;
3735}
3736
3737/*
3738** Truncate an open file to a specified size
3739*/
3740static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003741 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003742 int rc;
dan6e09d692010-07-27 18:34:15 +00003743 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003744 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003745
3746 /* If the user has configured a chunk-size for this file, truncate the
3747 ** file so that it consists of an integer number of chunks (i.e. the
3748 ** actual file size after the operation may be larger than the requested
3749 ** size).
3750 */
drhb8af4b72012-04-05 20:04:39 +00003751 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003752 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3753 }
3754
dan2ee53412014-09-06 16:49:40 +00003755 rc = robust_ftruncate(pFile->h, nByte);
drh734c9862008-11-28 15:37:20 +00003756 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003757 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003758 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003759 }else{
drhd3d8c042012-05-29 17:02:40 +00003760#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003761 /* If we are doing a normal write to a database file (as opposed to
3762 ** doing a hot-journal rollback or a write to some file other than a
3763 ** normal database file) and we truncate the file to zero length,
3764 ** that effectively updates the change counter. This might happen
3765 ** when restoring a database using the backup API from a zero-length
3766 ** source.
3767 */
dan6e09d692010-07-27 18:34:15 +00003768 if( pFile->inNormalWrite && nByte==0 ){
3769 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003770 }
danf23da962013-03-23 21:00:41 +00003771#endif
danc0003312013-03-22 17:46:11 +00003772
mistachkine98844f2013-08-24 00:59:24 +00003773#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003774 /* If the file was just truncated to a size smaller than the currently
3775 ** mapped region, reduce the effective mapping size as well. SQLite will
3776 ** use read() and write() to access data beyond this point from now on.
3777 */
3778 if( nByte<pFile->mmapSize ){
3779 pFile->mmapSize = nByte;
3780 }
mistachkine98844f2013-08-24 00:59:24 +00003781#endif
drh3313b142009-11-06 04:13:18 +00003782
drh734c9862008-11-28 15:37:20 +00003783 return SQLITE_OK;
3784 }
3785}
3786
3787/*
3788** Determine the current size of a file in bytes
3789*/
3790static int unixFileSize(sqlite3_file *id, i64 *pSize){
3791 int rc;
3792 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003793 assert( id );
3794 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003795 SimulateIOError( rc=1 );
3796 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00003797 storeLastErrno((unixFile*)id, errno);
drh734c9862008-11-28 15:37:20 +00003798 return SQLITE_IOERR_FSTAT;
3799 }
3800 *pSize = buf.st_size;
3801
drh8af6c222010-05-14 12:43:01 +00003802 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003803 ** writes a single byte into that file in order to work around a bug
3804 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3805 ** layers, we need to report this file size as zero even though it is
3806 ** really 1. Ticket #3260.
3807 */
3808 if( *pSize==1 ) *pSize = 0;
3809
3810
3811 return SQLITE_OK;
3812}
3813
drhd2cb50b2009-01-09 21:41:17 +00003814#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003815/*
3816** Handler for proxy-locking file-control verbs. Defined below in the
3817** proxying locking division.
3818*/
3819static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003820#endif
drh715ff302008-12-03 22:32:44 +00003821
dan502019c2010-07-28 14:26:17 +00003822/*
3823** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003824** file-control operation. Enlarge the database to nBytes in size
3825** (rounded up to the next chunk-size). If the database is already
3826** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003827*/
3828static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003829 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003830 i64 nSize; /* Required file size */
3831 struct stat buf; /* Used to hold return values of fstat() */
3832
drh4bf66fd2015-02-19 02:43:02 +00003833 if( osFstat(pFile->h, &buf) ){
3834 return SQLITE_IOERR_FSTAT;
3835 }
dan502019c2010-07-28 14:26:17 +00003836
3837 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3838 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003839
dan502019c2010-07-28 14:26:17 +00003840#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003841 /* The code below is handling the return value of osFallocate()
3842 ** correctly. posix_fallocate() is defined to "returns zero on success,
3843 ** or an error number on failure". See the manpage for details. */
3844 int err;
drhff812312011-02-23 13:33:46 +00003845 do{
dan661d71a2011-03-30 19:08:03 +00003846 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3847 }while( err==EINTR );
drh789df142018-06-02 14:37:39 +00003848 if( err && err!=EINVAL ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003849#else
dan592bf7f2014-12-30 19:58:31 +00003850 /* If the OS does not have posix_fallocate(), fake it. Write a
3851 ** single byte to the last byte in each block that falls entirely
3852 ** within the extended region. Then, if required, a single byte
3853 ** at offset (nSize-1), to set the size of the file correctly.
3854 ** This is a similar technique to that used by glibc on systems
3855 ** that do not have a real fallocate() call.
dan502019c2010-07-28 14:26:17 +00003856 */
3857 int nBlk = buf.st_blksize; /* File-system block size */
danef3d66c2015-01-06 21:31:47 +00003858 int nWrite = 0; /* Number of bytes written by seekAndWrite */
dan502019c2010-07-28 14:26:17 +00003859 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003860
drh053378d2015-12-01 22:09:42 +00003861 iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
dan592bf7f2014-12-30 19:58:31 +00003862 assert( iWrite>=buf.st_size );
dan592bf7f2014-12-30 19:58:31 +00003863 assert( ((iWrite+1)%nBlk)==0 );
drh053378d2015-12-01 22:09:42 +00003864 for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
3865 if( iWrite>=nSize ) iWrite = nSize - 1;
danef3d66c2015-01-06 21:31:47 +00003866 nWrite = seekAndWrite(pFile, iWrite, "", 1);
dandc5df0f2011-04-06 19:15:45 +00003867 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dandc5df0f2011-04-06 19:15:45 +00003868 }
dan502019c2010-07-28 14:26:17 +00003869#endif
3870 }
3871 }
3872
mistachkine98844f2013-08-24 00:59:24 +00003873#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003874 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003875 int rc;
3876 if( pFile->szChunk<=0 ){
3877 if( robust_ftruncate(pFile->h, nByte) ){
drh4bf66fd2015-02-19 02:43:02 +00003878 storeLastErrno(pFile, errno);
danf23da962013-03-23 21:00:41 +00003879 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3880 }
3881 }
3882
3883 rc = unixMapfile(pFile, nByte);
3884 return rc;
3885 }
mistachkine98844f2013-08-24 00:59:24 +00003886#endif
danf23da962013-03-23 21:00:41 +00003887
dan502019c2010-07-28 14:26:17 +00003888 return SQLITE_OK;
3889}
danielk1977ad94b582007-08-20 06:44:22 +00003890
danielk1977e3026632004-06-22 11:29:02 +00003891/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003892** If *pArg is initially negative then this is a query. Set *pArg to
drhf12b3f62011-12-21 14:42:29 +00003893** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3894**
3895** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3896*/
3897static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3898 if( *pArg<0 ){
3899 *pArg = (pFile->ctrlFlags & mask)!=0;
3900 }else if( (*pArg)==0 ){
3901 pFile->ctrlFlags &= ~mask;
3902 }else{
3903 pFile->ctrlFlags |= mask;
3904 }
3905}
3906
drh696b33e2012-12-06 19:01:42 +00003907/* Forward declaration */
3908static int unixGetTempname(int nBuf, char *zBuf);
3909
drhf12b3f62011-12-21 14:42:29 +00003910/*
drh9e33c2c2007-08-31 18:34:59 +00003911** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003912*/
drhcc6bb3e2007-08-31 16:11:35 +00003913static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003914 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003915 switch( op ){
drhd76dba72017-07-22 16:00:34 +00003916#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
danefe16972017-07-20 19:49:14 +00003917 case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: {
3918 int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE);
drh344f7632017-07-28 13:18:35 +00003919 return rc ? SQLITE_IOERR_BEGIN_ATOMIC : SQLITE_OK;
danefe16972017-07-20 19:49:14 +00003920 }
3921 case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: {
3922 int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE);
drh344f7632017-07-28 13:18:35 +00003923 return rc ? SQLITE_IOERR_COMMIT_ATOMIC : SQLITE_OK;
danefe16972017-07-20 19:49:14 +00003924 }
3925 case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: {
3926 int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE);
drh344f7632017-07-28 13:18:35 +00003927 return rc ? SQLITE_IOERR_ROLLBACK_ATOMIC : SQLITE_OK;
danefe16972017-07-20 19:49:14 +00003928 }
drhd76dba72017-07-22 16:00:34 +00003929#endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
danefe16972017-07-20 19:49:14 +00003930
drh9e33c2c2007-08-31 18:34:59 +00003931 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003932 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003933 return SQLITE_OK;
3934 }
drh4bf66fd2015-02-19 02:43:02 +00003935 case SQLITE_FCNTL_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003936 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003937 return SQLITE_OK;
3938 }
dan6e09d692010-07-27 18:34:15 +00003939 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003940 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003941 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003942 }
drh9ff27ec2010-05-19 19:26:05 +00003943 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003944 int rc;
3945 SimulateIOErrorBenign(1);
3946 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3947 SimulateIOErrorBenign(0);
3948 return rc;
drhf0b190d2011-07-26 16:03:07 +00003949 }
3950 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003951 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3952 return SQLITE_OK;
3953 }
drhcb15f352011-12-23 01:04:17 +00003954 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3955 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003956 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003957 }
drhde60fc22011-12-14 17:53:36 +00003958 case SQLITE_FCNTL_VFSNAME: {
3959 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3960 return SQLITE_OK;
3961 }
drh696b33e2012-12-06 19:01:42 +00003962 case SQLITE_FCNTL_TEMPFILENAME: {
drhf3cdcdc2015-04-29 16:50:28 +00003963 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
drh696b33e2012-12-06 19:01:42 +00003964 if( zTFile ){
3965 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3966 *(char**)pArg = zTFile;
3967 }
3968 return SQLITE_OK;
3969 }
drhb959a012013-12-07 12:29:22 +00003970 case SQLITE_FCNTL_HAS_MOVED: {
3971 *(int*)pArg = fileHasMoved(pFile);
3972 return SQLITE_OK;
3973 }
drhf0119b22018-03-26 17:40:53 +00003974#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
3975 case SQLITE_FCNTL_LOCK_TIMEOUT: {
3976 pFile->iBusyTimeout = *(int*)pArg;
3977 return SQLITE_OK;
3978 }
3979#endif
mistachkine98844f2013-08-24 00:59:24 +00003980#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003981 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003982 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003983 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003984 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3985 newLimit = sqlite3GlobalConfig.mxMmap;
3986 }
dan43c1e622017-08-07 18:13:28 +00003987
3988 /* The value of newLimit may be eventually cast to (size_t) and passed
mistachkine35395a2017-08-07 19:06:54 +00003989 ** to mmap(). Restrict its value to 2GB if (size_t) is not at least a
3990 ** 64-bit type. */
dan089df502017-08-07 18:54:10 +00003991 if( newLimit>0 && sizeof(size_t)<8 ){
dan43c1e622017-08-07 18:13:28 +00003992 newLimit = (newLimit & 0x7FFFFFFF);
3993 }
3994
drh9b4c59f2013-04-15 17:03:42 +00003995 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003996 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003997 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003998 if( pFile->mmapSize>0 ){
3999 unixUnmapfile(pFile);
4000 rc = unixMapfile(pFile, -1);
4001 }
danbcb8a862013-04-08 15:30:41 +00004002 }
drh34e258c2013-05-23 01:40:53 +00004003 return rc;
danb2d3de32013-03-14 18:34:37 +00004004 }
mistachkine98844f2013-08-24 00:59:24 +00004005#endif
drhd3d8c042012-05-29 17:02:40 +00004006#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00004007 /* The pager calls this method to signal that it has done
4008 ** a rollback and that the database is therefore unchanged and
4009 ** it hence it is OK for the transaction change counter to be
4010 ** unchanged.
4011 */
4012 case SQLITE_FCNTL_DB_UNCHANGED: {
4013 ((unixFile*)id)->dbUpdate = 0;
4014 return SQLITE_OK;
4015 }
4016#endif
drhd2cb50b2009-01-09 21:41:17 +00004017#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh4bf66fd2015-02-19 02:43:02 +00004018 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
4019 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00004020 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00004021 }
drhd2cb50b2009-01-09 21:41:17 +00004022#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00004023 }
drh0b52b7d2011-01-26 19:46:22 +00004024 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00004025}
4026
4027/*
danefe16972017-07-20 19:49:14 +00004028** If pFd->sectorSize is non-zero when this function is called, it is a
4029** no-op. Otherwise, the values of pFd->sectorSize and
4030** pFd->deviceCharacteristics are set according to the file-system
4031** characteristics.
danielk1977a3d4c882007-03-23 10:08:38 +00004032**
danefe16972017-07-20 19:49:14 +00004033** There are two versions of this function. One for QNX and one for all
4034** other systems.
danielk1977a3d4c882007-03-23 10:08:38 +00004035*/
danefe16972017-07-20 19:49:14 +00004036#ifndef __QNXNTO__
4037static void setDeviceCharacteristics(unixFile *pFd){
drhd76dba72017-07-22 16:00:34 +00004038 assert( pFd->deviceCharacteristics==0 || pFd->sectorSize!=0 );
danefe16972017-07-20 19:49:14 +00004039 if( pFd->sectorSize==0 ){
drhd76dba72017-07-22 16:00:34 +00004040#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
danefe16972017-07-20 19:49:14 +00004041 int res;
dan9d709542017-07-21 21:06:24 +00004042 u32 f = 0;
drh537dddf2012-10-26 13:46:24 +00004043
danefe16972017-07-20 19:49:14 +00004044 /* Check for support for F2FS atomic batch writes. */
dan9d709542017-07-21 21:06:24 +00004045 res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES, &f);
4046 if( res==0 && (f & F2FS_FEATURE_ATOMIC_WRITE) ){
dan77b4f522017-07-27 18:34:00 +00004047 pFd->deviceCharacteristics = SQLITE_IOCAP_BATCH_ATOMIC;
danefe16972017-07-20 19:49:14 +00004048 }
drhd76dba72017-07-22 16:00:34 +00004049#endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
danefe16972017-07-20 19:49:14 +00004050
4051 /* Set the POWERSAFE_OVERWRITE flag if requested. */
4052 if( pFd->ctrlFlags & UNIXFILE_PSOW ){
4053 pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
4054 }
4055
4056 pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4057 }
4058}
4059#else
drh537dddf2012-10-26 13:46:24 +00004060#include <sys/dcmd_blk.h>
4061#include <sys/statvfs.h>
danefe16972017-07-20 19:49:14 +00004062static void setDeviceCharacteristics(unixFile *pFile){
drh537dddf2012-10-26 13:46:24 +00004063 if( pFile->sectorSize == 0 ){
4064 struct statvfs fsInfo;
4065
4066 /* Set defaults for non-supported filesystems */
4067 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4068 pFile->deviceCharacteristics = 0;
4069 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
drha9be5082018-01-15 14:32:37 +00004070 return;
drh537dddf2012-10-26 13:46:24 +00004071 }
4072
4073 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
4074 pFile->sectorSize = fsInfo.f_bsize;
4075 pFile->deviceCharacteristics =
4076 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
4077 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4078 ** the write succeeds */
4079 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4080 ** so it is ordered */
4081 0;
4082 }else if( strstr(fsInfo.f_basetype, "etfs") ){
4083 pFile->sectorSize = fsInfo.f_bsize;
4084 pFile->deviceCharacteristics =
4085 /* etfs cluster size writes are atomic */
4086 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
4087 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4088 ** the write succeeds */
4089 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4090 ** so it is ordered */
4091 0;
4092 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
4093 pFile->sectorSize = fsInfo.f_bsize;
4094 pFile->deviceCharacteristics =
4095 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
4096 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4097 ** the write succeeds */
4098 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4099 ** so it is ordered */
4100 0;
4101 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
4102 pFile->sectorSize = fsInfo.f_bsize;
4103 pFile->deviceCharacteristics =
4104 /* full bitset of atomics from max sector size and smaller */
4105 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
4106 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4107 ** so it is ordered */
4108 0;
4109 }else if( strstr(fsInfo.f_basetype, "dos") ){
4110 pFile->sectorSize = fsInfo.f_bsize;
4111 pFile->deviceCharacteristics =
4112 /* full bitset of atomics from max sector size and smaller */
4113 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
4114 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4115 ** so it is ordered */
4116 0;
4117 }else{
4118 pFile->deviceCharacteristics =
4119 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
4120 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4121 ** the write succeeds */
4122 0;
4123 }
4124 }
4125 /* Last chance verification. If the sector size isn't a multiple of 512
4126 ** then it isn't valid.*/
4127 if( pFile->sectorSize % 512 != 0 ){
4128 pFile->deviceCharacteristics = 0;
4129 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4130 }
drh537dddf2012-10-26 13:46:24 +00004131}
danefe16972017-07-20 19:49:14 +00004132#endif
4133
4134/*
4135** Return the sector size in bytes of the underlying block device for
4136** the specified file. This is almost always 512 bytes, but may be
4137** larger for some devices.
4138**
4139** SQLite code assumes this function cannot fail. It also assumes that
4140** if two files are created in the same file-system directory (i.e.
4141** a database and its journal file) that the sector size will be the
4142** same for both.
4143*/
4144static int unixSectorSize(sqlite3_file *id){
4145 unixFile *pFd = (unixFile*)id;
4146 setDeviceCharacteristics(pFd);
4147 return pFd->sectorSize;
4148}
danielk1977a3d4c882007-03-23 10:08:38 +00004149
danielk197790949c22007-08-17 16:50:38 +00004150/*
drhf12b3f62011-12-21 14:42:29 +00004151** Return the device characteristics for the file.
4152**
drhcb15f352011-12-23 01:04:17 +00004153** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
peter.d.reid60ec9142014-09-06 16:39:46 +00004154** However, that choice is controversial since technically the underlying
drhcb15f352011-12-23 01:04:17 +00004155** file system does not always provide powersafe overwrites. (In other
4156** words, after a power-loss event, parts of the file that were never
4157** written might end up being altered.) However, non-PSOW behavior is very,
4158** very rare. And asserting PSOW makes a large reduction in the amount
4159** of required I/O for journaling, since a lot of padding is eliminated.
4160** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
4161** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00004162*/
drhf12b3f62011-12-21 14:42:29 +00004163static int unixDeviceCharacteristics(sqlite3_file *id){
danefe16972017-07-20 19:49:14 +00004164 unixFile *pFd = (unixFile*)id;
4165 setDeviceCharacteristics(pFd);
4166 return pFd->deviceCharacteristics;
danielk197762079062007-08-15 17:08:46 +00004167}
4168
dan702eec12014-06-23 10:04:58 +00004169#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00004170
dan702eec12014-06-23 10:04:58 +00004171/*
4172** Return the system page size.
4173**
4174** This function should not be called directly by other code in this file.
4175** Instead, it should be called via macro osGetpagesize().
4176*/
4177static int unixGetpagesize(void){
drh8cd5b252015-03-02 22:06:43 +00004178#if OS_VXWORKS
4179 return 1024;
4180#elif defined(_BSD_SOURCE)
dan702eec12014-06-23 10:04:58 +00004181 return getpagesize();
4182#else
4183 return (int)sysconf(_SC_PAGESIZE);
4184#endif
4185}
4186
4187#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
4188
4189#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00004190
4191/*
drhd91c68f2010-05-14 14:52:25 +00004192** Object used to represent an shared memory buffer.
4193**
4194** When multiple threads all reference the same wal-index, each thread
4195** has its own unixShm object, but they all point to a single instance
4196** of this unixShmNode object. In other words, each wal-index is opened
4197** only once per process.
4198**
4199** Each unixShmNode object is connected to a single unixInodeInfo object.
4200** We could coalesce this object into unixInodeInfo, but that would mean
4201** every open file that does not use shared memory (in other words, most
4202** open files) would have to carry around this extra information. So
4203** the unixInodeInfo object contains a pointer to this unixShmNode object
4204** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00004205**
4206** unixMutexHeld() must be true when creating or destroying
4207** this object or while reading or writing the following fields:
4208**
4209** nRef
drhd9e5c4f2010-05-12 18:01:39 +00004210**
4211** The following fields are read-only after the object is created:
4212**
4213** fid
4214** zFilename
4215**
drhd91c68f2010-05-14 14:52:25 +00004216** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00004217** unixMutexHeld() is true when reading or writing any other field
4218** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00004219*/
drhd91c68f2010-05-14 14:52:25 +00004220struct unixShmNode {
4221 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00004222 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00004223 char *zFilename; /* Name of the mmapped file */
4224 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00004225 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00004226 u16 nRegion; /* Size of array apRegion */
4227 u8 isReadonly; /* True if read-only */
dan92c02da2017-11-01 20:59:28 +00004228 u8 isUnlocked; /* True if no DMS lock held */
dan18801912010-06-14 14:07:50 +00004229 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00004230 int nRef; /* Number of unixShm objects pointing to this */
4231 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00004232#ifdef SQLITE_DEBUG
4233 u8 exclMask; /* Mask of exclusive locks held */
4234 u8 sharedMask; /* Mask of shared locks held */
4235 u8 nextShmId; /* Next available unixShm.id value */
4236#endif
4237};
4238
4239/*
drhd9e5c4f2010-05-12 18:01:39 +00004240** Structure used internally by this VFS to record the state of an
4241** open shared memory connection.
4242**
drhd91c68f2010-05-14 14:52:25 +00004243** The following fields are initialized when this object is created and
4244** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004245**
drhd91c68f2010-05-14 14:52:25 +00004246** unixShm.pFile
4247** unixShm.id
4248**
4249** All other fields are read/write. The unixShm.pFile->mutex must be held
4250** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004251*/
4252struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004253 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4254 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004255 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004256 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004257 u16 sharedMask; /* Mask of shared locks held */
4258 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004259};
4260
4261/*
drhd9e5c4f2010-05-12 18:01:39 +00004262** Constants used for locking
4263*/
drhbd9676c2010-06-23 17:58:38 +00004264#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004265#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004266
drhd9e5c4f2010-05-12 18:01:39 +00004267/*
drh73b64e42010-05-30 19:55:15 +00004268** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004269**
4270** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4271** otherwise.
4272*/
4273static int unixShmSystemLock(
drhbbf76ee2015-03-10 20:22:35 +00004274 unixFile *pFile, /* Open connection to the WAL file */
drhd91c68f2010-05-14 14:52:25 +00004275 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004276 int ofst, /* First byte of the locking range */
4277 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004278){
drhbbf76ee2015-03-10 20:22:35 +00004279 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4280 struct flock f; /* The posix advisory locking structure */
4281 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004282
drhd91c68f2010-05-14 14:52:25 +00004283 /* Access to the unixShmNode object is serialized by the caller */
drhbbf76ee2015-03-10 20:22:35 +00004284 pShmNode = pFile->pInode->pShmNode;
drh37874b52017-12-13 10:11:09 +00004285 assert( pShmNode->nRef==0 || sqlite3_mutex_held(pShmNode->mutex) );
drhd9e5c4f2010-05-12 18:01:39 +00004286
dan9181ae92017-10-26 17:05:22 +00004287 /* Shared locks never span more than one byte */
4288 assert( n==1 || lockType!=F_RDLCK );
4289
4290 /* Locks are within range */
4291 assert( n>=1 && n<=SQLITE_SHM_NLOCK );
4292
drh3cb93392011-03-12 18:10:44 +00004293 if( pShmNode->h>=0 ){
4294 /* Initialize the locking parameters */
drh3cb93392011-03-12 18:10:44 +00004295 f.l_type = lockType;
4296 f.l_whence = SEEK_SET;
4297 f.l_start = ofst;
4298 f.l_len = n;
drhf0119b22018-03-26 17:40:53 +00004299 rc = osSetPosixAdvisoryLock(pShmNode->h, &f, pFile);
drh3cb93392011-03-12 18:10:44 +00004300 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4301 }
drhd9e5c4f2010-05-12 18:01:39 +00004302
4303 /* Update the global lock state and do debug tracing */
4304#ifdef SQLITE_DEBUG
dan9181ae92017-10-26 17:05:22 +00004305 { u16 mask;
4306 OSTRACE(("SHM-LOCK "));
4307 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
4308 if( rc==SQLITE_OK ){
4309 if( lockType==F_UNLCK ){
4310 OSTRACE(("unlock %d ok", ofst));
4311 pShmNode->exclMask &= ~mask;
4312 pShmNode->sharedMask &= ~mask;
4313 }else if( lockType==F_RDLCK ){
4314 OSTRACE(("read-lock %d ok", ofst));
4315 pShmNode->exclMask &= ~mask;
4316 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004317 }else{
dan9181ae92017-10-26 17:05:22 +00004318 assert( lockType==F_WRLCK );
4319 OSTRACE(("write-lock %d ok", ofst));
4320 pShmNode->exclMask |= mask;
4321 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004322 }
dan9181ae92017-10-26 17:05:22 +00004323 }else{
4324 if( lockType==F_UNLCK ){
4325 OSTRACE(("unlock %d failed", ofst));
4326 }else if( lockType==F_RDLCK ){
4327 OSTRACE(("read-lock failed"));
4328 }else{
4329 assert( lockType==F_WRLCK );
4330 OSTRACE(("write-lock %d failed", ofst));
4331 }
4332 }
4333 OSTRACE((" - afterwards %03x,%03x\n",
4334 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004335 }
drhd9e5c4f2010-05-12 18:01:39 +00004336#endif
4337
4338 return rc;
4339}
4340
dan781e34c2014-03-20 08:59:47 +00004341/*
dan781e34c2014-03-20 08:59:47 +00004342** Return the minimum number of 32KB shm regions that should be mapped at
4343** a time, assuming that each mapping must be an integer multiple of the
4344** current system page-size.
4345**
4346** Usually, this is 1. The exception seems to be systems that are configured
4347** to use 64KB pages - in this case each mapping must cover at least two
4348** shm regions.
4349*/
4350static int unixShmRegionPerMap(void){
4351 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004352 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004353 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4354 if( pgsz<shmsz ) return 1;
4355 return pgsz/shmsz;
4356}
drhd9e5c4f2010-05-12 18:01:39 +00004357
4358/*
drhd91c68f2010-05-14 14:52:25 +00004359** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004360**
4361** This is not a VFS shared-memory method; it is a utility function called
4362** by VFS shared-memory methods.
4363*/
drhd91c68f2010-05-14 14:52:25 +00004364static void unixShmPurge(unixFile *pFd){
4365 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004366 assert( unixMutexHeld() );
drhf3b1ed02015-12-02 13:11:03 +00004367 if( p && ALWAYS(p->nRef==0) ){
dan781e34c2014-03-20 08:59:47 +00004368 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004369 int i;
drhd91c68f2010-05-14 14:52:25 +00004370 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004371 sqlite3_mutex_free(p->mutex);
dan781e34c2014-03-20 08:59:47 +00004372 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh3cb93392011-03-12 18:10:44 +00004373 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004374 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004375 }else{
4376 sqlite3_free(p->apRegion[i]);
4377 }
dan13a3cb82010-06-11 19:04:21 +00004378 }
dan18801912010-06-14 14:07:50 +00004379 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004380 if( p->h>=0 ){
4381 robust_close(pFd, p->h, __LINE__);
4382 p->h = -1;
4383 }
drhd91c68f2010-05-14 14:52:25 +00004384 p->pInode->pShmNode = 0;
4385 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004386 }
4387}
4388
4389/*
dan92c02da2017-11-01 20:59:28 +00004390** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
4391** take it now. Return SQLITE_OK if successful, or an SQLite error
4392** code otherwise.
4393**
4394** If the DMS cannot be locked because this is a readonly_shm=1
4395** connection and no other process already holds a lock, return
drh7e45e3a2017-11-08 17:32:12 +00004396** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
dan92c02da2017-11-01 20:59:28 +00004397*/
4398static int unixLockSharedMemory(unixFile *pDbFd, unixShmNode *pShmNode){
4399 struct flock lock;
4400 int rc = SQLITE_OK;
4401
4402 /* Use F_GETLK to determine the locks other processes are holding
4403 ** on the DMS byte. If it indicates that another process is holding
4404 ** a SHARED lock, then this process may also take a SHARED lock
4405 ** and proceed with opening the *-shm file.
4406 **
4407 ** Or, if no other process is holding any lock, then this process
4408 ** is the first to open it. In this case take an EXCLUSIVE lock on the
4409 ** DMS byte and truncate the *-shm file to zero bytes in size. Then
4410 ** downgrade to a SHARED lock on the DMS byte.
4411 **
4412 ** If another process is holding an EXCLUSIVE lock on the DMS byte,
4413 ** return SQLITE_BUSY to the caller (it will try again). An earlier
4414 ** version of this code attempted the SHARED lock at this point. But
4415 ** this introduced a subtle race condition: if the process holding
4416 ** EXCLUSIVE failed just before truncating the *-shm file, then this
4417 ** process might open and use the *-shm file without truncating it.
4418 ** And if the *-shm file has been corrupted by a power failure or
4419 ** system crash, the database itself may also become corrupt. */
4420 lock.l_whence = SEEK_SET;
4421 lock.l_start = UNIX_SHM_DMS;
4422 lock.l_len = 1;
4423 lock.l_type = F_WRLCK;
4424 if( osFcntl(pShmNode->h, F_GETLK, &lock)!=0 ) {
4425 rc = SQLITE_IOERR_LOCK;
4426 }else if( lock.l_type==F_UNLCK ){
4427 if( pShmNode->isReadonly ){
4428 pShmNode->isUnlocked = 1;
drh7e45e3a2017-11-08 17:32:12 +00004429 rc = SQLITE_READONLY_CANTINIT;
dan92c02da2017-11-01 20:59:28 +00004430 }else{
4431 rc = unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1);
4432 if( rc==SQLITE_OK && robust_ftruncate(pShmNode->h, 0) ){
4433 rc = unixLogError(SQLITE_IOERR_SHMOPEN,"ftruncate",pShmNode->zFilename);
4434 }
4435 }
4436 }else if( lock.l_type==F_WRLCK ){
4437 rc = SQLITE_BUSY;
4438 }
4439
4440 if( rc==SQLITE_OK ){
4441 assert( lock.l_type==F_UNLCK || lock.l_type==F_RDLCK );
4442 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
4443 }
4444 return rc;
4445}
4446
4447/*
danda9fe0c2010-07-13 18:44:03 +00004448** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004449** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004450**
drh7234c6d2010-06-19 15:10:09 +00004451** The file used to implement shared-memory is in the same directory
4452** as the open database file and has the same name as the open database
4453** file with the "-shm" suffix added. For example, if the database file
4454** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004455** for shared memory will be called "/home/user1/config.db-shm".
4456**
4457** Another approach to is to use files in /dev/shm or /dev/tmp or an
4458** some other tmpfs mount. But if a file in a different directory
4459** from the database file is used, then differing access permissions
4460** or a chroot() might cause two different processes on the same
4461** database to end up using different files for shared memory -
4462** meaning that their memory would not really be shared - resulting
4463** in database corruption. Nevertheless, this tmpfs file usage
4464** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4465** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4466** option results in an incompatible build of SQLite; builds of SQLite
4467** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4468** same database file at the same time, database corruption will likely
4469** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4470** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004471**
4472** When opening a new shared-memory file, if no other instances of that
4473** file are currently open, in this process or in other processes, then
4474** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004475**
4476** If the original database file (pDbFd) is using the "unix-excl" VFS
4477** that means that an exclusive lock is held on the database file and
4478** that no other processes are able to read or write the database. In
4479** that case, we do not really need shared memory. No shared memory
4480** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004481*/
danda9fe0c2010-07-13 18:44:03 +00004482static int unixOpenSharedMemory(unixFile *pDbFd){
4483 struct unixShm *p = 0; /* The connection to be opened */
4484 struct unixShmNode *pShmNode; /* The underlying mmapped file */
dan92c02da2017-11-01 20:59:28 +00004485 int rc = SQLITE_OK; /* Result code */
danda9fe0c2010-07-13 18:44:03 +00004486 unixInodeInfo *pInode; /* The inode of fd */
danf12ba662017-11-07 15:43:52 +00004487 char *zShm; /* Name of the file used for SHM */
danda9fe0c2010-07-13 18:44:03 +00004488 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004489
danda9fe0c2010-07-13 18:44:03 +00004490 /* Allocate space for the new unixShm object. */
drhf3cdcdc2015-04-29 16:50:28 +00004491 p = sqlite3_malloc64( sizeof(*p) );
mistachkinfad30392016-02-13 23:43:46 +00004492 if( p==0 ) return SQLITE_NOMEM_BKPT;
drhd9e5c4f2010-05-12 18:01:39 +00004493 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004494 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004495
danda9fe0c2010-07-13 18:44:03 +00004496 /* Check to see if a unixShmNode object already exists. Reuse an existing
4497 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004498 */
drh095908e2018-08-13 20:46:18 +00004499 assert( unixFileMutexNotheld(pDbFd) );
drhd9e5c4f2010-05-12 18:01:39 +00004500 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004501 pInode = pDbFd->pInode;
4502 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004503 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004504 struct stat sStat; /* fstat() info for database file */
drh4bf66fd2015-02-19 02:43:02 +00004505#ifndef SQLITE_SHM_DIRECTORY
4506 const char *zBasePath = pDbFd->zPath;
4507#endif
danddb0ac42010-07-14 14:48:58 +00004508
4509 /* Call fstat() to figure out the permissions on the database file. If
4510 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004511 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004512 */
drhf3b1ed02015-12-02 13:11:03 +00004513 if( osFstat(pDbFd->h, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004514 rc = SQLITE_IOERR_FSTAT;
4515 goto shm_open_err;
4516 }
4517
drha4ced192010-07-15 18:32:40 +00004518#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004519 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004520#else
drh4bf66fd2015-02-19 02:43:02 +00004521 nShmFilename = 6 + (int)strlen(zBasePath);
drha4ced192010-07-15 18:32:40 +00004522#endif
drhf3cdcdc2015-04-29 16:50:28 +00004523 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004524 if( pShmNode==0 ){
mistachkinfad30392016-02-13 23:43:46 +00004525 rc = SQLITE_NOMEM_BKPT;
drhd9e5c4f2010-05-12 18:01:39 +00004526 goto shm_open_err;
4527 }
drh9cb5a0d2012-01-05 21:19:54 +00004528 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
danf12ba662017-11-07 15:43:52 +00004529 zShm = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004530#ifdef SQLITE_SHM_DIRECTORY
danf12ba662017-11-07 15:43:52 +00004531 sqlite3_snprintf(nShmFilename, zShm,
drha4ced192010-07-15 18:32:40 +00004532 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4533 (u32)sStat.st_ino, (u32)sStat.st_dev);
4534#else
danf12ba662017-11-07 15:43:52 +00004535 sqlite3_snprintf(nShmFilename, zShm, "%s-shm", zBasePath);
4536 sqlite3FileSuffix3(pDbFd->zPath, zShm);
drha4ced192010-07-15 18:32:40 +00004537#endif
drhd91c68f2010-05-14 14:52:25 +00004538 pShmNode->h = -1;
4539 pDbFd->pInode->pShmNode = pShmNode;
4540 pShmNode->pInode = pDbFd->pInode;
drh97a7e5e2016-04-26 18:58:54 +00004541 if( sqlite3GlobalConfig.bCoreMutex ){
4542 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4543 if( pShmNode->mutex==0 ){
4544 rc = SQLITE_NOMEM_BKPT;
4545 goto shm_open_err;
4546 }
drhd91c68f2010-05-14 14:52:25 +00004547 }
drhd9e5c4f2010-05-12 18:01:39 +00004548
drh3cb93392011-03-12 18:10:44 +00004549 if( pInode->bProcessLock==0 ){
danf12ba662017-11-07 15:43:52 +00004550 if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
4551 pShmNode->h = robust_open(zShm, O_RDWR|O_CREAT, (sStat.st_mode&0777));
drh3ec4a0c2011-10-11 18:18:54 +00004552 }
drh3cb93392011-03-12 18:10:44 +00004553 if( pShmNode->h<0 ){
danf12ba662017-11-07 15:43:52 +00004554 pShmNode->h = robust_open(zShm, O_RDONLY, (sStat.st_mode&0777));
4555 if( pShmNode->h<0 ){
4556 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShm);
4557 goto shm_open_err;
4558 }
4559 pShmNode->isReadonly = 1;
drhd9e5c4f2010-05-12 18:01:39 +00004560 }
drhac7c3ac2012-02-11 19:23:48 +00004561
4562 /* If this process is running as root, make sure that the SHM file
4563 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004564 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004565 */
drh6226ca22015-11-24 15:06:28 +00004566 robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
dan176b2a92017-11-01 06:59:19 +00004567
dan92c02da2017-11-01 20:59:28 +00004568 rc = unixLockSharedMemory(pDbFd, pShmNode);
drh7e45e3a2017-11-08 17:32:12 +00004569 if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004570 }
drhd9e5c4f2010-05-12 18:01:39 +00004571 }
4572
drhd91c68f2010-05-14 14:52:25 +00004573 /* Make the new connection a child of the unixShmNode */
4574 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004575#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004576 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004577#endif
drhd91c68f2010-05-14 14:52:25 +00004578 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004579 pDbFd->pShm = p;
4580 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004581
4582 /* The reference count on pShmNode has already been incremented under
4583 ** the cover of the unixEnterMutex() mutex and the pointer from the
4584 ** new (struct unixShm) object to the pShmNode has been set. All that is
4585 ** left to do is to link the new object into the linked list starting
4586 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4587 ** mutex.
4588 */
4589 sqlite3_mutex_enter(pShmNode->mutex);
4590 p->pNext = pShmNode->pFirst;
4591 pShmNode->pFirst = p;
4592 sqlite3_mutex_leave(pShmNode->mutex);
dan92c02da2017-11-01 20:59:28 +00004593 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004594
4595 /* Jump here on any error */
4596shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004597 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004598 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004599 unixLeaveMutex();
4600 return rc;
4601}
4602
4603/*
danda9fe0c2010-07-13 18:44:03 +00004604** This function is called to obtain a pointer to region iRegion of the
4605** shared-memory associated with the database file fd. Shared-memory regions
4606** are numbered starting from zero. Each shared-memory region is szRegion
4607** bytes in size.
4608**
4609** If an error occurs, an error code is returned and *pp is set to NULL.
4610**
4611** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4612** region has not been allocated (by any client, including one running in a
4613** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4614** bExtend is non-zero and the requested shared-memory region has not yet
4615** been allocated, it is allocated by this function.
4616**
4617** If the shared-memory region has already been allocated or is allocated by
4618** this call as described above, then it is mapped into this processes
4619** address space (if it is not already), *pp is set to point to the mapped
4620** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004621*/
danda9fe0c2010-07-13 18:44:03 +00004622static int unixShmMap(
4623 sqlite3_file *fd, /* Handle open on database file */
4624 int iRegion, /* Region to retrieve */
4625 int szRegion, /* Size of regions */
4626 int bExtend, /* True to extend file if necessary */
4627 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004628){
danda9fe0c2010-07-13 18:44:03 +00004629 unixFile *pDbFd = (unixFile*)fd;
4630 unixShm *p;
4631 unixShmNode *pShmNode;
4632 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004633 int nShmPerMap = unixShmRegionPerMap();
4634 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004635
danda9fe0c2010-07-13 18:44:03 +00004636 /* If the shared-memory file has not yet been opened, open it now. */
4637 if( pDbFd->pShm==0 ){
4638 rc = unixOpenSharedMemory(pDbFd);
4639 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004640 }
drhd9e5c4f2010-05-12 18:01:39 +00004641
danda9fe0c2010-07-13 18:44:03 +00004642 p = pDbFd->pShm;
4643 pShmNode = p->pShmNode;
4644 sqlite3_mutex_enter(pShmNode->mutex);
dan92c02da2017-11-01 20:59:28 +00004645 if( pShmNode->isUnlocked ){
4646 rc = unixLockSharedMemory(pDbFd, pShmNode);
4647 if( rc!=SQLITE_OK ) goto shmpage_out;
4648 pShmNode->isUnlocked = 0;
4649 }
danda9fe0c2010-07-13 18:44:03 +00004650 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004651 assert( pShmNode->pInode==pDbFd->pInode );
4652 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4653 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004654
dan781e34c2014-03-20 08:59:47 +00004655 /* Minimum number of regions required to be mapped. */
4656 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4657
4658 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004659 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004660 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004661 struct stat sStat; /* Used by fstat() */
4662
4663 pShmNode->szRegion = szRegion;
4664
drh3cb93392011-03-12 18:10:44 +00004665 if( pShmNode->h>=0 ){
4666 /* The requested region is not mapped into this processes address space.
4667 ** Check to see if it has been allocated (i.e. if the wal-index file is
4668 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004669 */
drh3cb93392011-03-12 18:10:44 +00004670 if( osFstat(pShmNode->h, &sStat) ){
4671 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004672 goto shmpage_out;
4673 }
drh3cb93392011-03-12 18:10:44 +00004674
4675 if( sStat.st_size<nByte ){
4676 /* The requested memory region does not exist. If bExtend is set to
4677 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004678 */
dan47a2b4a2013-04-26 16:09:29 +00004679 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004680 goto shmpage_out;
4681 }
dan47a2b4a2013-04-26 16:09:29 +00004682
4683 /* Alternatively, if bExtend is true, extend the file. Do this by
4684 ** writing a single byte to the end of each (OS) page being
4685 ** allocated or extended. Technically, we need only write to the
4686 ** last page in order to extend the file. But writing to all new
4687 ** pages forces the OS to allocate them immediately, which reduces
4688 ** the chances of SIGBUS while accessing the mapped region later on.
4689 */
4690 else{
4691 static const int pgsz = 4096;
4692 int iPg;
4693
4694 /* Write to the last byte of each newly allocated or extended page */
4695 assert( (nByte % pgsz)==0 );
4696 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
drhe1818ec2015-12-01 16:21:35 +00004697 int x = 0;
4698 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
dan47a2b4a2013-04-26 16:09:29 +00004699 const char *zFile = pShmNode->zFilename;
4700 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4701 goto shmpage_out;
4702 }
4703 }
drh3cb93392011-03-12 18:10:44 +00004704 }
4705 }
danda9fe0c2010-07-13 18:44:03 +00004706 }
4707
4708 /* Map the requested memory region into this processes address space. */
4709 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004710 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004711 );
4712 if( !apNew ){
mistachkinfad30392016-02-13 23:43:46 +00004713 rc = SQLITE_IOERR_NOMEM_BKPT;
danda9fe0c2010-07-13 18:44:03 +00004714 goto shmpage_out;
4715 }
4716 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004717 while( pShmNode->nRegion<nReqRegion ){
4718 int nMap = szRegion*nShmPerMap;
4719 int i;
drh3cb93392011-03-12 18:10:44 +00004720 void *pMem;
4721 if( pShmNode->h>=0 ){
dan781e34c2014-03-20 08:59:47 +00004722 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004723 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004724 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004725 );
4726 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004727 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004728 goto shmpage_out;
4729 }
4730 }else{
drhf3cdcdc2015-04-29 16:50:28 +00004731 pMem = sqlite3_malloc64(szRegion);
drh3cb93392011-03-12 18:10:44 +00004732 if( pMem==0 ){
mistachkinfad30392016-02-13 23:43:46 +00004733 rc = SQLITE_NOMEM_BKPT;
drh3cb93392011-03-12 18:10:44 +00004734 goto shmpage_out;
4735 }
4736 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004737 }
dan781e34c2014-03-20 08:59:47 +00004738
4739 for(i=0; i<nShmPerMap; i++){
4740 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4741 }
4742 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004743 }
4744 }
4745
4746shmpage_out:
4747 if( pShmNode->nRegion>iRegion ){
4748 *pp = pShmNode->apRegion[iRegion];
4749 }else{
4750 *pp = 0;
4751 }
drh66dfec8b2011-06-01 20:01:49 +00004752 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004753 sqlite3_mutex_leave(pShmNode->mutex);
4754 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004755}
4756
4757/*
drhd9e5c4f2010-05-12 18:01:39 +00004758** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004759**
4760** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4761** different here than in posix. In xShmLock(), one can go from unlocked
4762** to shared and back or from unlocked to exclusive and back. But one may
4763** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004764*/
4765static int unixShmLock(
4766 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004767 int ofst, /* First lock to acquire or release */
4768 int n, /* Number of locks to acquire or release */
4769 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004770){
drh73b64e42010-05-30 19:55:15 +00004771 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4772 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4773 unixShm *pX; /* For looping over all siblings */
4774 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4775 int rc = SQLITE_OK; /* Result code */
4776 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004777
drhd91c68f2010-05-14 14:52:25 +00004778 assert( pShmNode==pDbFd->pInode->pShmNode );
4779 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004780 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004781 assert( n>=1 );
4782 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4783 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4784 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4785 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4786 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004787 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4788 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004789
drhc99597c2010-05-31 01:41:15 +00004790 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004791 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004792 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004793 if( flags & SQLITE_SHM_UNLOCK ){
4794 u16 allMask = 0; /* Mask of locks held by siblings */
4795
4796 /* See if any siblings hold this same lock */
4797 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4798 if( pX==p ) continue;
4799 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4800 allMask |= pX->sharedMask;
4801 }
4802
4803 /* Unlock the system-level locks */
4804 if( (mask & allMask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004805 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004806 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004807 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004808 }
drh73b64e42010-05-30 19:55:15 +00004809
4810 /* Undo the local locks */
4811 if( rc==SQLITE_OK ){
4812 p->exclMask &= ~mask;
4813 p->sharedMask &= ~mask;
4814 }
4815 }else if( flags & SQLITE_SHM_SHARED ){
4816 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4817
4818 /* Find out which shared locks are already held by sibling connections.
4819 ** If any sibling already holds an exclusive lock, go ahead and return
4820 ** SQLITE_BUSY.
4821 */
4822 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004823 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004824 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004825 break;
4826 }
4827 allShared |= pX->sharedMask;
4828 }
4829
4830 /* Get shared locks at the system level, if necessary */
4831 if( rc==SQLITE_OK ){
4832 if( (allShared & mask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004833 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004834 }else{
drh73b64e42010-05-30 19:55:15 +00004835 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004836 }
drhd9e5c4f2010-05-12 18:01:39 +00004837 }
drh73b64e42010-05-30 19:55:15 +00004838
4839 /* Get the local shared locks */
4840 if( rc==SQLITE_OK ){
4841 p->sharedMask |= mask;
4842 }
4843 }else{
4844 /* Make sure no sibling connections hold locks that will block this
4845 ** lock. If any do, return SQLITE_BUSY right away.
4846 */
4847 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004848 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4849 rc = SQLITE_BUSY;
4850 break;
4851 }
4852 }
4853
4854 /* Get the exclusive locks at the system level. Then if successful
4855 ** also mark the local connection as being locked.
4856 */
4857 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004858 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004859 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004860 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004861 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004862 }
drhd9e5c4f2010-05-12 18:01:39 +00004863 }
4864 }
drhd91c68f2010-05-14 14:52:25 +00004865 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004866 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
drh5ac93652015-03-21 20:59:43 +00004867 p->id, osGetpid(0), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004868 return rc;
4869}
4870
drh286a2882010-05-20 23:51:06 +00004871/*
4872** Implement a memory barrier or memory fence on shared memory.
4873**
4874** All loads and stores begun before the barrier must complete before
4875** any load or store begun after the barrier.
4876*/
4877static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004878 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004879){
drhff828942010-06-26 21:34:06 +00004880 UNUSED_PARAMETER(fd);
drh22c733d2015-09-24 12:40:43 +00004881 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
drh095908e2018-08-13 20:46:18 +00004882 assert( unixFileMutexNotheld((unixFile*)fd) );
drh22c733d2015-09-24 12:40:43 +00004883 unixEnterMutex(); /* Also mutex, for redundancy */
drhb29ad852010-06-01 00:03:57 +00004884 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004885}
4886
dan18801912010-06-14 14:07:50 +00004887/*
danda9fe0c2010-07-13 18:44:03 +00004888** Close a connection to shared-memory. Delete the underlying
4889** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004890**
4891** If there is no shared memory associated with the connection then this
4892** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004893*/
danda9fe0c2010-07-13 18:44:03 +00004894static int unixShmUnmap(
4895 sqlite3_file *fd, /* The underlying database file */
4896 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004897){
danda9fe0c2010-07-13 18:44:03 +00004898 unixShm *p; /* The connection to be closed */
4899 unixShmNode *pShmNode; /* The underlying shared-memory file */
4900 unixShm **pp; /* For looping over sibling connections */
4901 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004902
danda9fe0c2010-07-13 18:44:03 +00004903 pDbFd = (unixFile*)fd;
4904 p = pDbFd->pShm;
4905 if( p==0 ) return SQLITE_OK;
4906 pShmNode = p->pShmNode;
4907
4908 assert( pShmNode==pDbFd->pInode->pShmNode );
4909 assert( pShmNode->pInode==pDbFd->pInode );
4910
4911 /* Remove connection p from the set of connections associated
4912 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004913 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004914 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4915 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004916
danda9fe0c2010-07-13 18:44:03 +00004917 /* Free the connection p */
4918 sqlite3_free(p);
4919 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004920 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004921
4922 /* If pShmNode->nRef has reached 0, then close the underlying
4923 ** shared-memory file, too */
drh095908e2018-08-13 20:46:18 +00004924 assert( unixFileMutexNotheld(pDbFd) );
danda9fe0c2010-07-13 18:44:03 +00004925 unixEnterMutex();
4926 assert( pShmNode->nRef>0 );
4927 pShmNode->nRef--;
4928 if( pShmNode->nRef==0 ){
drh4bf66fd2015-02-19 02:43:02 +00004929 if( deleteFlag && pShmNode->h>=0 ){
4930 osUnlink(pShmNode->zFilename);
4931 }
danda9fe0c2010-07-13 18:44:03 +00004932 unixShmPurge(pDbFd);
4933 }
4934 unixLeaveMutex();
4935
4936 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004937}
drh286a2882010-05-20 23:51:06 +00004938
danda9fe0c2010-07-13 18:44:03 +00004939
drhd9e5c4f2010-05-12 18:01:39 +00004940#else
drh6b017cc2010-06-14 18:01:46 +00004941# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004942# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004943# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004944# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004945#endif /* #ifndef SQLITE_OMIT_WAL */
4946
mistachkine98844f2013-08-24 00:59:24 +00004947#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004948/*
danaef49d72013-03-25 16:28:54 +00004949** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004950*/
danf23da962013-03-23 21:00:41 +00004951static void unixUnmapfile(unixFile *pFd){
4952 assert( pFd->nFetchOut==0 );
4953 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004954 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004955 pFd->pMapRegion = 0;
4956 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004957 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004958 }
4959}
dan5d8a1372013-03-19 19:28:06 +00004960
danaef49d72013-03-25 16:28:54 +00004961/*
dane6ecd662013-04-01 17:56:59 +00004962** Attempt to set the size of the memory mapping maintained by file
4963** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4964**
4965** If successful, this function sets the following variables:
4966**
4967** unixFile.pMapRegion
4968** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004969** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004970**
4971** If unsuccessful, an error message is logged via sqlite3_log() and
4972** the three variables above are zeroed. In this case SQLite should
4973** continue accessing the database using the xRead() and xWrite()
4974** methods.
4975*/
4976static void unixRemapfile(
4977 unixFile *pFd, /* File descriptor object */
4978 i64 nNew /* Required mapping size */
4979){
dan4ff7bc42013-04-02 12:04:09 +00004980 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004981 int h = pFd->h; /* File descriptor open on db file */
4982 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004983 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004984 u8 *pNew = 0; /* Location of new mapping */
4985 int flags = PROT_READ; /* Flags to pass to mmap() */
4986
4987 assert( pFd->nFetchOut==0 );
4988 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004989 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004990 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004991 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004992 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004993
danfe33e392015-11-17 20:56:06 +00004994#ifdef SQLITE_MMAP_READWRITE
dane6ecd662013-04-01 17:56:59 +00004995 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
danfe33e392015-11-17 20:56:06 +00004996#endif
dane6ecd662013-04-01 17:56:59 +00004997
4998 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00004999#if HAVE_MREMAP
5000 i64 nReuse = pFd->mmapSize;
5001#else
danbc760632014-03-20 09:42:09 +00005002 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00005003 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00005004#endif
dane6ecd662013-04-01 17:56:59 +00005005 u8 *pReq = &pOrig[nReuse];
5006
5007 /* Unmap any pages of the existing mapping that cannot be reused. */
5008 if( nReuse!=nOrig ){
5009 osMunmap(pReq, nOrig-nReuse);
5010 }
5011
5012#if HAVE_MREMAP
5013 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00005014 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00005015#else
5016 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
5017 if( pNew!=MAP_FAILED ){
5018 if( pNew!=pReq ){
5019 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00005020 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00005021 }else{
5022 pNew = pOrig;
5023 }
5024 }
5025#endif
5026
dan48ccef82013-04-02 20:55:01 +00005027 /* The attempt to extend the existing mapping failed. Free it. */
5028 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00005029 osMunmap(pOrig, nReuse);
5030 }
5031 }
5032
5033 /* If pNew is still NULL, try to create an entirely new mapping. */
5034 if( pNew==0 ){
5035 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00005036 }
5037
dan4ff7bc42013-04-02 12:04:09 +00005038 if( pNew==MAP_FAILED ){
5039 pNew = 0;
5040 nNew = 0;
5041 unixLogError(SQLITE_OK, zErr, pFd->zPath);
5042
5043 /* If the mmap() above failed, assume that all subsequent mmap() calls
5044 ** will probably fail too. Fall back to using xRead/xWrite exclusively
5045 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00005046 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00005047 }
dane6ecd662013-04-01 17:56:59 +00005048 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00005049 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00005050}
5051
5052/*
danaef49d72013-03-25 16:28:54 +00005053** Memory map or remap the file opened by file-descriptor pFd (if the file
5054** is already mapped, the existing mapping is replaced by the new). Or, if
5055** there already exists a mapping for this file, and there are still
5056** outstanding xFetch() references to it, this function is a no-op.
5057**
5058** If parameter nByte is non-negative, then it is the requested size of
5059** the mapping to create. Otherwise, if nByte is less than zero, then the
5060** requested size is the size of the file on disk. The actual size of the
5061** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00005062** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00005063**
5064** SQLITE_OK is returned if no error occurs (even if the mapping is not
5065** recreated as a result of outstanding references) or an SQLite error
5066** code otherwise.
5067*/
drhf3b1ed02015-12-02 13:11:03 +00005068static int unixMapfile(unixFile *pFd, i64 nMap){
danf23da962013-03-23 21:00:41 +00005069 assert( nMap>=0 || pFd->nFetchOut==0 );
drh333e6ca2015-12-02 15:44:39 +00005070 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00005071 if( pFd->nFetchOut>0 ) return SQLITE_OK;
5072
5073 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00005074 struct stat statbuf; /* Low-level file information */
drhf3b1ed02015-12-02 13:11:03 +00005075 if( osFstat(pFd->h, &statbuf) ){
danf23da962013-03-23 21:00:41 +00005076 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00005077 }
drh3044b512014-06-16 16:41:52 +00005078 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00005079 }
drh9b4c59f2013-04-15 17:03:42 +00005080 if( nMap>pFd->mmapSizeMax ){
5081 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00005082 }
5083
drh333e6ca2015-12-02 15:44:39 +00005084 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00005085 if( nMap!=pFd->mmapSize ){
drh333e6ca2015-12-02 15:44:39 +00005086 unixRemapfile(pFd, nMap);
dan5d8a1372013-03-19 19:28:06 +00005087 }
5088
danf23da962013-03-23 21:00:41 +00005089 return SQLITE_OK;
5090}
mistachkine98844f2013-08-24 00:59:24 +00005091#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00005092
danaef49d72013-03-25 16:28:54 +00005093/*
5094** If possible, return a pointer to a mapping of file fd starting at offset
5095** iOff. The mapping must be valid for at least nAmt bytes.
5096**
5097** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
5098** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
5099** Finally, if an error does occur, return an SQLite error code. The final
5100** value of *pp is undefined in this case.
5101**
5102** If this function does return a pointer, the caller must eventually
5103** release the reference by calling unixUnfetch().
5104*/
danf23da962013-03-23 21:00:41 +00005105static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00005106#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00005107 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00005108#endif
danf23da962013-03-23 21:00:41 +00005109 *pp = 0;
5110
drh9b4c59f2013-04-15 17:03:42 +00005111#if SQLITE_MAX_MMAP_SIZE>0
5112 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00005113 if( pFd->pMapRegion==0 ){
5114 int rc = unixMapfile(pFd, -1);
5115 if( rc!=SQLITE_OK ) return rc;
5116 }
5117 if( pFd->mmapSize >= iOff+nAmt ){
5118 *pp = &((u8 *)pFd->pMapRegion)[iOff];
5119 pFd->nFetchOut++;
5120 }
5121 }
drh6e0b6d52013-04-09 16:19:20 +00005122#endif
danf23da962013-03-23 21:00:41 +00005123 return SQLITE_OK;
5124}
5125
danaef49d72013-03-25 16:28:54 +00005126/*
dandf737fe2013-03-25 17:00:24 +00005127** If the third argument is non-NULL, then this function releases a
5128** reference obtained by an earlier call to unixFetch(). The second
5129** argument passed to this function must be the same as the corresponding
5130** argument that was passed to the unixFetch() invocation.
5131**
5132** Or, if the third argument is NULL, then this function is being called
5133** to inform the VFS layer that, according to POSIX, any existing mapping
5134** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00005135*/
dandf737fe2013-03-25 17:00:24 +00005136static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00005137#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00005138 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00005139 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00005140
danaef49d72013-03-25 16:28:54 +00005141 /* If p==0 (unmap the entire file) then there must be no outstanding
5142 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
5143 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00005144 assert( (p==0)==(pFd->nFetchOut==0) );
5145
dandf737fe2013-03-25 17:00:24 +00005146 /* If p!=0, it must match the iOff value. */
5147 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
5148
danf23da962013-03-23 21:00:41 +00005149 if( p ){
5150 pFd->nFetchOut--;
5151 }else{
5152 unixUnmapfile(pFd);
5153 }
5154
5155 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00005156#else
5157 UNUSED_PARAMETER(fd);
5158 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00005159 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00005160#endif
danf23da962013-03-23 21:00:41 +00005161 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00005162}
5163
5164/*
drh734c9862008-11-28 15:37:20 +00005165** Here ends the implementation of all sqlite3_file methods.
5166**
5167********************** End sqlite3_file Methods *******************************
5168******************************************************************************/
5169
5170/*
drh6b9d6dd2008-12-03 19:34:47 +00005171** This division contains definitions of sqlite3_io_methods objects that
5172** implement various file locking strategies. It also contains definitions
5173** of "finder" functions. A finder-function is used to locate the appropriate
5174** sqlite3_io_methods object for a particular database file. The pAppData
5175** field of the sqlite3_vfs VFS objects are initialized to be pointers to
5176** the correct finder-function for that VFS.
5177**
5178** Most finder functions return a pointer to a fixed sqlite3_io_methods
5179** object. The only interesting finder-function is autolockIoFinder, which
5180** looks at the filesystem type and tries to guess the best locking
5181** strategy from that.
5182**
peter.d.reid60ec9142014-09-06 16:39:46 +00005183** For finder-function F, two objects are created:
drh1875f7a2008-12-08 18:19:17 +00005184**
5185** (1) The real finder-function named "FImpt()".
5186**
dane946c392009-08-22 11:39:46 +00005187** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00005188**
5189**
5190** A pointer to the F pointer is used as the pAppData value for VFS
5191** objects. We have to do this instead of letting pAppData point
5192** directly at the finder-function since C90 rules prevent a void*
5193** from be cast into a function pointer.
5194**
drh6b9d6dd2008-12-03 19:34:47 +00005195**
drh7708e972008-11-29 00:56:52 +00005196** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00005197**
drh7708e972008-11-29 00:56:52 +00005198** * A constant sqlite3_io_methods object call METHOD that has locking
5199** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
5200**
5201** * An I/O method finder function called FINDER that returns a pointer
5202** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00005203*/
drhe6d41732015-02-21 00:49:00 +00005204#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
drh7708e972008-11-29 00:56:52 +00005205static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00005206 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00005207 CLOSE, /* xClose */ \
5208 unixRead, /* xRead */ \
5209 unixWrite, /* xWrite */ \
5210 unixTruncate, /* xTruncate */ \
5211 unixSync, /* xSync */ \
5212 unixFileSize, /* xFileSize */ \
5213 LOCK, /* xLock */ \
5214 UNLOCK, /* xUnlock */ \
5215 CKLOCK, /* xCheckReservedLock */ \
5216 unixFileControl, /* xFileControl */ \
5217 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00005218 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drhd9f94412014-09-22 03:22:27 +00005219 SHMMAP, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00005220 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00005221 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00005222 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00005223 unixFetch, /* xFetch */ \
5224 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00005225}; \
drh0c2694b2009-09-03 16:23:44 +00005226static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
5227 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00005228 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00005229} \
drh0c2694b2009-09-03 16:23:44 +00005230static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00005231 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00005232
5233/*
5234** Here are all of the sqlite3_io_methods objects for each of the
5235** locking strategies. Functions that return pointers to these methods
5236** are also created.
5237*/
5238IOMETHODS(
5239 posixIoFinder, /* Finder function name */
5240 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00005241 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00005242 unixClose, /* xClose method */
5243 unixLock, /* xLock method */
5244 unixUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005245 unixCheckReservedLock, /* xCheckReservedLock method */
5246 unixShmMap /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005247)
drh7708e972008-11-29 00:56:52 +00005248IOMETHODS(
5249 nolockIoFinder, /* Finder function name */
5250 nolockIoMethods, /* sqlite3_io_methods object name */
drh3e2c8422018-08-13 11:32:07 +00005251 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00005252 nolockClose, /* xClose method */
5253 nolockLock, /* xLock method */
5254 nolockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005255 nolockCheckReservedLock, /* xCheckReservedLock method */
5256 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005257)
drh7708e972008-11-29 00:56:52 +00005258IOMETHODS(
5259 dotlockIoFinder, /* Finder function name */
5260 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005261 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005262 dotlockClose, /* xClose method */
5263 dotlockLock, /* xLock method */
5264 dotlockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005265 dotlockCheckReservedLock, /* xCheckReservedLock method */
5266 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005267)
drh7708e972008-11-29 00:56:52 +00005268
drhe89b2912015-03-03 20:42:01 +00005269#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005270IOMETHODS(
5271 flockIoFinder, /* Finder function name */
5272 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005273 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005274 flockClose, /* xClose method */
5275 flockLock, /* xLock method */
5276 flockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005277 flockCheckReservedLock, /* xCheckReservedLock method */
5278 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005279)
drh7708e972008-11-29 00:56:52 +00005280#endif
5281
drh6c7d5c52008-11-21 20:32:33 +00005282#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005283IOMETHODS(
5284 semIoFinder, /* Finder function name */
5285 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005286 1, /* shared memory is disabled */
drh8cd5b252015-03-02 22:06:43 +00005287 semXClose, /* xClose method */
5288 semXLock, /* xLock method */
5289 semXUnlock, /* xUnlock method */
5290 semXCheckReservedLock, /* xCheckReservedLock method */
drhd9f94412014-09-22 03:22:27 +00005291 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005292)
aswiftaebf4132008-11-21 00:10:35 +00005293#endif
drh7708e972008-11-29 00:56:52 +00005294
drhd2cb50b2009-01-09 21:41:17 +00005295#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005296IOMETHODS(
5297 afpIoFinder, /* Finder function name */
5298 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005299 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005300 afpClose, /* xClose method */
5301 afpLock, /* xLock method */
5302 afpUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005303 afpCheckReservedLock, /* xCheckReservedLock method */
5304 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005305)
drh715ff302008-12-03 22:32:44 +00005306#endif
5307
5308/*
5309** The proxy locking method is a "super-method" in the sense that it
5310** opens secondary file descriptors for the conch and lock files and
5311** it uses proxy, dot-file, AFP, and flock() locking methods on those
5312** secondary files. For this reason, the division that implements
5313** proxy locking is located much further down in the file. But we need
5314** to go ahead and define the sqlite3_io_methods and finder function
5315** for proxy locking here. So we forward declare the I/O methods.
5316*/
drhd2cb50b2009-01-09 21:41:17 +00005317#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005318static int proxyClose(sqlite3_file*);
5319static int proxyLock(sqlite3_file*, int);
5320static int proxyUnlock(sqlite3_file*, int);
5321static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005322IOMETHODS(
5323 proxyIoFinder, /* Finder function name */
5324 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005325 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005326 proxyClose, /* xClose method */
5327 proxyLock, /* xLock method */
5328 proxyUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005329 proxyCheckReservedLock, /* xCheckReservedLock method */
5330 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005331)
aswiftaebf4132008-11-21 00:10:35 +00005332#endif
drh7708e972008-11-29 00:56:52 +00005333
drh7ed97b92010-01-20 13:07:21 +00005334/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5335#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5336IOMETHODS(
5337 nfsIoFinder, /* Finder function name */
5338 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005339 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005340 unixClose, /* xClose method */
5341 unixLock, /* xLock method */
5342 nfsUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005343 unixCheckReservedLock, /* xCheckReservedLock method */
5344 0 /* xShmMap method */
drh7ed97b92010-01-20 13:07:21 +00005345)
5346#endif
drh7708e972008-11-29 00:56:52 +00005347
drhd2cb50b2009-01-09 21:41:17 +00005348#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005349/*
drh6b9d6dd2008-12-03 19:34:47 +00005350** This "finder" function attempts to determine the best locking strategy
5351** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005352** object that implements that strategy.
5353**
5354** This is for MacOSX only.
5355*/
drh1875f7a2008-12-08 18:19:17 +00005356static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005357 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005358 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005359){
5360 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005361 const char *zFilesystem; /* Filesystem type name */
5362 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005363 } aMap[] = {
5364 { "hfs", &posixIoMethods },
5365 { "ufs", &posixIoMethods },
5366 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005367 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005368 { "webdav", &nolockIoMethods },
5369 { 0, 0 }
5370 };
5371 int i;
5372 struct statfs fsInfo;
5373 struct flock lockInfo;
5374
5375 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005376 /* If filePath==NULL that means we are dealing with a transient file
5377 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005378 return &nolockIoMethods;
5379 }
5380 if( statfs(filePath, &fsInfo) != -1 ){
5381 if( fsInfo.f_flags & MNT_RDONLY ){
5382 return &nolockIoMethods;
5383 }
5384 for(i=0; aMap[i].zFilesystem; i++){
5385 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5386 return aMap[i].pMethods;
5387 }
5388 }
5389 }
5390
5391 /* Default case. Handles, amongst others, "nfs".
5392 ** Test byte-range lock using fcntl(). If the call succeeds,
5393 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005394 */
drh7708e972008-11-29 00:56:52 +00005395 lockInfo.l_len = 1;
5396 lockInfo.l_start = 0;
5397 lockInfo.l_whence = SEEK_SET;
5398 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005399 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005400 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5401 return &nfsIoMethods;
5402 } else {
5403 return &posixIoMethods;
5404 }
drh7708e972008-11-29 00:56:52 +00005405 }else{
5406 return &dotlockIoMethods;
5407 }
5408}
drh0c2694b2009-09-03 16:23:44 +00005409static const sqlite3_io_methods
5410 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005411
drhd2cb50b2009-01-09 21:41:17 +00005412#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005413
drhe89b2912015-03-03 20:42:01 +00005414#if OS_VXWORKS
5415/*
5416** This "finder" function for VxWorks checks to see if posix advisory
5417** locking works. If it does, then that is what is used. If it does not
5418** work, then fallback to named semaphore locking.
chw78a13182009-04-07 05:35:03 +00005419*/
drhe89b2912015-03-03 20:42:01 +00005420static const sqlite3_io_methods *vxworksIoFinderImpl(
chw78a13182009-04-07 05:35:03 +00005421 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005422 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005423){
5424 struct flock lockInfo;
5425
5426 if( !filePath ){
5427 /* If filePath==NULL that means we are dealing with a transient file
5428 ** that does not need to be locked. */
5429 return &nolockIoMethods;
5430 }
5431
5432 /* Test if fcntl() is supported and use POSIX style locks.
5433 ** Otherwise fall back to the named semaphore method.
5434 */
5435 lockInfo.l_len = 1;
5436 lockInfo.l_start = 0;
5437 lockInfo.l_whence = SEEK_SET;
5438 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005439 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005440 return &posixIoMethods;
5441 }else{
5442 return &semIoMethods;
5443 }
5444}
drh0c2694b2009-09-03 16:23:44 +00005445static const sqlite3_io_methods
drhe89b2912015-03-03 20:42:01 +00005446 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005447
drhe89b2912015-03-03 20:42:01 +00005448#endif /* OS_VXWORKS */
chw78a13182009-04-07 05:35:03 +00005449
drh7708e972008-11-29 00:56:52 +00005450/*
peter.d.reid60ec9142014-09-06 16:39:46 +00005451** An abstract type for a pointer to an IO method finder function:
drh7708e972008-11-29 00:56:52 +00005452*/
drh0c2694b2009-09-03 16:23:44 +00005453typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005454
aswiftaebf4132008-11-21 00:10:35 +00005455
drh734c9862008-11-28 15:37:20 +00005456/****************************************************************************
5457**************************** sqlite3_vfs methods ****************************
5458**
5459** This division contains the implementation of methods on the
5460** sqlite3_vfs object.
5461*/
5462
danielk1977a3d4c882007-03-23 10:08:38 +00005463/*
danielk1977e339d652008-06-28 11:23:00 +00005464** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005465*/
5466static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005467 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005468 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005469 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005470 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005471 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005472){
drh7708e972008-11-29 00:56:52 +00005473 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005474 unixFile *pNew = (unixFile *)pId;
5475 int rc = SQLITE_OK;
5476
drh8af6c222010-05-14 12:43:01 +00005477 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005478
drhb07028f2011-10-14 21:49:18 +00005479 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005480 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005481
drh308c2a52010-05-14 11:30:18 +00005482 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005483 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005484 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005485 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005486 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005487#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005488 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005489#endif
drhc02a43a2012-01-10 23:18:38 +00005490 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5491 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005492 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005493 }
drh503a6862013-03-01 01:07:17 +00005494 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005495 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005496 }
drh339eb0b2008-03-07 15:34:11 +00005497
drh6c7d5c52008-11-21 20:32:33 +00005498#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005499 pNew->pId = vxworksFindFileId(zFilename);
5500 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005501 ctrlFlags |= UNIXFILE_NOLOCK;
mistachkinfad30392016-02-13 23:43:46 +00005502 rc = SQLITE_NOMEM_BKPT;
chw97185482008-11-17 08:05:31 +00005503 }
5504#endif
5505
drhc02a43a2012-01-10 23:18:38 +00005506 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005507 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005508 }else{
drh0c2694b2009-09-03 16:23:44 +00005509 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005510#if SQLITE_ENABLE_LOCKING_STYLE
5511 /* Cache zFilename in the locking context (AFP and dotlock override) for
5512 ** proxyLock activation is possible (remote proxy is based on db name)
5513 ** zFilename remains valid until file is closed, to support */
5514 pNew->lockingContext = (void*)zFilename;
5515#endif
drhda0e7682008-07-30 15:27:54 +00005516 }
danielk1977e339d652008-06-28 11:23:00 +00005517
drh7ed97b92010-01-20 13:07:21 +00005518 if( pLockingStyle == &posixIoMethods
5519#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5520 || pLockingStyle == &nfsIoMethods
5521#endif
5522 ){
drh7708e972008-11-29 00:56:52 +00005523 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005524 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005525 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005526 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005527 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005528 ** in two scenarios:
5529 **
5530 ** (a) A call to fstat() failed.
5531 ** (b) A malloc failed.
5532 **
5533 ** Scenario (b) may only occur if the process is holding no other
5534 ** file descriptors open on the same file. If there were other file
5535 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005536 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005537 ** handle h - as it is guaranteed that no posix locks will be released
5538 ** by doing so.
5539 **
5540 ** If scenario (a) caused the error then things are not so safe. The
5541 ** implicit assumption here is that if fstat() fails, things are in
5542 ** such bad shape that dropping a lock or two doesn't matter much.
5543 */
drh0e9365c2011-03-02 02:08:13 +00005544 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005545 h = -1;
5546 }
drh7708e972008-11-29 00:56:52 +00005547 unixLeaveMutex();
5548 }
danielk1977e339d652008-06-28 11:23:00 +00005549
drhd2cb50b2009-01-09 21:41:17 +00005550#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005551 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005552 /* AFP locking uses the file path so it needs to be included in
5553 ** the afpLockingContext.
5554 */
5555 afpLockingContext *pCtx;
drhf3cdcdc2015-04-29 16:50:28 +00005556 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh7708e972008-11-29 00:56:52 +00005557 if( pCtx==0 ){
mistachkinfad30392016-02-13 23:43:46 +00005558 rc = SQLITE_NOMEM_BKPT;
drh7708e972008-11-29 00:56:52 +00005559 }else{
5560 /* NB: zFilename exists and remains valid until the file is closed
5561 ** according to requirement F11141. So we do not need to make a
5562 ** copy of the filename. */
5563 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005564 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005565 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005566 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005567 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005568 if( rc!=SQLITE_OK ){
5569 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005570 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005571 h = -1;
5572 }
drh7708e972008-11-29 00:56:52 +00005573 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005574 }
drh7708e972008-11-29 00:56:52 +00005575 }
5576#endif
danielk1977e339d652008-06-28 11:23:00 +00005577
drh7708e972008-11-29 00:56:52 +00005578 else if( pLockingStyle == &dotlockIoMethods ){
5579 /* Dotfile locking uses the file path so it needs to be included in
5580 ** the dotlockLockingContext
5581 */
5582 char *zLockFile;
5583 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005584 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005585 nFilename = (int)strlen(zFilename) + 6;
drhf3cdcdc2015-04-29 16:50:28 +00005586 zLockFile = (char *)sqlite3_malloc64(nFilename);
drh7708e972008-11-29 00:56:52 +00005587 if( zLockFile==0 ){
mistachkinfad30392016-02-13 23:43:46 +00005588 rc = SQLITE_NOMEM_BKPT;
drh7708e972008-11-29 00:56:52 +00005589 }else{
5590 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005591 }
drh7708e972008-11-29 00:56:52 +00005592 pNew->lockingContext = zLockFile;
5593 }
danielk1977e339d652008-06-28 11:23:00 +00005594
drh6c7d5c52008-11-21 20:32:33 +00005595#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005596 else if( pLockingStyle == &semIoMethods ){
5597 /* Named semaphore locking uses the file path so it needs to be
5598 ** included in the semLockingContext
5599 */
5600 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005601 rc = findInodeInfo(pNew, &pNew->pInode);
5602 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5603 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005604 int n;
drh2238dcc2009-08-27 17:56:20 +00005605 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005606 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005607 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005608 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005609 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5610 if( pNew->pInode->pSem == SEM_FAILED ){
mistachkinfad30392016-02-13 23:43:46 +00005611 rc = SQLITE_NOMEM_BKPT;
drh8af6c222010-05-14 12:43:01 +00005612 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005613 }
chw97185482008-11-17 08:05:31 +00005614 }
drh7708e972008-11-29 00:56:52 +00005615 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005616 }
drh7708e972008-11-29 00:56:52 +00005617#endif
aswift5b1a2562008-08-22 00:22:35 +00005618
drh4bf66fd2015-02-19 02:43:02 +00005619 storeLastErrno(pNew, 0);
drh6c7d5c52008-11-21 20:32:33 +00005620#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005621 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005622 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005623 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005624 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005625 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005626 }
chw97185482008-11-17 08:05:31 +00005627#endif
danielk1977e339d652008-06-28 11:23:00 +00005628 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005629 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005630 }else{
drh7708e972008-11-29 00:56:52 +00005631 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005632 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005633 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005634 }
danielk1977e339d652008-06-28 11:23:00 +00005635 return rc;
drh054889e2005-11-30 03:20:31 +00005636}
drh9c06c952005-11-26 00:25:00 +00005637
danielk1977ad94b582007-08-20 06:44:22 +00005638/*
drh8b3cf822010-06-01 21:02:51 +00005639** Return the name of a directory in which to put temporary files.
5640** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005641*/
drh7234c6d2010-06-19 15:10:09 +00005642static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005643 static const char *azDirs[] = {
5644 0,
aswiftaebf4132008-11-21 00:10:35 +00005645 0,
danielk197717b90b52008-06-06 11:11:25 +00005646 "/var/tmp",
5647 "/usr/tmp",
5648 "/tmp",
drhb7e50ad2015-11-28 21:49:53 +00005649 "."
danielk197717b90b52008-06-06 11:11:25 +00005650 };
drh2aab11f2016-04-29 20:30:56 +00005651 unsigned int i = 0;
drh8b3cf822010-06-01 21:02:51 +00005652 struct stat buf;
drhb7e50ad2015-11-28 21:49:53 +00005653 const char *zDir = sqlite3_temp_directory;
drh8b3cf822010-06-01 21:02:51 +00005654
drhb7e50ad2015-11-28 21:49:53 +00005655 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
5656 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh2aab11f2016-04-29 20:30:56 +00005657 while(1){
5658 if( zDir!=0
5659 && osStat(zDir, &buf)==0
5660 && S_ISDIR(buf.st_mode)
5661 && osAccess(zDir, 03)==0
5662 ){
5663 return zDir;
5664 }
5665 if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
5666 zDir = azDirs[i++];
drh8b3cf822010-06-01 21:02:51 +00005667 }
drh7694e062016-04-21 23:37:24 +00005668 return 0;
drh8b3cf822010-06-01 21:02:51 +00005669}
5670
5671/*
5672** Create a temporary file name in zBuf. zBuf must be allocated
5673** by the calling process and must be big enough to hold at least
5674** pVfs->mxPathname bytes.
5675*/
5676static int unixGetTempname(int nBuf, char *zBuf){
drh8b3cf822010-06-01 21:02:51 +00005677 const char *zDir;
drhb7e50ad2015-11-28 21:49:53 +00005678 int iLimit = 0;
danielk197717b90b52008-06-06 11:11:25 +00005679
5680 /* It's odd to simulate an io-error here, but really this is just
5681 ** using the io-error infrastructure to test that SQLite handles this
5682 ** function failing.
5683 */
drh7694e062016-04-21 23:37:24 +00005684 zBuf[0] = 0;
danielk197717b90b52008-06-06 11:11:25 +00005685 SimulateIOError( return SQLITE_IOERR );
5686
drh7234c6d2010-06-19 15:10:09 +00005687 zDir = unixTempFileDir();
drh7694e062016-04-21 23:37:24 +00005688 if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
danielk197717b90b52008-06-06 11:11:25 +00005689 do{
drh970942e2015-11-25 23:13:14 +00005690 u64 r;
5691 sqlite3_randomness(sizeof(r), &r);
5692 assert( nBuf>2 );
5693 zBuf[nBuf-2] = 0;
5694 sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
5695 zDir, r, 0);
drhb7e50ad2015-11-28 21:49:53 +00005696 if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
drh99ab3b12011-03-02 15:09:07 +00005697 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005698 return SQLITE_OK;
5699}
5700
drhd2cb50b2009-01-09 21:41:17 +00005701#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005702/*
5703** Routine to transform a unixFile into a proxy-locking unixFile.
5704** Implementation in the proxy-lock division, but used by unixOpen()
5705** if SQLITE_PREFER_PROXY_LOCKING is defined.
5706*/
5707static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005708#endif
drhc66d5b62008-12-03 22:48:32 +00005709
dan08da86a2009-08-21 17:18:03 +00005710/*
5711** Search for an unused file descriptor that was opened on the database
5712** file (not a journal or master-journal file) identified by pathname
5713** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5714** argument to this function.
5715**
5716** Such a file descriptor may exist if a database connection was closed
5717** but the associated file descriptor could not be closed because some
5718** other file descriptor open on the same file is holding a file-lock.
5719** Refer to comments in the unixClose() function and the lengthy comment
5720** describing "Posix Advisory Locking" at the start of this file for
5721** further details. Also, ticket #4018.
5722**
5723** If a suitable file descriptor is found, then it is returned. If no
5724** such file descriptor is located, -1 is returned.
5725*/
dane946c392009-08-22 11:39:46 +00005726static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5727 UnixUnusedFd *pUnused = 0;
5728
5729 /* Do not search for an unused file descriptor on vxworks. Not because
5730 ** vxworks would not benefit from the change (it might, we're not sure),
5731 ** but because no way to test it is currently available. It is better
5732 ** not to risk breaking vxworks support for the sake of such an obscure
5733 ** feature. */
5734#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005735 struct stat sStat; /* Results of stat() call */
5736
drhc68886b2017-08-18 16:09:52 +00005737 unixEnterMutex();
5738
dan08da86a2009-08-21 17:18:03 +00005739 /* A stat() call may fail for various reasons. If this happens, it is
5740 ** almost certain that an open() call on the same path will also fail.
5741 ** For this reason, if an error occurs in the stat() call here, it is
5742 ** ignored and -1 is returned. The caller will try to open a new file
5743 ** descriptor on the same path, fail, and return an error to SQLite.
5744 **
5745 ** Even if a subsequent open() call does succeed, the consequences of
peter.d.reid60ec9142014-09-06 16:39:46 +00005746 ** not searching for a reusable file descriptor are not dire. */
drh095908e2018-08-13 20:46:18 +00005747 if( inodeList!=0 && 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005748 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005749
drh8af6c222010-05-14 12:43:01 +00005750 pInode = inodeList;
5751 while( pInode && (pInode->fileId.dev!=sStat.st_dev
drh25ef7f52016-12-05 20:06:45 +00005752 || pInode->fileId.ino!=(u64)sStat.st_ino) ){
drh8af6c222010-05-14 12:43:01 +00005753 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005754 }
drh8af6c222010-05-14 12:43:01 +00005755 if( pInode ){
dane946c392009-08-22 11:39:46 +00005756 UnixUnusedFd **pp;
drh095908e2018-08-13 20:46:18 +00005757 assert( sqlite3_mutex_notheld(pInode->pLockMutex) );
5758 sqlite3_mutex_enter(pInode->pLockMutex);
drh8af6c222010-05-14 12:43:01 +00005759 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005760 pUnused = *pp;
5761 if( pUnused ){
5762 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005763 }
drh095908e2018-08-13 20:46:18 +00005764 sqlite3_mutex_leave(pInode->pLockMutex);
dan08da86a2009-08-21 17:18:03 +00005765 }
dan08da86a2009-08-21 17:18:03 +00005766 }
drhc68886b2017-08-18 16:09:52 +00005767 unixLeaveMutex();
dane946c392009-08-22 11:39:46 +00005768#endif /* if !OS_VXWORKS */
5769 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005770}
danielk197717b90b52008-06-06 11:11:25 +00005771
5772/*
dan1bf4ca72016-08-11 18:05:47 +00005773** Find the mode, uid and gid of file zFile.
5774*/
5775static int getFileMode(
5776 const char *zFile, /* File name */
5777 mode_t *pMode, /* OUT: Permissions of zFile */
5778 uid_t *pUid, /* OUT: uid of zFile. */
5779 gid_t *pGid /* OUT: gid of zFile. */
5780){
5781 struct stat sStat; /* Output of stat() on database file */
5782 int rc = SQLITE_OK;
5783 if( 0==osStat(zFile, &sStat) ){
5784 *pMode = sStat.st_mode & 0777;
5785 *pUid = sStat.st_uid;
5786 *pGid = sStat.st_gid;
5787 }else{
5788 rc = SQLITE_IOERR_FSTAT;
5789 }
5790 return rc;
5791}
5792
5793/*
danddb0ac42010-07-14 14:48:58 +00005794** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005795** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005796** and a value suitable for passing as the third argument to open(2) is
5797** written to *pMode. If an IO error occurs, an SQLite error code is
5798** returned and the value of *pMode is not modified.
5799**
peter.d.reid60ec9142014-09-06 16:39:46 +00005800** In most cases, this routine sets *pMode to 0, which will become
drh8c815d12012-02-13 20:16:37 +00005801** an indication to robust_open() to create the file using
5802** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5803** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005804** this function queries the file-system for the permissions on the
5805** corresponding database file and sets *pMode to this value. Whenever
5806** possible, WAL and journal files are created using the same permissions
5807** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005808**
5809** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5810** original filename is unavailable. But 8_3_NAMES is only used for
5811** FAT filesystems and permissions do not matter there, so just use
5812** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005813*/
5814static int findCreateFileMode(
5815 const char *zPath, /* Path of file (possibly) being created */
5816 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005817 mode_t *pMode, /* OUT: Permissions to open file with */
5818 uid_t *pUid, /* OUT: uid to set on the file */
5819 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005820){
5821 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005822 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005823 *pUid = 0;
5824 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005825 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005826 char zDb[MAX_PATHNAME+1]; /* Database file path */
5827 int nDb; /* Number of valid bytes in zDb */
danddb0ac42010-07-14 14:48:58 +00005828
dana0c989d2010-11-05 18:07:37 +00005829 /* zPath is a path to a WAL or journal file. The following block derives
5830 ** the path to the associated database file from zPath. This block handles
5831 ** the following naming conventions:
5832 **
5833 ** "<path to db>-journal"
5834 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005835 ** "<path to db>-journalNN"
5836 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005837 **
drhd337c5b2011-10-20 18:23:35 +00005838 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005839 ** used by the test_multiplex.c module.
5840 */
5841 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005842 while( zPath[nDb]!='-' ){
dan629ec142017-09-14 20:41:17 +00005843 /* In normal operation, the journal file name will always contain
5844 ** a '-' character. However in 8+3 filename mode, or if a corrupt
5845 ** rollback journal specifies a master journal with a goofy name, then
5846 ** the '-' might be missing. */
drh90e5dda2015-12-03 20:42:28 +00005847 if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005848 nDb--;
5849 }
danddb0ac42010-07-14 14:48:58 +00005850 memcpy(zDb, zPath, nDb);
5851 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005852
dan1bf4ca72016-08-11 18:05:47 +00005853 rc = getFileMode(zDb, pMode, pUid, pGid);
danddb0ac42010-07-14 14:48:58 +00005854 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5855 *pMode = 0600;
dan1bf4ca72016-08-11 18:05:47 +00005856 }else if( flags & SQLITE_OPEN_URI ){
5857 /* If this is a main database file and the file was opened using a URI
5858 ** filename, check for the "modeof" parameter. If present, interpret
5859 ** its value as a filename and try to copy the mode, uid and gid from
5860 ** that file. */
5861 const char *z = sqlite3_uri_parameter(zPath, "modeof");
5862 if( z ){
5863 rc = getFileMode(z, pMode, pUid, pGid);
5864 }
danddb0ac42010-07-14 14:48:58 +00005865 }
5866 return rc;
5867}
5868
5869/*
danielk1977ad94b582007-08-20 06:44:22 +00005870** Open the file zPath.
5871**
danielk1977b4b47412007-08-17 15:53:36 +00005872** Previously, the SQLite OS layer used three functions in place of this
5873** one:
5874**
5875** sqlite3OsOpenReadWrite();
5876** sqlite3OsOpenReadOnly();
5877** sqlite3OsOpenExclusive();
5878**
5879** These calls correspond to the following combinations of flags:
5880**
5881** ReadWrite() -> (READWRITE | CREATE)
5882** ReadOnly() -> (READONLY)
5883** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5884**
5885** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5886** true, the file was configured to be automatically deleted when the
5887** file handle closed. To achieve the same effect using this new
5888** interface, add the DELETEONCLOSE flag to those specified above for
5889** OpenExclusive().
5890*/
5891static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005892 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5893 const char *zPath, /* Pathname of file to be opened */
5894 sqlite3_file *pFile, /* The file descriptor to be filled in */
5895 int flags, /* Input flags to control the opening */
5896 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005897){
dan08da86a2009-08-21 17:18:03 +00005898 unixFile *p = (unixFile *)pFile;
5899 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005900 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005901 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005902 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005903 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005904 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005905
5906 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5907 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5908 int isCreate = (flags & SQLITE_OPEN_CREATE);
5909 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5910 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005911#if SQLITE_ENABLE_LOCKING_STYLE
5912 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5913#endif
drh3d4435b2011-08-26 20:55:50 +00005914#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5915 struct statfs fsInfo;
5916#endif
danielk1977b4b47412007-08-17 15:53:36 +00005917
danielk1977fee2d252007-08-18 10:59:19 +00005918 /* If creating a master or main-file journal, this function will open
5919 ** a file-descriptor on the directory too. The first time unixSync()
5920 ** is called the directory file descriptor will be fsync()ed and close()d.
5921 */
drha803a2c2017-12-13 20:02:29 +00005922 int isNewJrnl = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005923 eType==SQLITE_OPEN_MASTER_JOURNAL
5924 || eType==SQLITE_OPEN_MAIN_JOURNAL
5925 || eType==SQLITE_OPEN_WAL
5926 ));
danielk1977fee2d252007-08-18 10:59:19 +00005927
danielk197717b90b52008-06-06 11:11:25 +00005928 /* If argument zPath is a NULL pointer, this function is required to open
5929 ** a temporary file. Use this buffer to store the file name in.
5930 */
drhc02a43a2012-01-10 23:18:38 +00005931 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005932 const char *zName = zPath;
5933
danielk1977fee2d252007-08-18 10:59:19 +00005934 /* Check the following statements are true:
5935 **
5936 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5937 ** (b) if CREATE is set, then READWRITE must also be set, and
5938 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005939 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005940 */
danielk1977b4b47412007-08-17 15:53:36 +00005941 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005942 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005943 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005944 assert(isDelete==0 || isCreate);
5945
danddb0ac42010-07-14 14:48:58 +00005946 /* The main DB, main journal, WAL file and master journal are never
5947 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005948 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5949 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5950 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005951 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005952
danielk1977fee2d252007-08-18 10:59:19 +00005953 /* Assert that the upper layer has set one of the "file-type" flags. */
5954 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5955 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5956 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005957 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005958 );
5959
drhb00d8622014-01-01 15:18:36 +00005960 /* Detect a pid change and reset the PRNG. There is a race condition
5961 ** here such that two or more threads all trying to open databases at
5962 ** the same instant might all reset the PRNG. But multiple resets
5963 ** are harmless.
5964 */
drh5ac93652015-03-21 20:59:43 +00005965 if( randomnessPid!=osGetpid(0) ){
5966 randomnessPid = osGetpid(0);
drhb00d8622014-01-01 15:18:36 +00005967 sqlite3_randomness(0,0);
5968 }
dan08da86a2009-08-21 17:18:03 +00005969 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005970
dan08da86a2009-08-21 17:18:03 +00005971 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005972 UnixUnusedFd *pUnused;
5973 pUnused = findReusableFd(zName, flags);
5974 if( pUnused ){
5975 fd = pUnused->fd;
5976 }else{
drhf3cdcdc2015-04-29 16:50:28 +00005977 pUnused = sqlite3_malloc64(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005978 if( !pUnused ){
mistachkinfad30392016-02-13 23:43:46 +00005979 return SQLITE_NOMEM_BKPT;
dane946c392009-08-22 11:39:46 +00005980 }
5981 }
drhc68886b2017-08-18 16:09:52 +00005982 p->pPreallocatedUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005983
5984 /* Database filenames are double-zero terminated if they are not
5985 ** URIs with parameters. Hence, they can always be passed into
5986 ** sqlite3_uri_parameter(). */
5987 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5988
dan08da86a2009-08-21 17:18:03 +00005989 }else if( !zName ){
5990 /* If zName is NULL, the upper layer is requesting a temp file. */
drha803a2c2017-12-13 20:02:29 +00005991 assert(isDelete && !isNewJrnl);
drhb7e50ad2015-11-28 21:49:53 +00005992 rc = unixGetTempname(pVfs->mxPathname, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005993 if( rc!=SQLITE_OK ){
5994 return rc;
5995 }
5996 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005997
5998 /* Generated temporary filenames are always double-zero terminated
5999 ** for use by sqlite3_uri_parameter(). */
6000 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00006001 }
6002
dan08da86a2009-08-21 17:18:03 +00006003 /* Determine the value of the flags parameter passed to POSIX function
6004 ** open(). These must be calculated even if open() is not called, as
6005 ** they may be stored as part of the file handle and used by the
6006 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00006007 if( isReadonly ) openFlags |= O_RDONLY;
6008 if( isReadWrite ) openFlags |= O_RDWR;
6009 if( isCreate ) openFlags |= O_CREAT;
6010 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
6011 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00006012
danielk1977b4b47412007-08-17 15:53:36 +00006013 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00006014 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00006015 uid_t uid; /* Userid for the file */
6016 gid_t gid; /* Groupid for the file */
6017 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00006018 if( rc!=SQLITE_OK ){
drhc68886b2017-08-18 16:09:52 +00006019 assert( !p->pPreallocatedUnused );
drh8ab58662010-07-15 18:38:39 +00006020 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00006021 return rc;
6022 }
drhad4f1e52011-03-04 15:43:57 +00006023 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00006024 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
drh5a2d9702015-11-26 02:21:05 +00006025 assert( !isExclusive || (openFlags & O_CREAT)!=0 );
dana688ca52018-01-10 11:56:03 +00006026 if( fd<0 ){
6027 if( isNewJrnl && errno==EACCES && osAccess(zName, F_OK) ){
6028 /* If unable to create a journal because the directory is not
6029 ** writable, change the error code to indicate that. */
6030 rc = SQLITE_READONLY_DIRECTORY;
6031 }else if( errno!=EISDIR && isReadWrite ){
6032 /* Failed to open the file for read/write access. Try read-only. */
6033 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
6034 openFlags &= ~(O_RDWR|O_CREAT);
6035 flags |= SQLITE_OPEN_READONLY;
6036 openFlags |= O_RDONLY;
6037 isReadonly = 1;
6038 fd = robust_open(zName, openFlags, openMode);
6039 }
dan08da86a2009-08-21 17:18:03 +00006040 }
6041 if( fd<0 ){
dana688ca52018-01-10 11:56:03 +00006042 int rc2 = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
6043 if( rc==SQLITE_OK ) rc = rc2;
dane946c392009-08-22 11:39:46 +00006044 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00006045 }
drhac7c3ac2012-02-11 19:23:48 +00006046
6047 /* If this process is running as root and if creating a new rollback
6048 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00006049 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00006050 */
6051 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drh6226ca22015-11-24 15:06:28 +00006052 robustFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00006053 }
danielk1977b4b47412007-08-17 15:53:36 +00006054 }
dan08da86a2009-08-21 17:18:03 +00006055 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00006056 if( pOutFlags ){
6057 *pOutFlags = flags;
6058 }
6059
drhc68886b2017-08-18 16:09:52 +00006060 if( p->pPreallocatedUnused ){
6061 p->pPreallocatedUnused->fd = fd;
6062 p->pPreallocatedUnused->flags = flags;
dane946c392009-08-22 11:39:46 +00006063 }
6064
danielk1977b4b47412007-08-17 15:53:36 +00006065 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00006066#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006067 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00006068#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
6069 zPath = sqlite3_mprintf("%s", zName);
6070 if( zPath==0 ){
6071 robust_close(p, fd, __LINE__);
mistachkinfad30392016-02-13 23:43:46 +00006072 return SQLITE_NOMEM_BKPT;
drh0bdbc902014-06-16 18:35:06 +00006073 }
chw97185482008-11-17 08:05:31 +00006074#else
drh036ac7f2011-08-08 23:18:05 +00006075 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00006076#endif
danielk1977b4b47412007-08-17 15:53:36 +00006077 }
drh41022642008-11-21 00:24:42 +00006078#if SQLITE_ENABLE_LOCKING_STYLE
6079 else{
dan08da86a2009-08-21 17:18:03 +00006080 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00006081 }
6082#endif
drh7ed97b92010-01-20 13:07:21 +00006083
6084#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00006085 if( fstatfs(fd, &fsInfo) == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00006086 storeLastErrno(p, errno);
drh0e9365c2011-03-02 02:08:13 +00006087 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006088 return SQLITE_IOERR_ACCESS;
6089 }
6090 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
6091 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
6092 }
drh4bf66fd2015-02-19 02:43:02 +00006093 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
6094 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
6095 }
drh7ed97b92010-01-20 13:07:21 +00006096#endif
drhc02a43a2012-01-10 23:18:38 +00006097
6098 /* Set up appropriate ctrlFlags */
6099 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
6100 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
drh86151e82015-12-08 14:37:16 +00006101 noLock = eType!=SQLITE_OPEN_MAIN_DB;
drhc02a43a2012-01-10 23:18:38 +00006102 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
drha803a2c2017-12-13 20:02:29 +00006103 if( isNewJrnl ) ctrlFlags |= UNIXFILE_DIRSYNC;
drhc02a43a2012-01-10 23:18:38 +00006104 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
6105
drh7ed97b92010-01-20 13:07:21 +00006106#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00006107#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00006108 isAutoProxy = 1;
6109#endif
6110 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00006111 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
6112 int useProxy = 0;
6113
dan08da86a2009-08-21 17:18:03 +00006114 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
6115 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00006116 if( envforce!=NULL ){
6117 useProxy = atoi(envforce)>0;
6118 }else{
aswiftaebf4132008-11-21 00:10:35 +00006119 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
6120 }
6121 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00006122 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00006123 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006124 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00006125 if( rc!=SQLITE_OK ){
6126 /* Use unixClose to clean up the resources added in fillInUnixFile
6127 ** and clear all the structure's references. Specifically,
6128 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
6129 */
6130 unixClose(pFile);
6131 return rc;
6132 }
aswiftaebf4132008-11-21 00:10:35 +00006133 }
dane946c392009-08-22 11:39:46 +00006134 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00006135 }
6136 }
6137#endif
6138
dan3ed0f1c2017-09-14 21:12:07 +00006139 assert( zPath==0 || zPath[0]=='/'
6140 || eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL
6141 );
drhc02a43a2012-01-10 23:18:38 +00006142 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
6143
dane946c392009-08-22 11:39:46 +00006144open_finished:
6145 if( rc!=SQLITE_OK ){
drhc68886b2017-08-18 16:09:52 +00006146 sqlite3_free(p->pPreallocatedUnused);
dane946c392009-08-22 11:39:46 +00006147 }
6148 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00006149}
6150
dane946c392009-08-22 11:39:46 +00006151
danielk1977b4b47412007-08-17 15:53:36 +00006152/*
danielk1977fee2d252007-08-18 10:59:19 +00006153** Delete the file at zPath. If the dirSync argument is true, fsync()
6154** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00006155*/
drh6b9d6dd2008-12-03 19:34:47 +00006156static int unixDelete(
6157 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
6158 const char *zPath, /* Name of file to be deleted */
6159 int dirSync /* If true, fsync() directory after deleting file */
6160){
danielk1977fee2d252007-08-18 10:59:19 +00006161 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00006162 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006163 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00006164 if( osUnlink(zPath)==(-1) ){
drhbd945542014-08-13 11:39:42 +00006165 if( errno==ENOENT
6166#if OS_VXWORKS
drh19541f32014-09-01 13:37:55 +00006167 || osAccess(zPath,0)!=0
drhbd945542014-08-13 11:39:42 +00006168#endif
6169 ){
dan9fc5b4a2012-11-09 20:17:26 +00006170 rc = SQLITE_IOERR_DELETE_NOENT;
6171 }else{
drhb4308162012-11-09 21:40:02 +00006172 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00006173 }
drhb4308162012-11-09 21:40:02 +00006174 return rc;
drh5d4feff2010-07-14 01:45:22 +00006175 }
danielk1977d39fa702008-10-16 13:27:40 +00006176#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00006177 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00006178 int fd;
drh90315a22011-08-10 01:52:12 +00006179 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00006180 if( rc==SQLITE_OK ){
drh6d258992016-02-04 09:48:12 +00006181 if( full_fsync(fd,0,0) ){
dane18d4952011-02-21 11:46:24 +00006182 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00006183 }
drh0e9365c2011-03-02 02:08:13 +00006184 robust_close(0, fd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00006185 }else{
6186 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00006187 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00006188 }
6189 }
danielk1977d138dd82008-10-15 16:02:48 +00006190#endif
danielk1977fee2d252007-08-18 10:59:19 +00006191 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00006192}
6193
danielk197790949c22007-08-17 16:50:38 +00006194/*
mistachkin48864df2013-03-21 21:20:32 +00006195** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00006196** test performed depends on the value of flags:
6197**
6198** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
6199** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
6200** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
6201**
6202** Otherwise return 0.
6203*/
danielk1977861f7452008-06-05 11:39:11 +00006204static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00006205 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
6206 const char *zPath, /* Path of the file to examine */
6207 int flags, /* What do we want to learn about the zPath file? */
6208 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00006209){
danielk1977397d65f2008-11-19 11:35:39 +00006210 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00006211 SimulateIOError( return SQLITE_IOERR_ACCESS; );
drhd260b5b2015-11-25 18:03:33 +00006212 assert( pResOut!=0 );
danielk1977b4b47412007-08-17 15:53:36 +00006213
drhd260b5b2015-11-25 18:03:33 +00006214 /* The spec says there are three possible values for flags. But only
6215 ** two of them are actually used */
6216 assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
6217
6218 if( flags==SQLITE_ACCESS_EXISTS ){
dan83acd422010-06-18 11:10:06 +00006219 struct stat buf;
drhd260b5b2015-11-25 18:03:33 +00006220 *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
6221 }else{
6222 *pResOut = osAccess(zPath, W_OK|R_OK)==0;
dan83acd422010-06-18 11:10:06 +00006223 }
danielk1977861f7452008-06-05 11:39:11 +00006224 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006225}
6226
danielk1977b4b47412007-08-17 15:53:36 +00006227/*
danielk1977b4b47412007-08-17 15:53:36 +00006228**
danielk1977b4b47412007-08-17 15:53:36 +00006229*/
dane88ec182016-01-25 17:04:48 +00006230static int mkFullPathname(
dancaf6b152016-01-25 18:05:49 +00006231 const char *zPath, /* Input path */
6232 char *zOut, /* Output buffer */
dane88ec182016-01-25 17:04:48 +00006233 int nOut /* Allocated size of buffer zOut */
danielk1977adfb9b02007-09-17 07:02:56 +00006234){
dancaf6b152016-01-25 18:05:49 +00006235 int nPath = sqlite3Strlen30(zPath);
6236 int iOff = 0;
6237 if( zPath[0]!='/' ){
6238 if( osGetcwd(zOut, nOut-2)==0 ){
dane18d4952011-02-21 11:46:24 +00006239 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006240 }
dancaf6b152016-01-25 18:05:49 +00006241 iOff = sqlite3Strlen30(zOut);
6242 zOut[iOff++] = '/';
danielk1977b4b47412007-08-17 15:53:36 +00006243 }
dan23496702016-01-26 13:56:42 +00006244 if( (iOff+nPath+1)>nOut ){
6245 /* SQLite assumes that xFullPathname() nul-terminates the output buffer
6246 ** even if it returns an error. */
6247 zOut[iOff] = '\0';
6248 return SQLITE_CANTOPEN_BKPT;
6249 }
dancaf6b152016-01-25 18:05:49 +00006250 sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006251 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006252}
6253
dane88ec182016-01-25 17:04:48 +00006254/*
6255** Turn a relative pathname into a full pathname. The relative path
6256** is stored as a nul-terminated string in the buffer pointed to by
6257** zPath.
6258**
6259** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
6260** (in this case, MAX_PATHNAME bytes). The full-path is written to
6261** this buffer before returning.
6262*/
6263static int unixFullPathname(
6264 sqlite3_vfs *pVfs, /* Pointer to vfs object */
6265 const char *zPath, /* Possibly relative input path */
6266 int nOut, /* Size of output buffer in bytes */
6267 char *zOut /* Output buffer */
6268){
danaf1b36b2016-01-25 18:43:05 +00006269#if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
dancaf6b152016-01-25 18:05:49 +00006270 return mkFullPathname(zPath, zOut, nOut);
dane88ec182016-01-25 17:04:48 +00006271#else
6272 int rc = SQLITE_OK;
6273 int nByte;
dancaf6b152016-01-25 18:05:49 +00006274 int nLink = 1; /* Number of symbolic links followed so far */
dane88ec182016-01-25 17:04:48 +00006275 const char *zIn = zPath; /* Input path for each iteration of loop */
6276 char *zDel = 0;
6277
6278 assert( pVfs->mxPathname==MAX_PATHNAME );
6279 UNUSED_PARAMETER(pVfs);
6280
6281 /* It's odd to simulate an io-error here, but really this is just
6282 ** using the io-error infrastructure to test that SQLite handles this
6283 ** function failing. This function could fail if, for example, the
6284 ** current working directory has been unlinked.
6285 */
6286 SimulateIOError( return SQLITE_ERROR );
6287
6288 do {
6289
dancaf6b152016-01-25 18:05:49 +00006290 /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
6291 ** link, or false otherwise. */
6292 int bLink = 0;
6293 struct stat buf;
6294 if( osLstat(zIn, &buf)!=0 ){
6295 if( errno!=ENOENT ){
danaf1b36b2016-01-25 18:43:05 +00006296 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
dane88ec182016-01-25 17:04:48 +00006297 }
dane88ec182016-01-25 17:04:48 +00006298 }else{
dancaf6b152016-01-25 18:05:49 +00006299 bLink = S_ISLNK(buf.st_mode);
6300 }
6301
6302 if( bLink ){
dane88ec182016-01-25 17:04:48 +00006303 if( zDel==0 ){
6304 zDel = sqlite3_malloc(nOut);
mistachkinfad30392016-02-13 23:43:46 +00006305 if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
dancaf6b152016-01-25 18:05:49 +00006306 }else if( ++nLink>SQLITE_MAX_SYMLINKS ){
6307 rc = SQLITE_CANTOPEN_BKPT;
dane88ec182016-01-25 17:04:48 +00006308 }
dancaf6b152016-01-25 18:05:49 +00006309
6310 if( rc==SQLITE_OK ){
6311 nByte = osReadlink(zIn, zDel, nOut-1);
6312 if( nByte<0 ){
6313 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
dan23496702016-01-26 13:56:42 +00006314 }else{
6315 if( zDel[0]!='/' ){
6316 int n;
6317 for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
6318 if( nByte+n+1>nOut ){
6319 rc = SQLITE_CANTOPEN_BKPT;
6320 }else{
6321 memmove(&zDel[n], zDel, nByte+1);
6322 memcpy(zDel, zIn, n);
6323 nByte += n;
6324 }
dancaf6b152016-01-25 18:05:49 +00006325 }
6326 zDel[nByte] = '\0';
6327 }
6328 }
6329
6330 zIn = zDel;
dane88ec182016-01-25 17:04:48 +00006331 }
6332
dan23496702016-01-26 13:56:42 +00006333 assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
6334 if( rc==SQLITE_OK && zIn!=zOut ){
dancaf6b152016-01-25 18:05:49 +00006335 rc = mkFullPathname(zIn, zOut, nOut);
dane88ec182016-01-25 17:04:48 +00006336 }
dancaf6b152016-01-25 18:05:49 +00006337 if( bLink==0 ) break;
6338 zIn = zOut;
6339 }while( rc==SQLITE_OK );
dane88ec182016-01-25 17:04:48 +00006340
6341 sqlite3_free(zDel);
6342 return rc;
danaf1b36b2016-01-25 18:43:05 +00006343#endif /* HAVE_READLINK && HAVE_LSTAT */
dane88ec182016-01-25 17:04:48 +00006344}
6345
drh0ccebe72005-06-07 22:22:50 +00006346
drh761df872006-12-21 01:29:22 +00006347#ifndef SQLITE_OMIT_LOAD_EXTENSION
6348/*
6349** Interfaces for opening a shared library, finding entry points
6350** within the shared library, and closing the shared library.
6351*/
6352#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00006353static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6354 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00006355 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6356}
danielk197795c8a542007-09-01 06:51:27 +00006357
6358/*
6359** SQLite calls this function immediately after a call to unixDlSym() or
6360** unixDlOpen() fails (returns a null pointer). If a more detailed error
6361** message is available, it is written to zBufOut. If no error message
6362** is available, zBufOut is left unmodified and SQLite uses a default
6363** error message.
6364*/
danielk1977397d65f2008-11-19 11:35:39 +00006365static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006366 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006367 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006368 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006369 zErr = dlerror();
6370 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006371 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006372 }
drh6c7d5c52008-11-21 20:32:33 +00006373 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006374}
drh1875f7a2008-12-08 18:19:17 +00006375static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6376 /*
6377 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6378 ** cast into a pointer to a function. And yet the library dlsym() routine
6379 ** returns a void* which is really a pointer to a function. So how do we
6380 ** use dlsym() with -pedantic-errors?
6381 **
6382 ** Variable x below is defined to be a pointer to a function taking
6383 ** parameters void* and const char* and returning a pointer to a function.
6384 ** We initialize x by assigning it a pointer to the dlsym() function.
6385 ** (That assignment requires a cast.) Then we call the function that
6386 ** x points to.
6387 **
6388 ** This work-around is unlikely to work correctly on any system where
6389 ** you really cannot cast a function pointer into void*. But then, on the
6390 ** other hand, dlsym() will not work on such a system either, so we have
6391 ** not really lost anything.
6392 */
6393 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006394 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006395 x = (void(*(*)(void*,const char*))(void))dlsym;
6396 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006397}
danielk1977397d65f2008-11-19 11:35:39 +00006398static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6399 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006400 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006401}
danielk1977b4b47412007-08-17 15:53:36 +00006402#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6403 #define unixDlOpen 0
6404 #define unixDlError 0
6405 #define unixDlSym 0
6406 #define unixDlClose 0
6407#endif
6408
6409/*
danielk197790949c22007-08-17 16:50:38 +00006410** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006411*/
danielk1977397d65f2008-11-19 11:35:39 +00006412static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6413 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006414 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006415
drhbbd42a62004-05-22 17:41:58 +00006416 /* We have to initialize zBuf to prevent valgrind from reporting
6417 ** errors. The reports issued by valgrind are incorrect - we would
6418 ** prefer that the randomness be increased by making use of the
6419 ** uninitialized space in zBuf - but valgrind errors tend to worry
6420 ** some users. Rather than argue, it seems easier just to initialize
6421 ** the whole array and silence valgrind, even if that means less randomness
6422 ** in the random seed.
6423 **
6424 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006425 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006426 ** tests repeatable.
6427 */
danielk1977b4b47412007-08-17 15:53:36 +00006428 memset(zBuf, 0, nBuf);
drh5ac93652015-03-21 20:59:43 +00006429 randomnessPid = osGetpid(0);
drh6a412b82015-04-30 12:31:49 +00006430#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
drhbbd42a62004-05-22 17:41:58 +00006431 {
drhb00d8622014-01-01 15:18:36 +00006432 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006433 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006434 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006435 time_t t;
6436 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006437 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006438 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6439 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6440 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006441 }else{
drhc18b4042012-02-10 03:10:27 +00006442 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006443 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006444 }
drhbbd42a62004-05-22 17:41:58 +00006445 }
6446#endif
drh72cbd072008-10-14 17:58:38 +00006447 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006448}
6449
danielk1977b4b47412007-08-17 15:53:36 +00006450
drhbbd42a62004-05-22 17:41:58 +00006451/*
6452** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006453** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006454** The return value is the number of microseconds of sleep actually
6455** requested from the underlying operating system, a number which
6456** might be greater than or equal to the argument, but not less
6457** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006458*/
danielk1977397d65f2008-11-19 11:35:39 +00006459static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006460#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006461 struct timespec sp;
6462
6463 sp.tv_sec = microseconds / 1000000;
6464 sp.tv_nsec = (microseconds % 1000000) * 1000;
6465 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006466 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006467 return microseconds;
6468#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006469 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006470 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006471 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006472#else
danielk1977b4b47412007-08-17 15:53:36 +00006473 int seconds = (microseconds+999999)/1000000;
6474 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006475 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006476 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006477#endif
drh88f474a2006-01-02 20:00:12 +00006478}
6479
6480/*
drh6b9d6dd2008-12-03 19:34:47 +00006481** The following variable, if set to a non-zero value, is interpreted as
6482** the number of seconds since 1970 and is used to set the result of
6483** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006484*/
6485#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006486int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006487#endif
6488
6489/*
drhb7e8ea22010-05-03 14:32:30 +00006490** Find the current time (in Universal Coordinated Time). Write into *piNow
6491** the current time and date as a Julian Day number times 86_400_000. In
6492** other words, write into *piNow the number of milliseconds since the Julian
6493** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6494** proleptic Gregorian calendar.
6495**
drh31702252011-10-12 23:13:43 +00006496** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6497** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006498*/
6499static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6500 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006501 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006502#if defined(NO_GETTOD)
6503 time_t t;
6504 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006505 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006506#elif OS_VXWORKS
6507 struct timespec sNow;
6508 clock_gettime(CLOCK_REALTIME, &sNow);
6509 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6510#else
6511 struct timeval sNow;
drh970942e2015-11-25 23:13:14 +00006512 (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
6513 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
drhb7e8ea22010-05-03 14:32:30 +00006514#endif
6515
6516#ifdef SQLITE_TEST
6517 if( sqlite3_current_time ){
6518 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6519 }
6520#endif
6521 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006522 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006523}
6524
drhc3dfa5e2016-01-22 19:44:03 +00006525#ifndef SQLITE_OMIT_DEPRECATED
drhb7e8ea22010-05-03 14:32:30 +00006526/*
drhbbd42a62004-05-22 17:41:58 +00006527** Find the current time (in Universal Coordinated Time). Write the
6528** current time and date as a Julian Day number into *prNow and
6529** return 0. Return 1 if the time and date cannot be found.
6530*/
danielk1977397d65f2008-11-19 11:35:39 +00006531static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006532 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006533 int rc;
drhff828942010-06-26 21:34:06 +00006534 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006535 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006536 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006537 return rc;
drhbbd42a62004-05-22 17:41:58 +00006538}
drh5337dac2015-11-25 15:15:03 +00006539#else
6540# define unixCurrentTime 0
6541#endif
danielk1977b4b47412007-08-17 15:53:36 +00006542
drh6b9d6dd2008-12-03 19:34:47 +00006543/*
drh1b9f2142016-03-17 16:01:23 +00006544** The xGetLastError() method is designed to return a better
6545** low-level error message when operating-system problems come up
6546** during SQLite operation. Only the integer return code is currently
6547** used.
drh6b9d6dd2008-12-03 19:34:47 +00006548*/
danielk1977397d65f2008-11-19 11:35:39 +00006549static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6550 UNUSED_PARAMETER(NotUsed);
6551 UNUSED_PARAMETER(NotUsed2);
6552 UNUSED_PARAMETER(NotUsed3);
drh1b9f2142016-03-17 16:01:23 +00006553 return errno;
danielk1977bcb97fe2008-06-06 15:49:29 +00006554}
6555
drhf2424c52010-04-26 00:04:55 +00006556
6557/*
drh734c9862008-11-28 15:37:20 +00006558************************ End of sqlite3_vfs methods ***************************
6559******************************************************************************/
6560
drh715ff302008-12-03 22:32:44 +00006561/******************************************************************************
6562************************** Begin Proxy Locking ********************************
6563**
6564** Proxy locking is a "uber-locking-method" in this sense: It uses the
6565** other locking methods on secondary lock files. Proxy locking is a
6566** meta-layer over top of the primitive locking implemented above. For
6567** this reason, the division that implements of proxy locking is deferred
6568** until late in the file (here) after all of the other I/O methods have
6569** been defined - so that the primitive locking methods are available
6570** as services to help with the implementation of proxy locking.
6571**
6572****
6573**
6574** The default locking schemes in SQLite use byte-range locks on the
6575** database file to coordinate safe, concurrent access by multiple readers
6576** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6577** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6578** as POSIX read & write locks over fixed set of locations (via fsctl),
6579** on AFP and SMB only exclusive byte-range locks are available via fsctl
6580** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6581** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6582** address in the shared range is taken for a SHARED lock, the entire
6583** shared range is taken for an EXCLUSIVE lock):
6584**
drhf2f105d2012-08-20 15:53:54 +00006585** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006586** RESERVED_BYTE 0x40000001
6587** SHARED_RANGE 0x40000002 -> 0x40000200
6588**
6589** This works well on the local file system, but shows a nearly 100x
6590** slowdown in read performance on AFP because the AFP client disables
6591** the read cache when byte-range locks are present. Enabling the read
6592** cache exposes a cache coherency problem that is present on all OS X
6593** supported network file systems. NFS and AFP both observe the
6594** close-to-open semantics for ensuring cache coherency
6595** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6596** address the requirements for concurrent database access by multiple
6597** readers and writers
6598** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6599**
6600** To address the performance and cache coherency issues, proxy file locking
6601** changes the way database access is controlled by limiting access to a
6602** single host at a time and moving file locks off of the database file
6603** and onto a proxy file on the local file system.
6604**
6605**
6606** Using proxy locks
6607** -----------------
6608**
6609** C APIs
6610**
drh4bf66fd2015-02-19 02:43:02 +00006611** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
drh715ff302008-12-03 22:32:44 +00006612** <proxy_path> | ":auto:");
drh4bf66fd2015-02-19 02:43:02 +00006613** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6614** &<proxy_path>);
drh715ff302008-12-03 22:32:44 +00006615**
6616**
6617** SQL pragmas
6618**
6619** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6620** PRAGMA [database.]lock_proxy_file
6621**
6622** Specifying ":auto:" means that if there is a conch file with a matching
6623** host ID in it, the proxy path in the conch file will be used, otherwise
6624** a proxy path based on the user's temp dir
6625** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6626** actual proxy file name is generated from the name and path of the
6627** database file. For example:
6628**
6629** For database path "/Users/me/foo.db"
6630** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6631**
6632** Once a lock proxy is configured for a database connection, it can not
6633** be removed, however it may be switched to a different proxy path via
6634** the above APIs (assuming the conch file is not being held by another
6635** connection or process).
6636**
6637**
6638** How proxy locking works
6639** -----------------------
6640**
6641** Proxy file locking relies primarily on two new supporting files:
6642**
6643** * conch file to limit access to the database file to a single host
6644** at a time
6645**
6646** * proxy file to act as a proxy for the advisory locks normally
6647** taken on the database
6648**
6649** The conch file - to use a proxy file, sqlite must first "hold the conch"
6650** by taking an sqlite-style shared lock on the conch file, reading the
6651** contents and comparing the host's unique host ID (see below) and lock
6652** proxy path against the values stored in the conch. The conch file is
6653** stored in the same directory as the database file and the file name
6654** is patterned after the database file name as ".<databasename>-conch".
peter.d.reid60ec9142014-09-06 16:39:46 +00006655** If the conch file does not exist, or its contents do not match the
drh715ff302008-12-03 22:32:44 +00006656** host ID and/or proxy path, then the lock is escalated to an exclusive
6657** lock and the conch file contents is updated with the host ID and proxy
6658** path and the lock is downgraded to a shared lock again. If the conch
6659** is held by another process (with a shared lock), the exclusive lock
6660** will fail and SQLITE_BUSY is returned.
6661**
6662** The proxy file - a single-byte file used for all advisory file locks
6663** normally taken on the database file. This allows for safe sharing
6664** of the database file for multiple readers and writers on the same
6665** host (the conch ensures that they all use the same local lock file).
6666**
drh715ff302008-12-03 22:32:44 +00006667** Requesting the lock proxy does not immediately take the conch, it is
6668** only taken when the first request to lock database file is made.
6669** This matches the semantics of the traditional locking behavior, where
6670** opening a connection to a database file does not take a lock on it.
6671** The shared lock and an open file descriptor are maintained until
6672** the connection to the database is closed.
6673**
6674** The proxy file and the lock file are never deleted so they only need
6675** to be created the first time they are used.
6676**
6677** Configuration options
6678** ---------------------
6679**
6680** SQLITE_PREFER_PROXY_LOCKING
6681**
6682** Database files accessed on non-local file systems are
6683** automatically configured for proxy locking, lock files are
6684** named automatically using the same logic as
6685** PRAGMA lock_proxy_file=":auto:"
6686**
6687** SQLITE_PROXY_DEBUG
6688**
6689** Enables the logging of error messages during host id file
6690** retrieval and creation
6691**
drh715ff302008-12-03 22:32:44 +00006692** LOCKPROXYDIR
6693**
6694** Overrides the default directory used for lock proxy files that
6695** are named automatically via the ":auto:" setting
6696**
6697** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6698**
6699** Permissions to use when creating a directory for storing the
6700** lock proxy files, only used when LOCKPROXYDIR is not set.
6701**
6702**
6703** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6704** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6705** force proxy locking to be used for every database file opened, and 0
6706** will force automatic proxy locking to be disabled for all database
drh4bf66fd2015-02-19 02:43:02 +00006707** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
drh715ff302008-12-03 22:32:44 +00006708** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6709*/
6710
6711/*
6712** Proxy locking is only available on MacOSX
6713*/
drhd2cb50b2009-01-09 21:41:17 +00006714#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006715
drh715ff302008-12-03 22:32:44 +00006716/*
6717** The proxyLockingContext has the path and file structures for the remote
6718** and local proxy files in it
6719*/
6720typedef struct proxyLockingContext proxyLockingContext;
6721struct proxyLockingContext {
6722 unixFile *conchFile; /* Open conch file */
6723 char *conchFilePath; /* Name of the conch file */
6724 unixFile *lockProxy; /* Open proxy lock file */
6725 char *lockProxyPath; /* Name of the proxy lock file */
6726 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006727 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh4bf66fd2015-02-19 02:43:02 +00006728 int nFails; /* Number of conch taking failures */
drh715ff302008-12-03 22:32:44 +00006729 void *oldLockingContext; /* Original lockingcontext to restore on close */
6730 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6731};
6732
drh7ed97b92010-01-20 13:07:21 +00006733/*
6734** The proxy lock file path for the database at dbPath is written into lPath,
6735** which must point to valid, writable memory large enough for a maxLen length
6736** file path.
drh715ff302008-12-03 22:32:44 +00006737*/
drh715ff302008-12-03 22:32:44 +00006738static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6739 int len;
6740 int dbLen;
6741 int i;
6742
6743#ifdef LOCKPROXYDIR
6744 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6745#else
6746# ifdef _CS_DARWIN_USER_TEMP_DIR
6747 {
drh7ed97b92010-01-20 13:07:21 +00006748 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006749 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006750 lPath, errno, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006751 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006752 }
drh7ed97b92010-01-20 13:07:21 +00006753 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006754 }
6755# else
6756 len = strlcpy(lPath, "/tmp/", maxLen);
6757# endif
6758#endif
6759
6760 if( lPath[len-1]!='/' ){
6761 len = strlcat(lPath, "/", maxLen);
6762 }
6763
6764 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006765 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006766 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006767 char c = dbPath[i];
6768 lPath[i+len] = (c=='/')?'_':c;
6769 }
6770 lPath[i+len]='\0';
6771 strlcat(lPath, ":auto:", maxLen);
drh5ac93652015-03-21 20:59:43 +00006772 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006773 return SQLITE_OK;
6774}
6775
drh7ed97b92010-01-20 13:07:21 +00006776/*
6777 ** Creates the lock file and any missing directories in lockPath
6778 */
6779static int proxyCreateLockPath(const char *lockPath){
6780 int i, len;
6781 char buf[MAXPATHLEN];
6782 int start = 0;
6783
6784 assert(lockPath!=NULL);
6785 /* try to create all the intermediate directories */
6786 len = (int)strlen(lockPath);
6787 buf[0] = lockPath[0];
6788 for( i=1; i<len; i++ ){
6789 if( lockPath[i] == '/' && (i - start > 0) ){
6790 /* only mkdir if leaf dir != "." or "/" or ".." */
6791 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6792 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6793 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006794 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006795 int err=errno;
6796 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006797 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006798 "'%s' proxy lock path=%s pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006799 buf, strerror(err), lockPath, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006800 return err;
6801 }
6802 }
6803 }
6804 start=i+1;
6805 }
6806 buf[i] = lockPath[i];
6807 }
drh62aaa6c2015-11-21 17:27:42 +00006808 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006809 return 0;
6810}
6811
drh715ff302008-12-03 22:32:44 +00006812/*
6813** Create a new VFS file descriptor (stored in memory obtained from
6814** sqlite3_malloc) and open the file named "path" in the file descriptor.
6815**
6816** The caller is responsible not only for closing the file descriptor
6817** but also for freeing the memory associated with the file descriptor.
6818*/
drh7ed97b92010-01-20 13:07:21 +00006819static int proxyCreateUnixFile(
6820 const char *path, /* path for the new unixFile */
6821 unixFile **ppFile, /* unixFile created and returned by ref */
6822 int islockfile /* if non zero missing dirs will be created */
6823) {
6824 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006825 unixFile *pNew;
6826 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006827 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006828 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006829 int terrno = 0;
6830 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006831
drh7ed97b92010-01-20 13:07:21 +00006832 /* 1. first try to open/create the file
6833 ** 2. if that fails, and this is a lock file (not-conch), try creating
6834 ** the parent directories and then try again.
6835 ** 3. if that fails, try to open the file read-only
6836 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6837 */
6838 pUnused = findReusableFd(path, openFlags);
6839 if( pUnused ){
6840 fd = pUnused->fd;
6841 }else{
drhf3cdcdc2015-04-29 16:50:28 +00006842 pUnused = sqlite3_malloc64(sizeof(*pUnused));
drh7ed97b92010-01-20 13:07:21 +00006843 if( !pUnused ){
mistachkinfad30392016-02-13 23:43:46 +00006844 return SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006845 }
6846 }
6847 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006848 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006849 terrno = errno;
6850 if( fd<0 && errno==ENOENT && islockfile ){
6851 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006852 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006853 }
6854 }
6855 }
6856 if( fd<0 ){
6857 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006858 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006859 terrno = errno;
6860 }
6861 if( fd<0 ){
6862 if( islockfile ){
6863 return SQLITE_BUSY;
6864 }
6865 switch (terrno) {
6866 case EACCES:
6867 return SQLITE_PERM;
6868 case EIO:
6869 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6870 default:
drh9978c972010-02-23 17:36:32 +00006871 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006872 }
6873 }
6874
drhf3cdcdc2015-04-29 16:50:28 +00006875 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
drh7ed97b92010-01-20 13:07:21 +00006876 if( pNew==NULL ){
mistachkinfad30392016-02-13 23:43:46 +00006877 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006878 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006879 }
6880 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006881 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006882 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006883 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006884 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006885 pUnused->fd = fd;
6886 pUnused->flags = openFlags;
drhc68886b2017-08-18 16:09:52 +00006887 pNew->pPreallocatedUnused = pUnused;
drh7ed97b92010-01-20 13:07:21 +00006888
drhc02a43a2012-01-10 23:18:38 +00006889 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006890 if( rc==SQLITE_OK ){
6891 *ppFile = pNew;
6892 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006893 }
drh7ed97b92010-01-20 13:07:21 +00006894end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006895 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006896 sqlite3_free(pNew);
6897 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006898 return rc;
6899}
6900
drh7ed97b92010-01-20 13:07:21 +00006901#ifdef SQLITE_TEST
6902/* simulate multiple hosts by creating unique hostid file paths */
6903int sqlite3_hostid_num = 0;
6904#endif
6905
6906#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6907
drh6bca6512015-04-13 23:05:28 +00006908#ifdef HAVE_GETHOSTUUID
drh0ab216a2010-07-02 17:10:40 +00006909/* Not always defined in the headers as it ought to be */
6910extern int gethostuuid(uuid_t id, const struct timespec *wait);
drh6bca6512015-04-13 23:05:28 +00006911#endif
drh0ab216a2010-07-02 17:10:40 +00006912
drh7ed97b92010-01-20 13:07:21 +00006913/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6914** bytes of writable memory.
6915*/
6916static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006917 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6918 memset(pHostID, 0, PROXY_HOSTIDLEN);
drh6bca6512015-04-13 23:05:28 +00006919#ifdef HAVE_GETHOSTUUID
drh29ecd8a2010-12-21 00:16:40 +00006920 {
drh4bf66fd2015-02-19 02:43:02 +00006921 struct timespec timeout = {1, 0}; /* 1 sec timeout */
drh29ecd8a2010-12-21 00:16:40 +00006922 if( gethostuuid(pHostID, &timeout) ){
6923 int err = errno;
6924 if( pError ){
6925 *pError = err;
6926 }
6927 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006928 }
drh7ed97b92010-01-20 13:07:21 +00006929 }
drh3d4435b2011-08-26 20:55:50 +00006930#else
6931 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006932#endif
drh7ed97b92010-01-20 13:07:21 +00006933#ifdef SQLITE_TEST
6934 /* simulate multiple hosts by creating unique hostid file paths */
6935 if( sqlite3_hostid_num != 0){
6936 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6937 }
6938#endif
6939
6940 return SQLITE_OK;
6941}
6942
6943/* The conch file contains the header, host id and lock file path
6944 */
6945#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6946#define PROXY_HEADERLEN 1 /* conch file header length */
6947#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6948#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6949
6950/*
6951** Takes an open conch file, copies the contents to a new path and then moves
6952** it back. The newly created file's file descriptor is assigned to the
6953** conch file structure and finally the original conch file descriptor is
6954** closed. Returns zero if successful.
6955*/
6956static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6957 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6958 unixFile *conchFile = pCtx->conchFile;
6959 char tPath[MAXPATHLEN];
6960 char buf[PROXY_MAXCONCHLEN];
6961 char *cPath = pCtx->conchFilePath;
6962 size_t readLen = 0;
6963 size_t pathLen = 0;
6964 char errmsg[64] = "";
6965 int fd = -1;
6966 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006967 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006968
6969 /* create a new path by replace the trailing '-conch' with '-break' */
6970 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6971 if( pathLen>MAXPATHLEN || pathLen<6 ||
6972 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006973 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006974 goto end_breaklock;
6975 }
6976 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006977 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006978 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006979 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006980 goto end_breaklock;
6981 }
6982 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006983 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006984 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006985 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006986 goto end_breaklock;
6987 }
drhe562be52011-03-02 18:01:10 +00006988 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006989 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006990 goto end_breaklock;
6991 }
6992 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006993 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006994 goto end_breaklock;
6995 }
6996 rc = 0;
6997 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006998 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006999 conchFile->h = fd;
7000 conchFile->openFlags = O_RDWR | O_CREAT;
7001
7002end_breaklock:
7003 if( rc ){
7004 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00007005 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00007006 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00007007 }
7008 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
7009 }
7010 return rc;
7011}
7012
7013/* Take the requested lock on the conch file and break a stale lock if the
7014** host id matches.
7015*/
7016static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
7017 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7018 unixFile *conchFile = pCtx->conchFile;
7019 int rc = SQLITE_OK;
7020 int nTries = 0;
7021 struct timespec conchModTime;
7022
drh3d4435b2011-08-26 20:55:50 +00007023 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00007024 do {
7025 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
7026 nTries ++;
7027 if( rc==SQLITE_BUSY ){
7028 /* If the lock failed (busy):
7029 * 1st try: get the mod time of the conch, wait 0.5s and try again.
7030 * 2nd try: fail if the mod time changed or host id is different, wait
7031 * 10 sec and try again
7032 * 3rd try: break the lock unless the mod time has changed.
7033 */
7034 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00007035 if( osFstat(conchFile->h, &buf) ){
drh4bf66fd2015-02-19 02:43:02 +00007036 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00007037 return SQLITE_IOERR_LOCK;
7038 }
7039
7040 if( nTries==1 ){
7041 conchModTime = buf.st_mtimespec;
7042 usleep(500000); /* wait 0.5 sec and try the lock again*/
7043 continue;
7044 }
7045
7046 assert( nTries>1 );
7047 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
7048 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
7049 return SQLITE_BUSY;
7050 }
7051
7052 if( nTries==2 ){
7053 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00007054 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00007055 if( len<0 ){
drh4bf66fd2015-02-19 02:43:02 +00007056 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00007057 return SQLITE_IOERR_LOCK;
7058 }
7059 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
7060 /* don't break the lock if the host id doesn't match */
7061 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
7062 return SQLITE_BUSY;
7063 }
7064 }else{
7065 /* don't break the lock on short read or a version mismatch */
7066 return SQLITE_BUSY;
7067 }
7068 usleep(10000000); /* wait 10 sec and try the lock again */
7069 continue;
7070 }
7071
7072 assert( nTries==3 );
7073 if( 0==proxyBreakConchLock(pFile, myHostID) ){
7074 rc = SQLITE_OK;
7075 if( lockType==EXCLUSIVE_LOCK ){
drhe6d41732015-02-21 00:49:00 +00007076 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
drh7ed97b92010-01-20 13:07:21 +00007077 }
7078 if( !rc ){
7079 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
7080 }
7081 }
7082 }
7083 } while( rc==SQLITE_BUSY && nTries<3 );
7084
7085 return rc;
7086}
7087
7088/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00007089** lockPath is non-NULL, the host ID and lock file path must match. A NULL
7090** lockPath means that the lockPath in the conch file will be used if the
7091** host IDs match, or a new lock path will be generated automatically
7092** and written to the conch file.
7093*/
7094static int proxyTakeConch(unixFile *pFile){
7095 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7096
drh7ed97b92010-01-20 13:07:21 +00007097 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00007098 return SQLITE_OK;
7099 }else{
7100 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00007101 uuid_t myHostID;
7102 int pError = 0;
7103 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00007104 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00007105 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00007106 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00007107 int createConch = 0;
7108 int hostIdMatch = 0;
7109 int readLen = 0;
7110 int tryOldLockPath = 0;
7111 int forceNewLockPath = 0;
7112
drh308c2a52010-05-14 11:30:18 +00007113 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
drh91eb93c2015-03-03 19:56:20 +00007114 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00007115 osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007116
drh7ed97b92010-01-20 13:07:21 +00007117 rc = proxyGetHostID(myHostID, &pError);
7118 if( (rc&0xff)==SQLITE_IOERR ){
drh4bf66fd2015-02-19 02:43:02 +00007119 storeLastErrno(pFile, pError);
drh7ed97b92010-01-20 13:07:21 +00007120 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00007121 }
drh7ed97b92010-01-20 13:07:21 +00007122 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00007123 if( rc!=SQLITE_OK ){
7124 goto end_takeconch;
7125 }
drh7ed97b92010-01-20 13:07:21 +00007126 /* read the existing conch file */
7127 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
7128 if( readLen<0 ){
7129 /* I/O error: lastErrno set by seekAndRead */
drh4bf66fd2015-02-19 02:43:02 +00007130 storeLastErrno(pFile, conchFile->lastErrno);
drh7ed97b92010-01-20 13:07:21 +00007131 rc = SQLITE_IOERR_READ;
7132 goto end_takeconch;
7133 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
7134 readBuf[0]!=(char)PROXY_CONCHVERSION ){
7135 /* a short read or version format mismatch means we need to create a new
7136 ** conch file.
7137 */
7138 createConch = 1;
7139 }
7140 /* if the host id matches and the lock path already exists in the conch
7141 ** we'll try to use the path there, if we can't open that path, we'll
7142 ** retry with a new auto-generated path
7143 */
7144 do { /* in case we need to try again for an :auto: named lock file */
7145
7146 if( !createConch && !forceNewLockPath ){
7147 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
7148 PROXY_HOSTIDLEN);
7149 /* if the conch has data compare the contents */
7150 if( !pCtx->lockProxyPath ){
7151 /* for auto-named local lock file, just check the host ID and we'll
7152 ** use the local lock file path that's already in there
7153 */
7154 if( hostIdMatch ){
7155 size_t pathLen = (readLen - PROXY_PATHINDEX);
7156
7157 if( pathLen>=MAXPATHLEN ){
7158 pathLen=MAXPATHLEN-1;
7159 }
7160 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
7161 lockPath[pathLen] = 0;
7162 tempLockPath = lockPath;
7163 tryOldLockPath = 1;
7164 /* create a copy of the lock path if the conch is taken */
7165 goto end_takeconch;
7166 }
7167 }else if( hostIdMatch
7168 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
7169 readLen-PROXY_PATHINDEX)
7170 ){
7171 /* conch host and lock path match */
7172 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00007173 }
drh7ed97b92010-01-20 13:07:21 +00007174 }
7175
7176 /* if the conch isn't writable and doesn't match, we can't take it */
7177 if( (conchFile->openFlags&O_RDWR) == 0 ){
7178 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00007179 goto end_takeconch;
7180 }
drh7ed97b92010-01-20 13:07:21 +00007181
7182 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00007183 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00007184 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
7185 tempLockPath = lockPath;
7186 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00007187 }
drh7ed97b92010-01-20 13:07:21 +00007188
7189 /* update conch with host and path (this will fail if other process
7190 ** has a shared lock already), if the host id matches, use the big
7191 ** stick.
drh715ff302008-12-03 22:32:44 +00007192 */
drh7ed97b92010-01-20 13:07:21 +00007193 futimes(conchFile->h, NULL);
7194 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00007195 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00007196 /* We are trying for an exclusive lock but another thread in this
7197 ** same process is still holding a shared lock. */
7198 rc = SQLITE_BUSY;
7199 } else {
7200 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00007201 }
drh715ff302008-12-03 22:32:44 +00007202 }else{
drh4bf66fd2015-02-19 02:43:02 +00007203 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00007204 }
drh7ed97b92010-01-20 13:07:21 +00007205 if( rc==SQLITE_OK ){
7206 char writeBuffer[PROXY_MAXCONCHLEN];
7207 int writeSize = 0;
7208
7209 writeBuffer[0] = (char)PROXY_CONCHVERSION;
7210 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
7211 if( pCtx->lockProxyPath!=NULL ){
drh4bf66fd2015-02-19 02:43:02 +00007212 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
7213 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007214 }else{
7215 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
7216 }
7217 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00007218 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00007219 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
drh6d258992016-02-04 09:48:12 +00007220 full_fsync(conchFile->h,0,0);
drh7ed97b92010-01-20 13:07:21 +00007221 /* If we created a new conch file (not just updated the contents of a
7222 ** valid conch file), try to match the permissions of the database
7223 */
7224 if( rc==SQLITE_OK && createConch ){
7225 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00007226 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00007227 if( err==0 ){
7228 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
7229 S_IROTH|S_IWOTH);
7230 /* try to match the database file R/W permissions, ignore failure */
7231#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00007232 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00007233#else
drhff812312011-02-23 13:33:46 +00007234 do{
drhe562be52011-03-02 18:01:10 +00007235 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00007236 }while( rc==(-1) && errno==EINTR );
7237 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00007238 int code = errno;
7239 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
7240 cmode, code, strerror(code));
7241 } else {
7242 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
7243 }
7244 }else{
7245 int code = errno;
7246 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
7247 err, code, strerror(code));
7248#endif
7249 }
drh715ff302008-12-03 22:32:44 +00007250 }
7251 }
drh7ed97b92010-01-20 13:07:21 +00007252 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
7253
7254 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00007255 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00007256 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00007257 int fd;
drh7ed97b92010-01-20 13:07:21 +00007258 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00007259 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00007260 }
7261 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00007262 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00007263 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00007264 if( fd>=0 ){
7265 pFile->h = fd;
7266 }else{
drh9978c972010-02-23 17:36:32 +00007267 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00007268 during locking */
7269 }
7270 }
7271 if( rc==SQLITE_OK && !pCtx->lockProxy ){
7272 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
7273 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
7274 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
7275 /* we couldn't create the proxy lock file with the old lock file path
7276 ** so try again via auto-naming
7277 */
7278 forceNewLockPath = 1;
7279 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00007280 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00007281 }
7282 }
7283 if( rc==SQLITE_OK ){
7284 /* Need to make a copy of path if we extracted the value
7285 ** from the conch file or the path was allocated on the stack
7286 */
7287 if( tempLockPath ){
7288 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
7289 if( !pCtx->lockProxyPath ){
mistachkinfad30392016-02-13 23:43:46 +00007290 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00007291 }
7292 }
7293 }
7294 if( rc==SQLITE_OK ){
7295 pCtx->conchHeld = 1;
7296
7297 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
7298 afpLockingContext *afpCtx;
7299 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
7300 afpCtx->dbPath = pCtx->lockProxyPath;
7301 }
7302 } else {
7303 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7304 }
drh308c2a52010-05-14 11:30:18 +00007305 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
7306 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00007307 return rc;
drh308c2a52010-05-14 11:30:18 +00007308 } while (1); /* in case we need to retry the :auto: lock file -
7309 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00007310 }
7311}
7312
7313/*
7314** If pFile holds a lock on a conch file, then release that lock.
7315*/
7316static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00007317 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00007318 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
7319 unixFile *conchFile; /* Name of the conch file */
7320
7321 pCtx = (proxyLockingContext *)pFile->lockingContext;
7322 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00007323 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00007324 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00007325 osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00007326 if( pCtx->conchHeld>0 ){
7327 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7328 }
drh715ff302008-12-03 22:32:44 +00007329 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00007330 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
7331 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007332 return rc;
7333}
7334
7335/*
7336** Given the name of a database file, compute the name of its conch file.
drhf3cdcdc2015-04-29 16:50:28 +00007337** Store the conch filename in memory obtained from sqlite3_malloc64().
drh715ff302008-12-03 22:32:44 +00007338** Make *pConchPath point to the new name. Return SQLITE_OK on success
7339** or SQLITE_NOMEM if unable to obtain memory.
7340**
7341** The caller is responsible for ensuring that the allocated memory
7342** space is eventually freed.
7343**
7344** *pConchPath is set to NULL if a memory allocation error occurs.
7345*/
7346static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7347 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00007348 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00007349 char *conchPath; /* buffer in which to construct conch name */
7350
7351 /* Allocate space for the conch filename and initialize the name to
7352 ** the name of the original database file. */
drhf3cdcdc2015-04-29 16:50:28 +00007353 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
drh715ff302008-12-03 22:32:44 +00007354 if( conchPath==0 ){
mistachkinfad30392016-02-13 23:43:46 +00007355 return SQLITE_NOMEM_BKPT;
drh715ff302008-12-03 22:32:44 +00007356 }
7357 memcpy(conchPath, dbPath, len+1);
7358
7359 /* now insert a "." before the last / character */
7360 for( i=(len-1); i>=0; i-- ){
7361 if( conchPath[i]=='/' ){
7362 i++;
7363 break;
7364 }
7365 }
7366 conchPath[i]='.';
7367 while ( i<len ){
7368 conchPath[i+1]=dbPath[i];
7369 i++;
7370 }
7371
7372 /* append the "-conch" suffix to the file */
7373 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007374 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007375
7376 return SQLITE_OK;
7377}
7378
7379
7380/* Takes a fully configured proxy locking-style unix file and switches
7381** the local lock file path
7382*/
7383static int switchLockProxyPath(unixFile *pFile, const char *path) {
7384 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7385 char *oldPath = pCtx->lockProxyPath;
7386 int rc = SQLITE_OK;
7387
drh308c2a52010-05-14 11:30:18 +00007388 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007389 return SQLITE_BUSY;
7390 }
7391
7392 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7393 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7394 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7395 return SQLITE_OK;
7396 }else{
7397 unixFile *lockProxy = pCtx->lockProxy;
7398 pCtx->lockProxy=NULL;
7399 pCtx->conchHeld = 0;
7400 if( lockProxy!=NULL ){
7401 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7402 if( rc ) return rc;
7403 sqlite3_free(lockProxy);
7404 }
7405 sqlite3_free(oldPath);
7406 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7407 }
7408
7409 return rc;
7410}
7411
7412/*
7413** pFile is a file that has been opened by a prior xOpen call. dbPath
7414** is a string buffer at least MAXPATHLEN+1 characters in size.
7415**
7416** This routine find the filename associated with pFile and writes it
7417** int dbPath.
7418*/
7419static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007420#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007421 if( pFile->pMethod == &afpIoMethods ){
7422 /* afp style keeps a reference to the db path in the filePath field
7423 ** of the struct */
drhea678832008-12-10 19:26:22 +00007424 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh4bf66fd2015-02-19 02:43:02 +00007425 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7426 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007427 } else
drh715ff302008-12-03 22:32:44 +00007428#endif
7429 if( pFile->pMethod == &dotlockIoMethods ){
7430 /* dot lock style uses the locking context to store the dot lock
7431 ** file path */
7432 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7433 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7434 }else{
7435 /* all other styles use the locking context to store the db file path */
7436 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007437 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007438 }
7439 return SQLITE_OK;
7440}
7441
7442/*
7443** Takes an already filled in unix file and alters it so all file locking
7444** will be performed on the local proxy lock file. The following fields
7445** are preserved in the locking context so that they can be restored and
7446** the unix structure properly cleaned up at close time:
7447** ->lockingContext
7448** ->pMethod
7449*/
7450static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7451 proxyLockingContext *pCtx;
7452 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7453 char *lockPath=NULL;
7454 int rc = SQLITE_OK;
7455
drh308c2a52010-05-14 11:30:18 +00007456 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007457 return SQLITE_BUSY;
7458 }
7459 proxyGetDbPathForUnixFile(pFile, dbPath);
7460 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7461 lockPath=NULL;
7462 }else{
7463 lockPath=(char *)path;
7464 }
7465
drh308c2a52010-05-14 11:30:18 +00007466 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
drh5ac93652015-03-21 20:59:43 +00007467 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007468
drhf3cdcdc2015-04-29 16:50:28 +00007469 pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh715ff302008-12-03 22:32:44 +00007470 if( pCtx==0 ){
mistachkinfad30392016-02-13 23:43:46 +00007471 return SQLITE_NOMEM_BKPT;
drh715ff302008-12-03 22:32:44 +00007472 }
7473 memset(pCtx, 0, sizeof(*pCtx));
7474
7475 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7476 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007477 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7478 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7479 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7480 ** (c) the file system is read-only, then enable no-locking access.
7481 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7482 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7483 */
7484 struct statfs fsInfo;
7485 struct stat conchInfo;
7486 int goLockless = 0;
7487
drh99ab3b12011-03-02 15:09:07 +00007488 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007489 int err = errno;
7490 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7491 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7492 }
7493 }
7494 if( goLockless ){
7495 pCtx->conchHeld = -1; /* read only FS/ lockless */
7496 rc = SQLITE_OK;
7497 }
7498 }
drh715ff302008-12-03 22:32:44 +00007499 }
7500 if( rc==SQLITE_OK && lockPath ){
7501 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7502 }
7503
7504 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007505 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7506 if( pCtx->dbPath==NULL ){
mistachkinfad30392016-02-13 23:43:46 +00007507 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00007508 }
7509 }
7510 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007511 /* all memory is allocated, proxys are created and assigned,
7512 ** switch the locking context and pMethod then return.
7513 */
drh715ff302008-12-03 22:32:44 +00007514 pCtx->oldLockingContext = pFile->lockingContext;
7515 pFile->lockingContext = pCtx;
7516 pCtx->pOldMethod = pFile->pMethod;
7517 pFile->pMethod = &proxyIoMethods;
7518 }else{
7519 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007520 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007521 sqlite3_free(pCtx->conchFile);
7522 }
drhd56b1212010-08-11 06:14:15 +00007523 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007524 sqlite3_free(pCtx->conchFilePath);
7525 sqlite3_free(pCtx);
7526 }
drh308c2a52010-05-14 11:30:18 +00007527 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7528 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007529 return rc;
7530}
7531
7532
7533/*
7534** This routine handles sqlite3_file_control() calls that are specific
7535** to proxy locking.
7536*/
7537static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7538 switch( op ){
drh4bf66fd2015-02-19 02:43:02 +00007539 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007540 unixFile *pFile = (unixFile*)id;
7541 if( pFile->pMethod == &proxyIoMethods ){
7542 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7543 proxyTakeConch(pFile);
7544 if( pCtx->lockProxyPath ){
7545 *(const char **)pArg = pCtx->lockProxyPath;
7546 }else{
7547 *(const char **)pArg = ":auto: (not held)";
7548 }
7549 } else {
7550 *(const char **)pArg = NULL;
7551 }
7552 return SQLITE_OK;
7553 }
drh4bf66fd2015-02-19 02:43:02 +00007554 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007555 unixFile *pFile = (unixFile*)id;
7556 int rc = SQLITE_OK;
7557 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7558 if( pArg==NULL || (const char *)pArg==0 ){
7559 if( isProxyStyle ){
drh4bf66fd2015-02-19 02:43:02 +00007560 /* turn off proxy locking - not supported. If support is added for
7561 ** switching proxy locking mode off then it will need to fail if
7562 ** the journal mode is WAL mode.
7563 */
drh715ff302008-12-03 22:32:44 +00007564 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7565 }else{
7566 /* turn off proxy locking - already off - NOOP */
7567 rc = SQLITE_OK;
7568 }
7569 }else{
7570 const char *proxyPath = (const char *)pArg;
7571 if( isProxyStyle ){
7572 proxyLockingContext *pCtx =
7573 (proxyLockingContext*)pFile->lockingContext;
7574 if( !strcmp(pArg, ":auto:")
7575 || (pCtx->lockProxyPath &&
7576 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7577 ){
7578 rc = SQLITE_OK;
7579 }else{
7580 rc = switchLockProxyPath(pFile, proxyPath);
7581 }
7582 }else{
7583 /* turn on proxy file locking */
7584 rc = proxyTransformUnixFile(pFile, proxyPath);
7585 }
7586 }
7587 return rc;
7588 }
7589 default: {
7590 assert( 0 ); /* The call assures that only valid opcodes are sent */
7591 }
7592 }
7593 /*NOTREACHED*/
7594 return SQLITE_ERROR;
7595}
7596
7597/*
7598** Within this division (the proxying locking implementation) the procedures
7599** above this point are all utilities. The lock-related methods of the
7600** proxy-locking sqlite3_io_method object follow.
7601*/
7602
7603
7604/*
7605** This routine checks if there is a RESERVED lock held on the specified
7606** file by this or any other process. If such a lock is held, set *pResOut
7607** to a non-zero value otherwise *pResOut is set to zero. The return value
7608** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7609*/
7610static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7611 unixFile *pFile = (unixFile*)id;
7612 int rc = proxyTakeConch(pFile);
7613 if( rc==SQLITE_OK ){
7614 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007615 if( pCtx->conchHeld>0 ){
7616 unixFile *proxy = pCtx->lockProxy;
7617 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7618 }else{ /* conchHeld < 0 is lockless */
7619 pResOut=0;
7620 }
drh715ff302008-12-03 22:32:44 +00007621 }
7622 return rc;
7623}
7624
7625/*
drh308c2a52010-05-14 11:30:18 +00007626** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007627** of the following:
7628**
7629** (1) SHARED_LOCK
7630** (2) RESERVED_LOCK
7631** (3) PENDING_LOCK
7632** (4) EXCLUSIVE_LOCK
7633**
7634** Sometimes when requesting one lock state, additional lock states
7635** are inserted in between. The locking might fail on one of the later
7636** transitions leaving the lock state different from what it started but
7637** still short of its goal. The following chart shows the allowed
7638** transitions and the inserted intermediate states:
7639**
7640** UNLOCKED -> SHARED
7641** SHARED -> RESERVED
7642** SHARED -> (PENDING) -> EXCLUSIVE
7643** RESERVED -> (PENDING) -> EXCLUSIVE
7644** PENDING -> EXCLUSIVE
7645**
7646** This routine will only increase a lock. Use the sqlite3OsUnlock()
7647** routine to lower a locking level.
7648*/
drh308c2a52010-05-14 11:30:18 +00007649static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007650 unixFile *pFile = (unixFile*)id;
7651 int rc = proxyTakeConch(pFile);
7652 if( rc==SQLITE_OK ){
7653 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007654 if( pCtx->conchHeld>0 ){
7655 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007656 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7657 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007658 }else{
7659 /* conchHeld < 0 is lockless */
7660 }
drh715ff302008-12-03 22:32:44 +00007661 }
7662 return rc;
7663}
7664
7665
7666/*
drh308c2a52010-05-14 11:30:18 +00007667** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007668** must be either NO_LOCK or SHARED_LOCK.
7669**
7670** If the locking level of the file descriptor is already at or below
7671** the requested locking level, this routine is a no-op.
7672*/
drh308c2a52010-05-14 11:30:18 +00007673static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007674 unixFile *pFile = (unixFile*)id;
7675 int rc = proxyTakeConch(pFile);
7676 if( rc==SQLITE_OK ){
7677 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007678 if( pCtx->conchHeld>0 ){
7679 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007680 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7681 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007682 }else{
7683 /* conchHeld < 0 is lockless */
7684 }
drh715ff302008-12-03 22:32:44 +00007685 }
7686 return rc;
7687}
7688
7689/*
7690** Close a file that uses proxy locks.
7691*/
7692static int proxyClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00007693 if( ALWAYS(id) ){
drh715ff302008-12-03 22:32:44 +00007694 unixFile *pFile = (unixFile*)id;
7695 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7696 unixFile *lockProxy = pCtx->lockProxy;
7697 unixFile *conchFile = pCtx->conchFile;
7698 int rc = SQLITE_OK;
7699
7700 if( lockProxy ){
7701 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7702 if( rc ) return rc;
7703 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7704 if( rc ) return rc;
7705 sqlite3_free(lockProxy);
7706 pCtx->lockProxy = 0;
7707 }
7708 if( conchFile ){
7709 if( pCtx->conchHeld ){
7710 rc = proxyReleaseConch(pFile);
7711 if( rc ) return rc;
7712 }
7713 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7714 if( rc ) return rc;
7715 sqlite3_free(conchFile);
7716 }
drhd56b1212010-08-11 06:14:15 +00007717 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007718 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007719 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007720 /* restore the original locking context and pMethod then close it */
7721 pFile->lockingContext = pCtx->oldLockingContext;
7722 pFile->pMethod = pCtx->pOldMethod;
7723 sqlite3_free(pCtx);
7724 return pFile->pMethod->xClose(id);
7725 }
7726 return SQLITE_OK;
7727}
7728
7729
7730
drhd2cb50b2009-01-09 21:41:17 +00007731#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007732/*
7733** The proxy locking style is intended for use with AFP filesystems.
7734** And since AFP is only supported on MacOSX, the proxy locking is also
7735** restricted to MacOSX.
7736**
7737**
7738******************* End of the proxy lock implementation **********************
7739******************************************************************************/
7740
drh734c9862008-11-28 15:37:20 +00007741/*
danielk1977e339d652008-06-28 11:23:00 +00007742** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007743**
7744** This routine registers all VFS implementations for unix-like operating
7745** systems. This routine, and the sqlite3_os_end() routine that follows,
7746** should be the only routines in this file that are visible from other
7747** files.
drh6b9d6dd2008-12-03 19:34:47 +00007748**
7749** This routine is called once during SQLite initialization and by a
7750** single thread. The memory allocation and mutex subsystems have not
7751** necessarily been initialized when this routine is called, and so they
7752** should not be used.
drh153c62c2007-08-24 03:51:33 +00007753*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007754int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007755 /*
7756 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007757 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7758 ** to the "finder" function. (pAppData is a pointer to a pointer because
7759 ** silly C90 rules prohibit a void* from being cast to a function pointer
7760 ** and so we have to go through the intermediate pointer to avoid problems
7761 ** when compiling with -pedantic-errors on GCC.)
7762 **
7763 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007764 ** finder-function. The finder-function returns a pointer to the
7765 ** sqlite_io_methods object that implements the desired locking
7766 ** behaviors. See the division above that contains the IOMETHODS
7767 ** macro for addition information on finder-functions.
7768 **
7769 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7770 ** object. But the "autolockIoFinder" available on MacOSX does a little
7771 ** more than that; it looks at the filesystem type that hosts the
7772 ** database file and tries to choose an locking method appropriate for
7773 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007774 */
drh7708e972008-11-29 00:56:52 +00007775 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007776 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007777 sizeof(unixFile), /* szOsFile */ \
7778 MAX_PATHNAME, /* mxPathname */ \
7779 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007780 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007781 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007782 unixOpen, /* xOpen */ \
7783 unixDelete, /* xDelete */ \
7784 unixAccess, /* xAccess */ \
7785 unixFullPathname, /* xFullPathname */ \
7786 unixDlOpen, /* xDlOpen */ \
7787 unixDlError, /* xDlError */ \
7788 unixDlSym, /* xDlSym */ \
7789 unixDlClose, /* xDlClose */ \
7790 unixRandomness, /* xRandomness */ \
7791 unixSleep, /* xSleep */ \
7792 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007793 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007794 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007795 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007796 unixGetSystemCall, /* xGetSystemCall */ \
7797 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007798 }
7799
drh6b9d6dd2008-12-03 19:34:47 +00007800 /*
7801 ** All default VFSes for unix are contained in the following array.
7802 **
7803 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7804 ** by the SQLite core when the VFS is registered. So the following
7805 ** array cannot be const.
7806 */
danielk1977e339d652008-06-28 11:23:00 +00007807 static sqlite3_vfs aVfs[] = {
drhe89b2912015-03-03 20:42:01 +00007808#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007809 UNIXVFS("unix", autolockIoFinder ),
drhe89b2912015-03-03 20:42:01 +00007810#elif OS_VXWORKS
7811 UNIXVFS("unix", vxworksIoFinder ),
drh7708e972008-11-29 00:56:52 +00007812#else
7813 UNIXVFS("unix", posixIoFinder ),
7814#endif
7815 UNIXVFS("unix-none", nolockIoFinder ),
7816 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007817 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007818#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007819 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007820#endif
drhe89b2912015-03-03 20:42:01 +00007821#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007822 UNIXVFS("unix-posix", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007823#endif
drhe89b2912015-03-03 20:42:01 +00007824#if SQLITE_ENABLE_LOCKING_STYLE
7825 UNIXVFS("unix-flock", flockIoFinder ),
chw78a13182009-04-07 05:35:03 +00007826#endif
drhd2cb50b2009-01-09 21:41:17 +00007827#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007828 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007829 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007830 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007831#endif
drh153c62c2007-08-24 03:51:33 +00007832 };
drh6b9d6dd2008-12-03 19:34:47 +00007833 unsigned int i; /* Loop counter */
7834
drh2aa5a002011-04-13 13:42:25 +00007835 /* Double-check that the aSyscall[] array has been constructed
7836 ** correctly. See ticket [bb3a86e890c8e96ab] */
danefe16972017-07-20 19:49:14 +00007837 assert( ArraySize(aSyscall)==29 );
drh2aa5a002011-04-13 13:42:25 +00007838
drh6b9d6dd2008-12-03 19:34:47 +00007839 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007840 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007841 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007842 }
drh56115892018-02-05 16:39:12 +00007843 unixBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
danielk1977c0fa4c52008-06-25 17:19:00 +00007844 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007845}
danielk1977e339d652008-06-28 11:23:00 +00007846
7847/*
drh6b9d6dd2008-12-03 19:34:47 +00007848** Shutdown the operating system interface.
7849**
7850** Some operating systems might need to do some cleanup in this routine,
7851** to release dynamically allocated objects. But not on unix.
7852** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007853*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007854int sqlite3_os_end(void){
drh56115892018-02-05 16:39:12 +00007855 unixBigLock = 0;
danielk1977c0fa4c52008-06-25 17:19:00 +00007856 return SQLITE_OK;
7857}
drhdce8bdb2007-08-16 13:01:44 +00007858
danielk197729bafea2008-06-26 10:41:19 +00007859#endif /* SQLITE_OS_UNIX */