blob: 9cd1fa19adac292ed8240b199c97b1f5542b15ed [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
dan702eec12014-06-23 10:04:58 +0000483
drhe562be52011-03-02 18:01:10 +0000484}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000485
drh6226ca22015-11-24 15:06:28 +0000486
487/*
488** On some systems, calls to fchown() will trigger a message in a security
489** log if they come from non-root processes. So avoid calling fchown() if
490** we are not running as root.
491*/
492static int robustFchown(int fd, uid_t uid, gid_t gid){
drhe2258a22016-01-12 00:37:55 +0000493#if defined(HAVE_FCHOWN)
drh6226ca22015-11-24 15:06:28 +0000494 return osGeteuid() ? 0 : osFchown(fd,uid,gid);
drhe2258a22016-01-12 00:37:55 +0000495#else
496 return 0;
drh6226ca22015-11-24 15:06:28 +0000497#endif
498}
499
drh99ab3b12011-03-02 15:09:07 +0000500/*
501** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000502** "unix" VFSes. Return SQLITE_OK opon successfully updating the
503** system call pointer, or SQLITE_NOTFOUND if there is no configurable
504** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000505*/
506static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000507 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
508 const char *zName, /* Name of system call to override */
509 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000510){
drh58ad5802011-03-23 22:02:23 +0000511 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000512 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000513
514 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000515 if( zName==0 ){
516 /* If no zName is given, restore all system calls to their default
517 ** settings and return NULL
518 */
dan51438a72011-04-02 17:00:47 +0000519 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000520 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
521 if( aSyscall[i].pDefault ){
522 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000523 }
524 }
525 }else{
526 /* If zName is specified, operate on only the one system call
527 ** specified.
528 */
529 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
530 if( strcmp(zName, aSyscall[i].zName)==0 ){
531 if( aSyscall[i].pDefault==0 ){
532 aSyscall[i].pDefault = aSyscall[i].pCurrent;
533 }
drh1df30962011-03-02 19:06:42 +0000534 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000535 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
536 aSyscall[i].pCurrent = pNewFunc;
537 break;
538 }
539 }
540 }
541 return rc;
542}
543
drh1df30962011-03-02 19:06:42 +0000544/*
545** Return the value of a system call. Return NULL if zName is not a
546** recognized system call name. NULL is also returned if the system call
547** is currently undefined.
548*/
drh58ad5802011-03-23 22:02:23 +0000549static sqlite3_syscall_ptr unixGetSystemCall(
550 sqlite3_vfs *pNotUsed,
551 const char *zName
552){
553 unsigned int i;
554
555 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000556 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
557 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
558 }
559 return 0;
560}
561
562/*
563** Return the name of the first system call after zName. If zName==NULL
564** then return the name of the first system call. Return NULL if zName
565** is the last system call or if zName is not the name of a valid
566** system call.
567*/
568static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000569 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000570
571 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000572 if( zName ){
573 for(i=0; i<ArraySize(aSyscall)-1; i++){
574 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000575 }
576 }
dan0fd7d862011-03-29 10:04:23 +0000577 for(i++; i<ArraySize(aSyscall); i++){
578 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000579 }
580 return 0;
581}
582
drhad4f1e52011-03-04 15:43:57 +0000583/*
drh77a3fdc2013-08-30 14:24:12 +0000584** Do not accept any file descriptor less than this value, in order to avoid
585** opening database file using file descriptors that are commonly used for
586** standard input, output, and error.
587*/
588#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
589# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
590#endif
591
592/*
drh8c815d12012-02-13 20:16:37 +0000593** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000594** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000595**
596** If the file creation mode "m" is 0 then set it to the default for
597** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
598** 0644) as modified by the system umask. If m is not 0, then
599** make the file creation mode be exactly m ignoring the umask.
600**
601** The m parameter will be non-zero only when creating -wal, -journal,
602** and -shm files. We want those files to have *exactly* the same
603** permissions as their original database, unadulterated by the umask.
604** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
605** transaction crashes and leaves behind hot journals, then any
606** process that is able to write to the database will also be able to
607** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000608*/
drh8c815d12012-02-13 20:16:37 +0000609static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000610 int fd;
drhe1186ab2013-01-04 20:45:13 +0000611 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5128d002013-08-30 06:20:23 +0000612 while(1){
drh5adc60b2012-04-14 13:25:11 +0000613#if defined(O_CLOEXEC)
614 fd = osOpen(z,f|O_CLOEXEC,m2);
615#else
616 fd = osOpen(z,f,m2);
617#endif
drh5128d002013-08-30 06:20:23 +0000618 if( fd<0 ){
619 if( errno==EINTR ) continue;
620 break;
621 }
drh77a3fdc2013-08-30 14:24:12 +0000622 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
drh5128d002013-08-30 06:20:23 +0000623 osClose(fd);
624 sqlite3_log(SQLITE_WARNING,
625 "attempt to open \"%s\" as file descriptor %d", z, fd);
626 fd = -1;
627 if( osOpen("/dev/null", f, m)<0 ) break;
628 }
drhe1186ab2013-01-04 20:45:13 +0000629 if( fd>=0 ){
630 if( m!=0 ){
631 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000632 if( osFstat(fd, &statbuf)==0
633 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000634 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000635 ){
drhe1186ab2013-01-04 20:45:13 +0000636 osFchmod(fd, m);
637 }
638 }
drh5adc60b2012-04-14 13:25:11 +0000639#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000640 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000641#endif
drhe1186ab2013-01-04 20:45:13 +0000642 }
drh5adc60b2012-04-14 13:25:11 +0000643 return fd;
drhad4f1e52011-03-04 15:43:57 +0000644}
danielk197713adf8a2004-06-03 16:08:41 +0000645
drh107886a2008-11-21 22:21:50 +0000646/*
dan9359c7b2009-08-21 08:29:10 +0000647** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000648** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000649** vxworksFileId objects used by this file, all of which may be
650** shared by multiple threads.
651**
652** Function unixMutexHeld() is used to assert() that the global mutex
653** is held when required. This function is only used as part of assert()
654** statements. e.g.
655**
656** unixEnterMutex()
657** assert( unixMutexHeld() );
658** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000659*/
660static void unixEnterMutex(void){
mistachkin93de6532015-07-03 21:38:09 +0000661 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
drh107886a2008-11-21 22:21:50 +0000662}
663static void unixLeaveMutex(void){
mistachkin93de6532015-07-03 21:38:09 +0000664 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
drh107886a2008-11-21 22:21:50 +0000665}
dan9359c7b2009-08-21 08:29:10 +0000666#ifdef SQLITE_DEBUG
667static int unixMutexHeld(void) {
mistachkin93de6532015-07-03 21:38:09 +0000668 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
dan9359c7b2009-08-21 08:29:10 +0000669}
670#endif
drh107886a2008-11-21 22:21:50 +0000671
drh734c9862008-11-28 15:37:20 +0000672
mistachkinfb383e92015-04-16 03:24:38 +0000673#ifdef SQLITE_HAVE_OS_TRACE
drh734c9862008-11-28 15:37:20 +0000674/*
675** Helper function for printing out trace information from debugging
peter.d.reid60ec9142014-09-06 16:39:46 +0000676** binaries. This returns the string representation of the supplied
drh734c9862008-11-28 15:37:20 +0000677** integer lock-type.
678*/
drh308c2a52010-05-14 11:30:18 +0000679static const char *azFileLock(int eFileLock){
680 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000681 case NO_LOCK: return "NONE";
682 case SHARED_LOCK: return "SHARED";
683 case RESERVED_LOCK: return "RESERVED";
684 case PENDING_LOCK: return "PENDING";
685 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000686 }
687 return "ERROR";
688}
689#endif
690
691#ifdef SQLITE_LOCK_TRACE
692/*
693** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000694**
drh734c9862008-11-28 15:37:20 +0000695** This routine is used for troubleshooting locks on multithreaded
696** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
697** command-line option on the compiler. This code is normally
698** turned off.
699*/
700static int lockTrace(int fd, int op, struct flock *p){
701 char *zOpName, *zType;
702 int s;
703 int savedErrno;
704 if( op==F_GETLK ){
705 zOpName = "GETLK";
706 }else if( op==F_SETLK ){
707 zOpName = "SETLK";
708 }else{
drh99ab3b12011-03-02 15:09:07 +0000709 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000710 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
711 return s;
712 }
713 if( p->l_type==F_RDLCK ){
714 zType = "RDLCK";
715 }else if( p->l_type==F_WRLCK ){
716 zType = "WRLCK";
717 }else if( p->l_type==F_UNLCK ){
718 zType = "UNLCK";
719 }else{
720 assert( 0 );
721 }
722 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000723 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000724 savedErrno = errno;
725 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
726 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
727 (int)p->l_pid, s);
728 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
729 struct flock l2;
730 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000731 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000732 if( l2.l_type==F_RDLCK ){
733 zType = "RDLCK";
734 }else if( l2.l_type==F_WRLCK ){
735 zType = "WRLCK";
736 }else if( l2.l_type==F_UNLCK ){
737 zType = "UNLCK";
738 }else{
739 assert( 0 );
740 }
741 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
742 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
743 }
744 errno = savedErrno;
745 return s;
746}
drh99ab3b12011-03-02 15:09:07 +0000747#undef osFcntl
748#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000749#endif /* SQLITE_LOCK_TRACE */
750
drhff812312011-02-23 13:33:46 +0000751/*
752** Retry ftruncate() calls that fail due to EINTR
dan2ee53412014-09-06 16:49:40 +0000753**
drhe6d41732015-02-21 00:49:00 +0000754** All calls to ftruncate() within this file should be made through
755** this wrapper. On the Android platform, bypassing the logic below
756** could lead to a corrupt database.
drhff812312011-02-23 13:33:46 +0000757*/
drhff812312011-02-23 13:33:46 +0000758static int robust_ftruncate(int h, sqlite3_int64 sz){
759 int rc;
dan2ee53412014-09-06 16:49:40 +0000760#ifdef __ANDROID__
761 /* On Android, ftruncate() always uses 32-bit offsets, even if
762 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
dan524a7332014-09-06 17:06:13 +0000763 ** truncate a file to any size larger than 2GiB. Silently ignore any
dan2ee53412014-09-06 16:49:40 +0000764 ** such attempts. */
765 if( sz>(sqlite3_int64)0x7FFFFFFF ){
766 rc = SQLITE_OK;
767 }else
768#endif
drh99ab3b12011-03-02 15:09:07 +0000769 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000770 return rc;
771}
drh734c9862008-11-28 15:37:20 +0000772
773/*
774** This routine translates a standard POSIX errno code into something
775** useful to the clients of the sqlite3 functions. Specifically, it is
776** intended to translate a variety of "try again" errors into SQLITE_BUSY
777** and a variety of "please close the file descriptor NOW" errors into
778** SQLITE_IOERR
779**
780** Errors during initialization of locks, or file system support for locks,
781** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
782*/
783static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
drh91c4def2015-11-25 14:00:07 +0000784 assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
785 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
786 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
787 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
drh734c9862008-11-28 15:37:20 +0000788 switch (posixError) {
drh91c4def2015-11-25 14:00:07 +0000789 case EACCES:
drh734c9862008-11-28 15:37:20 +0000790 case EAGAIN:
791 case ETIMEDOUT:
792 case EBUSY:
793 case EINTR:
794 case ENOLCK:
795 /* random NFS retry error, unless during file system support
796 * introspection, in which it actually means what it says */
797 return SQLITE_BUSY;
798
drh734c9862008-11-28 15:37:20 +0000799 case EPERM:
800 return SQLITE_PERM;
801
drh734c9862008-11-28 15:37:20 +0000802 default:
803 return sqliteIOErr;
804 }
805}
806
807
drh734c9862008-11-28 15:37:20 +0000808/******************************************************************************
809****************** Begin Unique File ID Utility Used By VxWorks ***************
810**
811** On most versions of unix, we can get a unique ID for a file by concatenating
812** the device number and the inode number. But this does not work on VxWorks.
813** On VxWorks, a unique file id must be based on the canonical filename.
814**
815** A pointer to an instance of the following structure can be used as a
816** unique file ID in VxWorks. Each instance of this structure contains
817** a copy of the canonical filename. There is also a reference count.
818** The structure is reclaimed when the number of pointers to it drops to
819** zero.
820**
821** There are never very many files open at one time and lookups are not
822** a performance-critical path, so it is sufficient to put these
823** structures on a linked list.
824*/
825struct vxworksFileId {
826 struct vxworksFileId *pNext; /* Next in a list of them all */
827 int nRef; /* Number of references to this one */
828 int nName; /* Length of the zCanonicalName[] string */
829 char *zCanonicalName; /* Canonical filename */
830};
831
832#if OS_VXWORKS
833/*
drh9b35ea62008-11-29 02:20:26 +0000834** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000835** variable:
836*/
837static struct vxworksFileId *vxworksFileList = 0;
838
839/*
840** Simplify a filename into its canonical form
841** by making the following changes:
842**
843** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000844** * convert /./ into just /
845** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000846**
847** Changes are made in-place. Return the new name length.
848**
849** The original filename is in z[0..n-1]. Return the number of
850** characters in the simplified name.
851*/
852static int vxworksSimplifyName(char *z, int n){
853 int i, j;
854 while( n>1 && z[n-1]=='/' ){ n--; }
855 for(i=j=0; i<n; i++){
856 if( z[i]=='/' ){
857 if( z[i+1]=='/' ) continue;
858 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
859 i += 1;
860 continue;
861 }
862 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
863 while( j>0 && z[j-1]!='/' ){ j--; }
864 if( j>0 ){ j--; }
865 i += 2;
866 continue;
867 }
868 }
869 z[j++] = z[i];
870 }
871 z[j] = 0;
872 return j;
873}
874
875/*
876** Find a unique file ID for the given absolute pathname. Return
877** a pointer to the vxworksFileId object. This pointer is the unique
878** file ID.
879**
880** The nRef field of the vxworksFileId object is incremented before
881** the object is returned. A new vxworksFileId object is created
882** and added to the global list if necessary.
883**
884** If a memory allocation error occurs, return NULL.
885*/
886static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
887 struct vxworksFileId *pNew; /* search key and new file ID */
888 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
889 int n; /* Length of zAbsoluteName string */
890
891 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000892 n = (int)strlen(zAbsoluteName);
drhf3cdcdc2015-04-29 16:50:28 +0000893 pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
drh734c9862008-11-28 15:37:20 +0000894 if( pNew==0 ) return 0;
895 pNew->zCanonicalName = (char*)&pNew[1];
896 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
897 n = vxworksSimplifyName(pNew->zCanonicalName, n);
898
899 /* Search for an existing entry that matching the canonical name.
900 ** If found, increment the reference count and return a pointer to
901 ** the existing file ID.
902 */
903 unixEnterMutex();
904 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
905 if( pCandidate->nName==n
906 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
907 ){
908 sqlite3_free(pNew);
909 pCandidate->nRef++;
910 unixLeaveMutex();
911 return pCandidate;
912 }
913 }
914
915 /* No match was found. We will make a new file ID */
916 pNew->nRef = 1;
917 pNew->nName = n;
918 pNew->pNext = vxworksFileList;
919 vxworksFileList = pNew;
920 unixLeaveMutex();
921 return pNew;
922}
923
924/*
925** Decrement the reference count on a vxworksFileId object. Free
926** the object when the reference count reaches zero.
927*/
928static void vxworksReleaseFileId(struct vxworksFileId *pId){
929 unixEnterMutex();
930 assert( pId->nRef>0 );
931 pId->nRef--;
932 if( pId->nRef==0 ){
933 struct vxworksFileId **pp;
934 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
935 assert( *pp==pId );
936 *pp = pId->pNext;
937 sqlite3_free(pId);
938 }
939 unixLeaveMutex();
940}
941#endif /* OS_VXWORKS */
942/*************** End of Unique File ID Utility Used By VxWorks ****************
943******************************************************************************/
944
945
946/******************************************************************************
947*************************** Posix Advisory Locking ****************************
948**
drh9b35ea62008-11-29 02:20:26 +0000949** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000950** section 6.5.2.2 lines 483 through 490 specify that when a process
951** sets or clears a lock, that operation overrides any prior locks set
952** by the same process. It does not explicitly say so, but this implies
953** that it overrides locks set by the same process using a different
954** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000955**
956** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000957** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
958**
959** Suppose ./file1 and ./file2 are really the same file (because
960** one is a hard or symbolic link to the other) then if you set
961** an exclusive lock on fd1, then try to get an exclusive lock
962** on fd2, it works. I would have expected the second lock to
963** fail since there was already a lock on the file due to fd1.
964** But not so. Since both locks came from the same process, the
965** second overrides the first, even though they were on different
966** file descriptors opened on different file names.
967**
drh734c9862008-11-28 15:37:20 +0000968** This means that we cannot use POSIX locks to synchronize file access
969** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000970** to synchronize access for threads in separate processes, but not
971** threads within the same process.
972**
973** To work around the problem, SQLite has to manage file locks internally
974** on its own. Whenever a new database is opened, we have to find the
975** specific inode of the database file (the inode is determined by the
976** st_dev and st_ino fields of the stat structure that fstat() fills in)
977** and check for locks already existing on that inode. When locks are
978** created or removed, we have to look at our own internal record of the
979** locks to see if another thread has previously set a lock on that same
980** inode.
981**
drh9b35ea62008-11-29 02:20:26 +0000982** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
983** For VxWorks, we have to use the alternative unique ID system based on
984** canonical filename and implemented in the previous division.)
985**
danielk1977ad94b582007-08-20 06:44:22 +0000986** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000987** descriptor. It is now a structure that holds the integer file
988** descriptor and a pointer to a structure that describes the internal
989** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000990** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000991** point to the same locking structure. The locking structure keeps
992** a reference count (so we will know when to delete it) and a "cnt"
993** field that tells us its internal lock status. cnt==0 means the
994** file is unlocked. cnt==-1 means the file has an exclusive lock.
995** cnt>0 means there are cnt shared locks on the file.
996**
997** Any attempt to lock or unlock a file first checks the locking
998** structure. The fcntl() system call is only invoked to set a
999** POSIX lock if the internal lock structure transitions between
1000** a locked and an unlocked state.
1001**
drh734c9862008-11-28 15:37:20 +00001002** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +00001003**
1004** If you close a file descriptor that points to a file that has locks,
1005** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +00001006** released. To work around this problem, each unixInodeInfo object
1007** maintains a count of the number of pending locks on tha inode.
1008** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +00001009** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +00001010** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +00001011** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +00001012** be closed and that list is walked (and cleared) when the last lock
1013** clears.
1014**
drh9b35ea62008-11-29 02:20:26 +00001015** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +00001016**
drh9b35ea62008-11-29 02:20:26 +00001017** Many older versions of linux use the LinuxThreads library which is
1018** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +00001019** A cannot be modified or overridden by a different thread B.
1020** Only thread A can modify the lock. Locking behavior is correct
1021** if the appliation uses the newer Native Posix Thread Library (NPTL)
1022** on linux - with NPTL a lock created by thread A can override locks
1023** in thread B. But there is no way to know at compile-time which
1024** threading library is being used. So there is no way to know at
1025** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001026** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001027** current process.
drh5fdae772004-06-29 03:29:00 +00001028**
drh8af6c222010-05-14 12:43:01 +00001029** SQLite used to support LinuxThreads. But support for LinuxThreads
1030** was dropped beginning with version 3.7.0. SQLite will still work with
1031** LinuxThreads provided that (1) there is no more than one connection
1032** per database file in the same process and (2) database connections
1033** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001034*/
1035
1036/*
1037** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001038** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001039*/
1040struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001041 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001042#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001043 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001044#else
drh107886a2008-11-21 22:21:50 +00001045 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001046#endif
1047};
1048
1049/*
drhbbd42a62004-05-22 17:41:58 +00001050** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001051** inode. Or, on LinuxThreads, there is one of these structures for
1052** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001053**
danielk1977ad94b582007-08-20 06:44:22 +00001054** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001055** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001056** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001057*/
drh8af6c222010-05-14 12:43:01 +00001058struct unixInodeInfo {
1059 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001060 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001061 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1062 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001063 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001064 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1065 int nLock; /* Number of outstanding file locks */
1066 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1067 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1068 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001069#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001070 unsigned long long sharedByte; /* for AFP simulated shared lock */
1071#endif
drh6c7d5c52008-11-21 20:32:33 +00001072#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001073 sem_t *pSem; /* Named POSIX semaphore */
1074 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001075#endif
drhbbd42a62004-05-22 17:41:58 +00001076};
1077
drhda0e7682008-07-30 15:27:54 +00001078/*
drh8af6c222010-05-14 12:43:01 +00001079** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001080*/
drhd91c68f2010-05-14 14:52:25 +00001081static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001082
drh5fdae772004-06-29 03:29:00 +00001083/*
dane18d4952011-02-21 11:46:24 +00001084**
drhaaeaa182015-11-24 15:12:47 +00001085** This function - unixLogErrorAtLine(), is only ever called via the macro
dane18d4952011-02-21 11:46:24 +00001086** unixLogError().
1087**
1088** It is invoked after an error occurs in an OS function and errno has been
1089** set. It logs a message using sqlite3_log() containing the current value of
1090** errno and, if possible, the human-readable equivalent from strerror() or
1091** strerror_r().
1092**
1093** The first argument passed to the macro should be the error code that
1094** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1095** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001096** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001097** if any.
1098*/
drh0e9365c2011-03-02 02:08:13 +00001099#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1100static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001101 int errcode, /* SQLite error code */
1102 const char *zFunc, /* Name of OS function that failed */
1103 const char *zPath, /* File path associated with error */
1104 int iLine /* Source line number where error occurred */
1105){
1106 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001107 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001108
1109 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1110 ** the strerror() function to obtain the human-readable error message
1111 ** equivalent to errno. Otherwise, use strerror_r().
1112 */
1113#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1114 char aErr[80];
1115 memset(aErr, 0, sizeof(aErr));
1116 zErr = aErr;
1117
1118 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001119 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001120 ** returns a pointer to a buffer containing the error message. That pointer
1121 ** may point to aErr[], or it may point to some static storage somewhere.
1122 ** Otherwise, assume that the system provides the POSIX version of
1123 ** strerror_r(), which always writes an error message into aErr[].
1124 **
1125 ** If the code incorrectly assumes that it is the POSIX version that is
1126 ** available, the error message will often be an empty string. Not a
1127 ** huge problem. Incorrectly concluding that the GNU version is available
1128 ** could lead to a segfault though.
1129 */
1130#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1131 zErr =
1132# endif
drh0e9365c2011-03-02 02:08:13 +00001133 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001134
1135#elif SQLITE_THREADSAFE
1136 /* This is a threadsafe build, but strerror_r() is not available. */
1137 zErr = "";
1138#else
1139 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001140 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001141#endif
1142
drh0e9365c2011-03-02 02:08:13 +00001143 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001144 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001145 "os_unix.c:%d: (%d) %s(%s) - %s",
1146 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001147 );
1148
1149 return errcode;
1150}
1151
drh0e9365c2011-03-02 02:08:13 +00001152/*
1153** Close a file descriptor.
1154**
1155** We assume that close() almost always works, since it is only in a
1156** very sick application or on a very sick platform that it might fail.
1157** If it does fail, simply leak the file descriptor, but do log the
1158** error.
1159**
1160** Note that it is not safe to retry close() after EINTR since the
1161** file descriptor might have already been reused by another thread.
1162** So we don't even try to recover from an EINTR. Just log the error
1163** and move on.
1164*/
1165static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001166 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001167 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1168 pFile ? pFile->zPath : 0, lineno);
1169 }
1170}
dane18d4952011-02-21 11:46:24 +00001171
1172/*
drhe6d41732015-02-21 00:49:00 +00001173** Set the pFile->lastErrno. Do this in a subroutine as that provides
1174** a convenient place to set a breakpoint.
drh4bf66fd2015-02-19 02:43:02 +00001175*/
1176static void storeLastErrno(unixFile *pFile, int error){
1177 pFile->lastErrno = error;
1178}
1179
1180/*
danb0ac3e32010-06-16 10:55:42 +00001181** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001182*/
drh0e9365c2011-03-02 02:08:13 +00001183static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001184 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001185 UnixUnusedFd *p;
1186 UnixUnusedFd *pNext;
1187 for(p=pInode->pUnused; p; p=pNext){
1188 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001189 robust_close(pFile, p->fd, __LINE__);
1190 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001191 }
drh0e9365c2011-03-02 02:08:13 +00001192 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001193}
1194
1195/*
drh8af6c222010-05-14 12:43:01 +00001196** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001197**
1198** The mutex entered using the unixEnterMutex() function must be held
1199** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001200*/
danb0ac3e32010-06-16 10:55:42 +00001201static void releaseInodeInfo(unixFile *pFile){
1202 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001203 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001204 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001205 pInode->nRef--;
1206 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001207 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001208 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001209 if( pInode->pPrev ){
1210 assert( pInode->pPrev->pNext==pInode );
1211 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001212 }else{
drh8af6c222010-05-14 12:43:01 +00001213 assert( inodeList==pInode );
1214 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001215 }
drh8af6c222010-05-14 12:43:01 +00001216 if( pInode->pNext ){
1217 assert( pInode->pNext->pPrev==pInode );
1218 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001219 }
drh8af6c222010-05-14 12:43:01 +00001220 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001221 }
drhbbd42a62004-05-22 17:41:58 +00001222 }
1223}
1224
1225/*
drh8af6c222010-05-14 12:43:01 +00001226** Given a file descriptor, locate the unixInodeInfo object that
1227** describes that file descriptor. Create a new one if necessary. The
1228** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001229**
dan9359c7b2009-08-21 08:29:10 +00001230** The mutex entered using the unixEnterMutex() function must be held
1231** when this function is called.
1232**
drh6c7d5c52008-11-21 20:32:33 +00001233** Return an appropriate error code.
1234*/
drh8af6c222010-05-14 12:43:01 +00001235static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001236 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001237 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001238){
1239 int rc; /* System call return code */
1240 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001241 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1242 struct stat statbuf; /* Low-level file information */
1243 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001244
dan9359c7b2009-08-21 08:29:10 +00001245 assert( unixMutexHeld() );
1246
drh6c7d5c52008-11-21 20:32:33 +00001247 /* Get low-level information about the file that we can used to
1248 ** create a unique name for the file.
1249 */
1250 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001251 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001252 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001253 storeLastErrno(pFile, errno);
drh40fe8d32015-11-30 20:36:26 +00001254#if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
drh6c7d5c52008-11-21 20:32:33 +00001255 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1256#endif
1257 return SQLITE_IOERR;
1258 }
1259
drheb0d74f2009-02-03 15:27:02 +00001260#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001261 /* On OS X on an msdos filesystem, the inode number is reported
1262 ** incorrectly for zero-size files. See ticket #3260. To work
1263 ** around this problem (we consider it a bug in OS X, not SQLite)
1264 ** we always increase the file size to 1 by writing a single byte
1265 ** prior to accessing the inode number. The one byte written is
1266 ** an ASCII 'S' character which also happens to be the first byte
1267 ** in the header of every SQLite database. In this way, if there
1268 ** is a race condition such that another thread has already populated
1269 ** the first page of the database, no damage is done.
1270 */
drh7ed97b92010-01-20 13:07:21 +00001271 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001272 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001273 if( rc!=1 ){
drh4bf66fd2015-02-19 02:43:02 +00001274 storeLastErrno(pFile, errno);
drheb0d74f2009-02-03 15:27:02 +00001275 return SQLITE_IOERR;
1276 }
drh99ab3b12011-03-02 15:09:07 +00001277 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001278 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001279 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001280 return SQLITE_IOERR;
1281 }
1282 }
drheb0d74f2009-02-03 15:27:02 +00001283#endif
drh6c7d5c52008-11-21 20:32:33 +00001284
drh8af6c222010-05-14 12:43:01 +00001285 memset(&fileId, 0, sizeof(fileId));
1286 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001287#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001288 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001289#else
drh8af6c222010-05-14 12:43:01 +00001290 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001291#endif
drh8af6c222010-05-14 12:43:01 +00001292 pInode = inodeList;
1293 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1294 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001295 }
drh8af6c222010-05-14 12:43:01 +00001296 if( pInode==0 ){
drhf3cdcdc2015-04-29 16:50:28 +00001297 pInode = sqlite3_malloc64( sizeof(*pInode) );
drh8af6c222010-05-14 12:43:01 +00001298 if( pInode==0 ){
1299 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001300 }
drh8af6c222010-05-14 12:43:01 +00001301 memset(pInode, 0, sizeof(*pInode));
1302 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1303 pInode->nRef = 1;
1304 pInode->pNext = inodeList;
1305 pInode->pPrev = 0;
1306 if( inodeList ) inodeList->pPrev = pInode;
1307 inodeList = pInode;
1308 }else{
1309 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001310 }
drh8af6c222010-05-14 12:43:01 +00001311 *ppInode = pInode;
1312 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001313}
drh6c7d5c52008-11-21 20:32:33 +00001314
drhb959a012013-12-07 12:29:22 +00001315/*
1316** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1317*/
1318static int fileHasMoved(unixFile *pFile){
drh61ffea52014-08-12 12:19:25 +00001319#if OS_VXWORKS
1320 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1321#else
drhb959a012013-12-07 12:29:22 +00001322 struct stat buf;
1323 return pFile->pInode!=0 &&
drh61ffea52014-08-12 12:19:25 +00001324 (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
drh91be7dc2014-08-11 13:53:30 +00001325#endif
drhb959a012013-12-07 12:29:22 +00001326}
1327
aswift5b1a2562008-08-22 00:22:35 +00001328
1329/*
drhfbc7e882013-04-11 01:16:15 +00001330** Check a unixFile that is a database. Verify the following:
1331**
1332** (1) There is exactly one hard link on the file
1333** (2) The file is not a symbolic link
1334** (3) The file has not been renamed or unlinked
1335**
1336** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1337*/
1338static void verifyDbFile(unixFile *pFile){
1339 struct stat buf;
1340 int rc;
drhfbc7e882013-04-11 01:16:15 +00001341 rc = osFstat(pFile->h, &buf);
1342 if( rc!=0 ){
1343 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001344 return;
1345 }
drh3044b512014-06-16 16:41:52 +00001346 if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
drhfbc7e882013-04-11 01:16:15 +00001347 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001348 return;
1349 }
1350 if( buf.st_nlink>1 ){
1351 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001352 return;
1353 }
drhb959a012013-12-07 12:29:22 +00001354 if( fileHasMoved(pFile) ){
drhfbc7e882013-04-11 01:16:15 +00001355 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001356 return;
1357 }
1358}
1359
1360
1361/*
danielk197713adf8a2004-06-03 16:08:41 +00001362** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001363** file by this or any other process. If such a lock is held, set *pResOut
1364** to a non-zero value otherwise *pResOut is set to zero. The return value
1365** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001366*/
danielk1977861f7452008-06-05 11:39:11 +00001367static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001368 int rc = SQLITE_OK;
1369 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001370 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001371
danielk1977861f7452008-06-05 11:39:11 +00001372 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1373
drh054889e2005-11-30 03:20:31 +00001374 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00001375 assert( pFile->eFileLock<=SHARED_LOCK );
drh8af6c222010-05-14 12:43:01 +00001376 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001377
1378 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001379 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001380 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001381 }
1382
drh2ac3ee92004-06-07 16:27:46 +00001383 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001384 */
danielk197709480a92009-02-09 05:32:32 +00001385#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001386 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001387 struct flock lock;
1388 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001389 lock.l_start = RESERVED_BYTE;
1390 lock.l_len = 1;
1391 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001392 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1393 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001394 storeLastErrno(pFile, errno);
aswift5b1a2562008-08-22 00:22:35 +00001395 } else if( lock.l_type!=F_UNLCK ){
1396 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001397 }
1398 }
danielk197709480a92009-02-09 05:32:32 +00001399#endif
danielk197713adf8a2004-06-03 16:08:41 +00001400
drh6c7d5c52008-11-21 20:32:33 +00001401 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001402 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001403
aswift5b1a2562008-08-22 00:22:35 +00001404 *pResOut = reserved;
1405 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001406}
1407
1408/*
drha7e61d82011-03-12 17:02:57 +00001409** Attempt to set a system-lock on the file pFile. The lock is
1410** described by pLock.
1411**
drh77197112011-03-15 19:08:48 +00001412** If the pFile was opened read/write from unix-excl, then the only lock
1413** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001414** the first time any lock is attempted. All subsequent system locking
1415** operations become no-ops. Locking operations still happen internally,
1416** in order to coordinate access between separate database connections
1417** within this process, but all of that is handled in memory and the
1418** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001419**
1420** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1421** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1422** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001423**
1424** Zero is returned if the call completes successfully, or -1 if a call
1425** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001426*/
1427static int unixFileLock(unixFile *pFile, struct flock *pLock){
1428 int rc;
drh3cb93392011-03-12 18:10:44 +00001429 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001430 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001431 assert( pInode!=0 );
drh50358ad2015-12-02 01:04:33 +00001432 if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
drh3cb93392011-03-12 18:10:44 +00001433 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001434 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001435 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001436 lock.l_whence = SEEK_SET;
1437 lock.l_start = SHARED_FIRST;
1438 lock.l_len = SHARED_SIZE;
1439 lock.l_type = F_WRLCK;
1440 rc = osFcntl(pFile->h, F_SETLK, &lock);
1441 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001442 pInode->bProcessLock = 1;
1443 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001444 }else{
1445 rc = 0;
1446 }
1447 }else{
1448 rc = osFcntl(pFile->h, F_SETLK, pLock);
1449 }
1450 return rc;
1451}
1452
1453/*
drh308c2a52010-05-14 11:30:18 +00001454** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001455** of the following:
1456**
drh2ac3ee92004-06-07 16:27:46 +00001457** (1) SHARED_LOCK
1458** (2) RESERVED_LOCK
1459** (3) PENDING_LOCK
1460** (4) EXCLUSIVE_LOCK
1461**
drhb3e04342004-06-08 00:47:47 +00001462** Sometimes when requesting one lock state, additional lock states
1463** are inserted in between. The locking might fail on one of the later
1464** transitions leaving the lock state different from what it started but
1465** still short of its goal. The following chart shows the allowed
1466** transitions and the inserted intermediate states:
1467**
1468** UNLOCKED -> SHARED
1469** SHARED -> RESERVED
1470** SHARED -> (PENDING) -> EXCLUSIVE
1471** RESERVED -> (PENDING) -> EXCLUSIVE
1472** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001473**
drha6abd042004-06-09 17:37:22 +00001474** This routine will only increase a lock. Use the sqlite3OsUnlock()
1475** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001476*/
drh308c2a52010-05-14 11:30:18 +00001477static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001478 /* The following describes the implementation of the various locks and
1479 ** lock transitions in terms of the POSIX advisory shared and exclusive
1480 ** lock primitives (called read-locks and write-locks below, to avoid
1481 ** confusion with SQLite lock names). The algorithms are complicated
1482 ** slightly in order to be compatible with windows systems simultaneously
1483 ** accessing the same database file, in case that is ever required.
1484 **
1485 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1486 ** byte', each single bytes at well known offsets, and the 'shared byte
1487 ** range', a range of 510 bytes at a well known offset.
1488 **
1489 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1490 ** byte'. If this is successful, a random byte from the 'shared byte
1491 ** range' is read-locked and the lock on the 'pending byte' released.
1492 **
danielk197790ba3bd2004-06-25 08:32:25 +00001493 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1494 ** A RESERVED lock is implemented by grabbing a write-lock on the
1495 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001496 **
1497 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001498 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1499 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1500 ** obtained, but existing SHARED locks are allowed to persist. A process
1501 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1502 ** This property is used by the algorithm for rolling back a journal file
1503 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001504 **
danielk197790ba3bd2004-06-25 08:32:25 +00001505 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1506 ** implemented by obtaining a write-lock on the entire 'shared byte
1507 ** range'. Since all other locks require a read-lock on one of the bytes
1508 ** within this range, this ensures that no other locks are held on the
1509 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001510 **
1511 ** The reason a single byte cannot be used instead of the 'shared byte
1512 ** range' is that some versions of windows do not support read-locks. By
1513 ** locking a random byte from a range, concurrent SHARED locks may exist
1514 ** even if the locking primitive used is always a write-lock.
1515 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001516 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001517 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001518 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001519 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001520 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001521
drh054889e2005-11-30 03:20:31 +00001522 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001523 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1524 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh91eb93c2015-03-03 19:56:20 +00001525 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001526 osGetpid(0)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001527
1528 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001529 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001530 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001531 */
drh308c2a52010-05-14 11:30:18 +00001532 if( pFile->eFileLock>=eFileLock ){
1533 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1534 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001535 return SQLITE_OK;
1536 }
1537
drh0c2694b2009-09-03 16:23:44 +00001538 /* Make sure the locking sequence is correct.
1539 ** (1) We never move from unlocked to anything higher than shared lock.
1540 ** (2) SQLite never explicitly requests a pendig lock.
1541 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001542 */
drh308c2a52010-05-14 11:30:18 +00001543 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1544 assert( eFileLock!=PENDING_LOCK );
1545 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001546
drh8af6c222010-05-14 12:43:01 +00001547 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001548 */
drh6c7d5c52008-11-21 20:32:33 +00001549 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001550 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001551
danielk1977ad94b582007-08-20 06:44:22 +00001552 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001553 ** handle that precludes the requested lock, return BUSY.
1554 */
drh8af6c222010-05-14 12:43:01 +00001555 if( (pFile->eFileLock!=pInode->eFileLock &&
1556 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001557 ){
1558 rc = SQLITE_BUSY;
1559 goto end_lock;
1560 }
1561
1562 /* If a SHARED lock is requested, and some thread using this PID already
1563 ** has a SHARED or RESERVED lock, then increment reference counts and
1564 ** return SQLITE_OK.
1565 */
drh308c2a52010-05-14 11:30:18 +00001566 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001567 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001568 assert( eFileLock==SHARED_LOCK );
1569 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001570 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001571 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001572 pInode->nShared++;
1573 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001574 goto end_lock;
1575 }
1576
danielk19779a1d0ab2004-06-01 14:09:28 +00001577
drh3cde3bb2004-06-12 02:17:14 +00001578 /* A PENDING lock is needed before acquiring a SHARED lock and before
1579 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1580 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001581 */
drh0c2694b2009-09-03 16:23:44 +00001582 lock.l_len = 1L;
1583 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001584 if( eFileLock==SHARED_LOCK
1585 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001586 ){
drh308c2a52010-05-14 11:30:18 +00001587 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001588 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001589 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001590 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001591 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001592 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001593 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001594 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001595 goto end_lock;
1596 }
drh3cde3bb2004-06-12 02:17:14 +00001597 }
1598
1599
1600 /* If control gets to this point, then actually go ahead and make
1601 ** operating system calls for the specified lock.
1602 */
drh308c2a52010-05-14 11:30:18 +00001603 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001604 assert( pInode->nShared==0 );
1605 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001606 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001607
drh2ac3ee92004-06-07 16:27:46 +00001608 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001609 lock.l_start = SHARED_FIRST;
1610 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001611 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001612 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001613 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001614 }
dan661d71a2011-03-30 19:08:03 +00001615
drh2ac3ee92004-06-07 16:27:46 +00001616 /* Drop the temporary PENDING lock */
1617 lock.l_start = PENDING_BYTE;
1618 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001619 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001620 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1621 /* This could happen with a network mount */
1622 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001623 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001624 }
dan661d71a2011-03-30 19:08:03 +00001625
1626 if( rc ){
1627 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001628 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001629 }
dan661d71a2011-03-30 19:08:03 +00001630 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001631 }else{
drh308c2a52010-05-14 11:30:18 +00001632 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001633 pInode->nLock++;
1634 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001635 }
drh8af6c222010-05-14 12:43:01 +00001636 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001637 /* We are trying for an exclusive lock but another thread in this
1638 ** same process is still holding a shared lock. */
1639 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001640 }else{
drh3cde3bb2004-06-12 02:17:14 +00001641 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001642 ** assumed that there is a SHARED or greater lock on the file
1643 ** already.
1644 */
drh308c2a52010-05-14 11:30:18 +00001645 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001646 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001647
1648 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1649 if( eFileLock==RESERVED_LOCK ){
1650 lock.l_start = RESERVED_BYTE;
1651 lock.l_len = 1L;
1652 }else{
1653 lock.l_start = SHARED_FIRST;
1654 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001655 }
dan661d71a2011-03-30 19:08:03 +00001656
1657 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001658 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001659 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001660 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001661 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001662 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001663 }
drhbbd42a62004-05-22 17:41:58 +00001664 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001665
drh8f941bc2009-01-14 23:03:40 +00001666
drhd3d8c042012-05-29 17:02:40 +00001667#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001668 /* Set up the transaction-counter change checking flags when
1669 ** transitioning from a SHARED to a RESERVED lock. The change
1670 ** from SHARED to RESERVED marks the beginning of a normal
1671 ** write operation (not a hot journal rollback).
1672 */
1673 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001674 && pFile->eFileLock<=SHARED_LOCK
1675 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001676 ){
1677 pFile->transCntrChng = 0;
1678 pFile->dbUpdate = 0;
1679 pFile->inNormalWrite = 1;
1680 }
1681#endif
1682
1683
danielk1977ecb2a962004-06-02 06:30:16 +00001684 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001685 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001686 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001687 }else if( eFileLock==EXCLUSIVE_LOCK ){
1688 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001689 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001690 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001691
1692end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001693 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001694 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1695 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001696 return rc;
1697}
1698
1699/*
dan08da86a2009-08-21 17:18:03 +00001700** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001701** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001702*/
1703static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001704 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001705 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001706 p->pNext = pInode->pUnused;
1707 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001708 pFile->h = -1;
1709 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001710}
1711
1712/*
drh308c2a52010-05-14 11:30:18 +00001713** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001714** must be either NO_LOCK or SHARED_LOCK.
1715**
1716** If the locking level of the file descriptor is already at or below
1717** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001718**
1719** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1720** the byte range is divided into 2 parts and the first part is unlocked then
1721** set to a read lock, then the other part is simply unlocked. This works
1722** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1723** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001724*/
drha7e61d82011-03-12 17:02:57 +00001725static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001726 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001727 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001728 struct flock lock;
1729 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001730
drh054889e2005-11-30 03:20:31 +00001731 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001732 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001733 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001734 osGetpid(0)));
drha6abd042004-06-09 17:37:22 +00001735
drh308c2a52010-05-14 11:30:18 +00001736 assert( eFileLock<=SHARED_LOCK );
1737 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001738 return SQLITE_OK;
1739 }
drh6c7d5c52008-11-21 20:32:33 +00001740 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001741 pInode = pFile->pInode;
1742 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001743 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001744 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001745
drhd3d8c042012-05-29 17:02:40 +00001746#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001747 /* When reducing a lock such that other processes can start
1748 ** reading the database file again, make sure that the
1749 ** transaction counter was updated if any part of the database
1750 ** file changed. If the transaction counter is not updated,
1751 ** other connections to the same file might not realize that
1752 ** the file has changed and hence might not know to flush their
1753 ** cache. The use of a stale cache can lead to database corruption.
1754 */
drh8f941bc2009-01-14 23:03:40 +00001755 pFile->inNormalWrite = 0;
1756#endif
1757
drh7ed97b92010-01-20 13:07:21 +00001758 /* downgrading to a shared lock on NFS involves clearing the write lock
1759 ** before establishing the readlock - to avoid a race condition we downgrade
1760 ** the lock in 2 blocks, so that part of the range will be covered by a
1761 ** write lock until the rest is covered by a read lock:
1762 ** 1: [WWWWW]
1763 ** 2: [....W]
1764 ** 3: [RRRRW]
1765 ** 4: [RRRR.]
1766 */
drh308c2a52010-05-14 11:30:18 +00001767 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001768#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001769 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001770 assert( handleNFSUnlock==0 );
1771#endif
1772#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001773 if( handleNFSUnlock ){
drha712b4b2015-02-19 16:12:04 +00001774 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001775 off_t divSize = SHARED_SIZE - 1;
1776
1777 lock.l_type = F_UNLCK;
1778 lock.l_whence = SEEK_SET;
1779 lock.l_start = SHARED_FIRST;
1780 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001781 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001782 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001783 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001784 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001785 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001786 }
drh7ed97b92010-01-20 13:07:21 +00001787 lock.l_type = F_RDLCK;
1788 lock.l_whence = SEEK_SET;
1789 lock.l_start = SHARED_FIRST;
1790 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001791 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001792 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001793 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1794 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001795 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001796 }
1797 goto end_unlock;
1798 }
1799 lock.l_type = F_UNLCK;
1800 lock.l_whence = SEEK_SET;
1801 lock.l_start = SHARED_FIRST+divSize;
1802 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001803 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001804 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001805 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001806 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001807 goto end_unlock;
1808 }
drh30f776f2011-02-25 03:25:07 +00001809 }else
1810#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1811 {
drh7ed97b92010-01-20 13:07:21 +00001812 lock.l_type = F_RDLCK;
1813 lock.l_whence = SEEK_SET;
1814 lock.l_start = SHARED_FIRST;
1815 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001816 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001817 /* In theory, the call to unixFileLock() cannot fail because another
1818 ** process is holding an incompatible lock. If it does, this
1819 ** indicates that the other process is not following the locking
1820 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1821 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1822 ** an assert to fail). */
1823 rc = SQLITE_IOERR_RDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001824 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00001825 goto end_unlock;
1826 }
drh9c105bb2004-10-02 20:38:28 +00001827 }
1828 }
drhbbd42a62004-05-22 17:41:58 +00001829 lock.l_type = F_UNLCK;
1830 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001831 lock.l_start = PENDING_BYTE;
1832 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001833 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001834 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001835 }else{
danea83bc62011-04-01 11:56:32 +00001836 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001837 storeLastErrno(pFile, errno);
drhcd731cf2009-03-28 23:23:02 +00001838 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001839 }
drhbbd42a62004-05-22 17:41:58 +00001840 }
drh308c2a52010-05-14 11:30:18 +00001841 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001842 /* Decrement the shared lock counter. Release the lock using an
1843 ** OS call only when all threads in this same process have released
1844 ** the lock.
1845 */
drh8af6c222010-05-14 12:43:01 +00001846 pInode->nShared--;
1847 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001848 lock.l_type = F_UNLCK;
1849 lock.l_whence = SEEK_SET;
1850 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001851 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001852 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001853 }else{
danea83bc62011-04-01 11:56:32 +00001854 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001855 storeLastErrno(pFile, errno);
drh8af6c222010-05-14 12:43:01 +00001856 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001857 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001858 }
drha6abd042004-06-09 17:37:22 +00001859 }
1860
drhbbd42a62004-05-22 17:41:58 +00001861 /* Decrement the count of locks against this same file. When the
1862 ** count reaches zero, close any other file descriptors whose close
1863 ** was deferred because of outstanding locks.
1864 */
drh8af6c222010-05-14 12:43:01 +00001865 pInode->nLock--;
1866 assert( pInode->nLock>=0 );
1867 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001868 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001869 }
1870 }
drhf2f105d2012-08-20 15:53:54 +00001871
aswift5b1a2562008-08-22 00:22:35 +00001872end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001873 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001874 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001875 return rc;
drhbbd42a62004-05-22 17:41:58 +00001876}
1877
1878/*
drh308c2a52010-05-14 11:30:18 +00001879** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001880** must be either NO_LOCK or SHARED_LOCK.
1881**
1882** If the locking level of the file descriptor is already at or below
1883** the requested locking level, this routine is a no-op.
1884*/
drh308c2a52010-05-14 11:30:18 +00001885static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00001886#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00001887 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00001888#endif
drha7e61d82011-03-12 17:02:57 +00001889 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001890}
1891
mistachkine98844f2013-08-24 00:59:24 +00001892#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001893static int unixMapfile(unixFile *pFd, i64 nByte);
1894static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00001895#endif
danf23da962013-03-23 21:00:41 +00001896
drh7ed97b92010-01-20 13:07:21 +00001897/*
danielk1977e339d652008-06-28 11:23:00 +00001898** This function performs the parts of the "close file" operation
1899** common to all locking schemes. It closes the directory and file
1900** handles, if they are valid, and sets all fields of the unixFile
1901** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001902**
1903** It is *not* necessary to hold the mutex when this routine is called,
1904** even on VxWorks. A mutex will be acquired on VxWorks by the
1905** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001906*/
1907static int closeUnixFile(sqlite3_file *id){
1908 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00001909#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001910 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00001911#endif
dan661d71a2011-03-30 19:08:03 +00001912 if( pFile->h>=0 ){
1913 robust_close(pFile, pFile->h, __LINE__);
1914 pFile->h = -1;
1915 }
1916#if OS_VXWORKS
1917 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001918 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001919 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001920 }
1921 vxworksReleaseFileId(pFile->pId);
1922 pFile->pId = 0;
1923 }
1924#endif
drh0bdbc902014-06-16 18:35:06 +00001925#ifdef SQLITE_UNLINK_AFTER_CLOSE
1926 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
1927 osUnlink(pFile->zPath);
1928 sqlite3_free(*(char**)&pFile->zPath);
1929 pFile->zPath = 0;
1930 }
1931#endif
dan661d71a2011-03-30 19:08:03 +00001932 OSTRACE(("CLOSE %-3d\n", pFile->h));
1933 OpenCounter(-1);
1934 sqlite3_free(pFile->pUnused);
1935 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001936 return SQLITE_OK;
1937}
1938
1939/*
danielk1977e3026632004-06-22 11:29:02 +00001940** Close a file.
1941*/
danielk197762079062007-08-15 17:08:46 +00001942static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001943 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001944 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00001945 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00001946 unixUnlock(id, NO_LOCK);
1947 unixEnterMutex();
1948
1949 /* unixFile.pInode is always valid here. Otherwise, a different close
1950 ** routine (e.g. nolockClose()) would be called instead.
1951 */
1952 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1953 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1954 /* If there are outstanding locks, do not actually close the file just
1955 ** yet because that would clear those locks. Instead, add the file
1956 ** descriptor to pInode->pUnused list. It will be automatically closed
1957 ** when the last lock is cleared.
1958 */
1959 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001960 }
dan661d71a2011-03-30 19:08:03 +00001961 releaseInodeInfo(pFile);
1962 rc = closeUnixFile(id);
1963 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001964 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001965}
1966
drh734c9862008-11-28 15:37:20 +00001967/************** End of the posix advisory lock implementation *****************
1968******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001969
drh734c9862008-11-28 15:37:20 +00001970/******************************************************************************
1971****************************** No-op Locking **********************************
1972**
1973** Of the various locking implementations available, this is by far the
1974** simplest: locking is ignored. No attempt is made to lock the database
1975** file for reading or writing.
1976**
1977** This locking mode is appropriate for use on read-only databases
1978** (ex: databases that are burned into CD-ROM, for example.) It can
1979** also be used if the application employs some external mechanism to
1980** prevent simultaneous access of the same database by two or more
1981** database connections. But there is a serious risk of database
1982** corruption if this locking mode is used in situations where multiple
1983** database connections are accessing the same database file at the same
1984** time and one or more of those connections are writing.
1985*/
drhbfe66312006-10-03 17:40:40 +00001986
drh734c9862008-11-28 15:37:20 +00001987static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1988 UNUSED_PARAMETER(NotUsed);
1989 *pResOut = 0;
1990 return SQLITE_OK;
1991}
drh734c9862008-11-28 15:37:20 +00001992static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1993 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1994 return SQLITE_OK;
1995}
drh734c9862008-11-28 15:37:20 +00001996static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1997 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1998 return SQLITE_OK;
1999}
2000
2001/*
drh9b35ea62008-11-29 02:20:26 +00002002** Close the file.
drh734c9862008-11-28 15:37:20 +00002003*/
2004static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00002005 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002006}
2007
2008/******************* End of the no-op lock implementation *********************
2009******************************************************************************/
2010
2011/******************************************************************************
2012************************* Begin dot-file Locking ******************************
2013**
mistachkin48864df2013-03-21 21:20:32 +00002014** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00002015** files (really a directory) to control access to the database. This works
2016** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002017**
2018** (1) There is zero concurrency. A single reader blocks all other
2019** connections from reading or writing the database.
2020**
2021** (2) An application crash or power loss can leave stale lock files
2022** sitting around that need to be cleared manually.
2023**
2024** Nevertheless, a dotlock is an appropriate locking mode for use if no
2025** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002026**
drh9ef6bc42011-11-04 02:24:02 +00002027** Dotfile locking works by creating a subdirectory in the same directory as
2028** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002029** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002030** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002031*/
2032
2033/*
2034** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002035** lock directory.
drh734c9862008-11-28 15:37:20 +00002036*/
2037#define DOTLOCK_SUFFIX ".lock"
2038
drh7708e972008-11-29 00:56:52 +00002039/*
2040** This routine checks if there is a RESERVED lock held on the specified
2041** file by this or any other process. If such a lock is held, set *pResOut
2042** to a non-zero value otherwise *pResOut is set to zero. The return value
2043** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2044**
2045** In dotfile locking, either a lock exists or it does not. So in this
2046** variation of CheckReservedLock(), *pResOut is set to true if any lock
2047** is held on the file and false if the file is unlocked.
2048*/
drh734c9862008-11-28 15:37:20 +00002049static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2050 int rc = SQLITE_OK;
2051 int reserved = 0;
2052 unixFile *pFile = (unixFile*)id;
2053
2054 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2055
2056 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00002057 reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
drh308c2a52010-05-14 11:30:18 +00002058 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002059 *pResOut = reserved;
2060 return rc;
2061}
2062
drh7708e972008-11-29 00:56:52 +00002063/*
drh308c2a52010-05-14 11:30:18 +00002064** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002065** of the following:
2066**
2067** (1) SHARED_LOCK
2068** (2) RESERVED_LOCK
2069** (3) PENDING_LOCK
2070** (4) EXCLUSIVE_LOCK
2071**
2072** Sometimes when requesting one lock state, additional lock states
2073** are inserted in between. The locking might fail on one of the later
2074** transitions leaving the lock state different from what it started but
2075** still short of its goal. The following chart shows the allowed
2076** transitions and the inserted intermediate states:
2077**
2078** UNLOCKED -> SHARED
2079** SHARED -> RESERVED
2080** SHARED -> (PENDING) -> EXCLUSIVE
2081** RESERVED -> (PENDING) -> EXCLUSIVE
2082** PENDING -> EXCLUSIVE
2083**
2084** This routine will only increase a lock. Use the sqlite3OsUnlock()
2085** routine to lower a locking level.
2086**
2087** With dotfile locking, we really only support state (4): EXCLUSIVE.
2088** But we track the other locking levels internally.
2089*/
drh308c2a52010-05-14 11:30:18 +00002090static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002091 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002092 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002093 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002094
drh7708e972008-11-29 00:56:52 +00002095
2096 /* If we have any lock, then the lock file already exists. All we have
2097 ** to do is adjust our internal record of the lock level.
2098 */
drh308c2a52010-05-14 11:30:18 +00002099 if( pFile->eFileLock > NO_LOCK ){
2100 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002101 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002102#ifdef HAVE_UTIME
2103 utime(zLockFile, NULL);
2104#else
drh734c9862008-11-28 15:37:20 +00002105 utimes(zLockFile, NULL);
2106#endif
drh7708e972008-11-29 00:56:52 +00002107 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002108 }
2109
2110 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002111 rc = osMkdir(zLockFile, 0777);
2112 if( rc<0 ){
2113 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002114 int tErrno = errno;
2115 if( EEXIST == tErrno ){
2116 rc = SQLITE_BUSY;
2117 } else {
2118 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drha8de1e12015-11-30 00:05:39 +00002119 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00002120 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002121 }
2122 }
drh7708e972008-11-29 00:56:52 +00002123 return rc;
drh734c9862008-11-28 15:37:20 +00002124 }
drh734c9862008-11-28 15:37:20 +00002125
2126 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002127 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002128 return rc;
2129}
2130
drh7708e972008-11-29 00:56:52 +00002131/*
drh308c2a52010-05-14 11:30:18 +00002132** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002133** must be either NO_LOCK or SHARED_LOCK.
2134**
2135** If the locking level of the file descriptor is already at or below
2136** the requested locking level, this routine is a no-op.
2137**
2138** When the locking level reaches NO_LOCK, delete the lock file.
2139*/
drh308c2a52010-05-14 11:30:18 +00002140static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002141 unixFile *pFile = (unixFile*)id;
2142 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002143 int rc;
drh734c9862008-11-28 15:37:20 +00002144
2145 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002146 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002147 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002148 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002149
2150 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002151 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002152 return SQLITE_OK;
2153 }
drh7708e972008-11-29 00:56:52 +00002154
2155 /* To downgrade to shared, simply update our internal notion of the
2156 ** lock state. No need to mess with the file on disk.
2157 */
drh308c2a52010-05-14 11:30:18 +00002158 if( eFileLock==SHARED_LOCK ){
2159 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002160 return SQLITE_OK;
2161 }
2162
drh7708e972008-11-29 00:56:52 +00002163 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002164 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002165 rc = osRmdir(zLockFile);
drh9ef6bc42011-11-04 02:24:02 +00002166 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002167 int tErrno = errno;
drha8de1e12015-11-30 00:05:39 +00002168 if( tErrno==ENOENT ){
2169 rc = SQLITE_OK;
2170 }else{
danea83bc62011-04-01 11:56:32 +00002171 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002172 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002173 }
2174 return rc;
2175 }
drh308c2a52010-05-14 11:30:18 +00002176 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002177 return SQLITE_OK;
2178}
2179
2180/*
drh9b35ea62008-11-29 02:20:26 +00002181** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002182*/
2183static int dotlockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002184 unixFile *pFile = (unixFile*)id;
2185 assert( id!=0 );
2186 dotlockUnlock(id, NO_LOCK);
2187 sqlite3_free(pFile->lockingContext);
2188 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002189}
2190/****************** End of the dot-file lock implementation *******************
2191******************************************************************************/
2192
2193/******************************************************************************
2194************************** Begin flock Locking ********************************
2195**
2196** Use the flock() system call to do file locking.
2197**
drh6b9d6dd2008-12-03 19:34:47 +00002198** flock() locking is like dot-file locking in that the various
2199** fine-grain locking levels supported by SQLite are collapsed into
2200** a single exclusive lock. In other words, SHARED, RESERVED, and
2201** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2202** still works when you do this, but concurrency is reduced since
2203** only a single process can be reading the database at a time.
2204**
drhe89b2912015-03-03 20:42:01 +00002205** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
drh734c9862008-11-28 15:37:20 +00002206*/
drhe89b2912015-03-03 20:42:01 +00002207#if SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002208
drh6b9d6dd2008-12-03 19:34:47 +00002209/*
drhff812312011-02-23 13:33:46 +00002210** Retry flock() calls that fail with EINTR
2211*/
2212#ifdef EINTR
2213static int robust_flock(int fd, int op){
2214 int rc;
2215 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2216 return rc;
2217}
2218#else
drh5c819272011-02-23 14:00:12 +00002219# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002220#endif
2221
2222
2223/*
drh6b9d6dd2008-12-03 19:34:47 +00002224** This routine checks if there is a RESERVED lock held on the specified
2225** file by this or any other process. If such a lock is held, set *pResOut
2226** to a non-zero value otherwise *pResOut is set to zero. The return value
2227** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2228*/
drh734c9862008-11-28 15:37:20 +00002229static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2230 int rc = SQLITE_OK;
2231 int reserved = 0;
2232 unixFile *pFile = (unixFile*)id;
2233
2234 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2235
2236 assert( pFile );
2237
2238 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002239 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002240 reserved = 1;
2241 }
2242
2243 /* Otherwise see if some other process holds it. */
2244 if( !reserved ){
2245 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002246 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002247 if( !lrc ){
2248 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002249 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002250 if ( lrc ) {
2251 int tErrno = errno;
2252 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002253 lrc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00002254 storeLastErrno(pFile, tErrno);
2255 rc = lrc;
drh734c9862008-11-28 15:37:20 +00002256 }
2257 } else {
2258 int tErrno = errno;
2259 reserved = 1;
2260 /* someone else might have it reserved */
2261 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2262 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002263 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002264 rc = lrc;
2265 }
2266 }
2267 }
drh308c2a52010-05-14 11:30:18 +00002268 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002269
2270#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2271 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2272 rc = SQLITE_OK;
2273 reserved=1;
2274 }
2275#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2276 *pResOut = reserved;
2277 return rc;
2278}
2279
drh6b9d6dd2008-12-03 19:34:47 +00002280/*
drh308c2a52010-05-14 11:30:18 +00002281** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002282** of the following:
2283**
2284** (1) SHARED_LOCK
2285** (2) RESERVED_LOCK
2286** (3) PENDING_LOCK
2287** (4) EXCLUSIVE_LOCK
2288**
2289** Sometimes when requesting one lock state, additional lock states
2290** are inserted in between. The locking might fail on one of the later
2291** transitions leaving the lock state different from what it started but
2292** still short of its goal. The following chart shows the allowed
2293** transitions and the inserted intermediate states:
2294**
2295** UNLOCKED -> SHARED
2296** SHARED -> RESERVED
2297** SHARED -> (PENDING) -> EXCLUSIVE
2298** RESERVED -> (PENDING) -> EXCLUSIVE
2299** PENDING -> EXCLUSIVE
2300**
2301** flock() only really support EXCLUSIVE locks. We track intermediate
2302** lock states in the sqlite3_file structure, but all locks SHARED or
2303** above are really EXCLUSIVE locks and exclude all other processes from
2304** access the file.
2305**
2306** This routine will only increase a lock. Use the sqlite3OsUnlock()
2307** routine to lower a locking level.
2308*/
drh308c2a52010-05-14 11:30:18 +00002309static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002310 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002311 unixFile *pFile = (unixFile*)id;
2312
2313 assert( pFile );
2314
2315 /* if we already have a lock, it is exclusive.
2316 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002317 if (pFile->eFileLock > NO_LOCK) {
2318 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002319 return SQLITE_OK;
2320 }
2321
2322 /* grab an exclusive lock */
2323
drhff812312011-02-23 13:33:46 +00002324 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002325 int tErrno = errno;
2326 /* didn't get, must be busy */
2327 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2328 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002329 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002330 }
2331 } else {
2332 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002333 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002334 }
drh308c2a52010-05-14 11:30:18 +00002335 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2336 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002337#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2338 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2339 rc = SQLITE_BUSY;
2340 }
2341#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2342 return rc;
2343}
2344
drh6b9d6dd2008-12-03 19:34:47 +00002345
2346/*
drh308c2a52010-05-14 11:30:18 +00002347** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002348** must be either NO_LOCK or SHARED_LOCK.
2349**
2350** If the locking level of the file descriptor is already at or below
2351** the requested locking level, this routine is a no-op.
2352*/
drh308c2a52010-05-14 11:30:18 +00002353static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002354 unixFile *pFile = (unixFile*)id;
2355
2356 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002357 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002358 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002359 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002360
2361 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002362 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002363 return SQLITE_OK;
2364 }
2365
2366 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002367 if (eFileLock==SHARED_LOCK) {
2368 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002369 return SQLITE_OK;
2370 }
2371
2372 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002373 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002374#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002375 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002376#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002377 return SQLITE_IOERR_UNLOCK;
2378 }else{
drh308c2a52010-05-14 11:30:18 +00002379 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002380 return SQLITE_OK;
2381 }
2382}
2383
2384/*
2385** Close a file.
2386*/
2387static int flockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002388 assert( id!=0 );
2389 flockUnlock(id, NO_LOCK);
2390 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002391}
2392
2393#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2394
2395/******************* End of the flock lock implementation *********************
2396******************************************************************************/
2397
2398/******************************************************************************
2399************************ Begin Named Semaphore Locking ************************
2400**
2401** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002402**
2403** Semaphore locking is like dot-lock and flock in that it really only
2404** supports EXCLUSIVE locking. Only a single process can read or write
2405** the database file at a time. This reduces potential concurrency, but
2406** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002407*/
2408#if OS_VXWORKS
2409
drh6b9d6dd2008-12-03 19:34:47 +00002410/*
2411** This routine checks if there is a RESERVED lock held on the specified
2412** file by this or any other process. If such a lock is held, set *pResOut
2413** to a non-zero value otherwise *pResOut is set to zero. The return value
2414** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2415*/
drh8cd5b252015-03-02 22:06:43 +00002416static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
drh734c9862008-11-28 15:37:20 +00002417 int rc = SQLITE_OK;
2418 int reserved = 0;
2419 unixFile *pFile = (unixFile*)id;
2420
2421 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2422
2423 assert( pFile );
2424
2425 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002426 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002427 reserved = 1;
2428 }
2429
2430 /* Otherwise see if some other process holds it. */
2431 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002432 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002433
2434 if( sem_trywait(pSem)==-1 ){
2435 int tErrno = errno;
2436 if( EAGAIN != tErrno ){
2437 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
drh4bf66fd2015-02-19 02:43:02 +00002438 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002439 } else {
2440 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002441 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002442 }
2443 }else{
2444 /* we could have it if we want it */
2445 sem_post(pSem);
2446 }
2447 }
drh308c2a52010-05-14 11:30:18 +00002448 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002449
2450 *pResOut = reserved;
2451 return rc;
2452}
2453
drh6b9d6dd2008-12-03 19:34:47 +00002454/*
drh308c2a52010-05-14 11:30:18 +00002455** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002456** of the following:
2457**
2458** (1) SHARED_LOCK
2459** (2) RESERVED_LOCK
2460** (3) PENDING_LOCK
2461** (4) EXCLUSIVE_LOCK
2462**
2463** Sometimes when requesting one lock state, additional lock states
2464** are inserted in between. The locking might fail on one of the later
2465** transitions leaving the lock state different from what it started but
2466** still short of its goal. The following chart shows the allowed
2467** transitions and the inserted intermediate states:
2468**
2469** UNLOCKED -> SHARED
2470** SHARED -> RESERVED
2471** SHARED -> (PENDING) -> EXCLUSIVE
2472** RESERVED -> (PENDING) -> EXCLUSIVE
2473** PENDING -> EXCLUSIVE
2474**
2475** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2476** lock states in the sqlite3_file structure, but all locks SHARED or
2477** above are really EXCLUSIVE locks and exclude all other processes from
2478** access the file.
2479**
2480** This routine will only increase a lock. Use the sqlite3OsUnlock()
2481** routine to lower a locking level.
2482*/
drh8cd5b252015-03-02 22:06:43 +00002483static int semXLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002484 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002485 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002486 int rc = SQLITE_OK;
2487
2488 /* if we already have a lock, it is exclusive.
2489 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002490 if (pFile->eFileLock > NO_LOCK) {
2491 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002492 rc = SQLITE_OK;
2493 goto sem_end_lock;
2494 }
2495
2496 /* lock semaphore now but bail out when already locked. */
2497 if( sem_trywait(pSem)==-1 ){
2498 rc = SQLITE_BUSY;
2499 goto sem_end_lock;
2500 }
2501
2502 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002503 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002504
2505 sem_end_lock:
2506 return rc;
2507}
2508
drh6b9d6dd2008-12-03 19:34:47 +00002509/*
drh308c2a52010-05-14 11:30:18 +00002510** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002511** must be either NO_LOCK or SHARED_LOCK.
2512**
2513** If the locking level of the file descriptor is already at or below
2514** the requested locking level, this routine is a no-op.
2515*/
drh8cd5b252015-03-02 22:06:43 +00002516static int semXUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002517 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002518 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002519
2520 assert( pFile );
2521 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002522 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002523 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002524 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002525
2526 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002527 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002528 return SQLITE_OK;
2529 }
2530
2531 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002532 if (eFileLock==SHARED_LOCK) {
2533 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002534 return SQLITE_OK;
2535 }
2536
2537 /* no, really unlock. */
2538 if ( sem_post(pSem)==-1 ) {
2539 int rc, tErrno = errno;
2540 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2541 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002542 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002543 }
2544 return rc;
2545 }
drh308c2a52010-05-14 11:30:18 +00002546 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002547 return SQLITE_OK;
2548}
2549
2550/*
2551 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002552 */
drh8cd5b252015-03-02 22:06:43 +00002553static int semXClose(sqlite3_file *id) {
drh734c9862008-11-28 15:37:20 +00002554 if( id ){
2555 unixFile *pFile = (unixFile*)id;
drh8cd5b252015-03-02 22:06:43 +00002556 semXUnlock(id, NO_LOCK);
drh734c9862008-11-28 15:37:20 +00002557 assert( pFile );
2558 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002559 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002560 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002561 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002562 }
2563 return SQLITE_OK;
2564}
2565
2566#endif /* OS_VXWORKS */
2567/*
2568** Named semaphore locking is only available on VxWorks.
2569**
2570*************** End of the named semaphore lock implementation ****************
2571******************************************************************************/
2572
2573
2574/******************************************************************************
2575*************************** Begin AFP Locking *********************************
2576**
2577** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2578** on Apple Macintosh computers - both OS9 and OSX.
2579**
2580** Third-party implementations of AFP are available. But this code here
2581** only works on OSX.
2582*/
2583
drhd2cb50b2009-01-09 21:41:17 +00002584#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002585/*
2586** The afpLockingContext structure contains all afp lock specific state
2587*/
drhbfe66312006-10-03 17:40:40 +00002588typedef struct afpLockingContext afpLockingContext;
2589struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002590 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002591 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002592};
2593
2594struct ByteRangeLockPB2
2595{
2596 unsigned long long offset; /* offset to first byte to lock */
2597 unsigned long long length; /* nbr of bytes to lock */
2598 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2599 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2600 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2601 int fd; /* file desc to assoc this lock with */
2602};
2603
drhfd131da2007-08-07 17:13:03 +00002604#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002605
drh6b9d6dd2008-12-03 19:34:47 +00002606/*
2607** This is a utility for setting or clearing a bit-range lock on an
2608** AFP filesystem.
2609**
2610** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2611*/
2612static int afpSetLock(
2613 const char *path, /* Name of the file to be locked or unlocked */
2614 unixFile *pFile, /* Open file descriptor on path */
2615 unsigned long long offset, /* First byte to be locked */
2616 unsigned long long length, /* Number of bytes to lock */
2617 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002618){
drh6b9d6dd2008-12-03 19:34:47 +00002619 struct ByteRangeLockPB2 pb;
2620 int err;
drhbfe66312006-10-03 17:40:40 +00002621
2622 pb.unLockFlag = setLockFlag ? 0 : 1;
2623 pb.startEndFlag = 0;
2624 pb.offset = offset;
2625 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002626 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002627
drh308c2a52010-05-14 11:30:18 +00002628 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002629 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002630 offset, length));
drhbfe66312006-10-03 17:40:40 +00002631 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2632 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002633 int rc;
2634 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002635 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2636 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002637#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2638 rc = SQLITE_BUSY;
2639#else
drh734c9862008-11-28 15:37:20 +00002640 rc = sqliteErrorFromPosixError(tErrno,
2641 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002642#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002643 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002644 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00002645 }
2646 return rc;
drhbfe66312006-10-03 17:40:40 +00002647 } else {
aswift5b1a2562008-08-22 00:22:35 +00002648 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002649 }
2650}
2651
drh6b9d6dd2008-12-03 19:34:47 +00002652/*
2653** This routine checks if there is a RESERVED lock held on the specified
2654** file by this or any other process. If such a lock is held, set *pResOut
2655** to a non-zero value otherwise *pResOut is set to zero. The return value
2656** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2657*/
danielk1977e339d652008-06-28 11:23:00 +00002658static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002659 int rc = SQLITE_OK;
2660 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002661 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002662 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002663
aswift5b1a2562008-08-22 00:22:35 +00002664 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2665
2666 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002667 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002668 if( context->reserved ){
2669 *pResOut = 1;
2670 return SQLITE_OK;
2671 }
drh8af6c222010-05-14 12:43:01 +00002672 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002673
2674 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002675 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002676 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002677 }
2678
2679 /* Otherwise see if some other process holds it.
2680 */
aswift5b1a2562008-08-22 00:22:35 +00002681 if( !reserved ){
2682 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002683 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002684 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002685 /* if we succeeded in taking the reserved lock, unlock it to restore
2686 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002687 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002688 } else {
2689 /* if we failed to get the lock then someone else must have it */
2690 reserved = 1;
2691 }
2692 if( IS_LOCK_ERROR(lrc) ){
2693 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002694 }
2695 }
drhbfe66312006-10-03 17:40:40 +00002696
drh7ed97b92010-01-20 13:07:21 +00002697 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002698 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002699
2700 *pResOut = reserved;
2701 return rc;
drhbfe66312006-10-03 17:40:40 +00002702}
2703
drh6b9d6dd2008-12-03 19:34:47 +00002704/*
drh308c2a52010-05-14 11:30:18 +00002705** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002706** of the following:
2707**
2708** (1) SHARED_LOCK
2709** (2) RESERVED_LOCK
2710** (3) PENDING_LOCK
2711** (4) EXCLUSIVE_LOCK
2712**
2713** Sometimes when requesting one lock state, additional lock states
2714** are inserted in between. The locking might fail on one of the later
2715** transitions leaving the lock state different from what it started but
2716** still short of its goal. The following chart shows the allowed
2717** transitions and the inserted intermediate states:
2718**
2719** UNLOCKED -> SHARED
2720** SHARED -> RESERVED
2721** SHARED -> (PENDING) -> EXCLUSIVE
2722** RESERVED -> (PENDING) -> EXCLUSIVE
2723** PENDING -> EXCLUSIVE
2724**
2725** This routine will only increase a lock. Use the sqlite3OsUnlock()
2726** routine to lower a locking level.
2727*/
drh308c2a52010-05-14 11:30:18 +00002728static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002729 int rc = SQLITE_OK;
2730 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002731 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002732 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002733
2734 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002735 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2736 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh5ac93652015-03-21 20:59:43 +00002737 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
drh339eb0b2008-03-07 15:34:11 +00002738
drhbfe66312006-10-03 17:40:40 +00002739 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002740 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002741 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002742 */
drh308c2a52010-05-14 11:30:18 +00002743 if( pFile->eFileLock>=eFileLock ){
2744 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2745 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002746 return SQLITE_OK;
2747 }
2748
2749 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002750 ** (1) We never move from unlocked to anything higher than shared lock.
2751 ** (2) SQLite never explicitly requests a pendig lock.
2752 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002753 */
drh308c2a52010-05-14 11:30:18 +00002754 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2755 assert( eFileLock!=PENDING_LOCK );
2756 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002757
drh8af6c222010-05-14 12:43:01 +00002758 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002759 */
drh6c7d5c52008-11-21 20:32:33 +00002760 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002761 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002762
2763 /* If some thread using this PID has a lock via a different unixFile*
2764 ** handle that precludes the requested lock, return BUSY.
2765 */
drh8af6c222010-05-14 12:43:01 +00002766 if( (pFile->eFileLock!=pInode->eFileLock &&
2767 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002768 ){
2769 rc = SQLITE_BUSY;
2770 goto afp_end_lock;
2771 }
2772
2773 /* If a SHARED lock is requested, and some thread using this PID already
2774 ** has a SHARED or RESERVED lock, then increment reference counts and
2775 ** return SQLITE_OK.
2776 */
drh308c2a52010-05-14 11:30:18 +00002777 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002778 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002779 assert( eFileLock==SHARED_LOCK );
2780 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002781 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002782 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002783 pInode->nShared++;
2784 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002785 goto afp_end_lock;
2786 }
drhbfe66312006-10-03 17:40:40 +00002787
2788 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002789 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2790 ** be released.
2791 */
drh308c2a52010-05-14 11:30:18 +00002792 if( eFileLock==SHARED_LOCK
2793 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002794 ){
2795 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002796 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002797 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002798 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002799 goto afp_end_lock;
2800 }
2801 }
2802
2803 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002804 ** operating system calls for the specified lock.
2805 */
drh308c2a52010-05-14 11:30:18 +00002806 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002807 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002808 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002809
drh8af6c222010-05-14 12:43:01 +00002810 assert( pInode->nShared==0 );
2811 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002812
2813 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002814 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002815 /* note that the quality of the randomness doesn't matter that much */
2816 lk = random();
drh8af6c222010-05-14 12:43:01 +00002817 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002818 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002819 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002820 if( IS_LOCK_ERROR(lrc1) ){
2821 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002822 }
aswift5b1a2562008-08-22 00:22:35 +00002823 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002824 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002825
aswift5b1a2562008-08-22 00:22:35 +00002826 if( IS_LOCK_ERROR(lrc1) ) {
drh4bf66fd2015-02-19 02:43:02 +00002827 storeLastErrno(pFile, lrc1Errno);
aswift5b1a2562008-08-22 00:22:35 +00002828 rc = lrc1;
2829 goto afp_end_lock;
2830 } else if( IS_LOCK_ERROR(lrc2) ){
2831 rc = lrc2;
2832 goto afp_end_lock;
2833 } else if( lrc1 != SQLITE_OK ) {
2834 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002835 } else {
drh308c2a52010-05-14 11:30:18 +00002836 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002837 pInode->nLock++;
2838 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002839 }
drh8af6c222010-05-14 12:43:01 +00002840 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002841 /* We are trying for an exclusive lock but another thread in this
2842 ** same process is still holding a shared lock. */
2843 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002844 }else{
2845 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2846 ** assumed that there is a SHARED or greater lock on the file
2847 ** already.
2848 */
2849 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002850 assert( 0!=pFile->eFileLock );
2851 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002852 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002853 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002854 if( !failed ){
2855 context->reserved = 1;
2856 }
drhbfe66312006-10-03 17:40:40 +00002857 }
drh308c2a52010-05-14 11:30:18 +00002858 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002859 /* Acquire an EXCLUSIVE lock */
2860
2861 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002862 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002863 */
drh6b9d6dd2008-12-03 19:34:47 +00002864 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002865 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002866 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002867 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002868 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002869 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002870 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002871 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002872 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2873 ** a critical I/O error
2874 */
2875 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2876 SQLITE_IOERR_LOCK;
2877 goto afp_end_lock;
2878 }
2879 }else{
aswift5b1a2562008-08-22 00:22:35 +00002880 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002881 }
2882 }
aswift5b1a2562008-08-22 00:22:35 +00002883 if( failed ){
2884 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002885 }
2886 }
2887
2888 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002889 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002890 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002891 }else if( eFileLock==EXCLUSIVE_LOCK ){
2892 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002893 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002894 }
2895
2896afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002897 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002898 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2899 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002900 return rc;
2901}
2902
2903/*
drh308c2a52010-05-14 11:30:18 +00002904** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002905** must be either NO_LOCK or SHARED_LOCK.
2906**
2907** If the locking level of the file descriptor is already at or below
2908** the requested locking level, this routine is a no-op.
2909*/
drh308c2a52010-05-14 11:30:18 +00002910static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002911 int rc = SQLITE_OK;
2912 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002913 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002914 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2915 int skipShared = 0;
2916#ifdef SQLITE_TEST
2917 int h = pFile->h;
2918#endif
drhbfe66312006-10-03 17:40:40 +00002919
2920 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002921 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002922 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00002923 osGetpid(0)));
aswift5b1a2562008-08-22 00:22:35 +00002924
drh308c2a52010-05-14 11:30:18 +00002925 assert( eFileLock<=SHARED_LOCK );
2926 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002927 return SQLITE_OK;
2928 }
drh6c7d5c52008-11-21 20:32:33 +00002929 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002930 pInode = pFile->pInode;
2931 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002932 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002933 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002934 SimulateIOErrorBenign(1);
2935 SimulateIOError( h=(-1) )
2936 SimulateIOErrorBenign(0);
2937
drhd3d8c042012-05-29 17:02:40 +00002938#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002939 /* When reducing a lock such that other processes can start
2940 ** reading the database file again, make sure that the
2941 ** transaction counter was updated if any part of the database
2942 ** file changed. If the transaction counter is not updated,
2943 ** other connections to the same file might not realize that
2944 ** the file has changed and hence might not know to flush their
2945 ** cache. The use of a stale cache can lead to database corruption.
2946 */
2947 assert( pFile->inNormalWrite==0
2948 || pFile->dbUpdate==0
2949 || pFile->transCntrChng==1 );
2950 pFile->inNormalWrite = 0;
2951#endif
aswiftaebf4132008-11-21 00:10:35 +00002952
drh308c2a52010-05-14 11:30:18 +00002953 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002954 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002955 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002956 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002957 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002958 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2959 } else {
2960 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002961 }
2962 }
drh308c2a52010-05-14 11:30:18 +00002963 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002964 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002965 }
drh308c2a52010-05-14 11:30:18 +00002966 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002967 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2968 if( !rc ){
2969 context->reserved = 0;
2970 }
aswiftaebf4132008-11-21 00:10:35 +00002971 }
drh8af6c222010-05-14 12:43:01 +00002972 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2973 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002974 }
aswiftaebf4132008-11-21 00:10:35 +00002975 }
drh308c2a52010-05-14 11:30:18 +00002976 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002977
drh7ed97b92010-01-20 13:07:21 +00002978 /* Decrement the shared lock counter. Release the lock using an
2979 ** OS call only when all threads in this same process have released
2980 ** the lock.
2981 */
drh8af6c222010-05-14 12:43:01 +00002982 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2983 pInode->nShared--;
2984 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002985 SimulateIOErrorBenign(1);
2986 SimulateIOError( h=(-1) )
2987 SimulateIOErrorBenign(0);
2988 if( !skipShared ){
2989 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2990 }
2991 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002992 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002993 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002994 }
2995 }
2996 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002997 pInode->nLock--;
2998 assert( pInode->nLock>=0 );
2999 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00003000 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00003001 }
3002 }
drhbfe66312006-10-03 17:40:40 +00003003 }
drh7ed97b92010-01-20 13:07:21 +00003004
drh6c7d5c52008-11-21 20:32:33 +00003005 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00003006 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00003007 return rc;
3008}
3009
3010/*
drh339eb0b2008-03-07 15:34:11 +00003011** Close a file & cleanup AFP specific locking context
3012*/
danielk1977e339d652008-06-28 11:23:00 +00003013static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003014 int rc = SQLITE_OK;
drha8de1e12015-11-30 00:05:39 +00003015 unixFile *pFile = (unixFile*)id;
3016 assert( id!=0 );
3017 afpUnlock(id, NO_LOCK);
3018 unixEnterMutex();
3019 if( pFile->pInode && pFile->pInode->nLock ){
3020 /* If there are outstanding locks, do not actually close the file just
3021 ** yet because that would clear those locks. Instead, add the file
3022 ** descriptor to pInode->aPending. It will be automatically closed when
3023 ** the last lock is cleared.
3024 */
3025 setPendingFd(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003026 }
drha8de1e12015-11-30 00:05:39 +00003027 releaseInodeInfo(pFile);
3028 sqlite3_free(pFile->lockingContext);
3029 rc = closeUnixFile(id);
3030 unixLeaveMutex();
drh7ed97b92010-01-20 13:07:21 +00003031 return rc;
drhbfe66312006-10-03 17:40:40 +00003032}
3033
drhd2cb50b2009-01-09 21:41:17 +00003034#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003035/*
3036** The code above is the AFP lock implementation. The code is specific
3037** to MacOSX and does not work on other unix platforms. No alternative
3038** is available. If you don't compile for a mac, then the "unix-afp"
3039** VFS is not available.
3040**
3041********************* End of the AFP lock implementation **********************
3042******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003043
drh7ed97b92010-01-20 13:07:21 +00003044/******************************************************************************
3045*************************** Begin NFS Locking ********************************/
3046
3047#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3048/*
drh308c2a52010-05-14 11:30:18 +00003049 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003050 ** must be either NO_LOCK or SHARED_LOCK.
3051 **
3052 ** If the locking level of the file descriptor is already at or below
3053 ** the requested locking level, this routine is a no-op.
3054 */
drh308c2a52010-05-14 11:30:18 +00003055static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003056 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003057}
3058
3059#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3060/*
3061** The code above is the NFS lock implementation. The code is specific
3062** to MacOSX and does not work on other unix platforms. No alternative
3063** is available.
3064**
3065********************* End of the NFS lock implementation **********************
3066******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003067
3068/******************************************************************************
3069**************** Non-locking sqlite3_file methods *****************************
3070**
3071** The next division contains implementations for all methods of the
3072** sqlite3_file object other than the locking methods. The locking
3073** methods were defined in divisions above (one locking method per
3074** division). Those methods that are common to all locking modes
3075** are gather together into this division.
3076*/
drhbfe66312006-10-03 17:40:40 +00003077
3078/*
drh734c9862008-11-28 15:37:20 +00003079** Seek to the offset passed as the second argument, then read cnt
3080** bytes into pBuf. Return the number of bytes actually read.
3081**
3082** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3083** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3084** one system to another. Since SQLite does not define USE_PREAD
peter.d.reid60ec9142014-09-06 16:39:46 +00003085** in any form by default, we will not attempt to define _XOPEN_SOURCE.
drh734c9862008-11-28 15:37:20 +00003086** See tickets #2741 and #2681.
3087**
3088** To avoid stomping the errno value on a failed read the lastErrno value
3089** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003090*/
drh734c9862008-11-28 15:37:20 +00003091static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3092 int got;
drh58024642011-11-07 18:16:00 +00003093 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003094#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003095 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003096#endif
drh734c9862008-11-28 15:37:20 +00003097 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003098 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003099 assert( id->h>2 );
drh58024642011-11-07 18:16:00 +00003100 do{
drh734c9862008-11-28 15:37:20 +00003101#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003102 got = osPread(id->h, pBuf, cnt, offset);
3103 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003104#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003105 got = osPread64(id->h, pBuf, cnt, offset);
3106 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003107#else
drh58024642011-11-07 18:16:00 +00003108 newOffset = lseek(id->h, offset, SEEK_SET);
drhe1818ec2015-12-01 16:21:35 +00003109 SimulateIOError( newOffset = -1 );
3110 if( newOffset<0 ){
3111 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003112 return -1;
drh734c9862008-11-28 15:37:20 +00003113 }
drh58024642011-11-07 18:16:00 +00003114 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003115#endif
drh58024642011-11-07 18:16:00 +00003116 if( got==cnt ) break;
3117 if( got<0 ){
3118 if( errno==EINTR ){ got = 1; continue; }
3119 prior = 0;
drh4bf66fd2015-02-19 02:43:02 +00003120 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003121 break;
3122 }else if( got>0 ){
3123 cnt -= got;
3124 offset += got;
3125 prior += got;
3126 pBuf = (void*)(got + (char*)pBuf);
3127 }
3128 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003129 TIMER_END;
drh58024642011-11-07 18:16:00 +00003130 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3131 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3132 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003133}
3134
3135/*
drh734c9862008-11-28 15:37:20 +00003136** Read data from a file into a buffer. Return SQLITE_OK if all
3137** bytes were read successfully and SQLITE_IOERR if anything goes
3138** wrong.
drh339eb0b2008-03-07 15:34:11 +00003139*/
drh734c9862008-11-28 15:37:20 +00003140static int unixRead(
3141 sqlite3_file *id,
3142 void *pBuf,
3143 int amt,
3144 sqlite3_int64 offset
3145){
dan08da86a2009-08-21 17:18:03 +00003146 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003147 int got;
3148 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003149 assert( offset>=0 );
3150 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003151
dan08da86a2009-08-21 17:18:03 +00003152 /* If this is a database file (not a journal, master-journal or temp
3153 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003154#if 0
dane946c392009-08-22 11:39:46 +00003155 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003156 || offset>=PENDING_BYTE+512
3157 || offset+amt<=PENDING_BYTE
3158 );
dan7c246102010-04-12 19:00:29 +00003159#endif
drh08c6d442009-02-09 17:34:07 +00003160
drh9b4c59f2013-04-15 17:03:42 +00003161#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003162 /* Deal with as much of this read request as possible by transfering
3163 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003164 if( offset<pFile->mmapSize ){
3165 if( offset+amt <= pFile->mmapSize ){
3166 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3167 return SQLITE_OK;
3168 }else{
3169 int nCopy = pFile->mmapSize - offset;
3170 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3171 pBuf = &((u8 *)pBuf)[nCopy];
3172 amt -= nCopy;
3173 offset += nCopy;
3174 }
3175 }
drh6e0b6d52013-04-09 16:19:20 +00003176#endif
danf23da962013-03-23 21:00:41 +00003177
dan08da86a2009-08-21 17:18:03 +00003178 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003179 if( got==amt ){
3180 return SQLITE_OK;
3181 }else if( got<0 ){
3182 /* lastErrno set by seekAndRead */
3183 return SQLITE_IOERR_READ;
3184 }else{
drh4bf66fd2015-02-19 02:43:02 +00003185 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003186 /* Unread parts of the buffer must be zero-filled */
3187 memset(&((char*)pBuf)[got], 0, amt-got);
3188 return SQLITE_IOERR_SHORT_READ;
3189 }
3190}
3191
3192/*
dan47a2b4a2013-04-26 16:09:29 +00003193** Attempt to seek the file-descriptor passed as the first argument to
3194** absolute offset iOff, then attempt to write nBuf bytes of data from
3195** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3196** return the actual number of bytes written (which may be less than
3197** nBuf).
3198*/
3199static int seekAndWriteFd(
3200 int fd, /* File descriptor to write to */
3201 i64 iOff, /* File offset to begin writing at */
3202 const void *pBuf, /* Copy data from this buffer to the file */
3203 int nBuf, /* Size of buffer pBuf in bytes */
3204 int *piErrno /* OUT: Error number if error occurs */
3205){
3206 int rc = 0; /* Value returned by system call */
3207
3208 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003209 assert( fd>2 );
drhe1818ec2015-12-01 16:21:35 +00003210 assert( piErrno!=0 );
dan47a2b4a2013-04-26 16:09:29 +00003211 nBuf &= 0x1ffff;
3212 TIMER_START;
3213
3214#if defined(USE_PREAD)
drh2da47d32015-02-21 00:56:05 +00003215 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
dan47a2b4a2013-04-26 16:09:29 +00003216#elif defined(USE_PREAD64)
drh2da47d32015-02-21 00:56:05 +00003217 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
dan47a2b4a2013-04-26 16:09:29 +00003218#else
3219 do{
3220 i64 iSeek = lseek(fd, iOff, SEEK_SET);
drhe1818ec2015-12-01 16:21:35 +00003221 SimulateIOError( iSeek = -1 );
3222 if( iSeek<0 ){
3223 rc = -1;
3224 break;
dan47a2b4a2013-04-26 16:09:29 +00003225 }
3226 rc = osWrite(fd, pBuf, nBuf);
3227 }while( rc<0 && errno==EINTR );
3228#endif
3229
3230 TIMER_END;
3231 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3232
drhe1818ec2015-12-01 16:21:35 +00003233 if( rc<0 ) *piErrno = errno;
dan47a2b4a2013-04-26 16:09:29 +00003234 return rc;
3235}
3236
3237
3238/*
drh734c9862008-11-28 15:37:20 +00003239** Seek to the offset in id->offset then read cnt bytes into pBuf.
3240** Return the number of bytes actually read. Update the offset.
3241**
3242** To avoid stomping the errno value on a failed write the lastErrno value
3243** is set before returning.
3244*/
3245static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003246 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003247}
3248
3249
3250/*
3251** Write data from a buffer into a file. Return SQLITE_OK on success
3252** or some other error code on failure.
3253*/
3254static int unixWrite(
3255 sqlite3_file *id,
3256 const void *pBuf,
3257 int amt,
3258 sqlite3_int64 offset
3259){
dan08da86a2009-08-21 17:18:03 +00003260 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003261 int wrote = 0;
3262 assert( id );
3263 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003264
dan08da86a2009-08-21 17:18:03 +00003265 /* If this is a database file (not a journal, master-journal or temp
3266 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003267#if 0
dane946c392009-08-22 11:39:46 +00003268 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003269 || offset>=PENDING_BYTE+512
3270 || offset+amt<=PENDING_BYTE
3271 );
dan7c246102010-04-12 19:00:29 +00003272#endif
drh08c6d442009-02-09 17:34:07 +00003273
drhd3d8c042012-05-29 17:02:40 +00003274#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003275 /* If we are doing a normal write to a database file (as opposed to
3276 ** doing a hot-journal rollback or a write to some file other than a
3277 ** normal database file) then record the fact that the database
3278 ** has changed. If the transaction counter is modified, record that
3279 ** fact too.
3280 */
dan08da86a2009-08-21 17:18:03 +00003281 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003282 pFile->dbUpdate = 1; /* The database has been modified */
3283 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003284 int rc;
drh8f941bc2009-01-14 23:03:40 +00003285 char oldCntr[4];
3286 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003287 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003288 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003289 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003290 pFile->transCntrChng = 1; /* The transaction counter has changed */
3291 }
3292 }
3293 }
3294#endif
3295
danfe33e392015-11-17 20:56:06 +00003296#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003297 /* Deal with as much of this write request as possible by transfering
3298 ** data from the memory mapping using memcpy(). */
3299 if( offset<pFile->mmapSize ){
3300 if( offset+amt <= pFile->mmapSize ){
3301 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3302 return SQLITE_OK;
3303 }else{
3304 int nCopy = pFile->mmapSize - offset;
3305 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3306 pBuf = &((u8 *)pBuf)[nCopy];
3307 amt -= nCopy;
3308 offset += nCopy;
3309 }
3310 }
drh6e0b6d52013-04-09 16:19:20 +00003311#endif
drh02bf8b42015-09-01 23:51:53 +00003312
3313 while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
drh734c9862008-11-28 15:37:20 +00003314 amt -= wrote;
3315 offset += wrote;
3316 pBuf = &((char*)pBuf)[wrote];
3317 }
3318 SimulateIOError(( wrote=(-1), amt=1 ));
3319 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003320
drh02bf8b42015-09-01 23:51:53 +00003321 if( amt>wrote ){
drha21b83b2011-04-15 12:36:10 +00003322 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003323 /* lastErrno set by seekAndWrite */
3324 return SQLITE_IOERR_WRITE;
3325 }else{
drh4bf66fd2015-02-19 02:43:02 +00003326 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003327 return SQLITE_FULL;
3328 }
3329 }
dan6e09d692010-07-27 18:34:15 +00003330
drh734c9862008-11-28 15:37:20 +00003331 return SQLITE_OK;
3332}
3333
3334#ifdef SQLITE_TEST
3335/*
3336** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003337** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003338*/
3339int sqlite3_sync_count = 0;
3340int sqlite3_fullsync_count = 0;
3341#endif
3342
3343/*
drh89240432009-03-25 01:06:01 +00003344** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003345** Others do no. To be safe, we will stick with the (slightly slower)
3346** fsync(). If you know that your system does support fdatasync() correctly,
drhf7a4a1b2015-01-10 18:02:45 +00003347** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003348*/
drhf7a4a1b2015-01-10 18:02:45 +00003349#if !defined(fdatasync) && !HAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003350# define fdatasync fsync
3351#endif
3352
3353/*
3354** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3355** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3356** only available on Mac OS X. But that could change.
3357*/
3358#ifdef F_FULLFSYNC
3359# define HAVE_FULLFSYNC 1
3360#else
3361# define HAVE_FULLFSYNC 0
3362#endif
3363
3364
3365/*
3366** The fsync() system call does not work as advertised on many
3367** unix systems. The following procedure is an attempt to make
3368** it work better.
3369**
3370** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3371** for testing when we want to run through the test suite quickly.
3372** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3373** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3374** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003375**
3376** SQLite sets the dataOnly flag if the size of the file is unchanged.
3377** The idea behind dataOnly is that it should only write the file content
3378** to disk, not the inode. We only set dataOnly if the file size is
3379** unchanged since the file size is part of the inode. However,
3380** Ted Ts'o tells us that fdatasync() will also write the inode if the
3381** file size has changed. The only real difference between fdatasync()
3382** and fsync(), Ted tells us, is that fdatasync() will not flush the
3383** inode if the mtime or owner or other inode attributes have changed.
3384** We only care about the file size, not the other file attributes, so
3385** as far as SQLite is concerned, an fdatasync() is always adequate.
3386** So, we always use fdatasync() if it is available, regardless of
3387** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003388*/
3389static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003390 int rc;
drh734c9862008-11-28 15:37:20 +00003391
3392 /* The following "ifdef/elif/else/" block has the same structure as
3393 ** the one below. It is replicated here solely to avoid cluttering
3394 ** up the real code with the UNUSED_PARAMETER() macros.
3395 */
3396#ifdef SQLITE_NO_SYNC
3397 UNUSED_PARAMETER(fd);
3398 UNUSED_PARAMETER(fullSync);
3399 UNUSED_PARAMETER(dataOnly);
3400#elif HAVE_FULLFSYNC
3401 UNUSED_PARAMETER(dataOnly);
3402#else
3403 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003404 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003405#endif
3406
3407 /* Record the number of times that we do a normal fsync() and
3408 ** FULLSYNC. This is used during testing to verify that this procedure
3409 ** gets called with the correct arguments.
3410 */
3411#ifdef SQLITE_TEST
3412 if( fullSync ) sqlite3_fullsync_count++;
3413 sqlite3_sync_count++;
3414#endif
3415
3416 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
drh2c8fd122015-12-02 02:33:36 +00003417 ** no-op. But go ahead and call fstat() to validate the file
3418 ** descriptor as we need a method to provoke a failure during
3419 ** coverate testing.
drh734c9862008-11-28 15:37:20 +00003420 */
3421#ifdef SQLITE_NO_SYNC
drh2c8fd122015-12-02 02:33:36 +00003422 {
3423 struct stat buf;
3424 rc = osFstat(fd, &buf);
3425 }
drh734c9862008-11-28 15:37:20 +00003426#elif HAVE_FULLFSYNC
3427 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003428 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003429 }else{
3430 rc = 1;
3431 }
3432 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003433 ** It shouldn't be possible for fullfsync to fail on the local
3434 ** file system (on OSX), so failure indicates that FULLFSYNC
3435 ** isn't supported for this file system. So, attempt an fsync
3436 ** and (for now) ignore the overhead of a superfluous fcntl call.
3437 ** It'd be better to detect fullfsync support once and avoid
3438 ** the fcntl call every time sync is called.
3439 */
drh734c9862008-11-28 15:37:20 +00003440 if( rc ) rc = fsync(fd);
3441
drh7ed97b92010-01-20 13:07:21 +00003442#elif defined(__APPLE__)
3443 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3444 ** so currently we default to the macro that redefines fdatasync to fsync
3445 */
3446 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003447#else
drh0b647ff2009-03-21 14:41:04 +00003448 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003449#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003450 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003451 rc = fsync(fd);
3452 }
drh0b647ff2009-03-21 14:41:04 +00003453#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003454#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3455
3456 if( OS_VXWORKS && rc!= -1 ){
3457 rc = 0;
3458 }
chw97185482008-11-17 08:05:31 +00003459 return rc;
drhbfe66312006-10-03 17:40:40 +00003460}
3461
drh734c9862008-11-28 15:37:20 +00003462/*
drh0059eae2011-08-08 23:48:40 +00003463** Open a file descriptor to the directory containing file zFilename.
3464** If successful, *pFd is set to the opened file descriptor and
3465** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3466** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3467** value.
3468**
drh90315a22011-08-10 01:52:12 +00003469** The directory file descriptor is used for only one thing - to
3470** fsync() a directory to make sure file creation and deletion events
3471** are flushed to disk. Such fsyncs are not needed on newer
3472** journaling filesystems, but are required on older filesystems.
3473**
3474** This routine can be overridden using the xSetSysCall interface.
3475** The ability to override this routine was added in support of the
3476** chromium sandbox. Opening a directory is a security risk (we are
3477** told) so making it overrideable allows the chromium sandbox to
3478** replace this routine with a harmless no-op. To make this routine
3479** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3480** *pFd set to a negative number.
3481**
drh0059eae2011-08-08 23:48:40 +00003482** If SQLITE_OK is returned, the caller is responsible for closing
3483** the file descriptor *pFd using close().
3484*/
3485static int openDirectory(const char *zFilename, int *pFd){
3486 int ii;
3487 int fd = -1;
3488 char zDirname[MAX_PATHNAME+1];
3489
3490 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drhdc278512015-12-07 18:18:33 +00003491 for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
3492 if( ii>0 ){
drh0059eae2011-08-08 23:48:40 +00003493 zDirname[ii] = '\0';
drhdc278512015-12-07 18:18:33 +00003494 }else{
3495 if( zDirname[0]!='/' ) zDirname[0] = '.';
3496 zDirname[1] = 0;
3497 }
3498 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3499 if( fd>=0 ){
3500 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
drh0059eae2011-08-08 23:48:40 +00003501 }
3502 *pFd = fd;
drhacb6b282015-11-26 10:37:05 +00003503 if( fd>=0 ) return SQLITE_OK;
3504 return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
drh0059eae2011-08-08 23:48:40 +00003505}
3506
3507/*
drh734c9862008-11-28 15:37:20 +00003508** Make sure all writes to a particular file are committed to disk.
3509**
3510** If dataOnly==0 then both the file itself and its metadata (file
3511** size, access time, etc) are synced. If dataOnly!=0 then only the
3512** file data is synced.
3513**
3514** Under Unix, also make sure that the directory entry for the file
3515** has been created by fsync-ing the directory that contains the file.
3516** If we do not do this and we encounter a power failure, the directory
3517** entry for the journal might not exist after we reboot. The next
3518** SQLite to access the file will not know that the journal exists (because
3519** the directory entry for the journal was never created) and the transaction
3520** will not roll back - possibly leading to database corruption.
3521*/
3522static int unixSync(sqlite3_file *id, int flags){
3523 int rc;
3524 unixFile *pFile = (unixFile*)id;
3525
3526 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3527 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3528
3529 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3530 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3531 || (flags&0x0F)==SQLITE_SYNC_FULL
3532 );
3533
3534 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3535 ** line is to test that doing so does not cause any problems.
3536 */
3537 SimulateDiskfullError( return SQLITE_FULL );
3538
3539 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003540 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003541 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3542 SimulateIOError( rc=1 );
3543 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003544 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003545 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003546 }
drh0059eae2011-08-08 23:48:40 +00003547
3548 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003549 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003550 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003551 */
3552 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3553 int dirfd;
3554 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003555 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003556 rc = osOpenDirectory(pFile->zPath, &dirfd);
drhacb6b282015-11-26 10:37:05 +00003557 if( rc==SQLITE_OK ){
drh0059eae2011-08-08 23:48:40 +00003558 full_fsync(dirfd, 0, 0);
3559 robust_close(pFile, dirfd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00003560 }else{
3561 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00003562 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003563 }
drh0059eae2011-08-08 23:48:40 +00003564 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003565 }
3566 return rc;
3567}
3568
3569/*
3570** Truncate an open file to a specified size
3571*/
3572static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003573 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003574 int rc;
dan6e09d692010-07-27 18:34:15 +00003575 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003576 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003577
3578 /* If the user has configured a chunk-size for this file, truncate the
3579 ** file so that it consists of an integer number of chunks (i.e. the
3580 ** actual file size after the operation may be larger than the requested
3581 ** size).
3582 */
drhb8af4b72012-04-05 20:04:39 +00003583 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003584 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3585 }
3586
dan2ee53412014-09-06 16:49:40 +00003587 rc = robust_ftruncate(pFile->h, nByte);
drh734c9862008-11-28 15:37:20 +00003588 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003589 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003590 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003591 }else{
drhd3d8c042012-05-29 17:02:40 +00003592#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003593 /* If we are doing a normal write to a database file (as opposed to
3594 ** doing a hot-journal rollback or a write to some file other than a
3595 ** normal database file) and we truncate the file to zero length,
3596 ** that effectively updates the change counter. This might happen
3597 ** when restoring a database using the backup API from a zero-length
3598 ** source.
3599 */
dan6e09d692010-07-27 18:34:15 +00003600 if( pFile->inNormalWrite && nByte==0 ){
3601 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003602 }
danf23da962013-03-23 21:00:41 +00003603#endif
danc0003312013-03-22 17:46:11 +00003604
mistachkine98844f2013-08-24 00:59:24 +00003605#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003606 /* If the file was just truncated to a size smaller than the currently
3607 ** mapped region, reduce the effective mapping size as well. SQLite will
3608 ** use read() and write() to access data beyond this point from now on.
3609 */
3610 if( nByte<pFile->mmapSize ){
3611 pFile->mmapSize = nByte;
3612 }
mistachkine98844f2013-08-24 00:59:24 +00003613#endif
drh3313b142009-11-06 04:13:18 +00003614
drh734c9862008-11-28 15:37:20 +00003615 return SQLITE_OK;
3616 }
3617}
3618
3619/*
3620** Determine the current size of a file in bytes
3621*/
3622static int unixFileSize(sqlite3_file *id, i64 *pSize){
3623 int rc;
3624 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003625 assert( id );
3626 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003627 SimulateIOError( rc=1 );
3628 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00003629 storeLastErrno((unixFile*)id, errno);
drh734c9862008-11-28 15:37:20 +00003630 return SQLITE_IOERR_FSTAT;
3631 }
3632 *pSize = buf.st_size;
3633
drh8af6c222010-05-14 12:43:01 +00003634 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003635 ** writes a single byte into that file in order to work around a bug
3636 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3637 ** layers, we need to report this file size as zero even though it is
3638 ** really 1. Ticket #3260.
3639 */
3640 if( *pSize==1 ) *pSize = 0;
3641
3642
3643 return SQLITE_OK;
3644}
3645
drhd2cb50b2009-01-09 21:41:17 +00003646#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003647/*
3648** Handler for proxy-locking file-control verbs. Defined below in the
3649** proxying locking division.
3650*/
3651static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003652#endif
drh715ff302008-12-03 22:32:44 +00003653
dan502019c2010-07-28 14:26:17 +00003654/*
3655** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003656** file-control operation. Enlarge the database to nBytes in size
3657** (rounded up to the next chunk-size). If the database is already
3658** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003659*/
3660static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003661 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003662 i64 nSize; /* Required file size */
3663 struct stat buf; /* Used to hold return values of fstat() */
3664
drh4bf66fd2015-02-19 02:43:02 +00003665 if( osFstat(pFile->h, &buf) ){
3666 return SQLITE_IOERR_FSTAT;
3667 }
dan502019c2010-07-28 14:26:17 +00003668
3669 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3670 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003671
dan502019c2010-07-28 14:26:17 +00003672#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003673 /* The code below is handling the return value of osFallocate()
3674 ** correctly. posix_fallocate() is defined to "returns zero on success,
3675 ** or an error number on failure". See the manpage for details. */
3676 int err;
drhff812312011-02-23 13:33:46 +00003677 do{
dan661d71a2011-03-30 19:08:03 +00003678 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3679 }while( err==EINTR );
3680 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003681#else
dan592bf7f2014-12-30 19:58:31 +00003682 /* If the OS does not have posix_fallocate(), fake it. Write a
3683 ** single byte to the last byte in each block that falls entirely
3684 ** within the extended region. Then, if required, a single byte
3685 ** at offset (nSize-1), to set the size of the file correctly.
3686 ** This is a similar technique to that used by glibc on systems
3687 ** that do not have a real fallocate() call.
dan502019c2010-07-28 14:26:17 +00003688 */
3689 int nBlk = buf.st_blksize; /* File-system block size */
danef3d66c2015-01-06 21:31:47 +00003690 int nWrite = 0; /* Number of bytes written by seekAndWrite */
dan502019c2010-07-28 14:26:17 +00003691 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003692
drh053378d2015-12-01 22:09:42 +00003693 iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
dan592bf7f2014-12-30 19:58:31 +00003694 assert( iWrite>=buf.st_size );
dan592bf7f2014-12-30 19:58:31 +00003695 assert( ((iWrite+1)%nBlk)==0 );
drh053378d2015-12-01 22:09:42 +00003696 for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
3697 if( iWrite>=nSize ) iWrite = nSize - 1;
danef3d66c2015-01-06 21:31:47 +00003698 nWrite = seekAndWrite(pFile, iWrite, "", 1);
dandc5df0f2011-04-06 19:15:45 +00003699 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dandc5df0f2011-04-06 19:15:45 +00003700 }
dan502019c2010-07-28 14:26:17 +00003701#endif
3702 }
3703 }
3704
mistachkine98844f2013-08-24 00:59:24 +00003705#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003706 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003707 int rc;
3708 if( pFile->szChunk<=0 ){
3709 if( robust_ftruncate(pFile->h, nByte) ){
drh4bf66fd2015-02-19 02:43:02 +00003710 storeLastErrno(pFile, errno);
danf23da962013-03-23 21:00:41 +00003711 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3712 }
3713 }
3714
3715 rc = unixMapfile(pFile, nByte);
3716 return rc;
3717 }
mistachkine98844f2013-08-24 00:59:24 +00003718#endif
danf23da962013-03-23 21:00:41 +00003719
dan502019c2010-07-28 14:26:17 +00003720 return SQLITE_OK;
3721}
danielk1977ad94b582007-08-20 06:44:22 +00003722
danielk1977e3026632004-06-22 11:29:02 +00003723/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003724** If *pArg is initially negative then this is a query. Set *pArg to
drhf12b3f62011-12-21 14:42:29 +00003725** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3726**
3727** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3728*/
3729static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3730 if( *pArg<0 ){
3731 *pArg = (pFile->ctrlFlags & mask)!=0;
3732 }else if( (*pArg)==0 ){
3733 pFile->ctrlFlags &= ~mask;
3734 }else{
3735 pFile->ctrlFlags |= mask;
3736 }
3737}
3738
drh696b33e2012-12-06 19:01:42 +00003739/* Forward declaration */
3740static int unixGetTempname(int nBuf, char *zBuf);
3741
drhf12b3f62011-12-21 14:42:29 +00003742/*
drh9e33c2c2007-08-31 18:34:59 +00003743** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003744*/
drhcc6bb3e2007-08-31 16:11:35 +00003745static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003746 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003747 switch( op ){
3748 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003749 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003750 return SQLITE_OK;
3751 }
drh4bf66fd2015-02-19 02:43:02 +00003752 case SQLITE_FCNTL_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003753 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003754 return SQLITE_OK;
3755 }
dan6e09d692010-07-27 18:34:15 +00003756 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003757 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003758 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003759 }
drh9ff27ec2010-05-19 19:26:05 +00003760 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003761 int rc;
3762 SimulateIOErrorBenign(1);
3763 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3764 SimulateIOErrorBenign(0);
3765 return rc;
drhf0b190d2011-07-26 16:03:07 +00003766 }
3767 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003768 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3769 return SQLITE_OK;
3770 }
drhcb15f352011-12-23 01:04:17 +00003771 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3772 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003773 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003774 }
drhde60fc22011-12-14 17:53:36 +00003775 case SQLITE_FCNTL_VFSNAME: {
3776 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3777 return SQLITE_OK;
3778 }
drh696b33e2012-12-06 19:01:42 +00003779 case SQLITE_FCNTL_TEMPFILENAME: {
drhf3cdcdc2015-04-29 16:50:28 +00003780 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
drh696b33e2012-12-06 19:01:42 +00003781 if( zTFile ){
3782 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3783 *(char**)pArg = zTFile;
3784 }
3785 return SQLITE_OK;
3786 }
drhb959a012013-12-07 12:29:22 +00003787 case SQLITE_FCNTL_HAS_MOVED: {
3788 *(int*)pArg = fileHasMoved(pFile);
3789 return SQLITE_OK;
3790 }
mistachkine98844f2013-08-24 00:59:24 +00003791#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003792 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003793 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003794 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003795 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3796 newLimit = sqlite3GlobalConfig.mxMmap;
3797 }
3798 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003799 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003800 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003801 if( pFile->mmapSize>0 ){
3802 unixUnmapfile(pFile);
3803 rc = unixMapfile(pFile, -1);
3804 }
danbcb8a862013-04-08 15:30:41 +00003805 }
drh34e258c2013-05-23 01:40:53 +00003806 return rc;
danb2d3de32013-03-14 18:34:37 +00003807 }
mistachkine98844f2013-08-24 00:59:24 +00003808#endif
drhd3d8c042012-05-29 17:02:40 +00003809#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003810 /* The pager calls this method to signal that it has done
3811 ** a rollback and that the database is therefore unchanged and
3812 ** it hence it is OK for the transaction change counter to be
3813 ** unchanged.
3814 */
3815 case SQLITE_FCNTL_DB_UNCHANGED: {
3816 ((unixFile*)id)->dbUpdate = 0;
3817 return SQLITE_OK;
3818 }
3819#endif
drhd2cb50b2009-01-09 21:41:17 +00003820#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh4bf66fd2015-02-19 02:43:02 +00003821 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
3822 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003823 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003824 }
drhd2cb50b2009-01-09 21:41:17 +00003825#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003826 }
drh0b52b7d2011-01-26 19:46:22 +00003827 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003828}
3829
3830/*
danielk1977a3d4c882007-03-23 10:08:38 +00003831** Return the sector size in bytes of the underlying block device for
3832** the specified file. This is almost always 512 bytes, but may be
3833** larger for some devices.
3834**
3835** SQLite code assumes this function cannot fail. It also assumes that
3836** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003837** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003838** same for both.
3839*/
drh537dddf2012-10-26 13:46:24 +00003840#ifndef __QNXNTO__
3841static int unixSectorSize(sqlite3_file *NotUsed){
3842 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003843 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003844}
drh537dddf2012-10-26 13:46:24 +00003845#endif
3846
3847/*
3848** The following version of unixSectorSize() is optimized for QNX.
3849*/
3850#ifdef __QNXNTO__
3851#include <sys/dcmd_blk.h>
3852#include <sys/statvfs.h>
3853static int unixSectorSize(sqlite3_file *id){
3854 unixFile *pFile = (unixFile*)id;
3855 if( pFile->sectorSize == 0 ){
3856 struct statvfs fsInfo;
3857
3858 /* Set defaults for non-supported filesystems */
3859 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3860 pFile->deviceCharacteristics = 0;
3861 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3862 return pFile->sectorSize;
3863 }
3864
3865 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3866 pFile->sectorSize = fsInfo.f_bsize;
3867 pFile->deviceCharacteristics =
3868 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3869 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3870 ** the write succeeds */
3871 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3872 ** so it is ordered */
3873 0;
3874 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3875 pFile->sectorSize = fsInfo.f_bsize;
3876 pFile->deviceCharacteristics =
3877 /* etfs cluster size writes are atomic */
3878 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3879 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3880 ** the write succeeds */
3881 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3882 ** so it is ordered */
3883 0;
3884 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3885 pFile->sectorSize = fsInfo.f_bsize;
3886 pFile->deviceCharacteristics =
3887 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3888 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3889 ** the write succeeds */
3890 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3891 ** so it is ordered */
3892 0;
3893 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3894 pFile->sectorSize = fsInfo.f_bsize;
3895 pFile->deviceCharacteristics =
3896 /* full bitset of atomics from max sector size and smaller */
3897 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3898 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3899 ** so it is ordered */
3900 0;
3901 }else if( strstr(fsInfo.f_basetype, "dos") ){
3902 pFile->sectorSize = fsInfo.f_bsize;
3903 pFile->deviceCharacteristics =
3904 /* full bitset of atomics from max sector size and smaller */
3905 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3906 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3907 ** so it is ordered */
3908 0;
3909 }else{
3910 pFile->deviceCharacteristics =
3911 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3912 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3913 ** the write succeeds */
3914 0;
3915 }
3916 }
3917 /* Last chance verification. If the sector size isn't a multiple of 512
3918 ** then it isn't valid.*/
3919 if( pFile->sectorSize % 512 != 0 ){
3920 pFile->deviceCharacteristics = 0;
3921 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3922 }
3923 return pFile->sectorSize;
3924}
3925#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003926
danielk197790949c22007-08-17 16:50:38 +00003927/*
drhf12b3f62011-12-21 14:42:29 +00003928** Return the device characteristics for the file.
3929**
drhcb15f352011-12-23 01:04:17 +00003930** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
peter.d.reid60ec9142014-09-06 16:39:46 +00003931** However, that choice is controversial since technically the underlying
drhcb15f352011-12-23 01:04:17 +00003932** file system does not always provide powersafe overwrites. (In other
3933** words, after a power-loss event, parts of the file that were never
3934** written might end up being altered.) However, non-PSOW behavior is very,
3935** very rare. And asserting PSOW makes a large reduction in the amount
3936** of required I/O for journaling, since a lot of padding is eliminated.
3937** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3938** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003939*/
drhf12b3f62011-12-21 14:42:29 +00003940static int unixDeviceCharacteristics(sqlite3_file *id){
3941 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003942 int rc = 0;
3943#ifdef __QNXNTO__
3944 if( p->sectorSize==0 ) unixSectorSize(id);
3945 rc = p->deviceCharacteristics;
3946#endif
drhcb15f352011-12-23 01:04:17 +00003947 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003948 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003949 }
drh537dddf2012-10-26 13:46:24 +00003950 return rc;
danielk197762079062007-08-15 17:08:46 +00003951}
3952
dan702eec12014-06-23 10:04:58 +00003953#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00003954
dan702eec12014-06-23 10:04:58 +00003955/*
3956** Return the system page size.
3957**
3958** This function should not be called directly by other code in this file.
3959** Instead, it should be called via macro osGetpagesize().
3960*/
3961static int unixGetpagesize(void){
drh8cd5b252015-03-02 22:06:43 +00003962#if OS_VXWORKS
3963 return 1024;
3964#elif defined(_BSD_SOURCE)
dan702eec12014-06-23 10:04:58 +00003965 return getpagesize();
3966#else
3967 return (int)sysconf(_SC_PAGESIZE);
3968#endif
3969}
3970
3971#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
3972
3973#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00003974
3975/*
drhd91c68f2010-05-14 14:52:25 +00003976** Object used to represent an shared memory buffer.
3977**
3978** When multiple threads all reference the same wal-index, each thread
3979** has its own unixShm object, but they all point to a single instance
3980** of this unixShmNode object. In other words, each wal-index is opened
3981** only once per process.
3982**
3983** Each unixShmNode object is connected to a single unixInodeInfo object.
3984** We could coalesce this object into unixInodeInfo, but that would mean
3985** every open file that does not use shared memory (in other words, most
3986** open files) would have to carry around this extra information. So
3987** the unixInodeInfo object contains a pointer to this unixShmNode object
3988** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003989**
3990** unixMutexHeld() must be true when creating or destroying
3991** this object or while reading or writing the following fields:
3992**
3993** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003994**
3995** The following fields are read-only after the object is created:
3996**
3997** fid
3998** zFilename
3999**
drhd91c68f2010-05-14 14:52:25 +00004000** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00004001** unixMutexHeld() is true when reading or writing any other field
4002** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00004003*/
drhd91c68f2010-05-14 14:52:25 +00004004struct unixShmNode {
4005 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00004006 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00004007 char *zFilename; /* Name of the mmapped file */
4008 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00004009 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00004010 u16 nRegion; /* Size of array apRegion */
4011 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00004012 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00004013 int nRef; /* Number of unixShm objects pointing to this */
4014 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00004015#ifdef SQLITE_DEBUG
4016 u8 exclMask; /* Mask of exclusive locks held */
4017 u8 sharedMask; /* Mask of shared locks held */
4018 u8 nextShmId; /* Next available unixShm.id value */
4019#endif
4020};
4021
4022/*
drhd9e5c4f2010-05-12 18:01:39 +00004023** Structure used internally by this VFS to record the state of an
4024** open shared memory connection.
4025**
drhd91c68f2010-05-14 14:52:25 +00004026** The following fields are initialized when this object is created and
4027** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004028**
drhd91c68f2010-05-14 14:52:25 +00004029** unixShm.pFile
4030** unixShm.id
4031**
4032** All other fields are read/write. The unixShm.pFile->mutex must be held
4033** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004034*/
4035struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004036 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4037 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004038 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004039 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004040 u16 sharedMask; /* Mask of shared locks held */
4041 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004042};
4043
4044/*
drhd9e5c4f2010-05-12 18:01:39 +00004045** Constants used for locking
4046*/
drhbd9676c2010-06-23 17:58:38 +00004047#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004048#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004049
drhd9e5c4f2010-05-12 18:01:39 +00004050/*
drh73b64e42010-05-30 19:55:15 +00004051** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004052**
4053** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4054** otherwise.
4055*/
4056static int unixShmSystemLock(
drhbbf76ee2015-03-10 20:22:35 +00004057 unixFile *pFile, /* Open connection to the WAL file */
drhd91c68f2010-05-14 14:52:25 +00004058 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004059 int ofst, /* First byte of the locking range */
4060 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004061){
drhbbf76ee2015-03-10 20:22:35 +00004062 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4063 struct flock f; /* The posix advisory locking structure */
4064 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004065
drhd91c68f2010-05-14 14:52:25 +00004066 /* Access to the unixShmNode object is serialized by the caller */
drhbbf76ee2015-03-10 20:22:35 +00004067 pShmNode = pFile->pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004068 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004069
drh73b64e42010-05-30 19:55:15 +00004070 /* Shared locks never span more than one byte */
4071 assert( n==1 || lockType!=F_RDLCK );
4072
4073 /* Locks are within range */
drhaf19f172015-12-02 17:40:13 +00004074 assert( n>=1 && n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004075
drh3cb93392011-03-12 18:10:44 +00004076 if( pShmNode->h>=0 ){
4077 /* Initialize the locking parameters */
4078 memset(&f, 0, sizeof(f));
4079 f.l_type = lockType;
4080 f.l_whence = SEEK_SET;
4081 f.l_start = ofst;
4082 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004083
drhdcfb9652015-12-02 00:05:26 +00004084 rc = osFcntl(pShmNode->h, F_SETLK, &f);
drh3cb93392011-03-12 18:10:44 +00004085 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4086 }
drhd9e5c4f2010-05-12 18:01:39 +00004087
4088 /* Update the global lock state and do debug tracing */
4089#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004090 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004091 OSTRACE(("SHM-LOCK "));
drh693e6712014-01-24 22:58:00 +00004092 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004093 if( rc==SQLITE_OK ){
4094 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004095 OSTRACE(("unlock %d ok", ofst));
4096 pShmNode->exclMask &= ~mask;
4097 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004098 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004099 OSTRACE(("read-lock %d ok", ofst));
4100 pShmNode->exclMask &= ~mask;
4101 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004102 }else{
4103 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004104 OSTRACE(("write-lock %d ok", ofst));
4105 pShmNode->exclMask |= mask;
4106 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004107 }
4108 }else{
4109 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004110 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004111 }else if( lockType==F_RDLCK ){
4112 OSTRACE(("read-lock failed"));
4113 }else{
4114 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004115 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004116 }
4117 }
drh20e1f082010-05-31 16:10:12 +00004118 OSTRACE((" - afterwards %03x,%03x\n",
4119 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004120 }
drhd9e5c4f2010-05-12 18:01:39 +00004121#endif
4122
4123 return rc;
4124}
4125
dan781e34c2014-03-20 08:59:47 +00004126/*
dan781e34c2014-03-20 08:59:47 +00004127** Return the minimum number of 32KB shm regions that should be mapped at
4128** a time, assuming that each mapping must be an integer multiple of the
4129** current system page-size.
4130**
4131** Usually, this is 1. The exception seems to be systems that are configured
4132** to use 64KB pages - in this case each mapping must cover at least two
4133** shm regions.
4134*/
4135static int unixShmRegionPerMap(void){
4136 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004137 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004138 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4139 if( pgsz<shmsz ) return 1;
4140 return pgsz/shmsz;
4141}
drhd9e5c4f2010-05-12 18:01:39 +00004142
4143/*
drhd91c68f2010-05-14 14:52:25 +00004144** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004145**
4146** This is not a VFS shared-memory method; it is a utility function called
4147** by VFS shared-memory methods.
4148*/
drhd91c68f2010-05-14 14:52:25 +00004149static void unixShmPurge(unixFile *pFd){
4150 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004151 assert( unixMutexHeld() );
drhf3b1ed02015-12-02 13:11:03 +00004152 if( p && ALWAYS(p->nRef==0) ){
dan781e34c2014-03-20 08:59:47 +00004153 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004154 int i;
drhd91c68f2010-05-14 14:52:25 +00004155 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004156 sqlite3_mutex_free(p->mutex);
dan781e34c2014-03-20 08:59:47 +00004157 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh3cb93392011-03-12 18:10:44 +00004158 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004159 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004160 }else{
4161 sqlite3_free(p->apRegion[i]);
4162 }
dan13a3cb82010-06-11 19:04:21 +00004163 }
dan18801912010-06-14 14:07:50 +00004164 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004165 if( p->h>=0 ){
4166 robust_close(pFd, p->h, __LINE__);
4167 p->h = -1;
4168 }
drhd91c68f2010-05-14 14:52:25 +00004169 p->pInode->pShmNode = 0;
4170 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004171 }
4172}
4173
4174/*
danda9fe0c2010-07-13 18:44:03 +00004175** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004176** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004177**
drh7234c6d2010-06-19 15:10:09 +00004178** The file used to implement shared-memory is in the same directory
4179** as the open database file and has the same name as the open database
4180** file with the "-shm" suffix added. For example, if the database file
4181** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004182** for shared memory will be called "/home/user1/config.db-shm".
4183**
4184** Another approach to is to use files in /dev/shm or /dev/tmp or an
4185** some other tmpfs mount. But if a file in a different directory
4186** from the database file is used, then differing access permissions
4187** or a chroot() might cause two different processes on the same
4188** database to end up using different files for shared memory -
4189** meaning that their memory would not really be shared - resulting
4190** in database corruption. Nevertheless, this tmpfs file usage
4191** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4192** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4193** option results in an incompatible build of SQLite; builds of SQLite
4194** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4195** same database file at the same time, database corruption will likely
4196** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4197** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004198**
4199** When opening a new shared-memory file, if no other instances of that
4200** file are currently open, in this process or in other processes, then
4201** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004202**
4203** If the original database file (pDbFd) is using the "unix-excl" VFS
4204** that means that an exclusive lock is held on the database file and
4205** that no other processes are able to read or write the database. In
4206** that case, we do not really need shared memory. No shared memory
4207** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004208*/
danda9fe0c2010-07-13 18:44:03 +00004209static int unixOpenSharedMemory(unixFile *pDbFd){
4210 struct unixShm *p = 0; /* The connection to be opened */
4211 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4212 int rc; /* Result code */
4213 unixInodeInfo *pInode; /* The inode of fd */
4214 char *zShmFilename; /* Name of the file used for SHM */
4215 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004216
danda9fe0c2010-07-13 18:44:03 +00004217 /* Allocate space for the new unixShm object. */
drhf3cdcdc2015-04-29 16:50:28 +00004218 p = sqlite3_malloc64( sizeof(*p) );
drhd9e5c4f2010-05-12 18:01:39 +00004219 if( p==0 ) return SQLITE_NOMEM;
4220 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004221 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004222
danda9fe0c2010-07-13 18:44:03 +00004223 /* Check to see if a unixShmNode object already exists. Reuse an existing
4224 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004225 */
4226 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004227 pInode = pDbFd->pInode;
4228 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004229 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004230 struct stat sStat; /* fstat() info for database file */
drh4bf66fd2015-02-19 02:43:02 +00004231#ifndef SQLITE_SHM_DIRECTORY
4232 const char *zBasePath = pDbFd->zPath;
4233#endif
danddb0ac42010-07-14 14:48:58 +00004234
4235 /* Call fstat() to figure out the permissions on the database file. If
4236 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004237 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004238 */
drhf3b1ed02015-12-02 13:11:03 +00004239 if( osFstat(pDbFd->h, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004240 rc = SQLITE_IOERR_FSTAT;
4241 goto shm_open_err;
4242 }
4243
drha4ced192010-07-15 18:32:40 +00004244#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004245 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004246#else
drh4bf66fd2015-02-19 02:43:02 +00004247 nShmFilename = 6 + (int)strlen(zBasePath);
drha4ced192010-07-15 18:32:40 +00004248#endif
drhf3cdcdc2015-04-29 16:50:28 +00004249 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004250 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004251 rc = SQLITE_NOMEM;
4252 goto shm_open_err;
4253 }
drh9cb5a0d2012-01-05 21:19:54 +00004254 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004255 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004256#ifdef SQLITE_SHM_DIRECTORY
4257 sqlite3_snprintf(nShmFilename, zShmFilename,
4258 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4259 (u32)sStat.st_ino, (u32)sStat.st_dev);
4260#else
drh4bf66fd2015-02-19 02:43:02 +00004261 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
drh81cc5162011-05-17 20:36:21 +00004262 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004263#endif
drhd91c68f2010-05-14 14:52:25 +00004264 pShmNode->h = -1;
4265 pDbFd->pInode->pShmNode = pShmNode;
4266 pShmNode->pInode = pDbFd->pInode;
4267 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4268 if( pShmNode->mutex==0 ){
4269 rc = SQLITE_NOMEM;
4270 goto shm_open_err;
4271 }
drhd9e5c4f2010-05-12 18:01:39 +00004272
drh3cb93392011-03-12 18:10:44 +00004273 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004274 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004275 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004276 openFlags = O_RDONLY;
4277 pShmNode->isReadonly = 1;
4278 }
4279 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004280 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004281 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4282 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004283 }
drhac7c3ac2012-02-11 19:23:48 +00004284
4285 /* If this process is running as root, make sure that the SHM file
4286 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004287 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004288 */
drh6226ca22015-11-24 15:06:28 +00004289 robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004290
4291 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004292 ** If not, truncate the file to zero length.
4293 */
4294 rc = SQLITE_OK;
drhbbf76ee2015-03-10 20:22:35 +00004295 if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
drh66dfec8b2011-06-01 20:01:49 +00004296 if( robust_ftruncate(pShmNode->h, 0) ){
4297 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004298 }
4299 }
drh66dfec8b2011-06-01 20:01:49 +00004300 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004301 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
drh66dfec8b2011-06-01 20:01:49 +00004302 }
4303 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004304 }
drhd9e5c4f2010-05-12 18:01:39 +00004305 }
4306
drhd91c68f2010-05-14 14:52:25 +00004307 /* Make the new connection a child of the unixShmNode */
4308 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004309#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004310 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004311#endif
drhd91c68f2010-05-14 14:52:25 +00004312 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004313 pDbFd->pShm = p;
4314 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004315
4316 /* The reference count on pShmNode has already been incremented under
4317 ** the cover of the unixEnterMutex() mutex and the pointer from the
4318 ** new (struct unixShm) object to the pShmNode has been set. All that is
4319 ** left to do is to link the new object into the linked list starting
4320 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4321 ** mutex.
4322 */
4323 sqlite3_mutex_enter(pShmNode->mutex);
4324 p->pNext = pShmNode->pFirst;
4325 pShmNode->pFirst = p;
4326 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004327 return SQLITE_OK;
4328
4329 /* Jump here on any error */
4330shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004331 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004332 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004333 unixLeaveMutex();
4334 return rc;
4335}
4336
4337/*
danda9fe0c2010-07-13 18:44:03 +00004338** This function is called to obtain a pointer to region iRegion of the
4339** shared-memory associated with the database file fd. Shared-memory regions
4340** are numbered starting from zero. Each shared-memory region is szRegion
4341** bytes in size.
4342**
4343** If an error occurs, an error code is returned and *pp is set to NULL.
4344**
4345** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4346** region has not been allocated (by any client, including one running in a
4347** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4348** bExtend is non-zero and the requested shared-memory region has not yet
4349** been allocated, it is allocated by this function.
4350**
4351** If the shared-memory region has already been allocated or is allocated by
4352** this call as described above, then it is mapped into this processes
4353** address space (if it is not already), *pp is set to point to the mapped
4354** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004355*/
danda9fe0c2010-07-13 18:44:03 +00004356static int unixShmMap(
4357 sqlite3_file *fd, /* Handle open on database file */
4358 int iRegion, /* Region to retrieve */
4359 int szRegion, /* Size of regions */
4360 int bExtend, /* True to extend file if necessary */
4361 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004362){
danda9fe0c2010-07-13 18:44:03 +00004363 unixFile *pDbFd = (unixFile*)fd;
4364 unixShm *p;
4365 unixShmNode *pShmNode;
4366 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004367 int nShmPerMap = unixShmRegionPerMap();
4368 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004369
danda9fe0c2010-07-13 18:44:03 +00004370 /* If the shared-memory file has not yet been opened, open it now. */
4371 if( pDbFd->pShm==0 ){
4372 rc = unixOpenSharedMemory(pDbFd);
4373 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004374 }
drhd9e5c4f2010-05-12 18:01:39 +00004375
danda9fe0c2010-07-13 18:44:03 +00004376 p = pDbFd->pShm;
4377 pShmNode = p->pShmNode;
4378 sqlite3_mutex_enter(pShmNode->mutex);
4379 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004380 assert( pShmNode->pInode==pDbFd->pInode );
4381 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4382 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004383
dan781e34c2014-03-20 08:59:47 +00004384 /* Minimum number of regions required to be mapped. */
4385 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4386
4387 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004388 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004389 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004390 struct stat sStat; /* Used by fstat() */
4391
4392 pShmNode->szRegion = szRegion;
4393
drh3cb93392011-03-12 18:10:44 +00004394 if( pShmNode->h>=0 ){
4395 /* The requested region is not mapped into this processes address space.
4396 ** Check to see if it has been allocated (i.e. if the wal-index file is
4397 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004398 */
drh3cb93392011-03-12 18:10:44 +00004399 if( osFstat(pShmNode->h, &sStat) ){
4400 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004401 goto shmpage_out;
4402 }
drh3cb93392011-03-12 18:10:44 +00004403
4404 if( sStat.st_size<nByte ){
4405 /* The requested memory region does not exist. If bExtend is set to
4406 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004407 */
dan47a2b4a2013-04-26 16:09:29 +00004408 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004409 goto shmpage_out;
4410 }
dan47a2b4a2013-04-26 16:09:29 +00004411
4412 /* Alternatively, if bExtend is true, extend the file. Do this by
4413 ** writing a single byte to the end of each (OS) page being
4414 ** allocated or extended. Technically, we need only write to the
4415 ** last page in order to extend the file. But writing to all new
4416 ** pages forces the OS to allocate them immediately, which reduces
4417 ** the chances of SIGBUS while accessing the mapped region later on.
4418 */
4419 else{
4420 static const int pgsz = 4096;
4421 int iPg;
4422
4423 /* Write to the last byte of each newly allocated or extended page */
4424 assert( (nByte % pgsz)==0 );
4425 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
drhe1818ec2015-12-01 16:21:35 +00004426 int x = 0;
4427 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
dan47a2b4a2013-04-26 16:09:29 +00004428 const char *zFile = pShmNode->zFilename;
4429 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4430 goto shmpage_out;
4431 }
4432 }
drh3cb93392011-03-12 18:10:44 +00004433 }
4434 }
danda9fe0c2010-07-13 18:44:03 +00004435 }
4436
4437 /* Map the requested memory region into this processes address space. */
4438 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004439 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004440 );
4441 if( !apNew ){
4442 rc = SQLITE_IOERR_NOMEM;
4443 goto shmpage_out;
4444 }
4445 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004446 while( pShmNode->nRegion<nReqRegion ){
4447 int nMap = szRegion*nShmPerMap;
4448 int i;
drh3cb93392011-03-12 18:10:44 +00004449 void *pMem;
4450 if( pShmNode->h>=0 ){
dan781e34c2014-03-20 08:59:47 +00004451 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004452 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004453 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004454 );
4455 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004456 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004457 goto shmpage_out;
4458 }
4459 }else{
drhf3cdcdc2015-04-29 16:50:28 +00004460 pMem = sqlite3_malloc64(szRegion);
drh3cb93392011-03-12 18:10:44 +00004461 if( pMem==0 ){
4462 rc = SQLITE_NOMEM;
4463 goto shmpage_out;
4464 }
4465 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004466 }
dan781e34c2014-03-20 08:59:47 +00004467
4468 for(i=0; i<nShmPerMap; i++){
4469 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4470 }
4471 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004472 }
4473 }
4474
4475shmpage_out:
4476 if( pShmNode->nRegion>iRegion ){
4477 *pp = pShmNode->apRegion[iRegion];
4478 }else{
4479 *pp = 0;
4480 }
drh66dfec8b2011-06-01 20:01:49 +00004481 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004482 sqlite3_mutex_leave(pShmNode->mutex);
4483 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004484}
4485
4486/*
drhd9e5c4f2010-05-12 18:01:39 +00004487** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004488**
4489** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4490** different here than in posix. In xShmLock(), one can go from unlocked
4491** to shared and back or from unlocked to exclusive and back. But one may
4492** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004493*/
4494static int unixShmLock(
4495 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004496 int ofst, /* First lock to acquire or release */
4497 int n, /* Number of locks to acquire or release */
4498 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004499){
drh73b64e42010-05-30 19:55:15 +00004500 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4501 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4502 unixShm *pX; /* For looping over all siblings */
4503 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4504 int rc = SQLITE_OK; /* Result code */
4505 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004506
drhd91c68f2010-05-14 14:52:25 +00004507 assert( pShmNode==pDbFd->pInode->pShmNode );
4508 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004509 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004510 assert( n>=1 );
4511 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4512 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4513 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4514 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4515 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004516 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4517 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004518
drhc99597c2010-05-31 01:41:15 +00004519 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004520 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004521 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004522 if( flags & SQLITE_SHM_UNLOCK ){
4523 u16 allMask = 0; /* Mask of locks held by siblings */
4524
4525 /* See if any siblings hold this same lock */
4526 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4527 if( pX==p ) continue;
4528 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4529 allMask |= pX->sharedMask;
4530 }
4531
4532 /* Unlock the system-level locks */
4533 if( (mask & allMask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004534 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004535 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004536 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004537 }
drh73b64e42010-05-30 19:55:15 +00004538
4539 /* Undo the local locks */
4540 if( rc==SQLITE_OK ){
4541 p->exclMask &= ~mask;
4542 p->sharedMask &= ~mask;
4543 }
4544 }else if( flags & SQLITE_SHM_SHARED ){
4545 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4546
4547 /* Find out which shared locks are already held by sibling connections.
4548 ** If any sibling already holds an exclusive lock, go ahead and return
4549 ** SQLITE_BUSY.
4550 */
4551 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004552 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004553 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004554 break;
4555 }
4556 allShared |= pX->sharedMask;
4557 }
4558
4559 /* Get shared locks at the system level, if necessary */
4560 if( rc==SQLITE_OK ){
4561 if( (allShared & mask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004562 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004563 }else{
drh73b64e42010-05-30 19:55:15 +00004564 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004565 }
drhd9e5c4f2010-05-12 18:01:39 +00004566 }
drh73b64e42010-05-30 19:55:15 +00004567
4568 /* Get the local shared locks */
4569 if( rc==SQLITE_OK ){
4570 p->sharedMask |= mask;
4571 }
4572 }else{
4573 /* Make sure no sibling connections hold locks that will block this
4574 ** lock. If any do, return SQLITE_BUSY right away.
4575 */
4576 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004577 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4578 rc = SQLITE_BUSY;
4579 break;
4580 }
4581 }
4582
4583 /* Get the exclusive locks at the system level. Then if successful
4584 ** also mark the local connection as being locked.
4585 */
4586 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004587 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004588 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004589 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004590 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004591 }
drhd9e5c4f2010-05-12 18:01:39 +00004592 }
4593 }
drhd91c68f2010-05-14 14:52:25 +00004594 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004595 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
drh5ac93652015-03-21 20:59:43 +00004596 p->id, osGetpid(0), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004597 return rc;
4598}
4599
drh286a2882010-05-20 23:51:06 +00004600/*
4601** Implement a memory barrier or memory fence on shared memory.
4602**
4603** All loads and stores begun before the barrier must complete before
4604** any load or store begun after the barrier.
4605*/
4606static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004607 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004608){
drhff828942010-06-26 21:34:06 +00004609 UNUSED_PARAMETER(fd);
drh22c733d2015-09-24 12:40:43 +00004610 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
4611 unixEnterMutex(); /* Also mutex, for redundancy */
drhb29ad852010-06-01 00:03:57 +00004612 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004613}
4614
dan18801912010-06-14 14:07:50 +00004615/*
danda9fe0c2010-07-13 18:44:03 +00004616** Close a connection to shared-memory. Delete the underlying
4617** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004618**
4619** If there is no shared memory associated with the connection then this
4620** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004621*/
danda9fe0c2010-07-13 18:44:03 +00004622static int unixShmUnmap(
4623 sqlite3_file *fd, /* The underlying database file */
4624 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004625){
danda9fe0c2010-07-13 18:44:03 +00004626 unixShm *p; /* The connection to be closed */
4627 unixShmNode *pShmNode; /* The underlying shared-memory file */
4628 unixShm **pp; /* For looping over sibling connections */
4629 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004630
danda9fe0c2010-07-13 18:44:03 +00004631 pDbFd = (unixFile*)fd;
4632 p = pDbFd->pShm;
4633 if( p==0 ) return SQLITE_OK;
4634 pShmNode = p->pShmNode;
4635
4636 assert( pShmNode==pDbFd->pInode->pShmNode );
4637 assert( pShmNode->pInode==pDbFd->pInode );
4638
4639 /* Remove connection p from the set of connections associated
4640 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004641 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004642 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4643 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004644
danda9fe0c2010-07-13 18:44:03 +00004645 /* Free the connection p */
4646 sqlite3_free(p);
4647 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004648 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004649
4650 /* If pShmNode->nRef has reached 0, then close the underlying
4651 ** shared-memory file, too */
4652 unixEnterMutex();
4653 assert( pShmNode->nRef>0 );
4654 pShmNode->nRef--;
4655 if( pShmNode->nRef==0 ){
drh4bf66fd2015-02-19 02:43:02 +00004656 if( deleteFlag && pShmNode->h>=0 ){
4657 osUnlink(pShmNode->zFilename);
4658 }
danda9fe0c2010-07-13 18:44:03 +00004659 unixShmPurge(pDbFd);
4660 }
4661 unixLeaveMutex();
4662
4663 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004664}
drh286a2882010-05-20 23:51:06 +00004665
danda9fe0c2010-07-13 18:44:03 +00004666
drhd9e5c4f2010-05-12 18:01:39 +00004667#else
drh6b017cc2010-06-14 18:01:46 +00004668# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004669# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004670# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004671# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004672#endif /* #ifndef SQLITE_OMIT_WAL */
4673
mistachkine98844f2013-08-24 00:59:24 +00004674#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004675/*
danaef49d72013-03-25 16:28:54 +00004676** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004677*/
danf23da962013-03-23 21:00:41 +00004678static void unixUnmapfile(unixFile *pFd){
4679 assert( pFd->nFetchOut==0 );
4680 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004681 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004682 pFd->pMapRegion = 0;
4683 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004684 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004685 }
4686}
dan5d8a1372013-03-19 19:28:06 +00004687
danaef49d72013-03-25 16:28:54 +00004688/*
dane6ecd662013-04-01 17:56:59 +00004689** Attempt to set the size of the memory mapping maintained by file
4690** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4691**
4692** If successful, this function sets the following variables:
4693**
4694** unixFile.pMapRegion
4695** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004696** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004697**
4698** If unsuccessful, an error message is logged via sqlite3_log() and
4699** the three variables above are zeroed. In this case SQLite should
4700** continue accessing the database using the xRead() and xWrite()
4701** methods.
4702*/
4703static void unixRemapfile(
4704 unixFile *pFd, /* File descriptor object */
4705 i64 nNew /* Required mapping size */
4706){
dan4ff7bc42013-04-02 12:04:09 +00004707 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004708 int h = pFd->h; /* File descriptor open on db file */
4709 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004710 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004711 u8 *pNew = 0; /* Location of new mapping */
4712 int flags = PROT_READ; /* Flags to pass to mmap() */
4713
4714 assert( pFd->nFetchOut==0 );
4715 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004716 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004717 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004718 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004719 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004720
danfe33e392015-11-17 20:56:06 +00004721#ifdef SQLITE_MMAP_READWRITE
dane6ecd662013-04-01 17:56:59 +00004722 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
danfe33e392015-11-17 20:56:06 +00004723#endif
dane6ecd662013-04-01 17:56:59 +00004724
4725 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00004726#if HAVE_MREMAP
4727 i64 nReuse = pFd->mmapSize;
4728#else
danbc760632014-03-20 09:42:09 +00004729 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00004730 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00004731#endif
dane6ecd662013-04-01 17:56:59 +00004732 u8 *pReq = &pOrig[nReuse];
4733
4734 /* Unmap any pages of the existing mapping that cannot be reused. */
4735 if( nReuse!=nOrig ){
4736 osMunmap(pReq, nOrig-nReuse);
4737 }
4738
4739#if HAVE_MREMAP
4740 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004741 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004742#else
4743 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4744 if( pNew!=MAP_FAILED ){
4745 if( pNew!=pReq ){
4746 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004747 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004748 }else{
4749 pNew = pOrig;
4750 }
4751 }
4752#endif
4753
dan48ccef82013-04-02 20:55:01 +00004754 /* The attempt to extend the existing mapping failed. Free it. */
4755 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004756 osMunmap(pOrig, nReuse);
4757 }
4758 }
4759
4760 /* If pNew is still NULL, try to create an entirely new mapping. */
4761 if( pNew==0 ){
4762 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004763 }
4764
dan4ff7bc42013-04-02 12:04:09 +00004765 if( pNew==MAP_FAILED ){
4766 pNew = 0;
4767 nNew = 0;
4768 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4769
4770 /* If the mmap() above failed, assume that all subsequent mmap() calls
4771 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4772 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004773 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004774 }
dane6ecd662013-04-01 17:56:59 +00004775 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004776 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004777}
4778
4779/*
danaef49d72013-03-25 16:28:54 +00004780** Memory map or remap the file opened by file-descriptor pFd (if the file
4781** is already mapped, the existing mapping is replaced by the new). Or, if
4782** there already exists a mapping for this file, and there are still
4783** outstanding xFetch() references to it, this function is a no-op.
4784**
4785** If parameter nByte is non-negative, then it is the requested size of
4786** the mapping to create. Otherwise, if nByte is less than zero, then the
4787** requested size is the size of the file on disk. The actual size of the
4788** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004789** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004790**
4791** SQLITE_OK is returned if no error occurs (even if the mapping is not
4792** recreated as a result of outstanding references) or an SQLite error
4793** code otherwise.
4794*/
drhf3b1ed02015-12-02 13:11:03 +00004795static int unixMapfile(unixFile *pFd, i64 nMap){
danf23da962013-03-23 21:00:41 +00004796 assert( nMap>=0 || pFd->nFetchOut==0 );
drh333e6ca2015-12-02 15:44:39 +00004797 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00004798 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4799
4800 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00004801 struct stat statbuf; /* Low-level file information */
drhf3b1ed02015-12-02 13:11:03 +00004802 if( osFstat(pFd->h, &statbuf) ){
danf23da962013-03-23 21:00:41 +00004803 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004804 }
drh3044b512014-06-16 16:41:52 +00004805 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00004806 }
drh9b4c59f2013-04-15 17:03:42 +00004807 if( nMap>pFd->mmapSizeMax ){
4808 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004809 }
4810
drh333e6ca2015-12-02 15:44:39 +00004811 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00004812 if( nMap!=pFd->mmapSize ){
drh333e6ca2015-12-02 15:44:39 +00004813 unixRemapfile(pFd, nMap);
dan5d8a1372013-03-19 19:28:06 +00004814 }
4815
danf23da962013-03-23 21:00:41 +00004816 return SQLITE_OK;
4817}
mistachkine98844f2013-08-24 00:59:24 +00004818#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004819
danaef49d72013-03-25 16:28:54 +00004820/*
4821** If possible, return a pointer to a mapping of file fd starting at offset
4822** iOff. The mapping must be valid for at least nAmt bytes.
4823**
4824** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4825** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4826** Finally, if an error does occur, return an SQLite error code. The final
4827** value of *pp is undefined in this case.
4828**
4829** If this function does return a pointer, the caller must eventually
4830** release the reference by calling unixUnfetch().
4831*/
danf23da962013-03-23 21:00:41 +00004832static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004833#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004834 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004835#endif
danf23da962013-03-23 21:00:41 +00004836 *pp = 0;
4837
drh9b4c59f2013-04-15 17:03:42 +00004838#if SQLITE_MAX_MMAP_SIZE>0
4839 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004840 if( pFd->pMapRegion==0 ){
4841 int rc = unixMapfile(pFd, -1);
4842 if( rc!=SQLITE_OK ) return rc;
4843 }
4844 if( pFd->mmapSize >= iOff+nAmt ){
4845 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4846 pFd->nFetchOut++;
4847 }
4848 }
drh6e0b6d52013-04-09 16:19:20 +00004849#endif
danf23da962013-03-23 21:00:41 +00004850 return SQLITE_OK;
4851}
4852
danaef49d72013-03-25 16:28:54 +00004853/*
dandf737fe2013-03-25 17:00:24 +00004854** If the third argument is non-NULL, then this function releases a
4855** reference obtained by an earlier call to unixFetch(). The second
4856** argument passed to this function must be the same as the corresponding
4857** argument that was passed to the unixFetch() invocation.
4858**
4859** Or, if the third argument is NULL, then this function is being called
4860** to inform the VFS layer that, according to POSIX, any existing mapping
4861** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004862*/
dandf737fe2013-03-25 17:00:24 +00004863static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00004864#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00004865 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00004866 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00004867
danaef49d72013-03-25 16:28:54 +00004868 /* If p==0 (unmap the entire file) then there must be no outstanding
4869 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4870 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004871 assert( (p==0)==(pFd->nFetchOut==0) );
4872
dandf737fe2013-03-25 17:00:24 +00004873 /* If p!=0, it must match the iOff value. */
4874 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4875
danf23da962013-03-23 21:00:41 +00004876 if( p ){
4877 pFd->nFetchOut--;
4878 }else{
4879 unixUnmapfile(pFd);
4880 }
4881
4882 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00004883#else
4884 UNUSED_PARAMETER(fd);
4885 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00004886 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00004887#endif
danf23da962013-03-23 21:00:41 +00004888 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004889}
4890
4891/*
drh734c9862008-11-28 15:37:20 +00004892** Here ends the implementation of all sqlite3_file methods.
4893**
4894********************** End sqlite3_file Methods *******************************
4895******************************************************************************/
4896
4897/*
drh6b9d6dd2008-12-03 19:34:47 +00004898** This division contains definitions of sqlite3_io_methods objects that
4899** implement various file locking strategies. It also contains definitions
4900** of "finder" functions. A finder-function is used to locate the appropriate
4901** sqlite3_io_methods object for a particular database file. The pAppData
4902** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4903** the correct finder-function for that VFS.
4904**
4905** Most finder functions return a pointer to a fixed sqlite3_io_methods
4906** object. The only interesting finder-function is autolockIoFinder, which
4907** looks at the filesystem type and tries to guess the best locking
4908** strategy from that.
4909**
peter.d.reid60ec9142014-09-06 16:39:46 +00004910** For finder-function F, two objects are created:
drh1875f7a2008-12-08 18:19:17 +00004911**
4912** (1) The real finder-function named "FImpt()".
4913**
dane946c392009-08-22 11:39:46 +00004914** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004915**
4916**
4917** A pointer to the F pointer is used as the pAppData value for VFS
4918** objects. We have to do this instead of letting pAppData point
4919** directly at the finder-function since C90 rules prevent a void*
4920** from be cast into a function pointer.
4921**
drh6b9d6dd2008-12-03 19:34:47 +00004922**
drh7708e972008-11-29 00:56:52 +00004923** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004924**
drh7708e972008-11-29 00:56:52 +00004925** * A constant sqlite3_io_methods object call METHOD that has locking
4926** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4927**
4928** * An I/O method finder function called FINDER that returns a pointer
4929** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004930*/
drhe6d41732015-02-21 00:49:00 +00004931#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
drh7708e972008-11-29 00:56:52 +00004932static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004933 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004934 CLOSE, /* xClose */ \
4935 unixRead, /* xRead */ \
4936 unixWrite, /* xWrite */ \
4937 unixTruncate, /* xTruncate */ \
4938 unixSync, /* xSync */ \
4939 unixFileSize, /* xFileSize */ \
4940 LOCK, /* xLock */ \
4941 UNLOCK, /* xUnlock */ \
4942 CKLOCK, /* xCheckReservedLock */ \
4943 unixFileControl, /* xFileControl */ \
4944 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004945 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drhd9f94412014-09-22 03:22:27 +00004946 SHMMAP, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004947 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004948 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00004949 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00004950 unixFetch, /* xFetch */ \
4951 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00004952}; \
drh0c2694b2009-09-03 16:23:44 +00004953static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4954 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004955 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004956} \
drh0c2694b2009-09-03 16:23:44 +00004957static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004958 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004959
4960/*
4961** Here are all of the sqlite3_io_methods objects for each of the
4962** locking strategies. Functions that return pointers to these methods
4963** are also created.
4964*/
4965IOMETHODS(
4966 posixIoFinder, /* Finder function name */
4967 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00004968 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00004969 unixClose, /* xClose method */
4970 unixLock, /* xLock method */
4971 unixUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004972 unixCheckReservedLock, /* xCheckReservedLock method */
4973 unixShmMap /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004974)
drh7708e972008-11-29 00:56:52 +00004975IOMETHODS(
4976 nolockIoFinder, /* Finder function name */
4977 nolockIoMethods, /* sqlite3_io_methods object name */
drh142341c2014-09-19 19:00:48 +00004978 3, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004979 nolockClose, /* xClose method */
4980 nolockLock, /* xLock method */
4981 nolockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004982 nolockCheckReservedLock, /* xCheckReservedLock method */
4983 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004984)
drh7708e972008-11-29 00:56:52 +00004985IOMETHODS(
4986 dotlockIoFinder, /* Finder function name */
4987 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004988 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004989 dotlockClose, /* xClose method */
4990 dotlockLock, /* xLock method */
4991 dotlockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004992 dotlockCheckReservedLock, /* xCheckReservedLock method */
4993 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004994)
drh7708e972008-11-29 00:56:52 +00004995
drhe89b2912015-03-03 20:42:01 +00004996#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004997IOMETHODS(
4998 flockIoFinder, /* Finder function name */
4999 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005000 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005001 flockClose, /* xClose method */
5002 flockLock, /* xLock method */
5003 flockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005004 flockCheckReservedLock, /* xCheckReservedLock method */
5005 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005006)
drh7708e972008-11-29 00:56:52 +00005007#endif
5008
drh6c7d5c52008-11-21 20:32:33 +00005009#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005010IOMETHODS(
5011 semIoFinder, /* Finder function name */
5012 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005013 1, /* shared memory is disabled */
drh8cd5b252015-03-02 22:06:43 +00005014 semXClose, /* xClose method */
5015 semXLock, /* xLock method */
5016 semXUnlock, /* xUnlock method */
5017 semXCheckReservedLock, /* xCheckReservedLock method */
drhd9f94412014-09-22 03:22:27 +00005018 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005019)
aswiftaebf4132008-11-21 00:10:35 +00005020#endif
drh7708e972008-11-29 00:56:52 +00005021
drhd2cb50b2009-01-09 21:41:17 +00005022#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005023IOMETHODS(
5024 afpIoFinder, /* Finder function name */
5025 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005026 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005027 afpClose, /* xClose method */
5028 afpLock, /* xLock method */
5029 afpUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005030 afpCheckReservedLock, /* xCheckReservedLock method */
5031 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005032)
drh715ff302008-12-03 22:32:44 +00005033#endif
5034
5035/*
5036** The proxy locking method is a "super-method" in the sense that it
5037** opens secondary file descriptors for the conch and lock files and
5038** it uses proxy, dot-file, AFP, and flock() locking methods on those
5039** secondary files. For this reason, the division that implements
5040** proxy locking is located much further down in the file. But we need
5041** to go ahead and define the sqlite3_io_methods and finder function
5042** for proxy locking here. So we forward declare the I/O methods.
5043*/
drhd2cb50b2009-01-09 21:41:17 +00005044#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005045static int proxyClose(sqlite3_file*);
5046static int proxyLock(sqlite3_file*, int);
5047static int proxyUnlock(sqlite3_file*, int);
5048static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005049IOMETHODS(
5050 proxyIoFinder, /* Finder function name */
5051 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005052 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005053 proxyClose, /* xClose method */
5054 proxyLock, /* xLock method */
5055 proxyUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005056 proxyCheckReservedLock, /* xCheckReservedLock method */
5057 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005058)
aswiftaebf4132008-11-21 00:10:35 +00005059#endif
drh7708e972008-11-29 00:56:52 +00005060
drh7ed97b92010-01-20 13:07:21 +00005061/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5062#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5063IOMETHODS(
5064 nfsIoFinder, /* Finder function name */
5065 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005066 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005067 unixClose, /* xClose method */
5068 unixLock, /* xLock method */
5069 nfsUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005070 unixCheckReservedLock, /* xCheckReservedLock method */
5071 0 /* xShmMap method */
drh7ed97b92010-01-20 13:07:21 +00005072)
5073#endif
drh7708e972008-11-29 00:56:52 +00005074
drhd2cb50b2009-01-09 21:41:17 +00005075#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005076/*
drh6b9d6dd2008-12-03 19:34:47 +00005077** This "finder" function attempts to determine the best locking strategy
5078** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005079** object that implements that strategy.
5080**
5081** This is for MacOSX only.
5082*/
drh1875f7a2008-12-08 18:19:17 +00005083static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005084 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005085 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005086){
5087 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005088 const char *zFilesystem; /* Filesystem type name */
5089 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005090 } aMap[] = {
5091 { "hfs", &posixIoMethods },
5092 { "ufs", &posixIoMethods },
5093 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005094 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005095 { "webdav", &nolockIoMethods },
5096 { 0, 0 }
5097 };
5098 int i;
5099 struct statfs fsInfo;
5100 struct flock lockInfo;
5101
5102 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005103 /* If filePath==NULL that means we are dealing with a transient file
5104 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005105 return &nolockIoMethods;
5106 }
5107 if( statfs(filePath, &fsInfo) != -1 ){
5108 if( fsInfo.f_flags & MNT_RDONLY ){
5109 return &nolockIoMethods;
5110 }
5111 for(i=0; aMap[i].zFilesystem; i++){
5112 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5113 return aMap[i].pMethods;
5114 }
5115 }
5116 }
5117
5118 /* Default case. Handles, amongst others, "nfs".
5119 ** Test byte-range lock using fcntl(). If the call succeeds,
5120 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005121 */
drh7708e972008-11-29 00:56:52 +00005122 lockInfo.l_len = 1;
5123 lockInfo.l_start = 0;
5124 lockInfo.l_whence = SEEK_SET;
5125 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005126 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005127 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5128 return &nfsIoMethods;
5129 } else {
5130 return &posixIoMethods;
5131 }
drh7708e972008-11-29 00:56:52 +00005132 }else{
5133 return &dotlockIoMethods;
5134 }
5135}
drh0c2694b2009-09-03 16:23:44 +00005136static const sqlite3_io_methods
5137 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005138
drhd2cb50b2009-01-09 21:41:17 +00005139#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005140
drhe89b2912015-03-03 20:42:01 +00005141#if OS_VXWORKS
5142/*
5143** This "finder" function for VxWorks checks to see if posix advisory
5144** locking works. If it does, then that is what is used. If it does not
5145** work, then fallback to named semaphore locking.
chw78a13182009-04-07 05:35:03 +00005146*/
drhe89b2912015-03-03 20:42:01 +00005147static const sqlite3_io_methods *vxworksIoFinderImpl(
chw78a13182009-04-07 05:35:03 +00005148 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005149 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005150){
5151 struct flock lockInfo;
5152
5153 if( !filePath ){
5154 /* If filePath==NULL that means we are dealing with a transient file
5155 ** that does not need to be locked. */
5156 return &nolockIoMethods;
5157 }
5158
5159 /* Test if fcntl() is supported and use POSIX style locks.
5160 ** Otherwise fall back to the named semaphore method.
5161 */
5162 lockInfo.l_len = 1;
5163 lockInfo.l_start = 0;
5164 lockInfo.l_whence = SEEK_SET;
5165 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005166 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005167 return &posixIoMethods;
5168 }else{
5169 return &semIoMethods;
5170 }
5171}
drh0c2694b2009-09-03 16:23:44 +00005172static const sqlite3_io_methods
drhe89b2912015-03-03 20:42:01 +00005173 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005174
drhe89b2912015-03-03 20:42:01 +00005175#endif /* OS_VXWORKS */
chw78a13182009-04-07 05:35:03 +00005176
drh7708e972008-11-29 00:56:52 +00005177/*
peter.d.reid60ec9142014-09-06 16:39:46 +00005178** An abstract type for a pointer to an IO method finder function:
drh7708e972008-11-29 00:56:52 +00005179*/
drh0c2694b2009-09-03 16:23:44 +00005180typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005181
aswiftaebf4132008-11-21 00:10:35 +00005182
drh734c9862008-11-28 15:37:20 +00005183/****************************************************************************
5184**************************** sqlite3_vfs methods ****************************
5185**
5186** This division contains the implementation of methods on the
5187** sqlite3_vfs object.
5188*/
5189
danielk1977a3d4c882007-03-23 10:08:38 +00005190/*
danielk1977e339d652008-06-28 11:23:00 +00005191** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005192*/
5193static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005194 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005195 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005196 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005197 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005198 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005199){
drh7708e972008-11-29 00:56:52 +00005200 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005201 unixFile *pNew = (unixFile *)pId;
5202 int rc = SQLITE_OK;
5203
drh8af6c222010-05-14 12:43:01 +00005204 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005205
dan00157392010-10-05 11:33:15 +00005206 /* Usually the path zFilename should not be a relative pathname. The
5207 ** exception is when opening the proxy "conch" file in builds that
5208 ** include the special Apple locking styles.
5209 */
dan00157392010-10-05 11:33:15 +00005210#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005211 assert( zFilename==0 || zFilename[0]=='/'
5212 || pVfs->pAppData==(void*)&autolockIoFinder );
5213#else
5214 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005215#endif
dan00157392010-10-05 11:33:15 +00005216
drhb07028f2011-10-14 21:49:18 +00005217 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005218 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005219
drh308c2a52010-05-14 11:30:18 +00005220 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005221 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005222 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005223 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005224 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005225#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005226 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005227#endif
drhc02a43a2012-01-10 23:18:38 +00005228 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5229 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005230 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005231 }
drh503a6862013-03-01 01:07:17 +00005232 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005233 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005234 }
drh339eb0b2008-03-07 15:34:11 +00005235
drh6c7d5c52008-11-21 20:32:33 +00005236#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005237 pNew->pId = vxworksFindFileId(zFilename);
5238 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005239 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00005240 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00005241 }
5242#endif
5243
drhc02a43a2012-01-10 23:18:38 +00005244 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005245 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005246 }else{
drh0c2694b2009-09-03 16:23:44 +00005247 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005248#if SQLITE_ENABLE_LOCKING_STYLE
5249 /* Cache zFilename in the locking context (AFP and dotlock override) for
5250 ** proxyLock activation is possible (remote proxy is based on db name)
5251 ** zFilename remains valid until file is closed, to support */
5252 pNew->lockingContext = (void*)zFilename;
5253#endif
drhda0e7682008-07-30 15:27:54 +00005254 }
danielk1977e339d652008-06-28 11:23:00 +00005255
drh7ed97b92010-01-20 13:07:21 +00005256 if( pLockingStyle == &posixIoMethods
5257#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5258 || pLockingStyle == &nfsIoMethods
5259#endif
5260 ){
drh7708e972008-11-29 00:56:52 +00005261 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005262 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005263 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005264 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005265 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005266 ** in two scenarios:
5267 **
5268 ** (a) A call to fstat() failed.
5269 ** (b) A malloc failed.
5270 **
5271 ** Scenario (b) may only occur if the process is holding no other
5272 ** file descriptors open on the same file. If there were other file
5273 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005274 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005275 ** handle h - as it is guaranteed that no posix locks will be released
5276 ** by doing so.
5277 **
5278 ** If scenario (a) caused the error then things are not so safe. The
5279 ** implicit assumption here is that if fstat() fails, things are in
5280 ** such bad shape that dropping a lock or two doesn't matter much.
5281 */
drh0e9365c2011-03-02 02:08:13 +00005282 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005283 h = -1;
5284 }
drh7708e972008-11-29 00:56:52 +00005285 unixLeaveMutex();
5286 }
danielk1977e339d652008-06-28 11:23:00 +00005287
drhd2cb50b2009-01-09 21:41:17 +00005288#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005289 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005290 /* AFP locking uses the file path so it needs to be included in
5291 ** the afpLockingContext.
5292 */
5293 afpLockingContext *pCtx;
drhf3cdcdc2015-04-29 16:50:28 +00005294 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh7708e972008-11-29 00:56:52 +00005295 if( pCtx==0 ){
5296 rc = SQLITE_NOMEM;
5297 }else{
5298 /* NB: zFilename exists and remains valid until the file is closed
5299 ** according to requirement F11141. So we do not need to make a
5300 ** copy of the filename. */
5301 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005302 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005303 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005304 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005305 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005306 if( rc!=SQLITE_OK ){
5307 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005308 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005309 h = -1;
5310 }
drh7708e972008-11-29 00:56:52 +00005311 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005312 }
drh7708e972008-11-29 00:56:52 +00005313 }
5314#endif
danielk1977e339d652008-06-28 11:23:00 +00005315
drh7708e972008-11-29 00:56:52 +00005316 else if( pLockingStyle == &dotlockIoMethods ){
5317 /* Dotfile locking uses the file path so it needs to be included in
5318 ** the dotlockLockingContext
5319 */
5320 char *zLockFile;
5321 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005322 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005323 nFilename = (int)strlen(zFilename) + 6;
drhf3cdcdc2015-04-29 16:50:28 +00005324 zLockFile = (char *)sqlite3_malloc64(nFilename);
drh7708e972008-11-29 00:56:52 +00005325 if( zLockFile==0 ){
5326 rc = SQLITE_NOMEM;
5327 }else{
5328 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005329 }
drh7708e972008-11-29 00:56:52 +00005330 pNew->lockingContext = zLockFile;
5331 }
danielk1977e339d652008-06-28 11:23:00 +00005332
drh6c7d5c52008-11-21 20:32:33 +00005333#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005334 else if( pLockingStyle == &semIoMethods ){
5335 /* Named semaphore locking uses the file path so it needs to be
5336 ** included in the semLockingContext
5337 */
5338 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005339 rc = findInodeInfo(pNew, &pNew->pInode);
5340 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5341 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005342 int n;
drh2238dcc2009-08-27 17:56:20 +00005343 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005344 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005345 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005346 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005347 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5348 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00005349 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00005350 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005351 }
chw97185482008-11-17 08:05:31 +00005352 }
drh7708e972008-11-29 00:56:52 +00005353 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005354 }
drh7708e972008-11-29 00:56:52 +00005355#endif
aswift5b1a2562008-08-22 00:22:35 +00005356
drh4bf66fd2015-02-19 02:43:02 +00005357 storeLastErrno(pNew, 0);
drh6c7d5c52008-11-21 20:32:33 +00005358#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005359 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005360 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005361 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005362 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005363 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005364 }
chw97185482008-11-17 08:05:31 +00005365#endif
danielk1977e339d652008-06-28 11:23:00 +00005366 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005367 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005368 }else{
drh7708e972008-11-29 00:56:52 +00005369 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005370 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005371 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005372 }
danielk1977e339d652008-06-28 11:23:00 +00005373 return rc;
drh054889e2005-11-30 03:20:31 +00005374}
drh9c06c952005-11-26 00:25:00 +00005375
danielk1977ad94b582007-08-20 06:44:22 +00005376/*
drh8b3cf822010-06-01 21:02:51 +00005377** Return the name of a directory in which to put temporary files.
5378** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005379*/
drh7234c6d2010-06-19 15:10:09 +00005380static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005381 static const char *azDirs[] = {
5382 0,
aswiftaebf4132008-11-21 00:10:35 +00005383 0,
danielk197717b90b52008-06-06 11:11:25 +00005384 "/var/tmp",
5385 "/usr/tmp",
5386 "/tmp",
drhb7e50ad2015-11-28 21:49:53 +00005387 "."
danielk197717b90b52008-06-06 11:11:25 +00005388 };
drh8b3cf822010-06-01 21:02:51 +00005389 unsigned int i;
5390 struct stat buf;
drhb7e50ad2015-11-28 21:49:53 +00005391 const char *zDir = sqlite3_temp_directory;
drh8b3cf822010-06-01 21:02:51 +00005392
drhb7e50ad2015-11-28 21:49:53 +00005393 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
5394 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005395 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005396 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005397 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005398 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005399 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005400 break;
5401 }
5402 return zDir;
5403}
5404
5405/*
5406** Create a temporary file name in zBuf. zBuf must be allocated
5407** by the calling process and must be big enough to hold at least
5408** pVfs->mxPathname bytes.
5409*/
5410static int unixGetTempname(int nBuf, char *zBuf){
drh8b3cf822010-06-01 21:02:51 +00005411 const char *zDir;
drhb7e50ad2015-11-28 21:49:53 +00005412 int iLimit = 0;
danielk197717b90b52008-06-06 11:11:25 +00005413
5414 /* It's odd to simulate an io-error here, but really this is just
5415 ** using the io-error infrastructure to test that SQLite handles this
5416 ** function failing.
5417 */
5418 SimulateIOError( return SQLITE_IOERR );
5419
drh7234c6d2010-06-19 15:10:09 +00005420 zDir = unixTempFileDir();
danielk197717b90b52008-06-06 11:11:25 +00005421 do{
drh970942e2015-11-25 23:13:14 +00005422 u64 r;
5423 sqlite3_randomness(sizeof(r), &r);
5424 assert( nBuf>2 );
5425 zBuf[nBuf-2] = 0;
5426 sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
5427 zDir, r, 0);
drhb7e50ad2015-11-28 21:49:53 +00005428 if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
drh99ab3b12011-03-02 15:09:07 +00005429 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005430 return SQLITE_OK;
5431}
5432
drhd2cb50b2009-01-09 21:41:17 +00005433#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005434/*
5435** Routine to transform a unixFile into a proxy-locking unixFile.
5436** Implementation in the proxy-lock division, but used by unixOpen()
5437** if SQLITE_PREFER_PROXY_LOCKING is defined.
5438*/
5439static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005440#endif
drhc66d5b62008-12-03 22:48:32 +00005441
dan08da86a2009-08-21 17:18:03 +00005442/*
5443** Search for an unused file descriptor that was opened on the database
5444** file (not a journal or master-journal file) identified by pathname
5445** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5446** argument to this function.
5447**
5448** Such a file descriptor may exist if a database connection was closed
5449** but the associated file descriptor could not be closed because some
5450** other file descriptor open on the same file is holding a file-lock.
5451** Refer to comments in the unixClose() function and the lengthy comment
5452** describing "Posix Advisory Locking" at the start of this file for
5453** further details. Also, ticket #4018.
5454**
5455** If a suitable file descriptor is found, then it is returned. If no
5456** such file descriptor is located, -1 is returned.
5457*/
dane946c392009-08-22 11:39:46 +00005458static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5459 UnixUnusedFd *pUnused = 0;
5460
5461 /* Do not search for an unused file descriptor on vxworks. Not because
5462 ** vxworks would not benefit from the change (it might, we're not sure),
5463 ** but because no way to test it is currently available. It is better
5464 ** not to risk breaking vxworks support for the sake of such an obscure
5465 ** feature. */
5466#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005467 struct stat sStat; /* Results of stat() call */
5468
5469 /* A stat() call may fail for various reasons. If this happens, it is
5470 ** almost certain that an open() call on the same path will also fail.
5471 ** For this reason, if an error occurs in the stat() call here, it is
5472 ** ignored and -1 is returned. The caller will try to open a new file
5473 ** descriptor on the same path, fail, and return an error to SQLite.
5474 **
5475 ** Even if a subsequent open() call does succeed, the consequences of
peter.d.reid60ec9142014-09-06 16:39:46 +00005476 ** not searching for a reusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005477 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005478 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005479
5480 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005481 pInode = inodeList;
5482 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5483 || pInode->fileId.ino!=sStat.st_ino) ){
5484 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005485 }
drh8af6c222010-05-14 12:43:01 +00005486 if( pInode ){
dane946c392009-08-22 11:39:46 +00005487 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005488 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005489 pUnused = *pp;
5490 if( pUnused ){
5491 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005492 }
5493 }
5494 unixLeaveMutex();
5495 }
dane946c392009-08-22 11:39:46 +00005496#endif /* if !OS_VXWORKS */
5497 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005498}
danielk197717b90b52008-06-06 11:11:25 +00005499
5500/*
danddb0ac42010-07-14 14:48:58 +00005501** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005502** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005503** and a value suitable for passing as the third argument to open(2) is
5504** written to *pMode. If an IO error occurs, an SQLite error code is
5505** returned and the value of *pMode is not modified.
5506**
peter.d.reid60ec9142014-09-06 16:39:46 +00005507** In most cases, this routine sets *pMode to 0, which will become
drh8c815d12012-02-13 20:16:37 +00005508** an indication to robust_open() to create the file using
5509** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5510** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005511** this function queries the file-system for the permissions on the
5512** corresponding database file and sets *pMode to this value. Whenever
5513** possible, WAL and journal files are created using the same permissions
5514** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005515**
5516** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5517** original filename is unavailable. But 8_3_NAMES is only used for
5518** FAT filesystems and permissions do not matter there, so just use
5519** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005520*/
5521static int findCreateFileMode(
5522 const char *zPath, /* Path of file (possibly) being created */
5523 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005524 mode_t *pMode, /* OUT: Permissions to open file with */
5525 uid_t *pUid, /* OUT: uid to set on the file */
5526 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005527){
5528 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005529 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005530 *pUid = 0;
5531 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005532 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005533 char zDb[MAX_PATHNAME+1]; /* Database file path */
5534 int nDb; /* Number of valid bytes in zDb */
5535 struct stat sStat; /* Output of stat() on database file */
5536
dana0c989d2010-11-05 18:07:37 +00005537 /* zPath is a path to a WAL or journal file. The following block derives
5538 ** the path to the associated database file from zPath. This block handles
5539 ** the following naming conventions:
5540 **
5541 ** "<path to db>-journal"
5542 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005543 ** "<path to db>-journalNN"
5544 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005545 **
drhd337c5b2011-10-20 18:23:35 +00005546 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005547 ** used by the test_multiplex.c module.
5548 */
5549 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005550 while( zPath[nDb]!='-' ){
drh90e5dda2015-12-03 20:42:28 +00005551#ifndef SQLITE_ENABLE_8_3_NAMES
5552 /* In the normal case (8+3 filenames disabled) the journal filename
5553 ** is guaranteed to contain a '-' character. */
drhc47167a2011-10-05 15:26:13 +00005554 assert( nDb>0 );
drh90e5dda2015-12-03 20:42:28 +00005555 assert( sqlite3Isalnum(zPath[nDb]) );
5556#else
5557 /* If 8+3 names are possible, then the journal file might not contain
5558 ** a '-' character. So check for that case and return early. */
5559 if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
5560#endif
drhc47167a2011-10-05 15:26:13 +00005561 nDb--;
5562 }
danddb0ac42010-07-14 14:48:58 +00005563 memcpy(zDb, zPath, nDb);
5564 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005565
drh58384f12011-07-28 00:14:45 +00005566 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005567 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005568 *pUid = sStat.st_uid;
5569 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005570 }else{
5571 rc = SQLITE_IOERR_FSTAT;
5572 }
5573 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5574 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005575 }
5576 return rc;
5577}
5578
5579/*
danielk1977ad94b582007-08-20 06:44:22 +00005580** Open the file zPath.
5581**
danielk1977b4b47412007-08-17 15:53:36 +00005582** Previously, the SQLite OS layer used three functions in place of this
5583** one:
5584**
5585** sqlite3OsOpenReadWrite();
5586** sqlite3OsOpenReadOnly();
5587** sqlite3OsOpenExclusive();
5588**
5589** These calls correspond to the following combinations of flags:
5590**
5591** ReadWrite() -> (READWRITE | CREATE)
5592** ReadOnly() -> (READONLY)
5593** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5594**
5595** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5596** true, the file was configured to be automatically deleted when the
5597** file handle closed. To achieve the same effect using this new
5598** interface, add the DELETEONCLOSE flag to those specified above for
5599** OpenExclusive().
5600*/
5601static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005602 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5603 const char *zPath, /* Pathname of file to be opened */
5604 sqlite3_file *pFile, /* The file descriptor to be filled in */
5605 int flags, /* Input flags to control the opening */
5606 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005607){
dan08da86a2009-08-21 17:18:03 +00005608 unixFile *p = (unixFile *)pFile;
5609 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005610 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005611 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005612 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005613 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005614 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005615
5616 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5617 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5618 int isCreate = (flags & SQLITE_OPEN_CREATE);
5619 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5620 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005621#if SQLITE_ENABLE_LOCKING_STYLE
5622 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5623#endif
drh3d4435b2011-08-26 20:55:50 +00005624#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5625 struct statfs fsInfo;
5626#endif
danielk1977b4b47412007-08-17 15:53:36 +00005627
danielk1977fee2d252007-08-18 10:59:19 +00005628 /* If creating a master or main-file journal, this function will open
5629 ** a file-descriptor on the directory too. The first time unixSync()
5630 ** is called the directory file descriptor will be fsync()ed and close()d.
5631 */
drh0059eae2011-08-08 23:48:40 +00005632 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005633 eType==SQLITE_OPEN_MASTER_JOURNAL
5634 || eType==SQLITE_OPEN_MAIN_JOURNAL
5635 || eType==SQLITE_OPEN_WAL
5636 ));
danielk1977fee2d252007-08-18 10:59:19 +00005637
danielk197717b90b52008-06-06 11:11:25 +00005638 /* If argument zPath is a NULL pointer, this function is required to open
5639 ** a temporary file. Use this buffer to store the file name in.
5640 */
drhc02a43a2012-01-10 23:18:38 +00005641 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005642 const char *zName = zPath;
5643
danielk1977fee2d252007-08-18 10:59:19 +00005644 /* Check the following statements are true:
5645 **
5646 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5647 ** (b) if CREATE is set, then READWRITE must also be set, and
5648 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005649 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005650 */
danielk1977b4b47412007-08-17 15:53:36 +00005651 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005652 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005653 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005654 assert(isDelete==0 || isCreate);
5655
danddb0ac42010-07-14 14:48:58 +00005656 /* The main DB, main journal, WAL file and master journal are never
5657 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005658 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5659 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5660 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005661 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005662
danielk1977fee2d252007-08-18 10:59:19 +00005663 /* Assert that the upper layer has set one of the "file-type" flags. */
5664 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5665 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5666 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005667 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005668 );
5669
drhb00d8622014-01-01 15:18:36 +00005670 /* Detect a pid change and reset the PRNG. There is a race condition
5671 ** here such that two or more threads all trying to open databases at
5672 ** the same instant might all reset the PRNG. But multiple resets
5673 ** are harmless.
5674 */
drh5ac93652015-03-21 20:59:43 +00005675 if( randomnessPid!=osGetpid(0) ){
5676 randomnessPid = osGetpid(0);
drhb00d8622014-01-01 15:18:36 +00005677 sqlite3_randomness(0,0);
5678 }
5679
dan08da86a2009-08-21 17:18:03 +00005680 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005681
dan08da86a2009-08-21 17:18:03 +00005682 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005683 UnixUnusedFd *pUnused;
5684 pUnused = findReusableFd(zName, flags);
5685 if( pUnused ){
5686 fd = pUnused->fd;
5687 }else{
drhf3cdcdc2015-04-29 16:50:28 +00005688 pUnused = sqlite3_malloc64(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005689 if( !pUnused ){
5690 return SQLITE_NOMEM;
5691 }
5692 }
5693 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005694
5695 /* Database filenames are double-zero terminated if they are not
5696 ** URIs with parameters. Hence, they can always be passed into
5697 ** sqlite3_uri_parameter(). */
5698 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5699
dan08da86a2009-08-21 17:18:03 +00005700 }else if( !zName ){
5701 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005702 assert(isDelete && !syncDir);
drhb7e50ad2015-11-28 21:49:53 +00005703 rc = unixGetTempname(pVfs->mxPathname, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005704 if( rc!=SQLITE_OK ){
5705 return rc;
5706 }
5707 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005708
5709 /* Generated temporary filenames are always double-zero terminated
5710 ** for use by sqlite3_uri_parameter(). */
5711 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005712 }
5713
dan08da86a2009-08-21 17:18:03 +00005714 /* Determine the value of the flags parameter passed to POSIX function
5715 ** open(). These must be calculated even if open() is not called, as
5716 ** they may be stored as part of the file handle and used by the
5717 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005718 if( isReadonly ) openFlags |= O_RDONLY;
5719 if( isReadWrite ) openFlags |= O_RDWR;
5720 if( isCreate ) openFlags |= O_CREAT;
5721 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5722 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005723
danielk1977b4b47412007-08-17 15:53:36 +00005724 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005725 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005726 uid_t uid; /* Userid for the file */
5727 gid_t gid; /* Groupid for the file */
5728 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005729 if( rc!=SQLITE_OK ){
5730 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005731 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005732 return rc;
5733 }
drhad4f1e52011-03-04 15:43:57 +00005734 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005735 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
drh5a2d9702015-11-26 02:21:05 +00005736 assert( !isExclusive || (openFlags & O_CREAT)!=0 );
5737 if( fd<0 && errno!=EISDIR && isReadWrite ){
dan08da86a2009-08-21 17:18:03 +00005738 /* Failed to open the file for read/write access. Try read-only. */
5739 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005740 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005741 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005742 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005743 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005744 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005745 }
5746 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005747 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005748 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005749 }
drhac7c3ac2012-02-11 19:23:48 +00005750
5751 /* If this process is running as root and if creating a new rollback
5752 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005753 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005754 */
5755 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drh6226ca22015-11-24 15:06:28 +00005756 robustFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005757 }
danielk1977b4b47412007-08-17 15:53:36 +00005758 }
dan08da86a2009-08-21 17:18:03 +00005759 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005760 if( pOutFlags ){
5761 *pOutFlags = flags;
5762 }
5763
dane946c392009-08-22 11:39:46 +00005764 if( p->pUnused ){
5765 p->pUnused->fd = fd;
5766 p->pUnused->flags = flags;
5767 }
5768
danielk1977b4b47412007-08-17 15:53:36 +00005769 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005770#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005771 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00005772#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
5773 zPath = sqlite3_mprintf("%s", zName);
5774 if( zPath==0 ){
5775 robust_close(p, fd, __LINE__);
5776 return SQLITE_NOMEM;
5777 }
chw97185482008-11-17 08:05:31 +00005778#else
drh036ac7f2011-08-08 23:18:05 +00005779 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005780#endif
danielk1977b4b47412007-08-17 15:53:36 +00005781 }
drh41022642008-11-21 00:24:42 +00005782#if SQLITE_ENABLE_LOCKING_STYLE
5783 else{
dan08da86a2009-08-21 17:18:03 +00005784 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005785 }
5786#endif
5787
drhda0e7682008-07-30 15:27:54 +00005788 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005789
drh7ed97b92010-01-20 13:07:21 +00005790
5791#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005792 if( fstatfs(fd, &fsInfo) == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00005793 storeLastErrno(p, errno);
drh0e9365c2011-03-02 02:08:13 +00005794 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005795 return SQLITE_IOERR_ACCESS;
5796 }
5797 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5798 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5799 }
drh4bf66fd2015-02-19 02:43:02 +00005800 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
5801 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5802 }
drh7ed97b92010-01-20 13:07:21 +00005803#endif
drhc02a43a2012-01-10 23:18:38 +00005804
5805 /* Set up appropriate ctrlFlags */
5806 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5807 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5808 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5809 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5810 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5811
drh7ed97b92010-01-20 13:07:21 +00005812#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005813#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005814 isAutoProxy = 1;
5815#endif
5816 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005817 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5818 int useProxy = 0;
5819
dan08da86a2009-08-21 17:18:03 +00005820 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5821 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005822 if( envforce!=NULL ){
5823 useProxy = atoi(envforce)>0;
5824 }else{
aswiftaebf4132008-11-21 00:10:35 +00005825 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5826 }
5827 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005828 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005829 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005830 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005831 if( rc!=SQLITE_OK ){
5832 /* Use unixClose to clean up the resources added in fillInUnixFile
5833 ** and clear all the structure's references. Specifically,
5834 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5835 */
5836 unixClose(pFile);
5837 return rc;
5838 }
aswiftaebf4132008-11-21 00:10:35 +00005839 }
dane946c392009-08-22 11:39:46 +00005840 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005841 }
5842 }
5843#endif
5844
drhc02a43a2012-01-10 23:18:38 +00005845 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5846
dane946c392009-08-22 11:39:46 +00005847open_finished:
5848 if( rc!=SQLITE_OK ){
5849 sqlite3_free(p->pUnused);
5850 }
5851 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005852}
5853
dane946c392009-08-22 11:39:46 +00005854
danielk1977b4b47412007-08-17 15:53:36 +00005855/*
danielk1977fee2d252007-08-18 10:59:19 +00005856** Delete the file at zPath. If the dirSync argument is true, fsync()
5857** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005858*/
drh6b9d6dd2008-12-03 19:34:47 +00005859static int unixDelete(
5860 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5861 const char *zPath, /* Name of file to be deleted */
5862 int dirSync /* If true, fsync() directory after deleting file */
5863){
danielk1977fee2d252007-08-18 10:59:19 +00005864 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005865 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005866 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005867 if( osUnlink(zPath)==(-1) ){
drhbd945542014-08-13 11:39:42 +00005868 if( errno==ENOENT
5869#if OS_VXWORKS
drh19541f32014-09-01 13:37:55 +00005870 || osAccess(zPath,0)!=0
drhbd945542014-08-13 11:39:42 +00005871#endif
5872 ){
dan9fc5b4a2012-11-09 20:17:26 +00005873 rc = SQLITE_IOERR_DELETE_NOENT;
5874 }else{
drhb4308162012-11-09 21:40:02 +00005875 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005876 }
drhb4308162012-11-09 21:40:02 +00005877 return rc;
drh5d4feff2010-07-14 01:45:22 +00005878 }
danielk1977d39fa702008-10-16 13:27:40 +00005879#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005880 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005881 int fd;
drh90315a22011-08-10 01:52:12 +00005882 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005883 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005884#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005885 if( fsync(fd)==-1 )
5886#else
5887 if( fsync(fd) )
5888#endif
5889 {
dane18d4952011-02-21 11:46:24 +00005890 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005891 }
drh0e9365c2011-03-02 02:08:13 +00005892 robust_close(0, fd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00005893 }else{
5894 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00005895 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005896 }
5897 }
danielk1977d138dd82008-10-15 16:02:48 +00005898#endif
danielk1977fee2d252007-08-18 10:59:19 +00005899 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005900}
5901
danielk197790949c22007-08-17 16:50:38 +00005902/*
mistachkin48864df2013-03-21 21:20:32 +00005903** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00005904** test performed depends on the value of flags:
5905**
5906** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5907** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5908** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5909**
5910** Otherwise return 0.
5911*/
danielk1977861f7452008-06-05 11:39:11 +00005912static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005913 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5914 const char *zPath, /* Path of the file to examine */
5915 int flags, /* What do we want to learn about the zPath file? */
5916 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005917){
danielk1977397d65f2008-11-19 11:35:39 +00005918 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005919 SimulateIOError( return SQLITE_IOERR_ACCESS; );
drhd260b5b2015-11-25 18:03:33 +00005920 assert( pResOut!=0 );
danielk1977b4b47412007-08-17 15:53:36 +00005921
drhd260b5b2015-11-25 18:03:33 +00005922 /* The spec says there are three possible values for flags. But only
5923 ** two of them are actually used */
5924 assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
5925
5926 if( flags==SQLITE_ACCESS_EXISTS ){
dan83acd422010-06-18 11:10:06 +00005927 struct stat buf;
drhd260b5b2015-11-25 18:03:33 +00005928 *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
5929 }else{
5930 *pResOut = osAccess(zPath, W_OK|R_OK)==0;
dan83acd422010-06-18 11:10:06 +00005931 }
danielk1977861f7452008-06-05 11:39:11 +00005932 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005933}
5934
danielk1977b4b47412007-08-17 15:53:36 +00005935/*
dane88ec182016-01-25 17:04:48 +00005936** Buffer zOut contains a (possibly) relative pathname. Overwrite it with
5937** the corresponding full pathname.
danielk1977b4b47412007-08-17 15:53:36 +00005938**
dane88ec182016-01-25 17:04:48 +00005939** Parameter nOut is the allocated size of buffer zOut. nByte is the number
5940** of bytes in the nul-terminated string that it contains (not including
5941** the nul-terminator itself).
5942**
5943** Return SQLITE_OK if successful, or an SQLite error code otherwise.
danielk1977b4b47412007-08-17 15:53:36 +00005944*/
dane88ec182016-01-25 17:04:48 +00005945static int mkFullPathname(
5946 const char *zPath, /* Use this path to log any errors */
5947 char *zOut, /* IN/OUT: Buffer to modify */
5948 int nByte, /* size of nul-terminated zOut in bytes */
5949 int nOut /* Allocated size of buffer zOut */
danielk1977adfb9b02007-09-17 07:02:56 +00005950){
dan245fdc62015-10-31 17:58:33 +00005951 /* If buffer zOut[] now contains an absolute path there is nothing more
5952 ** to do. If it contains a relative path, do the following:
5953 **
5954 ** * move the relative path string so that it is at the end of th
5955 ** zOut[] buffer.
5956 ** * Call getcwd() to read the path of the current working directory
5957 ** into the start of the zOut[] buffer.
5958 ** * Append a '/' character to the cwd string and move the
5959 ** relative path back within the buffer so that it immediately
5960 ** follows the '/'.
5961 **
5962 ** This code is written so that if the combination of the CWD and relative
5963 ** path are larger than the allocated size of zOut[] the CWD is silently
5964 ** truncated to make it fit. This is Ok, as SQLite refuses to open any
5965 ** file for which this function returns a full path larger than (nOut-8)
5966 ** bytes in size. */
dane88ec182016-01-25 17:04:48 +00005967 assert( nByte<nOut );
drh025d2f72015-11-30 22:22:23 +00005968 testcase( nByte==nOut-5 );
5969 testcase( nByte==nOut-4 );
5970 if( zOut[0]!='/' && nByte<nOut-4 ){
danielk1977b4b47412007-08-17 15:53:36 +00005971 int nCwd;
dan245fdc62015-10-31 17:58:33 +00005972 int nRem = nOut-nByte-1;
5973 memmove(&zOut[nRem], zOut, nByte+1);
5974 zOut[nRem-1] = '\0';
5975 if( osGetcwd(zOut, nRem-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005976 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005977 }
dan245fdc62015-10-31 17:58:33 +00005978 nCwd = sqlite3Strlen30(zOut);
5979 assert( nCwd<=nRem-1 );
5980 zOut[nCwd] = '/';
5981 memmove(&zOut[nCwd+1], &zOut[nRem], nByte+1);
danielk1977b4b47412007-08-17 15:53:36 +00005982 }
dan245fdc62015-10-31 17:58:33 +00005983
danielk1977b4b47412007-08-17 15:53:36 +00005984 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005985}
5986
dane88ec182016-01-25 17:04:48 +00005987/*
5988** Turn a relative pathname into a full pathname. The relative path
5989** is stored as a nul-terminated string in the buffer pointed to by
5990** zPath.
5991**
5992** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5993** (in this case, MAX_PATHNAME bytes). The full-path is written to
5994** this buffer before returning.
5995*/
5996static int unixFullPathname(
5997 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5998 const char *zPath, /* Possibly relative input path */
5999 int nOut, /* Size of output buffer in bytes */
6000 char *zOut /* Output buffer */
6001){
6002#if !defined(HAVE_READLINK)
6003 sqlite3_snprintf(nOut, zOut, "%s", zIn);
6004 nByte = sqlite3Strlen30(zOut);
6005 return mkFullPathname(zPath, zOut, sqlite3Strlen30(zOut), nOut);
6006#else
6007 int rc = SQLITE_OK;
6008 int nByte;
6009 int nLink = 0; /* Number of symbolic links followed so far */
6010 int bLink; /* True for a symbolic link */
6011 const char *zIn = zPath; /* Input path for each iteration of loop */
6012 char *zDel = 0;
6013
6014 assert( pVfs->mxPathname==MAX_PATHNAME );
6015 UNUSED_PARAMETER(pVfs);
6016
6017 /* It's odd to simulate an io-error here, but really this is just
6018 ** using the io-error infrastructure to test that SQLite handles this
6019 ** function failing. This function could fail if, for example, the
6020 ** current working directory has been unlinked.
6021 */
6022 SimulateIOError( return SQLITE_ERROR );
6023
6024 do {
6025
6026 /* Attempt to resolve the path as if it were a symbolic link. If it is
6027 ** a symbolic link, the resolved path is stored in buffer zOut[]. Or, if
6028 ** the identified file is not a symbolic link or does not exist, then
6029 ** zPath is copied directly into zOut. Either way, nByte is left set to
6030 ** the size of the string copied into zOut[] in bytes. */
6031 assert( (zDel==0 && zIn==zPath) || (zDel!=0 && zIn==zDel) );
6032 if( zDel ){
6033 assert( zIn==zDel );
6034 sqlite3_snprintf(nOut, zDel, "%s", zOut);
6035 }
6036 nByte = osReadlink(zIn, zOut, nOut-1);
6037 if( nByte<0 ){
6038 if( errno!=EINVAL && errno!=ENOENT ){
6039 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zPath);
6040 }else{
6041 sqlite3_snprintf(nOut, zOut, "%s", zIn);
6042 nByte = sqlite3Strlen30(zOut);
6043 }
6044 bLink = 0;
6045 }else if( ++nLink>SQLITE_MAX_SYMLINKS ){
6046 sqlite3_log(SQLITE_CANTOPEN,
6047 "too many symbolic links (max=%d)", SQLITE_MAX_SYMLINKS
6048 );
6049 rc = SQLITE_CANTOPEN_BKPT;
6050 }else{
6051 zOut[nByte] = '\0';
6052 if( zOut[0]!='/' ){
6053 int n;
6054 for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
6055 if( nByte+n+1>nOut ){
6056 rc = SQLITE_CANTOPEN_BKPT;
6057 }else{
6058 memmove(&zOut[n], zOut, nByte+1);
6059 memcpy(zOut, zIn, n);
6060 nByte += n;
6061 }
6062 }
6063 if( zDel==0 ){
6064 zDel = sqlite3_malloc(nOut);
6065 if( zDel==0 ) rc = SQLITE_NOMEM;
6066 zIn = (const char*)zDel;
6067 }
6068 bLink = 1;
6069 }
6070
6071 if( rc==SQLITE_OK ){
6072 rc = mkFullPathname(zPath, zOut, nByte, nOut);
6073 }
6074 }while( bLink && rc==SQLITE_OK );
6075
6076 sqlite3_free(zDel);
6077 return rc;
6078#endif /* HAVE_READLINK */
6079}
6080
drh0ccebe72005-06-07 22:22:50 +00006081
drh761df872006-12-21 01:29:22 +00006082#ifndef SQLITE_OMIT_LOAD_EXTENSION
6083/*
6084** Interfaces for opening a shared library, finding entry points
6085** within the shared library, and closing the shared library.
6086*/
6087#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00006088static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6089 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00006090 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6091}
danielk197795c8a542007-09-01 06:51:27 +00006092
6093/*
6094** SQLite calls this function immediately after a call to unixDlSym() or
6095** unixDlOpen() fails (returns a null pointer). If a more detailed error
6096** message is available, it is written to zBufOut. If no error message
6097** is available, zBufOut is left unmodified and SQLite uses a default
6098** error message.
6099*/
danielk1977397d65f2008-11-19 11:35:39 +00006100static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006101 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006102 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006103 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006104 zErr = dlerror();
6105 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006106 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006107 }
drh6c7d5c52008-11-21 20:32:33 +00006108 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006109}
drh1875f7a2008-12-08 18:19:17 +00006110static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6111 /*
6112 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6113 ** cast into a pointer to a function. And yet the library dlsym() routine
6114 ** returns a void* which is really a pointer to a function. So how do we
6115 ** use dlsym() with -pedantic-errors?
6116 **
6117 ** Variable x below is defined to be a pointer to a function taking
6118 ** parameters void* and const char* and returning a pointer to a function.
6119 ** We initialize x by assigning it a pointer to the dlsym() function.
6120 ** (That assignment requires a cast.) Then we call the function that
6121 ** x points to.
6122 **
6123 ** This work-around is unlikely to work correctly on any system where
6124 ** you really cannot cast a function pointer into void*. But then, on the
6125 ** other hand, dlsym() will not work on such a system either, so we have
6126 ** not really lost anything.
6127 */
6128 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006129 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006130 x = (void(*(*)(void*,const char*))(void))dlsym;
6131 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006132}
danielk1977397d65f2008-11-19 11:35:39 +00006133static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6134 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006135 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006136}
danielk1977b4b47412007-08-17 15:53:36 +00006137#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6138 #define unixDlOpen 0
6139 #define unixDlError 0
6140 #define unixDlSym 0
6141 #define unixDlClose 0
6142#endif
6143
6144/*
danielk197790949c22007-08-17 16:50:38 +00006145** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006146*/
danielk1977397d65f2008-11-19 11:35:39 +00006147static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6148 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006149 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006150
drhbbd42a62004-05-22 17:41:58 +00006151 /* We have to initialize zBuf to prevent valgrind from reporting
6152 ** errors. The reports issued by valgrind are incorrect - we would
6153 ** prefer that the randomness be increased by making use of the
6154 ** uninitialized space in zBuf - but valgrind errors tend to worry
6155 ** some users. Rather than argue, it seems easier just to initialize
6156 ** the whole array and silence valgrind, even if that means less randomness
6157 ** in the random seed.
6158 **
6159 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006160 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006161 ** tests repeatable.
6162 */
danielk1977b4b47412007-08-17 15:53:36 +00006163 memset(zBuf, 0, nBuf);
drh5ac93652015-03-21 20:59:43 +00006164 randomnessPid = osGetpid(0);
drh6a412b82015-04-30 12:31:49 +00006165#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
drhbbd42a62004-05-22 17:41:58 +00006166 {
drhb00d8622014-01-01 15:18:36 +00006167 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006168 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006169 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006170 time_t t;
6171 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006172 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006173 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6174 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6175 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006176 }else{
drhc18b4042012-02-10 03:10:27 +00006177 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006178 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006179 }
drhbbd42a62004-05-22 17:41:58 +00006180 }
6181#endif
drh72cbd072008-10-14 17:58:38 +00006182 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006183}
6184
danielk1977b4b47412007-08-17 15:53:36 +00006185
drhbbd42a62004-05-22 17:41:58 +00006186/*
6187** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006188** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006189** The return value is the number of microseconds of sleep actually
6190** requested from the underlying operating system, a number which
6191** might be greater than or equal to the argument, but not less
6192** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006193*/
danielk1977397d65f2008-11-19 11:35:39 +00006194static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006195#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006196 struct timespec sp;
6197
6198 sp.tv_sec = microseconds / 1000000;
6199 sp.tv_nsec = (microseconds % 1000000) * 1000;
6200 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006201 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006202 return microseconds;
6203#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006204 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006205 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006206 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006207#else
danielk1977b4b47412007-08-17 15:53:36 +00006208 int seconds = (microseconds+999999)/1000000;
6209 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006210 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006211 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006212#endif
drh88f474a2006-01-02 20:00:12 +00006213}
6214
6215/*
drh6b9d6dd2008-12-03 19:34:47 +00006216** The following variable, if set to a non-zero value, is interpreted as
6217** the number of seconds since 1970 and is used to set the result of
6218** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006219*/
6220#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006221int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006222#endif
6223
6224/*
drhb7e8ea22010-05-03 14:32:30 +00006225** Find the current time (in Universal Coordinated Time). Write into *piNow
6226** the current time and date as a Julian Day number times 86_400_000. In
6227** other words, write into *piNow the number of milliseconds since the Julian
6228** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6229** proleptic Gregorian calendar.
6230**
drh31702252011-10-12 23:13:43 +00006231** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6232** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006233*/
6234static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6235 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006236 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006237#if defined(NO_GETTOD)
6238 time_t t;
6239 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006240 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006241#elif OS_VXWORKS
6242 struct timespec sNow;
6243 clock_gettime(CLOCK_REALTIME, &sNow);
6244 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6245#else
6246 struct timeval sNow;
drh970942e2015-11-25 23:13:14 +00006247 (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
6248 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
drhb7e8ea22010-05-03 14:32:30 +00006249#endif
6250
6251#ifdef SQLITE_TEST
6252 if( sqlite3_current_time ){
6253 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6254 }
6255#endif
6256 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006257 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006258}
6259
drhc3dfa5e2016-01-22 19:44:03 +00006260#ifndef SQLITE_OMIT_DEPRECATED
drhb7e8ea22010-05-03 14:32:30 +00006261/*
drhbbd42a62004-05-22 17:41:58 +00006262** Find the current time (in Universal Coordinated Time). Write the
6263** current time and date as a Julian Day number into *prNow and
6264** return 0. Return 1 if the time and date cannot be found.
6265*/
danielk1977397d65f2008-11-19 11:35:39 +00006266static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006267 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006268 int rc;
drhff828942010-06-26 21:34:06 +00006269 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006270 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006271 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006272 return rc;
drhbbd42a62004-05-22 17:41:58 +00006273}
drh5337dac2015-11-25 15:15:03 +00006274#else
6275# define unixCurrentTime 0
6276#endif
danielk1977b4b47412007-08-17 15:53:36 +00006277
drhc3dfa5e2016-01-22 19:44:03 +00006278#ifndef SQLITE_OMIT_DEPRECATED
drh6b9d6dd2008-12-03 19:34:47 +00006279/*
6280** We added the xGetLastError() method with the intention of providing
6281** better low-level error messages when operating-system problems come up
6282** during SQLite operation. But so far, none of that has been implemented
6283** in the core. So this routine is never called. For now, it is merely
6284** a place-holder.
6285*/
danielk1977397d65f2008-11-19 11:35:39 +00006286static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6287 UNUSED_PARAMETER(NotUsed);
6288 UNUSED_PARAMETER(NotUsed2);
6289 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00006290 return 0;
6291}
drh5337dac2015-11-25 15:15:03 +00006292#else
6293# define unixGetLastError 0
6294#endif
danielk1977bcb97fe2008-06-06 15:49:29 +00006295
drhf2424c52010-04-26 00:04:55 +00006296
6297/*
drh734c9862008-11-28 15:37:20 +00006298************************ End of sqlite3_vfs methods ***************************
6299******************************************************************************/
6300
drh715ff302008-12-03 22:32:44 +00006301/******************************************************************************
6302************************** Begin Proxy Locking ********************************
6303**
6304** Proxy locking is a "uber-locking-method" in this sense: It uses the
6305** other locking methods on secondary lock files. Proxy locking is a
6306** meta-layer over top of the primitive locking implemented above. For
6307** this reason, the division that implements of proxy locking is deferred
6308** until late in the file (here) after all of the other I/O methods have
6309** been defined - so that the primitive locking methods are available
6310** as services to help with the implementation of proxy locking.
6311**
6312****
6313**
6314** The default locking schemes in SQLite use byte-range locks on the
6315** database file to coordinate safe, concurrent access by multiple readers
6316** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6317** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6318** as POSIX read & write locks over fixed set of locations (via fsctl),
6319** on AFP and SMB only exclusive byte-range locks are available via fsctl
6320** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6321** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6322** address in the shared range is taken for a SHARED lock, the entire
6323** shared range is taken for an EXCLUSIVE lock):
6324**
drhf2f105d2012-08-20 15:53:54 +00006325** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006326** RESERVED_BYTE 0x40000001
6327** SHARED_RANGE 0x40000002 -> 0x40000200
6328**
6329** This works well on the local file system, but shows a nearly 100x
6330** slowdown in read performance on AFP because the AFP client disables
6331** the read cache when byte-range locks are present. Enabling the read
6332** cache exposes a cache coherency problem that is present on all OS X
6333** supported network file systems. NFS and AFP both observe the
6334** close-to-open semantics for ensuring cache coherency
6335** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6336** address the requirements for concurrent database access by multiple
6337** readers and writers
6338** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6339**
6340** To address the performance and cache coherency issues, proxy file locking
6341** changes the way database access is controlled by limiting access to a
6342** single host at a time and moving file locks off of the database file
6343** and onto a proxy file on the local file system.
6344**
6345**
6346** Using proxy locks
6347** -----------------
6348**
6349** C APIs
6350**
drh4bf66fd2015-02-19 02:43:02 +00006351** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
drh715ff302008-12-03 22:32:44 +00006352** <proxy_path> | ":auto:");
drh4bf66fd2015-02-19 02:43:02 +00006353** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6354** &<proxy_path>);
drh715ff302008-12-03 22:32:44 +00006355**
6356**
6357** SQL pragmas
6358**
6359** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6360** PRAGMA [database.]lock_proxy_file
6361**
6362** Specifying ":auto:" means that if there is a conch file with a matching
6363** host ID in it, the proxy path in the conch file will be used, otherwise
6364** a proxy path based on the user's temp dir
6365** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6366** actual proxy file name is generated from the name and path of the
6367** database file. For example:
6368**
6369** For database path "/Users/me/foo.db"
6370** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6371**
6372** Once a lock proxy is configured for a database connection, it can not
6373** be removed, however it may be switched to a different proxy path via
6374** the above APIs (assuming the conch file is not being held by another
6375** connection or process).
6376**
6377**
6378** How proxy locking works
6379** -----------------------
6380**
6381** Proxy file locking relies primarily on two new supporting files:
6382**
6383** * conch file to limit access to the database file to a single host
6384** at a time
6385**
6386** * proxy file to act as a proxy for the advisory locks normally
6387** taken on the database
6388**
6389** The conch file - to use a proxy file, sqlite must first "hold the conch"
6390** by taking an sqlite-style shared lock on the conch file, reading the
6391** contents and comparing the host's unique host ID (see below) and lock
6392** proxy path against the values stored in the conch. The conch file is
6393** stored in the same directory as the database file and the file name
6394** is patterned after the database file name as ".<databasename>-conch".
peter.d.reid60ec9142014-09-06 16:39:46 +00006395** If the conch file does not exist, or its contents do not match the
drh715ff302008-12-03 22:32:44 +00006396** host ID and/or proxy path, then the lock is escalated to an exclusive
6397** lock and the conch file contents is updated with the host ID and proxy
6398** path and the lock is downgraded to a shared lock again. If the conch
6399** is held by another process (with a shared lock), the exclusive lock
6400** will fail and SQLITE_BUSY is returned.
6401**
6402** The proxy file - a single-byte file used for all advisory file locks
6403** normally taken on the database file. This allows for safe sharing
6404** of the database file for multiple readers and writers on the same
6405** host (the conch ensures that they all use the same local lock file).
6406**
drh715ff302008-12-03 22:32:44 +00006407** Requesting the lock proxy does not immediately take the conch, it is
6408** only taken when the first request to lock database file is made.
6409** This matches the semantics of the traditional locking behavior, where
6410** opening a connection to a database file does not take a lock on it.
6411** The shared lock and an open file descriptor are maintained until
6412** the connection to the database is closed.
6413**
6414** The proxy file and the lock file are never deleted so they only need
6415** to be created the first time they are used.
6416**
6417** Configuration options
6418** ---------------------
6419**
6420** SQLITE_PREFER_PROXY_LOCKING
6421**
6422** Database files accessed on non-local file systems are
6423** automatically configured for proxy locking, lock files are
6424** named automatically using the same logic as
6425** PRAGMA lock_proxy_file=":auto:"
6426**
6427** SQLITE_PROXY_DEBUG
6428**
6429** Enables the logging of error messages during host id file
6430** retrieval and creation
6431**
drh715ff302008-12-03 22:32:44 +00006432** LOCKPROXYDIR
6433**
6434** Overrides the default directory used for lock proxy files that
6435** are named automatically via the ":auto:" setting
6436**
6437** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6438**
6439** Permissions to use when creating a directory for storing the
6440** lock proxy files, only used when LOCKPROXYDIR is not set.
6441**
6442**
6443** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6444** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6445** force proxy locking to be used for every database file opened, and 0
6446** will force automatic proxy locking to be disabled for all database
drh4bf66fd2015-02-19 02:43:02 +00006447** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
drh715ff302008-12-03 22:32:44 +00006448** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6449*/
6450
6451/*
6452** Proxy locking is only available on MacOSX
6453*/
drhd2cb50b2009-01-09 21:41:17 +00006454#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006455
drh715ff302008-12-03 22:32:44 +00006456/*
6457** The proxyLockingContext has the path and file structures for the remote
6458** and local proxy files in it
6459*/
6460typedef struct proxyLockingContext proxyLockingContext;
6461struct proxyLockingContext {
6462 unixFile *conchFile; /* Open conch file */
6463 char *conchFilePath; /* Name of the conch file */
6464 unixFile *lockProxy; /* Open proxy lock file */
6465 char *lockProxyPath; /* Name of the proxy lock file */
6466 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006467 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh4bf66fd2015-02-19 02:43:02 +00006468 int nFails; /* Number of conch taking failures */
drh715ff302008-12-03 22:32:44 +00006469 void *oldLockingContext; /* Original lockingcontext to restore on close */
6470 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6471};
6472
drh7ed97b92010-01-20 13:07:21 +00006473/*
6474** The proxy lock file path for the database at dbPath is written into lPath,
6475** which must point to valid, writable memory large enough for a maxLen length
6476** file path.
drh715ff302008-12-03 22:32:44 +00006477*/
drh715ff302008-12-03 22:32:44 +00006478static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6479 int len;
6480 int dbLen;
6481 int i;
6482
6483#ifdef LOCKPROXYDIR
6484 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6485#else
6486# ifdef _CS_DARWIN_USER_TEMP_DIR
6487 {
drh7ed97b92010-01-20 13:07:21 +00006488 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006489 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006490 lPath, errno, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006491 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006492 }
drh7ed97b92010-01-20 13:07:21 +00006493 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006494 }
6495# else
6496 len = strlcpy(lPath, "/tmp/", maxLen);
6497# endif
6498#endif
6499
6500 if( lPath[len-1]!='/' ){
6501 len = strlcat(lPath, "/", maxLen);
6502 }
6503
6504 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006505 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006506 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006507 char c = dbPath[i];
6508 lPath[i+len] = (c=='/')?'_':c;
6509 }
6510 lPath[i+len]='\0';
6511 strlcat(lPath, ":auto:", maxLen);
drh5ac93652015-03-21 20:59:43 +00006512 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006513 return SQLITE_OK;
6514}
6515
drh7ed97b92010-01-20 13:07:21 +00006516/*
6517 ** Creates the lock file and any missing directories in lockPath
6518 */
6519static int proxyCreateLockPath(const char *lockPath){
6520 int i, len;
6521 char buf[MAXPATHLEN];
6522 int start = 0;
6523
6524 assert(lockPath!=NULL);
6525 /* try to create all the intermediate directories */
6526 len = (int)strlen(lockPath);
6527 buf[0] = lockPath[0];
6528 for( i=1; i<len; i++ ){
6529 if( lockPath[i] == '/' && (i - start > 0) ){
6530 /* only mkdir if leaf dir != "." or "/" or ".." */
6531 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6532 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6533 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006534 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006535 int err=errno;
6536 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006537 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006538 "'%s' proxy lock path=%s pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006539 buf, strerror(err), lockPath, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006540 return err;
6541 }
6542 }
6543 }
6544 start=i+1;
6545 }
6546 buf[i] = lockPath[i];
6547 }
drh62aaa6c2015-11-21 17:27:42 +00006548 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006549 return 0;
6550}
6551
drh715ff302008-12-03 22:32:44 +00006552/*
6553** Create a new VFS file descriptor (stored in memory obtained from
6554** sqlite3_malloc) and open the file named "path" in the file descriptor.
6555**
6556** The caller is responsible not only for closing the file descriptor
6557** but also for freeing the memory associated with the file descriptor.
6558*/
drh7ed97b92010-01-20 13:07:21 +00006559static int proxyCreateUnixFile(
6560 const char *path, /* path for the new unixFile */
6561 unixFile **ppFile, /* unixFile created and returned by ref */
6562 int islockfile /* if non zero missing dirs will be created */
6563) {
6564 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006565 unixFile *pNew;
6566 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006567 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006568 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006569 int terrno = 0;
6570 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006571
drh7ed97b92010-01-20 13:07:21 +00006572 /* 1. first try to open/create the file
6573 ** 2. if that fails, and this is a lock file (not-conch), try creating
6574 ** the parent directories and then try again.
6575 ** 3. if that fails, try to open the file read-only
6576 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6577 */
6578 pUnused = findReusableFd(path, openFlags);
6579 if( pUnused ){
6580 fd = pUnused->fd;
6581 }else{
drhf3cdcdc2015-04-29 16:50:28 +00006582 pUnused = sqlite3_malloc64(sizeof(*pUnused));
drh7ed97b92010-01-20 13:07:21 +00006583 if( !pUnused ){
6584 return SQLITE_NOMEM;
6585 }
6586 }
6587 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006588 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006589 terrno = errno;
6590 if( fd<0 && errno==ENOENT && islockfile ){
6591 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006592 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006593 }
6594 }
6595 }
6596 if( fd<0 ){
6597 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006598 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006599 terrno = errno;
6600 }
6601 if( fd<0 ){
6602 if( islockfile ){
6603 return SQLITE_BUSY;
6604 }
6605 switch (terrno) {
6606 case EACCES:
6607 return SQLITE_PERM;
6608 case EIO:
6609 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6610 default:
drh9978c972010-02-23 17:36:32 +00006611 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006612 }
6613 }
6614
drhf3cdcdc2015-04-29 16:50:28 +00006615 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
drh7ed97b92010-01-20 13:07:21 +00006616 if( pNew==NULL ){
6617 rc = SQLITE_NOMEM;
6618 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006619 }
6620 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006621 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006622 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006623 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006624 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006625 pUnused->fd = fd;
6626 pUnused->flags = openFlags;
6627 pNew->pUnused = pUnused;
6628
drhc02a43a2012-01-10 23:18:38 +00006629 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006630 if( rc==SQLITE_OK ){
6631 *ppFile = pNew;
6632 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006633 }
drh7ed97b92010-01-20 13:07:21 +00006634end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006635 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006636 sqlite3_free(pNew);
6637 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006638 return rc;
6639}
6640
drh7ed97b92010-01-20 13:07:21 +00006641#ifdef SQLITE_TEST
6642/* simulate multiple hosts by creating unique hostid file paths */
6643int sqlite3_hostid_num = 0;
6644#endif
6645
6646#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6647
drh6bca6512015-04-13 23:05:28 +00006648#ifdef HAVE_GETHOSTUUID
drh0ab216a2010-07-02 17:10:40 +00006649/* Not always defined in the headers as it ought to be */
6650extern int gethostuuid(uuid_t id, const struct timespec *wait);
drh6bca6512015-04-13 23:05:28 +00006651#endif
drh0ab216a2010-07-02 17:10:40 +00006652
drh7ed97b92010-01-20 13:07:21 +00006653/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6654** bytes of writable memory.
6655*/
6656static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006657 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6658 memset(pHostID, 0, PROXY_HOSTIDLEN);
drh6bca6512015-04-13 23:05:28 +00006659#ifdef HAVE_GETHOSTUUID
drh29ecd8a2010-12-21 00:16:40 +00006660 {
drh4bf66fd2015-02-19 02:43:02 +00006661 struct timespec timeout = {1, 0}; /* 1 sec timeout */
drh29ecd8a2010-12-21 00:16:40 +00006662 if( gethostuuid(pHostID, &timeout) ){
6663 int err = errno;
6664 if( pError ){
6665 *pError = err;
6666 }
6667 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006668 }
drh7ed97b92010-01-20 13:07:21 +00006669 }
drh3d4435b2011-08-26 20:55:50 +00006670#else
6671 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006672#endif
drh7ed97b92010-01-20 13:07:21 +00006673#ifdef SQLITE_TEST
6674 /* simulate multiple hosts by creating unique hostid file paths */
6675 if( sqlite3_hostid_num != 0){
6676 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6677 }
6678#endif
6679
6680 return SQLITE_OK;
6681}
6682
6683/* The conch file contains the header, host id and lock file path
6684 */
6685#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6686#define PROXY_HEADERLEN 1 /* conch file header length */
6687#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6688#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6689
6690/*
6691** Takes an open conch file, copies the contents to a new path and then moves
6692** it back. The newly created file's file descriptor is assigned to the
6693** conch file structure and finally the original conch file descriptor is
6694** closed. Returns zero if successful.
6695*/
6696static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6697 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6698 unixFile *conchFile = pCtx->conchFile;
6699 char tPath[MAXPATHLEN];
6700 char buf[PROXY_MAXCONCHLEN];
6701 char *cPath = pCtx->conchFilePath;
6702 size_t readLen = 0;
6703 size_t pathLen = 0;
6704 char errmsg[64] = "";
6705 int fd = -1;
6706 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006707 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006708
6709 /* create a new path by replace the trailing '-conch' with '-break' */
6710 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6711 if( pathLen>MAXPATHLEN || pathLen<6 ||
6712 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006713 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006714 goto end_breaklock;
6715 }
6716 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006717 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006718 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006719 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006720 goto end_breaklock;
6721 }
6722 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006723 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006724 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006725 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006726 goto end_breaklock;
6727 }
drhe562be52011-03-02 18:01:10 +00006728 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006729 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006730 goto end_breaklock;
6731 }
6732 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006733 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006734 goto end_breaklock;
6735 }
6736 rc = 0;
6737 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006738 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006739 conchFile->h = fd;
6740 conchFile->openFlags = O_RDWR | O_CREAT;
6741
6742end_breaklock:
6743 if( rc ){
6744 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006745 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006746 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006747 }
6748 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6749 }
6750 return rc;
6751}
6752
6753/* Take the requested lock on the conch file and break a stale lock if the
6754** host id matches.
6755*/
6756static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6757 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6758 unixFile *conchFile = pCtx->conchFile;
6759 int rc = SQLITE_OK;
6760 int nTries = 0;
6761 struct timespec conchModTime;
6762
drh3d4435b2011-08-26 20:55:50 +00006763 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006764 do {
6765 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6766 nTries ++;
6767 if( rc==SQLITE_BUSY ){
6768 /* If the lock failed (busy):
6769 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6770 * 2nd try: fail if the mod time changed or host id is different, wait
6771 * 10 sec and try again
6772 * 3rd try: break the lock unless the mod time has changed.
6773 */
6774 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006775 if( osFstat(conchFile->h, &buf) ){
drh4bf66fd2015-02-19 02:43:02 +00006776 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006777 return SQLITE_IOERR_LOCK;
6778 }
6779
6780 if( nTries==1 ){
6781 conchModTime = buf.st_mtimespec;
6782 usleep(500000); /* wait 0.5 sec and try the lock again*/
6783 continue;
6784 }
6785
6786 assert( nTries>1 );
6787 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6788 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6789 return SQLITE_BUSY;
6790 }
6791
6792 if( nTries==2 ){
6793 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006794 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006795 if( len<0 ){
drh4bf66fd2015-02-19 02:43:02 +00006796 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006797 return SQLITE_IOERR_LOCK;
6798 }
6799 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6800 /* don't break the lock if the host id doesn't match */
6801 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6802 return SQLITE_BUSY;
6803 }
6804 }else{
6805 /* don't break the lock on short read or a version mismatch */
6806 return SQLITE_BUSY;
6807 }
6808 usleep(10000000); /* wait 10 sec and try the lock again */
6809 continue;
6810 }
6811
6812 assert( nTries==3 );
6813 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6814 rc = SQLITE_OK;
6815 if( lockType==EXCLUSIVE_LOCK ){
drhe6d41732015-02-21 00:49:00 +00006816 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
drh7ed97b92010-01-20 13:07:21 +00006817 }
6818 if( !rc ){
6819 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6820 }
6821 }
6822 }
6823 } while( rc==SQLITE_BUSY && nTries<3 );
6824
6825 return rc;
6826}
6827
6828/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006829** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6830** lockPath means that the lockPath in the conch file will be used if the
6831** host IDs match, or a new lock path will be generated automatically
6832** and written to the conch file.
6833*/
6834static int proxyTakeConch(unixFile *pFile){
6835 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6836
drh7ed97b92010-01-20 13:07:21 +00006837 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006838 return SQLITE_OK;
6839 }else{
6840 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006841 uuid_t myHostID;
6842 int pError = 0;
6843 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006844 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006845 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006846 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006847 int createConch = 0;
6848 int hostIdMatch = 0;
6849 int readLen = 0;
6850 int tryOldLockPath = 0;
6851 int forceNewLockPath = 0;
6852
drh308c2a52010-05-14 11:30:18 +00006853 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
drh91eb93c2015-03-03 19:56:20 +00006854 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00006855 osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006856
drh7ed97b92010-01-20 13:07:21 +00006857 rc = proxyGetHostID(myHostID, &pError);
6858 if( (rc&0xff)==SQLITE_IOERR ){
drh4bf66fd2015-02-19 02:43:02 +00006859 storeLastErrno(pFile, pError);
drh7ed97b92010-01-20 13:07:21 +00006860 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006861 }
drh7ed97b92010-01-20 13:07:21 +00006862 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006863 if( rc!=SQLITE_OK ){
6864 goto end_takeconch;
6865 }
drh7ed97b92010-01-20 13:07:21 +00006866 /* read the existing conch file */
6867 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6868 if( readLen<0 ){
6869 /* I/O error: lastErrno set by seekAndRead */
drh4bf66fd2015-02-19 02:43:02 +00006870 storeLastErrno(pFile, conchFile->lastErrno);
drh7ed97b92010-01-20 13:07:21 +00006871 rc = SQLITE_IOERR_READ;
6872 goto end_takeconch;
6873 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6874 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6875 /* a short read or version format mismatch means we need to create a new
6876 ** conch file.
6877 */
6878 createConch = 1;
6879 }
6880 /* if the host id matches and the lock path already exists in the conch
6881 ** we'll try to use the path there, if we can't open that path, we'll
6882 ** retry with a new auto-generated path
6883 */
6884 do { /* in case we need to try again for an :auto: named lock file */
6885
6886 if( !createConch && !forceNewLockPath ){
6887 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6888 PROXY_HOSTIDLEN);
6889 /* if the conch has data compare the contents */
6890 if( !pCtx->lockProxyPath ){
6891 /* for auto-named local lock file, just check the host ID and we'll
6892 ** use the local lock file path that's already in there
6893 */
6894 if( hostIdMatch ){
6895 size_t pathLen = (readLen - PROXY_PATHINDEX);
6896
6897 if( pathLen>=MAXPATHLEN ){
6898 pathLen=MAXPATHLEN-1;
6899 }
6900 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6901 lockPath[pathLen] = 0;
6902 tempLockPath = lockPath;
6903 tryOldLockPath = 1;
6904 /* create a copy of the lock path if the conch is taken */
6905 goto end_takeconch;
6906 }
6907 }else if( hostIdMatch
6908 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6909 readLen-PROXY_PATHINDEX)
6910 ){
6911 /* conch host and lock path match */
6912 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006913 }
drh7ed97b92010-01-20 13:07:21 +00006914 }
6915
6916 /* if the conch isn't writable and doesn't match, we can't take it */
6917 if( (conchFile->openFlags&O_RDWR) == 0 ){
6918 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006919 goto end_takeconch;
6920 }
drh7ed97b92010-01-20 13:07:21 +00006921
6922 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006923 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006924 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6925 tempLockPath = lockPath;
6926 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006927 }
drh7ed97b92010-01-20 13:07:21 +00006928
6929 /* update conch with host and path (this will fail if other process
6930 ** has a shared lock already), if the host id matches, use the big
6931 ** stick.
drh715ff302008-12-03 22:32:44 +00006932 */
drh7ed97b92010-01-20 13:07:21 +00006933 futimes(conchFile->h, NULL);
6934 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006935 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006936 /* We are trying for an exclusive lock but another thread in this
6937 ** same process is still holding a shared lock. */
6938 rc = SQLITE_BUSY;
6939 } else {
6940 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006941 }
drh715ff302008-12-03 22:32:44 +00006942 }else{
drh4bf66fd2015-02-19 02:43:02 +00006943 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006944 }
drh7ed97b92010-01-20 13:07:21 +00006945 if( rc==SQLITE_OK ){
6946 char writeBuffer[PROXY_MAXCONCHLEN];
6947 int writeSize = 0;
6948
6949 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6950 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6951 if( pCtx->lockProxyPath!=NULL ){
drh4bf66fd2015-02-19 02:43:02 +00006952 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
6953 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00006954 }else{
6955 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6956 }
6957 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006958 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006959 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6960 fsync(conchFile->h);
6961 /* If we created a new conch file (not just updated the contents of a
6962 ** valid conch file), try to match the permissions of the database
6963 */
6964 if( rc==SQLITE_OK && createConch ){
6965 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006966 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006967 if( err==0 ){
6968 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6969 S_IROTH|S_IWOTH);
6970 /* try to match the database file R/W permissions, ignore failure */
6971#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006972 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006973#else
drhff812312011-02-23 13:33:46 +00006974 do{
drhe562be52011-03-02 18:01:10 +00006975 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006976 }while( rc==(-1) && errno==EINTR );
6977 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006978 int code = errno;
6979 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6980 cmode, code, strerror(code));
6981 } else {
6982 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6983 }
6984 }else{
6985 int code = errno;
6986 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6987 err, code, strerror(code));
6988#endif
6989 }
drh715ff302008-12-03 22:32:44 +00006990 }
6991 }
drh7ed97b92010-01-20 13:07:21 +00006992 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6993
6994 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006995 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006996 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006997 int fd;
drh7ed97b92010-01-20 13:07:21 +00006998 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006999 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00007000 }
7001 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00007002 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00007003 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00007004 if( fd>=0 ){
7005 pFile->h = fd;
7006 }else{
drh9978c972010-02-23 17:36:32 +00007007 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00007008 during locking */
7009 }
7010 }
7011 if( rc==SQLITE_OK && !pCtx->lockProxy ){
7012 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
7013 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
7014 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
7015 /* we couldn't create the proxy lock file with the old lock file path
7016 ** so try again via auto-naming
7017 */
7018 forceNewLockPath = 1;
7019 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00007020 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00007021 }
7022 }
7023 if( rc==SQLITE_OK ){
7024 /* Need to make a copy of path if we extracted the value
7025 ** from the conch file or the path was allocated on the stack
7026 */
7027 if( tempLockPath ){
7028 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
7029 if( !pCtx->lockProxyPath ){
7030 rc = SQLITE_NOMEM;
7031 }
7032 }
7033 }
7034 if( rc==SQLITE_OK ){
7035 pCtx->conchHeld = 1;
7036
7037 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
7038 afpLockingContext *afpCtx;
7039 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
7040 afpCtx->dbPath = pCtx->lockProxyPath;
7041 }
7042 } else {
7043 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7044 }
drh308c2a52010-05-14 11:30:18 +00007045 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
7046 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00007047 return rc;
drh308c2a52010-05-14 11:30:18 +00007048 } while (1); /* in case we need to retry the :auto: lock file -
7049 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00007050 }
7051}
7052
7053/*
7054** If pFile holds a lock on a conch file, then release that lock.
7055*/
7056static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00007057 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00007058 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
7059 unixFile *conchFile; /* Name of the conch file */
7060
7061 pCtx = (proxyLockingContext *)pFile->lockingContext;
7062 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00007063 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00007064 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00007065 osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00007066 if( pCtx->conchHeld>0 ){
7067 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7068 }
drh715ff302008-12-03 22:32:44 +00007069 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00007070 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
7071 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007072 return rc;
7073}
7074
7075/*
7076** Given the name of a database file, compute the name of its conch file.
drhf3cdcdc2015-04-29 16:50:28 +00007077** Store the conch filename in memory obtained from sqlite3_malloc64().
drh715ff302008-12-03 22:32:44 +00007078** Make *pConchPath point to the new name. Return SQLITE_OK on success
7079** or SQLITE_NOMEM if unable to obtain memory.
7080**
7081** The caller is responsible for ensuring that the allocated memory
7082** space is eventually freed.
7083**
7084** *pConchPath is set to NULL if a memory allocation error occurs.
7085*/
7086static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7087 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00007088 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00007089 char *conchPath; /* buffer in which to construct conch name */
7090
7091 /* Allocate space for the conch filename and initialize the name to
7092 ** the name of the original database file. */
drhf3cdcdc2015-04-29 16:50:28 +00007093 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
drh715ff302008-12-03 22:32:44 +00007094 if( conchPath==0 ){
7095 return SQLITE_NOMEM;
7096 }
7097 memcpy(conchPath, dbPath, len+1);
7098
7099 /* now insert a "." before the last / character */
7100 for( i=(len-1); i>=0; i-- ){
7101 if( conchPath[i]=='/' ){
7102 i++;
7103 break;
7104 }
7105 }
7106 conchPath[i]='.';
7107 while ( i<len ){
7108 conchPath[i+1]=dbPath[i];
7109 i++;
7110 }
7111
7112 /* append the "-conch" suffix to the file */
7113 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007114 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007115
7116 return SQLITE_OK;
7117}
7118
7119
7120/* Takes a fully configured proxy locking-style unix file and switches
7121** the local lock file path
7122*/
7123static int switchLockProxyPath(unixFile *pFile, const char *path) {
7124 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7125 char *oldPath = pCtx->lockProxyPath;
7126 int rc = SQLITE_OK;
7127
drh308c2a52010-05-14 11:30:18 +00007128 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007129 return SQLITE_BUSY;
7130 }
7131
7132 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7133 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7134 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7135 return SQLITE_OK;
7136 }else{
7137 unixFile *lockProxy = pCtx->lockProxy;
7138 pCtx->lockProxy=NULL;
7139 pCtx->conchHeld = 0;
7140 if( lockProxy!=NULL ){
7141 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7142 if( rc ) return rc;
7143 sqlite3_free(lockProxy);
7144 }
7145 sqlite3_free(oldPath);
7146 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7147 }
7148
7149 return rc;
7150}
7151
7152/*
7153** pFile is a file that has been opened by a prior xOpen call. dbPath
7154** is a string buffer at least MAXPATHLEN+1 characters in size.
7155**
7156** This routine find the filename associated with pFile and writes it
7157** int dbPath.
7158*/
7159static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007160#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007161 if( pFile->pMethod == &afpIoMethods ){
7162 /* afp style keeps a reference to the db path in the filePath field
7163 ** of the struct */
drhea678832008-12-10 19:26:22 +00007164 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh4bf66fd2015-02-19 02:43:02 +00007165 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7166 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007167 } else
drh715ff302008-12-03 22:32:44 +00007168#endif
7169 if( pFile->pMethod == &dotlockIoMethods ){
7170 /* dot lock style uses the locking context to store the dot lock
7171 ** file path */
7172 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7173 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7174 }else{
7175 /* all other styles use the locking context to store the db file path */
7176 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007177 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007178 }
7179 return SQLITE_OK;
7180}
7181
7182/*
7183** Takes an already filled in unix file and alters it so all file locking
7184** will be performed on the local proxy lock file. The following fields
7185** are preserved in the locking context so that they can be restored and
7186** the unix structure properly cleaned up at close time:
7187** ->lockingContext
7188** ->pMethod
7189*/
7190static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7191 proxyLockingContext *pCtx;
7192 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7193 char *lockPath=NULL;
7194 int rc = SQLITE_OK;
7195
drh308c2a52010-05-14 11:30:18 +00007196 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007197 return SQLITE_BUSY;
7198 }
7199 proxyGetDbPathForUnixFile(pFile, dbPath);
7200 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7201 lockPath=NULL;
7202 }else{
7203 lockPath=(char *)path;
7204 }
7205
drh308c2a52010-05-14 11:30:18 +00007206 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
drh5ac93652015-03-21 20:59:43 +00007207 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007208
drhf3cdcdc2015-04-29 16:50:28 +00007209 pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh715ff302008-12-03 22:32:44 +00007210 if( pCtx==0 ){
7211 return SQLITE_NOMEM;
7212 }
7213 memset(pCtx, 0, sizeof(*pCtx));
7214
7215 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7216 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007217 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7218 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7219 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7220 ** (c) the file system is read-only, then enable no-locking access.
7221 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7222 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7223 */
7224 struct statfs fsInfo;
7225 struct stat conchInfo;
7226 int goLockless = 0;
7227
drh99ab3b12011-03-02 15:09:07 +00007228 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007229 int err = errno;
7230 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7231 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7232 }
7233 }
7234 if( goLockless ){
7235 pCtx->conchHeld = -1; /* read only FS/ lockless */
7236 rc = SQLITE_OK;
7237 }
7238 }
drh715ff302008-12-03 22:32:44 +00007239 }
7240 if( rc==SQLITE_OK && lockPath ){
7241 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7242 }
7243
7244 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007245 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7246 if( pCtx->dbPath==NULL ){
7247 rc = SQLITE_NOMEM;
7248 }
7249 }
7250 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007251 /* all memory is allocated, proxys are created and assigned,
7252 ** switch the locking context and pMethod then return.
7253 */
drh715ff302008-12-03 22:32:44 +00007254 pCtx->oldLockingContext = pFile->lockingContext;
7255 pFile->lockingContext = pCtx;
7256 pCtx->pOldMethod = pFile->pMethod;
7257 pFile->pMethod = &proxyIoMethods;
7258 }else{
7259 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007260 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007261 sqlite3_free(pCtx->conchFile);
7262 }
drhd56b1212010-08-11 06:14:15 +00007263 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007264 sqlite3_free(pCtx->conchFilePath);
7265 sqlite3_free(pCtx);
7266 }
drh308c2a52010-05-14 11:30:18 +00007267 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7268 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007269 return rc;
7270}
7271
7272
7273/*
7274** This routine handles sqlite3_file_control() calls that are specific
7275** to proxy locking.
7276*/
7277static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7278 switch( op ){
drh4bf66fd2015-02-19 02:43:02 +00007279 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007280 unixFile *pFile = (unixFile*)id;
7281 if( pFile->pMethod == &proxyIoMethods ){
7282 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7283 proxyTakeConch(pFile);
7284 if( pCtx->lockProxyPath ){
7285 *(const char **)pArg = pCtx->lockProxyPath;
7286 }else{
7287 *(const char **)pArg = ":auto: (not held)";
7288 }
7289 } else {
7290 *(const char **)pArg = NULL;
7291 }
7292 return SQLITE_OK;
7293 }
drh4bf66fd2015-02-19 02:43:02 +00007294 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007295 unixFile *pFile = (unixFile*)id;
7296 int rc = SQLITE_OK;
7297 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7298 if( pArg==NULL || (const char *)pArg==0 ){
7299 if( isProxyStyle ){
drh4bf66fd2015-02-19 02:43:02 +00007300 /* turn off proxy locking - not supported. If support is added for
7301 ** switching proxy locking mode off then it will need to fail if
7302 ** the journal mode is WAL mode.
7303 */
drh715ff302008-12-03 22:32:44 +00007304 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7305 }else{
7306 /* turn off proxy locking - already off - NOOP */
7307 rc = SQLITE_OK;
7308 }
7309 }else{
7310 const char *proxyPath = (const char *)pArg;
7311 if( isProxyStyle ){
7312 proxyLockingContext *pCtx =
7313 (proxyLockingContext*)pFile->lockingContext;
7314 if( !strcmp(pArg, ":auto:")
7315 || (pCtx->lockProxyPath &&
7316 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7317 ){
7318 rc = SQLITE_OK;
7319 }else{
7320 rc = switchLockProxyPath(pFile, proxyPath);
7321 }
7322 }else{
7323 /* turn on proxy file locking */
7324 rc = proxyTransformUnixFile(pFile, proxyPath);
7325 }
7326 }
7327 return rc;
7328 }
7329 default: {
7330 assert( 0 ); /* The call assures that only valid opcodes are sent */
7331 }
7332 }
7333 /*NOTREACHED*/
7334 return SQLITE_ERROR;
7335}
7336
7337/*
7338** Within this division (the proxying locking implementation) the procedures
7339** above this point are all utilities. The lock-related methods of the
7340** proxy-locking sqlite3_io_method object follow.
7341*/
7342
7343
7344/*
7345** This routine checks if there is a RESERVED lock held on the specified
7346** file by this or any other process. If such a lock is held, set *pResOut
7347** to a non-zero value otherwise *pResOut is set to zero. The return value
7348** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7349*/
7350static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7351 unixFile *pFile = (unixFile*)id;
7352 int rc = proxyTakeConch(pFile);
7353 if( rc==SQLITE_OK ){
7354 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007355 if( pCtx->conchHeld>0 ){
7356 unixFile *proxy = pCtx->lockProxy;
7357 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7358 }else{ /* conchHeld < 0 is lockless */
7359 pResOut=0;
7360 }
drh715ff302008-12-03 22:32:44 +00007361 }
7362 return rc;
7363}
7364
7365/*
drh308c2a52010-05-14 11:30:18 +00007366** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007367** of the following:
7368**
7369** (1) SHARED_LOCK
7370** (2) RESERVED_LOCK
7371** (3) PENDING_LOCK
7372** (4) EXCLUSIVE_LOCK
7373**
7374** Sometimes when requesting one lock state, additional lock states
7375** are inserted in between. The locking might fail on one of the later
7376** transitions leaving the lock state different from what it started but
7377** still short of its goal. The following chart shows the allowed
7378** transitions and the inserted intermediate states:
7379**
7380** UNLOCKED -> SHARED
7381** SHARED -> RESERVED
7382** SHARED -> (PENDING) -> EXCLUSIVE
7383** RESERVED -> (PENDING) -> EXCLUSIVE
7384** PENDING -> EXCLUSIVE
7385**
7386** This routine will only increase a lock. Use the sqlite3OsUnlock()
7387** routine to lower a locking level.
7388*/
drh308c2a52010-05-14 11:30:18 +00007389static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007390 unixFile *pFile = (unixFile*)id;
7391 int rc = proxyTakeConch(pFile);
7392 if( rc==SQLITE_OK ){
7393 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007394 if( pCtx->conchHeld>0 ){
7395 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007396 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7397 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007398 }else{
7399 /* conchHeld < 0 is lockless */
7400 }
drh715ff302008-12-03 22:32:44 +00007401 }
7402 return rc;
7403}
7404
7405
7406/*
drh308c2a52010-05-14 11:30:18 +00007407** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007408** must be either NO_LOCK or SHARED_LOCK.
7409**
7410** If the locking level of the file descriptor is already at or below
7411** the requested locking level, this routine is a no-op.
7412*/
drh308c2a52010-05-14 11:30:18 +00007413static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007414 unixFile *pFile = (unixFile*)id;
7415 int rc = proxyTakeConch(pFile);
7416 if( rc==SQLITE_OK ){
7417 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007418 if( pCtx->conchHeld>0 ){
7419 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007420 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7421 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007422 }else{
7423 /* conchHeld < 0 is lockless */
7424 }
drh715ff302008-12-03 22:32:44 +00007425 }
7426 return rc;
7427}
7428
7429/*
7430** Close a file that uses proxy locks.
7431*/
7432static int proxyClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00007433 if( ALWAYS(id) ){
drh715ff302008-12-03 22:32:44 +00007434 unixFile *pFile = (unixFile*)id;
7435 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7436 unixFile *lockProxy = pCtx->lockProxy;
7437 unixFile *conchFile = pCtx->conchFile;
7438 int rc = SQLITE_OK;
7439
7440 if( lockProxy ){
7441 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7442 if( rc ) return rc;
7443 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7444 if( rc ) return rc;
7445 sqlite3_free(lockProxy);
7446 pCtx->lockProxy = 0;
7447 }
7448 if( conchFile ){
7449 if( pCtx->conchHeld ){
7450 rc = proxyReleaseConch(pFile);
7451 if( rc ) return rc;
7452 }
7453 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7454 if( rc ) return rc;
7455 sqlite3_free(conchFile);
7456 }
drhd56b1212010-08-11 06:14:15 +00007457 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007458 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007459 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007460 /* restore the original locking context and pMethod then close it */
7461 pFile->lockingContext = pCtx->oldLockingContext;
7462 pFile->pMethod = pCtx->pOldMethod;
7463 sqlite3_free(pCtx);
7464 return pFile->pMethod->xClose(id);
7465 }
7466 return SQLITE_OK;
7467}
7468
7469
7470
drhd2cb50b2009-01-09 21:41:17 +00007471#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007472/*
7473** The proxy locking style is intended for use with AFP filesystems.
7474** And since AFP is only supported on MacOSX, the proxy locking is also
7475** restricted to MacOSX.
7476**
7477**
7478******************* End of the proxy lock implementation **********************
7479******************************************************************************/
7480
drh734c9862008-11-28 15:37:20 +00007481/*
danielk1977e339d652008-06-28 11:23:00 +00007482** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007483**
7484** This routine registers all VFS implementations for unix-like operating
7485** systems. This routine, and the sqlite3_os_end() routine that follows,
7486** should be the only routines in this file that are visible from other
7487** files.
drh6b9d6dd2008-12-03 19:34:47 +00007488**
7489** This routine is called once during SQLite initialization and by a
7490** single thread. The memory allocation and mutex subsystems have not
7491** necessarily been initialized when this routine is called, and so they
7492** should not be used.
drh153c62c2007-08-24 03:51:33 +00007493*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007494int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007495 /*
7496 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007497 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7498 ** to the "finder" function. (pAppData is a pointer to a pointer because
7499 ** silly C90 rules prohibit a void* from being cast to a function pointer
7500 ** and so we have to go through the intermediate pointer to avoid problems
7501 ** when compiling with -pedantic-errors on GCC.)
7502 **
7503 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007504 ** finder-function. The finder-function returns a pointer to the
7505 ** sqlite_io_methods object that implements the desired locking
7506 ** behaviors. See the division above that contains the IOMETHODS
7507 ** macro for addition information on finder-functions.
7508 **
7509 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7510 ** object. But the "autolockIoFinder" available on MacOSX does a little
7511 ** more than that; it looks at the filesystem type that hosts the
7512 ** database file and tries to choose an locking method appropriate for
7513 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007514 */
drh7708e972008-11-29 00:56:52 +00007515 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007516 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007517 sizeof(unixFile), /* szOsFile */ \
7518 MAX_PATHNAME, /* mxPathname */ \
7519 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007520 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007521 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007522 unixOpen, /* xOpen */ \
7523 unixDelete, /* xDelete */ \
7524 unixAccess, /* xAccess */ \
7525 unixFullPathname, /* xFullPathname */ \
7526 unixDlOpen, /* xDlOpen */ \
7527 unixDlError, /* xDlError */ \
7528 unixDlSym, /* xDlSym */ \
7529 unixDlClose, /* xDlClose */ \
7530 unixRandomness, /* xRandomness */ \
7531 unixSleep, /* xSleep */ \
7532 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007533 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007534 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007535 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007536 unixGetSystemCall, /* xGetSystemCall */ \
7537 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007538 }
7539
drh6b9d6dd2008-12-03 19:34:47 +00007540 /*
7541 ** All default VFSes for unix are contained in the following array.
7542 **
7543 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7544 ** by the SQLite core when the VFS is registered. So the following
7545 ** array cannot be const.
7546 */
danielk1977e339d652008-06-28 11:23:00 +00007547 static sqlite3_vfs aVfs[] = {
drhe89b2912015-03-03 20:42:01 +00007548#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007549 UNIXVFS("unix", autolockIoFinder ),
drhe89b2912015-03-03 20:42:01 +00007550#elif OS_VXWORKS
7551 UNIXVFS("unix", vxworksIoFinder ),
drh7708e972008-11-29 00:56:52 +00007552#else
7553 UNIXVFS("unix", posixIoFinder ),
7554#endif
7555 UNIXVFS("unix-none", nolockIoFinder ),
7556 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007557 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007558#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007559 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007560#endif
drhe89b2912015-03-03 20:42:01 +00007561#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007562 UNIXVFS("unix-posix", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007563#endif
drhe89b2912015-03-03 20:42:01 +00007564#if SQLITE_ENABLE_LOCKING_STYLE
7565 UNIXVFS("unix-flock", flockIoFinder ),
chw78a13182009-04-07 05:35:03 +00007566#endif
drhd2cb50b2009-01-09 21:41:17 +00007567#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007568 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007569 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007570 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007571#endif
drh153c62c2007-08-24 03:51:33 +00007572 };
drh6b9d6dd2008-12-03 19:34:47 +00007573 unsigned int i; /* Loop counter */
7574
drh2aa5a002011-04-13 13:42:25 +00007575 /* Double-check that the aSyscall[] array has been constructed
7576 ** correctly. See ticket [bb3a86e890c8e96ab] */
drh6226ca22015-11-24 15:06:28 +00007577 assert( ArraySize(aSyscall)==27 );
drh2aa5a002011-04-13 13:42:25 +00007578
drh6b9d6dd2008-12-03 19:34:47 +00007579 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007580 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007581 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007582 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007583 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007584}
danielk1977e339d652008-06-28 11:23:00 +00007585
7586/*
drh6b9d6dd2008-12-03 19:34:47 +00007587** Shutdown the operating system interface.
7588**
7589** Some operating systems might need to do some cleanup in this routine,
7590** to release dynamically allocated objects. But not on unix.
7591** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007592*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007593int sqlite3_os_end(void){
7594 return SQLITE_OK;
7595}
drhdce8bdb2007-08-16 13:01:44 +00007596
danielk197729bafea2008-06-26 10:41:19 +00007597#endif /* SQLITE_OS_UNIX */