blob: fe1fc6af19a4a2b45a422805e34be3aec8369208 [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
drh9cbe6352005-11-29 03:13:21 +000074/*
drh9cbe6352005-11-29 03:13:21 +000075** standard include files.
76*/
77#include <sys/types.h>
78#include <sys/stat.h>
79#include <fcntl.h>
80#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +000081#include <time.h>
drh19e2d372005-08-29 23:00:03 +000082#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +000083#include <errno.h>
dan32c12fe2013-05-02 17:37:31 +000084#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drh91be7dc2014-08-11 13:53:30 +000085# include <sys/mman.h>
drhb469f462010-12-22 21:48:50 +000086#endif
drh1da88f02011-12-17 16:09:16 +000087
drhe89b2912015-03-03 20:42:01 +000088#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +000089# include <sys/ioctl.h>
drhe89b2912015-03-03 20:42:01 +000090# include <sys/file.h>
91# include <sys/param.h>
drhbfe66312006-10-03 17:40:40 +000092#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +000093
drh6bca6512015-04-13 23:05:28 +000094#if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
95 (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
96# if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
97 && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
98# define HAVE_GETHOSTUUID 1
99# else
100# warning "gethostuuid() is disabled."
101# endif
102#endif
103
104
drhe89b2912015-03-03 20:42:01 +0000105#if OS_VXWORKS
106# include <sys/ioctl.h>
107# include <semaphore.h>
108# include <limits.h>
109#endif /* OS_VXWORKS */
110
111#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh84a2bf62010-03-05 13:41:06 +0000112# include <sys/mount.h>
113#endif
114
drhdbe4b882011-06-20 18:00:17 +0000115#ifdef HAVE_UTIME
116# include <utime.h>
117#endif
118
drh9cbe6352005-11-29 03:13:21 +0000119/*
drh7ed97b92010-01-20 13:07:21 +0000120** Allowed values of unixFile.fsFlags
121*/
122#define SQLITE_FSFLAGS_IS_MSDOS 0x1
123
124/*
drhf1a221e2006-01-15 17:27:17 +0000125** If we are to be thread-safe, include the pthreads header and define
126** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000127*/
drhd677b3d2007-08-20 22:48:41 +0000128#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000129# include <pthread.h>
130# define SQLITE_UNIX_THREADS 1
131#endif
132
133/*
134** Default permissions when creating a new file
135*/
136#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
137# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
138#endif
139
danielk1977b4b47412007-08-17 15:53:36 +0000140/*
drh5adc60b2012-04-14 13:25:11 +0000141** Default permissions when creating auto proxy dir
142*/
aswiftaebf4132008-11-21 00:10:35 +0000143#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
144# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
145#endif
146
147/*
danielk1977b4b47412007-08-17 15:53:36 +0000148** Maximum supported path-length.
149*/
150#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000151
dane88ec182016-01-25 17:04:48 +0000152/*
153** Maximum supported symbolic links
154*/
155#define SQLITE_MAX_SYMLINKS 100
156
drh91eb93c2015-03-03 19:56:20 +0000157/* Always cast the getpid() return type for compatibility with
158** kernel modules in VxWorks. */
159#define osGetpid(X) (pid_t)getpid()
160
drh734c9862008-11-28 15:37:20 +0000161/*
drh734c9862008-11-28 15:37:20 +0000162** Only set the lastErrno if the error code is a real error and not
163** a normal expected return code of SQLITE_BUSY or SQLITE_OK
164*/
165#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
166
drhd91c68f2010-05-14 14:52:25 +0000167/* Forward references */
168typedef struct unixShm unixShm; /* Connection shared memory */
169typedef struct unixShmNode unixShmNode; /* Shared memory instance */
170typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
171typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000172
173/*
dane946c392009-08-22 11:39:46 +0000174** Sometimes, after a file handle is closed by SQLite, the file descriptor
175** cannot be closed immediately. In these cases, instances of the following
176** structure are used to store the file descriptor while waiting for an
177** opportunity to either close or reuse it.
178*/
dane946c392009-08-22 11:39:46 +0000179struct UnixUnusedFd {
180 int fd; /* File descriptor to close */
181 int flags; /* Flags this file descriptor was opened with */
182 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
183};
184
185/*
drh9b35ea62008-11-29 02:20:26 +0000186** The unixFile structure is subclass of sqlite3_file specific to the unix
187** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000188*/
drh054889e2005-11-30 03:20:31 +0000189typedef struct unixFile unixFile;
190struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000191 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhde60fc22011-12-14 17:53:36 +0000192 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
drhd91c68f2010-05-14 14:52:25 +0000193 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000194 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000195 unsigned char eFileLock; /* The type of lock held on this fd */
drh3ee34842012-02-11 21:21:17 +0000196 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000197 int lastErrno; /* The unix errno from last I/O error */
198 void *lockingContext; /* Locking style specific state */
199 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000200 const char *zPath; /* Name of the file */
201 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000202 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
mistachkine98844f2013-08-24 00:59:24 +0000203#if SQLITE_MAX_MMAP_SIZE>0
drh0d0614b2013-03-25 23:09:28 +0000204 int nFetchOut; /* Number of outstanding xFetch refs */
205 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
drh9b4c59f2013-04-15 17:03:42 +0000206 sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
207 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
drh0d0614b2013-03-25 23:09:28 +0000208 void *pMapRegion; /* Memory mapped region */
mistachkine98844f2013-08-24 00:59:24 +0000209#endif
drh537dddf2012-10-26 13:46:24 +0000210#ifdef __QNXNTO__
211 int sectorSize; /* Device sector size */
212 int deviceCharacteristics; /* Precomputed device characteristics */
213#endif
drh08c6d442009-02-09 17:34:07 +0000214#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000215 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000216#endif
drh7ed97b92010-01-20 13:07:21 +0000217#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000218 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000219#endif
220#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000221 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000222#endif
drhd3d8c042012-05-29 17:02:40 +0000223#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +0000224 /* The next group of variables are used to track whether or not the
225 ** transaction counter in bytes 24-27 of database files are updated
226 ** whenever any part of the database changes. An assertion fault will
227 ** occur if a file is updated without also updating the transaction
228 ** counter. This test is made to avoid new problems similar to the
229 ** one described by ticket #3584.
230 */
231 unsigned char transCntrChng; /* True if the transaction counter changed */
232 unsigned char dbUpdate; /* True if any part of database file changed */
233 unsigned char inNormalWrite; /* True if in a normal write operation */
danf23da962013-03-23 21:00:41 +0000234
drh8f941bc2009-01-14 23:03:40 +0000235#endif
danf23da962013-03-23 21:00:41 +0000236
danielk1977967a4a12007-08-20 14:23:44 +0000237#ifdef SQLITE_TEST
238 /* In test mode, increase the size of this structure a bit so that
239 ** it is larger than the struct CrashFile defined in test6.c.
240 */
241 char aPadding[32];
242#endif
drh9cbe6352005-11-29 03:13:21 +0000243};
244
drhb00d8622014-01-01 15:18:36 +0000245/* This variable holds the process id (pid) from when the xRandomness()
246** method was called. If xOpen() is called from a different process id,
247** indicating that a fork() has occurred, the PRNG will be reset.
248*/
drh8cd5b252015-03-02 22:06:43 +0000249static pid_t randomnessPid = 0;
drhb00d8622014-01-01 15:18:36 +0000250
drh0ccebe72005-06-07 22:22:50 +0000251/*
drha7e61d82011-03-12 17:02:57 +0000252** Allowed values for the unixFile.ctrlFlags bitmask:
253*/
drhf0b190d2011-07-26 16:03:07 +0000254#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
255#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
256#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000257#ifndef SQLITE_DISABLE_DIRSYNC
258# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
259#else
260# define UNIXFILE_DIRSYNC 0x00
261#endif
drhcb15f352011-12-23 01:04:17 +0000262#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
drhc02a43a2012-01-10 23:18:38 +0000263#define UNIXFILE_DELETE 0x20 /* Delete on close */
264#define UNIXFILE_URI 0x40 /* Filename might have query parameters */
265#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
drha7e61d82011-03-12 17:02:57 +0000266
267/*
drh198bf392006-01-06 21:52:49 +0000268** Include code that is common to all os_*.c files
269*/
270#include "os_common.h"
271
272/*
drh0ccebe72005-06-07 22:22:50 +0000273** Define various macros that are missing from some systems.
274*/
drhbbd42a62004-05-22 17:41:58 +0000275#ifndef O_LARGEFILE
276# define O_LARGEFILE 0
277#endif
278#ifdef SQLITE_DISABLE_LFS
279# undef O_LARGEFILE
280# define O_LARGEFILE 0
281#endif
282#ifndef O_NOFOLLOW
283# define O_NOFOLLOW 0
284#endif
285#ifndef O_BINARY
286# define O_BINARY 0
287#endif
288
289/*
drh2b4b5962005-06-15 17:47:55 +0000290** The threadid macro resolves to the thread-id or to 0. Used for
291** testing and debugging only.
292*/
drhd677b3d2007-08-20 22:48:41 +0000293#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000294#define threadid pthread_self()
295#else
296#define threadid 0
297#endif
298
drh99ab3b12011-03-02 15:09:07 +0000299/*
dane6ecd662013-04-01 17:56:59 +0000300** HAVE_MREMAP defaults to true on Linux and false everywhere else.
301*/
302#if !defined(HAVE_MREMAP)
303# if defined(__linux__) && defined(_GNU_SOURCE)
304# define HAVE_MREMAP 1
305# else
306# define HAVE_MREMAP 0
307# endif
308#endif
309
310/*
dan2ee53412014-09-06 16:49:40 +0000311** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
312** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
313*/
314#ifdef __ANDROID__
315# define lseek lseek64
316#endif
317
318/*
drh9a3baf12011-04-25 18:01:27 +0000319** Different Unix systems declare open() in different ways. Same use
320** open(const char*,int,mode_t). Others use open(const char*,int,...).
321** The difference is important when using a pointer to the function.
322**
323** The safest way to deal with the problem is to always use this wrapper
324** which always has the same well-defined interface.
325*/
326static int posixOpen(const char *zFile, int flags, int mode){
327 return open(zFile, flags, mode);
328}
329
drh90315a22011-08-10 01:52:12 +0000330/* Forward reference */
331static int openDirectory(const char*, int*);
danbc760632014-03-20 09:42:09 +0000332static int unixGetpagesize(void);
drh90315a22011-08-10 01:52:12 +0000333
drh9a3baf12011-04-25 18:01:27 +0000334/*
drh99ab3b12011-03-02 15:09:07 +0000335** Many system calls are accessed through pointer-to-functions so that
336** they may be overridden at runtime to facilitate fault injection during
337** testing and sandboxing. The following array holds the names and pointers
338** to all overrideable system calls.
339*/
340static struct unix_syscall {
mistachkin48864df2013-03-21 21:20:32 +0000341 const char *zName; /* Name of the system call */
drh58ad5802011-03-23 22:02:23 +0000342 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
343 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000344} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000345 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
346#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000347
drh58ad5802011-03-23 22:02:23 +0000348 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000349#define osClose ((int(*)(int))aSyscall[1].pCurrent)
350
drh58ad5802011-03-23 22:02:23 +0000351 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000352#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
353
drh58ad5802011-03-23 22:02:23 +0000354 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000355#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
356
drh58ad5802011-03-23 22:02:23 +0000357 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000358#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
359
360/*
361** The DJGPP compiler environment looks mostly like Unix, but it
362** lacks the fcntl() system call. So redefine fcntl() to be something
363** that always succeeds. This means that locking does not occur under
364** DJGPP. But it is DOS - what did you expect?
365*/
366#ifdef __DJGPP__
367 { "fstat", 0, 0 },
368#define osFstat(a,b,c) 0
369#else
drh58ad5802011-03-23 22:02:23 +0000370 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000371#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
372#endif
373
drh58ad5802011-03-23 22:02:23 +0000374 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000375#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
376
drh58ad5802011-03-23 22:02:23 +0000377 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000378#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000379
drh58ad5802011-03-23 22:02:23 +0000380 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000381#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
382
drhe89b2912015-03-03 20:42:01 +0000383#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000384 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000385#else
drh58ad5802011-03-23 22:02:23 +0000386 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000387#endif
388#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
389
390#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000391 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000392#else
drh58ad5802011-03-23 22:02:23 +0000393 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000394#endif
395#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
396
drh58ad5802011-03-23 22:02:23 +0000397 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000398#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
399
drhe89b2912015-03-03 20:42:01 +0000400#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000401 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000402#else
drh58ad5802011-03-23 22:02:23 +0000403 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000404#endif
405#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
406 aSyscall[12].pCurrent)
407
408#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000409 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000410#else
drh58ad5802011-03-23 22:02:23 +0000411 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000412#endif
413#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
414 aSyscall[13].pCurrent)
415
drh6226ca22015-11-24 15:06:28 +0000416 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000417#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000418
419#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000420 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000421#else
drh58ad5802011-03-23 22:02:23 +0000422 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000423#endif
dan0fd7d862011-03-29 10:04:23 +0000424#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000425
drh036ac7f2011-08-08 23:18:05 +0000426 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
427#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
428
drh90315a22011-08-10 01:52:12 +0000429 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
430#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
431
drh9ef6bc42011-11-04 02:24:02 +0000432 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
433#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
434
435 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
436#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
437
drhe2258a22016-01-12 00:37:55 +0000438#if defined(HAVE_FCHOWN)
drh6226ca22015-11-24 15:06:28 +0000439 { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
drhe2258a22016-01-12 00:37:55 +0000440#else
441 { "fchown", (sqlite3_syscall_ptr)0, 0 },
442#endif
dand3eaebd2012-02-13 08:50:23 +0000443#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000444
drh6226ca22015-11-24 15:06:28 +0000445 { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
446#define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
447
dan4dd51442013-08-26 14:30:25 +0000448#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhe4a08f92016-01-08 19:17:30 +0000449 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
450#else
451 { "mmap", (sqlite3_syscall_ptr)0, 0 },
452#endif
drh6226ca22015-11-24 15:06:28 +0000453#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
dan893c0ff2013-03-25 19:05:07 +0000454
drhe4a08f92016-01-08 19:17:30 +0000455#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd1ab8062013-03-25 20:50:25 +0000456 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
drhe4a08f92016-01-08 19:17:30 +0000457#else
drha8299922016-01-08 22:31:00 +0000458 { "munmap", (sqlite3_syscall_ptr)0, 0 },
drhe4a08f92016-01-08 19:17:30 +0000459#endif
drh6226ca22015-11-24 15:06:28 +0000460#define osMunmap ((void*(*)(void*,size_t))aSyscall[23].pCurrent)
drhd1ab8062013-03-25 20:50:25 +0000461
drhe4a08f92016-01-08 19:17:30 +0000462#if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
drhd1ab8062013-03-25 20:50:25 +0000463 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
464#else
465 { "mremap", (sqlite3_syscall_ptr)0, 0 },
466#endif
drh6226ca22015-11-24 15:06:28 +0000467#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
468
drh24dbeae2016-01-08 22:18:00 +0000469#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
danbc760632014-03-20 09:42:09 +0000470 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
drh24dbeae2016-01-08 22:18:00 +0000471#else
472 { "getpagesize", (sqlite3_syscall_ptr)0, 0 },
473#endif
drh6226ca22015-11-24 15:06:28 +0000474#define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
danbc760632014-03-20 09:42:09 +0000475
drhe2258a22016-01-12 00:37:55 +0000476#if defined(HAVE_READLINK)
dan245fdc62015-10-31 17:58:33 +0000477 { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
drhe2258a22016-01-12 00:37:55 +0000478#else
479 { "readlink", (sqlite3_syscall_ptr)0, 0 },
480#endif
drh6226ca22015-11-24 15:06:28 +0000481#define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
dan245fdc62015-10-31 17:58:33 +0000482
danaf1b36b2016-01-25 18:43:05 +0000483#if defined(HAVE_LSTAT)
484 { "lstat", (sqlite3_syscall_ptr)lstat, 0 },
485#else
486 { "lstat", (sqlite3_syscall_ptr)0, 0 },
487#endif
dancaf6b152016-01-25 18:05:49 +0000488#define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
dan702eec12014-06-23 10:04:58 +0000489
drhe562be52011-03-02 18:01:10 +0000490}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000491
drh6226ca22015-11-24 15:06:28 +0000492
493/*
494** On some systems, calls to fchown() will trigger a message in a security
495** log if they come from non-root processes. So avoid calling fchown() if
496** we are not running as root.
497*/
498static int robustFchown(int fd, uid_t uid, gid_t gid){
drhe2258a22016-01-12 00:37:55 +0000499#if defined(HAVE_FCHOWN)
drh6226ca22015-11-24 15:06:28 +0000500 return osGeteuid() ? 0 : osFchown(fd,uid,gid);
drhe2258a22016-01-12 00:37:55 +0000501#else
502 return 0;
drh6226ca22015-11-24 15:06:28 +0000503#endif
504}
505
drh99ab3b12011-03-02 15:09:07 +0000506/*
507** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000508** "unix" VFSes. Return SQLITE_OK opon successfully updating the
509** system call pointer, or SQLITE_NOTFOUND if there is no configurable
510** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000511*/
512static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000513 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
514 const char *zName, /* Name of system call to override */
515 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000516){
drh58ad5802011-03-23 22:02:23 +0000517 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000518 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000519
520 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000521 if( zName==0 ){
522 /* If no zName is given, restore all system calls to their default
523 ** settings and return NULL
524 */
dan51438a72011-04-02 17:00:47 +0000525 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000526 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
527 if( aSyscall[i].pDefault ){
528 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000529 }
530 }
531 }else{
532 /* If zName is specified, operate on only the one system call
533 ** specified.
534 */
535 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
536 if( strcmp(zName, aSyscall[i].zName)==0 ){
537 if( aSyscall[i].pDefault==0 ){
538 aSyscall[i].pDefault = aSyscall[i].pCurrent;
539 }
drh1df30962011-03-02 19:06:42 +0000540 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000541 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
542 aSyscall[i].pCurrent = pNewFunc;
543 break;
544 }
545 }
546 }
547 return rc;
548}
549
drh1df30962011-03-02 19:06:42 +0000550/*
551** Return the value of a system call. Return NULL if zName is not a
552** recognized system call name. NULL is also returned if the system call
553** is currently undefined.
554*/
drh58ad5802011-03-23 22:02:23 +0000555static sqlite3_syscall_ptr unixGetSystemCall(
556 sqlite3_vfs *pNotUsed,
557 const char *zName
558){
559 unsigned int i;
560
561 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000562 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
563 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
564 }
565 return 0;
566}
567
568/*
569** Return the name of the first system call after zName. If zName==NULL
570** then return the name of the first system call. Return NULL if zName
571** is the last system call or if zName is not the name of a valid
572** system call.
573*/
574static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000575 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000576
577 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000578 if( zName ){
579 for(i=0; i<ArraySize(aSyscall)-1; i++){
580 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000581 }
582 }
dan0fd7d862011-03-29 10:04:23 +0000583 for(i++; i<ArraySize(aSyscall); i++){
584 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000585 }
586 return 0;
587}
588
drhad4f1e52011-03-04 15:43:57 +0000589/*
drh77a3fdc2013-08-30 14:24:12 +0000590** Do not accept any file descriptor less than this value, in order to avoid
591** opening database file using file descriptors that are commonly used for
592** standard input, output, and error.
593*/
594#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
595# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
596#endif
597
598/*
drh8c815d12012-02-13 20:16:37 +0000599** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000600** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000601**
602** If the file creation mode "m" is 0 then set it to the default for
603** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
604** 0644) as modified by the system umask. If m is not 0, then
605** make the file creation mode be exactly m ignoring the umask.
606**
607** The m parameter will be non-zero only when creating -wal, -journal,
608** and -shm files. We want those files to have *exactly* the same
609** permissions as their original database, unadulterated by the umask.
610** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
611** transaction crashes and leaves behind hot journals, then any
612** process that is able to write to the database will also be able to
613** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000614*/
drh8c815d12012-02-13 20:16:37 +0000615static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000616 int fd;
drhe1186ab2013-01-04 20:45:13 +0000617 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5128d002013-08-30 06:20:23 +0000618 while(1){
drh5adc60b2012-04-14 13:25:11 +0000619#if defined(O_CLOEXEC)
620 fd = osOpen(z,f|O_CLOEXEC,m2);
621#else
622 fd = osOpen(z,f,m2);
623#endif
drh5128d002013-08-30 06:20:23 +0000624 if( fd<0 ){
625 if( errno==EINTR ) continue;
626 break;
627 }
drh77a3fdc2013-08-30 14:24:12 +0000628 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
drh5128d002013-08-30 06:20:23 +0000629 osClose(fd);
630 sqlite3_log(SQLITE_WARNING,
631 "attempt to open \"%s\" as file descriptor %d", z, fd);
632 fd = -1;
633 if( osOpen("/dev/null", f, m)<0 ) break;
634 }
drhe1186ab2013-01-04 20:45:13 +0000635 if( fd>=0 ){
636 if( m!=0 ){
637 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000638 if( osFstat(fd, &statbuf)==0
639 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000640 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000641 ){
drhe1186ab2013-01-04 20:45:13 +0000642 osFchmod(fd, m);
643 }
644 }
drh5adc60b2012-04-14 13:25:11 +0000645#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000646 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000647#endif
drhe1186ab2013-01-04 20:45:13 +0000648 }
drh5adc60b2012-04-14 13:25:11 +0000649 return fd;
drhad4f1e52011-03-04 15:43:57 +0000650}
danielk197713adf8a2004-06-03 16:08:41 +0000651
drh107886a2008-11-21 22:21:50 +0000652/*
dan9359c7b2009-08-21 08:29:10 +0000653** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000654** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000655** vxworksFileId objects used by this file, all of which may be
656** shared by multiple threads.
657**
658** Function unixMutexHeld() is used to assert() that the global mutex
659** is held when required. This function is only used as part of assert()
660** statements. e.g.
661**
662** unixEnterMutex()
663** assert( unixMutexHeld() );
664** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000665*/
666static void unixEnterMutex(void){
mistachkin93de6532015-07-03 21:38:09 +0000667 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
drh107886a2008-11-21 22:21:50 +0000668}
669static void unixLeaveMutex(void){
mistachkin93de6532015-07-03 21:38:09 +0000670 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
drh107886a2008-11-21 22:21:50 +0000671}
dan9359c7b2009-08-21 08:29:10 +0000672#ifdef SQLITE_DEBUG
673static int unixMutexHeld(void) {
mistachkin93de6532015-07-03 21:38:09 +0000674 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
dan9359c7b2009-08-21 08:29:10 +0000675}
676#endif
drh107886a2008-11-21 22:21:50 +0000677
drh734c9862008-11-28 15:37:20 +0000678
mistachkinfb383e92015-04-16 03:24:38 +0000679#ifdef SQLITE_HAVE_OS_TRACE
drh734c9862008-11-28 15:37:20 +0000680/*
681** Helper function for printing out trace information from debugging
peter.d.reid60ec9142014-09-06 16:39:46 +0000682** binaries. This returns the string representation of the supplied
drh734c9862008-11-28 15:37:20 +0000683** integer lock-type.
684*/
drh308c2a52010-05-14 11:30:18 +0000685static const char *azFileLock(int eFileLock){
686 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000687 case NO_LOCK: return "NONE";
688 case SHARED_LOCK: return "SHARED";
689 case RESERVED_LOCK: return "RESERVED";
690 case PENDING_LOCK: return "PENDING";
691 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000692 }
693 return "ERROR";
694}
695#endif
696
697#ifdef SQLITE_LOCK_TRACE
698/*
699** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000700**
drh734c9862008-11-28 15:37:20 +0000701** This routine is used for troubleshooting locks on multithreaded
702** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
703** command-line option on the compiler. This code is normally
704** turned off.
705*/
706static int lockTrace(int fd, int op, struct flock *p){
707 char *zOpName, *zType;
708 int s;
709 int savedErrno;
710 if( op==F_GETLK ){
711 zOpName = "GETLK";
712 }else if( op==F_SETLK ){
713 zOpName = "SETLK";
714 }else{
drh99ab3b12011-03-02 15:09:07 +0000715 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000716 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
717 return s;
718 }
719 if( p->l_type==F_RDLCK ){
720 zType = "RDLCK";
721 }else if( p->l_type==F_WRLCK ){
722 zType = "WRLCK";
723 }else if( p->l_type==F_UNLCK ){
724 zType = "UNLCK";
725 }else{
726 assert( 0 );
727 }
728 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000729 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000730 savedErrno = errno;
731 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
732 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
733 (int)p->l_pid, s);
734 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
735 struct flock l2;
736 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000737 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000738 if( l2.l_type==F_RDLCK ){
739 zType = "RDLCK";
740 }else if( l2.l_type==F_WRLCK ){
741 zType = "WRLCK";
742 }else if( l2.l_type==F_UNLCK ){
743 zType = "UNLCK";
744 }else{
745 assert( 0 );
746 }
747 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
748 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
749 }
750 errno = savedErrno;
751 return s;
752}
drh99ab3b12011-03-02 15:09:07 +0000753#undef osFcntl
754#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000755#endif /* SQLITE_LOCK_TRACE */
756
drhff812312011-02-23 13:33:46 +0000757/*
758** Retry ftruncate() calls that fail due to EINTR
dan2ee53412014-09-06 16:49:40 +0000759**
drhe6d41732015-02-21 00:49:00 +0000760** All calls to ftruncate() within this file should be made through
761** this wrapper. On the Android platform, bypassing the logic below
762** could lead to a corrupt database.
drhff812312011-02-23 13:33:46 +0000763*/
drhff812312011-02-23 13:33:46 +0000764static int robust_ftruncate(int h, sqlite3_int64 sz){
765 int rc;
dan2ee53412014-09-06 16:49:40 +0000766#ifdef __ANDROID__
767 /* On Android, ftruncate() always uses 32-bit offsets, even if
768 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
dan524a7332014-09-06 17:06:13 +0000769 ** truncate a file to any size larger than 2GiB. Silently ignore any
dan2ee53412014-09-06 16:49:40 +0000770 ** such attempts. */
771 if( sz>(sqlite3_int64)0x7FFFFFFF ){
772 rc = SQLITE_OK;
773 }else
774#endif
drh99ab3b12011-03-02 15:09:07 +0000775 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000776 return rc;
777}
drh734c9862008-11-28 15:37:20 +0000778
779/*
780** This routine translates a standard POSIX errno code into something
781** useful to the clients of the sqlite3 functions. Specifically, it is
782** intended to translate a variety of "try again" errors into SQLITE_BUSY
783** and a variety of "please close the file descriptor NOW" errors into
784** SQLITE_IOERR
785**
786** Errors during initialization of locks, or file system support for locks,
787** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
788*/
789static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
drh91c4def2015-11-25 14:00:07 +0000790 assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
791 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
792 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
793 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
drh734c9862008-11-28 15:37:20 +0000794 switch (posixError) {
drh91c4def2015-11-25 14:00:07 +0000795 case EACCES:
drh734c9862008-11-28 15:37:20 +0000796 case EAGAIN:
797 case ETIMEDOUT:
798 case EBUSY:
799 case EINTR:
800 case ENOLCK:
801 /* random NFS retry error, unless during file system support
802 * introspection, in which it actually means what it says */
803 return SQLITE_BUSY;
804
drh734c9862008-11-28 15:37:20 +0000805 case EPERM:
806 return SQLITE_PERM;
807
drh734c9862008-11-28 15:37:20 +0000808 default:
809 return sqliteIOErr;
810 }
811}
812
813
drh734c9862008-11-28 15:37:20 +0000814/******************************************************************************
815****************** Begin Unique File ID Utility Used By VxWorks ***************
816**
817** On most versions of unix, we can get a unique ID for a file by concatenating
818** the device number and the inode number. But this does not work on VxWorks.
819** On VxWorks, a unique file id must be based on the canonical filename.
820**
821** A pointer to an instance of the following structure can be used as a
822** unique file ID in VxWorks. Each instance of this structure contains
823** a copy of the canonical filename. There is also a reference count.
824** The structure is reclaimed when the number of pointers to it drops to
825** zero.
826**
827** There are never very many files open at one time and lookups are not
828** a performance-critical path, so it is sufficient to put these
829** structures on a linked list.
830*/
831struct vxworksFileId {
832 struct vxworksFileId *pNext; /* Next in a list of them all */
833 int nRef; /* Number of references to this one */
834 int nName; /* Length of the zCanonicalName[] string */
835 char *zCanonicalName; /* Canonical filename */
836};
837
838#if OS_VXWORKS
839/*
drh9b35ea62008-11-29 02:20:26 +0000840** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000841** variable:
842*/
843static struct vxworksFileId *vxworksFileList = 0;
844
845/*
846** Simplify a filename into its canonical form
847** by making the following changes:
848**
849** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000850** * convert /./ into just /
851** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000852**
853** Changes are made in-place. Return the new name length.
854**
855** The original filename is in z[0..n-1]. Return the number of
856** characters in the simplified name.
857*/
858static int vxworksSimplifyName(char *z, int n){
859 int i, j;
860 while( n>1 && z[n-1]=='/' ){ n--; }
861 for(i=j=0; i<n; i++){
862 if( z[i]=='/' ){
863 if( z[i+1]=='/' ) continue;
864 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
865 i += 1;
866 continue;
867 }
868 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
869 while( j>0 && z[j-1]!='/' ){ j--; }
870 if( j>0 ){ j--; }
871 i += 2;
872 continue;
873 }
874 }
875 z[j++] = z[i];
876 }
877 z[j] = 0;
878 return j;
879}
880
881/*
882** Find a unique file ID for the given absolute pathname. Return
883** a pointer to the vxworksFileId object. This pointer is the unique
884** file ID.
885**
886** The nRef field of the vxworksFileId object is incremented before
887** the object is returned. A new vxworksFileId object is created
888** and added to the global list if necessary.
889**
890** If a memory allocation error occurs, return NULL.
891*/
892static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
893 struct vxworksFileId *pNew; /* search key and new file ID */
894 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
895 int n; /* Length of zAbsoluteName string */
896
897 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000898 n = (int)strlen(zAbsoluteName);
drhf3cdcdc2015-04-29 16:50:28 +0000899 pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
drh734c9862008-11-28 15:37:20 +0000900 if( pNew==0 ) return 0;
901 pNew->zCanonicalName = (char*)&pNew[1];
902 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
903 n = vxworksSimplifyName(pNew->zCanonicalName, n);
904
905 /* Search for an existing entry that matching the canonical name.
906 ** If found, increment the reference count and return a pointer to
907 ** the existing file ID.
908 */
909 unixEnterMutex();
910 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
911 if( pCandidate->nName==n
912 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
913 ){
914 sqlite3_free(pNew);
915 pCandidate->nRef++;
916 unixLeaveMutex();
917 return pCandidate;
918 }
919 }
920
921 /* No match was found. We will make a new file ID */
922 pNew->nRef = 1;
923 pNew->nName = n;
924 pNew->pNext = vxworksFileList;
925 vxworksFileList = pNew;
926 unixLeaveMutex();
927 return pNew;
928}
929
930/*
931** Decrement the reference count on a vxworksFileId object. Free
932** the object when the reference count reaches zero.
933*/
934static void vxworksReleaseFileId(struct vxworksFileId *pId){
935 unixEnterMutex();
936 assert( pId->nRef>0 );
937 pId->nRef--;
938 if( pId->nRef==0 ){
939 struct vxworksFileId **pp;
940 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
941 assert( *pp==pId );
942 *pp = pId->pNext;
943 sqlite3_free(pId);
944 }
945 unixLeaveMutex();
946}
947#endif /* OS_VXWORKS */
948/*************** End of Unique File ID Utility Used By VxWorks ****************
949******************************************************************************/
950
951
952/******************************************************************************
953*************************** Posix Advisory Locking ****************************
954**
drh9b35ea62008-11-29 02:20:26 +0000955** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000956** section 6.5.2.2 lines 483 through 490 specify that when a process
957** sets or clears a lock, that operation overrides any prior locks set
958** by the same process. It does not explicitly say so, but this implies
959** that it overrides locks set by the same process using a different
960** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000961**
962** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000963** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
964**
965** Suppose ./file1 and ./file2 are really the same file (because
966** one is a hard or symbolic link to the other) then if you set
967** an exclusive lock on fd1, then try to get an exclusive lock
968** on fd2, it works. I would have expected the second lock to
969** fail since there was already a lock on the file due to fd1.
970** But not so. Since both locks came from the same process, the
971** second overrides the first, even though they were on different
972** file descriptors opened on different file names.
973**
drh734c9862008-11-28 15:37:20 +0000974** This means that we cannot use POSIX locks to synchronize file access
975** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000976** to synchronize access for threads in separate processes, but not
977** threads within the same process.
978**
979** To work around the problem, SQLite has to manage file locks internally
980** on its own. Whenever a new database is opened, we have to find the
981** specific inode of the database file (the inode is determined by the
982** st_dev and st_ino fields of the stat structure that fstat() fills in)
983** and check for locks already existing on that inode. When locks are
984** created or removed, we have to look at our own internal record of the
985** locks to see if another thread has previously set a lock on that same
986** inode.
987**
drh9b35ea62008-11-29 02:20:26 +0000988** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
989** For VxWorks, we have to use the alternative unique ID system based on
990** canonical filename and implemented in the previous division.)
991**
danielk1977ad94b582007-08-20 06:44:22 +0000992** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000993** descriptor. It is now a structure that holds the integer file
994** descriptor and a pointer to a structure that describes the internal
995** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000996** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000997** point to the same locking structure. The locking structure keeps
998** a reference count (so we will know when to delete it) and a "cnt"
999** field that tells us its internal lock status. cnt==0 means the
1000** file is unlocked. cnt==-1 means the file has an exclusive lock.
1001** cnt>0 means there are cnt shared locks on the file.
1002**
1003** Any attempt to lock or unlock a file first checks the locking
1004** structure. The fcntl() system call is only invoked to set a
1005** POSIX lock if the internal lock structure transitions between
1006** a locked and an unlocked state.
1007**
drh734c9862008-11-28 15:37:20 +00001008** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +00001009**
1010** If you close a file descriptor that points to a file that has locks,
1011** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +00001012** released. To work around this problem, each unixInodeInfo object
1013** maintains a count of the number of pending locks on tha inode.
1014** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +00001015** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +00001016** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +00001017** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +00001018** be closed and that list is walked (and cleared) when the last lock
1019** clears.
1020**
drh9b35ea62008-11-29 02:20:26 +00001021** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +00001022**
drh9b35ea62008-11-29 02:20:26 +00001023** Many older versions of linux use the LinuxThreads library which is
1024** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +00001025** A cannot be modified or overridden by a different thread B.
1026** Only thread A can modify the lock. Locking behavior is correct
1027** if the appliation uses the newer Native Posix Thread Library (NPTL)
1028** on linux - with NPTL a lock created by thread A can override locks
1029** in thread B. But there is no way to know at compile-time which
1030** threading library is being used. So there is no way to know at
1031** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001032** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001033** current process.
drh5fdae772004-06-29 03:29:00 +00001034**
drh8af6c222010-05-14 12:43:01 +00001035** SQLite used to support LinuxThreads. But support for LinuxThreads
1036** was dropped beginning with version 3.7.0. SQLite will still work with
1037** LinuxThreads provided that (1) there is no more than one connection
1038** per database file in the same process and (2) database connections
1039** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001040*/
1041
1042/*
1043** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001044** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001045*/
1046struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001047 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001048#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001049 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001050#else
drh107886a2008-11-21 22:21:50 +00001051 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001052#endif
1053};
1054
1055/*
drhbbd42a62004-05-22 17:41:58 +00001056** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001057** inode. Or, on LinuxThreads, there is one of these structures for
1058** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001059**
danielk1977ad94b582007-08-20 06:44:22 +00001060** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001061** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001062** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001063*/
drh8af6c222010-05-14 12:43:01 +00001064struct unixInodeInfo {
1065 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001066 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001067 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1068 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001069 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001070 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1071 int nLock; /* Number of outstanding file locks */
1072 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1073 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1074 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001075#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001076 unsigned long long sharedByte; /* for AFP simulated shared lock */
1077#endif
drh6c7d5c52008-11-21 20:32:33 +00001078#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001079 sem_t *pSem; /* Named POSIX semaphore */
1080 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001081#endif
drhbbd42a62004-05-22 17:41:58 +00001082};
1083
drhda0e7682008-07-30 15:27:54 +00001084/*
drh8af6c222010-05-14 12:43:01 +00001085** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001086*/
drhd91c68f2010-05-14 14:52:25 +00001087static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001088
drh5fdae772004-06-29 03:29:00 +00001089/*
dane18d4952011-02-21 11:46:24 +00001090**
drhaaeaa182015-11-24 15:12:47 +00001091** This function - unixLogErrorAtLine(), is only ever called via the macro
dane18d4952011-02-21 11:46:24 +00001092** unixLogError().
1093**
1094** It is invoked after an error occurs in an OS function and errno has been
1095** set. It logs a message using sqlite3_log() containing the current value of
1096** errno and, if possible, the human-readable equivalent from strerror() or
1097** strerror_r().
1098**
1099** The first argument passed to the macro should be the error code that
1100** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1101** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001102** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001103** if any.
1104*/
drh0e9365c2011-03-02 02:08:13 +00001105#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1106static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001107 int errcode, /* SQLite error code */
1108 const char *zFunc, /* Name of OS function that failed */
1109 const char *zPath, /* File path associated with error */
1110 int iLine /* Source line number where error occurred */
1111){
1112 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001113 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001114
1115 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1116 ** the strerror() function to obtain the human-readable error message
1117 ** equivalent to errno. Otherwise, use strerror_r().
1118 */
1119#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1120 char aErr[80];
1121 memset(aErr, 0, sizeof(aErr));
1122 zErr = aErr;
1123
1124 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001125 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001126 ** returns a pointer to a buffer containing the error message. That pointer
1127 ** may point to aErr[], or it may point to some static storage somewhere.
1128 ** Otherwise, assume that the system provides the POSIX version of
1129 ** strerror_r(), which always writes an error message into aErr[].
1130 **
1131 ** If the code incorrectly assumes that it is the POSIX version that is
1132 ** available, the error message will often be an empty string. Not a
1133 ** huge problem. Incorrectly concluding that the GNU version is available
1134 ** could lead to a segfault though.
1135 */
1136#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1137 zErr =
1138# endif
drh0e9365c2011-03-02 02:08:13 +00001139 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001140
1141#elif SQLITE_THREADSAFE
1142 /* This is a threadsafe build, but strerror_r() is not available. */
1143 zErr = "";
1144#else
1145 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001146 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001147#endif
1148
drh0e9365c2011-03-02 02:08:13 +00001149 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001150 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001151 "os_unix.c:%d: (%d) %s(%s) - %s",
1152 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001153 );
1154
1155 return errcode;
1156}
1157
drh0e9365c2011-03-02 02:08:13 +00001158/*
1159** Close a file descriptor.
1160**
1161** We assume that close() almost always works, since it is only in a
1162** very sick application or on a very sick platform that it might fail.
1163** If it does fail, simply leak the file descriptor, but do log the
1164** error.
1165**
1166** Note that it is not safe to retry close() after EINTR since the
1167** file descriptor might have already been reused by another thread.
1168** So we don't even try to recover from an EINTR. Just log the error
1169** and move on.
1170*/
1171static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001172 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001173 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1174 pFile ? pFile->zPath : 0, lineno);
1175 }
1176}
dane18d4952011-02-21 11:46:24 +00001177
1178/*
drhe6d41732015-02-21 00:49:00 +00001179** Set the pFile->lastErrno. Do this in a subroutine as that provides
1180** a convenient place to set a breakpoint.
drh4bf66fd2015-02-19 02:43:02 +00001181*/
1182static void storeLastErrno(unixFile *pFile, int error){
1183 pFile->lastErrno = error;
1184}
1185
1186/*
danb0ac3e32010-06-16 10:55:42 +00001187** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001188*/
drh0e9365c2011-03-02 02:08:13 +00001189static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001190 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001191 UnixUnusedFd *p;
1192 UnixUnusedFd *pNext;
1193 for(p=pInode->pUnused; p; p=pNext){
1194 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001195 robust_close(pFile, p->fd, __LINE__);
1196 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001197 }
drh0e9365c2011-03-02 02:08:13 +00001198 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001199}
1200
1201/*
drh8af6c222010-05-14 12:43:01 +00001202** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001203**
1204** The mutex entered using the unixEnterMutex() function must be held
1205** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001206*/
danb0ac3e32010-06-16 10:55:42 +00001207static void releaseInodeInfo(unixFile *pFile){
1208 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001209 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001210 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001211 pInode->nRef--;
1212 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001213 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001214 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001215 if( pInode->pPrev ){
1216 assert( pInode->pPrev->pNext==pInode );
1217 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001218 }else{
drh8af6c222010-05-14 12:43:01 +00001219 assert( inodeList==pInode );
1220 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001221 }
drh8af6c222010-05-14 12:43:01 +00001222 if( pInode->pNext ){
1223 assert( pInode->pNext->pPrev==pInode );
1224 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001225 }
drh8af6c222010-05-14 12:43:01 +00001226 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001227 }
drhbbd42a62004-05-22 17:41:58 +00001228 }
1229}
1230
1231/*
drh8af6c222010-05-14 12:43:01 +00001232** Given a file descriptor, locate the unixInodeInfo object that
1233** describes that file descriptor. Create a new one if necessary. The
1234** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001235**
dan9359c7b2009-08-21 08:29:10 +00001236** The mutex entered using the unixEnterMutex() function must be held
1237** when this function is called.
1238**
drh6c7d5c52008-11-21 20:32:33 +00001239** Return an appropriate error code.
1240*/
drh8af6c222010-05-14 12:43:01 +00001241static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001242 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001243 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001244){
1245 int rc; /* System call return code */
1246 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001247 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1248 struct stat statbuf; /* Low-level file information */
1249 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001250
dan9359c7b2009-08-21 08:29:10 +00001251 assert( unixMutexHeld() );
1252
drh6c7d5c52008-11-21 20:32:33 +00001253 /* Get low-level information about the file that we can used to
1254 ** create a unique name for the file.
1255 */
1256 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001257 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001258 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001259 storeLastErrno(pFile, errno);
drh40fe8d32015-11-30 20:36:26 +00001260#if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
drh6c7d5c52008-11-21 20:32:33 +00001261 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1262#endif
1263 return SQLITE_IOERR;
1264 }
1265
drheb0d74f2009-02-03 15:27:02 +00001266#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001267 /* On OS X on an msdos filesystem, the inode number is reported
1268 ** incorrectly for zero-size files. See ticket #3260. To work
1269 ** around this problem (we consider it a bug in OS X, not SQLite)
1270 ** we always increase the file size to 1 by writing a single byte
1271 ** prior to accessing the inode number. The one byte written is
1272 ** an ASCII 'S' character which also happens to be the first byte
1273 ** in the header of every SQLite database. In this way, if there
1274 ** is a race condition such that another thread has already populated
1275 ** the first page of the database, no damage is done.
1276 */
drh7ed97b92010-01-20 13:07:21 +00001277 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001278 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001279 if( rc!=1 ){
drh4bf66fd2015-02-19 02:43:02 +00001280 storeLastErrno(pFile, errno);
drheb0d74f2009-02-03 15:27:02 +00001281 return SQLITE_IOERR;
1282 }
drh99ab3b12011-03-02 15:09:07 +00001283 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001284 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001285 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001286 return SQLITE_IOERR;
1287 }
1288 }
drheb0d74f2009-02-03 15:27:02 +00001289#endif
drh6c7d5c52008-11-21 20:32:33 +00001290
drh8af6c222010-05-14 12:43:01 +00001291 memset(&fileId, 0, sizeof(fileId));
1292 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001293#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001294 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001295#else
drh8af6c222010-05-14 12:43:01 +00001296 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001297#endif
drh8af6c222010-05-14 12:43:01 +00001298 pInode = inodeList;
1299 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1300 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001301 }
drh8af6c222010-05-14 12:43:01 +00001302 if( pInode==0 ){
drhf3cdcdc2015-04-29 16:50:28 +00001303 pInode = sqlite3_malloc64( sizeof(*pInode) );
drh8af6c222010-05-14 12:43:01 +00001304 if( pInode==0 ){
1305 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001306 }
drh8af6c222010-05-14 12:43:01 +00001307 memset(pInode, 0, sizeof(*pInode));
1308 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1309 pInode->nRef = 1;
1310 pInode->pNext = inodeList;
1311 pInode->pPrev = 0;
1312 if( inodeList ) inodeList->pPrev = pInode;
1313 inodeList = pInode;
1314 }else{
1315 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001316 }
drh8af6c222010-05-14 12:43:01 +00001317 *ppInode = pInode;
1318 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001319}
drh6c7d5c52008-11-21 20:32:33 +00001320
drhb959a012013-12-07 12:29:22 +00001321/*
1322** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1323*/
1324static int fileHasMoved(unixFile *pFile){
drh61ffea52014-08-12 12:19:25 +00001325#if OS_VXWORKS
1326 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1327#else
drhb959a012013-12-07 12:29:22 +00001328 struct stat buf;
1329 return pFile->pInode!=0 &&
drh61ffea52014-08-12 12:19:25 +00001330 (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
drh91be7dc2014-08-11 13:53:30 +00001331#endif
drhb959a012013-12-07 12:29:22 +00001332}
1333
aswift5b1a2562008-08-22 00:22:35 +00001334
1335/*
drhfbc7e882013-04-11 01:16:15 +00001336** Check a unixFile that is a database. Verify the following:
1337**
1338** (1) There is exactly one hard link on the file
1339** (2) The file is not a symbolic link
1340** (3) The file has not been renamed or unlinked
1341**
1342** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1343*/
1344static void verifyDbFile(unixFile *pFile){
1345 struct stat buf;
1346 int rc;
drhfbc7e882013-04-11 01:16:15 +00001347 rc = osFstat(pFile->h, &buf);
1348 if( rc!=0 ){
1349 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001350 return;
1351 }
drh3044b512014-06-16 16:41:52 +00001352 if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
drhfbc7e882013-04-11 01:16:15 +00001353 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001354 return;
1355 }
1356 if( buf.st_nlink>1 ){
1357 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001358 return;
1359 }
drhb959a012013-12-07 12:29:22 +00001360 if( fileHasMoved(pFile) ){
drhfbc7e882013-04-11 01:16:15 +00001361 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001362 return;
1363 }
1364}
1365
1366
1367/*
danielk197713adf8a2004-06-03 16:08:41 +00001368** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001369** file by this or any other process. If such a lock is held, set *pResOut
1370** to a non-zero value otherwise *pResOut is set to zero. The return value
1371** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001372*/
danielk1977861f7452008-06-05 11:39:11 +00001373static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001374 int rc = SQLITE_OK;
1375 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001376 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001377
danielk1977861f7452008-06-05 11:39:11 +00001378 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1379
drh054889e2005-11-30 03:20:31 +00001380 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00001381 assert( pFile->eFileLock<=SHARED_LOCK );
drh8af6c222010-05-14 12:43:01 +00001382 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001383
1384 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001385 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001386 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001387 }
1388
drh2ac3ee92004-06-07 16:27:46 +00001389 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001390 */
danielk197709480a92009-02-09 05:32:32 +00001391#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001392 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001393 struct flock lock;
1394 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001395 lock.l_start = RESERVED_BYTE;
1396 lock.l_len = 1;
1397 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001398 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1399 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001400 storeLastErrno(pFile, errno);
aswift5b1a2562008-08-22 00:22:35 +00001401 } else if( lock.l_type!=F_UNLCK ){
1402 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001403 }
1404 }
danielk197709480a92009-02-09 05:32:32 +00001405#endif
danielk197713adf8a2004-06-03 16:08:41 +00001406
drh6c7d5c52008-11-21 20:32:33 +00001407 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001408 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001409
aswift5b1a2562008-08-22 00:22:35 +00001410 *pResOut = reserved;
1411 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001412}
1413
1414/*
drha7e61d82011-03-12 17:02:57 +00001415** Attempt to set a system-lock on the file pFile. The lock is
1416** described by pLock.
1417**
drh77197112011-03-15 19:08:48 +00001418** If the pFile was opened read/write from unix-excl, then the only lock
1419** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001420** the first time any lock is attempted. All subsequent system locking
1421** operations become no-ops. Locking operations still happen internally,
1422** in order to coordinate access between separate database connections
1423** within this process, but all of that is handled in memory and the
1424** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001425**
1426** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1427** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1428** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001429**
1430** Zero is returned if the call completes successfully, or -1 if a call
1431** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001432*/
1433static int unixFileLock(unixFile *pFile, struct flock *pLock){
1434 int rc;
drh3cb93392011-03-12 18:10:44 +00001435 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001436 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001437 assert( pInode!=0 );
drh50358ad2015-12-02 01:04:33 +00001438 if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
drh3cb93392011-03-12 18:10:44 +00001439 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001440 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001441 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001442 lock.l_whence = SEEK_SET;
1443 lock.l_start = SHARED_FIRST;
1444 lock.l_len = SHARED_SIZE;
1445 lock.l_type = F_WRLCK;
1446 rc = osFcntl(pFile->h, F_SETLK, &lock);
1447 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001448 pInode->bProcessLock = 1;
1449 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001450 }else{
1451 rc = 0;
1452 }
1453 }else{
1454 rc = osFcntl(pFile->h, F_SETLK, pLock);
1455 }
1456 return rc;
1457}
1458
1459/*
drh308c2a52010-05-14 11:30:18 +00001460** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001461** of the following:
1462**
drh2ac3ee92004-06-07 16:27:46 +00001463** (1) SHARED_LOCK
1464** (2) RESERVED_LOCK
1465** (3) PENDING_LOCK
1466** (4) EXCLUSIVE_LOCK
1467**
drhb3e04342004-06-08 00:47:47 +00001468** Sometimes when requesting one lock state, additional lock states
1469** are inserted in between. The locking might fail on one of the later
1470** transitions leaving the lock state different from what it started but
1471** still short of its goal. The following chart shows the allowed
1472** transitions and the inserted intermediate states:
1473**
1474** UNLOCKED -> SHARED
1475** SHARED -> RESERVED
1476** SHARED -> (PENDING) -> EXCLUSIVE
1477** RESERVED -> (PENDING) -> EXCLUSIVE
1478** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001479**
drha6abd042004-06-09 17:37:22 +00001480** This routine will only increase a lock. Use the sqlite3OsUnlock()
1481** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001482*/
drh308c2a52010-05-14 11:30:18 +00001483static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001484 /* The following describes the implementation of the various locks and
1485 ** lock transitions in terms of the POSIX advisory shared and exclusive
1486 ** lock primitives (called read-locks and write-locks below, to avoid
1487 ** confusion with SQLite lock names). The algorithms are complicated
1488 ** slightly in order to be compatible with windows systems simultaneously
1489 ** accessing the same database file, in case that is ever required.
1490 **
1491 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1492 ** byte', each single bytes at well known offsets, and the 'shared byte
1493 ** range', a range of 510 bytes at a well known offset.
1494 **
1495 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1496 ** byte'. If this is successful, a random byte from the 'shared byte
1497 ** range' is read-locked and the lock on the 'pending byte' released.
1498 **
danielk197790ba3bd2004-06-25 08:32:25 +00001499 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1500 ** A RESERVED lock is implemented by grabbing a write-lock on the
1501 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001502 **
1503 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001504 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1505 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1506 ** obtained, but existing SHARED locks are allowed to persist. A process
1507 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1508 ** This property is used by the algorithm for rolling back a journal file
1509 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001510 **
danielk197790ba3bd2004-06-25 08:32:25 +00001511 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1512 ** implemented by obtaining a write-lock on the entire 'shared byte
1513 ** range'. Since all other locks require a read-lock on one of the bytes
1514 ** within this range, this ensures that no other locks are held on the
1515 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001516 **
1517 ** The reason a single byte cannot be used instead of the 'shared byte
1518 ** range' is that some versions of windows do not support read-locks. By
1519 ** locking a random byte from a range, concurrent SHARED locks may exist
1520 ** even if the locking primitive used is always a write-lock.
1521 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001522 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001523 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001524 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001525 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001526 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001527
drh054889e2005-11-30 03:20:31 +00001528 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001529 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1530 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh91eb93c2015-03-03 19:56:20 +00001531 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001532 osGetpid(0)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001533
1534 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001535 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001536 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001537 */
drh308c2a52010-05-14 11:30:18 +00001538 if( pFile->eFileLock>=eFileLock ){
1539 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1540 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001541 return SQLITE_OK;
1542 }
1543
drh0c2694b2009-09-03 16:23:44 +00001544 /* Make sure the locking sequence is correct.
1545 ** (1) We never move from unlocked to anything higher than shared lock.
1546 ** (2) SQLite never explicitly requests a pendig lock.
1547 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001548 */
drh308c2a52010-05-14 11:30:18 +00001549 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1550 assert( eFileLock!=PENDING_LOCK );
1551 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001552
drh8af6c222010-05-14 12:43:01 +00001553 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001554 */
drh6c7d5c52008-11-21 20:32:33 +00001555 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001556 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001557
danielk1977ad94b582007-08-20 06:44:22 +00001558 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001559 ** handle that precludes the requested lock, return BUSY.
1560 */
drh8af6c222010-05-14 12:43:01 +00001561 if( (pFile->eFileLock!=pInode->eFileLock &&
1562 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001563 ){
1564 rc = SQLITE_BUSY;
1565 goto end_lock;
1566 }
1567
1568 /* If a SHARED lock is requested, and some thread using this PID already
1569 ** has a SHARED or RESERVED lock, then increment reference counts and
1570 ** return SQLITE_OK.
1571 */
drh308c2a52010-05-14 11:30:18 +00001572 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001573 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001574 assert( eFileLock==SHARED_LOCK );
1575 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001576 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001577 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001578 pInode->nShared++;
1579 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001580 goto end_lock;
1581 }
1582
danielk19779a1d0ab2004-06-01 14:09:28 +00001583
drh3cde3bb2004-06-12 02:17:14 +00001584 /* A PENDING lock is needed before acquiring a SHARED lock and before
1585 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1586 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001587 */
drh0c2694b2009-09-03 16:23:44 +00001588 lock.l_len = 1L;
1589 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001590 if( eFileLock==SHARED_LOCK
1591 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001592 ){
drh308c2a52010-05-14 11:30:18 +00001593 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001594 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001595 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001596 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001597 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001598 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001599 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001600 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001601 goto end_lock;
1602 }
drh3cde3bb2004-06-12 02:17:14 +00001603 }
1604
1605
1606 /* If control gets to this point, then actually go ahead and make
1607 ** operating system calls for the specified lock.
1608 */
drh308c2a52010-05-14 11:30:18 +00001609 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001610 assert( pInode->nShared==0 );
1611 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001612 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001613
drh2ac3ee92004-06-07 16:27:46 +00001614 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001615 lock.l_start = SHARED_FIRST;
1616 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001617 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001618 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001619 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001620 }
dan661d71a2011-03-30 19:08:03 +00001621
drh2ac3ee92004-06-07 16:27:46 +00001622 /* Drop the temporary PENDING lock */
1623 lock.l_start = PENDING_BYTE;
1624 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001625 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001626 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1627 /* This could happen with a network mount */
1628 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001629 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001630 }
dan661d71a2011-03-30 19:08:03 +00001631
1632 if( rc ){
1633 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001634 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001635 }
dan661d71a2011-03-30 19:08:03 +00001636 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001637 }else{
drh308c2a52010-05-14 11:30:18 +00001638 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001639 pInode->nLock++;
1640 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001641 }
drh8af6c222010-05-14 12:43:01 +00001642 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001643 /* We are trying for an exclusive lock but another thread in this
1644 ** same process is still holding a shared lock. */
1645 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001646 }else{
drh3cde3bb2004-06-12 02:17:14 +00001647 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001648 ** assumed that there is a SHARED or greater lock on the file
1649 ** already.
1650 */
drh308c2a52010-05-14 11:30:18 +00001651 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001652 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001653
1654 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1655 if( eFileLock==RESERVED_LOCK ){
1656 lock.l_start = RESERVED_BYTE;
1657 lock.l_len = 1L;
1658 }else{
1659 lock.l_start = SHARED_FIRST;
1660 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001661 }
dan661d71a2011-03-30 19:08:03 +00001662
1663 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001664 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001665 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001666 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001667 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001668 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001669 }
drhbbd42a62004-05-22 17:41:58 +00001670 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001671
drh8f941bc2009-01-14 23:03:40 +00001672
drhd3d8c042012-05-29 17:02:40 +00001673#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001674 /* Set up the transaction-counter change checking flags when
1675 ** transitioning from a SHARED to a RESERVED lock. The change
1676 ** from SHARED to RESERVED marks the beginning of a normal
1677 ** write operation (not a hot journal rollback).
1678 */
1679 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001680 && pFile->eFileLock<=SHARED_LOCK
1681 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001682 ){
1683 pFile->transCntrChng = 0;
1684 pFile->dbUpdate = 0;
1685 pFile->inNormalWrite = 1;
1686 }
1687#endif
1688
1689
danielk1977ecb2a962004-06-02 06:30:16 +00001690 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001691 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001692 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001693 }else if( eFileLock==EXCLUSIVE_LOCK ){
1694 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001695 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001696 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001697
1698end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001699 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001700 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1701 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001702 return rc;
1703}
1704
1705/*
dan08da86a2009-08-21 17:18:03 +00001706** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001707** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001708*/
1709static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001710 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001711 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001712 p->pNext = pInode->pUnused;
1713 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001714 pFile->h = -1;
1715 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001716}
1717
1718/*
drh308c2a52010-05-14 11:30:18 +00001719** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001720** must be either NO_LOCK or SHARED_LOCK.
1721**
1722** If the locking level of the file descriptor is already at or below
1723** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001724**
1725** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1726** the byte range is divided into 2 parts and the first part is unlocked then
1727** set to a read lock, then the other part is simply unlocked. This works
1728** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1729** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001730*/
drha7e61d82011-03-12 17:02:57 +00001731static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001732 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001733 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001734 struct flock lock;
1735 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001736
drh054889e2005-11-30 03:20:31 +00001737 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001738 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001739 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001740 osGetpid(0)));
drha6abd042004-06-09 17:37:22 +00001741
drh308c2a52010-05-14 11:30:18 +00001742 assert( eFileLock<=SHARED_LOCK );
1743 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001744 return SQLITE_OK;
1745 }
drh6c7d5c52008-11-21 20:32:33 +00001746 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001747 pInode = pFile->pInode;
1748 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001749 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001750 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001751
drhd3d8c042012-05-29 17:02:40 +00001752#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001753 /* When reducing a lock such that other processes can start
1754 ** reading the database file again, make sure that the
1755 ** transaction counter was updated if any part of the database
1756 ** file changed. If the transaction counter is not updated,
1757 ** other connections to the same file might not realize that
1758 ** the file has changed and hence might not know to flush their
1759 ** cache. The use of a stale cache can lead to database corruption.
1760 */
drh8f941bc2009-01-14 23:03:40 +00001761 pFile->inNormalWrite = 0;
1762#endif
1763
drh7ed97b92010-01-20 13:07:21 +00001764 /* downgrading to a shared lock on NFS involves clearing the write lock
1765 ** before establishing the readlock - to avoid a race condition we downgrade
1766 ** the lock in 2 blocks, so that part of the range will be covered by a
1767 ** write lock until the rest is covered by a read lock:
1768 ** 1: [WWWWW]
1769 ** 2: [....W]
1770 ** 3: [RRRRW]
1771 ** 4: [RRRR.]
1772 */
drh308c2a52010-05-14 11:30:18 +00001773 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001774#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001775 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001776 assert( handleNFSUnlock==0 );
1777#endif
1778#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001779 if( handleNFSUnlock ){
drha712b4b2015-02-19 16:12:04 +00001780 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001781 off_t divSize = SHARED_SIZE - 1;
1782
1783 lock.l_type = F_UNLCK;
1784 lock.l_whence = SEEK_SET;
1785 lock.l_start = SHARED_FIRST;
1786 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001787 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001788 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001789 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001790 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001791 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001792 }
drh7ed97b92010-01-20 13:07:21 +00001793 lock.l_type = F_RDLCK;
1794 lock.l_whence = SEEK_SET;
1795 lock.l_start = SHARED_FIRST;
1796 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001797 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001798 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001799 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1800 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001801 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001802 }
1803 goto end_unlock;
1804 }
1805 lock.l_type = F_UNLCK;
1806 lock.l_whence = SEEK_SET;
1807 lock.l_start = SHARED_FIRST+divSize;
1808 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001809 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001810 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001811 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001812 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001813 goto end_unlock;
1814 }
drh30f776f2011-02-25 03:25:07 +00001815 }else
1816#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1817 {
drh7ed97b92010-01-20 13:07:21 +00001818 lock.l_type = F_RDLCK;
1819 lock.l_whence = SEEK_SET;
1820 lock.l_start = SHARED_FIRST;
1821 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001822 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001823 /* In theory, the call to unixFileLock() cannot fail because another
1824 ** process is holding an incompatible lock. If it does, this
1825 ** indicates that the other process is not following the locking
1826 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1827 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1828 ** an assert to fail). */
1829 rc = SQLITE_IOERR_RDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001830 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00001831 goto end_unlock;
1832 }
drh9c105bb2004-10-02 20:38:28 +00001833 }
1834 }
drhbbd42a62004-05-22 17:41:58 +00001835 lock.l_type = F_UNLCK;
1836 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001837 lock.l_start = PENDING_BYTE;
1838 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001839 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001840 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001841 }else{
danea83bc62011-04-01 11:56:32 +00001842 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001843 storeLastErrno(pFile, errno);
drhcd731cf2009-03-28 23:23:02 +00001844 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001845 }
drhbbd42a62004-05-22 17:41:58 +00001846 }
drh308c2a52010-05-14 11:30:18 +00001847 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001848 /* Decrement the shared lock counter. Release the lock using an
1849 ** OS call only when all threads in this same process have released
1850 ** the lock.
1851 */
drh8af6c222010-05-14 12:43:01 +00001852 pInode->nShared--;
1853 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001854 lock.l_type = F_UNLCK;
1855 lock.l_whence = SEEK_SET;
1856 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001857 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001858 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001859 }else{
danea83bc62011-04-01 11:56:32 +00001860 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001861 storeLastErrno(pFile, errno);
drh8af6c222010-05-14 12:43:01 +00001862 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001863 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001864 }
drha6abd042004-06-09 17:37:22 +00001865 }
1866
drhbbd42a62004-05-22 17:41:58 +00001867 /* Decrement the count of locks against this same file. When the
1868 ** count reaches zero, close any other file descriptors whose close
1869 ** was deferred because of outstanding locks.
1870 */
drh8af6c222010-05-14 12:43:01 +00001871 pInode->nLock--;
1872 assert( pInode->nLock>=0 );
1873 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001874 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001875 }
1876 }
drhf2f105d2012-08-20 15:53:54 +00001877
aswift5b1a2562008-08-22 00:22:35 +00001878end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001879 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001880 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001881 return rc;
drhbbd42a62004-05-22 17:41:58 +00001882}
1883
1884/*
drh308c2a52010-05-14 11:30:18 +00001885** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001886** must be either NO_LOCK or SHARED_LOCK.
1887**
1888** If the locking level of the file descriptor is already at or below
1889** the requested locking level, this routine is a no-op.
1890*/
drh308c2a52010-05-14 11:30:18 +00001891static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00001892#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00001893 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00001894#endif
drha7e61d82011-03-12 17:02:57 +00001895 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001896}
1897
mistachkine98844f2013-08-24 00:59:24 +00001898#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001899static int unixMapfile(unixFile *pFd, i64 nByte);
1900static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00001901#endif
danf23da962013-03-23 21:00:41 +00001902
drh7ed97b92010-01-20 13:07:21 +00001903/*
danielk1977e339d652008-06-28 11:23:00 +00001904** This function performs the parts of the "close file" operation
1905** common to all locking schemes. It closes the directory and file
1906** handles, if they are valid, and sets all fields of the unixFile
1907** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001908**
1909** It is *not* necessary to hold the mutex when this routine is called,
1910** even on VxWorks. A mutex will be acquired on VxWorks by the
1911** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001912*/
1913static int closeUnixFile(sqlite3_file *id){
1914 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00001915#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001916 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00001917#endif
dan661d71a2011-03-30 19:08:03 +00001918 if( pFile->h>=0 ){
1919 robust_close(pFile, pFile->h, __LINE__);
1920 pFile->h = -1;
1921 }
1922#if OS_VXWORKS
1923 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001924 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001925 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001926 }
1927 vxworksReleaseFileId(pFile->pId);
1928 pFile->pId = 0;
1929 }
1930#endif
drh0bdbc902014-06-16 18:35:06 +00001931#ifdef SQLITE_UNLINK_AFTER_CLOSE
1932 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
1933 osUnlink(pFile->zPath);
1934 sqlite3_free(*(char**)&pFile->zPath);
1935 pFile->zPath = 0;
1936 }
1937#endif
dan661d71a2011-03-30 19:08:03 +00001938 OSTRACE(("CLOSE %-3d\n", pFile->h));
1939 OpenCounter(-1);
1940 sqlite3_free(pFile->pUnused);
1941 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001942 return SQLITE_OK;
1943}
1944
1945/*
danielk1977e3026632004-06-22 11:29:02 +00001946** Close a file.
1947*/
danielk197762079062007-08-15 17:08:46 +00001948static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001949 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001950 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00001951 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00001952 unixUnlock(id, NO_LOCK);
1953 unixEnterMutex();
1954
1955 /* unixFile.pInode is always valid here. Otherwise, a different close
1956 ** routine (e.g. nolockClose()) would be called instead.
1957 */
1958 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1959 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1960 /* If there are outstanding locks, do not actually close the file just
1961 ** yet because that would clear those locks. Instead, add the file
1962 ** descriptor to pInode->pUnused list. It will be automatically closed
1963 ** when the last lock is cleared.
1964 */
1965 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001966 }
dan661d71a2011-03-30 19:08:03 +00001967 releaseInodeInfo(pFile);
1968 rc = closeUnixFile(id);
1969 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001970 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001971}
1972
drh734c9862008-11-28 15:37:20 +00001973/************** End of the posix advisory lock implementation *****************
1974******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001975
drh734c9862008-11-28 15:37:20 +00001976/******************************************************************************
1977****************************** No-op Locking **********************************
1978**
1979** Of the various locking implementations available, this is by far the
1980** simplest: locking is ignored. No attempt is made to lock the database
1981** file for reading or writing.
1982**
1983** This locking mode is appropriate for use on read-only databases
1984** (ex: databases that are burned into CD-ROM, for example.) It can
1985** also be used if the application employs some external mechanism to
1986** prevent simultaneous access of the same database by two or more
1987** database connections. But there is a serious risk of database
1988** corruption if this locking mode is used in situations where multiple
1989** database connections are accessing the same database file at the same
1990** time and one or more of those connections are writing.
1991*/
drhbfe66312006-10-03 17:40:40 +00001992
drh734c9862008-11-28 15:37:20 +00001993static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1994 UNUSED_PARAMETER(NotUsed);
1995 *pResOut = 0;
1996 return SQLITE_OK;
1997}
drh734c9862008-11-28 15:37:20 +00001998static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1999 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2000 return SQLITE_OK;
2001}
drh734c9862008-11-28 15:37:20 +00002002static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
2003 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2004 return SQLITE_OK;
2005}
2006
2007/*
drh9b35ea62008-11-29 02:20:26 +00002008** Close the file.
drh734c9862008-11-28 15:37:20 +00002009*/
2010static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00002011 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002012}
2013
2014/******************* End of the no-op lock implementation *********************
2015******************************************************************************/
2016
2017/******************************************************************************
2018************************* Begin dot-file Locking ******************************
2019**
mistachkin48864df2013-03-21 21:20:32 +00002020** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00002021** files (really a directory) to control access to the database. This works
2022** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002023**
2024** (1) There is zero concurrency. A single reader blocks all other
2025** connections from reading or writing the database.
2026**
2027** (2) An application crash or power loss can leave stale lock files
2028** sitting around that need to be cleared manually.
2029**
2030** Nevertheless, a dotlock is an appropriate locking mode for use if no
2031** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002032**
drh9ef6bc42011-11-04 02:24:02 +00002033** Dotfile locking works by creating a subdirectory in the same directory as
2034** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002035** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002036** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002037*/
2038
2039/*
2040** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002041** lock directory.
drh734c9862008-11-28 15:37:20 +00002042*/
2043#define DOTLOCK_SUFFIX ".lock"
2044
drh7708e972008-11-29 00:56:52 +00002045/*
2046** This routine checks if there is a RESERVED lock held on the specified
2047** file by this or any other process. If such a lock is held, set *pResOut
2048** to a non-zero value otherwise *pResOut is set to zero. The return value
2049** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2050**
2051** In dotfile locking, either a lock exists or it does not. So in this
2052** variation of CheckReservedLock(), *pResOut is set to true if any lock
2053** is held on the file and false if the file is unlocked.
2054*/
drh734c9862008-11-28 15:37:20 +00002055static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2056 int rc = SQLITE_OK;
2057 int reserved = 0;
2058 unixFile *pFile = (unixFile*)id;
2059
2060 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2061
2062 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00002063 reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
drh308c2a52010-05-14 11:30:18 +00002064 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002065 *pResOut = reserved;
2066 return rc;
2067}
2068
drh7708e972008-11-29 00:56:52 +00002069/*
drh308c2a52010-05-14 11:30:18 +00002070** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002071** of the following:
2072**
2073** (1) SHARED_LOCK
2074** (2) RESERVED_LOCK
2075** (3) PENDING_LOCK
2076** (4) EXCLUSIVE_LOCK
2077**
2078** Sometimes when requesting one lock state, additional lock states
2079** are inserted in between. The locking might fail on one of the later
2080** transitions leaving the lock state different from what it started but
2081** still short of its goal. The following chart shows the allowed
2082** transitions and the inserted intermediate states:
2083**
2084** UNLOCKED -> SHARED
2085** SHARED -> RESERVED
2086** SHARED -> (PENDING) -> EXCLUSIVE
2087** RESERVED -> (PENDING) -> EXCLUSIVE
2088** PENDING -> EXCLUSIVE
2089**
2090** This routine will only increase a lock. Use the sqlite3OsUnlock()
2091** routine to lower a locking level.
2092**
2093** With dotfile locking, we really only support state (4): EXCLUSIVE.
2094** But we track the other locking levels internally.
2095*/
drh308c2a52010-05-14 11:30:18 +00002096static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002097 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002098 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002099 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002100
drh7708e972008-11-29 00:56:52 +00002101
2102 /* If we have any lock, then the lock file already exists. All we have
2103 ** to do is adjust our internal record of the lock level.
2104 */
drh308c2a52010-05-14 11:30:18 +00002105 if( pFile->eFileLock > NO_LOCK ){
2106 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002107 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002108#ifdef HAVE_UTIME
2109 utime(zLockFile, NULL);
2110#else
drh734c9862008-11-28 15:37:20 +00002111 utimes(zLockFile, NULL);
2112#endif
drh7708e972008-11-29 00:56:52 +00002113 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002114 }
2115
2116 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002117 rc = osMkdir(zLockFile, 0777);
2118 if( rc<0 ){
2119 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002120 int tErrno = errno;
2121 if( EEXIST == tErrno ){
2122 rc = SQLITE_BUSY;
2123 } else {
2124 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drha8de1e12015-11-30 00:05:39 +00002125 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00002126 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002127 }
2128 }
drh7708e972008-11-29 00:56:52 +00002129 return rc;
drh734c9862008-11-28 15:37:20 +00002130 }
drh734c9862008-11-28 15:37:20 +00002131
2132 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002133 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002134 return rc;
2135}
2136
drh7708e972008-11-29 00:56:52 +00002137/*
drh308c2a52010-05-14 11:30:18 +00002138** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002139** must be either NO_LOCK or SHARED_LOCK.
2140**
2141** If the locking level of the file descriptor is already at or below
2142** the requested locking level, this routine is a no-op.
2143**
2144** When the locking level reaches NO_LOCK, delete the lock file.
2145*/
drh308c2a52010-05-14 11:30:18 +00002146static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002147 unixFile *pFile = (unixFile*)id;
2148 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002149 int rc;
drh734c9862008-11-28 15:37:20 +00002150
2151 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002152 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002153 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002154 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002155
2156 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002157 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002158 return SQLITE_OK;
2159 }
drh7708e972008-11-29 00:56:52 +00002160
2161 /* To downgrade to shared, simply update our internal notion of the
2162 ** lock state. No need to mess with the file on disk.
2163 */
drh308c2a52010-05-14 11:30:18 +00002164 if( eFileLock==SHARED_LOCK ){
2165 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002166 return SQLITE_OK;
2167 }
2168
drh7708e972008-11-29 00:56:52 +00002169 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002170 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002171 rc = osRmdir(zLockFile);
drh9ef6bc42011-11-04 02:24:02 +00002172 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002173 int tErrno = errno;
drha8de1e12015-11-30 00:05:39 +00002174 if( tErrno==ENOENT ){
2175 rc = SQLITE_OK;
2176 }else{
danea83bc62011-04-01 11:56:32 +00002177 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002178 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002179 }
2180 return rc;
2181 }
drh308c2a52010-05-14 11:30:18 +00002182 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002183 return SQLITE_OK;
2184}
2185
2186/*
drh9b35ea62008-11-29 02:20:26 +00002187** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002188*/
2189static int dotlockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002190 unixFile *pFile = (unixFile*)id;
2191 assert( id!=0 );
2192 dotlockUnlock(id, NO_LOCK);
2193 sqlite3_free(pFile->lockingContext);
2194 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002195}
2196/****************** End of the dot-file lock implementation *******************
2197******************************************************************************/
2198
2199/******************************************************************************
2200************************** Begin flock Locking ********************************
2201**
2202** Use the flock() system call to do file locking.
2203**
drh6b9d6dd2008-12-03 19:34:47 +00002204** flock() locking is like dot-file locking in that the various
2205** fine-grain locking levels supported by SQLite are collapsed into
2206** a single exclusive lock. In other words, SHARED, RESERVED, and
2207** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2208** still works when you do this, but concurrency is reduced since
2209** only a single process can be reading the database at a time.
2210**
drhe89b2912015-03-03 20:42:01 +00002211** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
drh734c9862008-11-28 15:37:20 +00002212*/
drhe89b2912015-03-03 20:42:01 +00002213#if SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002214
drh6b9d6dd2008-12-03 19:34:47 +00002215/*
drhff812312011-02-23 13:33:46 +00002216** Retry flock() calls that fail with EINTR
2217*/
2218#ifdef EINTR
2219static int robust_flock(int fd, int op){
2220 int rc;
2221 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2222 return rc;
2223}
2224#else
drh5c819272011-02-23 14:00:12 +00002225# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002226#endif
2227
2228
2229/*
drh6b9d6dd2008-12-03 19:34:47 +00002230** This routine checks if there is a RESERVED lock held on the specified
2231** file by this or any other process. If such a lock is held, set *pResOut
2232** to a non-zero value otherwise *pResOut is set to zero. The return value
2233** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2234*/
drh734c9862008-11-28 15:37:20 +00002235static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2236 int rc = SQLITE_OK;
2237 int reserved = 0;
2238 unixFile *pFile = (unixFile*)id;
2239
2240 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2241
2242 assert( pFile );
2243
2244 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002245 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002246 reserved = 1;
2247 }
2248
2249 /* Otherwise see if some other process holds it. */
2250 if( !reserved ){
2251 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002252 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002253 if( !lrc ){
2254 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002255 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002256 if ( lrc ) {
2257 int tErrno = errno;
2258 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002259 lrc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00002260 storeLastErrno(pFile, tErrno);
2261 rc = lrc;
drh734c9862008-11-28 15:37:20 +00002262 }
2263 } else {
2264 int tErrno = errno;
2265 reserved = 1;
2266 /* someone else might have it reserved */
2267 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2268 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002269 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002270 rc = lrc;
2271 }
2272 }
2273 }
drh308c2a52010-05-14 11:30:18 +00002274 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002275
2276#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2277 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2278 rc = SQLITE_OK;
2279 reserved=1;
2280 }
2281#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2282 *pResOut = reserved;
2283 return rc;
2284}
2285
drh6b9d6dd2008-12-03 19:34:47 +00002286/*
drh308c2a52010-05-14 11:30:18 +00002287** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002288** of the following:
2289**
2290** (1) SHARED_LOCK
2291** (2) RESERVED_LOCK
2292** (3) PENDING_LOCK
2293** (4) EXCLUSIVE_LOCK
2294**
2295** Sometimes when requesting one lock state, additional lock states
2296** are inserted in between. The locking might fail on one of the later
2297** transitions leaving the lock state different from what it started but
2298** still short of its goal. The following chart shows the allowed
2299** transitions and the inserted intermediate states:
2300**
2301** UNLOCKED -> SHARED
2302** SHARED -> RESERVED
2303** SHARED -> (PENDING) -> EXCLUSIVE
2304** RESERVED -> (PENDING) -> EXCLUSIVE
2305** PENDING -> EXCLUSIVE
2306**
2307** flock() only really support EXCLUSIVE locks. We track intermediate
2308** lock states in the sqlite3_file structure, but all locks SHARED or
2309** above are really EXCLUSIVE locks and exclude all other processes from
2310** access the file.
2311**
2312** This routine will only increase a lock. Use the sqlite3OsUnlock()
2313** routine to lower a locking level.
2314*/
drh308c2a52010-05-14 11:30:18 +00002315static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002316 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002317 unixFile *pFile = (unixFile*)id;
2318
2319 assert( pFile );
2320
2321 /* if we already have a lock, it is exclusive.
2322 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002323 if (pFile->eFileLock > NO_LOCK) {
2324 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002325 return SQLITE_OK;
2326 }
2327
2328 /* grab an exclusive lock */
2329
drhff812312011-02-23 13:33:46 +00002330 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002331 int tErrno = errno;
2332 /* didn't get, must be busy */
2333 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2334 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002335 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002336 }
2337 } else {
2338 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002339 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002340 }
drh308c2a52010-05-14 11:30:18 +00002341 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2342 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002343#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2344 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2345 rc = SQLITE_BUSY;
2346 }
2347#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2348 return rc;
2349}
2350
drh6b9d6dd2008-12-03 19:34:47 +00002351
2352/*
drh308c2a52010-05-14 11:30:18 +00002353** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002354** must be either NO_LOCK or SHARED_LOCK.
2355**
2356** If the locking level of the file descriptor is already at or below
2357** the requested locking level, this routine is a no-op.
2358*/
drh308c2a52010-05-14 11:30:18 +00002359static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002360 unixFile *pFile = (unixFile*)id;
2361
2362 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002363 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002364 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002365 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002366
2367 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002368 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002369 return SQLITE_OK;
2370 }
2371
2372 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002373 if (eFileLock==SHARED_LOCK) {
2374 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002375 return SQLITE_OK;
2376 }
2377
2378 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002379 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002380#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002381 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002382#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002383 return SQLITE_IOERR_UNLOCK;
2384 }else{
drh308c2a52010-05-14 11:30:18 +00002385 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002386 return SQLITE_OK;
2387 }
2388}
2389
2390/*
2391** Close a file.
2392*/
2393static int flockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002394 assert( id!=0 );
2395 flockUnlock(id, NO_LOCK);
2396 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002397}
2398
2399#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2400
2401/******************* End of the flock lock implementation *********************
2402******************************************************************************/
2403
2404/******************************************************************************
2405************************ Begin Named Semaphore Locking ************************
2406**
2407** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002408**
2409** Semaphore locking is like dot-lock and flock in that it really only
2410** supports EXCLUSIVE locking. Only a single process can read or write
2411** the database file at a time. This reduces potential concurrency, but
2412** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002413*/
2414#if OS_VXWORKS
2415
drh6b9d6dd2008-12-03 19:34:47 +00002416/*
2417** This routine checks if there is a RESERVED lock held on the specified
2418** file by this or any other process. If such a lock is held, set *pResOut
2419** to a non-zero value otherwise *pResOut is set to zero. The return value
2420** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2421*/
drh8cd5b252015-03-02 22:06:43 +00002422static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
drh734c9862008-11-28 15:37:20 +00002423 int rc = SQLITE_OK;
2424 int reserved = 0;
2425 unixFile *pFile = (unixFile*)id;
2426
2427 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2428
2429 assert( pFile );
2430
2431 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002432 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002433 reserved = 1;
2434 }
2435
2436 /* Otherwise see if some other process holds it. */
2437 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002438 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002439
2440 if( sem_trywait(pSem)==-1 ){
2441 int tErrno = errno;
2442 if( EAGAIN != tErrno ){
2443 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
drh4bf66fd2015-02-19 02:43:02 +00002444 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002445 } else {
2446 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002447 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002448 }
2449 }else{
2450 /* we could have it if we want it */
2451 sem_post(pSem);
2452 }
2453 }
drh308c2a52010-05-14 11:30:18 +00002454 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002455
2456 *pResOut = reserved;
2457 return rc;
2458}
2459
drh6b9d6dd2008-12-03 19:34:47 +00002460/*
drh308c2a52010-05-14 11:30:18 +00002461** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002462** of the following:
2463**
2464** (1) SHARED_LOCK
2465** (2) RESERVED_LOCK
2466** (3) PENDING_LOCK
2467** (4) EXCLUSIVE_LOCK
2468**
2469** Sometimes when requesting one lock state, additional lock states
2470** are inserted in between. The locking might fail on one of the later
2471** transitions leaving the lock state different from what it started but
2472** still short of its goal. The following chart shows the allowed
2473** transitions and the inserted intermediate states:
2474**
2475** UNLOCKED -> SHARED
2476** SHARED -> RESERVED
2477** SHARED -> (PENDING) -> EXCLUSIVE
2478** RESERVED -> (PENDING) -> EXCLUSIVE
2479** PENDING -> EXCLUSIVE
2480**
2481** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2482** lock states in the sqlite3_file structure, but all locks SHARED or
2483** above are really EXCLUSIVE locks and exclude all other processes from
2484** access the file.
2485**
2486** This routine will only increase a lock. Use the sqlite3OsUnlock()
2487** routine to lower a locking level.
2488*/
drh8cd5b252015-03-02 22:06:43 +00002489static int semXLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002490 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002491 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002492 int rc = SQLITE_OK;
2493
2494 /* if we already have a lock, it is exclusive.
2495 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002496 if (pFile->eFileLock > NO_LOCK) {
2497 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002498 rc = SQLITE_OK;
2499 goto sem_end_lock;
2500 }
2501
2502 /* lock semaphore now but bail out when already locked. */
2503 if( sem_trywait(pSem)==-1 ){
2504 rc = SQLITE_BUSY;
2505 goto sem_end_lock;
2506 }
2507
2508 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002509 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002510
2511 sem_end_lock:
2512 return rc;
2513}
2514
drh6b9d6dd2008-12-03 19:34:47 +00002515/*
drh308c2a52010-05-14 11:30:18 +00002516** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002517** must be either NO_LOCK or SHARED_LOCK.
2518**
2519** If the locking level of the file descriptor is already at or below
2520** the requested locking level, this routine is a no-op.
2521*/
drh8cd5b252015-03-02 22:06:43 +00002522static int semXUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002523 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002524 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002525
2526 assert( pFile );
2527 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002528 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002529 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002530 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002531
2532 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002533 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002534 return SQLITE_OK;
2535 }
2536
2537 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002538 if (eFileLock==SHARED_LOCK) {
2539 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002540 return SQLITE_OK;
2541 }
2542
2543 /* no, really unlock. */
2544 if ( sem_post(pSem)==-1 ) {
2545 int rc, tErrno = errno;
2546 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2547 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002548 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002549 }
2550 return rc;
2551 }
drh308c2a52010-05-14 11:30:18 +00002552 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002553 return SQLITE_OK;
2554}
2555
2556/*
2557 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002558 */
drh8cd5b252015-03-02 22:06:43 +00002559static int semXClose(sqlite3_file *id) {
drh734c9862008-11-28 15:37:20 +00002560 if( id ){
2561 unixFile *pFile = (unixFile*)id;
drh8cd5b252015-03-02 22:06:43 +00002562 semXUnlock(id, NO_LOCK);
drh734c9862008-11-28 15:37:20 +00002563 assert( pFile );
2564 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002565 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002566 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002567 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002568 }
2569 return SQLITE_OK;
2570}
2571
2572#endif /* OS_VXWORKS */
2573/*
2574** Named semaphore locking is only available on VxWorks.
2575**
2576*************** End of the named semaphore lock implementation ****************
2577******************************************************************************/
2578
2579
2580/******************************************************************************
2581*************************** Begin AFP Locking *********************************
2582**
2583** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2584** on Apple Macintosh computers - both OS9 and OSX.
2585**
2586** Third-party implementations of AFP are available. But this code here
2587** only works on OSX.
2588*/
2589
drhd2cb50b2009-01-09 21:41:17 +00002590#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002591/*
2592** The afpLockingContext structure contains all afp lock specific state
2593*/
drhbfe66312006-10-03 17:40:40 +00002594typedef struct afpLockingContext afpLockingContext;
2595struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002596 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002597 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002598};
2599
2600struct ByteRangeLockPB2
2601{
2602 unsigned long long offset; /* offset to first byte to lock */
2603 unsigned long long length; /* nbr of bytes to lock */
2604 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2605 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2606 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2607 int fd; /* file desc to assoc this lock with */
2608};
2609
drhfd131da2007-08-07 17:13:03 +00002610#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002611
drh6b9d6dd2008-12-03 19:34:47 +00002612/*
2613** This is a utility for setting or clearing a bit-range lock on an
2614** AFP filesystem.
2615**
2616** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2617*/
2618static int afpSetLock(
2619 const char *path, /* Name of the file to be locked or unlocked */
2620 unixFile *pFile, /* Open file descriptor on path */
2621 unsigned long long offset, /* First byte to be locked */
2622 unsigned long long length, /* Number of bytes to lock */
2623 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002624){
drh6b9d6dd2008-12-03 19:34:47 +00002625 struct ByteRangeLockPB2 pb;
2626 int err;
drhbfe66312006-10-03 17:40:40 +00002627
2628 pb.unLockFlag = setLockFlag ? 0 : 1;
2629 pb.startEndFlag = 0;
2630 pb.offset = offset;
2631 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002632 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002633
drh308c2a52010-05-14 11:30:18 +00002634 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002635 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002636 offset, length));
drhbfe66312006-10-03 17:40:40 +00002637 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2638 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002639 int rc;
2640 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002641 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2642 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002643#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2644 rc = SQLITE_BUSY;
2645#else
drh734c9862008-11-28 15:37:20 +00002646 rc = sqliteErrorFromPosixError(tErrno,
2647 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002648#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002649 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002650 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00002651 }
2652 return rc;
drhbfe66312006-10-03 17:40:40 +00002653 } else {
aswift5b1a2562008-08-22 00:22:35 +00002654 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002655 }
2656}
2657
drh6b9d6dd2008-12-03 19:34:47 +00002658/*
2659** This routine checks if there is a RESERVED lock held on the specified
2660** file by this or any other process. If such a lock is held, set *pResOut
2661** to a non-zero value otherwise *pResOut is set to zero. The return value
2662** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2663*/
danielk1977e339d652008-06-28 11:23:00 +00002664static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002665 int rc = SQLITE_OK;
2666 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002667 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002668 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002669
aswift5b1a2562008-08-22 00:22:35 +00002670 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2671
2672 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002673 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002674 if( context->reserved ){
2675 *pResOut = 1;
2676 return SQLITE_OK;
2677 }
drh8af6c222010-05-14 12:43:01 +00002678 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002679
2680 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002681 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002682 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002683 }
2684
2685 /* Otherwise see if some other process holds it.
2686 */
aswift5b1a2562008-08-22 00:22:35 +00002687 if( !reserved ){
2688 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002689 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002690 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002691 /* if we succeeded in taking the reserved lock, unlock it to restore
2692 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002693 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002694 } else {
2695 /* if we failed to get the lock then someone else must have it */
2696 reserved = 1;
2697 }
2698 if( IS_LOCK_ERROR(lrc) ){
2699 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002700 }
2701 }
drhbfe66312006-10-03 17:40:40 +00002702
drh7ed97b92010-01-20 13:07:21 +00002703 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002704 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002705
2706 *pResOut = reserved;
2707 return rc;
drhbfe66312006-10-03 17:40:40 +00002708}
2709
drh6b9d6dd2008-12-03 19:34:47 +00002710/*
drh308c2a52010-05-14 11:30:18 +00002711** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002712** of the following:
2713**
2714** (1) SHARED_LOCK
2715** (2) RESERVED_LOCK
2716** (3) PENDING_LOCK
2717** (4) EXCLUSIVE_LOCK
2718**
2719** Sometimes when requesting one lock state, additional lock states
2720** are inserted in between. The locking might fail on one of the later
2721** transitions leaving the lock state different from what it started but
2722** still short of its goal. The following chart shows the allowed
2723** transitions and the inserted intermediate states:
2724**
2725** UNLOCKED -> SHARED
2726** SHARED -> RESERVED
2727** SHARED -> (PENDING) -> EXCLUSIVE
2728** RESERVED -> (PENDING) -> EXCLUSIVE
2729** PENDING -> EXCLUSIVE
2730**
2731** This routine will only increase a lock. Use the sqlite3OsUnlock()
2732** routine to lower a locking level.
2733*/
drh308c2a52010-05-14 11:30:18 +00002734static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002735 int rc = SQLITE_OK;
2736 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002737 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002738 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002739
2740 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002741 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2742 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh5ac93652015-03-21 20:59:43 +00002743 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
drh339eb0b2008-03-07 15:34:11 +00002744
drhbfe66312006-10-03 17:40:40 +00002745 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002746 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002747 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002748 */
drh308c2a52010-05-14 11:30:18 +00002749 if( pFile->eFileLock>=eFileLock ){
2750 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2751 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002752 return SQLITE_OK;
2753 }
2754
2755 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002756 ** (1) We never move from unlocked to anything higher than shared lock.
2757 ** (2) SQLite never explicitly requests a pendig lock.
2758 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002759 */
drh308c2a52010-05-14 11:30:18 +00002760 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2761 assert( eFileLock!=PENDING_LOCK );
2762 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002763
drh8af6c222010-05-14 12:43:01 +00002764 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002765 */
drh6c7d5c52008-11-21 20:32:33 +00002766 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002767 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002768
2769 /* If some thread using this PID has a lock via a different unixFile*
2770 ** handle that precludes the requested lock, return BUSY.
2771 */
drh8af6c222010-05-14 12:43:01 +00002772 if( (pFile->eFileLock!=pInode->eFileLock &&
2773 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002774 ){
2775 rc = SQLITE_BUSY;
2776 goto afp_end_lock;
2777 }
2778
2779 /* If a SHARED lock is requested, and some thread using this PID already
2780 ** has a SHARED or RESERVED lock, then increment reference counts and
2781 ** return SQLITE_OK.
2782 */
drh308c2a52010-05-14 11:30:18 +00002783 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002784 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002785 assert( eFileLock==SHARED_LOCK );
2786 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002787 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002788 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002789 pInode->nShared++;
2790 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002791 goto afp_end_lock;
2792 }
drhbfe66312006-10-03 17:40:40 +00002793
2794 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002795 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2796 ** be released.
2797 */
drh308c2a52010-05-14 11:30:18 +00002798 if( eFileLock==SHARED_LOCK
2799 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002800 ){
2801 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002802 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002803 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002804 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002805 goto afp_end_lock;
2806 }
2807 }
2808
2809 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002810 ** operating system calls for the specified lock.
2811 */
drh308c2a52010-05-14 11:30:18 +00002812 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002813 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002814 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002815
drh8af6c222010-05-14 12:43:01 +00002816 assert( pInode->nShared==0 );
2817 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002818
2819 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002820 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002821 /* note that the quality of the randomness doesn't matter that much */
2822 lk = random();
drh8af6c222010-05-14 12:43:01 +00002823 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002824 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002825 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002826 if( IS_LOCK_ERROR(lrc1) ){
2827 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002828 }
aswift5b1a2562008-08-22 00:22:35 +00002829 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002830 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002831
aswift5b1a2562008-08-22 00:22:35 +00002832 if( IS_LOCK_ERROR(lrc1) ) {
drh4bf66fd2015-02-19 02:43:02 +00002833 storeLastErrno(pFile, lrc1Errno);
aswift5b1a2562008-08-22 00:22:35 +00002834 rc = lrc1;
2835 goto afp_end_lock;
2836 } else if( IS_LOCK_ERROR(lrc2) ){
2837 rc = lrc2;
2838 goto afp_end_lock;
2839 } else if( lrc1 != SQLITE_OK ) {
2840 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002841 } else {
drh308c2a52010-05-14 11:30:18 +00002842 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002843 pInode->nLock++;
2844 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002845 }
drh8af6c222010-05-14 12:43:01 +00002846 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002847 /* We are trying for an exclusive lock but another thread in this
2848 ** same process is still holding a shared lock. */
2849 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002850 }else{
2851 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2852 ** assumed that there is a SHARED or greater lock on the file
2853 ** already.
2854 */
2855 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002856 assert( 0!=pFile->eFileLock );
2857 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002858 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002859 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002860 if( !failed ){
2861 context->reserved = 1;
2862 }
drhbfe66312006-10-03 17:40:40 +00002863 }
drh308c2a52010-05-14 11:30:18 +00002864 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002865 /* Acquire an EXCLUSIVE lock */
2866
2867 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002868 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002869 */
drh6b9d6dd2008-12-03 19:34:47 +00002870 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002871 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002872 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002873 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002874 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002875 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002876 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002877 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002878 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2879 ** a critical I/O error
2880 */
2881 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2882 SQLITE_IOERR_LOCK;
2883 goto afp_end_lock;
2884 }
2885 }else{
aswift5b1a2562008-08-22 00:22:35 +00002886 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002887 }
2888 }
aswift5b1a2562008-08-22 00:22:35 +00002889 if( failed ){
2890 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002891 }
2892 }
2893
2894 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002895 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002896 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002897 }else if( eFileLock==EXCLUSIVE_LOCK ){
2898 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002899 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002900 }
2901
2902afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002903 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002904 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2905 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002906 return rc;
2907}
2908
2909/*
drh308c2a52010-05-14 11:30:18 +00002910** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002911** must be either NO_LOCK or SHARED_LOCK.
2912**
2913** If the locking level of the file descriptor is already at or below
2914** the requested locking level, this routine is a no-op.
2915*/
drh308c2a52010-05-14 11:30:18 +00002916static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002917 int rc = SQLITE_OK;
2918 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002919 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002920 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2921 int skipShared = 0;
2922#ifdef SQLITE_TEST
2923 int h = pFile->h;
2924#endif
drhbfe66312006-10-03 17:40:40 +00002925
2926 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002927 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002928 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00002929 osGetpid(0)));
aswift5b1a2562008-08-22 00:22:35 +00002930
drh308c2a52010-05-14 11:30:18 +00002931 assert( eFileLock<=SHARED_LOCK );
2932 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002933 return SQLITE_OK;
2934 }
drh6c7d5c52008-11-21 20:32:33 +00002935 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002936 pInode = pFile->pInode;
2937 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002938 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002939 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002940 SimulateIOErrorBenign(1);
2941 SimulateIOError( h=(-1) )
2942 SimulateIOErrorBenign(0);
2943
drhd3d8c042012-05-29 17:02:40 +00002944#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002945 /* When reducing a lock such that other processes can start
2946 ** reading the database file again, make sure that the
2947 ** transaction counter was updated if any part of the database
2948 ** file changed. If the transaction counter is not updated,
2949 ** other connections to the same file might not realize that
2950 ** the file has changed and hence might not know to flush their
2951 ** cache. The use of a stale cache can lead to database corruption.
2952 */
2953 assert( pFile->inNormalWrite==0
2954 || pFile->dbUpdate==0
2955 || pFile->transCntrChng==1 );
2956 pFile->inNormalWrite = 0;
2957#endif
aswiftaebf4132008-11-21 00:10:35 +00002958
drh308c2a52010-05-14 11:30:18 +00002959 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002960 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002961 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002962 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002963 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002964 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2965 } else {
2966 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002967 }
2968 }
drh308c2a52010-05-14 11:30:18 +00002969 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002970 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002971 }
drh308c2a52010-05-14 11:30:18 +00002972 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002973 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2974 if( !rc ){
2975 context->reserved = 0;
2976 }
aswiftaebf4132008-11-21 00:10:35 +00002977 }
drh8af6c222010-05-14 12:43:01 +00002978 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2979 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002980 }
aswiftaebf4132008-11-21 00:10:35 +00002981 }
drh308c2a52010-05-14 11:30:18 +00002982 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002983
drh7ed97b92010-01-20 13:07:21 +00002984 /* Decrement the shared lock counter. Release the lock using an
2985 ** OS call only when all threads in this same process have released
2986 ** the lock.
2987 */
drh8af6c222010-05-14 12:43:01 +00002988 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2989 pInode->nShared--;
2990 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002991 SimulateIOErrorBenign(1);
2992 SimulateIOError( h=(-1) )
2993 SimulateIOErrorBenign(0);
2994 if( !skipShared ){
2995 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2996 }
2997 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002998 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002999 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003000 }
3001 }
3002 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00003003 pInode->nLock--;
3004 assert( pInode->nLock>=0 );
3005 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00003006 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00003007 }
3008 }
drhbfe66312006-10-03 17:40:40 +00003009 }
drh7ed97b92010-01-20 13:07:21 +00003010
drh6c7d5c52008-11-21 20:32:33 +00003011 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00003012 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00003013 return rc;
3014}
3015
3016/*
drh339eb0b2008-03-07 15:34:11 +00003017** Close a file & cleanup AFP specific locking context
3018*/
danielk1977e339d652008-06-28 11:23:00 +00003019static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003020 int rc = SQLITE_OK;
drha8de1e12015-11-30 00:05:39 +00003021 unixFile *pFile = (unixFile*)id;
3022 assert( id!=0 );
3023 afpUnlock(id, NO_LOCK);
3024 unixEnterMutex();
3025 if( pFile->pInode && pFile->pInode->nLock ){
3026 /* If there are outstanding locks, do not actually close the file just
3027 ** yet because that would clear those locks. Instead, add the file
3028 ** descriptor to pInode->aPending. It will be automatically closed when
3029 ** the last lock is cleared.
3030 */
3031 setPendingFd(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003032 }
drha8de1e12015-11-30 00:05:39 +00003033 releaseInodeInfo(pFile);
3034 sqlite3_free(pFile->lockingContext);
3035 rc = closeUnixFile(id);
3036 unixLeaveMutex();
drh7ed97b92010-01-20 13:07:21 +00003037 return rc;
drhbfe66312006-10-03 17:40:40 +00003038}
3039
drhd2cb50b2009-01-09 21:41:17 +00003040#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003041/*
3042** The code above is the AFP lock implementation. The code is specific
3043** to MacOSX and does not work on other unix platforms. No alternative
3044** is available. If you don't compile for a mac, then the "unix-afp"
3045** VFS is not available.
3046**
3047********************* End of the AFP lock implementation **********************
3048******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003049
drh7ed97b92010-01-20 13:07:21 +00003050/******************************************************************************
3051*************************** Begin NFS Locking ********************************/
3052
3053#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3054/*
drh308c2a52010-05-14 11:30:18 +00003055 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003056 ** must be either NO_LOCK or SHARED_LOCK.
3057 **
3058 ** If the locking level of the file descriptor is already at or below
3059 ** the requested locking level, this routine is a no-op.
3060 */
drh308c2a52010-05-14 11:30:18 +00003061static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003062 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003063}
3064
3065#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3066/*
3067** The code above is the NFS lock implementation. The code is specific
3068** to MacOSX and does not work on other unix platforms. No alternative
3069** is available.
3070**
3071********************* End of the NFS lock implementation **********************
3072******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003073
3074/******************************************************************************
3075**************** Non-locking sqlite3_file methods *****************************
3076**
3077** The next division contains implementations for all methods of the
3078** sqlite3_file object other than the locking methods. The locking
3079** methods were defined in divisions above (one locking method per
3080** division). Those methods that are common to all locking modes
3081** are gather together into this division.
3082*/
drhbfe66312006-10-03 17:40:40 +00003083
3084/*
drh734c9862008-11-28 15:37:20 +00003085** Seek to the offset passed as the second argument, then read cnt
3086** bytes into pBuf. Return the number of bytes actually read.
3087**
3088** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3089** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3090** one system to another. Since SQLite does not define USE_PREAD
peter.d.reid60ec9142014-09-06 16:39:46 +00003091** in any form by default, we will not attempt to define _XOPEN_SOURCE.
drh734c9862008-11-28 15:37:20 +00003092** See tickets #2741 and #2681.
3093**
3094** To avoid stomping the errno value on a failed read the lastErrno value
3095** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003096*/
drh734c9862008-11-28 15:37:20 +00003097static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3098 int got;
drh58024642011-11-07 18:16:00 +00003099 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003100#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003101 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003102#endif
drh734c9862008-11-28 15:37:20 +00003103 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003104 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003105 assert( id->h>2 );
drh58024642011-11-07 18:16:00 +00003106 do{
drh734c9862008-11-28 15:37:20 +00003107#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003108 got = osPread(id->h, pBuf, cnt, offset);
3109 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003110#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003111 got = osPread64(id->h, pBuf, cnt, offset);
3112 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003113#else
drh58024642011-11-07 18:16:00 +00003114 newOffset = lseek(id->h, offset, SEEK_SET);
drhe1818ec2015-12-01 16:21:35 +00003115 SimulateIOError( newOffset = -1 );
3116 if( newOffset<0 ){
3117 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003118 return -1;
drh734c9862008-11-28 15:37:20 +00003119 }
drh58024642011-11-07 18:16:00 +00003120 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003121#endif
drh58024642011-11-07 18:16:00 +00003122 if( got==cnt ) break;
3123 if( got<0 ){
3124 if( errno==EINTR ){ got = 1; continue; }
3125 prior = 0;
drh4bf66fd2015-02-19 02:43:02 +00003126 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003127 break;
3128 }else if( got>0 ){
3129 cnt -= got;
3130 offset += got;
3131 prior += got;
3132 pBuf = (void*)(got + (char*)pBuf);
3133 }
3134 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003135 TIMER_END;
drh58024642011-11-07 18:16:00 +00003136 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3137 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3138 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003139}
3140
3141/*
drh734c9862008-11-28 15:37:20 +00003142** Read data from a file into a buffer. Return SQLITE_OK if all
3143** bytes were read successfully and SQLITE_IOERR if anything goes
3144** wrong.
drh339eb0b2008-03-07 15:34:11 +00003145*/
drh734c9862008-11-28 15:37:20 +00003146static int unixRead(
3147 sqlite3_file *id,
3148 void *pBuf,
3149 int amt,
3150 sqlite3_int64 offset
3151){
dan08da86a2009-08-21 17:18:03 +00003152 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003153 int got;
3154 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003155 assert( offset>=0 );
3156 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003157
dan08da86a2009-08-21 17:18:03 +00003158 /* If this is a database file (not a journal, master-journal or temp
3159 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003160#if 0
dane946c392009-08-22 11:39:46 +00003161 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003162 || offset>=PENDING_BYTE+512
3163 || offset+amt<=PENDING_BYTE
3164 );
dan7c246102010-04-12 19:00:29 +00003165#endif
drh08c6d442009-02-09 17:34:07 +00003166
drh9b4c59f2013-04-15 17:03:42 +00003167#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003168 /* Deal with as much of this read request as possible by transfering
3169 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003170 if( offset<pFile->mmapSize ){
3171 if( offset+amt <= pFile->mmapSize ){
3172 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3173 return SQLITE_OK;
3174 }else{
3175 int nCopy = pFile->mmapSize - offset;
3176 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3177 pBuf = &((u8 *)pBuf)[nCopy];
3178 amt -= nCopy;
3179 offset += nCopy;
3180 }
3181 }
drh6e0b6d52013-04-09 16:19:20 +00003182#endif
danf23da962013-03-23 21:00:41 +00003183
dan08da86a2009-08-21 17:18:03 +00003184 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003185 if( got==amt ){
3186 return SQLITE_OK;
3187 }else if( got<0 ){
3188 /* lastErrno set by seekAndRead */
3189 return SQLITE_IOERR_READ;
3190 }else{
drh4bf66fd2015-02-19 02:43:02 +00003191 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003192 /* Unread parts of the buffer must be zero-filled */
3193 memset(&((char*)pBuf)[got], 0, amt-got);
3194 return SQLITE_IOERR_SHORT_READ;
3195 }
3196}
3197
3198/*
dan47a2b4a2013-04-26 16:09:29 +00003199** Attempt to seek the file-descriptor passed as the first argument to
3200** absolute offset iOff, then attempt to write nBuf bytes of data from
3201** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3202** return the actual number of bytes written (which may be less than
3203** nBuf).
3204*/
3205static int seekAndWriteFd(
3206 int fd, /* File descriptor to write to */
3207 i64 iOff, /* File offset to begin writing at */
3208 const void *pBuf, /* Copy data from this buffer to the file */
3209 int nBuf, /* Size of buffer pBuf in bytes */
3210 int *piErrno /* OUT: Error number if error occurs */
3211){
3212 int rc = 0; /* Value returned by system call */
3213
3214 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003215 assert( fd>2 );
drhe1818ec2015-12-01 16:21:35 +00003216 assert( piErrno!=0 );
dan47a2b4a2013-04-26 16:09:29 +00003217 nBuf &= 0x1ffff;
3218 TIMER_START;
3219
3220#if defined(USE_PREAD)
drh2da47d32015-02-21 00:56:05 +00003221 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
dan47a2b4a2013-04-26 16:09:29 +00003222#elif defined(USE_PREAD64)
drh2da47d32015-02-21 00:56:05 +00003223 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
dan47a2b4a2013-04-26 16:09:29 +00003224#else
3225 do{
3226 i64 iSeek = lseek(fd, iOff, SEEK_SET);
drhe1818ec2015-12-01 16:21:35 +00003227 SimulateIOError( iSeek = -1 );
3228 if( iSeek<0 ){
3229 rc = -1;
3230 break;
dan47a2b4a2013-04-26 16:09:29 +00003231 }
3232 rc = osWrite(fd, pBuf, nBuf);
3233 }while( rc<0 && errno==EINTR );
3234#endif
3235
3236 TIMER_END;
3237 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3238
drhe1818ec2015-12-01 16:21:35 +00003239 if( rc<0 ) *piErrno = errno;
dan47a2b4a2013-04-26 16:09:29 +00003240 return rc;
3241}
3242
3243
3244/*
drh734c9862008-11-28 15:37:20 +00003245** Seek to the offset in id->offset then read cnt bytes into pBuf.
3246** Return the number of bytes actually read. Update the offset.
3247**
3248** To avoid stomping the errno value on a failed write the lastErrno value
3249** is set before returning.
3250*/
3251static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003252 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003253}
3254
3255
3256/*
3257** Write data from a buffer into a file. Return SQLITE_OK on success
3258** or some other error code on failure.
3259*/
3260static int unixWrite(
3261 sqlite3_file *id,
3262 const void *pBuf,
3263 int amt,
3264 sqlite3_int64 offset
3265){
dan08da86a2009-08-21 17:18:03 +00003266 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003267 int wrote = 0;
3268 assert( id );
3269 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003270
dan08da86a2009-08-21 17:18:03 +00003271 /* If this is a database file (not a journal, master-journal or temp
3272 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003273#if 0
dane946c392009-08-22 11:39:46 +00003274 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003275 || offset>=PENDING_BYTE+512
3276 || offset+amt<=PENDING_BYTE
3277 );
dan7c246102010-04-12 19:00:29 +00003278#endif
drh08c6d442009-02-09 17:34:07 +00003279
drhd3d8c042012-05-29 17:02:40 +00003280#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003281 /* If we are doing a normal write to a database file (as opposed to
3282 ** doing a hot-journal rollback or a write to some file other than a
3283 ** normal database file) then record the fact that the database
3284 ** has changed. If the transaction counter is modified, record that
3285 ** fact too.
3286 */
dan08da86a2009-08-21 17:18:03 +00003287 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003288 pFile->dbUpdate = 1; /* The database has been modified */
3289 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003290 int rc;
drh8f941bc2009-01-14 23:03:40 +00003291 char oldCntr[4];
3292 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003293 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003294 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003295 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003296 pFile->transCntrChng = 1; /* The transaction counter has changed */
3297 }
3298 }
3299 }
3300#endif
3301
danfe33e392015-11-17 20:56:06 +00003302#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003303 /* Deal with as much of this write request as possible by transfering
3304 ** data from the memory mapping using memcpy(). */
3305 if( offset<pFile->mmapSize ){
3306 if( offset+amt <= pFile->mmapSize ){
3307 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3308 return SQLITE_OK;
3309 }else{
3310 int nCopy = pFile->mmapSize - offset;
3311 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3312 pBuf = &((u8 *)pBuf)[nCopy];
3313 amt -= nCopy;
3314 offset += nCopy;
3315 }
3316 }
drh6e0b6d52013-04-09 16:19:20 +00003317#endif
drh02bf8b42015-09-01 23:51:53 +00003318
3319 while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
drh734c9862008-11-28 15:37:20 +00003320 amt -= wrote;
3321 offset += wrote;
3322 pBuf = &((char*)pBuf)[wrote];
3323 }
3324 SimulateIOError(( wrote=(-1), amt=1 ));
3325 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003326
drh02bf8b42015-09-01 23:51:53 +00003327 if( amt>wrote ){
drha21b83b2011-04-15 12:36:10 +00003328 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003329 /* lastErrno set by seekAndWrite */
3330 return SQLITE_IOERR_WRITE;
3331 }else{
drh4bf66fd2015-02-19 02:43:02 +00003332 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003333 return SQLITE_FULL;
3334 }
3335 }
dan6e09d692010-07-27 18:34:15 +00003336
drh734c9862008-11-28 15:37:20 +00003337 return SQLITE_OK;
3338}
3339
3340#ifdef SQLITE_TEST
3341/*
3342** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003343** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003344*/
3345int sqlite3_sync_count = 0;
3346int sqlite3_fullsync_count = 0;
3347#endif
3348
3349/*
drh89240432009-03-25 01:06:01 +00003350** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003351** Others do no. To be safe, we will stick with the (slightly slower)
3352** fsync(). If you know that your system does support fdatasync() correctly,
drhf7a4a1b2015-01-10 18:02:45 +00003353** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003354*/
drhf7a4a1b2015-01-10 18:02:45 +00003355#if !defined(fdatasync) && !HAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003356# define fdatasync fsync
3357#endif
3358
3359/*
3360** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3361** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3362** only available on Mac OS X. But that could change.
3363*/
3364#ifdef F_FULLFSYNC
3365# define HAVE_FULLFSYNC 1
3366#else
3367# define HAVE_FULLFSYNC 0
3368#endif
3369
3370
3371/*
3372** The fsync() system call does not work as advertised on many
3373** unix systems. The following procedure is an attempt to make
3374** it work better.
3375**
3376** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3377** for testing when we want to run through the test suite quickly.
3378** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3379** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3380** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003381**
3382** SQLite sets the dataOnly flag if the size of the file is unchanged.
3383** The idea behind dataOnly is that it should only write the file content
3384** to disk, not the inode. We only set dataOnly if the file size is
3385** unchanged since the file size is part of the inode. However,
3386** Ted Ts'o tells us that fdatasync() will also write the inode if the
3387** file size has changed. The only real difference between fdatasync()
3388** and fsync(), Ted tells us, is that fdatasync() will not flush the
3389** inode if the mtime or owner or other inode attributes have changed.
3390** We only care about the file size, not the other file attributes, so
3391** as far as SQLite is concerned, an fdatasync() is always adequate.
3392** So, we always use fdatasync() if it is available, regardless of
3393** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003394*/
3395static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003396 int rc;
drh734c9862008-11-28 15:37:20 +00003397
3398 /* The following "ifdef/elif/else/" block has the same structure as
3399 ** the one below. It is replicated here solely to avoid cluttering
3400 ** up the real code with the UNUSED_PARAMETER() macros.
3401 */
3402#ifdef SQLITE_NO_SYNC
3403 UNUSED_PARAMETER(fd);
3404 UNUSED_PARAMETER(fullSync);
3405 UNUSED_PARAMETER(dataOnly);
3406#elif HAVE_FULLFSYNC
3407 UNUSED_PARAMETER(dataOnly);
3408#else
3409 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003410 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003411#endif
3412
3413 /* Record the number of times that we do a normal fsync() and
3414 ** FULLSYNC. This is used during testing to verify that this procedure
3415 ** gets called with the correct arguments.
3416 */
3417#ifdef SQLITE_TEST
3418 if( fullSync ) sqlite3_fullsync_count++;
3419 sqlite3_sync_count++;
3420#endif
3421
3422 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
drh2c8fd122015-12-02 02:33:36 +00003423 ** no-op. But go ahead and call fstat() to validate the file
3424 ** descriptor as we need a method to provoke a failure during
3425 ** coverate testing.
drh734c9862008-11-28 15:37:20 +00003426 */
3427#ifdef SQLITE_NO_SYNC
drh2c8fd122015-12-02 02:33:36 +00003428 {
3429 struct stat buf;
3430 rc = osFstat(fd, &buf);
3431 }
drh734c9862008-11-28 15:37:20 +00003432#elif HAVE_FULLFSYNC
3433 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003434 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003435 }else{
3436 rc = 1;
3437 }
3438 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003439 ** It shouldn't be possible for fullfsync to fail on the local
3440 ** file system (on OSX), so failure indicates that FULLFSYNC
3441 ** isn't supported for this file system. So, attempt an fsync
3442 ** and (for now) ignore the overhead of a superfluous fcntl call.
3443 ** It'd be better to detect fullfsync support once and avoid
3444 ** the fcntl call every time sync is called.
3445 */
drh734c9862008-11-28 15:37:20 +00003446 if( rc ) rc = fsync(fd);
3447
drh7ed97b92010-01-20 13:07:21 +00003448#elif defined(__APPLE__)
3449 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3450 ** so currently we default to the macro that redefines fdatasync to fsync
3451 */
3452 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003453#else
drh0b647ff2009-03-21 14:41:04 +00003454 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003455#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003456 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003457 rc = fsync(fd);
3458 }
drh0b647ff2009-03-21 14:41:04 +00003459#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003460#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3461
3462 if( OS_VXWORKS && rc!= -1 ){
3463 rc = 0;
3464 }
chw97185482008-11-17 08:05:31 +00003465 return rc;
drhbfe66312006-10-03 17:40:40 +00003466}
3467
drh734c9862008-11-28 15:37:20 +00003468/*
drh0059eae2011-08-08 23:48:40 +00003469** Open a file descriptor to the directory containing file zFilename.
3470** If successful, *pFd is set to the opened file descriptor and
3471** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3472** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3473** value.
3474**
drh90315a22011-08-10 01:52:12 +00003475** The directory file descriptor is used for only one thing - to
3476** fsync() a directory to make sure file creation and deletion events
3477** are flushed to disk. Such fsyncs are not needed on newer
3478** journaling filesystems, but are required on older filesystems.
3479**
3480** This routine can be overridden using the xSetSysCall interface.
3481** The ability to override this routine was added in support of the
3482** chromium sandbox. Opening a directory is a security risk (we are
3483** told) so making it overrideable allows the chromium sandbox to
3484** replace this routine with a harmless no-op. To make this routine
3485** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3486** *pFd set to a negative number.
3487**
drh0059eae2011-08-08 23:48:40 +00003488** If SQLITE_OK is returned, the caller is responsible for closing
3489** the file descriptor *pFd using close().
3490*/
3491static int openDirectory(const char *zFilename, int *pFd){
3492 int ii;
3493 int fd = -1;
3494 char zDirname[MAX_PATHNAME+1];
3495
3496 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drhdc278512015-12-07 18:18:33 +00003497 for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
3498 if( ii>0 ){
drh0059eae2011-08-08 23:48:40 +00003499 zDirname[ii] = '\0';
drhdc278512015-12-07 18:18:33 +00003500 }else{
3501 if( zDirname[0]!='/' ) zDirname[0] = '.';
3502 zDirname[1] = 0;
3503 }
3504 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3505 if( fd>=0 ){
3506 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
drh0059eae2011-08-08 23:48:40 +00003507 }
3508 *pFd = fd;
drhacb6b282015-11-26 10:37:05 +00003509 if( fd>=0 ) return SQLITE_OK;
3510 return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
drh0059eae2011-08-08 23:48:40 +00003511}
3512
3513/*
drh734c9862008-11-28 15:37:20 +00003514** Make sure all writes to a particular file are committed to disk.
3515**
3516** If dataOnly==0 then both the file itself and its metadata (file
3517** size, access time, etc) are synced. If dataOnly!=0 then only the
3518** file data is synced.
3519**
3520** Under Unix, also make sure that the directory entry for the file
3521** has been created by fsync-ing the directory that contains the file.
3522** If we do not do this and we encounter a power failure, the directory
3523** entry for the journal might not exist after we reboot. The next
3524** SQLite to access the file will not know that the journal exists (because
3525** the directory entry for the journal was never created) and the transaction
3526** will not roll back - possibly leading to database corruption.
3527*/
3528static int unixSync(sqlite3_file *id, int flags){
3529 int rc;
3530 unixFile *pFile = (unixFile*)id;
3531
3532 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3533 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3534
3535 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3536 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3537 || (flags&0x0F)==SQLITE_SYNC_FULL
3538 );
3539
3540 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3541 ** line is to test that doing so does not cause any problems.
3542 */
3543 SimulateDiskfullError( return SQLITE_FULL );
3544
3545 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003546 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003547 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3548 SimulateIOError( rc=1 );
3549 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003550 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003551 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003552 }
drh0059eae2011-08-08 23:48:40 +00003553
3554 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003555 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003556 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003557 */
3558 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3559 int dirfd;
3560 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003561 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003562 rc = osOpenDirectory(pFile->zPath, &dirfd);
drhacb6b282015-11-26 10:37:05 +00003563 if( rc==SQLITE_OK ){
drh0059eae2011-08-08 23:48:40 +00003564 full_fsync(dirfd, 0, 0);
3565 robust_close(pFile, dirfd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00003566 }else{
3567 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00003568 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003569 }
drh0059eae2011-08-08 23:48:40 +00003570 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003571 }
3572 return rc;
3573}
3574
3575/*
3576** Truncate an open file to a specified size
3577*/
3578static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003579 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003580 int rc;
dan6e09d692010-07-27 18:34:15 +00003581 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003582 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003583
3584 /* If the user has configured a chunk-size for this file, truncate the
3585 ** file so that it consists of an integer number of chunks (i.e. the
3586 ** actual file size after the operation may be larger than the requested
3587 ** size).
3588 */
drhb8af4b72012-04-05 20:04:39 +00003589 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003590 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3591 }
3592
dan2ee53412014-09-06 16:49:40 +00003593 rc = robust_ftruncate(pFile->h, nByte);
drh734c9862008-11-28 15:37:20 +00003594 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003595 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003596 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003597 }else{
drhd3d8c042012-05-29 17:02:40 +00003598#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003599 /* If we are doing a normal write to a database file (as opposed to
3600 ** doing a hot-journal rollback or a write to some file other than a
3601 ** normal database file) and we truncate the file to zero length,
3602 ** that effectively updates the change counter. This might happen
3603 ** when restoring a database using the backup API from a zero-length
3604 ** source.
3605 */
dan6e09d692010-07-27 18:34:15 +00003606 if( pFile->inNormalWrite && nByte==0 ){
3607 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003608 }
danf23da962013-03-23 21:00:41 +00003609#endif
danc0003312013-03-22 17:46:11 +00003610
mistachkine98844f2013-08-24 00:59:24 +00003611#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003612 /* If the file was just truncated to a size smaller than the currently
3613 ** mapped region, reduce the effective mapping size as well. SQLite will
3614 ** use read() and write() to access data beyond this point from now on.
3615 */
3616 if( nByte<pFile->mmapSize ){
3617 pFile->mmapSize = nByte;
3618 }
mistachkine98844f2013-08-24 00:59:24 +00003619#endif
drh3313b142009-11-06 04:13:18 +00003620
drh734c9862008-11-28 15:37:20 +00003621 return SQLITE_OK;
3622 }
3623}
3624
3625/*
3626** Determine the current size of a file in bytes
3627*/
3628static int unixFileSize(sqlite3_file *id, i64 *pSize){
3629 int rc;
3630 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003631 assert( id );
3632 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003633 SimulateIOError( rc=1 );
3634 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00003635 storeLastErrno((unixFile*)id, errno);
drh734c9862008-11-28 15:37:20 +00003636 return SQLITE_IOERR_FSTAT;
3637 }
3638 *pSize = buf.st_size;
3639
drh8af6c222010-05-14 12:43:01 +00003640 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003641 ** writes a single byte into that file in order to work around a bug
3642 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3643 ** layers, we need to report this file size as zero even though it is
3644 ** really 1. Ticket #3260.
3645 */
3646 if( *pSize==1 ) *pSize = 0;
3647
3648
3649 return SQLITE_OK;
3650}
3651
drhd2cb50b2009-01-09 21:41:17 +00003652#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003653/*
3654** Handler for proxy-locking file-control verbs. Defined below in the
3655** proxying locking division.
3656*/
3657static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003658#endif
drh715ff302008-12-03 22:32:44 +00003659
dan502019c2010-07-28 14:26:17 +00003660/*
3661** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003662** file-control operation. Enlarge the database to nBytes in size
3663** (rounded up to the next chunk-size). If the database is already
3664** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003665*/
3666static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003667 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003668 i64 nSize; /* Required file size */
3669 struct stat buf; /* Used to hold return values of fstat() */
3670
drh4bf66fd2015-02-19 02:43:02 +00003671 if( osFstat(pFile->h, &buf) ){
3672 return SQLITE_IOERR_FSTAT;
3673 }
dan502019c2010-07-28 14:26:17 +00003674
3675 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3676 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003677
dan502019c2010-07-28 14:26:17 +00003678#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003679 /* The code below is handling the return value of osFallocate()
3680 ** correctly. posix_fallocate() is defined to "returns zero on success,
3681 ** or an error number on failure". See the manpage for details. */
3682 int err;
drhff812312011-02-23 13:33:46 +00003683 do{
dan661d71a2011-03-30 19:08:03 +00003684 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3685 }while( err==EINTR );
3686 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003687#else
dan592bf7f2014-12-30 19:58:31 +00003688 /* If the OS does not have posix_fallocate(), fake it. Write a
3689 ** single byte to the last byte in each block that falls entirely
3690 ** within the extended region. Then, if required, a single byte
3691 ** at offset (nSize-1), to set the size of the file correctly.
3692 ** This is a similar technique to that used by glibc on systems
3693 ** that do not have a real fallocate() call.
dan502019c2010-07-28 14:26:17 +00003694 */
3695 int nBlk = buf.st_blksize; /* File-system block size */
danef3d66c2015-01-06 21:31:47 +00003696 int nWrite = 0; /* Number of bytes written by seekAndWrite */
dan502019c2010-07-28 14:26:17 +00003697 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003698
drh053378d2015-12-01 22:09:42 +00003699 iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
dan592bf7f2014-12-30 19:58:31 +00003700 assert( iWrite>=buf.st_size );
dan592bf7f2014-12-30 19:58:31 +00003701 assert( ((iWrite+1)%nBlk)==0 );
drh053378d2015-12-01 22:09:42 +00003702 for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
3703 if( iWrite>=nSize ) iWrite = nSize - 1;
danef3d66c2015-01-06 21:31:47 +00003704 nWrite = seekAndWrite(pFile, iWrite, "", 1);
dandc5df0f2011-04-06 19:15:45 +00003705 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dandc5df0f2011-04-06 19:15:45 +00003706 }
dan502019c2010-07-28 14:26:17 +00003707#endif
3708 }
3709 }
3710
mistachkine98844f2013-08-24 00:59:24 +00003711#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003712 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003713 int rc;
3714 if( pFile->szChunk<=0 ){
3715 if( robust_ftruncate(pFile->h, nByte) ){
drh4bf66fd2015-02-19 02:43:02 +00003716 storeLastErrno(pFile, errno);
danf23da962013-03-23 21:00:41 +00003717 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3718 }
3719 }
3720
3721 rc = unixMapfile(pFile, nByte);
3722 return rc;
3723 }
mistachkine98844f2013-08-24 00:59:24 +00003724#endif
danf23da962013-03-23 21:00:41 +00003725
dan502019c2010-07-28 14:26:17 +00003726 return SQLITE_OK;
3727}
danielk1977ad94b582007-08-20 06:44:22 +00003728
danielk1977e3026632004-06-22 11:29:02 +00003729/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003730** If *pArg is initially negative then this is a query. Set *pArg to
drhf12b3f62011-12-21 14:42:29 +00003731** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3732**
3733** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3734*/
3735static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3736 if( *pArg<0 ){
3737 *pArg = (pFile->ctrlFlags & mask)!=0;
3738 }else if( (*pArg)==0 ){
3739 pFile->ctrlFlags &= ~mask;
3740 }else{
3741 pFile->ctrlFlags |= mask;
3742 }
3743}
3744
drh696b33e2012-12-06 19:01:42 +00003745/* Forward declaration */
3746static int unixGetTempname(int nBuf, char *zBuf);
3747
drhf12b3f62011-12-21 14:42:29 +00003748/*
drh9e33c2c2007-08-31 18:34:59 +00003749** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003750*/
drhcc6bb3e2007-08-31 16:11:35 +00003751static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003752 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003753 switch( op ){
3754 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003755 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003756 return SQLITE_OK;
3757 }
drh4bf66fd2015-02-19 02:43:02 +00003758 case SQLITE_FCNTL_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003759 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003760 return SQLITE_OK;
3761 }
dan6e09d692010-07-27 18:34:15 +00003762 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003763 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003764 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003765 }
drh9ff27ec2010-05-19 19:26:05 +00003766 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003767 int rc;
3768 SimulateIOErrorBenign(1);
3769 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3770 SimulateIOErrorBenign(0);
3771 return rc;
drhf0b190d2011-07-26 16:03:07 +00003772 }
3773 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003774 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3775 return SQLITE_OK;
3776 }
drhcb15f352011-12-23 01:04:17 +00003777 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3778 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003779 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003780 }
drhde60fc22011-12-14 17:53:36 +00003781 case SQLITE_FCNTL_VFSNAME: {
3782 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3783 return SQLITE_OK;
3784 }
drh696b33e2012-12-06 19:01:42 +00003785 case SQLITE_FCNTL_TEMPFILENAME: {
drhf3cdcdc2015-04-29 16:50:28 +00003786 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
drh696b33e2012-12-06 19:01:42 +00003787 if( zTFile ){
3788 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3789 *(char**)pArg = zTFile;
3790 }
3791 return SQLITE_OK;
3792 }
drhb959a012013-12-07 12:29:22 +00003793 case SQLITE_FCNTL_HAS_MOVED: {
3794 *(int*)pArg = fileHasMoved(pFile);
3795 return SQLITE_OK;
3796 }
mistachkine98844f2013-08-24 00:59:24 +00003797#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003798 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003799 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003800 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003801 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3802 newLimit = sqlite3GlobalConfig.mxMmap;
3803 }
3804 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003805 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003806 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003807 if( pFile->mmapSize>0 ){
3808 unixUnmapfile(pFile);
3809 rc = unixMapfile(pFile, -1);
3810 }
danbcb8a862013-04-08 15:30:41 +00003811 }
drh34e258c2013-05-23 01:40:53 +00003812 return rc;
danb2d3de32013-03-14 18:34:37 +00003813 }
mistachkine98844f2013-08-24 00:59:24 +00003814#endif
drhd3d8c042012-05-29 17:02:40 +00003815#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003816 /* The pager calls this method to signal that it has done
3817 ** a rollback and that the database is therefore unchanged and
3818 ** it hence it is OK for the transaction change counter to be
3819 ** unchanged.
3820 */
3821 case SQLITE_FCNTL_DB_UNCHANGED: {
3822 ((unixFile*)id)->dbUpdate = 0;
3823 return SQLITE_OK;
3824 }
3825#endif
drhd2cb50b2009-01-09 21:41:17 +00003826#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh4bf66fd2015-02-19 02:43:02 +00003827 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
3828 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003829 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003830 }
drhd2cb50b2009-01-09 21:41:17 +00003831#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003832 }
drh0b52b7d2011-01-26 19:46:22 +00003833 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003834}
3835
3836/*
danielk1977a3d4c882007-03-23 10:08:38 +00003837** Return the sector size in bytes of the underlying block device for
3838** the specified file. This is almost always 512 bytes, but may be
3839** larger for some devices.
3840**
3841** SQLite code assumes this function cannot fail. It also assumes that
3842** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003843** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003844** same for both.
3845*/
drh537dddf2012-10-26 13:46:24 +00003846#ifndef __QNXNTO__
3847static int unixSectorSize(sqlite3_file *NotUsed){
3848 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003849 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003850}
drh537dddf2012-10-26 13:46:24 +00003851#endif
3852
3853/*
3854** The following version of unixSectorSize() is optimized for QNX.
3855*/
3856#ifdef __QNXNTO__
3857#include <sys/dcmd_blk.h>
3858#include <sys/statvfs.h>
3859static int unixSectorSize(sqlite3_file *id){
3860 unixFile *pFile = (unixFile*)id;
3861 if( pFile->sectorSize == 0 ){
3862 struct statvfs fsInfo;
3863
3864 /* Set defaults for non-supported filesystems */
3865 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3866 pFile->deviceCharacteristics = 0;
3867 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3868 return pFile->sectorSize;
3869 }
3870
3871 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3872 pFile->sectorSize = fsInfo.f_bsize;
3873 pFile->deviceCharacteristics =
3874 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3875 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3876 ** the write succeeds */
3877 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3878 ** so it is ordered */
3879 0;
3880 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3881 pFile->sectorSize = fsInfo.f_bsize;
3882 pFile->deviceCharacteristics =
3883 /* etfs cluster size writes are atomic */
3884 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3885 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3886 ** the write succeeds */
3887 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3888 ** so it is ordered */
3889 0;
3890 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3891 pFile->sectorSize = fsInfo.f_bsize;
3892 pFile->deviceCharacteristics =
3893 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3894 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3895 ** the write succeeds */
3896 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3897 ** so it is ordered */
3898 0;
3899 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3900 pFile->sectorSize = fsInfo.f_bsize;
3901 pFile->deviceCharacteristics =
3902 /* full bitset of atomics from max sector size and smaller */
3903 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3904 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3905 ** so it is ordered */
3906 0;
3907 }else if( strstr(fsInfo.f_basetype, "dos") ){
3908 pFile->sectorSize = fsInfo.f_bsize;
3909 pFile->deviceCharacteristics =
3910 /* full bitset of atomics from max sector size and smaller */
3911 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3912 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3913 ** so it is ordered */
3914 0;
3915 }else{
3916 pFile->deviceCharacteristics =
3917 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3918 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3919 ** the write succeeds */
3920 0;
3921 }
3922 }
3923 /* Last chance verification. If the sector size isn't a multiple of 512
3924 ** then it isn't valid.*/
3925 if( pFile->sectorSize % 512 != 0 ){
3926 pFile->deviceCharacteristics = 0;
3927 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3928 }
3929 return pFile->sectorSize;
3930}
3931#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003932
danielk197790949c22007-08-17 16:50:38 +00003933/*
drhf12b3f62011-12-21 14:42:29 +00003934** Return the device characteristics for the file.
3935**
drhcb15f352011-12-23 01:04:17 +00003936** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
peter.d.reid60ec9142014-09-06 16:39:46 +00003937** However, that choice is controversial since technically the underlying
drhcb15f352011-12-23 01:04:17 +00003938** file system does not always provide powersafe overwrites. (In other
3939** words, after a power-loss event, parts of the file that were never
3940** written might end up being altered.) However, non-PSOW behavior is very,
3941** very rare. And asserting PSOW makes a large reduction in the amount
3942** of required I/O for journaling, since a lot of padding is eliminated.
3943** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3944** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003945*/
drhf12b3f62011-12-21 14:42:29 +00003946static int unixDeviceCharacteristics(sqlite3_file *id){
3947 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003948 int rc = 0;
3949#ifdef __QNXNTO__
3950 if( p->sectorSize==0 ) unixSectorSize(id);
3951 rc = p->deviceCharacteristics;
3952#endif
drhcb15f352011-12-23 01:04:17 +00003953 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003954 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003955 }
drh537dddf2012-10-26 13:46:24 +00003956 return rc;
danielk197762079062007-08-15 17:08:46 +00003957}
3958
dan702eec12014-06-23 10:04:58 +00003959#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00003960
dan702eec12014-06-23 10:04:58 +00003961/*
3962** Return the system page size.
3963**
3964** This function should not be called directly by other code in this file.
3965** Instead, it should be called via macro osGetpagesize().
3966*/
3967static int unixGetpagesize(void){
drh8cd5b252015-03-02 22:06:43 +00003968#if OS_VXWORKS
3969 return 1024;
3970#elif defined(_BSD_SOURCE)
dan702eec12014-06-23 10:04:58 +00003971 return getpagesize();
3972#else
3973 return (int)sysconf(_SC_PAGESIZE);
3974#endif
3975}
3976
3977#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
3978
3979#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00003980
3981/*
drhd91c68f2010-05-14 14:52:25 +00003982** Object used to represent an shared memory buffer.
3983**
3984** When multiple threads all reference the same wal-index, each thread
3985** has its own unixShm object, but they all point to a single instance
3986** of this unixShmNode object. In other words, each wal-index is opened
3987** only once per process.
3988**
3989** Each unixShmNode object is connected to a single unixInodeInfo object.
3990** We could coalesce this object into unixInodeInfo, but that would mean
3991** every open file that does not use shared memory (in other words, most
3992** open files) would have to carry around this extra information. So
3993** the unixInodeInfo object contains a pointer to this unixShmNode object
3994** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003995**
3996** unixMutexHeld() must be true when creating or destroying
3997** this object or while reading or writing the following fields:
3998**
3999** nRef
drhd9e5c4f2010-05-12 18:01:39 +00004000**
4001** The following fields are read-only after the object is created:
4002**
4003** fid
4004** zFilename
4005**
drhd91c68f2010-05-14 14:52:25 +00004006** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00004007** unixMutexHeld() is true when reading or writing any other field
4008** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00004009*/
drhd91c68f2010-05-14 14:52:25 +00004010struct unixShmNode {
4011 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00004012 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00004013 char *zFilename; /* Name of the mmapped file */
4014 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00004015 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00004016 u16 nRegion; /* Size of array apRegion */
4017 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00004018 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00004019 int nRef; /* Number of unixShm objects pointing to this */
4020 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00004021#ifdef SQLITE_DEBUG
4022 u8 exclMask; /* Mask of exclusive locks held */
4023 u8 sharedMask; /* Mask of shared locks held */
4024 u8 nextShmId; /* Next available unixShm.id value */
4025#endif
4026};
4027
4028/*
drhd9e5c4f2010-05-12 18:01:39 +00004029** Structure used internally by this VFS to record the state of an
4030** open shared memory connection.
4031**
drhd91c68f2010-05-14 14:52:25 +00004032** The following fields are initialized when this object is created and
4033** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004034**
drhd91c68f2010-05-14 14:52:25 +00004035** unixShm.pFile
4036** unixShm.id
4037**
4038** All other fields are read/write. The unixShm.pFile->mutex must be held
4039** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004040*/
4041struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004042 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4043 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004044 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004045 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004046 u16 sharedMask; /* Mask of shared locks held */
4047 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004048};
4049
4050/*
drhd9e5c4f2010-05-12 18:01:39 +00004051** Constants used for locking
4052*/
drhbd9676c2010-06-23 17:58:38 +00004053#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004054#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004055
drhd9e5c4f2010-05-12 18:01:39 +00004056/*
drh73b64e42010-05-30 19:55:15 +00004057** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004058**
4059** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4060** otherwise.
4061*/
4062static int unixShmSystemLock(
drhbbf76ee2015-03-10 20:22:35 +00004063 unixFile *pFile, /* Open connection to the WAL file */
drhd91c68f2010-05-14 14:52:25 +00004064 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004065 int ofst, /* First byte of the locking range */
4066 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004067){
drhbbf76ee2015-03-10 20:22:35 +00004068 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4069 struct flock f; /* The posix advisory locking structure */
4070 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004071
drhd91c68f2010-05-14 14:52:25 +00004072 /* Access to the unixShmNode object is serialized by the caller */
drhbbf76ee2015-03-10 20:22:35 +00004073 pShmNode = pFile->pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004074 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004075
drh73b64e42010-05-30 19:55:15 +00004076 /* Shared locks never span more than one byte */
4077 assert( n==1 || lockType!=F_RDLCK );
4078
4079 /* Locks are within range */
drhaf19f172015-12-02 17:40:13 +00004080 assert( n>=1 && n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004081
drh3cb93392011-03-12 18:10:44 +00004082 if( pShmNode->h>=0 ){
4083 /* Initialize the locking parameters */
4084 memset(&f, 0, sizeof(f));
4085 f.l_type = lockType;
4086 f.l_whence = SEEK_SET;
4087 f.l_start = ofst;
4088 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004089
drhdcfb9652015-12-02 00:05:26 +00004090 rc = osFcntl(pShmNode->h, F_SETLK, &f);
drh3cb93392011-03-12 18:10:44 +00004091 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4092 }
drhd9e5c4f2010-05-12 18:01:39 +00004093
4094 /* Update the global lock state and do debug tracing */
4095#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004096 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004097 OSTRACE(("SHM-LOCK "));
drh693e6712014-01-24 22:58:00 +00004098 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004099 if( rc==SQLITE_OK ){
4100 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004101 OSTRACE(("unlock %d ok", ofst));
4102 pShmNode->exclMask &= ~mask;
4103 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004104 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004105 OSTRACE(("read-lock %d ok", ofst));
4106 pShmNode->exclMask &= ~mask;
4107 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004108 }else{
4109 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004110 OSTRACE(("write-lock %d ok", ofst));
4111 pShmNode->exclMask |= mask;
4112 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004113 }
4114 }else{
4115 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004116 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004117 }else if( lockType==F_RDLCK ){
4118 OSTRACE(("read-lock failed"));
4119 }else{
4120 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004121 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004122 }
4123 }
drh20e1f082010-05-31 16:10:12 +00004124 OSTRACE((" - afterwards %03x,%03x\n",
4125 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004126 }
drhd9e5c4f2010-05-12 18:01:39 +00004127#endif
4128
4129 return rc;
4130}
4131
dan781e34c2014-03-20 08:59:47 +00004132/*
dan781e34c2014-03-20 08:59:47 +00004133** Return the minimum number of 32KB shm regions that should be mapped at
4134** a time, assuming that each mapping must be an integer multiple of the
4135** current system page-size.
4136**
4137** Usually, this is 1. The exception seems to be systems that are configured
4138** to use 64KB pages - in this case each mapping must cover at least two
4139** shm regions.
4140*/
4141static int unixShmRegionPerMap(void){
4142 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004143 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004144 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4145 if( pgsz<shmsz ) return 1;
4146 return pgsz/shmsz;
4147}
drhd9e5c4f2010-05-12 18:01:39 +00004148
4149/*
drhd91c68f2010-05-14 14:52:25 +00004150** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004151**
4152** This is not a VFS shared-memory method; it is a utility function called
4153** by VFS shared-memory methods.
4154*/
drhd91c68f2010-05-14 14:52:25 +00004155static void unixShmPurge(unixFile *pFd){
4156 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004157 assert( unixMutexHeld() );
drhf3b1ed02015-12-02 13:11:03 +00004158 if( p && ALWAYS(p->nRef==0) ){
dan781e34c2014-03-20 08:59:47 +00004159 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004160 int i;
drhd91c68f2010-05-14 14:52:25 +00004161 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004162 sqlite3_mutex_free(p->mutex);
dan781e34c2014-03-20 08:59:47 +00004163 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh3cb93392011-03-12 18:10:44 +00004164 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004165 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004166 }else{
4167 sqlite3_free(p->apRegion[i]);
4168 }
dan13a3cb82010-06-11 19:04:21 +00004169 }
dan18801912010-06-14 14:07:50 +00004170 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004171 if( p->h>=0 ){
4172 robust_close(pFd, p->h, __LINE__);
4173 p->h = -1;
4174 }
drhd91c68f2010-05-14 14:52:25 +00004175 p->pInode->pShmNode = 0;
4176 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004177 }
4178}
4179
4180/*
danda9fe0c2010-07-13 18:44:03 +00004181** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004182** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004183**
drh7234c6d2010-06-19 15:10:09 +00004184** The file used to implement shared-memory is in the same directory
4185** as the open database file and has the same name as the open database
4186** file with the "-shm" suffix added. For example, if the database file
4187** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004188** for shared memory will be called "/home/user1/config.db-shm".
4189**
4190** Another approach to is to use files in /dev/shm or /dev/tmp or an
4191** some other tmpfs mount. But if a file in a different directory
4192** from the database file is used, then differing access permissions
4193** or a chroot() might cause two different processes on the same
4194** database to end up using different files for shared memory -
4195** meaning that their memory would not really be shared - resulting
4196** in database corruption. Nevertheless, this tmpfs file usage
4197** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4198** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4199** option results in an incompatible build of SQLite; builds of SQLite
4200** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4201** same database file at the same time, database corruption will likely
4202** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4203** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004204**
4205** When opening a new shared-memory file, if no other instances of that
4206** file are currently open, in this process or in other processes, then
4207** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004208**
4209** If the original database file (pDbFd) is using the "unix-excl" VFS
4210** that means that an exclusive lock is held on the database file and
4211** that no other processes are able to read or write the database. In
4212** that case, we do not really need shared memory. No shared memory
4213** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004214*/
danda9fe0c2010-07-13 18:44:03 +00004215static int unixOpenSharedMemory(unixFile *pDbFd){
4216 struct unixShm *p = 0; /* The connection to be opened */
4217 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4218 int rc; /* Result code */
4219 unixInodeInfo *pInode; /* The inode of fd */
4220 char *zShmFilename; /* Name of the file used for SHM */
4221 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004222
danda9fe0c2010-07-13 18:44:03 +00004223 /* Allocate space for the new unixShm object. */
drhf3cdcdc2015-04-29 16:50:28 +00004224 p = sqlite3_malloc64( sizeof(*p) );
drhd9e5c4f2010-05-12 18:01:39 +00004225 if( p==0 ) return SQLITE_NOMEM;
4226 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004227 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004228
danda9fe0c2010-07-13 18:44:03 +00004229 /* Check to see if a unixShmNode object already exists. Reuse an existing
4230 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004231 */
4232 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004233 pInode = pDbFd->pInode;
4234 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004235 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004236 struct stat sStat; /* fstat() info for database file */
drh4bf66fd2015-02-19 02:43:02 +00004237#ifndef SQLITE_SHM_DIRECTORY
4238 const char *zBasePath = pDbFd->zPath;
4239#endif
danddb0ac42010-07-14 14:48:58 +00004240
4241 /* Call fstat() to figure out the permissions on the database file. If
4242 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004243 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004244 */
drhf3b1ed02015-12-02 13:11:03 +00004245 if( osFstat(pDbFd->h, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004246 rc = SQLITE_IOERR_FSTAT;
4247 goto shm_open_err;
4248 }
4249
drha4ced192010-07-15 18:32:40 +00004250#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004251 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004252#else
drh4bf66fd2015-02-19 02:43:02 +00004253 nShmFilename = 6 + (int)strlen(zBasePath);
drha4ced192010-07-15 18:32:40 +00004254#endif
drhf3cdcdc2015-04-29 16:50:28 +00004255 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004256 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004257 rc = SQLITE_NOMEM;
4258 goto shm_open_err;
4259 }
drh9cb5a0d2012-01-05 21:19:54 +00004260 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004261 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004262#ifdef SQLITE_SHM_DIRECTORY
4263 sqlite3_snprintf(nShmFilename, zShmFilename,
4264 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4265 (u32)sStat.st_ino, (u32)sStat.st_dev);
4266#else
drh4bf66fd2015-02-19 02:43:02 +00004267 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
drh81cc5162011-05-17 20:36:21 +00004268 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004269#endif
drhd91c68f2010-05-14 14:52:25 +00004270 pShmNode->h = -1;
4271 pDbFd->pInode->pShmNode = pShmNode;
4272 pShmNode->pInode = pDbFd->pInode;
4273 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4274 if( pShmNode->mutex==0 ){
4275 rc = SQLITE_NOMEM;
4276 goto shm_open_err;
4277 }
drhd9e5c4f2010-05-12 18:01:39 +00004278
drh3cb93392011-03-12 18:10:44 +00004279 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004280 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004281 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004282 openFlags = O_RDONLY;
4283 pShmNode->isReadonly = 1;
4284 }
4285 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004286 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004287 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4288 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004289 }
drhac7c3ac2012-02-11 19:23:48 +00004290
4291 /* If this process is running as root, make sure that the SHM file
4292 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004293 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004294 */
drh6226ca22015-11-24 15:06:28 +00004295 robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004296
4297 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004298 ** If not, truncate the file to zero length.
4299 */
4300 rc = SQLITE_OK;
drhbbf76ee2015-03-10 20:22:35 +00004301 if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
drh66dfec8b2011-06-01 20:01:49 +00004302 if( robust_ftruncate(pShmNode->h, 0) ){
4303 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004304 }
4305 }
drh66dfec8b2011-06-01 20:01:49 +00004306 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004307 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
drh66dfec8b2011-06-01 20:01:49 +00004308 }
4309 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004310 }
drhd9e5c4f2010-05-12 18:01:39 +00004311 }
4312
drhd91c68f2010-05-14 14:52:25 +00004313 /* Make the new connection a child of the unixShmNode */
4314 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004315#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004316 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004317#endif
drhd91c68f2010-05-14 14:52:25 +00004318 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004319 pDbFd->pShm = p;
4320 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004321
4322 /* The reference count on pShmNode has already been incremented under
4323 ** the cover of the unixEnterMutex() mutex and the pointer from the
4324 ** new (struct unixShm) object to the pShmNode has been set. All that is
4325 ** left to do is to link the new object into the linked list starting
4326 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4327 ** mutex.
4328 */
4329 sqlite3_mutex_enter(pShmNode->mutex);
4330 p->pNext = pShmNode->pFirst;
4331 pShmNode->pFirst = p;
4332 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004333 return SQLITE_OK;
4334
4335 /* Jump here on any error */
4336shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004337 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004338 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004339 unixLeaveMutex();
4340 return rc;
4341}
4342
4343/*
danda9fe0c2010-07-13 18:44:03 +00004344** This function is called to obtain a pointer to region iRegion of the
4345** shared-memory associated with the database file fd. Shared-memory regions
4346** are numbered starting from zero. Each shared-memory region is szRegion
4347** bytes in size.
4348**
4349** If an error occurs, an error code is returned and *pp is set to NULL.
4350**
4351** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4352** region has not been allocated (by any client, including one running in a
4353** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4354** bExtend is non-zero and the requested shared-memory region has not yet
4355** been allocated, it is allocated by this function.
4356**
4357** If the shared-memory region has already been allocated or is allocated by
4358** this call as described above, then it is mapped into this processes
4359** address space (if it is not already), *pp is set to point to the mapped
4360** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004361*/
danda9fe0c2010-07-13 18:44:03 +00004362static int unixShmMap(
4363 sqlite3_file *fd, /* Handle open on database file */
4364 int iRegion, /* Region to retrieve */
4365 int szRegion, /* Size of regions */
4366 int bExtend, /* True to extend file if necessary */
4367 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004368){
danda9fe0c2010-07-13 18:44:03 +00004369 unixFile *pDbFd = (unixFile*)fd;
4370 unixShm *p;
4371 unixShmNode *pShmNode;
4372 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004373 int nShmPerMap = unixShmRegionPerMap();
4374 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004375
danda9fe0c2010-07-13 18:44:03 +00004376 /* If the shared-memory file has not yet been opened, open it now. */
4377 if( pDbFd->pShm==0 ){
4378 rc = unixOpenSharedMemory(pDbFd);
4379 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004380 }
drhd9e5c4f2010-05-12 18:01:39 +00004381
danda9fe0c2010-07-13 18:44:03 +00004382 p = pDbFd->pShm;
4383 pShmNode = p->pShmNode;
4384 sqlite3_mutex_enter(pShmNode->mutex);
4385 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004386 assert( pShmNode->pInode==pDbFd->pInode );
4387 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4388 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004389
dan781e34c2014-03-20 08:59:47 +00004390 /* Minimum number of regions required to be mapped. */
4391 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4392
4393 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004394 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004395 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004396 struct stat sStat; /* Used by fstat() */
4397
4398 pShmNode->szRegion = szRegion;
4399
drh3cb93392011-03-12 18:10:44 +00004400 if( pShmNode->h>=0 ){
4401 /* The requested region is not mapped into this processes address space.
4402 ** Check to see if it has been allocated (i.e. if the wal-index file is
4403 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004404 */
drh3cb93392011-03-12 18:10:44 +00004405 if( osFstat(pShmNode->h, &sStat) ){
4406 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004407 goto shmpage_out;
4408 }
drh3cb93392011-03-12 18:10:44 +00004409
4410 if( sStat.st_size<nByte ){
4411 /* The requested memory region does not exist. If bExtend is set to
4412 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004413 */
dan47a2b4a2013-04-26 16:09:29 +00004414 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004415 goto shmpage_out;
4416 }
dan47a2b4a2013-04-26 16:09:29 +00004417
4418 /* Alternatively, if bExtend is true, extend the file. Do this by
4419 ** writing a single byte to the end of each (OS) page being
4420 ** allocated or extended. Technically, we need only write to the
4421 ** last page in order to extend the file. But writing to all new
4422 ** pages forces the OS to allocate them immediately, which reduces
4423 ** the chances of SIGBUS while accessing the mapped region later on.
4424 */
4425 else{
4426 static const int pgsz = 4096;
4427 int iPg;
4428
4429 /* Write to the last byte of each newly allocated or extended page */
4430 assert( (nByte % pgsz)==0 );
4431 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
drhe1818ec2015-12-01 16:21:35 +00004432 int x = 0;
4433 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
dan47a2b4a2013-04-26 16:09:29 +00004434 const char *zFile = pShmNode->zFilename;
4435 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4436 goto shmpage_out;
4437 }
4438 }
drh3cb93392011-03-12 18:10:44 +00004439 }
4440 }
danda9fe0c2010-07-13 18:44:03 +00004441 }
4442
4443 /* Map the requested memory region into this processes address space. */
4444 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004445 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004446 );
4447 if( !apNew ){
4448 rc = SQLITE_IOERR_NOMEM;
4449 goto shmpage_out;
4450 }
4451 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004452 while( pShmNode->nRegion<nReqRegion ){
4453 int nMap = szRegion*nShmPerMap;
4454 int i;
drh3cb93392011-03-12 18:10:44 +00004455 void *pMem;
4456 if( pShmNode->h>=0 ){
dan781e34c2014-03-20 08:59:47 +00004457 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004458 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004459 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004460 );
4461 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004462 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004463 goto shmpage_out;
4464 }
4465 }else{
drhf3cdcdc2015-04-29 16:50:28 +00004466 pMem = sqlite3_malloc64(szRegion);
drh3cb93392011-03-12 18:10:44 +00004467 if( pMem==0 ){
4468 rc = SQLITE_NOMEM;
4469 goto shmpage_out;
4470 }
4471 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004472 }
dan781e34c2014-03-20 08:59:47 +00004473
4474 for(i=0; i<nShmPerMap; i++){
4475 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4476 }
4477 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004478 }
4479 }
4480
4481shmpage_out:
4482 if( pShmNode->nRegion>iRegion ){
4483 *pp = pShmNode->apRegion[iRegion];
4484 }else{
4485 *pp = 0;
4486 }
drh66dfec8b2011-06-01 20:01:49 +00004487 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004488 sqlite3_mutex_leave(pShmNode->mutex);
4489 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004490}
4491
4492/*
drhd9e5c4f2010-05-12 18:01:39 +00004493** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004494**
4495** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4496** different here than in posix. In xShmLock(), one can go from unlocked
4497** to shared and back or from unlocked to exclusive and back. But one may
4498** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004499*/
4500static int unixShmLock(
4501 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004502 int ofst, /* First lock to acquire or release */
4503 int n, /* Number of locks to acquire or release */
4504 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004505){
drh73b64e42010-05-30 19:55:15 +00004506 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4507 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4508 unixShm *pX; /* For looping over all siblings */
4509 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4510 int rc = SQLITE_OK; /* Result code */
4511 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004512
drhd91c68f2010-05-14 14:52:25 +00004513 assert( pShmNode==pDbFd->pInode->pShmNode );
4514 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004515 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004516 assert( n>=1 );
4517 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4518 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4519 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4520 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4521 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004522 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4523 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004524
drhc99597c2010-05-31 01:41:15 +00004525 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004526 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004527 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004528 if( flags & SQLITE_SHM_UNLOCK ){
4529 u16 allMask = 0; /* Mask of locks held by siblings */
4530
4531 /* See if any siblings hold this same lock */
4532 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4533 if( pX==p ) continue;
4534 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4535 allMask |= pX->sharedMask;
4536 }
4537
4538 /* Unlock the system-level locks */
4539 if( (mask & allMask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004540 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004541 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004542 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004543 }
drh73b64e42010-05-30 19:55:15 +00004544
4545 /* Undo the local locks */
4546 if( rc==SQLITE_OK ){
4547 p->exclMask &= ~mask;
4548 p->sharedMask &= ~mask;
4549 }
4550 }else if( flags & SQLITE_SHM_SHARED ){
4551 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4552
4553 /* Find out which shared locks are already held by sibling connections.
4554 ** If any sibling already holds an exclusive lock, go ahead and return
4555 ** SQLITE_BUSY.
4556 */
4557 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004558 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004559 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004560 break;
4561 }
4562 allShared |= pX->sharedMask;
4563 }
4564
4565 /* Get shared locks at the system level, if necessary */
4566 if( rc==SQLITE_OK ){
4567 if( (allShared & mask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004568 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004569 }else{
drh73b64e42010-05-30 19:55:15 +00004570 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004571 }
drhd9e5c4f2010-05-12 18:01:39 +00004572 }
drh73b64e42010-05-30 19:55:15 +00004573
4574 /* Get the local shared locks */
4575 if( rc==SQLITE_OK ){
4576 p->sharedMask |= mask;
4577 }
4578 }else{
4579 /* Make sure no sibling connections hold locks that will block this
4580 ** lock. If any do, return SQLITE_BUSY right away.
4581 */
4582 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004583 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4584 rc = SQLITE_BUSY;
4585 break;
4586 }
4587 }
4588
4589 /* Get the exclusive locks at the system level. Then if successful
4590 ** also mark the local connection as being locked.
4591 */
4592 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004593 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004594 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004595 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004596 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004597 }
drhd9e5c4f2010-05-12 18:01:39 +00004598 }
4599 }
drhd91c68f2010-05-14 14:52:25 +00004600 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004601 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
drh5ac93652015-03-21 20:59:43 +00004602 p->id, osGetpid(0), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004603 return rc;
4604}
4605
drh286a2882010-05-20 23:51:06 +00004606/*
4607** Implement a memory barrier or memory fence on shared memory.
4608**
4609** All loads and stores begun before the barrier must complete before
4610** any load or store begun after the barrier.
4611*/
4612static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004613 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004614){
drhff828942010-06-26 21:34:06 +00004615 UNUSED_PARAMETER(fd);
drh22c733d2015-09-24 12:40:43 +00004616 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
4617 unixEnterMutex(); /* Also mutex, for redundancy */
drhb29ad852010-06-01 00:03:57 +00004618 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004619}
4620
dan18801912010-06-14 14:07:50 +00004621/*
danda9fe0c2010-07-13 18:44:03 +00004622** Close a connection to shared-memory. Delete the underlying
4623** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004624**
4625** If there is no shared memory associated with the connection then this
4626** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004627*/
danda9fe0c2010-07-13 18:44:03 +00004628static int unixShmUnmap(
4629 sqlite3_file *fd, /* The underlying database file */
4630 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004631){
danda9fe0c2010-07-13 18:44:03 +00004632 unixShm *p; /* The connection to be closed */
4633 unixShmNode *pShmNode; /* The underlying shared-memory file */
4634 unixShm **pp; /* For looping over sibling connections */
4635 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004636
danda9fe0c2010-07-13 18:44:03 +00004637 pDbFd = (unixFile*)fd;
4638 p = pDbFd->pShm;
4639 if( p==0 ) return SQLITE_OK;
4640 pShmNode = p->pShmNode;
4641
4642 assert( pShmNode==pDbFd->pInode->pShmNode );
4643 assert( pShmNode->pInode==pDbFd->pInode );
4644
4645 /* Remove connection p from the set of connections associated
4646 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004647 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004648 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4649 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004650
danda9fe0c2010-07-13 18:44:03 +00004651 /* Free the connection p */
4652 sqlite3_free(p);
4653 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004654 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004655
4656 /* If pShmNode->nRef has reached 0, then close the underlying
4657 ** shared-memory file, too */
4658 unixEnterMutex();
4659 assert( pShmNode->nRef>0 );
4660 pShmNode->nRef--;
4661 if( pShmNode->nRef==0 ){
drh4bf66fd2015-02-19 02:43:02 +00004662 if( deleteFlag && pShmNode->h>=0 ){
4663 osUnlink(pShmNode->zFilename);
4664 }
danda9fe0c2010-07-13 18:44:03 +00004665 unixShmPurge(pDbFd);
4666 }
4667 unixLeaveMutex();
4668
4669 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004670}
drh286a2882010-05-20 23:51:06 +00004671
danda9fe0c2010-07-13 18:44:03 +00004672
drhd9e5c4f2010-05-12 18:01:39 +00004673#else
drh6b017cc2010-06-14 18:01:46 +00004674# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004675# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004676# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004677# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004678#endif /* #ifndef SQLITE_OMIT_WAL */
4679
mistachkine98844f2013-08-24 00:59:24 +00004680#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004681/*
danaef49d72013-03-25 16:28:54 +00004682** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004683*/
danf23da962013-03-23 21:00:41 +00004684static void unixUnmapfile(unixFile *pFd){
4685 assert( pFd->nFetchOut==0 );
4686 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004687 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004688 pFd->pMapRegion = 0;
4689 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004690 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004691 }
4692}
dan5d8a1372013-03-19 19:28:06 +00004693
danaef49d72013-03-25 16:28:54 +00004694/*
dane6ecd662013-04-01 17:56:59 +00004695** Attempt to set the size of the memory mapping maintained by file
4696** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4697**
4698** If successful, this function sets the following variables:
4699**
4700** unixFile.pMapRegion
4701** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004702** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004703**
4704** If unsuccessful, an error message is logged via sqlite3_log() and
4705** the three variables above are zeroed. In this case SQLite should
4706** continue accessing the database using the xRead() and xWrite()
4707** methods.
4708*/
4709static void unixRemapfile(
4710 unixFile *pFd, /* File descriptor object */
4711 i64 nNew /* Required mapping size */
4712){
dan4ff7bc42013-04-02 12:04:09 +00004713 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004714 int h = pFd->h; /* File descriptor open on db file */
4715 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004716 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004717 u8 *pNew = 0; /* Location of new mapping */
4718 int flags = PROT_READ; /* Flags to pass to mmap() */
4719
4720 assert( pFd->nFetchOut==0 );
4721 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004722 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004723 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004724 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004725 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004726
danfe33e392015-11-17 20:56:06 +00004727#ifdef SQLITE_MMAP_READWRITE
dane6ecd662013-04-01 17:56:59 +00004728 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
danfe33e392015-11-17 20:56:06 +00004729#endif
dane6ecd662013-04-01 17:56:59 +00004730
4731 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00004732#if HAVE_MREMAP
4733 i64 nReuse = pFd->mmapSize;
4734#else
danbc760632014-03-20 09:42:09 +00004735 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00004736 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00004737#endif
dane6ecd662013-04-01 17:56:59 +00004738 u8 *pReq = &pOrig[nReuse];
4739
4740 /* Unmap any pages of the existing mapping that cannot be reused. */
4741 if( nReuse!=nOrig ){
4742 osMunmap(pReq, nOrig-nReuse);
4743 }
4744
4745#if HAVE_MREMAP
4746 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004747 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004748#else
4749 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4750 if( pNew!=MAP_FAILED ){
4751 if( pNew!=pReq ){
4752 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004753 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004754 }else{
4755 pNew = pOrig;
4756 }
4757 }
4758#endif
4759
dan48ccef82013-04-02 20:55:01 +00004760 /* The attempt to extend the existing mapping failed. Free it. */
4761 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004762 osMunmap(pOrig, nReuse);
4763 }
4764 }
4765
4766 /* If pNew is still NULL, try to create an entirely new mapping. */
4767 if( pNew==0 ){
4768 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004769 }
4770
dan4ff7bc42013-04-02 12:04:09 +00004771 if( pNew==MAP_FAILED ){
4772 pNew = 0;
4773 nNew = 0;
4774 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4775
4776 /* If the mmap() above failed, assume that all subsequent mmap() calls
4777 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4778 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004779 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004780 }
dane6ecd662013-04-01 17:56:59 +00004781 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004782 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004783}
4784
4785/*
danaef49d72013-03-25 16:28:54 +00004786** Memory map or remap the file opened by file-descriptor pFd (if the file
4787** is already mapped, the existing mapping is replaced by the new). Or, if
4788** there already exists a mapping for this file, and there are still
4789** outstanding xFetch() references to it, this function is a no-op.
4790**
4791** If parameter nByte is non-negative, then it is the requested size of
4792** the mapping to create. Otherwise, if nByte is less than zero, then the
4793** requested size is the size of the file on disk. The actual size of the
4794** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004795** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004796**
4797** SQLITE_OK is returned if no error occurs (even if the mapping is not
4798** recreated as a result of outstanding references) or an SQLite error
4799** code otherwise.
4800*/
drhf3b1ed02015-12-02 13:11:03 +00004801static int unixMapfile(unixFile *pFd, i64 nMap){
danf23da962013-03-23 21:00:41 +00004802 assert( nMap>=0 || pFd->nFetchOut==0 );
drh333e6ca2015-12-02 15:44:39 +00004803 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00004804 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4805
4806 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00004807 struct stat statbuf; /* Low-level file information */
drhf3b1ed02015-12-02 13:11:03 +00004808 if( osFstat(pFd->h, &statbuf) ){
danf23da962013-03-23 21:00:41 +00004809 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004810 }
drh3044b512014-06-16 16:41:52 +00004811 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00004812 }
drh9b4c59f2013-04-15 17:03:42 +00004813 if( nMap>pFd->mmapSizeMax ){
4814 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004815 }
4816
drh333e6ca2015-12-02 15:44:39 +00004817 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00004818 if( nMap!=pFd->mmapSize ){
drh333e6ca2015-12-02 15:44:39 +00004819 unixRemapfile(pFd, nMap);
dan5d8a1372013-03-19 19:28:06 +00004820 }
4821
danf23da962013-03-23 21:00:41 +00004822 return SQLITE_OK;
4823}
mistachkine98844f2013-08-24 00:59:24 +00004824#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004825
danaef49d72013-03-25 16:28:54 +00004826/*
4827** If possible, return a pointer to a mapping of file fd starting at offset
4828** iOff. The mapping must be valid for at least nAmt bytes.
4829**
4830** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4831** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4832** Finally, if an error does occur, return an SQLite error code. The final
4833** value of *pp is undefined in this case.
4834**
4835** If this function does return a pointer, the caller must eventually
4836** release the reference by calling unixUnfetch().
4837*/
danf23da962013-03-23 21:00:41 +00004838static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004839#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004840 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004841#endif
danf23da962013-03-23 21:00:41 +00004842 *pp = 0;
4843
drh9b4c59f2013-04-15 17:03:42 +00004844#if SQLITE_MAX_MMAP_SIZE>0
4845 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004846 if( pFd->pMapRegion==0 ){
4847 int rc = unixMapfile(pFd, -1);
4848 if( rc!=SQLITE_OK ) return rc;
4849 }
4850 if( pFd->mmapSize >= iOff+nAmt ){
4851 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4852 pFd->nFetchOut++;
4853 }
4854 }
drh6e0b6d52013-04-09 16:19:20 +00004855#endif
danf23da962013-03-23 21:00:41 +00004856 return SQLITE_OK;
4857}
4858
danaef49d72013-03-25 16:28:54 +00004859/*
dandf737fe2013-03-25 17:00:24 +00004860** If the third argument is non-NULL, then this function releases a
4861** reference obtained by an earlier call to unixFetch(). The second
4862** argument passed to this function must be the same as the corresponding
4863** argument that was passed to the unixFetch() invocation.
4864**
4865** Or, if the third argument is NULL, then this function is being called
4866** to inform the VFS layer that, according to POSIX, any existing mapping
4867** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004868*/
dandf737fe2013-03-25 17:00:24 +00004869static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00004870#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00004871 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00004872 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00004873
danaef49d72013-03-25 16:28:54 +00004874 /* If p==0 (unmap the entire file) then there must be no outstanding
4875 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4876 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004877 assert( (p==0)==(pFd->nFetchOut==0) );
4878
dandf737fe2013-03-25 17:00:24 +00004879 /* If p!=0, it must match the iOff value. */
4880 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4881
danf23da962013-03-23 21:00:41 +00004882 if( p ){
4883 pFd->nFetchOut--;
4884 }else{
4885 unixUnmapfile(pFd);
4886 }
4887
4888 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00004889#else
4890 UNUSED_PARAMETER(fd);
4891 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00004892 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00004893#endif
danf23da962013-03-23 21:00:41 +00004894 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004895}
4896
4897/*
drh734c9862008-11-28 15:37:20 +00004898** Here ends the implementation of all sqlite3_file methods.
4899**
4900********************** End sqlite3_file Methods *******************************
4901******************************************************************************/
4902
4903/*
drh6b9d6dd2008-12-03 19:34:47 +00004904** This division contains definitions of sqlite3_io_methods objects that
4905** implement various file locking strategies. It also contains definitions
4906** of "finder" functions. A finder-function is used to locate the appropriate
4907** sqlite3_io_methods object for a particular database file. The pAppData
4908** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4909** the correct finder-function for that VFS.
4910**
4911** Most finder functions return a pointer to a fixed sqlite3_io_methods
4912** object. The only interesting finder-function is autolockIoFinder, which
4913** looks at the filesystem type and tries to guess the best locking
4914** strategy from that.
4915**
peter.d.reid60ec9142014-09-06 16:39:46 +00004916** For finder-function F, two objects are created:
drh1875f7a2008-12-08 18:19:17 +00004917**
4918** (1) The real finder-function named "FImpt()".
4919**
dane946c392009-08-22 11:39:46 +00004920** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004921**
4922**
4923** A pointer to the F pointer is used as the pAppData value for VFS
4924** objects. We have to do this instead of letting pAppData point
4925** directly at the finder-function since C90 rules prevent a void*
4926** from be cast into a function pointer.
4927**
drh6b9d6dd2008-12-03 19:34:47 +00004928**
drh7708e972008-11-29 00:56:52 +00004929** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004930**
drh7708e972008-11-29 00:56:52 +00004931** * A constant sqlite3_io_methods object call METHOD that has locking
4932** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4933**
4934** * An I/O method finder function called FINDER that returns a pointer
4935** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004936*/
drhe6d41732015-02-21 00:49:00 +00004937#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
drh7708e972008-11-29 00:56:52 +00004938static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004939 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004940 CLOSE, /* xClose */ \
4941 unixRead, /* xRead */ \
4942 unixWrite, /* xWrite */ \
4943 unixTruncate, /* xTruncate */ \
4944 unixSync, /* xSync */ \
4945 unixFileSize, /* xFileSize */ \
4946 LOCK, /* xLock */ \
4947 UNLOCK, /* xUnlock */ \
4948 CKLOCK, /* xCheckReservedLock */ \
4949 unixFileControl, /* xFileControl */ \
4950 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004951 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drhd9f94412014-09-22 03:22:27 +00004952 SHMMAP, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004953 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004954 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00004955 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00004956 unixFetch, /* xFetch */ \
4957 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00004958}; \
drh0c2694b2009-09-03 16:23:44 +00004959static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4960 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004961 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004962} \
drh0c2694b2009-09-03 16:23:44 +00004963static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004964 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004965
4966/*
4967** Here are all of the sqlite3_io_methods objects for each of the
4968** locking strategies. Functions that return pointers to these methods
4969** are also created.
4970*/
4971IOMETHODS(
4972 posixIoFinder, /* Finder function name */
4973 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00004974 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00004975 unixClose, /* xClose method */
4976 unixLock, /* xLock method */
4977 unixUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004978 unixCheckReservedLock, /* xCheckReservedLock method */
4979 unixShmMap /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004980)
drh7708e972008-11-29 00:56:52 +00004981IOMETHODS(
4982 nolockIoFinder, /* Finder function name */
4983 nolockIoMethods, /* sqlite3_io_methods object name */
drh142341c2014-09-19 19:00:48 +00004984 3, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004985 nolockClose, /* xClose method */
4986 nolockLock, /* xLock method */
4987 nolockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004988 nolockCheckReservedLock, /* xCheckReservedLock method */
4989 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004990)
drh7708e972008-11-29 00:56:52 +00004991IOMETHODS(
4992 dotlockIoFinder, /* Finder function name */
4993 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004994 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004995 dotlockClose, /* xClose method */
4996 dotlockLock, /* xLock method */
4997 dotlockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004998 dotlockCheckReservedLock, /* xCheckReservedLock method */
4999 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005000)
drh7708e972008-11-29 00:56:52 +00005001
drhe89b2912015-03-03 20:42:01 +00005002#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005003IOMETHODS(
5004 flockIoFinder, /* Finder function name */
5005 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005006 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005007 flockClose, /* xClose method */
5008 flockLock, /* xLock method */
5009 flockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005010 flockCheckReservedLock, /* xCheckReservedLock method */
5011 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005012)
drh7708e972008-11-29 00:56:52 +00005013#endif
5014
drh6c7d5c52008-11-21 20:32:33 +00005015#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005016IOMETHODS(
5017 semIoFinder, /* Finder function name */
5018 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005019 1, /* shared memory is disabled */
drh8cd5b252015-03-02 22:06:43 +00005020 semXClose, /* xClose method */
5021 semXLock, /* xLock method */
5022 semXUnlock, /* xUnlock method */
5023 semXCheckReservedLock, /* xCheckReservedLock method */
drhd9f94412014-09-22 03:22:27 +00005024 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005025)
aswiftaebf4132008-11-21 00:10:35 +00005026#endif
drh7708e972008-11-29 00:56:52 +00005027
drhd2cb50b2009-01-09 21:41:17 +00005028#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005029IOMETHODS(
5030 afpIoFinder, /* Finder function name */
5031 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005032 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005033 afpClose, /* xClose method */
5034 afpLock, /* xLock method */
5035 afpUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005036 afpCheckReservedLock, /* xCheckReservedLock method */
5037 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005038)
drh715ff302008-12-03 22:32:44 +00005039#endif
5040
5041/*
5042** The proxy locking method is a "super-method" in the sense that it
5043** opens secondary file descriptors for the conch and lock files and
5044** it uses proxy, dot-file, AFP, and flock() locking methods on those
5045** secondary files. For this reason, the division that implements
5046** proxy locking is located much further down in the file. But we need
5047** to go ahead and define the sqlite3_io_methods and finder function
5048** for proxy locking here. So we forward declare the I/O methods.
5049*/
drhd2cb50b2009-01-09 21:41:17 +00005050#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005051static int proxyClose(sqlite3_file*);
5052static int proxyLock(sqlite3_file*, int);
5053static int proxyUnlock(sqlite3_file*, int);
5054static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005055IOMETHODS(
5056 proxyIoFinder, /* Finder function name */
5057 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005058 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005059 proxyClose, /* xClose method */
5060 proxyLock, /* xLock method */
5061 proxyUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005062 proxyCheckReservedLock, /* xCheckReservedLock method */
5063 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005064)
aswiftaebf4132008-11-21 00:10:35 +00005065#endif
drh7708e972008-11-29 00:56:52 +00005066
drh7ed97b92010-01-20 13:07:21 +00005067/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5068#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5069IOMETHODS(
5070 nfsIoFinder, /* Finder function name */
5071 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005072 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005073 unixClose, /* xClose method */
5074 unixLock, /* xLock method */
5075 nfsUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005076 unixCheckReservedLock, /* xCheckReservedLock method */
5077 0 /* xShmMap method */
drh7ed97b92010-01-20 13:07:21 +00005078)
5079#endif
drh7708e972008-11-29 00:56:52 +00005080
drhd2cb50b2009-01-09 21:41:17 +00005081#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005082/*
drh6b9d6dd2008-12-03 19:34:47 +00005083** This "finder" function attempts to determine the best locking strategy
5084** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005085** object that implements that strategy.
5086**
5087** This is for MacOSX only.
5088*/
drh1875f7a2008-12-08 18:19:17 +00005089static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005090 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005091 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005092){
5093 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005094 const char *zFilesystem; /* Filesystem type name */
5095 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005096 } aMap[] = {
5097 { "hfs", &posixIoMethods },
5098 { "ufs", &posixIoMethods },
5099 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005100 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005101 { "webdav", &nolockIoMethods },
5102 { 0, 0 }
5103 };
5104 int i;
5105 struct statfs fsInfo;
5106 struct flock lockInfo;
5107
5108 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005109 /* If filePath==NULL that means we are dealing with a transient file
5110 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005111 return &nolockIoMethods;
5112 }
5113 if( statfs(filePath, &fsInfo) != -1 ){
5114 if( fsInfo.f_flags & MNT_RDONLY ){
5115 return &nolockIoMethods;
5116 }
5117 for(i=0; aMap[i].zFilesystem; i++){
5118 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5119 return aMap[i].pMethods;
5120 }
5121 }
5122 }
5123
5124 /* Default case. Handles, amongst others, "nfs".
5125 ** Test byte-range lock using fcntl(). If the call succeeds,
5126 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005127 */
drh7708e972008-11-29 00:56:52 +00005128 lockInfo.l_len = 1;
5129 lockInfo.l_start = 0;
5130 lockInfo.l_whence = SEEK_SET;
5131 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005132 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005133 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5134 return &nfsIoMethods;
5135 } else {
5136 return &posixIoMethods;
5137 }
drh7708e972008-11-29 00:56:52 +00005138 }else{
5139 return &dotlockIoMethods;
5140 }
5141}
drh0c2694b2009-09-03 16:23:44 +00005142static const sqlite3_io_methods
5143 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005144
drhd2cb50b2009-01-09 21:41:17 +00005145#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005146
drhe89b2912015-03-03 20:42:01 +00005147#if OS_VXWORKS
5148/*
5149** This "finder" function for VxWorks checks to see if posix advisory
5150** locking works. If it does, then that is what is used. If it does not
5151** work, then fallback to named semaphore locking.
chw78a13182009-04-07 05:35:03 +00005152*/
drhe89b2912015-03-03 20:42:01 +00005153static const sqlite3_io_methods *vxworksIoFinderImpl(
chw78a13182009-04-07 05:35:03 +00005154 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005155 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005156){
5157 struct flock lockInfo;
5158
5159 if( !filePath ){
5160 /* If filePath==NULL that means we are dealing with a transient file
5161 ** that does not need to be locked. */
5162 return &nolockIoMethods;
5163 }
5164
5165 /* Test if fcntl() is supported and use POSIX style locks.
5166 ** Otherwise fall back to the named semaphore method.
5167 */
5168 lockInfo.l_len = 1;
5169 lockInfo.l_start = 0;
5170 lockInfo.l_whence = SEEK_SET;
5171 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005172 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005173 return &posixIoMethods;
5174 }else{
5175 return &semIoMethods;
5176 }
5177}
drh0c2694b2009-09-03 16:23:44 +00005178static const sqlite3_io_methods
drhe89b2912015-03-03 20:42:01 +00005179 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005180
drhe89b2912015-03-03 20:42:01 +00005181#endif /* OS_VXWORKS */
chw78a13182009-04-07 05:35:03 +00005182
drh7708e972008-11-29 00:56:52 +00005183/*
peter.d.reid60ec9142014-09-06 16:39:46 +00005184** An abstract type for a pointer to an IO method finder function:
drh7708e972008-11-29 00:56:52 +00005185*/
drh0c2694b2009-09-03 16:23:44 +00005186typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005187
aswiftaebf4132008-11-21 00:10:35 +00005188
drh734c9862008-11-28 15:37:20 +00005189/****************************************************************************
5190**************************** sqlite3_vfs methods ****************************
5191**
5192** This division contains the implementation of methods on the
5193** sqlite3_vfs object.
5194*/
5195
danielk1977a3d4c882007-03-23 10:08:38 +00005196/*
danielk1977e339d652008-06-28 11:23:00 +00005197** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005198*/
5199static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005200 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005201 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005202 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005203 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005204 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005205){
drh7708e972008-11-29 00:56:52 +00005206 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005207 unixFile *pNew = (unixFile *)pId;
5208 int rc = SQLITE_OK;
5209
drh8af6c222010-05-14 12:43:01 +00005210 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005211
dan00157392010-10-05 11:33:15 +00005212 /* Usually the path zFilename should not be a relative pathname. The
5213 ** exception is when opening the proxy "conch" file in builds that
5214 ** include the special Apple locking styles.
5215 */
dan00157392010-10-05 11:33:15 +00005216#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005217 assert( zFilename==0 || zFilename[0]=='/'
5218 || pVfs->pAppData==(void*)&autolockIoFinder );
5219#else
5220 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005221#endif
dan00157392010-10-05 11:33:15 +00005222
drhb07028f2011-10-14 21:49:18 +00005223 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005224 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005225
drh308c2a52010-05-14 11:30:18 +00005226 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005227 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005228 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005229 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005230 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005231#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005232 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005233#endif
drhc02a43a2012-01-10 23:18:38 +00005234 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5235 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005236 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005237 }
drh503a6862013-03-01 01:07:17 +00005238 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005239 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005240 }
drh339eb0b2008-03-07 15:34:11 +00005241
drh6c7d5c52008-11-21 20:32:33 +00005242#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005243 pNew->pId = vxworksFindFileId(zFilename);
5244 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005245 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00005246 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00005247 }
5248#endif
5249
drhc02a43a2012-01-10 23:18:38 +00005250 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005251 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005252 }else{
drh0c2694b2009-09-03 16:23:44 +00005253 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005254#if SQLITE_ENABLE_LOCKING_STYLE
5255 /* Cache zFilename in the locking context (AFP and dotlock override) for
5256 ** proxyLock activation is possible (remote proxy is based on db name)
5257 ** zFilename remains valid until file is closed, to support */
5258 pNew->lockingContext = (void*)zFilename;
5259#endif
drhda0e7682008-07-30 15:27:54 +00005260 }
danielk1977e339d652008-06-28 11:23:00 +00005261
drh7ed97b92010-01-20 13:07:21 +00005262 if( pLockingStyle == &posixIoMethods
5263#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5264 || pLockingStyle == &nfsIoMethods
5265#endif
5266 ){
drh7708e972008-11-29 00:56:52 +00005267 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005268 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005269 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005270 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005271 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005272 ** in two scenarios:
5273 **
5274 ** (a) A call to fstat() failed.
5275 ** (b) A malloc failed.
5276 **
5277 ** Scenario (b) may only occur if the process is holding no other
5278 ** file descriptors open on the same file. If there were other file
5279 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005280 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005281 ** handle h - as it is guaranteed that no posix locks will be released
5282 ** by doing so.
5283 **
5284 ** If scenario (a) caused the error then things are not so safe. The
5285 ** implicit assumption here is that if fstat() fails, things are in
5286 ** such bad shape that dropping a lock or two doesn't matter much.
5287 */
drh0e9365c2011-03-02 02:08:13 +00005288 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005289 h = -1;
5290 }
drh7708e972008-11-29 00:56:52 +00005291 unixLeaveMutex();
5292 }
danielk1977e339d652008-06-28 11:23:00 +00005293
drhd2cb50b2009-01-09 21:41:17 +00005294#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005295 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005296 /* AFP locking uses the file path so it needs to be included in
5297 ** the afpLockingContext.
5298 */
5299 afpLockingContext *pCtx;
drhf3cdcdc2015-04-29 16:50:28 +00005300 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh7708e972008-11-29 00:56:52 +00005301 if( pCtx==0 ){
5302 rc = SQLITE_NOMEM;
5303 }else{
5304 /* NB: zFilename exists and remains valid until the file is closed
5305 ** according to requirement F11141. So we do not need to make a
5306 ** copy of the filename. */
5307 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005308 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005309 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005310 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005311 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005312 if( rc!=SQLITE_OK ){
5313 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005314 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005315 h = -1;
5316 }
drh7708e972008-11-29 00:56:52 +00005317 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005318 }
drh7708e972008-11-29 00:56:52 +00005319 }
5320#endif
danielk1977e339d652008-06-28 11:23:00 +00005321
drh7708e972008-11-29 00:56:52 +00005322 else if( pLockingStyle == &dotlockIoMethods ){
5323 /* Dotfile locking uses the file path so it needs to be included in
5324 ** the dotlockLockingContext
5325 */
5326 char *zLockFile;
5327 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005328 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005329 nFilename = (int)strlen(zFilename) + 6;
drhf3cdcdc2015-04-29 16:50:28 +00005330 zLockFile = (char *)sqlite3_malloc64(nFilename);
drh7708e972008-11-29 00:56:52 +00005331 if( zLockFile==0 ){
5332 rc = SQLITE_NOMEM;
5333 }else{
5334 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005335 }
drh7708e972008-11-29 00:56:52 +00005336 pNew->lockingContext = zLockFile;
5337 }
danielk1977e339d652008-06-28 11:23:00 +00005338
drh6c7d5c52008-11-21 20:32:33 +00005339#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005340 else if( pLockingStyle == &semIoMethods ){
5341 /* Named semaphore locking uses the file path so it needs to be
5342 ** included in the semLockingContext
5343 */
5344 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005345 rc = findInodeInfo(pNew, &pNew->pInode);
5346 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5347 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005348 int n;
drh2238dcc2009-08-27 17:56:20 +00005349 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005350 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005351 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005352 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005353 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5354 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00005355 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00005356 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005357 }
chw97185482008-11-17 08:05:31 +00005358 }
drh7708e972008-11-29 00:56:52 +00005359 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005360 }
drh7708e972008-11-29 00:56:52 +00005361#endif
aswift5b1a2562008-08-22 00:22:35 +00005362
drh4bf66fd2015-02-19 02:43:02 +00005363 storeLastErrno(pNew, 0);
drh6c7d5c52008-11-21 20:32:33 +00005364#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005365 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005366 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005367 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005368 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005369 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005370 }
chw97185482008-11-17 08:05:31 +00005371#endif
danielk1977e339d652008-06-28 11:23:00 +00005372 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005373 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005374 }else{
drh7708e972008-11-29 00:56:52 +00005375 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005376 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005377 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005378 }
danielk1977e339d652008-06-28 11:23:00 +00005379 return rc;
drh054889e2005-11-30 03:20:31 +00005380}
drh9c06c952005-11-26 00:25:00 +00005381
danielk1977ad94b582007-08-20 06:44:22 +00005382/*
drh8b3cf822010-06-01 21:02:51 +00005383** Return the name of a directory in which to put temporary files.
5384** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005385*/
drh7234c6d2010-06-19 15:10:09 +00005386static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005387 static const char *azDirs[] = {
5388 0,
aswiftaebf4132008-11-21 00:10:35 +00005389 0,
danielk197717b90b52008-06-06 11:11:25 +00005390 "/var/tmp",
5391 "/usr/tmp",
5392 "/tmp",
drhb7e50ad2015-11-28 21:49:53 +00005393 "."
danielk197717b90b52008-06-06 11:11:25 +00005394 };
drh8b3cf822010-06-01 21:02:51 +00005395 unsigned int i;
5396 struct stat buf;
drhb7e50ad2015-11-28 21:49:53 +00005397 const char *zDir = sqlite3_temp_directory;
drh8b3cf822010-06-01 21:02:51 +00005398
drhb7e50ad2015-11-28 21:49:53 +00005399 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
5400 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005401 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005402 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005403 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005404 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005405 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005406 break;
5407 }
5408 return zDir;
5409}
5410
5411/*
5412** Create a temporary file name in zBuf. zBuf must be allocated
5413** by the calling process and must be big enough to hold at least
5414** pVfs->mxPathname bytes.
5415*/
5416static int unixGetTempname(int nBuf, char *zBuf){
drh8b3cf822010-06-01 21:02:51 +00005417 const char *zDir;
drhb7e50ad2015-11-28 21:49:53 +00005418 int iLimit = 0;
danielk197717b90b52008-06-06 11:11:25 +00005419
5420 /* It's odd to simulate an io-error here, but really this is just
5421 ** using the io-error infrastructure to test that SQLite handles this
5422 ** function failing.
5423 */
5424 SimulateIOError( return SQLITE_IOERR );
5425
drh7234c6d2010-06-19 15:10:09 +00005426 zDir = unixTempFileDir();
danielk197717b90b52008-06-06 11:11:25 +00005427 do{
drh970942e2015-11-25 23:13:14 +00005428 u64 r;
5429 sqlite3_randomness(sizeof(r), &r);
5430 assert( nBuf>2 );
5431 zBuf[nBuf-2] = 0;
5432 sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
5433 zDir, r, 0);
drhb7e50ad2015-11-28 21:49:53 +00005434 if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
drh99ab3b12011-03-02 15:09:07 +00005435 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005436 return SQLITE_OK;
5437}
5438
drhd2cb50b2009-01-09 21:41:17 +00005439#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005440/*
5441** Routine to transform a unixFile into a proxy-locking unixFile.
5442** Implementation in the proxy-lock division, but used by unixOpen()
5443** if SQLITE_PREFER_PROXY_LOCKING is defined.
5444*/
5445static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005446#endif
drhc66d5b62008-12-03 22:48:32 +00005447
dan08da86a2009-08-21 17:18:03 +00005448/*
5449** Search for an unused file descriptor that was opened on the database
5450** file (not a journal or master-journal file) identified by pathname
5451** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5452** argument to this function.
5453**
5454** Such a file descriptor may exist if a database connection was closed
5455** but the associated file descriptor could not be closed because some
5456** other file descriptor open on the same file is holding a file-lock.
5457** Refer to comments in the unixClose() function and the lengthy comment
5458** describing "Posix Advisory Locking" at the start of this file for
5459** further details. Also, ticket #4018.
5460**
5461** If a suitable file descriptor is found, then it is returned. If no
5462** such file descriptor is located, -1 is returned.
5463*/
dane946c392009-08-22 11:39:46 +00005464static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5465 UnixUnusedFd *pUnused = 0;
5466
5467 /* Do not search for an unused file descriptor on vxworks. Not because
5468 ** vxworks would not benefit from the change (it might, we're not sure),
5469 ** but because no way to test it is currently available. It is better
5470 ** not to risk breaking vxworks support for the sake of such an obscure
5471 ** feature. */
5472#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005473 struct stat sStat; /* Results of stat() call */
5474
5475 /* A stat() call may fail for various reasons. If this happens, it is
5476 ** almost certain that an open() call on the same path will also fail.
5477 ** For this reason, if an error occurs in the stat() call here, it is
5478 ** ignored and -1 is returned. The caller will try to open a new file
5479 ** descriptor on the same path, fail, and return an error to SQLite.
5480 **
5481 ** Even if a subsequent open() call does succeed, the consequences of
peter.d.reid60ec9142014-09-06 16:39:46 +00005482 ** not searching for a reusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005483 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005484 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005485
5486 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005487 pInode = inodeList;
5488 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5489 || pInode->fileId.ino!=sStat.st_ino) ){
5490 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005491 }
drh8af6c222010-05-14 12:43:01 +00005492 if( pInode ){
dane946c392009-08-22 11:39:46 +00005493 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005494 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005495 pUnused = *pp;
5496 if( pUnused ){
5497 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005498 }
5499 }
5500 unixLeaveMutex();
5501 }
dane946c392009-08-22 11:39:46 +00005502#endif /* if !OS_VXWORKS */
5503 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005504}
danielk197717b90b52008-06-06 11:11:25 +00005505
5506/*
danddb0ac42010-07-14 14:48:58 +00005507** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005508** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005509** and a value suitable for passing as the third argument to open(2) is
5510** written to *pMode. If an IO error occurs, an SQLite error code is
5511** returned and the value of *pMode is not modified.
5512**
peter.d.reid60ec9142014-09-06 16:39:46 +00005513** In most cases, this routine sets *pMode to 0, which will become
drh8c815d12012-02-13 20:16:37 +00005514** an indication to robust_open() to create the file using
5515** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5516** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005517** this function queries the file-system for the permissions on the
5518** corresponding database file and sets *pMode to this value. Whenever
5519** possible, WAL and journal files are created using the same permissions
5520** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005521**
5522** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5523** original filename is unavailable. But 8_3_NAMES is only used for
5524** FAT filesystems and permissions do not matter there, so just use
5525** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005526*/
5527static int findCreateFileMode(
5528 const char *zPath, /* Path of file (possibly) being created */
5529 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005530 mode_t *pMode, /* OUT: Permissions to open file with */
5531 uid_t *pUid, /* OUT: uid to set on the file */
5532 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005533){
5534 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005535 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005536 *pUid = 0;
5537 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005538 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005539 char zDb[MAX_PATHNAME+1]; /* Database file path */
5540 int nDb; /* Number of valid bytes in zDb */
5541 struct stat sStat; /* Output of stat() on database file */
5542
dana0c989d2010-11-05 18:07:37 +00005543 /* zPath is a path to a WAL or journal file. The following block derives
5544 ** the path to the associated database file from zPath. This block handles
5545 ** the following naming conventions:
5546 **
5547 ** "<path to db>-journal"
5548 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005549 ** "<path to db>-journalNN"
5550 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005551 **
drhd337c5b2011-10-20 18:23:35 +00005552 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005553 ** used by the test_multiplex.c module.
5554 */
5555 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005556 while( zPath[nDb]!='-' ){
drh90e5dda2015-12-03 20:42:28 +00005557#ifndef SQLITE_ENABLE_8_3_NAMES
5558 /* In the normal case (8+3 filenames disabled) the journal filename
5559 ** is guaranteed to contain a '-' character. */
drhc47167a2011-10-05 15:26:13 +00005560 assert( nDb>0 );
drh90e5dda2015-12-03 20:42:28 +00005561 assert( sqlite3Isalnum(zPath[nDb]) );
5562#else
5563 /* If 8+3 names are possible, then the journal file might not contain
5564 ** a '-' character. So check for that case and return early. */
5565 if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
5566#endif
drhc47167a2011-10-05 15:26:13 +00005567 nDb--;
5568 }
danddb0ac42010-07-14 14:48:58 +00005569 memcpy(zDb, zPath, nDb);
5570 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005571
drh58384f12011-07-28 00:14:45 +00005572 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005573 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005574 *pUid = sStat.st_uid;
5575 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005576 }else{
5577 rc = SQLITE_IOERR_FSTAT;
5578 }
5579 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5580 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005581 }
5582 return rc;
5583}
5584
5585/*
danielk1977ad94b582007-08-20 06:44:22 +00005586** Open the file zPath.
5587**
danielk1977b4b47412007-08-17 15:53:36 +00005588** Previously, the SQLite OS layer used three functions in place of this
5589** one:
5590**
5591** sqlite3OsOpenReadWrite();
5592** sqlite3OsOpenReadOnly();
5593** sqlite3OsOpenExclusive();
5594**
5595** These calls correspond to the following combinations of flags:
5596**
5597** ReadWrite() -> (READWRITE | CREATE)
5598** ReadOnly() -> (READONLY)
5599** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5600**
5601** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5602** true, the file was configured to be automatically deleted when the
5603** file handle closed. To achieve the same effect using this new
5604** interface, add the DELETEONCLOSE flag to those specified above for
5605** OpenExclusive().
5606*/
5607static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005608 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5609 const char *zPath, /* Pathname of file to be opened */
5610 sqlite3_file *pFile, /* The file descriptor to be filled in */
5611 int flags, /* Input flags to control the opening */
5612 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005613){
dan08da86a2009-08-21 17:18:03 +00005614 unixFile *p = (unixFile *)pFile;
5615 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005616 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005617 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005618 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005619 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005620 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005621
5622 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5623 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5624 int isCreate = (flags & SQLITE_OPEN_CREATE);
5625 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5626 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005627#if SQLITE_ENABLE_LOCKING_STYLE
5628 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5629#endif
drh3d4435b2011-08-26 20:55:50 +00005630#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5631 struct statfs fsInfo;
5632#endif
danielk1977b4b47412007-08-17 15:53:36 +00005633
danielk1977fee2d252007-08-18 10:59:19 +00005634 /* If creating a master or main-file journal, this function will open
5635 ** a file-descriptor on the directory too. The first time unixSync()
5636 ** is called the directory file descriptor will be fsync()ed and close()d.
5637 */
drh0059eae2011-08-08 23:48:40 +00005638 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005639 eType==SQLITE_OPEN_MASTER_JOURNAL
5640 || eType==SQLITE_OPEN_MAIN_JOURNAL
5641 || eType==SQLITE_OPEN_WAL
5642 ));
danielk1977fee2d252007-08-18 10:59:19 +00005643
danielk197717b90b52008-06-06 11:11:25 +00005644 /* If argument zPath is a NULL pointer, this function is required to open
5645 ** a temporary file. Use this buffer to store the file name in.
5646 */
drhc02a43a2012-01-10 23:18:38 +00005647 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005648 const char *zName = zPath;
5649
danielk1977fee2d252007-08-18 10:59:19 +00005650 /* Check the following statements are true:
5651 **
5652 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5653 ** (b) if CREATE is set, then READWRITE must also be set, and
5654 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005655 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005656 */
danielk1977b4b47412007-08-17 15:53:36 +00005657 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005658 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005659 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005660 assert(isDelete==0 || isCreate);
5661
danddb0ac42010-07-14 14:48:58 +00005662 /* The main DB, main journal, WAL file and master journal are never
5663 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005664 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5665 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5666 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005667 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005668
danielk1977fee2d252007-08-18 10:59:19 +00005669 /* Assert that the upper layer has set one of the "file-type" flags. */
5670 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5671 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5672 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005673 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005674 );
5675
drhb00d8622014-01-01 15:18:36 +00005676 /* Detect a pid change and reset the PRNG. There is a race condition
5677 ** here such that two or more threads all trying to open databases at
5678 ** the same instant might all reset the PRNG. But multiple resets
5679 ** are harmless.
5680 */
drh5ac93652015-03-21 20:59:43 +00005681 if( randomnessPid!=osGetpid(0) ){
5682 randomnessPid = osGetpid(0);
drhb00d8622014-01-01 15:18:36 +00005683 sqlite3_randomness(0,0);
5684 }
5685
dan08da86a2009-08-21 17:18:03 +00005686 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005687
dan08da86a2009-08-21 17:18:03 +00005688 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005689 UnixUnusedFd *pUnused;
5690 pUnused = findReusableFd(zName, flags);
5691 if( pUnused ){
5692 fd = pUnused->fd;
5693 }else{
drhf3cdcdc2015-04-29 16:50:28 +00005694 pUnused = sqlite3_malloc64(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005695 if( !pUnused ){
5696 return SQLITE_NOMEM;
5697 }
5698 }
5699 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005700
5701 /* Database filenames are double-zero terminated if they are not
5702 ** URIs with parameters. Hence, they can always be passed into
5703 ** sqlite3_uri_parameter(). */
5704 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5705
dan08da86a2009-08-21 17:18:03 +00005706 }else if( !zName ){
5707 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005708 assert(isDelete && !syncDir);
drhb7e50ad2015-11-28 21:49:53 +00005709 rc = unixGetTempname(pVfs->mxPathname, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005710 if( rc!=SQLITE_OK ){
5711 return rc;
5712 }
5713 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005714
5715 /* Generated temporary filenames are always double-zero terminated
5716 ** for use by sqlite3_uri_parameter(). */
5717 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005718 }
5719
dan08da86a2009-08-21 17:18:03 +00005720 /* Determine the value of the flags parameter passed to POSIX function
5721 ** open(). These must be calculated even if open() is not called, as
5722 ** they may be stored as part of the file handle and used by the
5723 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005724 if( isReadonly ) openFlags |= O_RDONLY;
5725 if( isReadWrite ) openFlags |= O_RDWR;
5726 if( isCreate ) openFlags |= O_CREAT;
5727 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5728 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005729
danielk1977b4b47412007-08-17 15:53:36 +00005730 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005731 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005732 uid_t uid; /* Userid for the file */
5733 gid_t gid; /* Groupid for the file */
5734 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005735 if( rc!=SQLITE_OK ){
5736 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005737 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005738 return rc;
5739 }
drhad4f1e52011-03-04 15:43:57 +00005740 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005741 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
drh5a2d9702015-11-26 02:21:05 +00005742 assert( !isExclusive || (openFlags & O_CREAT)!=0 );
5743 if( fd<0 && errno!=EISDIR && isReadWrite ){
dan08da86a2009-08-21 17:18:03 +00005744 /* Failed to open the file for read/write access. Try read-only. */
5745 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005746 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005747 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005748 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005749 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005750 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005751 }
5752 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005753 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005754 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005755 }
drhac7c3ac2012-02-11 19:23:48 +00005756
5757 /* If this process is running as root and if creating a new rollback
5758 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005759 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005760 */
5761 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drh6226ca22015-11-24 15:06:28 +00005762 robustFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005763 }
danielk1977b4b47412007-08-17 15:53:36 +00005764 }
dan08da86a2009-08-21 17:18:03 +00005765 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005766 if( pOutFlags ){
5767 *pOutFlags = flags;
5768 }
5769
dane946c392009-08-22 11:39:46 +00005770 if( p->pUnused ){
5771 p->pUnused->fd = fd;
5772 p->pUnused->flags = flags;
5773 }
5774
danielk1977b4b47412007-08-17 15:53:36 +00005775 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005776#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005777 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00005778#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
5779 zPath = sqlite3_mprintf("%s", zName);
5780 if( zPath==0 ){
5781 robust_close(p, fd, __LINE__);
5782 return SQLITE_NOMEM;
5783 }
chw97185482008-11-17 08:05:31 +00005784#else
drh036ac7f2011-08-08 23:18:05 +00005785 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005786#endif
danielk1977b4b47412007-08-17 15:53:36 +00005787 }
drh41022642008-11-21 00:24:42 +00005788#if SQLITE_ENABLE_LOCKING_STYLE
5789 else{
dan08da86a2009-08-21 17:18:03 +00005790 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005791 }
5792#endif
5793
drhda0e7682008-07-30 15:27:54 +00005794 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005795
drh7ed97b92010-01-20 13:07:21 +00005796
5797#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005798 if( fstatfs(fd, &fsInfo) == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00005799 storeLastErrno(p, errno);
drh0e9365c2011-03-02 02:08:13 +00005800 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005801 return SQLITE_IOERR_ACCESS;
5802 }
5803 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5804 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5805 }
drh4bf66fd2015-02-19 02:43:02 +00005806 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
5807 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5808 }
drh7ed97b92010-01-20 13:07:21 +00005809#endif
drhc02a43a2012-01-10 23:18:38 +00005810
5811 /* Set up appropriate ctrlFlags */
5812 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5813 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5814 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5815 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5816 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5817
drh7ed97b92010-01-20 13:07:21 +00005818#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005819#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005820 isAutoProxy = 1;
5821#endif
5822 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005823 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5824 int useProxy = 0;
5825
dan08da86a2009-08-21 17:18:03 +00005826 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5827 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005828 if( envforce!=NULL ){
5829 useProxy = atoi(envforce)>0;
5830 }else{
aswiftaebf4132008-11-21 00:10:35 +00005831 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5832 }
5833 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005834 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005835 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005836 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005837 if( rc!=SQLITE_OK ){
5838 /* Use unixClose to clean up the resources added in fillInUnixFile
5839 ** and clear all the structure's references. Specifically,
5840 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5841 */
5842 unixClose(pFile);
5843 return rc;
5844 }
aswiftaebf4132008-11-21 00:10:35 +00005845 }
dane946c392009-08-22 11:39:46 +00005846 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005847 }
5848 }
5849#endif
5850
drhc02a43a2012-01-10 23:18:38 +00005851 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5852
dane946c392009-08-22 11:39:46 +00005853open_finished:
5854 if( rc!=SQLITE_OK ){
5855 sqlite3_free(p->pUnused);
5856 }
5857 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005858}
5859
dane946c392009-08-22 11:39:46 +00005860
danielk1977b4b47412007-08-17 15:53:36 +00005861/*
danielk1977fee2d252007-08-18 10:59:19 +00005862** Delete the file at zPath. If the dirSync argument is true, fsync()
5863** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005864*/
drh6b9d6dd2008-12-03 19:34:47 +00005865static int unixDelete(
5866 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5867 const char *zPath, /* Name of file to be deleted */
5868 int dirSync /* If true, fsync() directory after deleting file */
5869){
danielk1977fee2d252007-08-18 10:59:19 +00005870 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005871 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005872 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005873 if( osUnlink(zPath)==(-1) ){
drhbd945542014-08-13 11:39:42 +00005874 if( errno==ENOENT
5875#if OS_VXWORKS
drh19541f32014-09-01 13:37:55 +00005876 || osAccess(zPath,0)!=0
drhbd945542014-08-13 11:39:42 +00005877#endif
5878 ){
dan9fc5b4a2012-11-09 20:17:26 +00005879 rc = SQLITE_IOERR_DELETE_NOENT;
5880 }else{
drhb4308162012-11-09 21:40:02 +00005881 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005882 }
drhb4308162012-11-09 21:40:02 +00005883 return rc;
drh5d4feff2010-07-14 01:45:22 +00005884 }
danielk1977d39fa702008-10-16 13:27:40 +00005885#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005886 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005887 int fd;
drh90315a22011-08-10 01:52:12 +00005888 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005889 if( rc==SQLITE_OK ){
drh6d258992016-02-04 09:48:12 +00005890 if( full_fsync(fd,0,0) ){
dane18d4952011-02-21 11:46:24 +00005891 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005892 }
drh0e9365c2011-03-02 02:08:13 +00005893 robust_close(0, fd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00005894 }else{
5895 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00005896 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005897 }
5898 }
danielk1977d138dd82008-10-15 16:02:48 +00005899#endif
danielk1977fee2d252007-08-18 10:59:19 +00005900 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005901}
5902
danielk197790949c22007-08-17 16:50:38 +00005903/*
mistachkin48864df2013-03-21 21:20:32 +00005904** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00005905** test performed depends on the value of flags:
5906**
5907** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5908** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5909** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5910**
5911** Otherwise return 0.
5912*/
danielk1977861f7452008-06-05 11:39:11 +00005913static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005914 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5915 const char *zPath, /* Path of the file to examine */
5916 int flags, /* What do we want to learn about the zPath file? */
5917 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005918){
danielk1977397d65f2008-11-19 11:35:39 +00005919 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005920 SimulateIOError( return SQLITE_IOERR_ACCESS; );
drhd260b5b2015-11-25 18:03:33 +00005921 assert( pResOut!=0 );
danielk1977b4b47412007-08-17 15:53:36 +00005922
drhd260b5b2015-11-25 18:03:33 +00005923 /* The spec says there are three possible values for flags. But only
5924 ** two of them are actually used */
5925 assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
5926
5927 if( flags==SQLITE_ACCESS_EXISTS ){
dan83acd422010-06-18 11:10:06 +00005928 struct stat buf;
drhd260b5b2015-11-25 18:03:33 +00005929 *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
5930 }else{
5931 *pResOut = osAccess(zPath, W_OK|R_OK)==0;
dan83acd422010-06-18 11:10:06 +00005932 }
danielk1977861f7452008-06-05 11:39:11 +00005933 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005934}
5935
danielk1977b4b47412007-08-17 15:53:36 +00005936/*
danielk1977b4b47412007-08-17 15:53:36 +00005937**
danielk1977b4b47412007-08-17 15:53:36 +00005938*/
dane88ec182016-01-25 17:04:48 +00005939static int mkFullPathname(
dancaf6b152016-01-25 18:05:49 +00005940 const char *zPath, /* Input path */
5941 char *zOut, /* Output buffer */
dane88ec182016-01-25 17:04:48 +00005942 int nOut /* Allocated size of buffer zOut */
danielk1977adfb9b02007-09-17 07:02:56 +00005943){
dancaf6b152016-01-25 18:05:49 +00005944 int nPath = sqlite3Strlen30(zPath);
5945 int iOff = 0;
5946 if( zPath[0]!='/' ){
5947 if( osGetcwd(zOut, nOut-2)==0 ){
dane18d4952011-02-21 11:46:24 +00005948 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005949 }
dancaf6b152016-01-25 18:05:49 +00005950 iOff = sqlite3Strlen30(zOut);
5951 zOut[iOff++] = '/';
danielk1977b4b47412007-08-17 15:53:36 +00005952 }
dan23496702016-01-26 13:56:42 +00005953 if( (iOff+nPath+1)>nOut ){
5954 /* SQLite assumes that xFullPathname() nul-terminates the output buffer
5955 ** even if it returns an error. */
5956 zOut[iOff] = '\0';
5957 return SQLITE_CANTOPEN_BKPT;
5958 }
dancaf6b152016-01-25 18:05:49 +00005959 sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005960 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005961}
5962
dane88ec182016-01-25 17:04:48 +00005963/*
5964** Turn a relative pathname into a full pathname. The relative path
5965** is stored as a nul-terminated string in the buffer pointed to by
5966** zPath.
5967**
5968** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5969** (in this case, MAX_PATHNAME bytes). The full-path is written to
5970** this buffer before returning.
5971*/
5972static int unixFullPathname(
5973 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5974 const char *zPath, /* Possibly relative input path */
5975 int nOut, /* Size of output buffer in bytes */
5976 char *zOut /* Output buffer */
5977){
danaf1b36b2016-01-25 18:43:05 +00005978#if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
dancaf6b152016-01-25 18:05:49 +00005979 return mkFullPathname(zPath, zOut, nOut);
dane88ec182016-01-25 17:04:48 +00005980#else
5981 int rc = SQLITE_OK;
5982 int nByte;
dancaf6b152016-01-25 18:05:49 +00005983 int nLink = 1; /* Number of symbolic links followed so far */
dane88ec182016-01-25 17:04:48 +00005984 const char *zIn = zPath; /* Input path for each iteration of loop */
5985 char *zDel = 0;
5986
5987 assert( pVfs->mxPathname==MAX_PATHNAME );
5988 UNUSED_PARAMETER(pVfs);
5989
5990 /* It's odd to simulate an io-error here, but really this is just
5991 ** using the io-error infrastructure to test that SQLite handles this
5992 ** function failing. This function could fail if, for example, the
5993 ** current working directory has been unlinked.
5994 */
5995 SimulateIOError( return SQLITE_ERROR );
5996
5997 do {
5998
dancaf6b152016-01-25 18:05:49 +00005999 /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
6000 ** link, or false otherwise. */
6001 int bLink = 0;
6002 struct stat buf;
6003 if( osLstat(zIn, &buf)!=0 ){
6004 if( errno!=ENOENT ){
danaf1b36b2016-01-25 18:43:05 +00006005 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
dane88ec182016-01-25 17:04:48 +00006006 }
dane88ec182016-01-25 17:04:48 +00006007 }else{
dancaf6b152016-01-25 18:05:49 +00006008 bLink = S_ISLNK(buf.st_mode);
6009 }
6010
6011 if( bLink ){
dane88ec182016-01-25 17:04:48 +00006012 if( zDel==0 ){
6013 zDel = sqlite3_malloc(nOut);
6014 if( zDel==0 ) rc = SQLITE_NOMEM;
dancaf6b152016-01-25 18:05:49 +00006015 }else if( ++nLink>SQLITE_MAX_SYMLINKS ){
6016 rc = SQLITE_CANTOPEN_BKPT;
dane88ec182016-01-25 17:04:48 +00006017 }
dancaf6b152016-01-25 18:05:49 +00006018
6019 if( rc==SQLITE_OK ){
6020 nByte = osReadlink(zIn, zDel, nOut-1);
6021 if( nByte<0 ){
6022 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
dan23496702016-01-26 13:56:42 +00006023 }else{
6024 if( zDel[0]!='/' ){
6025 int n;
6026 for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
6027 if( nByte+n+1>nOut ){
6028 rc = SQLITE_CANTOPEN_BKPT;
6029 }else{
6030 memmove(&zDel[n], zDel, nByte+1);
6031 memcpy(zDel, zIn, n);
6032 nByte += n;
6033 }
dancaf6b152016-01-25 18:05:49 +00006034 }
6035 zDel[nByte] = '\0';
6036 }
6037 }
6038
6039 zIn = zDel;
dane88ec182016-01-25 17:04:48 +00006040 }
6041
dan23496702016-01-26 13:56:42 +00006042 assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
6043 if( rc==SQLITE_OK && zIn!=zOut ){
dancaf6b152016-01-25 18:05:49 +00006044 rc = mkFullPathname(zIn, zOut, nOut);
dane88ec182016-01-25 17:04:48 +00006045 }
dancaf6b152016-01-25 18:05:49 +00006046 if( bLink==0 ) break;
6047 zIn = zOut;
6048 }while( rc==SQLITE_OK );
dane88ec182016-01-25 17:04:48 +00006049
6050 sqlite3_free(zDel);
6051 return rc;
danaf1b36b2016-01-25 18:43:05 +00006052#endif /* HAVE_READLINK && HAVE_LSTAT */
dane88ec182016-01-25 17:04:48 +00006053}
6054
drh0ccebe72005-06-07 22:22:50 +00006055
drh761df872006-12-21 01:29:22 +00006056#ifndef SQLITE_OMIT_LOAD_EXTENSION
6057/*
6058** Interfaces for opening a shared library, finding entry points
6059** within the shared library, and closing the shared library.
6060*/
6061#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00006062static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6063 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00006064 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6065}
danielk197795c8a542007-09-01 06:51:27 +00006066
6067/*
6068** SQLite calls this function immediately after a call to unixDlSym() or
6069** unixDlOpen() fails (returns a null pointer). If a more detailed error
6070** message is available, it is written to zBufOut. If no error message
6071** is available, zBufOut is left unmodified and SQLite uses a default
6072** error message.
6073*/
danielk1977397d65f2008-11-19 11:35:39 +00006074static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006075 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006076 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006077 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006078 zErr = dlerror();
6079 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006080 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006081 }
drh6c7d5c52008-11-21 20:32:33 +00006082 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006083}
drh1875f7a2008-12-08 18:19:17 +00006084static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6085 /*
6086 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6087 ** cast into a pointer to a function. And yet the library dlsym() routine
6088 ** returns a void* which is really a pointer to a function. So how do we
6089 ** use dlsym() with -pedantic-errors?
6090 **
6091 ** Variable x below is defined to be a pointer to a function taking
6092 ** parameters void* and const char* and returning a pointer to a function.
6093 ** We initialize x by assigning it a pointer to the dlsym() function.
6094 ** (That assignment requires a cast.) Then we call the function that
6095 ** x points to.
6096 **
6097 ** This work-around is unlikely to work correctly on any system where
6098 ** you really cannot cast a function pointer into void*. But then, on the
6099 ** other hand, dlsym() will not work on such a system either, so we have
6100 ** not really lost anything.
6101 */
6102 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006103 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006104 x = (void(*(*)(void*,const char*))(void))dlsym;
6105 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006106}
danielk1977397d65f2008-11-19 11:35:39 +00006107static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6108 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006109 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006110}
danielk1977b4b47412007-08-17 15:53:36 +00006111#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6112 #define unixDlOpen 0
6113 #define unixDlError 0
6114 #define unixDlSym 0
6115 #define unixDlClose 0
6116#endif
6117
6118/*
danielk197790949c22007-08-17 16:50:38 +00006119** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006120*/
danielk1977397d65f2008-11-19 11:35:39 +00006121static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6122 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006123 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006124
drhbbd42a62004-05-22 17:41:58 +00006125 /* We have to initialize zBuf to prevent valgrind from reporting
6126 ** errors. The reports issued by valgrind are incorrect - we would
6127 ** prefer that the randomness be increased by making use of the
6128 ** uninitialized space in zBuf - but valgrind errors tend to worry
6129 ** some users. Rather than argue, it seems easier just to initialize
6130 ** the whole array and silence valgrind, even if that means less randomness
6131 ** in the random seed.
6132 **
6133 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006134 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006135 ** tests repeatable.
6136 */
danielk1977b4b47412007-08-17 15:53:36 +00006137 memset(zBuf, 0, nBuf);
drh5ac93652015-03-21 20:59:43 +00006138 randomnessPid = osGetpid(0);
drh6a412b82015-04-30 12:31:49 +00006139#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
drhbbd42a62004-05-22 17:41:58 +00006140 {
drhb00d8622014-01-01 15:18:36 +00006141 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006142 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006143 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006144 time_t t;
6145 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006146 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006147 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6148 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6149 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006150 }else{
drhc18b4042012-02-10 03:10:27 +00006151 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006152 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006153 }
drhbbd42a62004-05-22 17:41:58 +00006154 }
6155#endif
drh72cbd072008-10-14 17:58:38 +00006156 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006157}
6158
danielk1977b4b47412007-08-17 15:53:36 +00006159
drhbbd42a62004-05-22 17:41:58 +00006160/*
6161** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006162** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006163** The return value is the number of microseconds of sleep actually
6164** requested from the underlying operating system, a number which
6165** might be greater than or equal to the argument, but not less
6166** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006167*/
danielk1977397d65f2008-11-19 11:35:39 +00006168static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006169#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006170 struct timespec sp;
6171
6172 sp.tv_sec = microseconds / 1000000;
6173 sp.tv_nsec = (microseconds % 1000000) * 1000;
6174 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006175 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006176 return microseconds;
6177#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006178 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006179 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006180 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006181#else
danielk1977b4b47412007-08-17 15:53:36 +00006182 int seconds = (microseconds+999999)/1000000;
6183 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006184 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006185 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006186#endif
drh88f474a2006-01-02 20:00:12 +00006187}
6188
6189/*
drh6b9d6dd2008-12-03 19:34:47 +00006190** The following variable, if set to a non-zero value, is interpreted as
6191** the number of seconds since 1970 and is used to set the result of
6192** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006193*/
6194#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006195int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006196#endif
6197
6198/*
drhb7e8ea22010-05-03 14:32:30 +00006199** Find the current time (in Universal Coordinated Time). Write into *piNow
6200** the current time and date as a Julian Day number times 86_400_000. In
6201** other words, write into *piNow the number of milliseconds since the Julian
6202** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6203** proleptic Gregorian calendar.
6204**
drh31702252011-10-12 23:13:43 +00006205** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6206** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006207*/
6208static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6209 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006210 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006211#if defined(NO_GETTOD)
6212 time_t t;
6213 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006214 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006215#elif OS_VXWORKS
6216 struct timespec sNow;
6217 clock_gettime(CLOCK_REALTIME, &sNow);
6218 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6219#else
6220 struct timeval sNow;
drh970942e2015-11-25 23:13:14 +00006221 (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
6222 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
drhb7e8ea22010-05-03 14:32:30 +00006223#endif
6224
6225#ifdef SQLITE_TEST
6226 if( sqlite3_current_time ){
6227 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6228 }
6229#endif
6230 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006231 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006232}
6233
drhc3dfa5e2016-01-22 19:44:03 +00006234#ifndef SQLITE_OMIT_DEPRECATED
drhb7e8ea22010-05-03 14:32:30 +00006235/*
drhbbd42a62004-05-22 17:41:58 +00006236** Find the current time (in Universal Coordinated Time). Write the
6237** current time and date as a Julian Day number into *prNow and
6238** return 0. Return 1 if the time and date cannot be found.
6239*/
danielk1977397d65f2008-11-19 11:35:39 +00006240static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006241 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006242 int rc;
drhff828942010-06-26 21:34:06 +00006243 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006244 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006245 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006246 return rc;
drhbbd42a62004-05-22 17:41:58 +00006247}
drh5337dac2015-11-25 15:15:03 +00006248#else
6249# define unixCurrentTime 0
6250#endif
danielk1977b4b47412007-08-17 15:53:36 +00006251
drhc3dfa5e2016-01-22 19:44:03 +00006252#ifndef SQLITE_OMIT_DEPRECATED
drh6b9d6dd2008-12-03 19:34:47 +00006253/*
6254** We added the xGetLastError() method with the intention of providing
6255** better low-level error messages when operating-system problems come up
6256** during SQLite operation. But so far, none of that has been implemented
6257** in the core. So this routine is never called. For now, it is merely
6258** a place-holder.
6259*/
danielk1977397d65f2008-11-19 11:35:39 +00006260static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6261 UNUSED_PARAMETER(NotUsed);
6262 UNUSED_PARAMETER(NotUsed2);
6263 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00006264 return 0;
6265}
drh5337dac2015-11-25 15:15:03 +00006266#else
6267# define unixGetLastError 0
6268#endif
danielk1977bcb97fe2008-06-06 15:49:29 +00006269
drhf2424c52010-04-26 00:04:55 +00006270
6271/*
drh734c9862008-11-28 15:37:20 +00006272************************ End of sqlite3_vfs methods ***************************
6273******************************************************************************/
6274
drh715ff302008-12-03 22:32:44 +00006275/******************************************************************************
6276************************** Begin Proxy Locking ********************************
6277**
6278** Proxy locking is a "uber-locking-method" in this sense: It uses the
6279** other locking methods on secondary lock files. Proxy locking is a
6280** meta-layer over top of the primitive locking implemented above. For
6281** this reason, the division that implements of proxy locking is deferred
6282** until late in the file (here) after all of the other I/O methods have
6283** been defined - so that the primitive locking methods are available
6284** as services to help with the implementation of proxy locking.
6285**
6286****
6287**
6288** The default locking schemes in SQLite use byte-range locks on the
6289** database file to coordinate safe, concurrent access by multiple readers
6290** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6291** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6292** as POSIX read & write locks over fixed set of locations (via fsctl),
6293** on AFP and SMB only exclusive byte-range locks are available via fsctl
6294** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6295** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6296** address in the shared range is taken for a SHARED lock, the entire
6297** shared range is taken for an EXCLUSIVE lock):
6298**
drhf2f105d2012-08-20 15:53:54 +00006299** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006300** RESERVED_BYTE 0x40000001
6301** SHARED_RANGE 0x40000002 -> 0x40000200
6302**
6303** This works well on the local file system, but shows a nearly 100x
6304** slowdown in read performance on AFP because the AFP client disables
6305** the read cache when byte-range locks are present. Enabling the read
6306** cache exposes a cache coherency problem that is present on all OS X
6307** supported network file systems. NFS and AFP both observe the
6308** close-to-open semantics for ensuring cache coherency
6309** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6310** address the requirements for concurrent database access by multiple
6311** readers and writers
6312** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6313**
6314** To address the performance and cache coherency issues, proxy file locking
6315** changes the way database access is controlled by limiting access to a
6316** single host at a time and moving file locks off of the database file
6317** and onto a proxy file on the local file system.
6318**
6319**
6320** Using proxy locks
6321** -----------------
6322**
6323** C APIs
6324**
drh4bf66fd2015-02-19 02:43:02 +00006325** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
drh715ff302008-12-03 22:32:44 +00006326** <proxy_path> | ":auto:");
drh4bf66fd2015-02-19 02:43:02 +00006327** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6328** &<proxy_path>);
drh715ff302008-12-03 22:32:44 +00006329**
6330**
6331** SQL pragmas
6332**
6333** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6334** PRAGMA [database.]lock_proxy_file
6335**
6336** Specifying ":auto:" means that if there is a conch file with a matching
6337** host ID in it, the proxy path in the conch file will be used, otherwise
6338** a proxy path based on the user's temp dir
6339** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6340** actual proxy file name is generated from the name and path of the
6341** database file. For example:
6342**
6343** For database path "/Users/me/foo.db"
6344** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6345**
6346** Once a lock proxy is configured for a database connection, it can not
6347** be removed, however it may be switched to a different proxy path via
6348** the above APIs (assuming the conch file is not being held by another
6349** connection or process).
6350**
6351**
6352** How proxy locking works
6353** -----------------------
6354**
6355** Proxy file locking relies primarily on two new supporting files:
6356**
6357** * conch file to limit access to the database file to a single host
6358** at a time
6359**
6360** * proxy file to act as a proxy for the advisory locks normally
6361** taken on the database
6362**
6363** The conch file - to use a proxy file, sqlite must first "hold the conch"
6364** by taking an sqlite-style shared lock on the conch file, reading the
6365** contents and comparing the host's unique host ID (see below) and lock
6366** proxy path against the values stored in the conch. The conch file is
6367** stored in the same directory as the database file and the file name
6368** is patterned after the database file name as ".<databasename>-conch".
peter.d.reid60ec9142014-09-06 16:39:46 +00006369** If the conch file does not exist, or its contents do not match the
drh715ff302008-12-03 22:32:44 +00006370** host ID and/or proxy path, then the lock is escalated to an exclusive
6371** lock and the conch file contents is updated with the host ID and proxy
6372** path and the lock is downgraded to a shared lock again. If the conch
6373** is held by another process (with a shared lock), the exclusive lock
6374** will fail and SQLITE_BUSY is returned.
6375**
6376** The proxy file - a single-byte file used for all advisory file locks
6377** normally taken on the database file. This allows for safe sharing
6378** of the database file for multiple readers and writers on the same
6379** host (the conch ensures that they all use the same local lock file).
6380**
drh715ff302008-12-03 22:32:44 +00006381** Requesting the lock proxy does not immediately take the conch, it is
6382** only taken when the first request to lock database file is made.
6383** This matches the semantics of the traditional locking behavior, where
6384** opening a connection to a database file does not take a lock on it.
6385** The shared lock and an open file descriptor are maintained until
6386** the connection to the database is closed.
6387**
6388** The proxy file and the lock file are never deleted so they only need
6389** to be created the first time they are used.
6390**
6391** Configuration options
6392** ---------------------
6393**
6394** SQLITE_PREFER_PROXY_LOCKING
6395**
6396** Database files accessed on non-local file systems are
6397** automatically configured for proxy locking, lock files are
6398** named automatically using the same logic as
6399** PRAGMA lock_proxy_file=":auto:"
6400**
6401** SQLITE_PROXY_DEBUG
6402**
6403** Enables the logging of error messages during host id file
6404** retrieval and creation
6405**
drh715ff302008-12-03 22:32:44 +00006406** LOCKPROXYDIR
6407**
6408** Overrides the default directory used for lock proxy files that
6409** are named automatically via the ":auto:" setting
6410**
6411** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6412**
6413** Permissions to use when creating a directory for storing the
6414** lock proxy files, only used when LOCKPROXYDIR is not set.
6415**
6416**
6417** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6418** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6419** force proxy locking to be used for every database file opened, and 0
6420** will force automatic proxy locking to be disabled for all database
drh4bf66fd2015-02-19 02:43:02 +00006421** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
drh715ff302008-12-03 22:32:44 +00006422** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6423*/
6424
6425/*
6426** Proxy locking is only available on MacOSX
6427*/
drhd2cb50b2009-01-09 21:41:17 +00006428#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006429
drh715ff302008-12-03 22:32:44 +00006430/*
6431** The proxyLockingContext has the path and file structures for the remote
6432** and local proxy files in it
6433*/
6434typedef struct proxyLockingContext proxyLockingContext;
6435struct proxyLockingContext {
6436 unixFile *conchFile; /* Open conch file */
6437 char *conchFilePath; /* Name of the conch file */
6438 unixFile *lockProxy; /* Open proxy lock file */
6439 char *lockProxyPath; /* Name of the proxy lock file */
6440 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006441 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh4bf66fd2015-02-19 02:43:02 +00006442 int nFails; /* Number of conch taking failures */
drh715ff302008-12-03 22:32:44 +00006443 void *oldLockingContext; /* Original lockingcontext to restore on close */
6444 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6445};
6446
drh7ed97b92010-01-20 13:07:21 +00006447/*
6448** The proxy lock file path for the database at dbPath is written into lPath,
6449** which must point to valid, writable memory large enough for a maxLen length
6450** file path.
drh715ff302008-12-03 22:32:44 +00006451*/
drh715ff302008-12-03 22:32:44 +00006452static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6453 int len;
6454 int dbLen;
6455 int i;
6456
6457#ifdef LOCKPROXYDIR
6458 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6459#else
6460# ifdef _CS_DARWIN_USER_TEMP_DIR
6461 {
drh7ed97b92010-01-20 13:07:21 +00006462 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006463 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006464 lPath, errno, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006465 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006466 }
drh7ed97b92010-01-20 13:07:21 +00006467 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006468 }
6469# else
6470 len = strlcpy(lPath, "/tmp/", maxLen);
6471# endif
6472#endif
6473
6474 if( lPath[len-1]!='/' ){
6475 len = strlcat(lPath, "/", maxLen);
6476 }
6477
6478 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006479 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006480 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006481 char c = dbPath[i];
6482 lPath[i+len] = (c=='/')?'_':c;
6483 }
6484 lPath[i+len]='\0';
6485 strlcat(lPath, ":auto:", maxLen);
drh5ac93652015-03-21 20:59:43 +00006486 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006487 return SQLITE_OK;
6488}
6489
drh7ed97b92010-01-20 13:07:21 +00006490/*
6491 ** Creates the lock file and any missing directories in lockPath
6492 */
6493static int proxyCreateLockPath(const char *lockPath){
6494 int i, len;
6495 char buf[MAXPATHLEN];
6496 int start = 0;
6497
6498 assert(lockPath!=NULL);
6499 /* try to create all the intermediate directories */
6500 len = (int)strlen(lockPath);
6501 buf[0] = lockPath[0];
6502 for( i=1; i<len; i++ ){
6503 if( lockPath[i] == '/' && (i - start > 0) ){
6504 /* only mkdir if leaf dir != "." or "/" or ".." */
6505 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6506 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6507 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006508 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006509 int err=errno;
6510 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006511 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006512 "'%s' proxy lock path=%s pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006513 buf, strerror(err), lockPath, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006514 return err;
6515 }
6516 }
6517 }
6518 start=i+1;
6519 }
6520 buf[i] = lockPath[i];
6521 }
drh62aaa6c2015-11-21 17:27:42 +00006522 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006523 return 0;
6524}
6525
drh715ff302008-12-03 22:32:44 +00006526/*
6527** Create a new VFS file descriptor (stored in memory obtained from
6528** sqlite3_malloc) and open the file named "path" in the file descriptor.
6529**
6530** The caller is responsible not only for closing the file descriptor
6531** but also for freeing the memory associated with the file descriptor.
6532*/
drh7ed97b92010-01-20 13:07:21 +00006533static int proxyCreateUnixFile(
6534 const char *path, /* path for the new unixFile */
6535 unixFile **ppFile, /* unixFile created and returned by ref */
6536 int islockfile /* if non zero missing dirs will be created */
6537) {
6538 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006539 unixFile *pNew;
6540 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006541 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006542 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006543 int terrno = 0;
6544 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006545
drh7ed97b92010-01-20 13:07:21 +00006546 /* 1. first try to open/create the file
6547 ** 2. if that fails, and this is a lock file (not-conch), try creating
6548 ** the parent directories and then try again.
6549 ** 3. if that fails, try to open the file read-only
6550 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6551 */
6552 pUnused = findReusableFd(path, openFlags);
6553 if( pUnused ){
6554 fd = pUnused->fd;
6555 }else{
drhf3cdcdc2015-04-29 16:50:28 +00006556 pUnused = sqlite3_malloc64(sizeof(*pUnused));
drh7ed97b92010-01-20 13:07:21 +00006557 if( !pUnused ){
6558 return SQLITE_NOMEM;
6559 }
6560 }
6561 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006562 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006563 terrno = errno;
6564 if( fd<0 && errno==ENOENT && islockfile ){
6565 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006566 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006567 }
6568 }
6569 }
6570 if( fd<0 ){
6571 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006572 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006573 terrno = errno;
6574 }
6575 if( fd<0 ){
6576 if( islockfile ){
6577 return SQLITE_BUSY;
6578 }
6579 switch (terrno) {
6580 case EACCES:
6581 return SQLITE_PERM;
6582 case EIO:
6583 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6584 default:
drh9978c972010-02-23 17:36:32 +00006585 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006586 }
6587 }
6588
drhf3cdcdc2015-04-29 16:50:28 +00006589 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
drh7ed97b92010-01-20 13:07:21 +00006590 if( pNew==NULL ){
6591 rc = SQLITE_NOMEM;
6592 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006593 }
6594 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006595 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006596 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006597 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006598 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006599 pUnused->fd = fd;
6600 pUnused->flags = openFlags;
6601 pNew->pUnused = pUnused;
6602
drhc02a43a2012-01-10 23:18:38 +00006603 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006604 if( rc==SQLITE_OK ){
6605 *ppFile = pNew;
6606 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006607 }
drh7ed97b92010-01-20 13:07:21 +00006608end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006609 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006610 sqlite3_free(pNew);
6611 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006612 return rc;
6613}
6614
drh7ed97b92010-01-20 13:07:21 +00006615#ifdef SQLITE_TEST
6616/* simulate multiple hosts by creating unique hostid file paths */
6617int sqlite3_hostid_num = 0;
6618#endif
6619
6620#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6621
drh6bca6512015-04-13 23:05:28 +00006622#ifdef HAVE_GETHOSTUUID
drh0ab216a2010-07-02 17:10:40 +00006623/* Not always defined in the headers as it ought to be */
6624extern int gethostuuid(uuid_t id, const struct timespec *wait);
drh6bca6512015-04-13 23:05:28 +00006625#endif
drh0ab216a2010-07-02 17:10:40 +00006626
drh7ed97b92010-01-20 13:07:21 +00006627/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6628** bytes of writable memory.
6629*/
6630static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006631 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6632 memset(pHostID, 0, PROXY_HOSTIDLEN);
drh6bca6512015-04-13 23:05:28 +00006633#ifdef HAVE_GETHOSTUUID
drh29ecd8a2010-12-21 00:16:40 +00006634 {
drh4bf66fd2015-02-19 02:43:02 +00006635 struct timespec timeout = {1, 0}; /* 1 sec timeout */
drh29ecd8a2010-12-21 00:16:40 +00006636 if( gethostuuid(pHostID, &timeout) ){
6637 int err = errno;
6638 if( pError ){
6639 *pError = err;
6640 }
6641 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006642 }
drh7ed97b92010-01-20 13:07:21 +00006643 }
drh3d4435b2011-08-26 20:55:50 +00006644#else
6645 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006646#endif
drh7ed97b92010-01-20 13:07:21 +00006647#ifdef SQLITE_TEST
6648 /* simulate multiple hosts by creating unique hostid file paths */
6649 if( sqlite3_hostid_num != 0){
6650 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6651 }
6652#endif
6653
6654 return SQLITE_OK;
6655}
6656
6657/* The conch file contains the header, host id and lock file path
6658 */
6659#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6660#define PROXY_HEADERLEN 1 /* conch file header length */
6661#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6662#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6663
6664/*
6665** Takes an open conch file, copies the contents to a new path and then moves
6666** it back. The newly created file's file descriptor is assigned to the
6667** conch file structure and finally the original conch file descriptor is
6668** closed. Returns zero if successful.
6669*/
6670static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6671 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6672 unixFile *conchFile = pCtx->conchFile;
6673 char tPath[MAXPATHLEN];
6674 char buf[PROXY_MAXCONCHLEN];
6675 char *cPath = pCtx->conchFilePath;
6676 size_t readLen = 0;
6677 size_t pathLen = 0;
6678 char errmsg[64] = "";
6679 int fd = -1;
6680 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006681 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006682
6683 /* create a new path by replace the trailing '-conch' with '-break' */
6684 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6685 if( pathLen>MAXPATHLEN || pathLen<6 ||
6686 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006687 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006688 goto end_breaklock;
6689 }
6690 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006691 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006692 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006693 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006694 goto end_breaklock;
6695 }
6696 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006697 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006698 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006699 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006700 goto end_breaklock;
6701 }
drhe562be52011-03-02 18:01:10 +00006702 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006703 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006704 goto end_breaklock;
6705 }
6706 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006707 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006708 goto end_breaklock;
6709 }
6710 rc = 0;
6711 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006712 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006713 conchFile->h = fd;
6714 conchFile->openFlags = O_RDWR | O_CREAT;
6715
6716end_breaklock:
6717 if( rc ){
6718 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006719 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006720 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006721 }
6722 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6723 }
6724 return rc;
6725}
6726
6727/* Take the requested lock on the conch file and break a stale lock if the
6728** host id matches.
6729*/
6730static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6731 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6732 unixFile *conchFile = pCtx->conchFile;
6733 int rc = SQLITE_OK;
6734 int nTries = 0;
6735 struct timespec conchModTime;
6736
drh3d4435b2011-08-26 20:55:50 +00006737 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006738 do {
6739 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6740 nTries ++;
6741 if( rc==SQLITE_BUSY ){
6742 /* If the lock failed (busy):
6743 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6744 * 2nd try: fail if the mod time changed or host id is different, wait
6745 * 10 sec and try again
6746 * 3rd try: break the lock unless the mod time has changed.
6747 */
6748 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006749 if( osFstat(conchFile->h, &buf) ){
drh4bf66fd2015-02-19 02:43:02 +00006750 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006751 return SQLITE_IOERR_LOCK;
6752 }
6753
6754 if( nTries==1 ){
6755 conchModTime = buf.st_mtimespec;
6756 usleep(500000); /* wait 0.5 sec and try the lock again*/
6757 continue;
6758 }
6759
6760 assert( nTries>1 );
6761 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6762 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6763 return SQLITE_BUSY;
6764 }
6765
6766 if( nTries==2 ){
6767 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006768 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006769 if( len<0 ){
drh4bf66fd2015-02-19 02:43:02 +00006770 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006771 return SQLITE_IOERR_LOCK;
6772 }
6773 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6774 /* don't break the lock if the host id doesn't match */
6775 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6776 return SQLITE_BUSY;
6777 }
6778 }else{
6779 /* don't break the lock on short read or a version mismatch */
6780 return SQLITE_BUSY;
6781 }
6782 usleep(10000000); /* wait 10 sec and try the lock again */
6783 continue;
6784 }
6785
6786 assert( nTries==3 );
6787 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6788 rc = SQLITE_OK;
6789 if( lockType==EXCLUSIVE_LOCK ){
drhe6d41732015-02-21 00:49:00 +00006790 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
drh7ed97b92010-01-20 13:07:21 +00006791 }
6792 if( !rc ){
6793 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6794 }
6795 }
6796 }
6797 } while( rc==SQLITE_BUSY && nTries<3 );
6798
6799 return rc;
6800}
6801
6802/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006803** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6804** lockPath means that the lockPath in the conch file will be used if the
6805** host IDs match, or a new lock path will be generated automatically
6806** and written to the conch file.
6807*/
6808static int proxyTakeConch(unixFile *pFile){
6809 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6810
drh7ed97b92010-01-20 13:07:21 +00006811 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006812 return SQLITE_OK;
6813 }else{
6814 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006815 uuid_t myHostID;
6816 int pError = 0;
6817 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006818 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006819 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006820 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006821 int createConch = 0;
6822 int hostIdMatch = 0;
6823 int readLen = 0;
6824 int tryOldLockPath = 0;
6825 int forceNewLockPath = 0;
6826
drh308c2a52010-05-14 11:30:18 +00006827 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
drh91eb93c2015-03-03 19:56:20 +00006828 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00006829 osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006830
drh7ed97b92010-01-20 13:07:21 +00006831 rc = proxyGetHostID(myHostID, &pError);
6832 if( (rc&0xff)==SQLITE_IOERR ){
drh4bf66fd2015-02-19 02:43:02 +00006833 storeLastErrno(pFile, pError);
drh7ed97b92010-01-20 13:07:21 +00006834 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006835 }
drh7ed97b92010-01-20 13:07:21 +00006836 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006837 if( rc!=SQLITE_OK ){
6838 goto end_takeconch;
6839 }
drh7ed97b92010-01-20 13:07:21 +00006840 /* read the existing conch file */
6841 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6842 if( readLen<0 ){
6843 /* I/O error: lastErrno set by seekAndRead */
drh4bf66fd2015-02-19 02:43:02 +00006844 storeLastErrno(pFile, conchFile->lastErrno);
drh7ed97b92010-01-20 13:07:21 +00006845 rc = SQLITE_IOERR_READ;
6846 goto end_takeconch;
6847 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6848 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6849 /* a short read or version format mismatch means we need to create a new
6850 ** conch file.
6851 */
6852 createConch = 1;
6853 }
6854 /* if the host id matches and the lock path already exists in the conch
6855 ** we'll try to use the path there, if we can't open that path, we'll
6856 ** retry with a new auto-generated path
6857 */
6858 do { /* in case we need to try again for an :auto: named lock file */
6859
6860 if( !createConch && !forceNewLockPath ){
6861 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6862 PROXY_HOSTIDLEN);
6863 /* if the conch has data compare the contents */
6864 if( !pCtx->lockProxyPath ){
6865 /* for auto-named local lock file, just check the host ID and we'll
6866 ** use the local lock file path that's already in there
6867 */
6868 if( hostIdMatch ){
6869 size_t pathLen = (readLen - PROXY_PATHINDEX);
6870
6871 if( pathLen>=MAXPATHLEN ){
6872 pathLen=MAXPATHLEN-1;
6873 }
6874 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6875 lockPath[pathLen] = 0;
6876 tempLockPath = lockPath;
6877 tryOldLockPath = 1;
6878 /* create a copy of the lock path if the conch is taken */
6879 goto end_takeconch;
6880 }
6881 }else if( hostIdMatch
6882 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6883 readLen-PROXY_PATHINDEX)
6884 ){
6885 /* conch host and lock path match */
6886 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006887 }
drh7ed97b92010-01-20 13:07:21 +00006888 }
6889
6890 /* if the conch isn't writable and doesn't match, we can't take it */
6891 if( (conchFile->openFlags&O_RDWR) == 0 ){
6892 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006893 goto end_takeconch;
6894 }
drh7ed97b92010-01-20 13:07:21 +00006895
6896 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006897 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006898 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6899 tempLockPath = lockPath;
6900 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006901 }
drh7ed97b92010-01-20 13:07:21 +00006902
6903 /* update conch with host and path (this will fail if other process
6904 ** has a shared lock already), if the host id matches, use the big
6905 ** stick.
drh715ff302008-12-03 22:32:44 +00006906 */
drh7ed97b92010-01-20 13:07:21 +00006907 futimes(conchFile->h, NULL);
6908 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006909 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006910 /* We are trying for an exclusive lock but another thread in this
6911 ** same process is still holding a shared lock. */
6912 rc = SQLITE_BUSY;
6913 } else {
6914 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006915 }
drh715ff302008-12-03 22:32:44 +00006916 }else{
drh4bf66fd2015-02-19 02:43:02 +00006917 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006918 }
drh7ed97b92010-01-20 13:07:21 +00006919 if( rc==SQLITE_OK ){
6920 char writeBuffer[PROXY_MAXCONCHLEN];
6921 int writeSize = 0;
6922
6923 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6924 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6925 if( pCtx->lockProxyPath!=NULL ){
drh4bf66fd2015-02-19 02:43:02 +00006926 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
6927 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00006928 }else{
6929 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6930 }
6931 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006932 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006933 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
drh6d258992016-02-04 09:48:12 +00006934 full_fsync(conchFile->h,0,0);
drh7ed97b92010-01-20 13:07:21 +00006935 /* If we created a new conch file (not just updated the contents of a
6936 ** valid conch file), try to match the permissions of the database
6937 */
6938 if( rc==SQLITE_OK && createConch ){
6939 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006940 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006941 if( err==0 ){
6942 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6943 S_IROTH|S_IWOTH);
6944 /* try to match the database file R/W permissions, ignore failure */
6945#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006946 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006947#else
drhff812312011-02-23 13:33:46 +00006948 do{
drhe562be52011-03-02 18:01:10 +00006949 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006950 }while( rc==(-1) && errno==EINTR );
6951 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006952 int code = errno;
6953 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6954 cmode, code, strerror(code));
6955 } else {
6956 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6957 }
6958 }else{
6959 int code = errno;
6960 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6961 err, code, strerror(code));
6962#endif
6963 }
drh715ff302008-12-03 22:32:44 +00006964 }
6965 }
drh7ed97b92010-01-20 13:07:21 +00006966 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6967
6968 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006969 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006970 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006971 int fd;
drh7ed97b92010-01-20 13:07:21 +00006972 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006973 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006974 }
6975 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006976 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006977 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006978 if( fd>=0 ){
6979 pFile->h = fd;
6980 }else{
drh9978c972010-02-23 17:36:32 +00006981 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006982 during locking */
6983 }
6984 }
6985 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6986 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6987 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6988 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6989 /* we couldn't create the proxy lock file with the old lock file path
6990 ** so try again via auto-naming
6991 */
6992 forceNewLockPath = 1;
6993 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006994 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006995 }
6996 }
6997 if( rc==SQLITE_OK ){
6998 /* Need to make a copy of path if we extracted the value
6999 ** from the conch file or the path was allocated on the stack
7000 */
7001 if( tempLockPath ){
7002 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
7003 if( !pCtx->lockProxyPath ){
7004 rc = SQLITE_NOMEM;
7005 }
7006 }
7007 }
7008 if( rc==SQLITE_OK ){
7009 pCtx->conchHeld = 1;
7010
7011 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
7012 afpLockingContext *afpCtx;
7013 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
7014 afpCtx->dbPath = pCtx->lockProxyPath;
7015 }
7016 } else {
7017 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7018 }
drh308c2a52010-05-14 11:30:18 +00007019 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
7020 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00007021 return rc;
drh308c2a52010-05-14 11:30:18 +00007022 } while (1); /* in case we need to retry the :auto: lock file -
7023 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00007024 }
7025}
7026
7027/*
7028** If pFile holds a lock on a conch file, then release that lock.
7029*/
7030static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00007031 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00007032 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
7033 unixFile *conchFile; /* Name of the conch file */
7034
7035 pCtx = (proxyLockingContext *)pFile->lockingContext;
7036 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00007037 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00007038 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00007039 osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00007040 if( pCtx->conchHeld>0 ){
7041 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7042 }
drh715ff302008-12-03 22:32:44 +00007043 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00007044 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
7045 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007046 return rc;
7047}
7048
7049/*
7050** Given the name of a database file, compute the name of its conch file.
drhf3cdcdc2015-04-29 16:50:28 +00007051** Store the conch filename in memory obtained from sqlite3_malloc64().
drh715ff302008-12-03 22:32:44 +00007052** Make *pConchPath point to the new name. Return SQLITE_OK on success
7053** or SQLITE_NOMEM if unable to obtain memory.
7054**
7055** The caller is responsible for ensuring that the allocated memory
7056** space is eventually freed.
7057**
7058** *pConchPath is set to NULL if a memory allocation error occurs.
7059*/
7060static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7061 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00007062 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00007063 char *conchPath; /* buffer in which to construct conch name */
7064
7065 /* Allocate space for the conch filename and initialize the name to
7066 ** the name of the original database file. */
drhf3cdcdc2015-04-29 16:50:28 +00007067 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
drh715ff302008-12-03 22:32:44 +00007068 if( conchPath==0 ){
7069 return SQLITE_NOMEM;
7070 }
7071 memcpy(conchPath, dbPath, len+1);
7072
7073 /* now insert a "." before the last / character */
7074 for( i=(len-1); i>=0; i-- ){
7075 if( conchPath[i]=='/' ){
7076 i++;
7077 break;
7078 }
7079 }
7080 conchPath[i]='.';
7081 while ( i<len ){
7082 conchPath[i+1]=dbPath[i];
7083 i++;
7084 }
7085
7086 /* append the "-conch" suffix to the file */
7087 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007088 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007089
7090 return SQLITE_OK;
7091}
7092
7093
7094/* Takes a fully configured proxy locking-style unix file and switches
7095** the local lock file path
7096*/
7097static int switchLockProxyPath(unixFile *pFile, const char *path) {
7098 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7099 char *oldPath = pCtx->lockProxyPath;
7100 int rc = SQLITE_OK;
7101
drh308c2a52010-05-14 11:30:18 +00007102 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007103 return SQLITE_BUSY;
7104 }
7105
7106 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7107 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7108 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7109 return SQLITE_OK;
7110 }else{
7111 unixFile *lockProxy = pCtx->lockProxy;
7112 pCtx->lockProxy=NULL;
7113 pCtx->conchHeld = 0;
7114 if( lockProxy!=NULL ){
7115 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7116 if( rc ) return rc;
7117 sqlite3_free(lockProxy);
7118 }
7119 sqlite3_free(oldPath);
7120 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7121 }
7122
7123 return rc;
7124}
7125
7126/*
7127** pFile is a file that has been opened by a prior xOpen call. dbPath
7128** is a string buffer at least MAXPATHLEN+1 characters in size.
7129**
7130** This routine find the filename associated with pFile and writes it
7131** int dbPath.
7132*/
7133static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007134#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007135 if( pFile->pMethod == &afpIoMethods ){
7136 /* afp style keeps a reference to the db path in the filePath field
7137 ** of the struct */
drhea678832008-12-10 19:26:22 +00007138 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh4bf66fd2015-02-19 02:43:02 +00007139 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7140 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007141 } else
drh715ff302008-12-03 22:32:44 +00007142#endif
7143 if( pFile->pMethod == &dotlockIoMethods ){
7144 /* dot lock style uses the locking context to store the dot lock
7145 ** file path */
7146 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7147 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7148 }else{
7149 /* all other styles use the locking context to store the db file path */
7150 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007151 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007152 }
7153 return SQLITE_OK;
7154}
7155
7156/*
7157** Takes an already filled in unix file and alters it so all file locking
7158** will be performed on the local proxy lock file. The following fields
7159** are preserved in the locking context so that they can be restored and
7160** the unix structure properly cleaned up at close time:
7161** ->lockingContext
7162** ->pMethod
7163*/
7164static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7165 proxyLockingContext *pCtx;
7166 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7167 char *lockPath=NULL;
7168 int rc = SQLITE_OK;
7169
drh308c2a52010-05-14 11:30:18 +00007170 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007171 return SQLITE_BUSY;
7172 }
7173 proxyGetDbPathForUnixFile(pFile, dbPath);
7174 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7175 lockPath=NULL;
7176 }else{
7177 lockPath=(char *)path;
7178 }
7179
drh308c2a52010-05-14 11:30:18 +00007180 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
drh5ac93652015-03-21 20:59:43 +00007181 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007182
drhf3cdcdc2015-04-29 16:50:28 +00007183 pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh715ff302008-12-03 22:32:44 +00007184 if( pCtx==0 ){
7185 return SQLITE_NOMEM;
7186 }
7187 memset(pCtx, 0, sizeof(*pCtx));
7188
7189 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7190 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007191 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7192 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7193 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7194 ** (c) the file system is read-only, then enable no-locking access.
7195 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7196 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7197 */
7198 struct statfs fsInfo;
7199 struct stat conchInfo;
7200 int goLockless = 0;
7201
drh99ab3b12011-03-02 15:09:07 +00007202 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007203 int err = errno;
7204 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7205 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7206 }
7207 }
7208 if( goLockless ){
7209 pCtx->conchHeld = -1; /* read only FS/ lockless */
7210 rc = SQLITE_OK;
7211 }
7212 }
drh715ff302008-12-03 22:32:44 +00007213 }
7214 if( rc==SQLITE_OK && lockPath ){
7215 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7216 }
7217
7218 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007219 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7220 if( pCtx->dbPath==NULL ){
7221 rc = SQLITE_NOMEM;
7222 }
7223 }
7224 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007225 /* all memory is allocated, proxys are created and assigned,
7226 ** switch the locking context and pMethod then return.
7227 */
drh715ff302008-12-03 22:32:44 +00007228 pCtx->oldLockingContext = pFile->lockingContext;
7229 pFile->lockingContext = pCtx;
7230 pCtx->pOldMethod = pFile->pMethod;
7231 pFile->pMethod = &proxyIoMethods;
7232 }else{
7233 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007234 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007235 sqlite3_free(pCtx->conchFile);
7236 }
drhd56b1212010-08-11 06:14:15 +00007237 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007238 sqlite3_free(pCtx->conchFilePath);
7239 sqlite3_free(pCtx);
7240 }
drh308c2a52010-05-14 11:30:18 +00007241 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7242 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007243 return rc;
7244}
7245
7246
7247/*
7248** This routine handles sqlite3_file_control() calls that are specific
7249** to proxy locking.
7250*/
7251static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7252 switch( op ){
drh4bf66fd2015-02-19 02:43:02 +00007253 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007254 unixFile *pFile = (unixFile*)id;
7255 if( pFile->pMethod == &proxyIoMethods ){
7256 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7257 proxyTakeConch(pFile);
7258 if( pCtx->lockProxyPath ){
7259 *(const char **)pArg = pCtx->lockProxyPath;
7260 }else{
7261 *(const char **)pArg = ":auto: (not held)";
7262 }
7263 } else {
7264 *(const char **)pArg = NULL;
7265 }
7266 return SQLITE_OK;
7267 }
drh4bf66fd2015-02-19 02:43:02 +00007268 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007269 unixFile *pFile = (unixFile*)id;
7270 int rc = SQLITE_OK;
7271 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7272 if( pArg==NULL || (const char *)pArg==0 ){
7273 if( isProxyStyle ){
drh4bf66fd2015-02-19 02:43:02 +00007274 /* turn off proxy locking - not supported. If support is added for
7275 ** switching proxy locking mode off then it will need to fail if
7276 ** the journal mode is WAL mode.
7277 */
drh715ff302008-12-03 22:32:44 +00007278 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7279 }else{
7280 /* turn off proxy locking - already off - NOOP */
7281 rc = SQLITE_OK;
7282 }
7283 }else{
7284 const char *proxyPath = (const char *)pArg;
7285 if( isProxyStyle ){
7286 proxyLockingContext *pCtx =
7287 (proxyLockingContext*)pFile->lockingContext;
7288 if( !strcmp(pArg, ":auto:")
7289 || (pCtx->lockProxyPath &&
7290 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7291 ){
7292 rc = SQLITE_OK;
7293 }else{
7294 rc = switchLockProxyPath(pFile, proxyPath);
7295 }
7296 }else{
7297 /* turn on proxy file locking */
7298 rc = proxyTransformUnixFile(pFile, proxyPath);
7299 }
7300 }
7301 return rc;
7302 }
7303 default: {
7304 assert( 0 ); /* The call assures that only valid opcodes are sent */
7305 }
7306 }
7307 /*NOTREACHED*/
7308 return SQLITE_ERROR;
7309}
7310
7311/*
7312** Within this division (the proxying locking implementation) the procedures
7313** above this point are all utilities. The lock-related methods of the
7314** proxy-locking sqlite3_io_method object follow.
7315*/
7316
7317
7318/*
7319** This routine checks if there is a RESERVED lock held on the specified
7320** file by this or any other process. If such a lock is held, set *pResOut
7321** to a non-zero value otherwise *pResOut is set to zero. The return value
7322** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7323*/
7324static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7325 unixFile *pFile = (unixFile*)id;
7326 int rc = proxyTakeConch(pFile);
7327 if( rc==SQLITE_OK ){
7328 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007329 if( pCtx->conchHeld>0 ){
7330 unixFile *proxy = pCtx->lockProxy;
7331 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7332 }else{ /* conchHeld < 0 is lockless */
7333 pResOut=0;
7334 }
drh715ff302008-12-03 22:32:44 +00007335 }
7336 return rc;
7337}
7338
7339/*
drh308c2a52010-05-14 11:30:18 +00007340** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007341** of the following:
7342**
7343** (1) SHARED_LOCK
7344** (2) RESERVED_LOCK
7345** (3) PENDING_LOCK
7346** (4) EXCLUSIVE_LOCK
7347**
7348** Sometimes when requesting one lock state, additional lock states
7349** are inserted in between. The locking might fail on one of the later
7350** transitions leaving the lock state different from what it started but
7351** still short of its goal. The following chart shows the allowed
7352** transitions and the inserted intermediate states:
7353**
7354** UNLOCKED -> SHARED
7355** SHARED -> RESERVED
7356** SHARED -> (PENDING) -> EXCLUSIVE
7357** RESERVED -> (PENDING) -> EXCLUSIVE
7358** PENDING -> EXCLUSIVE
7359**
7360** This routine will only increase a lock. Use the sqlite3OsUnlock()
7361** routine to lower a locking level.
7362*/
drh308c2a52010-05-14 11:30:18 +00007363static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007364 unixFile *pFile = (unixFile*)id;
7365 int rc = proxyTakeConch(pFile);
7366 if( rc==SQLITE_OK ){
7367 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007368 if( pCtx->conchHeld>0 ){
7369 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007370 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7371 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007372 }else{
7373 /* conchHeld < 0 is lockless */
7374 }
drh715ff302008-12-03 22:32:44 +00007375 }
7376 return rc;
7377}
7378
7379
7380/*
drh308c2a52010-05-14 11:30:18 +00007381** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007382** must be either NO_LOCK or SHARED_LOCK.
7383**
7384** If the locking level of the file descriptor is already at or below
7385** the requested locking level, this routine is a no-op.
7386*/
drh308c2a52010-05-14 11:30:18 +00007387static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007388 unixFile *pFile = (unixFile*)id;
7389 int rc = proxyTakeConch(pFile);
7390 if( rc==SQLITE_OK ){
7391 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007392 if( pCtx->conchHeld>0 ){
7393 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007394 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7395 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007396 }else{
7397 /* conchHeld < 0 is lockless */
7398 }
drh715ff302008-12-03 22:32:44 +00007399 }
7400 return rc;
7401}
7402
7403/*
7404** Close a file that uses proxy locks.
7405*/
7406static int proxyClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00007407 if( ALWAYS(id) ){
drh715ff302008-12-03 22:32:44 +00007408 unixFile *pFile = (unixFile*)id;
7409 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7410 unixFile *lockProxy = pCtx->lockProxy;
7411 unixFile *conchFile = pCtx->conchFile;
7412 int rc = SQLITE_OK;
7413
7414 if( lockProxy ){
7415 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7416 if( rc ) return rc;
7417 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7418 if( rc ) return rc;
7419 sqlite3_free(lockProxy);
7420 pCtx->lockProxy = 0;
7421 }
7422 if( conchFile ){
7423 if( pCtx->conchHeld ){
7424 rc = proxyReleaseConch(pFile);
7425 if( rc ) return rc;
7426 }
7427 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7428 if( rc ) return rc;
7429 sqlite3_free(conchFile);
7430 }
drhd56b1212010-08-11 06:14:15 +00007431 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007432 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007433 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007434 /* restore the original locking context and pMethod then close it */
7435 pFile->lockingContext = pCtx->oldLockingContext;
7436 pFile->pMethod = pCtx->pOldMethod;
7437 sqlite3_free(pCtx);
7438 return pFile->pMethod->xClose(id);
7439 }
7440 return SQLITE_OK;
7441}
7442
7443
7444
drhd2cb50b2009-01-09 21:41:17 +00007445#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007446/*
7447** The proxy locking style is intended for use with AFP filesystems.
7448** And since AFP is only supported on MacOSX, the proxy locking is also
7449** restricted to MacOSX.
7450**
7451**
7452******************* End of the proxy lock implementation **********************
7453******************************************************************************/
7454
drh734c9862008-11-28 15:37:20 +00007455/*
danielk1977e339d652008-06-28 11:23:00 +00007456** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007457**
7458** This routine registers all VFS implementations for unix-like operating
7459** systems. This routine, and the sqlite3_os_end() routine that follows,
7460** should be the only routines in this file that are visible from other
7461** files.
drh6b9d6dd2008-12-03 19:34:47 +00007462**
7463** This routine is called once during SQLite initialization and by a
7464** single thread. The memory allocation and mutex subsystems have not
7465** necessarily been initialized when this routine is called, and so they
7466** should not be used.
drh153c62c2007-08-24 03:51:33 +00007467*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007468int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007469 /*
7470 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007471 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7472 ** to the "finder" function. (pAppData is a pointer to a pointer because
7473 ** silly C90 rules prohibit a void* from being cast to a function pointer
7474 ** and so we have to go through the intermediate pointer to avoid problems
7475 ** when compiling with -pedantic-errors on GCC.)
7476 **
7477 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007478 ** finder-function. The finder-function returns a pointer to the
7479 ** sqlite_io_methods object that implements the desired locking
7480 ** behaviors. See the division above that contains the IOMETHODS
7481 ** macro for addition information on finder-functions.
7482 **
7483 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7484 ** object. But the "autolockIoFinder" available on MacOSX does a little
7485 ** more than that; it looks at the filesystem type that hosts the
7486 ** database file and tries to choose an locking method appropriate for
7487 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007488 */
drh7708e972008-11-29 00:56:52 +00007489 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007490 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007491 sizeof(unixFile), /* szOsFile */ \
7492 MAX_PATHNAME, /* mxPathname */ \
7493 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007494 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007495 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007496 unixOpen, /* xOpen */ \
7497 unixDelete, /* xDelete */ \
7498 unixAccess, /* xAccess */ \
7499 unixFullPathname, /* xFullPathname */ \
7500 unixDlOpen, /* xDlOpen */ \
7501 unixDlError, /* xDlError */ \
7502 unixDlSym, /* xDlSym */ \
7503 unixDlClose, /* xDlClose */ \
7504 unixRandomness, /* xRandomness */ \
7505 unixSleep, /* xSleep */ \
7506 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007507 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007508 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007509 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007510 unixGetSystemCall, /* xGetSystemCall */ \
7511 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007512 }
7513
drh6b9d6dd2008-12-03 19:34:47 +00007514 /*
7515 ** All default VFSes for unix are contained in the following array.
7516 **
7517 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7518 ** by the SQLite core when the VFS is registered. So the following
7519 ** array cannot be const.
7520 */
danielk1977e339d652008-06-28 11:23:00 +00007521 static sqlite3_vfs aVfs[] = {
drhe89b2912015-03-03 20:42:01 +00007522#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007523 UNIXVFS("unix", autolockIoFinder ),
drhe89b2912015-03-03 20:42:01 +00007524#elif OS_VXWORKS
7525 UNIXVFS("unix", vxworksIoFinder ),
drh7708e972008-11-29 00:56:52 +00007526#else
7527 UNIXVFS("unix", posixIoFinder ),
7528#endif
7529 UNIXVFS("unix-none", nolockIoFinder ),
7530 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007531 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007532#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007533 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007534#endif
drhe89b2912015-03-03 20:42:01 +00007535#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007536 UNIXVFS("unix-posix", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007537#endif
drhe89b2912015-03-03 20:42:01 +00007538#if SQLITE_ENABLE_LOCKING_STYLE
7539 UNIXVFS("unix-flock", flockIoFinder ),
chw78a13182009-04-07 05:35:03 +00007540#endif
drhd2cb50b2009-01-09 21:41:17 +00007541#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007542 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007543 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007544 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007545#endif
drh153c62c2007-08-24 03:51:33 +00007546 };
drh6b9d6dd2008-12-03 19:34:47 +00007547 unsigned int i; /* Loop counter */
7548
drh2aa5a002011-04-13 13:42:25 +00007549 /* Double-check that the aSyscall[] array has been constructed
7550 ** correctly. See ticket [bb3a86e890c8e96ab] */
dancaf6b152016-01-25 18:05:49 +00007551 assert( ArraySize(aSyscall)==28 );
drh2aa5a002011-04-13 13:42:25 +00007552
drh6b9d6dd2008-12-03 19:34:47 +00007553 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007554 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007555 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007556 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007557 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007558}
danielk1977e339d652008-06-28 11:23:00 +00007559
7560/*
drh6b9d6dd2008-12-03 19:34:47 +00007561** Shutdown the operating system interface.
7562**
7563** Some operating systems might need to do some cleanup in this routine,
7564** to release dynamically allocated objects. But not on unix.
7565** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007566*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007567int sqlite3_os_end(void){
7568 return SQLITE_OK;
7569}
drhdce8bdb2007-08-16 13:01:44 +00007570
danielk197729bafea2008-06-26 10:41:19 +00007571#endif /* SQLITE_OS_UNIX */