blob: 768a2a9eec4ef6add0948ae58d468cf6106c36e7 [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
drh91eb93c2015-03-03 19:56:20 +0000152/* Always cast the getpid() return type for compatibility with
153** kernel modules in VxWorks. */
154#define osGetpid(X) (pid_t)getpid()
155
drh734c9862008-11-28 15:37:20 +0000156/*
drh734c9862008-11-28 15:37:20 +0000157** Only set the lastErrno if the error code is a real error and not
158** a normal expected return code of SQLITE_BUSY or SQLITE_OK
159*/
160#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
161
drhd91c68f2010-05-14 14:52:25 +0000162/* Forward references */
163typedef struct unixShm unixShm; /* Connection shared memory */
164typedef struct unixShmNode unixShmNode; /* Shared memory instance */
165typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
166typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000167
168/*
dane946c392009-08-22 11:39:46 +0000169** Sometimes, after a file handle is closed by SQLite, the file descriptor
170** cannot be closed immediately. In these cases, instances of the following
171** structure are used to store the file descriptor while waiting for an
172** opportunity to either close or reuse it.
173*/
dane946c392009-08-22 11:39:46 +0000174struct UnixUnusedFd {
175 int fd; /* File descriptor to close */
176 int flags; /* Flags this file descriptor was opened with */
177 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
178};
179
180/*
drh9b35ea62008-11-29 02:20:26 +0000181** The unixFile structure is subclass of sqlite3_file specific to the unix
182** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000183*/
drh054889e2005-11-30 03:20:31 +0000184typedef struct unixFile unixFile;
185struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000186 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhde60fc22011-12-14 17:53:36 +0000187 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
drhd91c68f2010-05-14 14:52:25 +0000188 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000189 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000190 unsigned char eFileLock; /* The type of lock held on this fd */
drh3ee34842012-02-11 21:21:17 +0000191 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000192 int lastErrno; /* The unix errno from last I/O error */
193 void *lockingContext; /* Locking style specific state */
194 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000195 const char *zPath; /* Name of the file */
196 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000197 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
mistachkine98844f2013-08-24 00:59:24 +0000198#if SQLITE_MAX_MMAP_SIZE>0
drh0d0614b2013-03-25 23:09:28 +0000199 int nFetchOut; /* Number of outstanding xFetch refs */
200 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
drh9b4c59f2013-04-15 17:03:42 +0000201 sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
202 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
drh0d0614b2013-03-25 23:09:28 +0000203 void *pMapRegion; /* Memory mapped region */
mistachkine98844f2013-08-24 00:59:24 +0000204#endif
drh537dddf2012-10-26 13:46:24 +0000205#ifdef __QNXNTO__
206 int sectorSize; /* Device sector size */
207 int deviceCharacteristics; /* Precomputed device characteristics */
208#endif
drh08c6d442009-02-09 17:34:07 +0000209#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000210 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000211#endif
drh7ed97b92010-01-20 13:07:21 +0000212#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000213 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000214#endif
215#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000216 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000217#endif
drhd3d8c042012-05-29 17:02:40 +0000218#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +0000219 /* The next group of variables are used to track whether or not the
220 ** transaction counter in bytes 24-27 of database files are updated
221 ** whenever any part of the database changes. An assertion fault will
222 ** occur if a file is updated without also updating the transaction
223 ** counter. This test is made to avoid new problems similar to the
224 ** one described by ticket #3584.
225 */
226 unsigned char transCntrChng; /* True if the transaction counter changed */
227 unsigned char dbUpdate; /* True if any part of database file changed */
228 unsigned char inNormalWrite; /* True if in a normal write operation */
danf23da962013-03-23 21:00:41 +0000229
drh8f941bc2009-01-14 23:03:40 +0000230#endif
danf23da962013-03-23 21:00:41 +0000231
danielk1977967a4a12007-08-20 14:23:44 +0000232#ifdef SQLITE_TEST
233 /* In test mode, increase the size of this structure a bit so that
234 ** it is larger than the struct CrashFile defined in test6.c.
235 */
236 char aPadding[32];
237#endif
drh9cbe6352005-11-29 03:13:21 +0000238};
239
drhb00d8622014-01-01 15:18:36 +0000240/* This variable holds the process id (pid) from when the xRandomness()
241** method was called. If xOpen() is called from a different process id,
242** indicating that a fork() has occurred, the PRNG will be reset.
243*/
drh8cd5b252015-03-02 22:06:43 +0000244static pid_t randomnessPid = 0;
drhb00d8622014-01-01 15:18:36 +0000245
drh0ccebe72005-06-07 22:22:50 +0000246/*
drha7e61d82011-03-12 17:02:57 +0000247** Allowed values for the unixFile.ctrlFlags bitmask:
248*/
drhf0b190d2011-07-26 16:03:07 +0000249#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
250#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
251#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000252#ifndef SQLITE_DISABLE_DIRSYNC
253# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
254#else
255# define UNIXFILE_DIRSYNC 0x00
256#endif
drhcb15f352011-12-23 01:04:17 +0000257#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
drhc02a43a2012-01-10 23:18:38 +0000258#define UNIXFILE_DELETE 0x20 /* Delete on close */
259#define UNIXFILE_URI 0x40 /* Filename might have query parameters */
260#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
drhe6d41732015-02-21 00:49:00 +0000261#define UNIXFILE_WARNED 0x0100 /* verifyDbFile() warnings issued */
drhbbf76ee2015-03-10 20:22:35 +0000262#define UNIXFILE_BLOCK 0x0200 /* Next SHM lock might block */
drha7e61d82011-03-12 17:02:57 +0000263
264/*
drh198bf392006-01-06 21:52:49 +0000265** Include code that is common to all os_*.c files
266*/
267#include "os_common.h"
268
269/*
drh0ccebe72005-06-07 22:22:50 +0000270** Define various macros that are missing from some systems.
271*/
drhbbd42a62004-05-22 17:41:58 +0000272#ifndef O_LARGEFILE
273# define O_LARGEFILE 0
274#endif
275#ifdef SQLITE_DISABLE_LFS
276# undef O_LARGEFILE
277# define O_LARGEFILE 0
278#endif
279#ifndef O_NOFOLLOW
280# define O_NOFOLLOW 0
281#endif
282#ifndef O_BINARY
283# define O_BINARY 0
284#endif
285
286/*
drh2b4b5962005-06-15 17:47:55 +0000287** The threadid macro resolves to the thread-id or to 0. Used for
288** testing and debugging only.
289*/
drhd677b3d2007-08-20 22:48:41 +0000290#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000291#define threadid pthread_self()
292#else
293#define threadid 0
294#endif
295
drh99ab3b12011-03-02 15:09:07 +0000296/*
dane6ecd662013-04-01 17:56:59 +0000297** HAVE_MREMAP defaults to true on Linux and false everywhere else.
298*/
299#if !defined(HAVE_MREMAP)
300# if defined(__linux__) && defined(_GNU_SOURCE)
301# define HAVE_MREMAP 1
302# else
303# define HAVE_MREMAP 0
304# endif
305#endif
306
307/*
dan2ee53412014-09-06 16:49:40 +0000308** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
309** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
310*/
311#ifdef __ANDROID__
312# define lseek lseek64
313#endif
314
315/*
drh9a3baf12011-04-25 18:01:27 +0000316** Different Unix systems declare open() in different ways. Same use
317** open(const char*,int,mode_t). Others use open(const char*,int,...).
318** The difference is important when using a pointer to the function.
319**
320** The safest way to deal with the problem is to always use this wrapper
321** which always has the same well-defined interface.
322*/
323static int posixOpen(const char *zFile, int flags, int mode){
324 return open(zFile, flags, mode);
325}
326
drh90315a22011-08-10 01:52:12 +0000327/* Forward reference */
328static int openDirectory(const char*, int*);
danbc760632014-03-20 09:42:09 +0000329static int unixGetpagesize(void);
drh90315a22011-08-10 01:52:12 +0000330
drh9a3baf12011-04-25 18:01:27 +0000331/*
drh99ab3b12011-03-02 15:09:07 +0000332** Many system calls are accessed through pointer-to-functions so that
333** they may be overridden at runtime to facilitate fault injection during
334** testing and sandboxing. The following array holds the names and pointers
335** to all overrideable system calls.
336*/
337static struct unix_syscall {
mistachkin48864df2013-03-21 21:20:32 +0000338 const char *zName; /* Name of the system call */
drh58ad5802011-03-23 22:02:23 +0000339 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
340 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000341} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000342 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
343#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000344
drh58ad5802011-03-23 22:02:23 +0000345 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000346#define osClose ((int(*)(int))aSyscall[1].pCurrent)
347
drh58ad5802011-03-23 22:02:23 +0000348 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000349#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
350
drh58ad5802011-03-23 22:02:23 +0000351 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000352#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
353
drh58ad5802011-03-23 22:02:23 +0000354 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000355#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
356
357/*
358** The DJGPP compiler environment looks mostly like Unix, but it
359** lacks the fcntl() system call. So redefine fcntl() to be something
360** that always succeeds. This means that locking does not occur under
361** DJGPP. But it is DOS - what did you expect?
362*/
363#ifdef __DJGPP__
364 { "fstat", 0, 0 },
365#define osFstat(a,b,c) 0
366#else
drh58ad5802011-03-23 22:02:23 +0000367 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000368#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
369#endif
370
drh58ad5802011-03-23 22:02:23 +0000371 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000372#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
373
drh58ad5802011-03-23 22:02:23 +0000374 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000375#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000376
drh58ad5802011-03-23 22:02:23 +0000377 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000378#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
379
drhe89b2912015-03-03 20:42:01 +0000380#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000381 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000382#else
drh58ad5802011-03-23 22:02:23 +0000383 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000384#endif
385#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
386
387#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000388 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000389#else
drh58ad5802011-03-23 22:02:23 +0000390 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000391#endif
392#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
393
drh58ad5802011-03-23 22:02:23 +0000394 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000395#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
396
drhe89b2912015-03-03 20:42:01 +0000397#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000398 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000399#else
drh58ad5802011-03-23 22:02:23 +0000400 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000401#endif
402#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
403 aSyscall[12].pCurrent)
404
405#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000406 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000407#else
drh58ad5802011-03-23 22:02:23 +0000408 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000409#endif
410#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
411 aSyscall[13].pCurrent)
412
drh6226ca22015-11-24 15:06:28 +0000413 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000414#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000415
416#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000417 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000418#else
drh58ad5802011-03-23 22:02:23 +0000419 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000420#endif
dan0fd7d862011-03-29 10:04:23 +0000421#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000422
drh036ac7f2011-08-08 23:18:05 +0000423 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
424#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
425
drh90315a22011-08-10 01:52:12 +0000426 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
427#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
428
drh9ef6bc42011-11-04 02:24:02 +0000429 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
430#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
431
432 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
433#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
434
drh6226ca22015-11-24 15:06:28 +0000435 { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
dand3eaebd2012-02-13 08:50:23 +0000436#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000437
drh6226ca22015-11-24 15:06:28 +0000438 { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
439#define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
440
dan4dd51442013-08-26 14:30:25 +0000441#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
dan893c0ff2013-03-25 19:05:07 +0000442 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
drh6226ca22015-11-24 15:06:28 +0000443#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
dan893c0ff2013-03-25 19:05:07 +0000444
drhd1ab8062013-03-25 20:50:25 +0000445 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
drh6226ca22015-11-24 15:06:28 +0000446#define osMunmap ((void*(*)(void*,size_t))aSyscall[23].pCurrent)
drhd1ab8062013-03-25 20:50:25 +0000447
dane6ecd662013-04-01 17:56:59 +0000448#if HAVE_MREMAP
drhd1ab8062013-03-25 20:50:25 +0000449 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
450#else
451 { "mremap", (sqlite3_syscall_ptr)0, 0 },
452#endif
drh6226ca22015-11-24 15:06:28 +0000453#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
454
danbc760632014-03-20 09:42:09 +0000455 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
drh6226ca22015-11-24 15:06:28 +0000456#define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
danbc760632014-03-20 09:42:09 +0000457
dan245fdc62015-10-31 17:58:33 +0000458 { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
drh6226ca22015-11-24 15:06:28 +0000459#define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
dan245fdc62015-10-31 17:58:33 +0000460
dan702eec12014-06-23 10:04:58 +0000461#endif
462
drhe562be52011-03-02 18:01:10 +0000463}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000464
drh6226ca22015-11-24 15:06:28 +0000465
466/*
467** On some systems, calls to fchown() will trigger a message in a security
468** log if they come from non-root processes. So avoid calling fchown() if
469** we are not running as root.
470*/
471static int robustFchown(int fd, uid_t uid, gid_t gid){
472#if OS_VXWORKS
473 return 0;
474#else
475 return osGeteuid() ? 0 : osFchown(fd,uid,gid);
476#endif
477}
478
drh99ab3b12011-03-02 15:09:07 +0000479/*
480** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000481** "unix" VFSes. Return SQLITE_OK opon successfully updating the
482** system call pointer, or SQLITE_NOTFOUND if there is no configurable
483** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000484*/
485static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000486 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
487 const char *zName, /* Name of system call to override */
488 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000489){
drh58ad5802011-03-23 22:02:23 +0000490 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000491 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000492
493 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000494 if( zName==0 ){
495 /* If no zName is given, restore all system calls to their default
496 ** settings and return NULL
497 */
dan51438a72011-04-02 17:00:47 +0000498 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000499 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
500 if( aSyscall[i].pDefault ){
501 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000502 }
503 }
504 }else{
505 /* If zName is specified, operate on only the one system call
506 ** specified.
507 */
508 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
509 if( strcmp(zName, aSyscall[i].zName)==0 ){
510 if( aSyscall[i].pDefault==0 ){
511 aSyscall[i].pDefault = aSyscall[i].pCurrent;
512 }
drh1df30962011-03-02 19:06:42 +0000513 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000514 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
515 aSyscall[i].pCurrent = pNewFunc;
516 break;
517 }
518 }
519 }
520 return rc;
521}
522
drh1df30962011-03-02 19:06:42 +0000523/*
524** Return the value of a system call. Return NULL if zName is not a
525** recognized system call name. NULL is also returned if the system call
526** is currently undefined.
527*/
drh58ad5802011-03-23 22:02:23 +0000528static sqlite3_syscall_ptr unixGetSystemCall(
529 sqlite3_vfs *pNotUsed,
530 const char *zName
531){
532 unsigned int i;
533
534 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000535 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
536 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
537 }
538 return 0;
539}
540
541/*
542** Return the name of the first system call after zName. If zName==NULL
543** then return the name of the first system call. Return NULL if zName
544** is the last system call or if zName is not the name of a valid
545** system call.
546*/
547static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000548 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000549
550 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000551 if( zName ){
552 for(i=0; i<ArraySize(aSyscall)-1; i++){
553 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000554 }
555 }
dan0fd7d862011-03-29 10:04:23 +0000556 for(i++; i<ArraySize(aSyscall); i++){
557 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000558 }
559 return 0;
560}
561
drhad4f1e52011-03-04 15:43:57 +0000562/*
drh77a3fdc2013-08-30 14:24:12 +0000563** Do not accept any file descriptor less than this value, in order to avoid
564** opening database file using file descriptors that are commonly used for
565** standard input, output, and error.
566*/
567#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
568# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
569#endif
570
571/*
drh8c815d12012-02-13 20:16:37 +0000572** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000573** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000574**
575** If the file creation mode "m" is 0 then set it to the default for
576** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
577** 0644) as modified by the system umask. If m is not 0, then
578** make the file creation mode be exactly m ignoring the umask.
579**
580** The m parameter will be non-zero only when creating -wal, -journal,
581** and -shm files. We want those files to have *exactly* the same
582** permissions as their original database, unadulterated by the umask.
583** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
584** transaction crashes and leaves behind hot journals, then any
585** process that is able to write to the database will also be able to
586** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000587*/
drh8c815d12012-02-13 20:16:37 +0000588static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000589 int fd;
drhe1186ab2013-01-04 20:45:13 +0000590 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5128d002013-08-30 06:20:23 +0000591 while(1){
drh5adc60b2012-04-14 13:25:11 +0000592#if defined(O_CLOEXEC)
593 fd = osOpen(z,f|O_CLOEXEC,m2);
594#else
595 fd = osOpen(z,f,m2);
596#endif
drh5128d002013-08-30 06:20:23 +0000597 if( fd<0 ){
598 if( errno==EINTR ) continue;
599 break;
600 }
drh77a3fdc2013-08-30 14:24:12 +0000601 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
drh5128d002013-08-30 06:20:23 +0000602 osClose(fd);
603 sqlite3_log(SQLITE_WARNING,
604 "attempt to open \"%s\" as file descriptor %d", z, fd);
605 fd = -1;
606 if( osOpen("/dev/null", f, m)<0 ) break;
607 }
drhe1186ab2013-01-04 20:45:13 +0000608 if( fd>=0 ){
609 if( m!=0 ){
610 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000611 if( osFstat(fd, &statbuf)==0
612 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000613 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000614 ){
drhe1186ab2013-01-04 20:45:13 +0000615 osFchmod(fd, m);
616 }
617 }
drh5adc60b2012-04-14 13:25:11 +0000618#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000619 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000620#endif
drhe1186ab2013-01-04 20:45:13 +0000621 }
drh5adc60b2012-04-14 13:25:11 +0000622 return fd;
drhad4f1e52011-03-04 15:43:57 +0000623}
danielk197713adf8a2004-06-03 16:08:41 +0000624
drh107886a2008-11-21 22:21:50 +0000625/*
dan9359c7b2009-08-21 08:29:10 +0000626** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000627** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000628** vxworksFileId objects used by this file, all of which may be
629** shared by multiple threads.
630**
631** Function unixMutexHeld() is used to assert() that the global mutex
632** is held when required. This function is only used as part of assert()
633** statements. e.g.
634**
635** unixEnterMutex()
636** assert( unixMutexHeld() );
637** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000638*/
639static void unixEnterMutex(void){
mistachkin93de6532015-07-03 21:38:09 +0000640 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
drh107886a2008-11-21 22:21:50 +0000641}
642static void unixLeaveMutex(void){
mistachkin93de6532015-07-03 21:38:09 +0000643 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
drh107886a2008-11-21 22:21:50 +0000644}
dan9359c7b2009-08-21 08:29:10 +0000645#ifdef SQLITE_DEBUG
646static int unixMutexHeld(void) {
mistachkin93de6532015-07-03 21:38:09 +0000647 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
dan9359c7b2009-08-21 08:29:10 +0000648}
649#endif
drh107886a2008-11-21 22:21:50 +0000650
drh734c9862008-11-28 15:37:20 +0000651
mistachkinfb383e92015-04-16 03:24:38 +0000652#ifdef SQLITE_HAVE_OS_TRACE
drh734c9862008-11-28 15:37:20 +0000653/*
654** Helper function for printing out trace information from debugging
peter.d.reid60ec9142014-09-06 16:39:46 +0000655** binaries. This returns the string representation of the supplied
drh734c9862008-11-28 15:37:20 +0000656** integer lock-type.
657*/
drh308c2a52010-05-14 11:30:18 +0000658static const char *azFileLock(int eFileLock){
659 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000660 case NO_LOCK: return "NONE";
661 case SHARED_LOCK: return "SHARED";
662 case RESERVED_LOCK: return "RESERVED";
663 case PENDING_LOCK: return "PENDING";
664 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000665 }
666 return "ERROR";
667}
668#endif
669
670#ifdef SQLITE_LOCK_TRACE
671/*
672** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000673**
drh734c9862008-11-28 15:37:20 +0000674** This routine is used for troubleshooting locks on multithreaded
675** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
676** command-line option on the compiler. This code is normally
677** turned off.
678*/
679static int lockTrace(int fd, int op, struct flock *p){
680 char *zOpName, *zType;
681 int s;
682 int savedErrno;
683 if( op==F_GETLK ){
684 zOpName = "GETLK";
685 }else if( op==F_SETLK ){
686 zOpName = "SETLK";
687 }else{
drh99ab3b12011-03-02 15:09:07 +0000688 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000689 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
690 return s;
691 }
692 if( p->l_type==F_RDLCK ){
693 zType = "RDLCK";
694 }else if( p->l_type==F_WRLCK ){
695 zType = "WRLCK";
696 }else if( p->l_type==F_UNLCK ){
697 zType = "UNLCK";
698 }else{
699 assert( 0 );
700 }
701 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000702 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000703 savedErrno = errno;
704 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
705 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
706 (int)p->l_pid, s);
707 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
708 struct flock l2;
709 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000710 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000711 if( l2.l_type==F_RDLCK ){
712 zType = "RDLCK";
713 }else if( l2.l_type==F_WRLCK ){
714 zType = "WRLCK";
715 }else if( l2.l_type==F_UNLCK ){
716 zType = "UNLCK";
717 }else{
718 assert( 0 );
719 }
720 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
721 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
722 }
723 errno = savedErrno;
724 return s;
725}
drh99ab3b12011-03-02 15:09:07 +0000726#undef osFcntl
727#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000728#endif /* SQLITE_LOCK_TRACE */
729
drhff812312011-02-23 13:33:46 +0000730/*
731** Retry ftruncate() calls that fail due to EINTR
dan2ee53412014-09-06 16:49:40 +0000732**
drhe6d41732015-02-21 00:49:00 +0000733** All calls to ftruncate() within this file should be made through
734** this wrapper. On the Android platform, bypassing the logic below
735** could lead to a corrupt database.
drhff812312011-02-23 13:33:46 +0000736*/
drhff812312011-02-23 13:33:46 +0000737static int robust_ftruncate(int h, sqlite3_int64 sz){
738 int rc;
dan2ee53412014-09-06 16:49:40 +0000739#ifdef __ANDROID__
740 /* On Android, ftruncate() always uses 32-bit offsets, even if
741 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
dan524a7332014-09-06 17:06:13 +0000742 ** truncate a file to any size larger than 2GiB. Silently ignore any
dan2ee53412014-09-06 16:49:40 +0000743 ** such attempts. */
744 if( sz>(sqlite3_int64)0x7FFFFFFF ){
745 rc = SQLITE_OK;
746 }else
747#endif
drh99ab3b12011-03-02 15:09:07 +0000748 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000749 return rc;
750}
drh734c9862008-11-28 15:37:20 +0000751
752/*
753** This routine translates a standard POSIX errno code into something
754** useful to the clients of the sqlite3 functions. Specifically, it is
755** intended to translate a variety of "try again" errors into SQLITE_BUSY
756** and a variety of "please close the file descriptor NOW" errors into
757** SQLITE_IOERR
758**
759** Errors during initialization of locks, or file system support for locks,
760** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
761*/
762static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
763 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000764#if 0
765 /* At one point this code was not commented out. In theory, this branch
766 ** should never be hit, as this function should only be called after
767 ** a locking-related function (i.e. fcntl()) has returned non-zero with
768 ** the value of errno as the first argument. Since a system call has failed,
769 ** errno should be non-zero.
770 **
771 ** Despite this, if errno really is zero, we still don't want to return
772 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
773 ** propagated back to the caller. Commenting this branch out means errno==0
774 ** will be handled by the "default:" case below.
775 */
drh734c9862008-11-28 15:37:20 +0000776 case 0:
777 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000778#endif
779
drh734c9862008-11-28 15:37:20 +0000780 case EAGAIN:
781 case ETIMEDOUT:
782 case EBUSY:
783 case EINTR:
784 case ENOLCK:
785 /* random NFS retry error, unless during file system support
786 * introspection, in which it actually means what it says */
787 return SQLITE_BUSY;
788
789 case EACCES:
790 /* EACCES is like EAGAIN during locking operations, but not any other time*/
791 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
drhf2f105d2012-08-20 15:53:54 +0000792 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
793 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
794 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
drh734c9862008-11-28 15:37:20 +0000795 return SQLITE_BUSY;
796 }
797 /* else fall through */
798 case EPERM:
799 return SQLITE_PERM;
800
drh734c9862008-11-28 15:37:20 +0000801#if EOPNOTSUPP!=ENOTSUP
802 case EOPNOTSUPP:
803 /* something went terribly awry, unless during file system support
804 * introspection, in which it actually means what it says */
805#endif
806#ifdef ENOTSUP
807 case ENOTSUP:
808 /* invalid fd, unless during file system support introspection, in which
809 * it actually means what it says */
810#endif
811 case EIO:
812 case EBADF:
813 case EINVAL:
814 case ENOTCONN:
815 case ENODEV:
816 case ENXIO:
817 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000818#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000819 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000820#endif
drh734c9862008-11-28 15:37:20 +0000821 case ENOSYS:
822 /* these should force the client to close the file and reconnect */
823
824 default:
825 return sqliteIOErr;
826 }
827}
828
829
drh734c9862008-11-28 15:37:20 +0000830/******************************************************************************
831****************** Begin Unique File ID Utility Used By VxWorks ***************
832**
833** On most versions of unix, we can get a unique ID for a file by concatenating
834** the device number and the inode number. But this does not work on VxWorks.
835** On VxWorks, a unique file id must be based on the canonical filename.
836**
837** A pointer to an instance of the following structure can be used as a
838** unique file ID in VxWorks. Each instance of this structure contains
839** a copy of the canonical filename. There is also a reference count.
840** The structure is reclaimed when the number of pointers to it drops to
841** zero.
842**
843** There are never very many files open at one time and lookups are not
844** a performance-critical path, so it is sufficient to put these
845** structures on a linked list.
846*/
847struct vxworksFileId {
848 struct vxworksFileId *pNext; /* Next in a list of them all */
849 int nRef; /* Number of references to this one */
850 int nName; /* Length of the zCanonicalName[] string */
851 char *zCanonicalName; /* Canonical filename */
852};
853
854#if OS_VXWORKS
855/*
drh9b35ea62008-11-29 02:20:26 +0000856** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000857** variable:
858*/
859static struct vxworksFileId *vxworksFileList = 0;
860
861/*
862** Simplify a filename into its canonical form
863** by making the following changes:
864**
865** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000866** * convert /./ into just /
867** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000868**
869** Changes are made in-place. Return the new name length.
870**
871** The original filename is in z[0..n-1]. Return the number of
872** characters in the simplified name.
873*/
874static int vxworksSimplifyName(char *z, int n){
875 int i, j;
876 while( n>1 && z[n-1]=='/' ){ n--; }
877 for(i=j=0; i<n; i++){
878 if( z[i]=='/' ){
879 if( z[i+1]=='/' ) continue;
880 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
881 i += 1;
882 continue;
883 }
884 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
885 while( j>0 && z[j-1]!='/' ){ j--; }
886 if( j>0 ){ j--; }
887 i += 2;
888 continue;
889 }
890 }
891 z[j++] = z[i];
892 }
893 z[j] = 0;
894 return j;
895}
896
897/*
898** Find a unique file ID for the given absolute pathname. Return
899** a pointer to the vxworksFileId object. This pointer is the unique
900** file ID.
901**
902** The nRef field of the vxworksFileId object is incremented before
903** the object is returned. A new vxworksFileId object is created
904** and added to the global list if necessary.
905**
906** If a memory allocation error occurs, return NULL.
907*/
908static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
909 struct vxworksFileId *pNew; /* search key and new file ID */
910 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
911 int n; /* Length of zAbsoluteName string */
912
913 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000914 n = (int)strlen(zAbsoluteName);
drhf3cdcdc2015-04-29 16:50:28 +0000915 pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
drh734c9862008-11-28 15:37:20 +0000916 if( pNew==0 ) return 0;
917 pNew->zCanonicalName = (char*)&pNew[1];
918 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
919 n = vxworksSimplifyName(pNew->zCanonicalName, n);
920
921 /* Search for an existing entry that matching the canonical name.
922 ** If found, increment the reference count and return a pointer to
923 ** the existing file ID.
924 */
925 unixEnterMutex();
926 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
927 if( pCandidate->nName==n
928 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
929 ){
930 sqlite3_free(pNew);
931 pCandidate->nRef++;
932 unixLeaveMutex();
933 return pCandidate;
934 }
935 }
936
937 /* No match was found. We will make a new file ID */
938 pNew->nRef = 1;
939 pNew->nName = n;
940 pNew->pNext = vxworksFileList;
941 vxworksFileList = pNew;
942 unixLeaveMutex();
943 return pNew;
944}
945
946/*
947** Decrement the reference count on a vxworksFileId object. Free
948** the object when the reference count reaches zero.
949*/
950static void vxworksReleaseFileId(struct vxworksFileId *pId){
951 unixEnterMutex();
952 assert( pId->nRef>0 );
953 pId->nRef--;
954 if( pId->nRef==0 ){
955 struct vxworksFileId **pp;
956 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
957 assert( *pp==pId );
958 *pp = pId->pNext;
959 sqlite3_free(pId);
960 }
961 unixLeaveMutex();
962}
963#endif /* OS_VXWORKS */
964/*************** End of Unique File ID Utility Used By VxWorks ****************
965******************************************************************************/
966
967
968/******************************************************************************
969*************************** Posix Advisory Locking ****************************
970**
drh9b35ea62008-11-29 02:20:26 +0000971** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000972** section 6.5.2.2 lines 483 through 490 specify that when a process
973** sets or clears a lock, that operation overrides any prior locks set
974** by the same process. It does not explicitly say so, but this implies
975** that it overrides locks set by the same process using a different
976** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000977**
978** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000979** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
980**
981** Suppose ./file1 and ./file2 are really the same file (because
982** one is a hard or symbolic link to the other) then if you set
983** an exclusive lock on fd1, then try to get an exclusive lock
984** on fd2, it works. I would have expected the second lock to
985** fail since there was already a lock on the file due to fd1.
986** But not so. Since both locks came from the same process, the
987** second overrides the first, even though they were on different
988** file descriptors opened on different file names.
989**
drh734c9862008-11-28 15:37:20 +0000990** This means that we cannot use POSIX locks to synchronize file access
991** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000992** to synchronize access for threads in separate processes, but not
993** threads within the same process.
994**
995** To work around the problem, SQLite has to manage file locks internally
996** on its own. Whenever a new database is opened, we have to find the
997** specific inode of the database file (the inode is determined by the
998** st_dev and st_ino fields of the stat structure that fstat() fills in)
999** and check for locks already existing on that inode. When locks are
1000** created or removed, we have to look at our own internal record of the
1001** locks to see if another thread has previously set a lock on that same
1002** inode.
1003**
drh9b35ea62008-11-29 02:20:26 +00001004** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
1005** For VxWorks, we have to use the alternative unique ID system based on
1006** canonical filename and implemented in the previous division.)
1007**
danielk1977ad94b582007-08-20 06:44:22 +00001008** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +00001009** descriptor. It is now a structure that holds the integer file
1010** descriptor and a pointer to a structure that describes the internal
1011** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +00001012** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +00001013** point to the same locking structure. The locking structure keeps
1014** a reference count (so we will know when to delete it) and a "cnt"
1015** field that tells us its internal lock status. cnt==0 means the
1016** file is unlocked. cnt==-1 means the file has an exclusive lock.
1017** cnt>0 means there are cnt shared locks on the file.
1018**
1019** Any attempt to lock or unlock a file first checks the locking
1020** structure. The fcntl() system call is only invoked to set a
1021** POSIX lock if the internal lock structure transitions between
1022** a locked and an unlocked state.
1023**
drh734c9862008-11-28 15:37:20 +00001024** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +00001025**
1026** If you close a file descriptor that points to a file that has locks,
1027** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +00001028** released. To work around this problem, each unixInodeInfo object
1029** maintains a count of the number of pending locks on tha inode.
1030** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +00001031** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +00001032** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +00001033** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +00001034** be closed and that list is walked (and cleared) when the last lock
1035** clears.
1036**
drh9b35ea62008-11-29 02:20:26 +00001037** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +00001038**
drh9b35ea62008-11-29 02:20:26 +00001039** Many older versions of linux use the LinuxThreads library which is
1040** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +00001041** A cannot be modified or overridden by a different thread B.
1042** Only thread A can modify the lock. Locking behavior is correct
1043** if the appliation uses the newer Native Posix Thread Library (NPTL)
1044** on linux - with NPTL a lock created by thread A can override locks
1045** in thread B. But there is no way to know at compile-time which
1046** threading library is being used. So there is no way to know at
1047** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001048** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001049** current process.
drh5fdae772004-06-29 03:29:00 +00001050**
drh8af6c222010-05-14 12:43:01 +00001051** SQLite used to support LinuxThreads. But support for LinuxThreads
1052** was dropped beginning with version 3.7.0. SQLite will still work with
1053** LinuxThreads provided that (1) there is no more than one connection
1054** per database file in the same process and (2) database connections
1055** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001056*/
1057
1058/*
1059** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001060** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001061*/
1062struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001063 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001064#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001065 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001066#else
drh107886a2008-11-21 22:21:50 +00001067 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001068#endif
1069};
1070
1071/*
drhbbd42a62004-05-22 17:41:58 +00001072** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001073** inode. Or, on LinuxThreads, there is one of these structures for
1074** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001075**
danielk1977ad94b582007-08-20 06:44:22 +00001076** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001077** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001078** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001079*/
drh8af6c222010-05-14 12:43:01 +00001080struct unixInodeInfo {
1081 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001082 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001083 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1084 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001085 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001086 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1087 int nLock; /* Number of outstanding file locks */
1088 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1089 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1090 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001091#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001092 unsigned long long sharedByte; /* for AFP simulated shared lock */
1093#endif
drh6c7d5c52008-11-21 20:32:33 +00001094#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001095 sem_t *pSem; /* Named POSIX semaphore */
1096 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001097#endif
drhbbd42a62004-05-22 17:41:58 +00001098};
1099
drhda0e7682008-07-30 15:27:54 +00001100/*
drh8af6c222010-05-14 12:43:01 +00001101** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001102*/
drhd91c68f2010-05-14 14:52:25 +00001103static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001104
drh5fdae772004-06-29 03:29:00 +00001105/*
dane18d4952011-02-21 11:46:24 +00001106**
drhaaeaa182015-11-24 15:12:47 +00001107** This function - unixLogErrorAtLine(), is only ever called via the macro
dane18d4952011-02-21 11:46:24 +00001108** unixLogError().
1109**
1110** It is invoked after an error occurs in an OS function and errno has been
1111** set. It logs a message using sqlite3_log() containing the current value of
1112** errno and, if possible, the human-readable equivalent from strerror() or
1113** strerror_r().
1114**
1115** The first argument passed to the macro should be the error code that
1116** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1117** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001118** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001119** if any.
1120*/
drh0e9365c2011-03-02 02:08:13 +00001121#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1122static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001123 int errcode, /* SQLite error code */
1124 const char *zFunc, /* Name of OS function that failed */
1125 const char *zPath, /* File path associated with error */
1126 int iLine /* Source line number where error occurred */
1127){
1128 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001129 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001130
1131 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1132 ** the strerror() function to obtain the human-readable error message
1133 ** equivalent to errno. Otherwise, use strerror_r().
1134 */
1135#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1136 char aErr[80];
1137 memset(aErr, 0, sizeof(aErr));
1138 zErr = aErr;
1139
1140 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001141 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001142 ** returns a pointer to a buffer containing the error message. That pointer
1143 ** may point to aErr[], or it may point to some static storage somewhere.
1144 ** Otherwise, assume that the system provides the POSIX version of
1145 ** strerror_r(), which always writes an error message into aErr[].
1146 **
1147 ** If the code incorrectly assumes that it is the POSIX version that is
1148 ** available, the error message will often be an empty string. Not a
1149 ** huge problem. Incorrectly concluding that the GNU version is available
1150 ** could lead to a segfault though.
1151 */
1152#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1153 zErr =
1154# endif
drh0e9365c2011-03-02 02:08:13 +00001155 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001156
1157#elif SQLITE_THREADSAFE
1158 /* This is a threadsafe build, but strerror_r() is not available. */
1159 zErr = "";
1160#else
1161 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001162 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001163#endif
1164
drh0e9365c2011-03-02 02:08:13 +00001165 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001166 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001167 "os_unix.c:%d: (%d) %s(%s) - %s",
1168 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001169 );
1170
1171 return errcode;
1172}
1173
drh0e9365c2011-03-02 02:08:13 +00001174/*
1175** Close a file descriptor.
1176**
1177** We assume that close() almost always works, since it is only in a
1178** very sick application or on a very sick platform that it might fail.
1179** If it does fail, simply leak the file descriptor, but do log the
1180** error.
1181**
1182** Note that it is not safe to retry close() after EINTR since the
1183** file descriptor might have already been reused by another thread.
1184** So we don't even try to recover from an EINTR. Just log the error
1185** and move on.
1186*/
1187static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001188 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001189 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1190 pFile ? pFile->zPath : 0, lineno);
1191 }
1192}
dane18d4952011-02-21 11:46:24 +00001193
1194/*
drhe6d41732015-02-21 00:49:00 +00001195** Set the pFile->lastErrno. Do this in a subroutine as that provides
1196** a convenient place to set a breakpoint.
drh4bf66fd2015-02-19 02:43:02 +00001197*/
1198static void storeLastErrno(unixFile *pFile, int error){
1199 pFile->lastErrno = error;
1200}
1201
1202/*
danb0ac3e32010-06-16 10:55:42 +00001203** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001204*/
drh0e9365c2011-03-02 02:08:13 +00001205static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001206 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001207 UnixUnusedFd *p;
1208 UnixUnusedFd *pNext;
1209 for(p=pInode->pUnused; p; p=pNext){
1210 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001211 robust_close(pFile, p->fd, __LINE__);
1212 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001213 }
drh0e9365c2011-03-02 02:08:13 +00001214 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001215}
1216
1217/*
drh8af6c222010-05-14 12:43:01 +00001218** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001219**
1220** The mutex entered using the unixEnterMutex() function must be held
1221** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001222*/
danb0ac3e32010-06-16 10:55:42 +00001223static void releaseInodeInfo(unixFile *pFile){
1224 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001225 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001226 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001227 pInode->nRef--;
1228 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001229 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001230 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001231 if( pInode->pPrev ){
1232 assert( pInode->pPrev->pNext==pInode );
1233 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001234 }else{
drh8af6c222010-05-14 12:43:01 +00001235 assert( inodeList==pInode );
1236 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001237 }
drh8af6c222010-05-14 12:43:01 +00001238 if( pInode->pNext ){
1239 assert( pInode->pNext->pPrev==pInode );
1240 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001241 }
drh8af6c222010-05-14 12:43:01 +00001242 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001243 }
drhbbd42a62004-05-22 17:41:58 +00001244 }
1245}
1246
1247/*
drh8af6c222010-05-14 12:43:01 +00001248** Given a file descriptor, locate the unixInodeInfo object that
1249** describes that file descriptor. Create a new one if necessary. The
1250** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001251**
dan9359c7b2009-08-21 08:29:10 +00001252** The mutex entered using the unixEnterMutex() function must be held
1253** when this function is called.
1254**
drh6c7d5c52008-11-21 20:32:33 +00001255** Return an appropriate error code.
1256*/
drh8af6c222010-05-14 12:43:01 +00001257static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001258 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001259 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001260){
1261 int rc; /* System call return code */
1262 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001263 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1264 struct stat statbuf; /* Low-level file information */
1265 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001266
dan9359c7b2009-08-21 08:29:10 +00001267 assert( unixMutexHeld() );
1268
drh6c7d5c52008-11-21 20:32:33 +00001269 /* Get low-level information about the file that we can used to
1270 ** create a unique name for the file.
1271 */
1272 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001273 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001274 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001275 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001276#ifdef EOVERFLOW
1277 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1278#endif
1279 return SQLITE_IOERR;
1280 }
1281
drheb0d74f2009-02-03 15:27:02 +00001282#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001283 /* On OS X on an msdos filesystem, the inode number is reported
1284 ** incorrectly for zero-size files. See ticket #3260. To work
1285 ** around this problem (we consider it a bug in OS X, not SQLite)
1286 ** we always increase the file size to 1 by writing a single byte
1287 ** prior to accessing the inode number. The one byte written is
1288 ** an ASCII 'S' character which also happens to be the first byte
1289 ** in the header of every SQLite database. In this way, if there
1290 ** is a race condition such that another thread has already populated
1291 ** the first page of the database, no damage is done.
1292 */
drh7ed97b92010-01-20 13:07:21 +00001293 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001294 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001295 if( rc!=1 ){
drh4bf66fd2015-02-19 02:43:02 +00001296 storeLastErrno(pFile, errno);
drheb0d74f2009-02-03 15:27:02 +00001297 return SQLITE_IOERR;
1298 }
drh99ab3b12011-03-02 15:09:07 +00001299 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001300 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001301 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001302 return SQLITE_IOERR;
1303 }
1304 }
drheb0d74f2009-02-03 15:27:02 +00001305#endif
drh6c7d5c52008-11-21 20:32:33 +00001306
drh8af6c222010-05-14 12:43:01 +00001307 memset(&fileId, 0, sizeof(fileId));
1308 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001309#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001310 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001311#else
drh8af6c222010-05-14 12:43:01 +00001312 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001313#endif
drh8af6c222010-05-14 12:43:01 +00001314 pInode = inodeList;
1315 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1316 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001317 }
drh8af6c222010-05-14 12:43:01 +00001318 if( pInode==0 ){
drhf3cdcdc2015-04-29 16:50:28 +00001319 pInode = sqlite3_malloc64( sizeof(*pInode) );
drh8af6c222010-05-14 12:43:01 +00001320 if( pInode==0 ){
1321 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001322 }
drh8af6c222010-05-14 12:43:01 +00001323 memset(pInode, 0, sizeof(*pInode));
1324 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1325 pInode->nRef = 1;
1326 pInode->pNext = inodeList;
1327 pInode->pPrev = 0;
1328 if( inodeList ) inodeList->pPrev = pInode;
1329 inodeList = pInode;
1330 }else{
1331 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001332 }
drh8af6c222010-05-14 12:43:01 +00001333 *ppInode = pInode;
1334 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001335}
drh6c7d5c52008-11-21 20:32:33 +00001336
drhb959a012013-12-07 12:29:22 +00001337/*
1338** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1339*/
1340static int fileHasMoved(unixFile *pFile){
drh61ffea52014-08-12 12:19:25 +00001341#if OS_VXWORKS
1342 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1343#else
drhb959a012013-12-07 12:29:22 +00001344 struct stat buf;
1345 return pFile->pInode!=0 &&
drh61ffea52014-08-12 12:19:25 +00001346 (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
drh91be7dc2014-08-11 13:53:30 +00001347#endif
drhb959a012013-12-07 12:29:22 +00001348}
1349
aswift5b1a2562008-08-22 00:22:35 +00001350
1351/*
drhfbc7e882013-04-11 01:16:15 +00001352** Check a unixFile that is a database. Verify the following:
1353**
1354** (1) There is exactly one hard link on the file
1355** (2) The file is not a symbolic link
1356** (3) The file has not been renamed or unlinked
1357**
1358** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1359*/
1360static void verifyDbFile(unixFile *pFile){
1361 struct stat buf;
1362 int rc;
drh3044b512014-06-16 16:41:52 +00001363 if( pFile->ctrlFlags & UNIXFILE_WARNED ){
1364 /* One or more of the following warnings have already been issued. Do not
1365 ** repeat them so as not to clutter the error log */
drhfbc7e882013-04-11 01:16:15 +00001366 return;
1367 }
1368 rc = osFstat(pFile->h, &buf);
1369 if( rc!=0 ){
1370 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
1371 pFile->ctrlFlags |= UNIXFILE_WARNED;
1372 return;
1373 }
drh3044b512014-06-16 16:41:52 +00001374 if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
drhfbc7e882013-04-11 01:16:15 +00001375 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
1376 pFile->ctrlFlags |= UNIXFILE_WARNED;
1377 return;
1378 }
1379 if( buf.st_nlink>1 ){
1380 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
1381 pFile->ctrlFlags |= UNIXFILE_WARNED;
1382 return;
1383 }
drhb959a012013-12-07 12:29:22 +00001384 if( fileHasMoved(pFile) ){
drhfbc7e882013-04-11 01:16:15 +00001385 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
1386 pFile->ctrlFlags |= UNIXFILE_WARNED;
1387 return;
1388 }
1389}
1390
1391
1392/*
danielk197713adf8a2004-06-03 16:08:41 +00001393** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001394** file by this or any other process. If such a lock is held, set *pResOut
1395** to a non-zero value otherwise *pResOut is set to zero. The return value
1396** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001397*/
danielk1977861f7452008-06-05 11:39:11 +00001398static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001399 int rc = SQLITE_OK;
1400 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001401 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001402
danielk1977861f7452008-06-05 11:39:11 +00001403 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1404
drh054889e2005-11-30 03:20:31 +00001405 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001406 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001407
1408 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001409 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001410 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001411 }
1412
drh2ac3ee92004-06-07 16:27:46 +00001413 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001414 */
danielk197709480a92009-02-09 05:32:32 +00001415#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001416 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001417 struct flock lock;
1418 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001419 lock.l_start = RESERVED_BYTE;
1420 lock.l_len = 1;
1421 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001422 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1423 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001424 storeLastErrno(pFile, errno);
aswift5b1a2562008-08-22 00:22:35 +00001425 } else if( lock.l_type!=F_UNLCK ){
1426 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001427 }
1428 }
danielk197709480a92009-02-09 05:32:32 +00001429#endif
danielk197713adf8a2004-06-03 16:08:41 +00001430
drh6c7d5c52008-11-21 20:32:33 +00001431 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001432 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001433
aswift5b1a2562008-08-22 00:22:35 +00001434 *pResOut = reserved;
1435 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001436}
1437
1438/*
drha7e61d82011-03-12 17:02:57 +00001439** Attempt to set a system-lock on the file pFile. The lock is
1440** described by pLock.
1441**
drh77197112011-03-15 19:08:48 +00001442** If the pFile was opened read/write from unix-excl, then the only lock
1443** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001444** the first time any lock is attempted. All subsequent system locking
1445** operations become no-ops. Locking operations still happen internally,
1446** in order to coordinate access between separate database connections
1447** within this process, but all of that is handled in memory and the
1448** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001449**
1450** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1451** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1452** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001453**
1454** Zero is returned if the call completes successfully, or -1 if a call
1455** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001456*/
1457static int unixFileLock(unixFile *pFile, struct flock *pLock){
1458 int rc;
drh3cb93392011-03-12 18:10:44 +00001459 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001460 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001461 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001462 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1463 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1464 ){
drh3cb93392011-03-12 18:10:44 +00001465 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001466 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001467 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001468 lock.l_whence = SEEK_SET;
1469 lock.l_start = SHARED_FIRST;
1470 lock.l_len = SHARED_SIZE;
1471 lock.l_type = F_WRLCK;
1472 rc = osFcntl(pFile->h, F_SETLK, &lock);
1473 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001474 pInode->bProcessLock = 1;
1475 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001476 }else{
1477 rc = 0;
1478 }
1479 }else{
1480 rc = osFcntl(pFile->h, F_SETLK, pLock);
1481 }
1482 return rc;
1483}
1484
1485/*
drh308c2a52010-05-14 11:30:18 +00001486** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001487** of the following:
1488**
drh2ac3ee92004-06-07 16:27:46 +00001489** (1) SHARED_LOCK
1490** (2) RESERVED_LOCK
1491** (3) PENDING_LOCK
1492** (4) EXCLUSIVE_LOCK
1493**
drhb3e04342004-06-08 00:47:47 +00001494** Sometimes when requesting one lock state, additional lock states
1495** are inserted in between. The locking might fail on one of the later
1496** transitions leaving the lock state different from what it started but
1497** still short of its goal. The following chart shows the allowed
1498** transitions and the inserted intermediate states:
1499**
1500** UNLOCKED -> SHARED
1501** SHARED -> RESERVED
1502** SHARED -> (PENDING) -> EXCLUSIVE
1503** RESERVED -> (PENDING) -> EXCLUSIVE
1504** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001505**
drha6abd042004-06-09 17:37:22 +00001506** This routine will only increase a lock. Use the sqlite3OsUnlock()
1507** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001508*/
drh308c2a52010-05-14 11:30:18 +00001509static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001510 /* The following describes the implementation of the various locks and
1511 ** lock transitions in terms of the POSIX advisory shared and exclusive
1512 ** lock primitives (called read-locks and write-locks below, to avoid
1513 ** confusion with SQLite lock names). The algorithms are complicated
1514 ** slightly in order to be compatible with windows systems simultaneously
1515 ** accessing the same database file, in case that is ever required.
1516 **
1517 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1518 ** byte', each single bytes at well known offsets, and the 'shared byte
1519 ** range', a range of 510 bytes at a well known offset.
1520 **
1521 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1522 ** byte'. If this is successful, a random byte from the 'shared byte
1523 ** range' is read-locked and the lock on the 'pending byte' released.
1524 **
danielk197790ba3bd2004-06-25 08:32:25 +00001525 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1526 ** A RESERVED lock is implemented by grabbing a write-lock on the
1527 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001528 **
1529 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001530 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1531 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1532 ** obtained, but existing SHARED locks are allowed to persist. A process
1533 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1534 ** This property is used by the algorithm for rolling back a journal file
1535 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001536 **
danielk197790ba3bd2004-06-25 08:32:25 +00001537 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1538 ** implemented by obtaining a write-lock on the entire 'shared byte
1539 ** range'. Since all other locks require a read-lock on one of the bytes
1540 ** within this range, this ensures that no other locks are held on the
1541 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001542 **
1543 ** The reason a single byte cannot be used instead of the 'shared byte
1544 ** range' is that some versions of windows do not support read-locks. By
1545 ** locking a random byte from a range, concurrent SHARED locks may exist
1546 ** even if the locking primitive used is always a write-lock.
1547 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001548 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001549 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001550 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001551 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001552 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001553
drh054889e2005-11-30 03:20:31 +00001554 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001555 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1556 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh91eb93c2015-03-03 19:56:20 +00001557 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001558 osGetpid(0)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001559
1560 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001561 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001562 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001563 */
drh308c2a52010-05-14 11:30:18 +00001564 if( pFile->eFileLock>=eFileLock ){
1565 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1566 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001567 return SQLITE_OK;
1568 }
1569
drh0c2694b2009-09-03 16:23:44 +00001570 /* Make sure the locking sequence is correct.
1571 ** (1) We never move from unlocked to anything higher than shared lock.
1572 ** (2) SQLite never explicitly requests a pendig lock.
1573 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001574 */
drh308c2a52010-05-14 11:30:18 +00001575 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1576 assert( eFileLock!=PENDING_LOCK );
1577 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001578
drh8af6c222010-05-14 12:43:01 +00001579 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001580 */
drh6c7d5c52008-11-21 20:32:33 +00001581 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001582 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001583
danielk1977ad94b582007-08-20 06:44:22 +00001584 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001585 ** handle that precludes the requested lock, return BUSY.
1586 */
drh8af6c222010-05-14 12:43:01 +00001587 if( (pFile->eFileLock!=pInode->eFileLock &&
1588 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001589 ){
1590 rc = SQLITE_BUSY;
1591 goto end_lock;
1592 }
1593
1594 /* If a SHARED lock is requested, and some thread using this PID already
1595 ** has a SHARED or RESERVED lock, then increment reference counts and
1596 ** return SQLITE_OK.
1597 */
drh308c2a52010-05-14 11:30:18 +00001598 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001599 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001600 assert( eFileLock==SHARED_LOCK );
1601 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001602 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001603 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001604 pInode->nShared++;
1605 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001606 goto end_lock;
1607 }
1608
danielk19779a1d0ab2004-06-01 14:09:28 +00001609
drh3cde3bb2004-06-12 02:17:14 +00001610 /* A PENDING lock is needed before acquiring a SHARED lock and before
1611 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1612 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001613 */
drh0c2694b2009-09-03 16:23:44 +00001614 lock.l_len = 1L;
1615 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001616 if( eFileLock==SHARED_LOCK
1617 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001618 ){
drh308c2a52010-05-14 11:30:18 +00001619 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001620 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001621 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001622 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001623 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001624 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001625 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001626 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001627 goto end_lock;
1628 }
drh3cde3bb2004-06-12 02:17:14 +00001629 }
1630
1631
1632 /* If control gets to this point, then actually go ahead and make
1633 ** operating system calls for the specified lock.
1634 */
drh308c2a52010-05-14 11:30:18 +00001635 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001636 assert( pInode->nShared==0 );
1637 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001638 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001639
drh2ac3ee92004-06-07 16:27:46 +00001640 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001641 lock.l_start = SHARED_FIRST;
1642 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001643 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001644 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001645 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001646 }
dan661d71a2011-03-30 19:08:03 +00001647
drh2ac3ee92004-06-07 16:27:46 +00001648 /* Drop the temporary PENDING lock */
1649 lock.l_start = PENDING_BYTE;
1650 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001651 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001652 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1653 /* This could happen with a network mount */
1654 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001655 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001656 }
dan661d71a2011-03-30 19:08:03 +00001657
1658 if( rc ){
1659 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001660 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001661 }
dan661d71a2011-03-30 19:08:03 +00001662 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001663 }else{
drh308c2a52010-05-14 11:30:18 +00001664 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001665 pInode->nLock++;
1666 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001667 }
drh8af6c222010-05-14 12:43:01 +00001668 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001669 /* We are trying for an exclusive lock but another thread in this
1670 ** same process is still holding a shared lock. */
1671 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001672 }else{
drh3cde3bb2004-06-12 02:17:14 +00001673 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001674 ** assumed that there is a SHARED or greater lock on the file
1675 ** already.
1676 */
drh308c2a52010-05-14 11:30:18 +00001677 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001678 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001679
1680 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1681 if( eFileLock==RESERVED_LOCK ){
1682 lock.l_start = RESERVED_BYTE;
1683 lock.l_len = 1L;
1684 }else{
1685 lock.l_start = SHARED_FIRST;
1686 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001687 }
dan661d71a2011-03-30 19:08:03 +00001688
1689 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001690 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001691 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001692 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001693 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001694 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001695 }
drhbbd42a62004-05-22 17:41:58 +00001696 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001697
drh8f941bc2009-01-14 23:03:40 +00001698
drhd3d8c042012-05-29 17:02:40 +00001699#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001700 /* Set up the transaction-counter change checking flags when
1701 ** transitioning from a SHARED to a RESERVED lock. The change
1702 ** from SHARED to RESERVED marks the beginning of a normal
1703 ** write operation (not a hot journal rollback).
1704 */
1705 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001706 && pFile->eFileLock<=SHARED_LOCK
1707 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001708 ){
1709 pFile->transCntrChng = 0;
1710 pFile->dbUpdate = 0;
1711 pFile->inNormalWrite = 1;
1712 }
1713#endif
1714
1715
danielk1977ecb2a962004-06-02 06:30:16 +00001716 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001717 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001718 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001719 }else if( eFileLock==EXCLUSIVE_LOCK ){
1720 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001721 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001722 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001723
1724end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001725 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001726 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1727 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001728 return rc;
1729}
1730
1731/*
dan08da86a2009-08-21 17:18:03 +00001732** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001733** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001734*/
1735static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001736 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001737 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001738 p->pNext = pInode->pUnused;
1739 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001740 pFile->h = -1;
1741 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001742}
1743
1744/*
drh308c2a52010-05-14 11:30:18 +00001745** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001746** must be either NO_LOCK or SHARED_LOCK.
1747**
1748** If the locking level of the file descriptor is already at or below
1749** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001750**
1751** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1752** the byte range is divided into 2 parts and the first part is unlocked then
1753** set to a read lock, then the other part is simply unlocked. This works
1754** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1755** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001756*/
drha7e61d82011-03-12 17:02:57 +00001757static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001758 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001759 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001760 struct flock lock;
1761 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001762
drh054889e2005-11-30 03:20:31 +00001763 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001764 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001765 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001766 osGetpid(0)));
drha6abd042004-06-09 17:37:22 +00001767
drh308c2a52010-05-14 11:30:18 +00001768 assert( eFileLock<=SHARED_LOCK );
1769 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001770 return SQLITE_OK;
1771 }
drh6c7d5c52008-11-21 20:32:33 +00001772 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001773 pInode = pFile->pInode;
1774 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001775 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001776 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001777
drhd3d8c042012-05-29 17:02:40 +00001778#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001779 /* When reducing a lock such that other processes can start
1780 ** reading the database file again, make sure that the
1781 ** transaction counter was updated if any part of the database
1782 ** file changed. If the transaction counter is not updated,
1783 ** other connections to the same file might not realize that
1784 ** the file has changed and hence might not know to flush their
1785 ** cache. The use of a stale cache can lead to database corruption.
1786 */
drh8f941bc2009-01-14 23:03:40 +00001787 pFile->inNormalWrite = 0;
1788#endif
1789
drh7ed97b92010-01-20 13:07:21 +00001790 /* downgrading to a shared lock on NFS involves clearing the write lock
1791 ** before establishing the readlock - to avoid a race condition we downgrade
1792 ** the lock in 2 blocks, so that part of the range will be covered by a
1793 ** write lock until the rest is covered by a read lock:
1794 ** 1: [WWWWW]
1795 ** 2: [....W]
1796 ** 3: [RRRRW]
1797 ** 4: [RRRR.]
1798 */
drh308c2a52010-05-14 11:30:18 +00001799 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001800#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001801 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001802 assert( handleNFSUnlock==0 );
1803#endif
1804#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001805 if( handleNFSUnlock ){
drha712b4b2015-02-19 16:12:04 +00001806 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001807 off_t divSize = SHARED_SIZE - 1;
1808
1809 lock.l_type = F_UNLCK;
1810 lock.l_whence = SEEK_SET;
1811 lock.l_start = SHARED_FIRST;
1812 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001813 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001814 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001815 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001816 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001817 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001818 }
1819 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001820 }
drh7ed97b92010-01-20 13:07:21 +00001821 lock.l_type = F_RDLCK;
1822 lock.l_whence = SEEK_SET;
1823 lock.l_start = SHARED_FIRST;
1824 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001825 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001826 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001827 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1828 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001829 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001830 }
1831 goto end_unlock;
1832 }
1833 lock.l_type = F_UNLCK;
1834 lock.l_whence = SEEK_SET;
1835 lock.l_start = SHARED_FIRST+divSize;
1836 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001837 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001838 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001839 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001840 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001841 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001842 }
1843 goto end_unlock;
1844 }
drh30f776f2011-02-25 03:25:07 +00001845 }else
1846#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1847 {
drh7ed97b92010-01-20 13:07:21 +00001848 lock.l_type = F_RDLCK;
1849 lock.l_whence = SEEK_SET;
1850 lock.l_start = SHARED_FIRST;
1851 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001852 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001853 /* In theory, the call to unixFileLock() cannot fail because another
1854 ** process is holding an incompatible lock. If it does, this
1855 ** indicates that the other process is not following the locking
1856 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1857 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1858 ** an assert to fail). */
1859 rc = SQLITE_IOERR_RDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001860 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00001861 goto end_unlock;
1862 }
drh9c105bb2004-10-02 20:38:28 +00001863 }
1864 }
drhbbd42a62004-05-22 17:41:58 +00001865 lock.l_type = F_UNLCK;
1866 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001867 lock.l_start = PENDING_BYTE;
1868 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001869 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001870 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001871 }else{
danea83bc62011-04-01 11:56:32 +00001872 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001873 storeLastErrno(pFile, errno);
drhcd731cf2009-03-28 23:23:02 +00001874 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001875 }
drhbbd42a62004-05-22 17:41:58 +00001876 }
drh308c2a52010-05-14 11:30:18 +00001877 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001878 /* Decrement the shared lock counter. Release the lock using an
1879 ** OS call only when all threads in this same process have released
1880 ** the lock.
1881 */
drh8af6c222010-05-14 12:43:01 +00001882 pInode->nShared--;
1883 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001884 lock.l_type = F_UNLCK;
1885 lock.l_whence = SEEK_SET;
1886 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001887 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001888 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001889 }else{
danea83bc62011-04-01 11:56:32 +00001890 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001891 storeLastErrno(pFile, errno);
drh8af6c222010-05-14 12:43:01 +00001892 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001893 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001894 }
drha6abd042004-06-09 17:37:22 +00001895 }
1896
drhbbd42a62004-05-22 17:41:58 +00001897 /* Decrement the count of locks against this same file. When the
1898 ** count reaches zero, close any other file descriptors whose close
1899 ** was deferred because of outstanding locks.
1900 */
drh8af6c222010-05-14 12:43:01 +00001901 pInode->nLock--;
1902 assert( pInode->nLock>=0 );
1903 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001904 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001905 }
1906 }
drhf2f105d2012-08-20 15:53:54 +00001907
aswift5b1a2562008-08-22 00:22:35 +00001908end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001909 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001910 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001911 return rc;
drhbbd42a62004-05-22 17:41:58 +00001912}
1913
1914/*
drh308c2a52010-05-14 11:30:18 +00001915** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001916** must be either NO_LOCK or SHARED_LOCK.
1917**
1918** If the locking level of the file descriptor is already at or below
1919** the requested locking level, this routine is a no-op.
1920*/
drh308c2a52010-05-14 11:30:18 +00001921static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00001922#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00001923 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00001924#endif
drha7e61d82011-03-12 17:02:57 +00001925 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001926}
1927
mistachkine98844f2013-08-24 00:59:24 +00001928#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001929static int unixMapfile(unixFile *pFd, i64 nByte);
1930static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00001931#endif
danf23da962013-03-23 21:00:41 +00001932
drh7ed97b92010-01-20 13:07:21 +00001933/*
danielk1977e339d652008-06-28 11:23:00 +00001934** This function performs the parts of the "close file" operation
1935** common to all locking schemes. It closes the directory and file
1936** handles, if they are valid, and sets all fields of the unixFile
1937** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001938**
1939** It is *not* necessary to hold the mutex when this routine is called,
1940** even on VxWorks. A mutex will be acquired on VxWorks by the
1941** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001942*/
1943static int closeUnixFile(sqlite3_file *id){
1944 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00001945#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001946 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00001947#endif
dan661d71a2011-03-30 19:08:03 +00001948 if( pFile->h>=0 ){
1949 robust_close(pFile, pFile->h, __LINE__);
1950 pFile->h = -1;
1951 }
1952#if OS_VXWORKS
1953 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001954 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001955 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001956 }
1957 vxworksReleaseFileId(pFile->pId);
1958 pFile->pId = 0;
1959 }
1960#endif
drh0bdbc902014-06-16 18:35:06 +00001961#ifdef SQLITE_UNLINK_AFTER_CLOSE
1962 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
1963 osUnlink(pFile->zPath);
1964 sqlite3_free(*(char**)&pFile->zPath);
1965 pFile->zPath = 0;
1966 }
1967#endif
dan661d71a2011-03-30 19:08:03 +00001968 OSTRACE(("CLOSE %-3d\n", pFile->h));
1969 OpenCounter(-1);
1970 sqlite3_free(pFile->pUnused);
1971 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001972 return SQLITE_OK;
1973}
1974
1975/*
danielk1977e3026632004-06-22 11:29:02 +00001976** Close a file.
1977*/
danielk197762079062007-08-15 17:08:46 +00001978static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001979 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001980 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00001981 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00001982 unixUnlock(id, NO_LOCK);
1983 unixEnterMutex();
1984
1985 /* unixFile.pInode is always valid here. Otherwise, a different close
1986 ** routine (e.g. nolockClose()) would be called instead.
1987 */
1988 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1989 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1990 /* If there are outstanding locks, do not actually close the file just
1991 ** yet because that would clear those locks. Instead, add the file
1992 ** descriptor to pInode->pUnused list. It will be automatically closed
1993 ** when the last lock is cleared.
1994 */
1995 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001996 }
dan661d71a2011-03-30 19:08:03 +00001997 releaseInodeInfo(pFile);
1998 rc = closeUnixFile(id);
1999 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00002000 return rc;
danielk1977e3026632004-06-22 11:29:02 +00002001}
2002
drh734c9862008-11-28 15:37:20 +00002003/************** End of the posix advisory lock implementation *****************
2004******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002005
drh734c9862008-11-28 15:37:20 +00002006/******************************************************************************
2007****************************** No-op Locking **********************************
2008**
2009** Of the various locking implementations available, this is by far the
2010** simplest: locking is ignored. No attempt is made to lock the database
2011** file for reading or writing.
2012**
2013** This locking mode is appropriate for use on read-only databases
2014** (ex: databases that are burned into CD-ROM, for example.) It can
2015** also be used if the application employs some external mechanism to
2016** prevent simultaneous access of the same database by two or more
2017** database connections. But there is a serious risk of database
2018** corruption if this locking mode is used in situations where multiple
2019** database connections are accessing the same database file at the same
2020** time and one or more of those connections are writing.
2021*/
drhbfe66312006-10-03 17:40:40 +00002022
drh734c9862008-11-28 15:37:20 +00002023static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
2024 UNUSED_PARAMETER(NotUsed);
2025 *pResOut = 0;
2026 return SQLITE_OK;
2027}
drh734c9862008-11-28 15:37:20 +00002028static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
2029 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2030 return SQLITE_OK;
2031}
drh734c9862008-11-28 15:37:20 +00002032static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
2033 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2034 return SQLITE_OK;
2035}
2036
2037/*
drh9b35ea62008-11-29 02:20:26 +00002038** Close the file.
drh734c9862008-11-28 15:37:20 +00002039*/
2040static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00002041 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002042}
2043
2044/******************* End of the no-op lock implementation *********************
2045******************************************************************************/
2046
2047/******************************************************************************
2048************************* Begin dot-file Locking ******************************
2049**
mistachkin48864df2013-03-21 21:20:32 +00002050** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00002051** files (really a directory) to control access to the database. This works
2052** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002053**
2054** (1) There is zero concurrency. A single reader blocks all other
2055** connections from reading or writing the database.
2056**
2057** (2) An application crash or power loss can leave stale lock files
2058** sitting around that need to be cleared manually.
2059**
2060** Nevertheless, a dotlock is an appropriate locking mode for use if no
2061** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002062**
drh9ef6bc42011-11-04 02:24:02 +00002063** Dotfile locking works by creating a subdirectory in the same directory as
2064** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002065** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002066** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002067*/
2068
2069/*
2070** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002071** lock directory.
drh734c9862008-11-28 15:37:20 +00002072*/
2073#define DOTLOCK_SUFFIX ".lock"
2074
drh7708e972008-11-29 00:56:52 +00002075/*
2076** This routine checks if there is a RESERVED lock held on the specified
2077** file by this or any other process. If such a lock is held, set *pResOut
2078** to a non-zero value otherwise *pResOut is set to zero. The return value
2079** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2080**
2081** In dotfile locking, either a lock exists or it does not. So in this
2082** variation of CheckReservedLock(), *pResOut is set to true if any lock
2083** is held on the file and false if the file is unlocked.
2084*/
drh734c9862008-11-28 15:37:20 +00002085static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2086 int rc = SQLITE_OK;
2087 int reserved = 0;
2088 unixFile *pFile = (unixFile*)id;
2089
2090 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2091
2092 assert( pFile );
2093
2094 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002095 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00002096 /* Either this connection or some other connection in the same process
2097 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00002098 reserved = 1;
drh7708e972008-11-29 00:56:52 +00002099 }else{
2100 /* The lock is held if and only if the lockfile exists */
2101 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00002102 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00002103 }
drh308c2a52010-05-14 11:30:18 +00002104 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002105 *pResOut = reserved;
2106 return rc;
2107}
2108
drh7708e972008-11-29 00:56:52 +00002109/*
drh308c2a52010-05-14 11:30:18 +00002110** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002111** of the following:
2112**
2113** (1) SHARED_LOCK
2114** (2) RESERVED_LOCK
2115** (3) PENDING_LOCK
2116** (4) EXCLUSIVE_LOCK
2117**
2118** Sometimes when requesting one lock state, additional lock states
2119** are inserted in between. The locking might fail on one of the later
2120** transitions leaving the lock state different from what it started but
2121** still short of its goal. The following chart shows the allowed
2122** transitions and the inserted intermediate states:
2123**
2124** UNLOCKED -> SHARED
2125** SHARED -> RESERVED
2126** SHARED -> (PENDING) -> EXCLUSIVE
2127** RESERVED -> (PENDING) -> EXCLUSIVE
2128** PENDING -> EXCLUSIVE
2129**
2130** This routine will only increase a lock. Use the sqlite3OsUnlock()
2131** routine to lower a locking level.
2132**
2133** With dotfile locking, we really only support state (4): EXCLUSIVE.
2134** But we track the other locking levels internally.
2135*/
drh308c2a52010-05-14 11:30:18 +00002136static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002137 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002138 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002139 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002140
drh7708e972008-11-29 00:56:52 +00002141
2142 /* If we have any lock, then the lock file already exists. All we have
2143 ** to do is adjust our internal record of the lock level.
2144 */
drh308c2a52010-05-14 11:30:18 +00002145 if( pFile->eFileLock > NO_LOCK ){
2146 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002147 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002148#ifdef HAVE_UTIME
2149 utime(zLockFile, NULL);
2150#else
drh734c9862008-11-28 15:37:20 +00002151 utimes(zLockFile, NULL);
2152#endif
drh7708e972008-11-29 00:56:52 +00002153 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002154 }
2155
2156 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002157 rc = osMkdir(zLockFile, 0777);
2158 if( rc<0 ){
2159 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002160 int tErrno = errno;
2161 if( EEXIST == tErrno ){
2162 rc = SQLITE_BUSY;
2163 } else {
2164 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2165 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002166 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002167 }
2168 }
drh7708e972008-11-29 00:56:52 +00002169 return rc;
drh734c9862008-11-28 15:37:20 +00002170 }
drh734c9862008-11-28 15:37:20 +00002171
2172 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002173 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002174 return rc;
2175}
2176
drh7708e972008-11-29 00:56:52 +00002177/*
drh308c2a52010-05-14 11:30:18 +00002178** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002179** must be either NO_LOCK or SHARED_LOCK.
2180**
2181** If the locking level of the file descriptor is already at or below
2182** the requested locking level, this routine is a no-op.
2183**
2184** When the locking level reaches NO_LOCK, delete the lock file.
2185*/
drh308c2a52010-05-14 11:30:18 +00002186static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002187 unixFile *pFile = (unixFile*)id;
2188 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002189 int rc;
drh734c9862008-11-28 15:37:20 +00002190
2191 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002192 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002193 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002194 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002195
2196 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002197 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002198 return SQLITE_OK;
2199 }
drh7708e972008-11-29 00:56:52 +00002200
2201 /* To downgrade to shared, simply update our internal notion of the
2202 ** lock state. No need to mess with the file on disk.
2203 */
drh308c2a52010-05-14 11:30:18 +00002204 if( eFileLock==SHARED_LOCK ){
2205 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002206 return SQLITE_OK;
2207 }
2208
drh7708e972008-11-29 00:56:52 +00002209 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002210 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002211 rc = osRmdir(zLockFile);
2212 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
2213 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002214 int tErrno = errno;
drh13e0ea92011-12-11 02:29:25 +00002215 rc = 0;
drh734c9862008-11-28 15:37:20 +00002216 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002217 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002218 }
2219 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002220 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002221 }
2222 return rc;
2223 }
drh308c2a52010-05-14 11:30:18 +00002224 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002225 return SQLITE_OK;
2226}
2227
2228/*
drh9b35ea62008-11-29 02:20:26 +00002229** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002230*/
2231static int dotlockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002232 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002233 if( id ){
2234 unixFile *pFile = (unixFile*)id;
2235 dotlockUnlock(id, NO_LOCK);
2236 sqlite3_free(pFile->lockingContext);
drh5a05be12012-10-09 18:51:44 +00002237 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002238 }
drh734c9862008-11-28 15:37:20 +00002239 return rc;
2240}
2241/****************** End of the dot-file lock implementation *******************
2242******************************************************************************/
2243
2244/******************************************************************************
2245************************** Begin flock Locking ********************************
2246**
2247** Use the flock() system call to do file locking.
2248**
drh6b9d6dd2008-12-03 19:34:47 +00002249** flock() locking is like dot-file locking in that the various
2250** fine-grain locking levels supported by SQLite are collapsed into
2251** a single exclusive lock. In other words, SHARED, RESERVED, and
2252** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2253** still works when you do this, but concurrency is reduced since
2254** only a single process can be reading the database at a time.
2255**
drhe89b2912015-03-03 20:42:01 +00002256** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
drh734c9862008-11-28 15:37:20 +00002257*/
drhe89b2912015-03-03 20:42:01 +00002258#if SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002259
drh6b9d6dd2008-12-03 19:34:47 +00002260/*
drhff812312011-02-23 13:33:46 +00002261** Retry flock() calls that fail with EINTR
2262*/
2263#ifdef EINTR
2264static int robust_flock(int fd, int op){
2265 int rc;
2266 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2267 return rc;
2268}
2269#else
drh5c819272011-02-23 14:00:12 +00002270# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002271#endif
2272
2273
2274/*
drh6b9d6dd2008-12-03 19:34:47 +00002275** This routine checks if there is a RESERVED lock held on the specified
2276** file by this or any other process. If such a lock is held, set *pResOut
2277** to a non-zero value otherwise *pResOut is set to zero. The return value
2278** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2279*/
drh734c9862008-11-28 15:37:20 +00002280static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2281 int rc = SQLITE_OK;
2282 int reserved = 0;
2283 unixFile *pFile = (unixFile*)id;
2284
2285 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2286
2287 assert( pFile );
2288
2289 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002290 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002291 reserved = 1;
2292 }
2293
2294 /* Otherwise see if some other process holds it. */
2295 if( !reserved ){
2296 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002297 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002298 if( !lrc ){
2299 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002300 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002301 if ( lrc ) {
2302 int tErrno = errno;
2303 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002304 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002305 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002306 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002307 rc = lrc;
2308 }
2309 }
2310 } else {
2311 int tErrno = errno;
2312 reserved = 1;
2313 /* someone else might have it reserved */
2314 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2315 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002316 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002317 rc = lrc;
2318 }
2319 }
2320 }
drh308c2a52010-05-14 11:30:18 +00002321 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002322
2323#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2324 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2325 rc = SQLITE_OK;
2326 reserved=1;
2327 }
2328#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2329 *pResOut = reserved;
2330 return rc;
2331}
2332
drh6b9d6dd2008-12-03 19:34:47 +00002333/*
drh308c2a52010-05-14 11:30:18 +00002334** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002335** of the following:
2336**
2337** (1) SHARED_LOCK
2338** (2) RESERVED_LOCK
2339** (3) PENDING_LOCK
2340** (4) EXCLUSIVE_LOCK
2341**
2342** Sometimes when requesting one lock state, additional lock states
2343** are inserted in between. The locking might fail on one of the later
2344** transitions leaving the lock state different from what it started but
2345** still short of its goal. The following chart shows the allowed
2346** transitions and the inserted intermediate states:
2347**
2348** UNLOCKED -> SHARED
2349** SHARED -> RESERVED
2350** SHARED -> (PENDING) -> EXCLUSIVE
2351** RESERVED -> (PENDING) -> EXCLUSIVE
2352** PENDING -> EXCLUSIVE
2353**
2354** flock() only really support EXCLUSIVE locks. We track intermediate
2355** lock states in the sqlite3_file structure, but all locks SHARED or
2356** above are really EXCLUSIVE locks and exclude all other processes from
2357** access the file.
2358**
2359** This routine will only increase a lock. Use the sqlite3OsUnlock()
2360** routine to lower a locking level.
2361*/
drh308c2a52010-05-14 11:30:18 +00002362static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002363 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002364 unixFile *pFile = (unixFile*)id;
2365
2366 assert( pFile );
2367
2368 /* if we already have a lock, it is exclusive.
2369 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002370 if (pFile->eFileLock > NO_LOCK) {
2371 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002372 return SQLITE_OK;
2373 }
2374
2375 /* grab an exclusive lock */
2376
drhff812312011-02-23 13:33:46 +00002377 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002378 int tErrno = errno;
2379 /* didn't get, must be busy */
2380 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2381 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002382 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002383 }
2384 } else {
2385 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002386 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002387 }
drh308c2a52010-05-14 11:30:18 +00002388 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2389 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002390#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2391 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2392 rc = SQLITE_BUSY;
2393 }
2394#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2395 return rc;
2396}
2397
drh6b9d6dd2008-12-03 19:34:47 +00002398
2399/*
drh308c2a52010-05-14 11:30:18 +00002400** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002401** must be either NO_LOCK or SHARED_LOCK.
2402**
2403** If the locking level of the file descriptor is already at or below
2404** the requested locking level, this routine is a no-op.
2405*/
drh308c2a52010-05-14 11:30:18 +00002406static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002407 unixFile *pFile = (unixFile*)id;
2408
2409 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002410 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002411 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002412 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002413
2414 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002415 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002416 return SQLITE_OK;
2417 }
2418
2419 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002420 if (eFileLock==SHARED_LOCK) {
2421 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002422 return SQLITE_OK;
2423 }
2424
2425 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002426 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002427#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002428 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002429#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002430 return SQLITE_IOERR_UNLOCK;
2431 }else{
drh308c2a52010-05-14 11:30:18 +00002432 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002433 return SQLITE_OK;
2434 }
2435}
2436
2437/*
2438** Close a file.
2439*/
2440static int flockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002441 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002442 if( id ){
2443 flockUnlock(id, NO_LOCK);
drh5a05be12012-10-09 18:51:44 +00002444 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002445 }
drh5a05be12012-10-09 18:51:44 +00002446 return rc;
drh734c9862008-11-28 15:37:20 +00002447}
2448
2449#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2450
2451/******************* End of the flock lock implementation *********************
2452******************************************************************************/
2453
2454/******************************************************************************
2455************************ Begin Named Semaphore Locking ************************
2456**
2457** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002458**
2459** Semaphore locking is like dot-lock and flock in that it really only
2460** supports EXCLUSIVE locking. Only a single process can read or write
2461** the database file at a time. This reduces potential concurrency, but
2462** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002463*/
2464#if OS_VXWORKS
2465
drh6b9d6dd2008-12-03 19:34:47 +00002466/*
2467** This routine checks if there is a RESERVED lock held on the specified
2468** file by this or any other process. If such a lock is held, set *pResOut
2469** to a non-zero value otherwise *pResOut is set to zero. The return value
2470** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2471*/
drh8cd5b252015-03-02 22:06:43 +00002472static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
drh734c9862008-11-28 15:37:20 +00002473 int rc = SQLITE_OK;
2474 int reserved = 0;
2475 unixFile *pFile = (unixFile*)id;
2476
2477 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2478
2479 assert( pFile );
2480
2481 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002482 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002483 reserved = 1;
2484 }
2485
2486 /* Otherwise see if some other process holds it. */
2487 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002488 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002489
2490 if( sem_trywait(pSem)==-1 ){
2491 int tErrno = errno;
2492 if( EAGAIN != tErrno ){
2493 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
drh4bf66fd2015-02-19 02:43:02 +00002494 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002495 } else {
2496 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002497 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002498 }
2499 }else{
2500 /* we could have it if we want it */
2501 sem_post(pSem);
2502 }
2503 }
drh308c2a52010-05-14 11:30:18 +00002504 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002505
2506 *pResOut = reserved;
2507 return rc;
2508}
2509
drh6b9d6dd2008-12-03 19:34:47 +00002510/*
drh308c2a52010-05-14 11:30:18 +00002511** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002512** of the following:
2513**
2514** (1) SHARED_LOCK
2515** (2) RESERVED_LOCK
2516** (3) PENDING_LOCK
2517** (4) EXCLUSIVE_LOCK
2518**
2519** Sometimes when requesting one lock state, additional lock states
2520** are inserted in between. The locking might fail on one of the later
2521** transitions leaving the lock state different from what it started but
2522** still short of its goal. The following chart shows the allowed
2523** transitions and the inserted intermediate states:
2524**
2525** UNLOCKED -> SHARED
2526** SHARED -> RESERVED
2527** SHARED -> (PENDING) -> EXCLUSIVE
2528** RESERVED -> (PENDING) -> EXCLUSIVE
2529** PENDING -> EXCLUSIVE
2530**
2531** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2532** lock states in the sqlite3_file structure, but all locks SHARED or
2533** above are really EXCLUSIVE locks and exclude all other processes from
2534** access the file.
2535**
2536** This routine will only increase a lock. Use the sqlite3OsUnlock()
2537** routine to lower a locking level.
2538*/
drh8cd5b252015-03-02 22:06:43 +00002539static int semXLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002540 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002541 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002542 int rc = SQLITE_OK;
2543
2544 /* if we already have a lock, it is exclusive.
2545 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002546 if (pFile->eFileLock > NO_LOCK) {
2547 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002548 rc = SQLITE_OK;
2549 goto sem_end_lock;
2550 }
2551
2552 /* lock semaphore now but bail out when already locked. */
2553 if( sem_trywait(pSem)==-1 ){
2554 rc = SQLITE_BUSY;
2555 goto sem_end_lock;
2556 }
2557
2558 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002559 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002560
2561 sem_end_lock:
2562 return rc;
2563}
2564
drh6b9d6dd2008-12-03 19:34:47 +00002565/*
drh308c2a52010-05-14 11:30:18 +00002566** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002567** must be either NO_LOCK or SHARED_LOCK.
2568**
2569** If the locking level of the file descriptor is already at or below
2570** the requested locking level, this routine is a no-op.
2571*/
drh8cd5b252015-03-02 22:06:43 +00002572static int semXUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002573 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002574 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002575
2576 assert( pFile );
2577 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002578 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002579 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002580 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002581
2582 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002583 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002584 return SQLITE_OK;
2585 }
2586
2587 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002588 if (eFileLock==SHARED_LOCK) {
2589 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002590 return SQLITE_OK;
2591 }
2592
2593 /* no, really unlock. */
2594 if ( sem_post(pSem)==-1 ) {
2595 int rc, tErrno = errno;
2596 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2597 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002598 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002599 }
2600 return rc;
2601 }
drh308c2a52010-05-14 11:30:18 +00002602 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002603 return SQLITE_OK;
2604}
2605
2606/*
2607 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002608 */
drh8cd5b252015-03-02 22:06:43 +00002609static int semXClose(sqlite3_file *id) {
drh734c9862008-11-28 15:37:20 +00002610 if( id ){
2611 unixFile *pFile = (unixFile*)id;
drh8cd5b252015-03-02 22:06:43 +00002612 semXUnlock(id, NO_LOCK);
drh734c9862008-11-28 15:37:20 +00002613 assert( pFile );
2614 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002615 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002616 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002617 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002618 }
2619 return SQLITE_OK;
2620}
2621
2622#endif /* OS_VXWORKS */
2623/*
2624** Named semaphore locking is only available on VxWorks.
2625**
2626*************** End of the named semaphore lock implementation ****************
2627******************************************************************************/
2628
2629
2630/******************************************************************************
2631*************************** Begin AFP Locking *********************************
2632**
2633** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2634** on Apple Macintosh computers - both OS9 and OSX.
2635**
2636** Third-party implementations of AFP are available. But this code here
2637** only works on OSX.
2638*/
2639
drhd2cb50b2009-01-09 21:41:17 +00002640#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002641/*
2642** The afpLockingContext structure contains all afp lock specific state
2643*/
drhbfe66312006-10-03 17:40:40 +00002644typedef struct afpLockingContext afpLockingContext;
2645struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002646 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002647 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002648};
2649
2650struct ByteRangeLockPB2
2651{
2652 unsigned long long offset; /* offset to first byte to lock */
2653 unsigned long long length; /* nbr of bytes to lock */
2654 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2655 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2656 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2657 int fd; /* file desc to assoc this lock with */
2658};
2659
drhfd131da2007-08-07 17:13:03 +00002660#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002661
drh6b9d6dd2008-12-03 19:34:47 +00002662/*
2663** This is a utility for setting or clearing a bit-range lock on an
2664** AFP filesystem.
2665**
2666** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2667*/
2668static int afpSetLock(
2669 const char *path, /* Name of the file to be locked or unlocked */
2670 unixFile *pFile, /* Open file descriptor on path */
2671 unsigned long long offset, /* First byte to be locked */
2672 unsigned long long length, /* Number of bytes to lock */
2673 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002674){
drh6b9d6dd2008-12-03 19:34:47 +00002675 struct ByteRangeLockPB2 pb;
2676 int err;
drhbfe66312006-10-03 17:40:40 +00002677
2678 pb.unLockFlag = setLockFlag ? 0 : 1;
2679 pb.startEndFlag = 0;
2680 pb.offset = offset;
2681 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002682 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002683
drh308c2a52010-05-14 11:30:18 +00002684 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002685 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002686 offset, length));
drhbfe66312006-10-03 17:40:40 +00002687 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2688 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002689 int rc;
2690 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002691 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2692 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002693#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2694 rc = SQLITE_BUSY;
2695#else
drh734c9862008-11-28 15:37:20 +00002696 rc = sqliteErrorFromPosixError(tErrno,
2697 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002698#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002699 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002700 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00002701 }
2702 return rc;
drhbfe66312006-10-03 17:40:40 +00002703 } else {
aswift5b1a2562008-08-22 00:22:35 +00002704 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002705 }
2706}
2707
drh6b9d6dd2008-12-03 19:34:47 +00002708/*
2709** This routine checks if there is a RESERVED lock held on the specified
2710** file by this or any other process. If such a lock is held, set *pResOut
2711** to a non-zero value otherwise *pResOut is set to zero. The return value
2712** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2713*/
danielk1977e339d652008-06-28 11:23:00 +00002714static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002715 int rc = SQLITE_OK;
2716 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002717 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002718 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002719
aswift5b1a2562008-08-22 00:22:35 +00002720 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2721
2722 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002723 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002724 if( context->reserved ){
2725 *pResOut = 1;
2726 return SQLITE_OK;
2727 }
drh8af6c222010-05-14 12:43:01 +00002728 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002729
2730 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002731 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002732 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002733 }
2734
2735 /* Otherwise see if some other process holds it.
2736 */
aswift5b1a2562008-08-22 00:22:35 +00002737 if( !reserved ){
2738 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002739 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002740 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002741 /* if we succeeded in taking the reserved lock, unlock it to restore
2742 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002743 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002744 } else {
2745 /* if we failed to get the lock then someone else must have it */
2746 reserved = 1;
2747 }
2748 if( IS_LOCK_ERROR(lrc) ){
2749 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002750 }
2751 }
drhbfe66312006-10-03 17:40:40 +00002752
drh7ed97b92010-01-20 13:07:21 +00002753 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002754 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002755
2756 *pResOut = reserved;
2757 return rc;
drhbfe66312006-10-03 17:40:40 +00002758}
2759
drh6b9d6dd2008-12-03 19:34:47 +00002760/*
drh308c2a52010-05-14 11:30:18 +00002761** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002762** of the following:
2763**
2764** (1) SHARED_LOCK
2765** (2) RESERVED_LOCK
2766** (3) PENDING_LOCK
2767** (4) EXCLUSIVE_LOCK
2768**
2769** Sometimes when requesting one lock state, additional lock states
2770** are inserted in between. The locking might fail on one of the later
2771** transitions leaving the lock state different from what it started but
2772** still short of its goal. The following chart shows the allowed
2773** transitions and the inserted intermediate states:
2774**
2775** UNLOCKED -> SHARED
2776** SHARED -> RESERVED
2777** SHARED -> (PENDING) -> EXCLUSIVE
2778** RESERVED -> (PENDING) -> EXCLUSIVE
2779** PENDING -> EXCLUSIVE
2780**
2781** This routine will only increase a lock. Use the sqlite3OsUnlock()
2782** routine to lower a locking level.
2783*/
drh308c2a52010-05-14 11:30:18 +00002784static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002785 int rc = SQLITE_OK;
2786 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002787 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002788 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002789
2790 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002791 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2792 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh5ac93652015-03-21 20:59:43 +00002793 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
drh339eb0b2008-03-07 15:34:11 +00002794
drhbfe66312006-10-03 17:40:40 +00002795 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002796 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002797 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002798 */
drh308c2a52010-05-14 11:30:18 +00002799 if( pFile->eFileLock>=eFileLock ){
2800 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2801 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002802 return SQLITE_OK;
2803 }
2804
2805 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002806 ** (1) We never move from unlocked to anything higher than shared lock.
2807 ** (2) SQLite never explicitly requests a pendig lock.
2808 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002809 */
drh308c2a52010-05-14 11:30:18 +00002810 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2811 assert( eFileLock!=PENDING_LOCK );
2812 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002813
drh8af6c222010-05-14 12:43:01 +00002814 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002815 */
drh6c7d5c52008-11-21 20:32:33 +00002816 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002817 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002818
2819 /* If some thread using this PID has a lock via a different unixFile*
2820 ** handle that precludes the requested lock, return BUSY.
2821 */
drh8af6c222010-05-14 12:43:01 +00002822 if( (pFile->eFileLock!=pInode->eFileLock &&
2823 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002824 ){
2825 rc = SQLITE_BUSY;
2826 goto afp_end_lock;
2827 }
2828
2829 /* If a SHARED lock is requested, and some thread using this PID already
2830 ** has a SHARED or RESERVED lock, then increment reference counts and
2831 ** return SQLITE_OK.
2832 */
drh308c2a52010-05-14 11:30:18 +00002833 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002834 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002835 assert( eFileLock==SHARED_LOCK );
2836 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002837 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002838 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002839 pInode->nShared++;
2840 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002841 goto afp_end_lock;
2842 }
drhbfe66312006-10-03 17:40:40 +00002843
2844 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002845 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2846 ** be released.
2847 */
drh308c2a52010-05-14 11:30:18 +00002848 if( eFileLock==SHARED_LOCK
2849 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002850 ){
2851 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002852 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002853 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002854 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002855 goto afp_end_lock;
2856 }
2857 }
2858
2859 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002860 ** operating system calls for the specified lock.
2861 */
drh308c2a52010-05-14 11:30:18 +00002862 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002863 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002864 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002865
drh8af6c222010-05-14 12:43:01 +00002866 assert( pInode->nShared==0 );
2867 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002868
2869 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002870 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002871 /* note that the quality of the randomness doesn't matter that much */
2872 lk = random();
drh8af6c222010-05-14 12:43:01 +00002873 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002874 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002875 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002876 if( IS_LOCK_ERROR(lrc1) ){
2877 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002878 }
aswift5b1a2562008-08-22 00:22:35 +00002879 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002880 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002881
aswift5b1a2562008-08-22 00:22:35 +00002882 if( IS_LOCK_ERROR(lrc1) ) {
drh4bf66fd2015-02-19 02:43:02 +00002883 storeLastErrno(pFile, lrc1Errno);
aswift5b1a2562008-08-22 00:22:35 +00002884 rc = lrc1;
2885 goto afp_end_lock;
2886 } else if( IS_LOCK_ERROR(lrc2) ){
2887 rc = lrc2;
2888 goto afp_end_lock;
2889 } else if( lrc1 != SQLITE_OK ) {
2890 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002891 } else {
drh308c2a52010-05-14 11:30:18 +00002892 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002893 pInode->nLock++;
2894 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002895 }
drh8af6c222010-05-14 12:43:01 +00002896 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002897 /* We are trying for an exclusive lock but another thread in this
2898 ** same process is still holding a shared lock. */
2899 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002900 }else{
2901 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2902 ** assumed that there is a SHARED or greater lock on the file
2903 ** already.
2904 */
2905 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002906 assert( 0!=pFile->eFileLock );
2907 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002908 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002909 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002910 if( !failed ){
2911 context->reserved = 1;
2912 }
drhbfe66312006-10-03 17:40:40 +00002913 }
drh308c2a52010-05-14 11:30:18 +00002914 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002915 /* Acquire an EXCLUSIVE lock */
2916
2917 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002918 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002919 */
drh6b9d6dd2008-12-03 19:34:47 +00002920 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002921 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002922 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002923 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002924 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002925 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002926 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002927 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002928 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2929 ** a critical I/O error
2930 */
2931 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2932 SQLITE_IOERR_LOCK;
2933 goto afp_end_lock;
2934 }
2935 }else{
aswift5b1a2562008-08-22 00:22:35 +00002936 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002937 }
2938 }
aswift5b1a2562008-08-22 00:22:35 +00002939 if( failed ){
2940 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002941 }
2942 }
2943
2944 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002945 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002946 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002947 }else if( eFileLock==EXCLUSIVE_LOCK ){
2948 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002949 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002950 }
2951
2952afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002953 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002954 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2955 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002956 return rc;
2957}
2958
2959/*
drh308c2a52010-05-14 11:30:18 +00002960** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002961** must be either NO_LOCK or SHARED_LOCK.
2962**
2963** If the locking level of the file descriptor is already at or below
2964** the requested locking level, this routine is a no-op.
2965*/
drh308c2a52010-05-14 11:30:18 +00002966static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002967 int rc = SQLITE_OK;
2968 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002969 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002970 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2971 int skipShared = 0;
2972#ifdef SQLITE_TEST
2973 int h = pFile->h;
2974#endif
drhbfe66312006-10-03 17:40:40 +00002975
2976 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002977 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002978 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00002979 osGetpid(0)));
aswift5b1a2562008-08-22 00:22:35 +00002980
drh308c2a52010-05-14 11:30:18 +00002981 assert( eFileLock<=SHARED_LOCK );
2982 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002983 return SQLITE_OK;
2984 }
drh6c7d5c52008-11-21 20:32:33 +00002985 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002986 pInode = pFile->pInode;
2987 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002988 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002989 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002990 SimulateIOErrorBenign(1);
2991 SimulateIOError( h=(-1) )
2992 SimulateIOErrorBenign(0);
2993
drhd3d8c042012-05-29 17:02:40 +00002994#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002995 /* When reducing a lock such that other processes can start
2996 ** reading the database file again, make sure that the
2997 ** transaction counter was updated if any part of the database
2998 ** file changed. If the transaction counter is not updated,
2999 ** other connections to the same file might not realize that
3000 ** the file has changed and hence might not know to flush their
3001 ** cache. The use of a stale cache can lead to database corruption.
3002 */
3003 assert( pFile->inNormalWrite==0
3004 || pFile->dbUpdate==0
3005 || pFile->transCntrChng==1 );
3006 pFile->inNormalWrite = 0;
3007#endif
aswiftaebf4132008-11-21 00:10:35 +00003008
drh308c2a52010-05-14 11:30:18 +00003009 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00003010 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00003011 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00003012 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00003013 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00003014 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
3015 } else {
3016 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00003017 }
3018 }
drh308c2a52010-05-14 11:30:18 +00003019 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00003020 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00003021 }
drh308c2a52010-05-14 11:30:18 +00003022 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00003023 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
3024 if( !rc ){
3025 context->reserved = 0;
3026 }
aswiftaebf4132008-11-21 00:10:35 +00003027 }
drh8af6c222010-05-14 12:43:01 +00003028 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
3029 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003030 }
aswiftaebf4132008-11-21 00:10:35 +00003031 }
drh308c2a52010-05-14 11:30:18 +00003032 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00003033
drh7ed97b92010-01-20 13:07:21 +00003034 /* Decrement the shared lock counter. Release the lock using an
3035 ** OS call only when all threads in this same process have released
3036 ** the lock.
3037 */
drh8af6c222010-05-14 12:43:01 +00003038 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3039 pInode->nShared--;
3040 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00003041 SimulateIOErrorBenign(1);
3042 SimulateIOError( h=(-1) )
3043 SimulateIOErrorBenign(0);
3044 if( !skipShared ){
3045 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
3046 }
3047 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00003048 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00003049 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003050 }
3051 }
3052 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00003053 pInode->nLock--;
3054 assert( pInode->nLock>=0 );
3055 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00003056 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00003057 }
3058 }
drhbfe66312006-10-03 17:40:40 +00003059 }
drh7ed97b92010-01-20 13:07:21 +00003060
drh6c7d5c52008-11-21 20:32:33 +00003061 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00003062 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00003063 return rc;
3064}
3065
3066/*
drh339eb0b2008-03-07 15:34:11 +00003067** Close a file & cleanup AFP specific locking context
3068*/
danielk1977e339d652008-06-28 11:23:00 +00003069static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003070 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00003071 if( id ){
3072 unixFile *pFile = (unixFile*)id;
3073 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00003074 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00003075 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00003076 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00003077 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00003078 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00003079 ** the last lock is cleared.
3080 */
dan08da86a2009-08-21 17:18:03 +00003081 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00003082 }
danb0ac3e32010-06-16 10:55:42 +00003083 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003084 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00003085 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00003086 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00003087 }
drh7ed97b92010-01-20 13:07:21 +00003088 return rc;
drhbfe66312006-10-03 17:40:40 +00003089}
3090
drhd2cb50b2009-01-09 21:41:17 +00003091#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003092/*
3093** The code above is the AFP lock implementation. The code is specific
3094** to MacOSX and does not work on other unix platforms. No alternative
3095** is available. If you don't compile for a mac, then the "unix-afp"
3096** VFS is not available.
3097**
3098********************* End of the AFP lock implementation **********************
3099******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003100
drh7ed97b92010-01-20 13:07:21 +00003101/******************************************************************************
3102*************************** Begin NFS Locking ********************************/
3103
3104#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3105/*
drh308c2a52010-05-14 11:30:18 +00003106 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003107 ** must be either NO_LOCK or SHARED_LOCK.
3108 **
3109 ** If the locking level of the file descriptor is already at or below
3110 ** the requested locking level, this routine is a no-op.
3111 */
drh308c2a52010-05-14 11:30:18 +00003112static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003113 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003114}
3115
3116#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3117/*
3118** The code above is the NFS lock implementation. The code is specific
3119** to MacOSX and does not work on other unix platforms. No alternative
3120** is available.
3121**
3122********************* End of the NFS lock implementation **********************
3123******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003124
3125/******************************************************************************
3126**************** Non-locking sqlite3_file methods *****************************
3127**
3128** The next division contains implementations for all methods of the
3129** sqlite3_file object other than the locking methods. The locking
3130** methods were defined in divisions above (one locking method per
3131** division). Those methods that are common to all locking modes
3132** are gather together into this division.
3133*/
drhbfe66312006-10-03 17:40:40 +00003134
3135/*
drh734c9862008-11-28 15:37:20 +00003136** Seek to the offset passed as the second argument, then read cnt
3137** bytes into pBuf. Return the number of bytes actually read.
3138**
3139** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3140** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3141** one system to another. Since SQLite does not define USE_PREAD
peter.d.reid60ec9142014-09-06 16:39:46 +00003142** in any form by default, we will not attempt to define _XOPEN_SOURCE.
drh734c9862008-11-28 15:37:20 +00003143** See tickets #2741 and #2681.
3144**
3145** To avoid stomping the errno value on a failed read the lastErrno value
3146** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003147*/
drh734c9862008-11-28 15:37:20 +00003148static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3149 int got;
drh58024642011-11-07 18:16:00 +00003150 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003151#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003152 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003153#endif
drh734c9862008-11-28 15:37:20 +00003154 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003155 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003156 assert( id->h>2 );
drh58024642011-11-07 18:16:00 +00003157 do{
drh734c9862008-11-28 15:37:20 +00003158#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003159 got = osPread(id->h, pBuf, cnt, offset);
3160 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003161#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003162 got = osPread64(id->h, pBuf, cnt, offset);
3163 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003164#else
drh58024642011-11-07 18:16:00 +00003165 newOffset = lseek(id->h, offset, SEEK_SET);
3166 SimulateIOError( newOffset-- );
3167 if( newOffset!=offset ){
3168 if( newOffset == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00003169 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003170 }else{
drh4bf66fd2015-02-19 02:43:02 +00003171 storeLastErrno((unixFile*)id, 0);
drh58024642011-11-07 18:16:00 +00003172 }
3173 return -1;
drh734c9862008-11-28 15:37:20 +00003174 }
drh58024642011-11-07 18:16:00 +00003175 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003176#endif
drh58024642011-11-07 18:16:00 +00003177 if( got==cnt ) break;
3178 if( got<0 ){
3179 if( errno==EINTR ){ got = 1; continue; }
3180 prior = 0;
drh4bf66fd2015-02-19 02:43:02 +00003181 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003182 break;
3183 }else if( got>0 ){
3184 cnt -= got;
3185 offset += got;
3186 prior += got;
3187 pBuf = (void*)(got + (char*)pBuf);
3188 }
3189 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003190 TIMER_END;
drh58024642011-11-07 18:16:00 +00003191 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3192 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3193 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003194}
3195
3196/*
drh734c9862008-11-28 15:37:20 +00003197** Read data from a file into a buffer. Return SQLITE_OK if all
3198** bytes were read successfully and SQLITE_IOERR if anything goes
3199** wrong.
drh339eb0b2008-03-07 15:34:11 +00003200*/
drh734c9862008-11-28 15:37:20 +00003201static int unixRead(
3202 sqlite3_file *id,
3203 void *pBuf,
3204 int amt,
3205 sqlite3_int64 offset
3206){
dan08da86a2009-08-21 17:18:03 +00003207 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003208 int got;
3209 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003210 assert( offset>=0 );
3211 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003212
dan08da86a2009-08-21 17:18:03 +00003213 /* If this is a database file (not a journal, master-journal or temp
3214 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003215#if 0
dane946c392009-08-22 11:39:46 +00003216 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003217 || offset>=PENDING_BYTE+512
3218 || offset+amt<=PENDING_BYTE
3219 );
dan7c246102010-04-12 19:00:29 +00003220#endif
drh08c6d442009-02-09 17:34:07 +00003221
drh9b4c59f2013-04-15 17:03:42 +00003222#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003223 /* Deal with as much of this read request as possible by transfering
3224 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003225 if( offset<pFile->mmapSize ){
3226 if( offset+amt <= pFile->mmapSize ){
3227 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3228 return SQLITE_OK;
3229 }else{
3230 int nCopy = pFile->mmapSize - offset;
3231 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3232 pBuf = &((u8 *)pBuf)[nCopy];
3233 amt -= nCopy;
3234 offset += nCopy;
3235 }
3236 }
drh6e0b6d52013-04-09 16:19:20 +00003237#endif
danf23da962013-03-23 21:00:41 +00003238
dan08da86a2009-08-21 17:18:03 +00003239 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003240 if( got==amt ){
3241 return SQLITE_OK;
3242 }else if( got<0 ){
3243 /* lastErrno set by seekAndRead */
3244 return SQLITE_IOERR_READ;
3245 }else{
drh4bf66fd2015-02-19 02:43:02 +00003246 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003247 /* Unread parts of the buffer must be zero-filled */
3248 memset(&((char*)pBuf)[got], 0, amt-got);
3249 return SQLITE_IOERR_SHORT_READ;
3250 }
3251}
3252
3253/*
dan47a2b4a2013-04-26 16:09:29 +00003254** Attempt to seek the file-descriptor passed as the first argument to
3255** absolute offset iOff, then attempt to write nBuf bytes of data from
3256** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3257** return the actual number of bytes written (which may be less than
3258** nBuf).
3259*/
3260static int seekAndWriteFd(
3261 int fd, /* File descriptor to write to */
3262 i64 iOff, /* File offset to begin writing at */
3263 const void *pBuf, /* Copy data from this buffer to the file */
3264 int nBuf, /* Size of buffer pBuf in bytes */
3265 int *piErrno /* OUT: Error number if error occurs */
3266){
3267 int rc = 0; /* Value returned by system call */
3268
3269 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003270 assert( fd>2 );
dan47a2b4a2013-04-26 16:09:29 +00003271 nBuf &= 0x1ffff;
3272 TIMER_START;
3273
3274#if defined(USE_PREAD)
drh2da47d32015-02-21 00:56:05 +00003275 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
dan47a2b4a2013-04-26 16:09:29 +00003276#elif defined(USE_PREAD64)
drh2da47d32015-02-21 00:56:05 +00003277 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
dan47a2b4a2013-04-26 16:09:29 +00003278#else
3279 do{
3280 i64 iSeek = lseek(fd, iOff, SEEK_SET);
3281 SimulateIOError( iSeek-- );
3282
3283 if( iSeek!=iOff ){
3284 if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
3285 return -1;
3286 }
3287 rc = osWrite(fd, pBuf, nBuf);
3288 }while( rc<0 && errno==EINTR );
3289#endif
3290
3291 TIMER_END;
3292 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3293
3294 if( rc<0 && piErrno ) *piErrno = errno;
3295 return rc;
3296}
3297
3298
3299/*
drh734c9862008-11-28 15:37:20 +00003300** Seek to the offset in id->offset then read cnt bytes into pBuf.
3301** Return the number of bytes actually read. Update the offset.
3302**
3303** To avoid stomping the errno value on a failed write the lastErrno value
3304** is set before returning.
3305*/
3306static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003307 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003308}
3309
3310
3311/*
3312** Write data from a buffer into a file. Return SQLITE_OK on success
3313** or some other error code on failure.
3314*/
3315static int unixWrite(
3316 sqlite3_file *id,
3317 const void *pBuf,
3318 int amt,
3319 sqlite3_int64 offset
3320){
dan08da86a2009-08-21 17:18:03 +00003321 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003322 int wrote = 0;
3323 assert( id );
3324 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003325
dan08da86a2009-08-21 17:18:03 +00003326 /* If this is a database file (not a journal, master-journal or temp
3327 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003328#if 0
dane946c392009-08-22 11:39:46 +00003329 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003330 || offset>=PENDING_BYTE+512
3331 || offset+amt<=PENDING_BYTE
3332 );
dan7c246102010-04-12 19:00:29 +00003333#endif
drh08c6d442009-02-09 17:34:07 +00003334
drhd3d8c042012-05-29 17:02:40 +00003335#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003336 /* If we are doing a normal write to a database file (as opposed to
3337 ** doing a hot-journal rollback or a write to some file other than a
3338 ** normal database file) then record the fact that the database
3339 ** has changed. If the transaction counter is modified, record that
3340 ** fact too.
3341 */
dan08da86a2009-08-21 17:18:03 +00003342 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003343 pFile->dbUpdate = 1; /* The database has been modified */
3344 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003345 int rc;
drh8f941bc2009-01-14 23:03:40 +00003346 char oldCntr[4];
3347 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003348 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003349 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003350 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003351 pFile->transCntrChng = 1; /* The transaction counter has changed */
3352 }
3353 }
3354 }
3355#endif
3356
danfe33e392015-11-17 20:56:06 +00003357#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003358 /* Deal with as much of this write request as possible by transfering
3359 ** data from the memory mapping using memcpy(). */
3360 if( offset<pFile->mmapSize ){
3361 if( offset+amt <= pFile->mmapSize ){
3362 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3363 return SQLITE_OK;
3364 }else{
3365 int nCopy = pFile->mmapSize - offset;
3366 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3367 pBuf = &((u8 *)pBuf)[nCopy];
3368 amt -= nCopy;
3369 offset += nCopy;
3370 }
3371 }
drh6e0b6d52013-04-09 16:19:20 +00003372#endif
drh02bf8b42015-09-01 23:51:53 +00003373
3374 while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
drh734c9862008-11-28 15:37:20 +00003375 amt -= wrote;
3376 offset += wrote;
3377 pBuf = &((char*)pBuf)[wrote];
3378 }
3379 SimulateIOError(( wrote=(-1), amt=1 ));
3380 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003381
drh02bf8b42015-09-01 23:51:53 +00003382 if( amt>wrote ){
drha21b83b2011-04-15 12:36:10 +00003383 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003384 /* lastErrno set by seekAndWrite */
3385 return SQLITE_IOERR_WRITE;
3386 }else{
drh4bf66fd2015-02-19 02:43:02 +00003387 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003388 return SQLITE_FULL;
3389 }
3390 }
dan6e09d692010-07-27 18:34:15 +00003391
drh734c9862008-11-28 15:37:20 +00003392 return SQLITE_OK;
3393}
3394
3395#ifdef SQLITE_TEST
3396/*
3397** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003398** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003399*/
3400int sqlite3_sync_count = 0;
3401int sqlite3_fullsync_count = 0;
3402#endif
3403
3404/*
drh89240432009-03-25 01:06:01 +00003405** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003406** Others do no. To be safe, we will stick with the (slightly slower)
3407** fsync(). If you know that your system does support fdatasync() correctly,
drhf7a4a1b2015-01-10 18:02:45 +00003408** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003409*/
drhf7a4a1b2015-01-10 18:02:45 +00003410#if !defined(fdatasync) && !HAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003411# define fdatasync fsync
3412#endif
3413
3414/*
3415** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3416** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3417** only available on Mac OS X. But that could change.
3418*/
3419#ifdef F_FULLFSYNC
3420# define HAVE_FULLFSYNC 1
3421#else
3422# define HAVE_FULLFSYNC 0
3423#endif
3424
3425
3426/*
3427** The fsync() system call does not work as advertised on many
3428** unix systems. The following procedure is an attempt to make
3429** it work better.
3430**
3431** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3432** for testing when we want to run through the test suite quickly.
3433** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3434** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3435** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003436**
3437** SQLite sets the dataOnly flag if the size of the file is unchanged.
3438** The idea behind dataOnly is that it should only write the file content
3439** to disk, not the inode. We only set dataOnly if the file size is
3440** unchanged since the file size is part of the inode. However,
3441** Ted Ts'o tells us that fdatasync() will also write the inode if the
3442** file size has changed. The only real difference between fdatasync()
3443** and fsync(), Ted tells us, is that fdatasync() will not flush the
3444** inode if the mtime or owner or other inode attributes have changed.
3445** We only care about the file size, not the other file attributes, so
3446** as far as SQLite is concerned, an fdatasync() is always adequate.
3447** So, we always use fdatasync() if it is available, regardless of
3448** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003449*/
3450static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003451 int rc;
drh734c9862008-11-28 15:37:20 +00003452
3453 /* The following "ifdef/elif/else/" block has the same structure as
3454 ** the one below. It is replicated here solely to avoid cluttering
3455 ** up the real code with the UNUSED_PARAMETER() macros.
3456 */
3457#ifdef SQLITE_NO_SYNC
3458 UNUSED_PARAMETER(fd);
3459 UNUSED_PARAMETER(fullSync);
3460 UNUSED_PARAMETER(dataOnly);
3461#elif HAVE_FULLFSYNC
3462 UNUSED_PARAMETER(dataOnly);
3463#else
3464 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003465 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003466#endif
3467
3468 /* Record the number of times that we do a normal fsync() and
3469 ** FULLSYNC. This is used during testing to verify that this procedure
3470 ** gets called with the correct arguments.
3471 */
3472#ifdef SQLITE_TEST
3473 if( fullSync ) sqlite3_fullsync_count++;
3474 sqlite3_sync_count++;
3475#endif
3476
3477 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3478 ** no-op
3479 */
3480#ifdef SQLITE_NO_SYNC
3481 rc = SQLITE_OK;
3482#elif HAVE_FULLFSYNC
3483 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003484 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003485 }else{
3486 rc = 1;
3487 }
3488 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003489 ** It shouldn't be possible for fullfsync to fail on the local
3490 ** file system (on OSX), so failure indicates that FULLFSYNC
3491 ** isn't supported for this file system. So, attempt an fsync
3492 ** and (for now) ignore the overhead of a superfluous fcntl call.
3493 ** It'd be better to detect fullfsync support once and avoid
3494 ** the fcntl call every time sync is called.
3495 */
drh734c9862008-11-28 15:37:20 +00003496 if( rc ) rc = fsync(fd);
3497
drh7ed97b92010-01-20 13:07:21 +00003498#elif defined(__APPLE__)
3499 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3500 ** so currently we default to the macro that redefines fdatasync to fsync
3501 */
3502 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003503#else
drh0b647ff2009-03-21 14:41:04 +00003504 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003505#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003506 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003507 rc = fsync(fd);
3508 }
drh0b647ff2009-03-21 14:41:04 +00003509#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003510#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3511
3512 if( OS_VXWORKS && rc!= -1 ){
3513 rc = 0;
3514 }
chw97185482008-11-17 08:05:31 +00003515 return rc;
drhbfe66312006-10-03 17:40:40 +00003516}
3517
drh734c9862008-11-28 15:37:20 +00003518/*
drh0059eae2011-08-08 23:48:40 +00003519** Open a file descriptor to the directory containing file zFilename.
3520** If successful, *pFd is set to the opened file descriptor and
3521** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3522** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3523** value.
3524**
drh90315a22011-08-10 01:52:12 +00003525** The directory file descriptor is used for only one thing - to
3526** fsync() a directory to make sure file creation and deletion events
3527** are flushed to disk. Such fsyncs are not needed on newer
3528** journaling filesystems, but are required on older filesystems.
3529**
3530** This routine can be overridden using the xSetSysCall interface.
3531** The ability to override this routine was added in support of the
3532** chromium sandbox. Opening a directory is a security risk (we are
3533** told) so making it overrideable allows the chromium sandbox to
3534** replace this routine with a harmless no-op. To make this routine
3535** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3536** *pFd set to a negative number.
3537**
drh0059eae2011-08-08 23:48:40 +00003538** If SQLITE_OK is returned, the caller is responsible for closing
3539** the file descriptor *pFd using close().
3540*/
3541static int openDirectory(const char *zFilename, int *pFd){
3542 int ii;
3543 int fd = -1;
3544 char zDirname[MAX_PATHNAME+1];
3545
3546 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3547 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3548 if( ii>0 ){
3549 zDirname[ii] = '\0';
3550 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3551 if( fd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003552 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3553 }
3554 }
3555 *pFd = fd;
3556 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3557}
3558
3559/*
drh734c9862008-11-28 15:37:20 +00003560** Make sure all writes to a particular file are committed to disk.
3561**
3562** If dataOnly==0 then both the file itself and its metadata (file
3563** size, access time, etc) are synced. If dataOnly!=0 then only the
3564** file data is synced.
3565**
3566** Under Unix, also make sure that the directory entry for the file
3567** has been created by fsync-ing the directory that contains the file.
3568** If we do not do this and we encounter a power failure, the directory
3569** entry for the journal might not exist after we reboot. The next
3570** SQLite to access the file will not know that the journal exists (because
3571** the directory entry for the journal was never created) and the transaction
3572** will not roll back - possibly leading to database corruption.
3573*/
3574static int unixSync(sqlite3_file *id, int flags){
3575 int rc;
3576 unixFile *pFile = (unixFile*)id;
3577
3578 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3579 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3580
3581 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3582 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3583 || (flags&0x0F)==SQLITE_SYNC_FULL
3584 );
3585
3586 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3587 ** line is to test that doing so does not cause any problems.
3588 */
3589 SimulateDiskfullError( return SQLITE_FULL );
3590
3591 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003592 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003593 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3594 SimulateIOError( rc=1 );
3595 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003596 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003597 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003598 }
drh0059eae2011-08-08 23:48:40 +00003599
3600 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003601 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003602 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003603 */
3604 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3605 int dirfd;
3606 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003607 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003608 rc = osOpenDirectory(pFile->zPath, &dirfd);
3609 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003610 full_fsync(dirfd, 0, 0);
3611 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003612 }else if( rc==SQLITE_CANTOPEN ){
3613 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003614 }
drh0059eae2011-08-08 23:48:40 +00003615 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003616 }
3617 return rc;
3618}
3619
3620/*
3621** Truncate an open file to a specified size
3622*/
3623static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003624 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003625 int rc;
dan6e09d692010-07-27 18:34:15 +00003626 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003627 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003628
3629 /* If the user has configured a chunk-size for this file, truncate the
3630 ** file so that it consists of an integer number of chunks (i.e. the
3631 ** actual file size after the operation may be larger than the requested
3632 ** size).
3633 */
drhb8af4b72012-04-05 20:04:39 +00003634 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003635 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3636 }
3637
dan2ee53412014-09-06 16:49:40 +00003638 rc = robust_ftruncate(pFile->h, nByte);
drh734c9862008-11-28 15:37:20 +00003639 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003640 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003641 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003642 }else{
drhd3d8c042012-05-29 17:02:40 +00003643#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003644 /* If we are doing a normal write to a database file (as opposed to
3645 ** doing a hot-journal rollback or a write to some file other than a
3646 ** normal database file) and we truncate the file to zero length,
3647 ** that effectively updates the change counter. This might happen
3648 ** when restoring a database using the backup API from a zero-length
3649 ** source.
3650 */
dan6e09d692010-07-27 18:34:15 +00003651 if( pFile->inNormalWrite && nByte==0 ){
3652 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003653 }
danf23da962013-03-23 21:00:41 +00003654#endif
danc0003312013-03-22 17:46:11 +00003655
mistachkine98844f2013-08-24 00:59:24 +00003656#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003657 /* If the file was just truncated to a size smaller than the currently
3658 ** mapped region, reduce the effective mapping size as well. SQLite will
3659 ** use read() and write() to access data beyond this point from now on.
3660 */
3661 if( nByte<pFile->mmapSize ){
3662 pFile->mmapSize = nByte;
3663 }
mistachkine98844f2013-08-24 00:59:24 +00003664#endif
drh3313b142009-11-06 04:13:18 +00003665
drh734c9862008-11-28 15:37:20 +00003666 return SQLITE_OK;
3667 }
3668}
3669
3670/*
3671** Determine the current size of a file in bytes
3672*/
3673static int unixFileSize(sqlite3_file *id, i64 *pSize){
3674 int rc;
3675 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003676 assert( id );
3677 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003678 SimulateIOError( rc=1 );
3679 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00003680 storeLastErrno((unixFile*)id, errno);
drh734c9862008-11-28 15:37:20 +00003681 return SQLITE_IOERR_FSTAT;
3682 }
3683 *pSize = buf.st_size;
3684
drh8af6c222010-05-14 12:43:01 +00003685 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003686 ** writes a single byte into that file in order to work around a bug
3687 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3688 ** layers, we need to report this file size as zero even though it is
3689 ** really 1. Ticket #3260.
3690 */
3691 if( *pSize==1 ) *pSize = 0;
3692
3693
3694 return SQLITE_OK;
3695}
3696
drhd2cb50b2009-01-09 21:41:17 +00003697#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003698/*
3699** Handler for proxy-locking file-control verbs. Defined below in the
3700** proxying locking division.
3701*/
3702static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003703#endif
drh715ff302008-12-03 22:32:44 +00003704
dan502019c2010-07-28 14:26:17 +00003705/*
3706** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003707** file-control operation. Enlarge the database to nBytes in size
3708** (rounded up to the next chunk-size). If the database is already
3709** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003710*/
3711static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003712 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003713 i64 nSize; /* Required file size */
3714 struct stat buf; /* Used to hold return values of fstat() */
3715
drh4bf66fd2015-02-19 02:43:02 +00003716 if( osFstat(pFile->h, &buf) ){
3717 return SQLITE_IOERR_FSTAT;
3718 }
dan502019c2010-07-28 14:26:17 +00003719
3720 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3721 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003722
dan502019c2010-07-28 14:26:17 +00003723#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003724 /* The code below is handling the return value of osFallocate()
3725 ** correctly. posix_fallocate() is defined to "returns zero on success,
3726 ** or an error number on failure". See the manpage for details. */
3727 int err;
drhff812312011-02-23 13:33:46 +00003728 do{
dan661d71a2011-03-30 19:08:03 +00003729 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3730 }while( err==EINTR );
3731 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003732#else
dan592bf7f2014-12-30 19:58:31 +00003733 /* If the OS does not have posix_fallocate(), fake it. Write a
3734 ** single byte to the last byte in each block that falls entirely
3735 ** within the extended region. Then, if required, a single byte
3736 ** at offset (nSize-1), to set the size of the file correctly.
3737 ** This is a similar technique to that used by glibc on systems
3738 ** that do not have a real fallocate() call.
dan502019c2010-07-28 14:26:17 +00003739 */
3740 int nBlk = buf.st_blksize; /* File-system block size */
danef3d66c2015-01-06 21:31:47 +00003741 int nWrite = 0; /* Number of bytes written by seekAndWrite */
dan502019c2010-07-28 14:26:17 +00003742 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003743
dan502019c2010-07-28 14:26:17 +00003744 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dan592bf7f2014-12-30 19:58:31 +00003745 assert( iWrite>=buf.st_size );
3746 assert( (iWrite/nBlk)==((buf.st_size+nBlk-1)/nBlk) );
3747 assert( ((iWrite+1)%nBlk)==0 );
3748 for(/*no-op*/; iWrite<nSize; iWrite+=nBlk ){
danef3d66c2015-01-06 21:31:47 +00003749 nWrite = seekAndWrite(pFile, iWrite, "", 1);
dandc5df0f2011-04-06 19:15:45 +00003750 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dandc5df0f2011-04-06 19:15:45 +00003751 }
danef3d66c2015-01-06 21:31:47 +00003752 if( nWrite==0 || (nSize%nBlk) ){
3753 nWrite = seekAndWrite(pFile, nSize-1, "", 1);
dan592bf7f2014-12-30 19:58:31 +00003754 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dand348c662014-12-30 14:40:53 +00003755 }
dan502019c2010-07-28 14:26:17 +00003756#endif
3757 }
3758 }
3759
mistachkine98844f2013-08-24 00:59:24 +00003760#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003761 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003762 int rc;
3763 if( pFile->szChunk<=0 ){
3764 if( robust_ftruncate(pFile->h, nByte) ){
drh4bf66fd2015-02-19 02:43:02 +00003765 storeLastErrno(pFile, errno);
danf23da962013-03-23 21:00:41 +00003766 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3767 }
3768 }
3769
3770 rc = unixMapfile(pFile, nByte);
3771 return rc;
3772 }
mistachkine98844f2013-08-24 00:59:24 +00003773#endif
danf23da962013-03-23 21:00:41 +00003774
dan502019c2010-07-28 14:26:17 +00003775 return SQLITE_OK;
3776}
danielk1977ad94b582007-08-20 06:44:22 +00003777
danielk1977e3026632004-06-22 11:29:02 +00003778/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003779** If *pArg is initially negative then this is a query. Set *pArg to
drhf12b3f62011-12-21 14:42:29 +00003780** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3781**
3782** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3783*/
3784static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3785 if( *pArg<0 ){
3786 *pArg = (pFile->ctrlFlags & mask)!=0;
3787 }else if( (*pArg)==0 ){
3788 pFile->ctrlFlags &= ~mask;
3789 }else{
3790 pFile->ctrlFlags |= mask;
3791 }
3792}
3793
drh696b33e2012-12-06 19:01:42 +00003794/* Forward declaration */
3795static int unixGetTempname(int nBuf, char *zBuf);
3796
drhf12b3f62011-12-21 14:42:29 +00003797/*
drh9e33c2c2007-08-31 18:34:59 +00003798** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003799*/
drhcc6bb3e2007-08-31 16:11:35 +00003800static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003801 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003802 switch( op ){
drhc435cf72015-03-21 16:36:03 +00003803 case SQLITE_FCNTL_WAL_BLOCK: {
drh62ca61e2015-04-03 20:33:33 +00003804 /* pFile->ctrlFlags |= UNIXFILE_BLOCK; // Deferred feature */
drhc435cf72015-03-21 16:36:03 +00003805 return SQLITE_OK;
3806 }
drh9e33c2c2007-08-31 18:34:59 +00003807 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003808 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003809 return SQLITE_OK;
3810 }
drh4bf66fd2015-02-19 02:43:02 +00003811 case SQLITE_FCNTL_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003812 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003813 return SQLITE_OK;
3814 }
dan6e09d692010-07-27 18:34:15 +00003815 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003816 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003817 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003818 }
drh9ff27ec2010-05-19 19:26:05 +00003819 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003820 int rc;
3821 SimulateIOErrorBenign(1);
3822 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3823 SimulateIOErrorBenign(0);
3824 return rc;
drhf0b190d2011-07-26 16:03:07 +00003825 }
3826 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003827 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3828 return SQLITE_OK;
3829 }
drhcb15f352011-12-23 01:04:17 +00003830 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3831 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003832 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003833 }
drhde60fc22011-12-14 17:53:36 +00003834 case SQLITE_FCNTL_VFSNAME: {
3835 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3836 return SQLITE_OK;
3837 }
drh696b33e2012-12-06 19:01:42 +00003838 case SQLITE_FCNTL_TEMPFILENAME: {
drhf3cdcdc2015-04-29 16:50:28 +00003839 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
drh696b33e2012-12-06 19:01:42 +00003840 if( zTFile ){
3841 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3842 *(char**)pArg = zTFile;
3843 }
3844 return SQLITE_OK;
3845 }
drhb959a012013-12-07 12:29:22 +00003846 case SQLITE_FCNTL_HAS_MOVED: {
3847 *(int*)pArg = fileHasMoved(pFile);
3848 return SQLITE_OK;
3849 }
mistachkine98844f2013-08-24 00:59:24 +00003850#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003851 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003852 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003853 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003854 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3855 newLimit = sqlite3GlobalConfig.mxMmap;
3856 }
3857 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003858 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003859 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003860 if( pFile->mmapSize>0 ){
3861 unixUnmapfile(pFile);
3862 rc = unixMapfile(pFile, -1);
3863 }
danbcb8a862013-04-08 15:30:41 +00003864 }
drh34e258c2013-05-23 01:40:53 +00003865 return rc;
danb2d3de32013-03-14 18:34:37 +00003866 }
mistachkine98844f2013-08-24 00:59:24 +00003867#endif
drhd3d8c042012-05-29 17:02:40 +00003868#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003869 /* The pager calls this method to signal that it has done
3870 ** a rollback and that the database is therefore unchanged and
3871 ** it hence it is OK for the transaction change counter to be
3872 ** unchanged.
3873 */
3874 case SQLITE_FCNTL_DB_UNCHANGED: {
3875 ((unixFile*)id)->dbUpdate = 0;
3876 return SQLITE_OK;
3877 }
3878#endif
drhd2cb50b2009-01-09 21:41:17 +00003879#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh4bf66fd2015-02-19 02:43:02 +00003880 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
3881 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003882 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003883 }
drhd2cb50b2009-01-09 21:41:17 +00003884#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003885 }
drh0b52b7d2011-01-26 19:46:22 +00003886 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003887}
3888
3889/*
danielk1977a3d4c882007-03-23 10:08:38 +00003890** Return the sector size in bytes of the underlying block device for
3891** the specified file. This is almost always 512 bytes, but may be
3892** larger for some devices.
3893**
3894** SQLite code assumes this function cannot fail. It also assumes that
3895** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003896** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003897** same for both.
3898*/
drh537dddf2012-10-26 13:46:24 +00003899#ifndef __QNXNTO__
3900static int unixSectorSize(sqlite3_file *NotUsed){
3901 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003902 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003903}
drh537dddf2012-10-26 13:46:24 +00003904#endif
3905
3906/*
3907** The following version of unixSectorSize() is optimized for QNX.
3908*/
3909#ifdef __QNXNTO__
3910#include <sys/dcmd_blk.h>
3911#include <sys/statvfs.h>
3912static int unixSectorSize(sqlite3_file *id){
3913 unixFile *pFile = (unixFile*)id;
3914 if( pFile->sectorSize == 0 ){
3915 struct statvfs fsInfo;
3916
3917 /* Set defaults for non-supported filesystems */
3918 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3919 pFile->deviceCharacteristics = 0;
3920 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3921 return pFile->sectorSize;
3922 }
3923
3924 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3925 pFile->sectorSize = fsInfo.f_bsize;
3926 pFile->deviceCharacteristics =
3927 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3928 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3929 ** the write succeeds */
3930 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3931 ** so it is ordered */
3932 0;
3933 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3934 pFile->sectorSize = fsInfo.f_bsize;
3935 pFile->deviceCharacteristics =
3936 /* etfs cluster size writes are atomic */
3937 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3938 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3939 ** the write succeeds */
3940 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3941 ** so it is ordered */
3942 0;
3943 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3944 pFile->sectorSize = fsInfo.f_bsize;
3945 pFile->deviceCharacteristics =
3946 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3947 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3948 ** the write succeeds */
3949 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3950 ** so it is ordered */
3951 0;
3952 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3953 pFile->sectorSize = fsInfo.f_bsize;
3954 pFile->deviceCharacteristics =
3955 /* full bitset of atomics from max sector size and smaller */
3956 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3957 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3958 ** so it is ordered */
3959 0;
3960 }else if( strstr(fsInfo.f_basetype, "dos") ){
3961 pFile->sectorSize = fsInfo.f_bsize;
3962 pFile->deviceCharacteristics =
3963 /* full bitset of atomics from max sector size and smaller */
3964 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3965 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3966 ** so it is ordered */
3967 0;
3968 }else{
3969 pFile->deviceCharacteristics =
3970 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3971 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3972 ** the write succeeds */
3973 0;
3974 }
3975 }
3976 /* Last chance verification. If the sector size isn't a multiple of 512
3977 ** then it isn't valid.*/
3978 if( pFile->sectorSize % 512 != 0 ){
3979 pFile->deviceCharacteristics = 0;
3980 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3981 }
3982 return pFile->sectorSize;
3983}
3984#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003985
danielk197790949c22007-08-17 16:50:38 +00003986/*
drhf12b3f62011-12-21 14:42:29 +00003987** Return the device characteristics for the file.
3988**
drhcb15f352011-12-23 01:04:17 +00003989** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
peter.d.reid60ec9142014-09-06 16:39:46 +00003990** However, that choice is controversial since technically the underlying
drhcb15f352011-12-23 01:04:17 +00003991** file system does not always provide powersafe overwrites. (In other
3992** words, after a power-loss event, parts of the file that were never
3993** written might end up being altered.) However, non-PSOW behavior is very,
3994** very rare. And asserting PSOW makes a large reduction in the amount
3995** of required I/O for journaling, since a lot of padding is eliminated.
3996** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3997** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003998*/
drhf12b3f62011-12-21 14:42:29 +00003999static int unixDeviceCharacteristics(sqlite3_file *id){
4000 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00004001 int rc = 0;
4002#ifdef __QNXNTO__
4003 if( p->sectorSize==0 ) unixSectorSize(id);
4004 rc = p->deviceCharacteristics;
4005#endif
drhcb15f352011-12-23 01:04:17 +00004006 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00004007 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00004008 }
drh537dddf2012-10-26 13:46:24 +00004009 return rc;
danielk197762079062007-08-15 17:08:46 +00004010}
4011
dan702eec12014-06-23 10:04:58 +00004012#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00004013
dan702eec12014-06-23 10:04:58 +00004014/*
4015** Return the system page size.
4016**
4017** This function should not be called directly by other code in this file.
4018** Instead, it should be called via macro osGetpagesize().
4019*/
4020static int unixGetpagesize(void){
drh8cd5b252015-03-02 22:06:43 +00004021#if OS_VXWORKS
4022 return 1024;
4023#elif defined(_BSD_SOURCE)
dan702eec12014-06-23 10:04:58 +00004024 return getpagesize();
4025#else
4026 return (int)sysconf(_SC_PAGESIZE);
4027#endif
4028}
4029
4030#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
4031
4032#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00004033
4034/*
drhd91c68f2010-05-14 14:52:25 +00004035** Object used to represent an shared memory buffer.
4036**
4037** When multiple threads all reference the same wal-index, each thread
4038** has its own unixShm object, but they all point to a single instance
4039** of this unixShmNode object. In other words, each wal-index is opened
4040** only once per process.
4041**
4042** Each unixShmNode object is connected to a single unixInodeInfo object.
4043** We could coalesce this object into unixInodeInfo, but that would mean
4044** every open file that does not use shared memory (in other words, most
4045** open files) would have to carry around this extra information. So
4046** the unixInodeInfo object contains a pointer to this unixShmNode object
4047** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00004048**
4049** unixMutexHeld() must be true when creating or destroying
4050** this object or while reading or writing the following fields:
4051**
4052** nRef
drhd9e5c4f2010-05-12 18:01:39 +00004053**
4054** The following fields are read-only after the object is created:
4055**
4056** fid
4057** zFilename
4058**
drhd91c68f2010-05-14 14:52:25 +00004059** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00004060** unixMutexHeld() is true when reading or writing any other field
4061** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00004062*/
drhd91c68f2010-05-14 14:52:25 +00004063struct unixShmNode {
4064 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00004065 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00004066 char *zFilename; /* Name of the mmapped file */
4067 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00004068 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00004069 u16 nRegion; /* Size of array apRegion */
4070 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00004071 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00004072 int nRef; /* Number of unixShm objects pointing to this */
4073 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00004074#ifdef SQLITE_DEBUG
4075 u8 exclMask; /* Mask of exclusive locks held */
4076 u8 sharedMask; /* Mask of shared locks held */
4077 u8 nextShmId; /* Next available unixShm.id value */
4078#endif
4079};
4080
4081/*
drhd9e5c4f2010-05-12 18:01:39 +00004082** Structure used internally by this VFS to record the state of an
4083** open shared memory connection.
4084**
drhd91c68f2010-05-14 14:52:25 +00004085** The following fields are initialized when this object is created and
4086** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004087**
drhd91c68f2010-05-14 14:52:25 +00004088** unixShm.pFile
4089** unixShm.id
4090**
4091** All other fields are read/write. The unixShm.pFile->mutex must be held
4092** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004093*/
4094struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004095 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4096 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004097 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004098 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004099 u16 sharedMask; /* Mask of shared locks held */
4100 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004101};
4102
4103/*
drhd9e5c4f2010-05-12 18:01:39 +00004104** Constants used for locking
4105*/
drhbd9676c2010-06-23 17:58:38 +00004106#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004107#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004108
drhd9e5c4f2010-05-12 18:01:39 +00004109/*
drh73b64e42010-05-30 19:55:15 +00004110** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004111**
4112** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4113** otherwise.
4114*/
4115static int unixShmSystemLock(
drhbbf76ee2015-03-10 20:22:35 +00004116 unixFile *pFile, /* Open connection to the WAL file */
drhd91c68f2010-05-14 14:52:25 +00004117 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004118 int ofst, /* First byte of the locking range */
4119 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004120){
drhbbf76ee2015-03-10 20:22:35 +00004121 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4122 struct flock f; /* The posix advisory locking structure */
4123 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004124
drhd91c68f2010-05-14 14:52:25 +00004125 /* Access to the unixShmNode object is serialized by the caller */
drhbbf76ee2015-03-10 20:22:35 +00004126 pShmNode = pFile->pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004127 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004128
drh73b64e42010-05-30 19:55:15 +00004129 /* Shared locks never span more than one byte */
4130 assert( n==1 || lockType!=F_RDLCK );
4131
4132 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00004133 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004134
drh3cb93392011-03-12 18:10:44 +00004135 if( pShmNode->h>=0 ){
drhbbf76ee2015-03-10 20:22:35 +00004136 int lkType;
drh3cb93392011-03-12 18:10:44 +00004137 /* Initialize the locking parameters */
4138 memset(&f, 0, sizeof(f));
4139 f.l_type = lockType;
4140 f.l_whence = SEEK_SET;
4141 f.l_start = ofst;
4142 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004143
drhbbf76ee2015-03-10 20:22:35 +00004144 lkType = (pFile->ctrlFlags & UNIXFILE_BLOCK)!=0 ? F_SETLKW : F_SETLK;
4145 rc = osFcntl(pShmNode->h, lkType, &f);
drh3cb93392011-03-12 18:10:44 +00004146 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
drhbbf76ee2015-03-10 20:22:35 +00004147 pFile->ctrlFlags &= ~UNIXFILE_BLOCK;
drh3cb93392011-03-12 18:10:44 +00004148 }
drhd9e5c4f2010-05-12 18:01:39 +00004149
4150 /* Update the global lock state and do debug tracing */
4151#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004152 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004153 OSTRACE(("SHM-LOCK "));
drh693e6712014-01-24 22:58:00 +00004154 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004155 if( rc==SQLITE_OK ){
4156 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004157 OSTRACE(("unlock %d ok", ofst));
4158 pShmNode->exclMask &= ~mask;
4159 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004160 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004161 OSTRACE(("read-lock %d ok", ofst));
4162 pShmNode->exclMask &= ~mask;
4163 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004164 }else{
4165 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004166 OSTRACE(("write-lock %d ok", ofst));
4167 pShmNode->exclMask |= mask;
4168 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004169 }
4170 }else{
4171 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004172 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004173 }else if( lockType==F_RDLCK ){
4174 OSTRACE(("read-lock failed"));
4175 }else{
4176 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004177 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004178 }
4179 }
drh20e1f082010-05-31 16:10:12 +00004180 OSTRACE((" - afterwards %03x,%03x\n",
4181 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004182 }
drhd9e5c4f2010-05-12 18:01:39 +00004183#endif
4184
4185 return rc;
4186}
4187
dan781e34c2014-03-20 08:59:47 +00004188/*
dan781e34c2014-03-20 08:59:47 +00004189** Return the minimum number of 32KB shm regions that should be mapped at
4190** a time, assuming that each mapping must be an integer multiple of the
4191** current system page-size.
4192**
4193** Usually, this is 1. The exception seems to be systems that are configured
4194** to use 64KB pages - in this case each mapping must cover at least two
4195** shm regions.
4196*/
4197static int unixShmRegionPerMap(void){
4198 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004199 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004200 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4201 if( pgsz<shmsz ) return 1;
4202 return pgsz/shmsz;
4203}
drhd9e5c4f2010-05-12 18:01:39 +00004204
4205/*
drhd91c68f2010-05-14 14:52:25 +00004206** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004207**
4208** This is not a VFS shared-memory method; it is a utility function called
4209** by VFS shared-memory methods.
4210*/
drhd91c68f2010-05-14 14:52:25 +00004211static void unixShmPurge(unixFile *pFd){
4212 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004213 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00004214 if( p && p->nRef==0 ){
dan781e34c2014-03-20 08:59:47 +00004215 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004216 int i;
drhd91c68f2010-05-14 14:52:25 +00004217 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004218 sqlite3_mutex_free(p->mutex);
dan781e34c2014-03-20 08:59:47 +00004219 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh3cb93392011-03-12 18:10:44 +00004220 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004221 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004222 }else{
4223 sqlite3_free(p->apRegion[i]);
4224 }
dan13a3cb82010-06-11 19:04:21 +00004225 }
dan18801912010-06-14 14:07:50 +00004226 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004227 if( p->h>=0 ){
4228 robust_close(pFd, p->h, __LINE__);
4229 p->h = -1;
4230 }
drhd91c68f2010-05-14 14:52:25 +00004231 p->pInode->pShmNode = 0;
4232 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004233 }
4234}
4235
4236/*
danda9fe0c2010-07-13 18:44:03 +00004237** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004238** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004239**
drh7234c6d2010-06-19 15:10:09 +00004240** The file used to implement shared-memory is in the same directory
4241** as the open database file and has the same name as the open database
4242** file with the "-shm" suffix added. For example, if the database file
4243** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004244** for shared memory will be called "/home/user1/config.db-shm".
4245**
4246** Another approach to is to use files in /dev/shm or /dev/tmp or an
4247** some other tmpfs mount. But if a file in a different directory
4248** from the database file is used, then differing access permissions
4249** or a chroot() might cause two different processes on the same
4250** database to end up using different files for shared memory -
4251** meaning that their memory would not really be shared - resulting
4252** in database corruption. Nevertheless, this tmpfs file usage
4253** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4254** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4255** option results in an incompatible build of SQLite; builds of SQLite
4256** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4257** same database file at the same time, database corruption will likely
4258** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4259** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004260**
4261** When opening a new shared-memory file, if no other instances of that
4262** file are currently open, in this process or in other processes, then
4263** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004264**
4265** If the original database file (pDbFd) is using the "unix-excl" VFS
4266** that means that an exclusive lock is held on the database file and
4267** that no other processes are able to read or write the database. In
4268** that case, we do not really need shared memory. No shared memory
4269** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004270*/
danda9fe0c2010-07-13 18:44:03 +00004271static int unixOpenSharedMemory(unixFile *pDbFd){
4272 struct unixShm *p = 0; /* The connection to be opened */
4273 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4274 int rc; /* Result code */
4275 unixInodeInfo *pInode; /* The inode of fd */
4276 char *zShmFilename; /* Name of the file used for SHM */
4277 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004278
danda9fe0c2010-07-13 18:44:03 +00004279 /* Allocate space for the new unixShm object. */
drhf3cdcdc2015-04-29 16:50:28 +00004280 p = sqlite3_malloc64( sizeof(*p) );
drhd9e5c4f2010-05-12 18:01:39 +00004281 if( p==0 ) return SQLITE_NOMEM;
4282 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004283 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004284
danda9fe0c2010-07-13 18:44:03 +00004285 /* Check to see if a unixShmNode object already exists. Reuse an existing
4286 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004287 */
4288 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004289 pInode = pDbFd->pInode;
4290 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004291 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004292 struct stat sStat; /* fstat() info for database file */
drh4bf66fd2015-02-19 02:43:02 +00004293#ifndef SQLITE_SHM_DIRECTORY
4294 const char *zBasePath = pDbFd->zPath;
4295#endif
danddb0ac42010-07-14 14:48:58 +00004296
4297 /* Call fstat() to figure out the permissions on the database file. If
4298 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004299 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004300 */
drh3cb93392011-03-12 18:10:44 +00004301 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00004302 rc = SQLITE_IOERR_FSTAT;
4303 goto shm_open_err;
4304 }
4305
drha4ced192010-07-15 18:32:40 +00004306#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004307 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004308#else
drh4bf66fd2015-02-19 02:43:02 +00004309 nShmFilename = 6 + (int)strlen(zBasePath);
drha4ced192010-07-15 18:32:40 +00004310#endif
drhf3cdcdc2015-04-29 16:50:28 +00004311 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004312 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004313 rc = SQLITE_NOMEM;
4314 goto shm_open_err;
4315 }
drh9cb5a0d2012-01-05 21:19:54 +00004316 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004317 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004318#ifdef SQLITE_SHM_DIRECTORY
4319 sqlite3_snprintf(nShmFilename, zShmFilename,
4320 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4321 (u32)sStat.st_ino, (u32)sStat.st_dev);
4322#else
drh4bf66fd2015-02-19 02:43:02 +00004323 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
drh81cc5162011-05-17 20:36:21 +00004324 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004325#endif
drhd91c68f2010-05-14 14:52:25 +00004326 pShmNode->h = -1;
4327 pDbFd->pInode->pShmNode = pShmNode;
4328 pShmNode->pInode = pDbFd->pInode;
4329 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4330 if( pShmNode->mutex==0 ){
4331 rc = SQLITE_NOMEM;
4332 goto shm_open_err;
4333 }
drhd9e5c4f2010-05-12 18:01:39 +00004334
drh3cb93392011-03-12 18:10:44 +00004335 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004336 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004337 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004338 openFlags = O_RDONLY;
4339 pShmNode->isReadonly = 1;
4340 }
4341 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004342 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004343 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4344 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004345 }
drhac7c3ac2012-02-11 19:23:48 +00004346
4347 /* If this process is running as root, make sure that the SHM file
4348 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004349 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004350 */
drh6226ca22015-11-24 15:06:28 +00004351 robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004352
4353 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004354 ** If not, truncate the file to zero length.
4355 */
4356 rc = SQLITE_OK;
drhbbf76ee2015-03-10 20:22:35 +00004357 if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
drh66dfec8b2011-06-01 20:01:49 +00004358 if( robust_ftruncate(pShmNode->h, 0) ){
4359 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004360 }
4361 }
drh66dfec8b2011-06-01 20:01:49 +00004362 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004363 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
drh66dfec8b2011-06-01 20:01:49 +00004364 }
4365 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004366 }
drhd9e5c4f2010-05-12 18:01:39 +00004367 }
4368
drhd91c68f2010-05-14 14:52:25 +00004369 /* Make the new connection a child of the unixShmNode */
4370 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004371#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004372 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004373#endif
drhd91c68f2010-05-14 14:52:25 +00004374 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004375 pDbFd->pShm = p;
4376 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004377
4378 /* The reference count on pShmNode has already been incremented under
4379 ** the cover of the unixEnterMutex() mutex and the pointer from the
4380 ** new (struct unixShm) object to the pShmNode has been set. All that is
4381 ** left to do is to link the new object into the linked list starting
4382 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4383 ** mutex.
4384 */
4385 sqlite3_mutex_enter(pShmNode->mutex);
4386 p->pNext = pShmNode->pFirst;
4387 pShmNode->pFirst = p;
4388 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004389 return SQLITE_OK;
4390
4391 /* Jump here on any error */
4392shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004393 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004394 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004395 unixLeaveMutex();
4396 return rc;
4397}
4398
4399/*
danda9fe0c2010-07-13 18:44:03 +00004400** This function is called to obtain a pointer to region iRegion of the
4401** shared-memory associated with the database file fd. Shared-memory regions
4402** are numbered starting from zero. Each shared-memory region is szRegion
4403** bytes in size.
4404**
4405** If an error occurs, an error code is returned and *pp is set to NULL.
4406**
4407** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4408** region has not been allocated (by any client, including one running in a
4409** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4410** bExtend is non-zero and the requested shared-memory region has not yet
4411** been allocated, it is allocated by this function.
4412**
4413** If the shared-memory region has already been allocated or is allocated by
4414** this call as described above, then it is mapped into this processes
4415** address space (if it is not already), *pp is set to point to the mapped
4416** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004417*/
danda9fe0c2010-07-13 18:44:03 +00004418static int unixShmMap(
4419 sqlite3_file *fd, /* Handle open on database file */
4420 int iRegion, /* Region to retrieve */
4421 int szRegion, /* Size of regions */
4422 int bExtend, /* True to extend file if necessary */
4423 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004424){
danda9fe0c2010-07-13 18:44:03 +00004425 unixFile *pDbFd = (unixFile*)fd;
4426 unixShm *p;
4427 unixShmNode *pShmNode;
4428 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004429 int nShmPerMap = unixShmRegionPerMap();
4430 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004431
danda9fe0c2010-07-13 18:44:03 +00004432 /* If the shared-memory file has not yet been opened, open it now. */
4433 if( pDbFd->pShm==0 ){
4434 rc = unixOpenSharedMemory(pDbFd);
4435 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004436 }
drhd9e5c4f2010-05-12 18:01:39 +00004437
danda9fe0c2010-07-13 18:44:03 +00004438 p = pDbFd->pShm;
4439 pShmNode = p->pShmNode;
4440 sqlite3_mutex_enter(pShmNode->mutex);
4441 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004442 assert( pShmNode->pInode==pDbFd->pInode );
4443 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4444 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004445
dan781e34c2014-03-20 08:59:47 +00004446 /* Minimum number of regions required to be mapped. */
4447 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4448
4449 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004450 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004451 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004452 struct stat sStat; /* Used by fstat() */
4453
4454 pShmNode->szRegion = szRegion;
4455
drh3cb93392011-03-12 18:10:44 +00004456 if( pShmNode->h>=0 ){
4457 /* The requested region is not mapped into this processes address space.
4458 ** Check to see if it has been allocated (i.e. if the wal-index file is
4459 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004460 */
drh3cb93392011-03-12 18:10:44 +00004461 if( osFstat(pShmNode->h, &sStat) ){
4462 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004463 goto shmpage_out;
4464 }
drh3cb93392011-03-12 18:10:44 +00004465
4466 if( sStat.st_size<nByte ){
4467 /* The requested memory region does not exist. If bExtend is set to
4468 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004469 */
dan47a2b4a2013-04-26 16:09:29 +00004470 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004471 goto shmpage_out;
4472 }
dan47a2b4a2013-04-26 16:09:29 +00004473
4474 /* Alternatively, if bExtend is true, extend the file. Do this by
4475 ** writing a single byte to the end of each (OS) page being
4476 ** allocated or extended. Technically, we need only write to the
4477 ** last page in order to extend the file. But writing to all new
4478 ** pages forces the OS to allocate them immediately, which reduces
4479 ** the chances of SIGBUS while accessing the mapped region later on.
4480 */
4481 else{
4482 static const int pgsz = 4096;
4483 int iPg;
4484
4485 /* Write to the last byte of each newly allocated or extended page */
4486 assert( (nByte % pgsz)==0 );
4487 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
4488 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
4489 const char *zFile = pShmNode->zFilename;
4490 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4491 goto shmpage_out;
4492 }
4493 }
drh3cb93392011-03-12 18:10:44 +00004494 }
4495 }
danda9fe0c2010-07-13 18:44:03 +00004496 }
4497
4498 /* Map the requested memory region into this processes address space. */
4499 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004500 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004501 );
4502 if( !apNew ){
4503 rc = SQLITE_IOERR_NOMEM;
4504 goto shmpage_out;
4505 }
4506 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004507 while( pShmNode->nRegion<nReqRegion ){
4508 int nMap = szRegion*nShmPerMap;
4509 int i;
drh3cb93392011-03-12 18:10:44 +00004510 void *pMem;
4511 if( pShmNode->h>=0 ){
dan781e34c2014-03-20 08:59:47 +00004512 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004513 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004514 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004515 );
4516 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004517 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004518 goto shmpage_out;
4519 }
4520 }else{
drhf3cdcdc2015-04-29 16:50:28 +00004521 pMem = sqlite3_malloc64(szRegion);
drh3cb93392011-03-12 18:10:44 +00004522 if( pMem==0 ){
4523 rc = SQLITE_NOMEM;
4524 goto shmpage_out;
4525 }
4526 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004527 }
dan781e34c2014-03-20 08:59:47 +00004528
4529 for(i=0; i<nShmPerMap; i++){
4530 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4531 }
4532 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004533 }
4534 }
4535
4536shmpage_out:
4537 if( pShmNode->nRegion>iRegion ){
4538 *pp = pShmNode->apRegion[iRegion];
4539 }else{
4540 *pp = 0;
4541 }
drh66dfec8b2011-06-01 20:01:49 +00004542 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004543 sqlite3_mutex_leave(pShmNode->mutex);
4544 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004545}
4546
4547/*
drhd9e5c4f2010-05-12 18:01:39 +00004548** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004549**
4550** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4551** different here than in posix. In xShmLock(), one can go from unlocked
4552** to shared and back or from unlocked to exclusive and back. But one may
4553** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004554*/
4555static int unixShmLock(
4556 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004557 int ofst, /* First lock to acquire or release */
4558 int n, /* Number of locks to acquire or release */
4559 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004560){
drh73b64e42010-05-30 19:55:15 +00004561 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4562 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4563 unixShm *pX; /* For looping over all siblings */
4564 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4565 int rc = SQLITE_OK; /* Result code */
4566 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004567
drhd91c68f2010-05-14 14:52:25 +00004568 assert( pShmNode==pDbFd->pInode->pShmNode );
4569 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004570 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004571 assert( n>=1 );
4572 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4573 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4574 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4575 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4576 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004577 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4578 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004579
drhc99597c2010-05-31 01:41:15 +00004580 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004581 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004582 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004583 if( flags & SQLITE_SHM_UNLOCK ){
4584 u16 allMask = 0; /* Mask of locks held by siblings */
4585
4586 /* See if any siblings hold this same lock */
4587 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4588 if( pX==p ) continue;
4589 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4590 allMask |= pX->sharedMask;
4591 }
4592
4593 /* Unlock the system-level locks */
4594 if( (mask & allMask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004595 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004596 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004597 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004598 }
drh73b64e42010-05-30 19:55:15 +00004599
4600 /* Undo the local locks */
4601 if( rc==SQLITE_OK ){
4602 p->exclMask &= ~mask;
4603 p->sharedMask &= ~mask;
4604 }
4605 }else if( flags & SQLITE_SHM_SHARED ){
4606 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4607
4608 /* Find out which shared locks are already held by sibling connections.
4609 ** If any sibling already holds an exclusive lock, go ahead and return
4610 ** SQLITE_BUSY.
4611 */
4612 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004613 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004614 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004615 break;
4616 }
4617 allShared |= pX->sharedMask;
4618 }
4619
4620 /* Get shared locks at the system level, if necessary */
4621 if( rc==SQLITE_OK ){
4622 if( (allShared & mask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004623 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004624 }else{
drh73b64e42010-05-30 19:55:15 +00004625 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004626 }
drhd9e5c4f2010-05-12 18:01:39 +00004627 }
drh73b64e42010-05-30 19:55:15 +00004628
4629 /* Get the local shared locks */
4630 if( rc==SQLITE_OK ){
4631 p->sharedMask |= mask;
4632 }
4633 }else{
4634 /* Make sure no sibling connections hold locks that will block this
4635 ** lock. If any do, return SQLITE_BUSY right away.
4636 */
4637 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004638 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4639 rc = SQLITE_BUSY;
4640 break;
4641 }
4642 }
4643
4644 /* Get the exclusive locks at the system level. Then if successful
4645 ** also mark the local connection as being locked.
4646 */
4647 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004648 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004649 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004650 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004651 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004652 }
drhd9e5c4f2010-05-12 18:01:39 +00004653 }
4654 }
drhd91c68f2010-05-14 14:52:25 +00004655 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004656 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
drh5ac93652015-03-21 20:59:43 +00004657 p->id, osGetpid(0), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004658 return rc;
4659}
4660
drh286a2882010-05-20 23:51:06 +00004661/*
4662** Implement a memory barrier or memory fence on shared memory.
4663**
4664** All loads and stores begun before the barrier must complete before
4665** any load or store begun after the barrier.
4666*/
4667static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004668 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004669){
drhff828942010-06-26 21:34:06 +00004670 UNUSED_PARAMETER(fd);
drh22c733d2015-09-24 12:40:43 +00004671 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
4672 unixEnterMutex(); /* Also mutex, for redundancy */
drhb29ad852010-06-01 00:03:57 +00004673 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004674}
4675
dan18801912010-06-14 14:07:50 +00004676/*
danda9fe0c2010-07-13 18:44:03 +00004677** Close a connection to shared-memory. Delete the underlying
4678** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004679**
4680** If there is no shared memory associated with the connection then this
4681** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004682*/
danda9fe0c2010-07-13 18:44:03 +00004683static int unixShmUnmap(
4684 sqlite3_file *fd, /* The underlying database file */
4685 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004686){
danda9fe0c2010-07-13 18:44:03 +00004687 unixShm *p; /* The connection to be closed */
4688 unixShmNode *pShmNode; /* The underlying shared-memory file */
4689 unixShm **pp; /* For looping over sibling connections */
4690 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004691
danda9fe0c2010-07-13 18:44:03 +00004692 pDbFd = (unixFile*)fd;
4693 p = pDbFd->pShm;
4694 if( p==0 ) return SQLITE_OK;
4695 pShmNode = p->pShmNode;
4696
4697 assert( pShmNode==pDbFd->pInode->pShmNode );
4698 assert( pShmNode->pInode==pDbFd->pInode );
4699
4700 /* Remove connection p from the set of connections associated
4701 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004702 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004703 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4704 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004705
danda9fe0c2010-07-13 18:44:03 +00004706 /* Free the connection p */
4707 sqlite3_free(p);
4708 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004709 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004710
4711 /* If pShmNode->nRef has reached 0, then close the underlying
4712 ** shared-memory file, too */
4713 unixEnterMutex();
4714 assert( pShmNode->nRef>0 );
4715 pShmNode->nRef--;
4716 if( pShmNode->nRef==0 ){
drh4bf66fd2015-02-19 02:43:02 +00004717 if( deleteFlag && pShmNode->h>=0 ){
4718 osUnlink(pShmNode->zFilename);
4719 }
danda9fe0c2010-07-13 18:44:03 +00004720 unixShmPurge(pDbFd);
4721 }
4722 unixLeaveMutex();
4723
4724 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004725}
drh286a2882010-05-20 23:51:06 +00004726
danda9fe0c2010-07-13 18:44:03 +00004727
drhd9e5c4f2010-05-12 18:01:39 +00004728#else
drh6b017cc2010-06-14 18:01:46 +00004729# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004730# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004731# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004732# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004733#endif /* #ifndef SQLITE_OMIT_WAL */
4734
mistachkine98844f2013-08-24 00:59:24 +00004735#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004736/*
danaef49d72013-03-25 16:28:54 +00004737** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004738*/
danf23da962013-03-23 21:00:41 +00004739static void unixUnmapfile(unixFile *pFd){
4740 assert( pFd->nFetchOut==0 );
4741 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004742 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004743 pFd->pMapRegion = 0;
4744 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004745 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004746 }
4747}
dan5d8a1372013-03-19 19:28:06 +00004748
danaef49d72013-03-25 16:28:54 +00004749/*
dane6ecd662013-04-01 17:56:59 +00004750** Attempt to set the size of the memory mapping maintained by file
4751** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4752**
4753** If successful, this function sets the following variables:
4754**
4755** unixFile.pMapRegion
4756** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004757** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004758**
4759** If unsuccessful, an error message is logged via sqlite3_log() and
4760** the three variables above are zeroed. In this case SQLite should
4761** continue accessing the database using the xRead() and xWrite()
4762** methods.
4763*/
4764static void unixRemapfile(
4765 unixFile *pFd, /* File descriptor object */
4766 i64 nNew /* Required mapping size */
4767){
dan4ff7bc42013-04-02 12:04:09 +00004768 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004769 int h = pFd->h; /* File descriptor open on db file */
4770 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004771 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004772 u8 *pNew = 0; /* Location of new mapping */
4773 int flags = PROT_READ; /* Flags to pass to mmap() */
4774
4775 assert( pFd->nFetchOut==0 );
4776 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004777 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004778 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004779 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004780 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004781
danfe33e392015-11-17 20:56:06 +00004782#ifdef SQLITE_MMAP_READWRITE
dane6ecd662013-04-01 17:56:59 +00004783 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
danfe33e392015-11-17 20:56:06 +00004784#endif
dane6ecd662013-04-01 17:56:59 +00004785
4786 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00004787#if HAVE_MREMAP
4788 i64 nReuse = pFd->mmapSize;
4789#else
danbc760632014-03-20 09:42:09 +00004790 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00004791 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00004792#endif
dane6ecd662013-04-01 17:56:59 +00004793 u8 *pReq = &pOrig[nReuse];
4794
4795 /* Unmap any pages of the existing mapping that cannot be reused. */
4796 if( nReuse!=nOrig ){
4797 osMunmap(pReq, nOrig-nReuse);
4798 }
4799
4800#if HAVE_MREMAP
4801 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004802 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004803#else
4804 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4805 if( pNew!=MAP_FAILED ){
4806 if( pNew!=pReq ){
4807 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004808 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004809 }else{
4810 pNew = pOrig;
4811 }
4812 }
4813#endif
4814
dan48ccef82013-04-02 20:55:01 +00004815 /* The attempt to extend the existing mapping failed. Free it. */
4816 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004817 osMunmap(pOrig, nReuse);
4818 }
4819 }
4820
4821 /* If pNew is still NULL, try to create an entirely new mapping. */
4822 if( pNew==0 ){
4823 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004824 }
4825
dan4ff7bc42013-04-02 12:04:09 +00004826 if( pNew==MAP_FAILED ){
4827 pNew = 0;
4828 nNew = 0;
4829 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4830
4831 /* If the mmap() above failed, assume that all subsequent mmap() calls
4832 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4833 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004834 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004835 }
dane6ecd662013-04-01 17:56:59 +00004836 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004837 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004838}
4839
4840/*
danaef49d72013-03-25 16:28:54 +00004841** Memory map or remap the file opened by file-descriptor pFd (if the file
4842** is already mapped, the existing mapping is replaced by the new). Or, if
4843** there already exists a mapping for this file, and there are still
4844** outstanding xFetch() references to it, this function is a no-op.
4845**
4846** If parameter nByte is non-negative, then it is the requested size of
4847** the mapping to create. Otherwise, if nByte is less than zero, then the
4848** requested size is the size of the file on disk. The actual size of the
4849** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004850** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004851**
4852** SQLITE_OK is returned if no error occurs (even if the mapping is not
4853** recreated as a result of outstanding references) or an SQLite error
4854** code otherwise.
4855*/
danf23da962013-03-23 21:00:41 +00004856static int unixMapfile(unixFile *pFd, i64 nByte){
4857 i64 nMap = nByte;
4858 int rc;
daneb97b292013-03-20 14:26:59 +00004859
danf23da962013-03-23 21:00:41 +00004860 assert( nMap>=0 || pFd->nFetchOut==0 );
4861 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4862
4863 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00004864 struct stat statbuf; /* Low-level file information */
4865 rc = osFstat(pFd->h, &statbuf);
danf23da962013-03-23 21:00:41 +00004866 if( rc!=SQLITE_OK ){
4867 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004868 }
drh3044b512014-06-16 16:41:52 +00004869 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00004870 }
drh9b4c59f2013-04-15 17:03:42 +00004871 if( nMap>pFd->mmapSizeMax ){
4872 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004873 }
4874
danf23da962013-03-23 21:00:41 +00004875 if( nMap!=pFd->mmapSize ){
dane6ecd662013-04-01 17:56:59 +00004876 if( nMap>0 ){
4877 unixRemapfile(pFd, nMap);
4878 }else{
danb7e3a322013-03-25 20:30:13 +00004879 unixUnmapfile(pFd);
dan5d8a1372013-03-19 19:28:06 +00004880 }
4881 }
4882
danf23da962013-03-23 21:00:41 +00004883 return SQLITE_OK;
4884}
mistachkine98844f2013-08-24 00:59:24 +00004885#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004886
danaef49d72013-03-25 16:28:54 +00004887/*
4888** If possible, return a pointer to a mapping of file fd starting at offset
4889** iOff. The mapping must be valid for at least nAmt bytes.
4890**
4891** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4892** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4893** Finally, if an error does occur, return an SQLite error code. The final
4894** value of *pp is undefined in this case.
4895**
4896** If this function does return a pointer, the caller must eventually
4897** release the reference by calling unixUnfetch().
4898*/
danf23da962013-03-23 21:00:41 +00004899static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004900#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004901 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004902#endif
danf23da962013-03-23 21:00:41 +00004903 *pp = 0;
4904
drh9b4c59f2013-04-15 17:03:42 +00004905#if SQLITE_MAX_MMAP_SIZE>0
4906 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004907 if( pFd->pMapRegion==0 ){
4908 int rc = unixMapfile(pFd, -1);
4909 if( rc!=SQLITE_OK ) return rc;
4910 }
4911 if( pFd->mmapSize >= iOff+nAmt ){
4912 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4913 pFd->nFetchOut++;
4914 }
4915 }
drh6e0b6d52013-04-09 16:19:20 +00004916#endif
danf23da962013-03-23 21:00:41 +00004917 return SQLITE_OK;
4918}
4919
danaef49d72013-03-25 16:28:54 +00004920/*
dandf737fe2013-03-25 17:00:24 +00004921** If the third argument is non-NULL, then this function releases a
4922** reference obtained by an earlier call to unixFetch(). The second
4923** argument passed to this function must be the same as the corresponding
4924** argument that was passed to the unixFetch() invocation.
4925**
4926** Or, if the third argument is NULL, then this function is being called
4927** to inform the VFS layer that, according to POSIX, any existing mapping
4928** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004929*/
dandf737fe2013-03-25 17:00:24 +00004930static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00004931#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00004932 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00004933 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00004934
danaef49d72013-03-25 16:28:54 +00004935 /* If p==0 (unmap the entire file) then there must be no outstanding
4936 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4937 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004938 assert( (p==0)==(pFd->nFetchOut==0) );
4939
dandf737fe2013-03-25 17:00:24 +00004940 /* If p!=0, it must match the iOff value. */
4941 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4942
danf23da962013-03-23 21:00:41 +00004943 if( p ){
4944 pFd->nFetchOut--;
4945 }else{
4946 unixUnmapfile(pFd);
4947 }
4948
4949 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00004950#else
4951 UNUSED_PARAMETER(fd);
4952 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00004953 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00004954#endif
danf23da962013-03-23 21:00:41 +00004955 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004956}
4957
4958/*
drh734c9862008-11-28 15:37:20 +00004959** Here ends the implementation of all sqlite3_file methods.
4960**
4961********************** End sqlite3_file Methods *******************************
4962******************************************************************************/
4963
4964/*
drh6b9d6dd2008-12-03 19:34:47 +00004965** This division contains definitions of sqlite3_io_methods objects that
4966** implement various file locking strategies. It also contains definitions
4967** of "finder" functions. A finder-function is used to locate the appropriate
4968** sqlite3_io_methods object for a particular database file. The pAppData
4969** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4970** the correct finder-function for that VFS.
4971**
4972** Most finder functions return a pointer to a fixed sqlite3_io_methods
4973** object. The only interesting finder-function is autolockIoFinder, which
4974** looks at the filesystem type and tries to guess the best locking
4975** strategy from that.
4976**
peter.d.reid60ec9142014-09-06 16:39:46 +00004977** For finder-function F, two objects are created:
drh1875f7a2008-12-08 18:19:17 +00004978**
4979** (1) The real finder-function named "FImpt()".
4980**
dane946c392009-08-22 11:39:46 +00004981** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004982**
4983**
4984** A pointer to the F pointer is used as the pAppData value for VFS
4985** objects. We have to do this instead of letting pAppData point
4986** directly at the finder-function since C90 rules prevent a void*
4987** from be cast into a function pointer.
4988**
drh6b9d6dd2008-12-03 19:34:47 +00004989**
drh7708e972008-11-29 00:56:52 +00004990** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004991**
drh7708e972008-11-29 00:56:52 +00004992** * A constant sqlite3_io_methods object call METHOD that has locking
4993** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4994**
4995** * An I/O method finder function called FINDER that returns a pointer
4996** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004997*/
drhe6d41732015-02-21 00:49:00 +00004998#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
drh7708e972008-11-29 00:56:52 +00004999static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00005000 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00005001 CLOSE, /* xClose */ \
5002 unixRead, /* xRead */ \
5003 unixWrite, /* xWrite */ \
5004 unixTruncate, /* xTruncate */ \
5005 unixSync, /* xSync */ \
5006 unixFileSize, /* xFileSize */ \
5007 LOCK, /* xLock */ \
5008 UNLOCK, /* xUnlock */ \
5009 CKLOCK, /* xCheckReservedLock */ \
5010 unixFileControl, /* xFileControl */ \
5011 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00005012 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drhd9f94412014-09-22 03:22:27 +00005013 SHMMAP, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00005014 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00005015 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00005016 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00005017 unixFetch, /* xFetch */ \
5018 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00005019}; \
drh0c2694b2009-09-03 16:23:44 +00005020static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
5021 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00005022 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00005023} \
drh0c2694b2009-09-03 16:23:44 +00005024static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00005025 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00005026
5027/*
5028** Here are all of the sqlite3_io_methods objects for each of the
5029** locking strategies. Functions that return pointers to these methods
5030** are also created.
5031*/
5032IOMETHODS(
5033 posixIoFinder, /* Finder function name */
5034 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00005035 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00005036 unixClose, /* xClose method */
5037 unixLock, /* xLock method */
5038 unixUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005039 unixCheckReservedLock, /* xCheckReservedLock method */
5040 unixShmMap /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005041)
drh7708e972008-11-29 00:56:52 +00005042IOMETHODS(
5043 nolockIoFinder, /* Finder function name */
5044 nolockIoMethods, /* sqlite3_io_methods object name */
drh142341c2014-09-19 19:00:48 +00005045 3, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005046 nolockClose, /* xClose method */
5047 nolockLock, /* xLock method */
5048 nolockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005049 nolockCheckReservedLock, /* xCheckReservedLock method */
5050 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005051)
drh7708e972008-11-29 00:56:52 +00005052IOMETHODS(
5053 dotlockIoFinder, /* Finder function name */
5054 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005055 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005056 dotlockClose, /* xClose method */
5057 dotlockLock, /* xLock method */
5058 dotlockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005059 dotlockCheckReservedLock, /* xCheckReservedLock method */
5060 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005061)
drh7708e972008-11-29 00:56:52 +00005062
drhe89b2912015-03-03 20:42:01 +00005063#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005064IOMETHODS(
5065 flockIoFinder, /* Finder function name */
5066 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005067 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005068 flockClose, /* xClose method */
5069 flockLock, /* xLock method */
5070 flockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005071 flockCheckReservedLock, /* xCheckReservedLock method */
5072 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005073)
drh7708e972008-11-29 00:56:52 +00005074#endif
5075
drh6c7d5c52008-11-21 20:32:33 +00005076#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005077IOMETHODS(
5078 semIoFinder, /* Finder function name */
5079 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005080 1, /* shared memory is disabled */
drh8cd5b252015-03-02 22:06:43 +00005081 semXClose, /* xClose method */
5082 semXLock, /* xLock method */
5083 semXUnlock, /* xUnlock method */
5084 semXCheckReservedLock, /* xCheckReservedLock method */
drhd9f94412014-09-22 03:22:27 +00005085 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005086)
aswiftaebf4132008-11-21 00:10:35 +00005087#endif
drh7708e972008-11-29 00:56:52 +00005088
drhd2cb50b2009-01-09 21:41:17 +00005089#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005090IOMETHODS(
5091 afpIoFinder, /* Finder function name */
5092 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005093 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005094 afpClose, /* xClose method */
5095 afpLock, /* xLock method */
5096 afpUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005097 afpCheckReservedLock, /* xCheckReservedLock method */
5098 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005099)
drh715ff302008-12-03 22:32:44 +00005100#endif
5101
5102/*
5103** The proxy locking method is a "super-method" in the sense that it
5104** opens secondary file descriptors for the conch and lock files and
5105** it uses proxy, dot-file, AFP, and flock() locking methods on those
5106** secondary files. For this reason, the division that implements
5107** proxy locking is located much further down in the file. But we need
5108** to go ahead and define the sqlite3_io_methods and finder function
5109** for proxy locking here. So we forward declare the I/O methods.
5110*/
drhd2cb50b2009-01-09 21:41:17 +00005111#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005112static int proxyClose(sqlite3_file*);
5113static int proxyLock(sqlite3_file*, int);
5114static int proxyUnlock(sqlite3_file*, int);
5115static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005116IOMETHODS(
5117 proxyIoFinder, /* Finder function name */
5118 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005119 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005120 proxyClose, /* xClose method */
5121 proxyLock, /* xLock method */
5122 proxyUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005123 proxyCheckReservedLock, /* xCheckReservedLock method */
5124 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005125)
aswiftaebf4132008-11-21 00:10:35 +00005126#endif
drh7708e972008-11-29 00:56:52 +00005127
drh7ed97b92010-01-20 13:07:21 +00005128/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5129#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5130IOMETHODS(
5131 nfsIoFinder, /* Finder function name */
5132 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005133 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005134 unixClose, /* xClose method */
5135 unixLock, /* xLock method */
5136 nfsUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005137 unixCheckReservedLock, /* xCheckReservedLock method */
5138 0 /* xShmMap method */
drh7ed97b92010-01-20 13:07:21 +00005139)
5140#endif
drh7708e972008-11-29 00:56:52 +00005141
drhd2cb50b2009-01-09 21:41:17 +00005142#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005143/*
drh6b9d6dd2008-12-03 19:34:47 +00005144** This "finder" function attempts to determine the best locking strategy
5145** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005146** object that implements that strategy.
5147**
5148** This is for MacOSX only.
5149*/
drh1875f7a2008-12-08 18:19:17 +00005150static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005151 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005152 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005153){
5154 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005155 const char *zFilesystem; /* Filesystem type name */
5156 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005157 } aMap[] = {
5158 { "hfs", &posixIoMethods },
5159 { "ufs", &posixIoMethods },
5160 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005161 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005162 { "webdav", &nolockIoMethods },
5163 { 0, 0 }
5164 };
5165 int i;
5166 struct statfs fsInfo;
5167 struct flock lockInfo;
5168
5169 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005170 /* If filePath==NULL that means we are dealing with a transient file
5171 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005172 return &nolockIoMethods;
5173 }
5174 if( statfs(filePath, &fsInfo) != -1 ){
5175 if( fsInfo.f_flags & MNT_RDONLY ){
5176 return &nolockIoMethods;
5177 }
5178 for(i=0; aMap[i].zFilesystem; i++){
5179 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5180 return aMap[i].pMethods;
5181 }
5182 }
5183 }
5184
5185 /* Default case. Handles, amongst others, "nfs".
5186 ** Test byte-range lock using fcntl(). If the call succeeds,
5187 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005188 */
drh7708e972008-11-29 00:56:52 +00005189 lockInfo.l_len = 1;
5190 lockInfo.l_start = 0;
5191 lockInfo.l_whence = SEEK_SET;
5192 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005193 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005194 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5195 return &nfsIoMethods;
5196 } else {
5197 return &posixIoMethods;
5198 }
drh7708e972008-11-29 00:56:52 +00005199 }else{
5200 return &dotlockIoMethods;
5201 }
5202}
drh0c2694b2009-09-03 16:23:44 +00005203static const sqlite3_io_methods
5204 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005205
drhd2cb50b2009-01-09 21:41:17 +00005206#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005207
drhe89b2912015-03-03 20:42:01 +00005208#if OS_VXWORKS
5209/*
5210** This "finder" function for VxWorks checks to see if posix advisory
5211** locking works. If it does, then that is what is used. If it does not
5212** work, then fallback to named semaphore locking.
chw78a13182009-04-07 05:35:03 +00005213*/
drhe89b2912015-03-03 20:42:01 +00005214static const sqlite3_io_methods *vxworksIoFinderImpl(
chw78a13182009-04-07 05:35:03 +00005215 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005216 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005217){
5218 struct flock lockInfo;
5219
5220 if( !filePath ){
5221 /* If filePath==NULL that means we are dealing with a transient file
5222 ** that does not need to be locked. */
5223 return &nolockIoMethods;
5224 }
5225
5226 /* Test if fcntl() is supported and use POSIX style locks.
5227 ** Otherwise fall back to the named semaphore method.
5228 */
5229 lockInfo.l_len = 1;
5230 lockInfo.l_start = 0;
5231 lockInfo.l_whence = SEEK_SET;
5232 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005233 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005234 return &posixIoMethods;
5235 }else{
5236 return &semIoMethods;
5237 }
5238}
drh0c2694b2009-09-03 16:23:44 +00005239static const sqlite3_io_methods
drhe89b2912015-03-03 20:42:01 +00005240 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005241
drhe89b2912015-03-03 20:42:01 +00005242#endif /* OS_VXWORKS */
chw78a13182009-04-07 05:35:03 +00005243
drh7708e972008-11-29 00:56:52 +00005244/*
peter.d.reid60ec9142014-09-06 16:39:46 +00005245** An abstract type for a pointer to an IO method finder function:
drh7708e972008-11-29 00:56:52 +00005246*/
drh0c2694b2009-09-03 16:23:44 +00005247typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005248
aswiftaebf4132008-11-21 00:10:35 +00005249
drh734c9862008-11-28 15:37:20 +00005250/****************************************************************************
5251**************************** sqlite3_vfs methods ****************************
5252**
5253** This division contains the implementation of methods on the
5254** sqlite3_vfs object.
5255*/
5256
danielk1977a3d4c882007-03-23 10:08:38 +00005257/*
danielk1977e339d652008-06-28 11:23:00 +00005258** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005259*/
5260static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005261 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005262 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005263 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005264 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005265 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005266){
drh7708e972008-11-29 00:56:52 +00005267 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005268 unixFile *pNew = (unixFile *)pId;
5269 int rc = SQLITE_OK;
5270
drh8af6c222010-05-14 12:43:01 +00005271 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005272
dan00157392010-10-05 11:33:15 +00005273 /* Usually the path zFilename should not be a relative pathname. The
5274 ** exception is when opening the proxy "conch" file in builds that
5275 ** include the special Apple locking styles.
5276 */
dan00157392010-10-05 11:33:15 +00005277#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005278 assert( zFilename==0 || zFilename[0]=='/'
5279 || pVfs->pAppData==(void*)&autolockIoFinder );
5280#else
5281 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005282#endif
dan00157392010-10-05 11:33:15 +00005283
drhb07028f2011-10-14 21:49:18 +00005284 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005285 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005286
drh308c2a52010-05-14 11:30:18 +00005287 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005288 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005289 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005290 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005291 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005292#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005293 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005294#endif
drhc02a43a2012-01-10 23:18:38 +00005295 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5296 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005297 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005298 }
drh503a6862013-03-01 01:07:17 +00005299 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005300 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005301 }
drh339eb0b2008-03-07 15:34:11 +00005302
drh6c7d5c52008-11-21 20:32:33 +00005303#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005304 pNew->pId = vxworksFindFileId(zFilename);
5305 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005306 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00005307 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00005308 }
5309#endif
5310
drhc02a43a2012-01-10 23:18:38 +00005311 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005312 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005313 }else{
drh0c2694b2009-09-03 16:23:44 +00005314 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005315#if SQLITE_ENABLE_LOCKING_STYLE
5316 /* Cache zFilename in the locking context (AFP and dotlock override) for
5317 ** proxyLock activation is possible (remote proxy is based on db name)
5318 ** zFilename remains valid until file is closed, to support */
5319 pNew->lockingContext = (void*)zFilename;
5320#endif
drhda0e7682008-07-30 15:27:54 +00005321 }
danielk1977e339d652008-06-28 11:23:00 +00005322
drh7ed97b92010-01-20 13:07:21 +00005323 if( pLockingStyle == &posixIoMethods
5324#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5325 || pLockingStyle == &nfsIoMethods
5326#endif
5327 ){
drh7708e972008-11-29 00:56:52 +00005328 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005329 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005330 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005331 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005332 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005333 ** in two scenarios:
5334 **
5335 ** (a) A call to fstat() failed.
5336 ** (b) A malloc failed.
5337 **
5338 ** Scenario (b) may only occur if the process is holding no other
5339 ** file descriptors open on the same file. If there were other file
5340 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005341 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005342 ** handle h - as it is guaranteed that no posix locks will be released
5343 ** by doing so.
5344 **
5345 ** If scenario (a) caused the error then things are not so safe. The
5346 ** implicit assumption here is that if fstat() fails, things are in
5347 ** such bad shape that dropping a lock or two doesn't matter much.
5348 */
drh0e9365c2011-03-02 02:08:13 +00005349 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005350 h = -1;
5351 }
drh7708e972008-11-29 00:56:52 +00005352 unixLeaveMutex();
5353 }
danielk1977e339d652008-06-28 11:23:00 +00005354
drhd2cb50b2009-01-09 21:41:17 +00005355#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005356 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005357 /* AFP locking uses the file path so it needs to be included in
5358 ** the afpLockingContext.
5359 */
5360 afpLockingContext *pCtx;
drhf3cdcdc2015-04-29 16:50:28 +00005361 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh7708e972008-11-29 00:56:52 +00005362 if( pCtx==0 ){
5363 rc = SQLITE_NOMEM;
5364 }else{
5365 /* NB: zFilename exists and remains valid until the file is closed
5366 ** according to requirement F11141. So we do not need to make a
5367 ** copy of the filename. */
5368 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005369 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005370 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005371 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005372 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005373 if( rc!=SQLITE_OK ){
5374 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005375 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005376 h = -1;
5377 }
drh7708e972008-11-29 00:56:52 +00005378 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005379 }
drh7708e972008-11-29 00:56:52 +00005380 }
5381#endif
danielk1977e339d652008-06-28 11:23:00 +00005382
drh7708e972008-11-29 00:56:52 +00005383 else if( pLockingStyle == &dotlockIoMethods ){
5384 /* Dotfile locking uses the file path so it needs to be included in
5385 ** the dotlockLockingContext
5386 */
5387 char *zLockFile;
5388 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005389 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005390 nFilename = (int)strlen(zFilename) + 6;
drhf3cdcdc2015-04-29 16:50:28 +00005391 zLockFile = (char *)sqlite3_malloc64(nFilename);
drh7708e972008-11-29 00:56:52 +00005392 if( zLockFile==0 ){
5393 rc = SQLITE_NOMEM;
5394 }else{
5395 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005396 }
drh7708e972008-11-29 00:56:52 +00005397 pNew->lockingContext = zLockFile;
5398 }
danielk1977e339d652008-06-28 11:23:00 +00005399
drh6c7d5c52008-11-21 20:32:33 +00005400#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005401 else if( pLockingStyle == &semIoMethods ){
5402 /* Named semaphore locking uses the file path so it needs to be
5403 ** included in the semLockingContext
5404 */
5405 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005406 rc = findInodeInfo(pNew, &pNew->pInode);
5407 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5408 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005409 int n;
drh2238dcc2009-08-27 17:56:20 +00005410 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005411 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005412 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005413 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005414 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5415 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00005416 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00005417 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005418 }
chw97185482008-11-17 08:05:31 +00005419 }
drh7708e972008-11-29 00:56:52 +00005420 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005421 }
drh7708e972008-11-29 00:56:52 +00005422#endif
aswift5b1a2562008-08-22 00:22:35 +00005423
drh4bf66fd2015-02-19 02:43:02 +00005424 storeLastErrno(pNew, 0);
drh6c7d5c52008-11-21 20:32:33 +00005425#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005426 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005427 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005428 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005429 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005430 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005431 }
chw97185482008-11-17 08:05:31 +00005432#endif
danielk1977e339d652008-06-28 11:23:00 +00005433 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005434 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005435 }else{
drh7708e972008-11-29 00:56:52 +00005436 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005437 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005438 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005439 }
danielk1977e339d652008-06-28 11:23:00 +00005440 return rc;
drh054889e2005-11-30 03:20:31 +00005441}
drh9c06c952005-11-26 00:25:00 +00005442
danielk1977ad94b582007-08-20 06:44:22 +00005443/*
drh8b3cf822010-06-01 21:02:51 +00005444** Return the name of a directory in which to put temporary files.
5445** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005446*/
drh7234c6d2010-06-19 15:10:09 +00005447static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005448 static const char *azDirs[] = {
5449 0,
aswiftaebf4132008-11-21 00:10:35 +00005450 0,
mistachkind95a3d32013-08-30 21:52:38 +00005451 0,
danielk197717b90b52008-06-06 11:11:25 +00005452 "/var/tmp",
5453 "/usr/tmp",
5454 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00005455 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00005456 };
drh8b3cf822010-06-01 21:02:51 +00005457 unsigned int i;
5458 struct stat buf;
5459 const char *zDir = 0;
5460
5461 azDirs[0] = sqlite3_temp_directory;
mistachkind95a3d32013-08-30 21:52:38 +00005462 if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
5463 if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005464 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005465 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005466 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005467 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005468 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005469 break;
5470 }
5471 return zDir;
5472}
5473
5474/*
5475** Create a temporary file name in zBuf. zBuf must be allocated
5476** by the calling process and must be big enough to hold at least
5477** pVfs->mxPathname bytes.
5478*/
5479static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00005480 static const unsigned char zChars[] =
5481 "abcdefghijklmnopqrstuvwxyz"
5482 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
5483 "0123456789";
drh41022642008-11-21 00:24:42 +00005484 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00005485 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00005486
5487 /* It's odd to simulate an io-error here, but really this is just
5488 ** using the io-error infrastructure to test that SQLite handles this
5489 ** function failing.
5490 */
5491 SimulateIOError( return SQLITE_IOERR );
5492
drh7234c6d2010-06-19 15:10:09 +00005493 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00005494 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00005495
5496 /* Check that the output buffer is large enough for the temporary file
5497 ** name. If it is not, return SQLITE_ERROR.
5498 */
drhc02a43a2012-01-10 23:18:38 +00005499 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00005500 return SQLITE_ERROR;
5501 }
5502
5503 do{
drhc02a43a2012-01-10 23:18:38 +00005504 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00005505 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00005506 sqlite3_randomness(15, &zBuf[j]);
5507 for(i=0; i<15; i++, j++){
5508 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
5509 }
5510 zBuf[j] = 0;
drhc02a43a2012-01-10 23:18:38 +00005511 zBuf[j+1] = 0;
drh99ab3b12011-03-02 15:09:07 +00005512 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005513 return SQLITE_OK;
5514}
5515
drhd2cb50b2009-01-09 21:41:17 +00005516#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005517/*
5518** Routine to transform a unixFile into a proxy-locking unixFile.
5519** Implementation in the proxy-lock division, but used by unixOpen()
5520** if SQLITE_PREFER_PROXY_LOCKING is defined.
5521*/
5522static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005523#endif
drhc66d5b62008-12-03 22:48:32 +00005524
dan08da86a2009-08-21 17:18:03 +00005525/*
5526** Search for an unused file descriptor that was opened on the database
5527** file (not a journal or master-journal file) identified by pathname
5528** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5529** argument to this function.
5530**
5531** Such a file descriptor may exist if a database connection was closed
5532** but the associated file descriptor could not be closed because some
5533** other file descriptor open on the same file is holding a file-lock.
5534** Refer to comments in the unixClose() function and the lengthy comment
5535** describing "Posix Advisory Locking" at the start of this file for
5536** further details. Also, ticket #4018.
5537**
5538** If a suitable file descriptor is found, then it is returned. If no
5539** such file descriptor is located, -1 is returned.
5540*/
dane946c392009-08-22 11:39:46 +00005541static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5542 UnixUnusedFd *pUnused = 0;
5543
5544 /* Do not search for an unused file descriptor on vxworks. Not because
5545 ** vxworks would not benefit from the change (it might, we're not sure),
5546 ** but because no way to test it is currently available. It is better
5547 ** not to risk breaking vxworks support for the sake of such an obscure
5548 ** feature. */
5549#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005550 struct stat sStat; /* Results of stat() call */
5551
5552 /* A stat() call may fail for various reasons. If this happens, it is
5553 ** almost certain that an open() call on the same path will also fail.
5554 ** For this reason, if an error occurs in the stat() call here, it is
5555 ** ignored and -1 is returned. The caller will try to open a new file
5556 ** descriptor on the same path, fail, and return an error to SQLite.
5557 **
5558 ** Even if a subsequent open() call does succeed, the consequences of
peter.d.reid60ec9142014-09-06 16:39:46 +00005559 ** not searching for a reusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005560 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005561 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005562
5563 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005564 pInode = inodeList;
5565 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5566 || pInode->fileId.ino!=sStat.st_ino) ){
5567 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005568 }
drh8af6c222010-05-14 12:43:01 +00005569 if( pInode ){
dane946c392009-08-22 11:39:46 +00005570 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005571 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005572 pUnused = *pp;
5573 if( pUnused ){
5574 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005575 }
5576 }
5577 unixLeaveMutex();
5578 }
dane946c392009-08-22 11:39:46 +00005579#endif /* if !OS_VXWORKS */
5580 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005581}
danielk197717b90b52008-06-06 11:11:25 +00005582
5583/*
danddb0ac42010-07-14 14:48:58 +00005584** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005585** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005586** and a value suitable for passing as the third argument to open(2) is
5587** written to *pMode. If an IO error occurs, an SQLite error code is
5588** returned and the value of *pMode is not modified.
5589**
peter.d.reid60ec9142014-09-06 16:39:46 +00005590** In most cases, this routine sets *pMode to 0, which will become
drh8c815d12012-02-13 20:16:37 +00005591** an indication to robust_open() to create the file using
5592** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5593** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005594** this function queries the file-system for the permissions on the
5595** corresponding database file and sets *pMode to this value. Whenever
5596** possible, WAL and journal files are created using the same permissions
5597** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005598**
5599** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5600** original filename is unavailable. But 8_3_NAMES is only used for
5601** FAT filesystems and permissions do not matter there, so just use
5602** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005603*/
5604static int findCreateFileMode(
5605 const char *zPath, /* Path of file (possibly) being created */
5606 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005607 mode_t *pMode, /* OUT: Permissions to open file with */
5608 uid_t *pUid, /* OUT: uid to set on the file */
5609 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005610){
5611 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005612 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005613 *pUid = 0;
5614 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005615 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005616 char zDb[MAX_PATHNAME+1]; /* Database file path */
5617 int nDb; /* Number of valid bytes in zDb */
5618 struct stat sStat; /* Output of stat() on database file */
5619
dana0c989d2010-11-05 18:07:37 +00005620 /* zPath is a path to a WAL or journal file. The following block derives
5621 ** the path to the associated database file from zPath. This block handles
5622 ** the following naming conventions:
5623 **
5624 ** "<path to db>-journal"
5625 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005626 ** "<path to db>-journalNN"
5627 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005628 **
drhd337c5b2011-10-20 18:23:35 +00005629 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005630 ** used by the test_multiplex.c module.
5631 */
5632 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005633#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00005634 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00005635 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005636#else
5637 while( zPath[nDb]!='-' ){
5638 assert( nDb>0 );
5639 assert( zPath[nDb]!='\n' );
5640 nDb--;
5641 }
5642#endif
danddb0ac42010-07-14 14:48:58 +00005643 memcpy(zDb, zPath, nDb);
5644 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005645
drh58384f12011-07-28 00:14:45 +00005646 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005647 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005648 *pUid = sStat.st_uid;
5649 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005650 }else{
5651 rc = SQLITE_IOERR_FSTAT;
5652 }
5653 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5654 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005655 }
5656 return rc;
5657}
5658
5659/*
danielk1977ad94b582007-08-20 06:44:22 +00005660** Open the file zPath.
5661**
danielk1977b4b47412007-08-17 15:53:36 +00005662** Previously, the SQLite OS layer used three functions in place of this
5663** one:
5664**
5665** sqlite3OsOpenReadWrite();
5666** sqlite3OsOpenReadOnly();
5667** sqlite3OsOpenExclusive();
5668**
5669** These calls correspond to the following combinations of flags:
5670**
5671** ReadWrite() -> (READWRITE | CREATE)
5672** ReadOnly() -> (READONLY)
5673** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5674**
5675** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5676** true, the file was configured to be automatically deleted when the
5677** file handle closed. To achieve the same effect using this new
5678** interface, add the DELETEONCLOSE flag to those specified above for
5679** OpenExclusive().
5680*/
5681static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005682 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5683 const char *zPath, /* Pathname of file to be opened */
5684 sqlite3_file *pFile, /* The file descriptor to be filled in */
5685 int flags, /* Input flags to control the opening */
5686 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005687){
dan08da86a2009-08-21 17:18:03 +00005688 unixFile *p = (unixFile *)pFile;
5689 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005690 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005691 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005692 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005693 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005694 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005695
5696 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5697 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5698 int isCreate = (flags & SQLITE_OPEN_CREATE);
5699 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5700 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005701#if SQLITE_ENABLE_LOCKING_STYLE
5702 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5703#endif
drh3d4435b2011-08-26 20:55:50 +00005704#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5705 struct statfs fsInfo;
5706#endif
danielk1977b4b47412007-08-17 15:53:36 +00005707
danielk1977fee2d252007-08-18 10:59:19 +00005708 /* If creating a master or main-file journal, this function will open
5709 ** a file-descriptor on the directory too. The first time unixSync()
5710 ** is called the directory file descriptor will be fsync()ed and close()d.
5711 */
drh0059eae2011-08-08 23:48:40 +00005712 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005713 eType==SQLITE_OPEN_MASTER_JOURNAL
5714 || eType==SQLITE_OPEN_MAIN_JOURNAL
5715 || eType==SQLITE_OPEN_WAL
5716 ));
danielk1977fee2d252007-08-18 10:59:19 +00005717
danielk197717b90b52008-06-06 11:11:25 +00005718 /* If argument zPath is a NULL pointer, this function is required to open
5719 ** a temporary file. Use this buffer to store the file name in.
5720 */
drhc02a43a2012-01-10 23:18:38 +00005721 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005722 const char *zName = zPath;
5723
danielk1977fee2d252007-08-18 10:59:19 +00005724 /* Check the following statements are true:
5725 **
5726 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5727 ** (b) if CREATE is set, then READWRITE must also be set, and
5728 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005729 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005730 */
danielk1977b4b47412007-08-17 15:53:36 +00005731 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005732 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005733 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005734 assert(isDelete==0 || isCreate);
5735
danddb0ac42010-07-14 14:48:58 +00005736 /* The main DB, main journal, WAL file and master journal are never
5737 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005738 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5739 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5740 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005741 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005742
danielk1977fee2d252007-08-18 10:59:19 +00005743 /* Assert that the upper layer has set one of the "file-type" flags. */
5744 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5745 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5746 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005747 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005748 );
5749
drhb00d8622014-01-01 15:18:36 +00005750 /* Detect a pid change and reset the PRNG. There is a race condition
5751 ** here such that two or more threads all trying to open databases at
5752 ** the same instant might all reset the PRNG. But multiple resets
5753 ** are harmless.
5754 */
drh5ac93652015-03-21 20:59:43 +00005755 if( randomnessPid!=osGetpid(0) ){
5756 randomnessPid = osGetpid(0);
drhb00d8622014-01-01 15:18:36 +00005757 sqlite3_randomness(0,0);
5758 }
5759
dan08da86a2009-08-21 17:18:03 +00005760 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005761
dan08da86a2009-08-21 17:18:03 +00005762 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005763 UnixUnusedFd *pUnused;
5764 pUnused = findReusableFd(zName, flags);
5765 if( pUnused ){
5766 fd = pUnused->fd;
5767 }else{
drhf3cdcdc2015-04-29 16:50:28 +00005768 pUnused = sqlite3_malloc64(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005769 if( !pUnused ){
5770 return SQLITE_NOMEM;
5771 }
5772 }
5773 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005774
5775 /* Database filenames are double-zero terminated if they are not
5776 ** URIs with parameters. Hence, they can always be passed into
5777 ** sqlite3_uri_parameter(). */
5778 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5779
dan08da86a2009-08-21 17:18:03 +00005780 }else if( !zName ){
5781 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005782 assert(isDelete && !syncDir);
drhc02a43a2012-01-10 23:18:38 +00005783 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005784 if( rc!=SQLITE_OK ){
5785 return rc;
5786 }
5787 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005788
5789 /* Generated temporary filenames are always double-zero terminated
5790 ** for use by sqlite3_uri_parameter(). */
5791 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005792 }
5793
dan08da86a2009-08-21 17:18:03 +00005794 /* Determine the value of the flags parameter passed to POSIX function
5795 ** open(). These must be calculated even if open() is not called, as
5796 ** they may be stored as part of the file handle and used by the
5797 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005798 if( isReadonly ) openFlags |= O_RDONLY;
5799 if( isReadWrite ) openFlags |= O_RDWR;
5800 if( isCreate ) openFlags |= O_CREAT;
5801 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5802 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005803
danielk1977b4b47412007-08-17 15:53:36 +00005804 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005805 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005806 uid_t uid; /* Userid for the file */
5807 gid_t gid; /* Groupid for the file */
5808 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005809 if( rc!=SQLITE_OK ){
5810 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005811 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005812 return rc;
5813 }
drhad4f1e52011-03-04 15:43:57 +00005814 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005815 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005816 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5817 /* Failed to open the file for read/write access. Try read-only. */
5818 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005819 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005820 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005821 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005822 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005823 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005824 }
5825 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005826 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005827 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005828 }
drhac7c3ac2012-02-11 19:23:48 +00005829
5830 /* If this process is running as root and if creating a new rollback
5831 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005832 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005833 */
5834 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drh6226ca22015-11-24 15:06:28 +00005835 robustFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005836 }
danielk1977b4b47412007-08-17 15:53:36 +00005837 }
dan08da86a2009-08-21 17:18:03 +00005838 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005839 if( pOutFlags ){
5840 *pOutFlags = flags;
5841 }
5842
dane946c392009-08-22 11:39:46 +00005843 if( p->pUnused ){
5844 p->pUnused->fd = fd;
5845 p->pUnused->flags = flags;
5846 }
5847
danielk1977b4b47412007-08-17 15:53:36 +00005848 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005849#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005850 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00005851#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
5852 zPath = sqlite3_mprintf("%s", zName);
5853 if( zPath==0 ){
5854 robust_close(p, fd, __LINE__);
5855 return SQLITE_NOMEM;
5856 }
chw97185482008-11-17 08:05:31 +00005857#else
drh036ac7f2011-08-08 23:18:05 +00005858 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005859#endif
danielk1977b4b47412007-08-17 15:53:36 +00005860 }
drh41022642008-11-21 00:24:42 +00005861#if SQLITE_ENABLE_LOCKING_STYLE
5862 else{
dan08da86a2009-08-21 17:18:03 +00005863 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005864 }
5865#endif
5866
drhda0e7682008-07-30 15:27:54 +00005867 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005868
drh7ed97b92010-01-20 13:07:21 +00005869
5870#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005871 if( fstatfs(fd, &fsInfo) == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00005872 storeLastErrno(p, errno);
drh0e9365c2011-03-02 02:08:13 +00005873 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005874 return SQLITE_IOERR_ACCESS;
5875 }
5876 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5877 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5878 }
drh4bf66fd2015-02-19 02:43:02 +00005879 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
5880 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5881 }
drh7ed97b92010-01-20 13:07:21 +00005882#endif
drhc02a43a2012-01-10 23:18:38 +00005883
5884 /* Set up appropriate ctrlFlags */
5885 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5886 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5887 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5888 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5889 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5890
drh7ed97b92010-01-20 13:07:21 +00005891#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005892#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005893 isAutoProxy = 1;
5894#endif
5895 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005896 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5897 int useProxy = 0;
5898
dan08da86a2009-08-21 17:18:03 +00005899 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5900 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005901 if( envforce!=NULL ){
5902 useProxy = atoi(envforce)>0;
5903 }else{
aswiftaebf4132008-11-21 00:10:35 +00005904 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5905 }
5906 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005907 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005908 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005909 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005910 if( rc!=SQLITE_OK ){
5911 /* Use unixClose to clean up the resources added in fillInUnixFile
5912 ** and clear all the structure's references. Specifically,
5913 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5914 */
5915 unixClose(pFile);
5916 return rc;
5917 }
aswiftaebf4132008-11-21 00:10:35 +00005918 }
dane946c392009-08-22 11:39:46 +00005919 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005920 }
5921 }
5922#endif
5923
drhc02a43a2012-01-10 23:18:38 +00005924 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5925
dane946c392009-08-22 11:39:46 +00005926open_finished:
5927 if( rc!=SQLITE_OK ){
5928 sqlite3_free(p->pUnused);
5929 }
5930 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005931}
5932
dane946c392009-08-22 11:39:46 +00005933
danielk1977b4b47412007-08-17 15:53:36 +00005934/*
danielk1977fee2d252007-08-18 10:59:19 +00005935** Delete the file at zPath. If the dirSync argument is true, fsync()
5936** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005937*/
drh6b9d6dd2008-12-03 19:34:47 +00005938static int unixDelete(
5939 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5940 const char *zPath, /* Name of file to be deleted */
5941 int dirSync /* If true, fsync() directory after deleting file */
5942){
danielk1977fee2d252007-08-18 10:59:19 +00005943 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005944 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005945 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005946 if( osUnlink(zPath)==(-1) ){
drhbd945542014-08-13 11:39:42 +00005947 if( errno==ENOENT
5948#if OS_VXWORKS
drh19541f32014-09-01 13:37:55 +00005949 || osAccess(zPath,0)!=0
drhbd945542014-08-13 11:39:42 +00005950#endif
5951 ){
dan9fc5b4a2012-11-09 20:17:26 +00005952 rc = SQLITE_IOERR_DELETE_NOENT;
5953 }else{
drhb4308162012-11-09 21:40:02 +00005954 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005955 }
drhb4308162012-11-09 21:40:02 +00005956 return rc;
drh5d4feff2010-07-14 01:45:22 +00005957 }
danielk1977d39fa702008-10-16 13:27:40 +00005958#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005959 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005960 int fd;
drh90315a22011-08-10 01:52:12 +00005961 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005962 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005963#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005964 if( fsync(fd)==-1 )
5965#else
5966 if( fsync(fd) )
5967#endif
5968 {
dane18d4952011-02-21 11:46:24 +00005969 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005970 }
drh0e9365c2011-03-02 02:08:13 +00005971 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005972 }else if( rc==SQLITE_CANTOPEN ){
5973 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005974 }
5975 }
danielk1977d138dd82008-10-15 16:02:48 +00005976#endif
danielk1977fee2d252007-08-18 10:59:19 +00005977 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005978}
5979
danielk197790949c22007-08-17 16:50:38 +00005980/*
mistachkin48864df2013-03-21 21:20:32 +00005981** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00005982** test performed depends on the value of flags:
5983**
5984** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5985** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5986** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5987**
5988** Otherwise return 0.
5989*/
danielk1977861f7452008-06-05 11:39:11 +00005990static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005991 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5992 const char *zPath, /* Path of the file to examine */
5993 int flags, /* What do we want to learn about the zPath file? */
5994 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005995){
rse25c0d1a2007-09-20 08:38:14 +00005996 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005997 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005998 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005999 switch( flags ){
6000 case SQLITE_ACCESS_EXISTS:
6001 amode = F_OK;
6002 break;
6003 case SQLITE_ACCESS_READWRITE:
6004 amode = W_OK|R_OK;
6005 break;
drh50d3f902007-08-27 21:10:36 +00006006 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00006007 amode = R_OK;
6008 break;
6009
6010 default:
6011 assert(!"Invalid flags argument");
6012 }
drh99ab3b12011-03-02 15:09:07 +00006013 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00006014 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
6015 struct stat buf;
drh58384f12011-07-28 00:14:45 +00006016 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00006017 *pResOut = 0;
6018 }
6019 }
danielk1977861f7452008-06-05 11:39:11 +00006020 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006021}
6022
danielk1977b4b47412007-08-17 15:53:36 +00006023
6024/*
6025** Turn a relative pathname into a full pathname. The relative path
6026** is stored as a nul-terminated string in the buffer pointed to by
6027** zPath.
6028**
6029** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
6030** (in this case, MAX_PATHNAME bytes). The full-path is written to
6031** this buffer before returning.
6032*/
danielk1977adfb9b02007-09-17 07:02:56 +00006033static int unixFullPathname(
6034 sqlite3_vfs *pVfs, /* Pointer to vfs object */
6035 const char *zPath, /* Possibly relative input path */
6036 int nOut, /* Size of output buffer in bytes */
6037 char *zOut /* Output buffer */
6038){
dan245fdc62015-10-31 17:58:33 +00006039 int nByte;
danielk1977843e65f2007-09-01 16:16:15 +00006040
6041 /* It's odd to simulate an io-error here, but really this is just
6042 ** using the io-error infrastructure to test that SQLite handles this
6043 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00006044 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00006045 */
6046 SimulateIOError( return SQLITE_ERROR );
6047
drh153c62c2007-08-24 03:51:33 +00006048 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00006049 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00006050
dan245fdc62015-10-31 17:58:33 +00006051 /* Attempt to resolve the path as if it were a symbolic link. If it is
6052 ** a symbolic link, the resolved path is stored in buffer zOut[]. Or, if
6053 ** the identified file is not a symbolic link or does not exist, then
6054 ** zPath is copied directly into zOut. Either way, nByte is left set to
6055 ** the size of the string copied into zOut[] in bytes. */
6056 nByte = osReadlink(zPath, zOut, nOut-1);
6057 if( nByte<0 ){
6058 if( errno!=EINVAL && errno!=ENOENT ){
6059 return unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zPath);
6060 }
6061 zOut[nOut-1] = '\0';
6062 sqlite3_snprintf(nOut-1, zOut, "%s", zPath);
6063 nByte = sqlite3Strlen30(zOut);
danielk1977b4b47412007-08-17 15:53:36 +00006064 }else{
dan245fdc62015-10-31 17:58:33 +00006065 zOut[nByte] = '\0';
6066 }
6067
6068 /* If buffer zOut[] now contains an absolute path there is nothing more
6069 ** to do. If it contains a relative path, do the following:
6070 **
6071 ** * move the relative path string so that it is at the end of th
6072 ** zOut[] buffer.
6073 ** * Call getcwd() to read the path of the current working directory
6074 ** into the start of the zOut[] buffer.
6075 ** * Append a '/' character to the cwd string and move the
6076 ** relative path back within the buffer so that it immediately
6077 ** follows the '/'.
6078 **
6079 ** This code is written so that if the combination of the CWD and relative
6080 ** path are larger than the allocated size of zOut[] the CWD is silently
6081 ** truncated to make it fit. This is Ok, as SQLite refuses to open any
6082 ** file for which this function returns a full path larger than (nOut-8)
6083 ** bytes in size. */
6084 if( zOut[0]!='/' ){
danielk1977b4b47412007-08-17 15:53:36 +00006085 int nCwd;
dan245fdc62015-10-31 17:58:33 +00006086 int nRem = nOut-nByte-1;
6087 memmove(&zOut[nRem], zOut, nByte+1);
6088 zOut[nRem-1] = '\0';
6089 if( osGetcwd(zOut, nRem-1)==0 ){
dane18d4952011-02-21 11:46:24 +00006090 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006091 }
dan245fdc62015-10-31 17:58:33 +00006092 nCwd = sqlite3Strlen30(zOut);
6093 assert( nCwd<=nRem-1 );
6094 zOut[nCwd] = '/';
6095 memmove(&zOut[nCwd+1], &zOut[nRem], nByte+1);
danielk1977b4b47412007-08-17 15:53:36 +00006096 }
dan245fdc62015-10-31 17:58:33 +00006097
danielk1977b4b47412007-08-17 15:53:36 +00006098 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006099}
6100
drh0ccebe72005-06-07 22:22:50 +00006101
drh761df872006-12-21 01:29:22 +00006102#ifndef SQLITE_OMIT_LOAD_EXTENSION
6103/*
6104** Interfaces for opening a shared library, finding entry points
6105** within the shared library, and closing the shared library.
6106*/
6107#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00006108static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6109 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00006110 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6111}
danielk197795c8a542007-09-01 06:51:27 +00006112
6113/*
6114** SQLite calls this function immediately after a call to unixDlSym() or
6115** unixDlOpen() fails (returns a null pointer). If a more detailed error
6116** message is available, it is written to zBufOut. If no error message
6117** is available, zBufOut is left unmodified and SQLite uses a default
6118** error message.
6119*/
danielk1977397d65f2008-11-19 11:35:39 +00006120static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006121 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006122 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006123 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006124 zErr = dlerror();
6125 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006126 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006127 }
drh6c7d5c52008-11-21 20:32:33 +00006128 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006129}
drh1875f7a2008-12-08 18:19:17 +00006130static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6131 /*
6132 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6133 ** cast into a pointer to a function. And yet the library dlsym() routine
6134 ** returns a void* which is really a pointer to a function. So how do we
6135 ** use dlsym() with -pedantic-errors?
6136 **
6137 ** Variable x below is defined to be a pointer to a function taking
6138 ** parameters void* and const char* and returning a pointer to a function.
6139 ** We initialize x by assigning it a pointer to the dlsym() function.
6140 ** (That assignment requires a cast.) Then we call the function that
6141 ** x points to.
6142 **
6143 ** This work-around is unlikely to work correctly on any system where
6144 ** you really cannot cast a function pointer into void*. But then, on the
6145 ** other hand, dlsym() will not work on such a system either, so we have
6146 ** not really lost anything.
6147 */
6148 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006149 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006150 x = (void(*(*)(void*,const char*))(void))dlsym;
6151 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006152}
danielk1977397d65f2008-11-19 11:35:39 +00006153static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6154 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006155 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006156}
danielk1977b4b47412007-08-17 15:53:36 +00006157#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6158 #define unixDlOpen 0
6159 #define unixDlError 0
6160 #define unixDlSym 0
6161 #define unixDlClose 0
6162#endif
6163
6164/*
danielk197790949c22007-08-17 16:50:38 +00006165** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006166*/
danielk1977397d65f2008-11-19 11:35:39 +00006167static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6168 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006169 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006170
drhbbd42a62004-05-22 17:41:58 +00006171 /* We have to initialize zBuf to prevent valgrind from reporting
6172 ** errors. The reports issued by valgrind are incorrect - we would
6173 ** prefer that the randomness be increased by making use of the
6174 ** uninitialized space in zBuf - but valgrind errors tend to worry
6175 ** some users. Rather than argue, it seems easier just to initialize
6176 ** the whole array and silence valgrind, even if that means less randomness
6177 ** in the random seed.
6178 **
6179 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006180 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006181 ** tests repeatable.
6182 */
danielk1977b4b47412007-08-17 15:53:36 +00006183 memset(zBuf, 0, nBuf);
drh5ac93652015-03-21 20:59:43 +00006184 randomnessPid = osGetpid(0);
drh6a412b82015-04-30 12:31:49 +00006185#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
drhbbd42a62004-05-22 17:41:58 +00006186 {
drhb00d8622014-01-01 15:18:36 +00006187 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006188 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006189 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006190 time_t t;
6191 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006192 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006193 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6194 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6195 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006196 }else{
drhc18b4042012-02-10 03:10:27 +00006197 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006198 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006199 }
drhbbd42a62004-05-22 17:41:58 +00006200 }
6201#endif
drh72cbd072008-10-14 17:58:38 +00006202 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006203}
6204
danielk1977b4b47412007-08-17 15:53:36 +00006205
drhbbd42a62004-05-22 17:41:58 +00006206/*
6207** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006208** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006209** The return value is the number of microseconds of sleep actually
6210** requested from the underlying operating system, a number which
6211** might be greater than or equal to the argument, but not less
6212** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006213*/
danielk1977397d65f2008-11-19 11:35:39 +00006214static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006215#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006216 struct timespec sp;
6217
6218 sp.tv_sec = microseconds / 1000000;
6219 sp.tv_nsec = (microseconds % 1000000) * 1000;
6220 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006221 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006222 return microseconds;
6223#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006224 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006225 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006226 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006227#else
danielk1977b4b47412007-08-17 15:53:36 +00006228 int seconds = (microseconds+999999)/1000000;
6229 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006230 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006231 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006232#endif
drh88f474a2006-01-02 20:00:12 +00006233}
6234
6235/*
drh6b9d6dd2008-12-03 19:34:47 +00006236** The following variable, if set to a non-zero value, is interpreted as
6237** the number of seconds since 1970 and is used to set the result of
6238** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006239*/
6240#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006241int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006242#endif
6243
6244/*
drhb7e8ea22010-05-03 14:32:30 +00006245** Find the current time (in Universal Coordinated Time). Write into *piNow
6246** the current time and date as a Julian Day number times 86_400_000. In
6247** other words, write into *piNow the number of milliseconds since the Julian
6248** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6249** proleptic Gregorian calendar.
6250**
drh31702252011-10-12 23:13:43 +00006251** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6252** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006253*/
6254static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6255 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006256 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006257#if defined(NO_GETTOD)
6258 time_t t;
6259 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006260 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006261#elif OS_VXWORKS
6262 struct timespec sNow;
6263 clock_gettime(CLOCK_REALTIME, &sNow);
6264 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6265#else
6266 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00006267 if( gettimeofday(&sNow, 0)==0 ){
6268 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
6269 }else{
6270 rc = SQLITE_ERROR;
6271 }
drhb7e8ea22010-05-03 14:32:30 +00006272#endif
6273
6274#ifdef SQLITE_TEST
6275 if( sqlite3_current_time ){
6276 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6277 }
6278#endif
6279 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006280 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006281}
6282
6283/*
drhbbd42a62004-05-22 17:41:58 +00006284** Find the current time (in Universal Coordinated Time). Write the
6285** current time and date as a Julian Day number into *prNow and
6286** return 0. Return 1 if the time and date cannot be found.
6287*/
danielk1977397d65f2008-11-19 11:35:39 +00006288static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006289 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006290 int rc;
drhff828942010-06-26 21:34:06 +00006291 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006292 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006293 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006294 return rc;
drhbbd42a62004-05-22 17:41:58 +00006295}
danielk1977b4b47412007-08-17 15:53:36 +00006296
drh6b9d6dd2008-12-03 19:34:47 +00006297/*
6298** We added the xGetLastError() method with the intention of providing
6299** better low-level error messages when operating-system problems come up
6300** during SQLite operation. But so far, none of that has been implemented
6301** in the core. So this routine is never called. For now, it is merely
6302** a place-holder.
6303*/
danielk1977397d65f2008-11-19 11:35:39 +00006304static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6305 UNUSED_PARAMETER(NotUsed);
6306 UNUSED_PARAMETER(NotUsed2);
6307 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00006308 return 0;
6309}
6310
drhf2424c52010-04-26 00:04:55 +00006311
6312/*
drh734c9862008-11-28 15:37:20 +00006313************************ End of sqlite3_vfs methods ***************************
6314******************************************************************************/
6315
drh715ff302008-12-03 22:32:44 +00006316/******************************************************************************
6317************************** Begin Proxy Locking ********************************
6318**
6319** Proxy locking is a "uber-locking-method" in this sense: It uses the
6320** other locking methods on secondary lock files. Proxy locking is a
6321** meta-layer over top of the primitive locking implemented above. For
6322** this reason, the division that implements of proxy locking is deferred
6323** until late in the file (here) after all of the other I/O methods have
6324** been defined - so that the primitive locking methods are available
6325** as services to help with the implementation of proxy locking.
6326**
6327****
6328**
6329** The default locking schemes in SQLite use byte-range locks on the
6330** database file to coordinate safe, concurrent access by multiple readers
6331** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6332** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6333** as POSIX read & write locks over fixed set of locations (via fsctl),
6334** on AFP and SMB only exclusive byte-range locks are available via fsctl
6335** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6336** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6337** address in the shared range is taken for a SHARED lock, the entire
6338** shared range is taken for an EXCLUSIVE lock):
6339**
drhf2f105d2012-08-20 15:53:54 +00006340** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006341** RESERVED_BYTE 0x40000001
6342** SHARED_RANGE 0x40000002 -> 0x40000200
6343**
6344** This works well on the local file system, but shows a nearly 100x
6345** slowdown in read performance on AFP because the AFP client disables
6346** the read cache when byte-range locks are present. Enabling the read
6347** cache exposes a cache coherency problem that is present on all OS X
6348** supported network file systems. NFS and AFP both observe the
6349** close-to-open semantics for ensuring cache coherency
6350** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6351** address the requirements for concurrent database access by multiple
6352** readers and writers
6353** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6354**
6355** To address the performance and cache coherency issues, proxy file locking
6356** changes the way database access is controlled by limiting access to a
6357** single host at a time and moving file locks off of the database file
6358** and onto a proxy file on the local file system.
6359**
6360**
6361** Using proxy locks
6362** -----------------
6363**
6364** C APIs
6365**
drh4bf66fd2015-02-19 02:43:02 +00006366** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
drh715ff302008-12-03 22:32:44 +00006367** <proxy_path> | ":auto:");
drh4bf66fd2015-02-19 02:43:02 +00006368** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6369** &<proxy_path>);
drh715ff302008-12-03 22:32:44 +00006370**
6371**
6372** SQL pragmas
6373**
6374** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6375** PRAGMA [database.]lock_proxy_file
6376**
6377** Specifying ":auto:" means that if there is a conch file with a matching
6378** host ID in it, the proxy path in the conch file will be used, otherwise
6379** a proxy path based on the user's temp dir
6380** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6381** actual proxy file name is generated from the name and path of the
6382** database file. For example:
6383**
6384** For database path "/Users/me/foo.db"
6385** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6386**
6387** Once a lock proxy is configured for a database connection, it can not
6388** be removed, however it may be switched to a different proxy path via
6389** the above APIs (assuming the conch file is not being held by another
6390** connection or process).
6391**
6392**
6393** How proxy locking works
6394** -----------------------
6395**
6396** Proxy file locking relies primarily on two new supporting files:
6397**
6398** * conch file to limit access to the database file to a single host
6399** at a time
6400**
6401** * proxy file to act as a proxy for the advisory locks normally
6402** taken on the database
6403**
6404** The conch file - to use a proxy file, sqlite must first "hold the conch"
6405** by taking an sqlite-style shared lock on the conch file, reading the
6406** contents and comparing the host's unique host ID (see below) and lock
6407** proxy path against the values stored in the conch. The conch file is
6408** stored in the same directory as the database file and the file name
6409** is patterned after the database file name as ".<databasename>-conch".
peter.d.reid60ec9142014-09-06 16:39:46 +00006410** If the conch file does not exist, or its contents do not match the
drh715ff302008-12-03 22:32:44 +00006411** host ID and/or proxy path, then the lock is escalated to an exclusive
6412** lock and the conch file contents is updated with the host ID and proxy
6413** path and the lock is downgraded to a shared lock again. If the conch
6414** is held by another process (with a shared lock), the exclusive lock
6415** will fail and SQLITE_BUSY is returned.
6416**
6417** The proxy file - a single-byte file used for all advisory file locks
6418** normally taken on the database file. This allows for safe sharing
6419** of the database file for multiple readers and writers on the same
6420** host (the conch ensures that they all use the same local lock file).
6421**
drh715ff302008-12-03 22:32:44 +00006422** Requesting the lock proxy does not immediately take the conch, it is
6423** only taken when the first request to lock database file is made.
6424** This matches the semantics of the traditional locking behavior, where
6425** opening a connection to a database file does not take a lock on it.
6426** The shared lock and an open file descriptor are maintained until
6427** the connection to the database is closed.
6428**
6429** The proxy file and the lock file are never deleted so they only need
6430** to be created the first time they are used.
6431**
6432** Configuration options
6433** ---------------------
6434**
6435** SQLITE_PREFER_PROXY_LOCKING
6436**
6437** Database files accessed on non-local file systems are
6438** automatically configured for proxy locking, lock files are
6439** named automatically using the same logic as
6440** PRAGMA lock_proxy_file=":auto:"
6441**
6442** SQLITE_PROXY_DEBUG
6443**
6444** Enables the logging of error messages during host id file
6445** retrieval and creation
6446**
drh715ff302008-12-03 22:32:44 +00006447** LOCKPROXYDIR
6448**
6449** Overrides the default directory used for lock proxy files that
6450** are named automatically via the ":auto:" setting
6451**
6452** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6453**
6454** Permissions to use when creating a directory for storing the
6455** lock proxy files, only used when LOCKPROXYDIR is not set.
6456**
6457**
6458** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6459** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6460** force proxy locking to be used for every database file opened, and 0
6461** will force automatic proxy locking to be disabled for all database
drh4bf66fd2015-02-19 02:43:02 +00006462** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
drh715ff302008-12-03 22:32:44 +00006463** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6464*/
6465
6466/*
6467** Proxy locking is only available on MacOSX
6468*/
drhd2cb50b2009-01-09 21:41:17 +00006469#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006470
drh715ff302008-12-03 22:32:44 +00006471/*
6472** The proxyLockingContext has the path and file structures for the remote
6473** and local proxy files in it
6474*/
6475typedef struct proxyLockingContext proxyLockingContext;
6476struct proxyLockingContext {
6477 unixFile *conchFile; /* Open conch file */
6478 char *conchFilePath; /* Name of the conch file */
6479 unixFile *lockProxy; /* Open proxy lock file */
6480 char *lockProxyPath; /* Name of the proxy lock file */
6481 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006482 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh4bf66fd2015-02-19 02:43:02 +00006483 int nFails; /* Number of conch taking failures */
drh715ff302008-12-03 22:32:44 +00006484 void *oldLockingContext; /* Original lockingcontext to restore on close */
6485 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6486};
6487
drh7ed97b92010-01-20 13:07:21 +00006488/*
6489** The proxy lock file path for the database at dbPath is written into lPath,
6490** which must point to valid, writable memory large enough for a maxLen length
6491** file path.
drh715ff302008-12-03 22:32:44 +00006492*/
drh715ff302008-12-03 22:32:44 +00006493static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6494 int len;
6495 int dbLen;
6496 int i;
6497
6498#ifdef LOCKPROXYDIR
6499 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6500#else
6501# ifdef _CS_DARWIN_USER_TEMP_DIR
6502 {
drh7ed97b92010-01-20 13:07:21 +00006503 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006504 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006505 lPath, errno, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006506 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006507 }
drh7ed97b92010-01-20 13:07:21 +00006508 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006509 }
6510# else
6511 len = strlcpy(lPath, "/tmp/", maxLen);
6512# endif
6513#endif
6514
6515 if( lPath[len-1]!='/' ){
6516 len = strlcat(lPath, "/", maxLen);
6517 }
6518
6519 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006520 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006521 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006522 char c = dbPath[i];
6523 lPath[i+len] = (c=='/')?'_':c;
6524 }
6525 lPath[i+len]='\0';
6526 strlcat(lPath, ":auto:", maxLen);
drh5ac93652015-03-21 20:59:43 +00006527 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006528 return SQLITE_OK;
6529}
6530
drh7ed97b92010-01-20 13:07:21 +00006531/*
6532 ** Creates the lock file and any missing directories in lockPath
6533 */
6534static int proxyCreateLockPath(const char *lockPath){
6535 int i, len;
6536 char buf[MAXPATHLEN];
6537 int start = 0;
6538
6539 assert(lockPath!=NULL);
6540 /* try to create all the intermediate directories */
6541 len = (int)strlen(lockPath);
6542 buf[0] = lockPath[0];
6543 for( i=1; i<len; i++ ){
6544 if( lockPath[i] == '/' && (i - start > 0) ){
6545 /* only mkdir if leaf dir != "." or "/" or ".." */
6546 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6547 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6548 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006549 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006550 int err=errno;
6551 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006552 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006553 "'%s' proxy lock path=%s pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006554 buf, strerror(err), lockPath, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006555 return err;
6556 }
6557 }
6558 }
6559 start=i+1;
6560 }
6561 buf[i] = lockPath[i];
6562 }
drh62aaa6c2015-11-21 17:27:42 +00006563 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006564 return 0;
6565}
6566
drh715ff302008-12-03 22:32:44 +00006567/*
6568** Create a new VFS file descriptor (stored in memory obtained from
6569** sqlite3_malloc) and open the file named "path" in the file descriptor.
6570**
6571** The caller is responsible not only for closing the file descriptor
6572** but also for freeing the memory associated with the file descriptor.
6573*/
drh7ed97b92010-01-20 13:07:21 +00006574static int proxyCreateUnixFile(
6575 const char *path, /* path for the new unixFile */
6576 unixFile **ppFile, /* unixFile created and returned by ref */
6577 int islockfile /* if non zero missing dirs will be created */
6578) {
6579 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006580 unixFile *pNew;
6581 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006582 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006583 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006584 int terrno = 0;
6585 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006586
drh7ed97b92010-01-20 13:07:21 +00006587 /* 1. first try to open/create the file
6588 ** 2. if that fails, and this is a lock file (not-conch), try creating
6589 ** the parent directories and then try again.
6590 ** 3. if that fails, try to open the file read-only
6591 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6592 */
6593 pUnused = findReusableFd(path, openFlags);
6594 if( pUnused ){
6595 fd = pUnused->fd;
6596 }else{
drhf3cdcdc2015-04-29 16:50:28 +00006597 pUnused = sqlite3_malloc64(sizeof(*pUnused));
drh7ed97b92010-01-20 13:07:21 +00006598 if( !pUnused ){
6599 return SQLITE_NOMEM;
6600 }
6601 }
6602 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006603 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006604 terrno = errno;
6605 if( fd<0 && errno==ENOENT && islockfile ){
6606 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006607 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006608 }
6609 }
6610 }
6611 if( fd<0 ){
6612 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006613 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006614 terrno = errno;
6615 }
6616 if( fd<0 ){
6617 if( islockfile ){
6618 return SQLITE_BUSY;
6619 }
6620 switch (terrno) {
6621 case EACCES:
6622 return SQLITE_PERM;
6623 case EIO:
6624 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6625 default:
drh9978c972010-02-23 17:36:32 +00006626 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006627 }
6628 }
6629
drhf3cdcdc2015-04-29 16:50:28 +00006630 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
drh7ed97b92010-01-20 13:07:21 +00006631 if( pNew==NULL ){
6632 rc = SQLITE_NOMEM;
6633 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006634 }
6635 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006636 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006637 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006638 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006639 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006640 pUnused->fd = fd;
6641 pUnused->flags = openFlags;
6642 pNew->pUnused = pUnused;
6643
drhc02a43a2012-01-10 23:18:38 +00006644 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006645 if( rc==SQLITE_OK ){
6646 *ppFile = pNew;
6647 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006648 }
drh7ed97b92010-01-20 13:07:21 +00006649end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006650 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006651 sqlite3_free(pNew);
6652 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006653 return rc;
6654}
6655
drh7ed97b92010-01-20 13:07:21 +00006656#ifdef SQLITE_TEST
6657/* simulate multiple hosts by creating unique hostid file paths */
6658int sqlite3_hostid_num = 0;
6659#endif
6660
6661#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6662
drh6bca6512015-04-13 23:05:28 +00006663#ifdef HAVE_GETHOSTUUID
drh0ab216a2010-07-02 17:10:40 +00006664/* Not always defined in the headers as it ought to be */
6665extern int gethostuuid(uuid_t id, const struct timespec *wait);
drh6bca6512015-04-13 23:05:28 +00006666#endif
drh0ab216a2010-07-02 17:10:40 +00006667
drh7ed97b92010-01-20 13:07:21 +00006668/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6669** bytes of writable memory.
6670*/
6671static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006672 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6673 memset(pHostID, 0, PROXY_HOSTIDLEN);
drh6bca6512015-04-13 23:05:28 +00006674#ifdef HAVE_GETHOSTUUID
drh29ecd8a2010-12-21 00:16:40 +00006675 {
drh4bf66fd2015-02-19 02:43:02 +00006676 struct timespec timeout = {1, 0}; /* 1 sec timeout */
drh29ecd8a2010-12-21 00:16:40 +00006677 if( gethostuuid(pHostID, &timeout) ){
6678 int err = errno;
6679 if( pError ){
6680 *pError = err;
6681 }
6682 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006683 }
drh7ed97b92010-01-20 13:07:21 +00006684 }
drh3d4435b2011-08-26 20:55:50 +00006685#else
6686 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006687#endif
drh7ed97b92010-01-20 13:07:21 +00006688#ifdef SQLITE_TEST
6689 /* simulate multiple hosts by creating unique hostid file paths */
6690 if( sqlite3_hostid_num != 0){
6691 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6692 }
6693#endif
6694
6695 return SQLITE_OK;
6696}
6697
6698/* The conch file contains the header, host id and lock file path
6699 */
6700#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6701#define PROXY_HEADERLEN 1 /* conch file header length */
6702#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6703#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6704
6705/*
6706** Takes an open conch file, copies the contents to a new path and then moves
6707** it back. The newly created file's file descriptor is assigned to the
6708** conch file structure and finally the original conch file descriptor is
6709** closed. Returns zero if successful.
6710*/
6711static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6712 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6713 unixFile *conchFile = pCtx->conchFile;
6714 char tPath[MAXPATHLEN];
6715 char buf[PROXY_MAXCONCHLEN];
6716 char *cPath = pCtx->conchFilePath;
6717 size_t readLen = 0;
6718 size_t pathLen = 0;
6719 char errmsg[64] = "";
6720 int fd = -1;
6721 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006722 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006723
6724 /* create a new path by replace the trailing '-conch' with '-break' */
6725 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6726 if( pathLen>MAXPATHLEN || pathLen<6 ||
6727 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006728 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006729 goto end_breaklock;
6730 }
6731 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006732 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006733 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006734 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006735 goto end_breaklock;
6736 }
6737 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006738 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006739 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006740 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006741 goto end_breaklock;
6742 }
drhe562be52011-03-02 18:01:10 +00006743 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006744 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006745 goto end_breaklock;
6746 }
6747 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006748 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006749 goto end_breaklock;
6750 }
6751 rc = 0;
6752 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006753 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006754 conchFile->h = fd;
6755 conchFile->openFlags = O_RDWR | O_CREAT;
6756
6757end_breaklock:
6758 if( rc ){
6759 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006760 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006761 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006762 }
6763 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6764 }
6765 return rc;
6766}
6767
6768/* Take the requested lock on the conch file and break a stale lock if the
6769** host id matches.
6770*/
6771static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6772 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6773 unixFile *conchFile = pCtx->conchFile;
6774 int rc = SQLITE_OK;
6775 int nTries = 0;
6776 struct timespec conchModTime;
6777
drh3d4435b2011-08-26 20:55:50 +00006778 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006779 do {
6780 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6781 nTries ++;
6782 if( rc==SQLITE_BUSY ){
6783 /* If the lock failed (busy):
6784 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6785 * 2nd try: fail if the mod time changed or host id is different, wait
6786 * 10 sec and try again
6787 * 3rd try: break the lock unless the mod time has changed.
6788 */
6789 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006790 if( osFstat(conchFile->h, &buf) ){
drh4bf66fd2015-02-19 02:43:02 +00006791 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006792 return SQLITE_IOERR_LOCK;
6793 }
6794
6795 if( nTries==1 ){
6796 conchModTime = buf.st_mtimespec;
6797 usleep(500000); /* wait 0.5 sec and try the lock again*/
6798 continue;
6799 }
6800
6801 assert( nTries>1 );
6802 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6803 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6804 return SQLITE_BUSY;
6805 }
6806
6807 if( nTries==2 ){
6808 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006809 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006810 if( len<0 ){
drh4bf66fd2015-02-19 02:43:02 +00006811 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006812 return SQLITE_IOERR_LOCK;
6813 }
6814 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6815 /* don't break the lock if the host id doesn't match */
6816 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6817 return SQLITE_BUSY;
6818 }
6819 }else{
6820 /* don't break the lock on short read or a version mismatch */
6821 return SQLITE_BUSY;
6822 }
6823 usleep(10000000); /* wait 10 sec and try the lock again */
6824 continue;
6825 }
6826
6827 assert( nTries==3 );
6828 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6829 rc = SQLITE_OK;
6830 if( lockType==EXCLUSIVE_LOCK ){
drhe6d41732015-02-21 00:49:00 +00006831 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
drh7ed97b92010-01-20 13:07:21 +00006832 }
6833 if( !rc ){
6834 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6835 }
6836 }
6837 }
6838 } while( rc==SQLITE_BUSY && nTries<3 );
6839
6840 return rc;
6841}
6842
6843/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006844** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6845** lockPath means that the lockPath in the conch file will be used if the
6846** host IDs match, or a new lock path will be generated automatically
6847** and written to the conch file.
6848*/
6849static int proxyTakeConch(unixFile *pFile){
6850 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6851
drh7ed97b92010-01-20 13:07:21 +00006852 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006853 return SQLITE_OK;
6854 }else{
6855 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006856 uuid_t myHostID;
6857 int pError = 0;
6858 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006859 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006860 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006861 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006862 int createConch = 0;
6863 int hostIdMatch = 0;
6864 int readLen = 0;
6865 int tryOldLockPath = 0;
6866 int forceNewLockPath = 0;
6867
drh308c2a52010-05-14 11:30:18 +00006868 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
drh91eb93c2015-03-03 19:56:20 +00006869 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00006870 osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006871
drh7ed97b92010-01-20 13:07:21 +00006872 rc = proxyGetHostID(myHostID, &pError);
6873 if( (rc&0xff)==SQLITE_IOERR ){
drh4bf66fd2015-02-19 02:43:02 +00006874 storeLastErrno(pFile, pError);
drh7ed97b92010-01-20 13:07:21 +00006875 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006876 }
drh7ed97b92010-01-20 13:07:21 +00006877 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006878 if( rc!=SQLITE_OK ){
6879 goto end_takeconch;
6880 }
drh7ed97b92010-01-20 13:07:21 +00006881 /* read the existing conch file */
6882 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6883 if( readLen<0 ){
6884 /* I/O error: lastErrno set by seekAndRead */
drh4bf66fd2015-02-19 02:43:02 +00006885 storeLastErrno(pFile, conchFile->lastErrno);
drh7ed97b92010-01-20 13:07:21 +00006886 rc = SQLITE_IOERR_READ;
6887 goto end_takeconch;
6888 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6889 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6890 /* a short read or version format mismatch means we need to create a new
6891 ** conch file.
6892 */
6893 createConch = 1;
6894 }
6895 /* if the host id matches and the lock path already exists in the conch
6896 ** we'll try to use the path there, if we can't open that path, we'll
6897 ** retry with a new auto-generated path
6898 */
6899 do { /* in case we need to try again for an :auto: named lock file */
6900
6901 if( !createConch && !forceNewLockPath ){
6902 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6903 PROXY_HOSTIDLEN);
6904 /* if the conch has data compare the contents */
6905 if( !pCtx->lockProxyPath ){
6906 /* for auto-named local lock file, just check the host ID and we'll
6907 ** use the local lock file path that's already in there
6908 */
6909 if( hostIdMatch ){
6910 size_t pathLen = (readLen - PROXY_PATHINDEX);
6911
6912 if( pathLen>=MAXPATHLEN ){
6913 pathLen=MAXPATHLEN-1;
6914 }
6915 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6916 lockPath[pathLen] = 0;
6917 tempLockPath = lockPath;
6918 tryOldLockPath = 1;
6919 /* create a copy of the lock path if the conch is taken */
6920 goto end_takeconch;
6921 }
6922 }else if( hostIdMatch
6923 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6924 readLen-PROXY_PATHINDEX)
6925 ){
6926 /* conch host and lock path match */
6927 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006928 }
drh7ed97b92010-01-20 13:07:21 +00006929 }
6930
6931 /* if the conch isn't writable and doesn't match, we can't take it */
6932 if( (conchFile->openFlags&O_RDWR) == 0 ){
6933 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006934 goto end_takeconch;
6935 }
drh7ed97b92010-01-20 13:07:21 +00006936
6937 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006938 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006939 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6940 tempLockPath = lockPath;
6941 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006942 }
drh7ed97b92010-01-20 13:07:21 +00006943
6944 /* update conch with host and path (this will fail if other process
6945 ** has a shared lock already), if the host id matches, use the big
6946 ** stick.
drh715ff302008-12-03 22:32:44 +00006947 */
drh7ed97b92010-01-20 13:07:21 +00006948 futimes(conchFile->h, NULL);
6949 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006950 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006951 /* We are trying for an exclusive lock but another thread in this
6952 ** same process is still holding a shared lock. */
6953 rc = SQLITE_BUSY;
6954 } else {
6955 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006956 }
drh715ff302008-12-03 22:32:44 +00006957 }else{
drh4bf66fd2015-02-19 02:43:02 +00006958 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006959 }
drh7ed97b92010-01-20 13:07:21 +00006960 if( rc==SQLITE_OK ){
6961 char writeBuffer[PROXY_MAXCONCHLEN];
6962 int writeSize = 0;
6963
6964 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6965 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6966 if( pCtx->lockProxyPath!=NULL ){
drh4bf66fd2015-02-19 02:43:02 +00006967 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
6968 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00006969 }else{
6970 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6971 }
6972 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006973 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006974 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6975 fsync(conchFile->h);
6976 /* If we created a new conch file (not just updated the contents of a
6977 ** valid conch file), try to match the permissions of the database
6978 */
6979 if( rc==SQLITE_OK && createConch ){
6980 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006981 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006982 if( err==0 ){
6983 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6984 S_IROTH|S_IWOTH);
6985 /* try to match the database file R/W permissions, ignore failure */
6986#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006987 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006988#else
drhff812312011-02-23 13:33:46 +00006989 do{
drhe562be52011-03-02 18:01:10 +00006990 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006991 }while( rc==(-1) && errno==EINTR );
6992 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006993 int code = errno;
6994 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6995 cmode, code, strerror(code));
6996 } else {
6997 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6998 }
6999 }else{
7000 int code = errno;
7001 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
7002 err, code, strerror(code));
7003#endif
7004 }
drh715ff302008-12-03 22:32:44 +00007005 }
7006 }
drh7ed97b92010-01-20 13:07:21 +00007007 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
7008
7009 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00007010 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00007011 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00007012 int fd;
drh7ed97b92010-01-20 13:07:21 +00007013 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00007014 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00007015 }
7016 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00007017 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00007018 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00007019 if( fd>=0 ){
7020 pFile->h = fd;
7021 }else{
drh9978c972010-02-23 17:36:32 +00007022 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00007023 during locking */
7024 }
7025 }
7026 if( rc==SQLITE_OK && !pCtx->lockProxy ){
7027 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
7028 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
7029 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
7030 /* we couldn't create the proxy lock file with the old lock file path
7031 ** so try again via auto-naming
7032 */
7033 forceNewLockPath = 1;
7034 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00007035 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00007036 }
7037 }
7038 if( rc==SQLITE_OK ){
7039 /* Need to make a copy of path if we extracted the value
7040 ** from the conch file or the path was allocated on the stack
7041 */
7042 if( tempLockPath ){
7043 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
7044 if( !pCtx->lockProxyPath ){
7045 rc = SQLITE_NOMEM;
7046 }
7047 }
7048 }
7049 if( rc==SQLITE_OK ){
7050 pCtx->conchHeld = 1;
7051
7052 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
7053 afpLockingContext *afpCtx;
7054 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
7055 afpCtx->dbPath = pCtx->lockProxyPath;
7056 }
7057 } else {
7058 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7059 }
drh308c2a52010-05-14 11:30:18 +00007060 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
7061 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00007062 return rc;
drh308c2a52010-05-14 11:30:18 +00007063 } while (1); /* in case we need to retry the :auto: lock file -
7064 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00007065 }
7066}
7067
7068/*
7069** If pFile holds a lock on a conch file, then release that lock.
7070*/
7071static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00007072 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00007073 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
7074 unixFile *conchFile; /* Name of the conch file */
7075
7076 pCtx = (proxyLockingContext *)pFile->lockingContext;
7077 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00007078 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00007079 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00007080 osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00007081 if( pCtx->conchHeld>0 ){
7082 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7083 }
drh715ff302008-12-03 22:32:44 +00007084 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00007085 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
7086 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007087 return rc;
7088}
7089
7090/*
7091** Given the name of a database file, compute the name of its conch file.
drhf3cdcdc2015-04-29 16:50:28 +00007092** Store the conch filename in memory obtained from sqlite3_malloc64().
drh715ff302008-12-03 22:32:44 +00007093** Make *pConchPath point to the new name. Return SQLITE_OK on success
7094** or SQLITE_NOMEM if unable to obtain memory.
7095**
7096** The caller is responsible for ensuring that the allocated memory
7097** space is eventually freed.
7098**
7099** *pConchPath is set to NULL if a memory allocation error occurs.
7100*/
7101static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7102 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00007103 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00007104 char *conchPath; /* buffer in which to construct conch name */
7105
7106 /* Allocate space for the conch filename and initialize the name to
7107 ** the name of the original database file. */
drhf3cdcdc2015-04-29 16:50:28 +00007108 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
drh715ff302008-12-03 22:32:44 +00007109 if( conchPath==0 ){
7110 return SQLITE_NOMEM;
7111 }
7112 memcpy(conchPath, dbPath, len+1);
7113
7114 /* now insert a "." before the last / character */
7115 for( i=(len-1); i>=0; i-- ){
7116 if( conchPath[i]=='/' ){
7117 i++;
7118 break;
7119 }
7120 }
7121 conchPath[i]='.';
7122 while ( i<len ){
7123 conchPath[i+1]=dbPath[i];
7124 i++;
7125 }
7126
7127 /* append the "-conch" suffix to the file */
7128 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007129 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007130
7131 return SQLITE_OK;
7132}
7133
7134
7135/* Takes a fully configured proxy locking-style unix file and switches
7136** the local lock file path
7137*/
7138static int switchLockProxyPath(unixFile *pFile, const char *path) {
7139 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7140 char *oldPath = pCtx->lockProxyPath;
7141 int rc = SQLITE_OK;
7142
drh308c2a52010-05-14 11:30:18 +00007143 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007144 return SQLITE_BUSY;
7145 }
7146
7147 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7148 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7149 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7150 return SQLITE_OK;
7151 }else{
7152 unixFile *lockProxy = pCtx->lockProxy;
7153 pCtx->lockProxy=NULL;
7154 pCtx->conchHeld = 0;
7155 if( lockProxy!=NULL ){
7156 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7157 if( rc ) return rc;
7158 sqlite3_free(lockProxy);
7159 }
7160 sqlite3_free(oldPath);
7161 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7162 }
7163
7164 return rc;
7165}
7166
7167/*
7168** pFile is a file that has been opened by a prior xOpen call. dbPath
7169** is a string buffer at least MAXPATHLEN+1 characters in size.
7170**
7171** This routine find the filename associated with pFile and writes it
7172** int dbPath.
7173*/
7174static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007175#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007176 if( pFile->pMethod == &afpIoMethods ){
7177 /* afp style keeps a reference to the db path in the filePath field
7178 ** of the struct */
drhea678832008-12-10 19:26:22 +00007179 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh4bf66fd2015-02-19 02:43:02 +00007180 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7181 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007182 } else
drh715ff302008-12-03 22:32:44 +00007183#endif
7184 if( pFile->pMethod == &dotlockIoMethods ){
7185 /* dot lock style uses the locking context to store the dot lock
7186 ** file path */
7187 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7188 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7189 }else{
7190 /* all other styles use the locking context to store the db file path */
7191 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007192 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007193 }
7194 return SQLITE_OK;
7195}
7196
7197/*
7198** Takes an already filled in unix file and alters it so all file locking
7199** will be performed on the local proxy lock file. The following fields
7200** are preserved in the locking context so that they can be restored and
7201** the unix structure properly cleaned up at close time:
7202** ->lockingContext
7203** ->pMethod
7204*/
7205static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7206 proxyLockingContext *pCtx;
7207 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7208 char *lockPath=NULL;
7209 int rc = SQLITE_OK;
7210
drh308c2a52010-05-14 11:30:18 +00007211 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007212 return SQLITE_BUSY;
7213 }
7214 proxyGetDbPathForUnixFile(pFile, dbPath);
7215 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7216 lockPath=NULL;
7217 }else{
7218 lockPath=(char *)path;
7219 }
7220
drh308c2a52010-05-14 11:30:18 +00007221 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
drh5ac93652015-03-21 20:59:43 +00007222 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007223
drhf3cdcdc2015-04-29 16:50:28 +00007224 pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh715ff302008-12-03 22:32:44 +00007225 if( pCtx==0 ){
7226 return SQLITE_NOMEM;
7227 }
7228 memset(pCtx, 0, sizeof(*pCtx));
7229
7230 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7231 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007232 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7233 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7234 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7235 ** (c) the file system is read-only, then enable no-locking access.
7236 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7237 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7238 */
7239 struct statfs fsInfo;
7240 struct stat conchInfo;
7241 int goLockless = 0;
7242
drh99ab3b12011-03-02 15:09:07 +00007243 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007244 int err = errno;
7245 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7246 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7247 }
7248 }
7249 if( goLockless ){
7250 pCtx->conchHeld = -1; /* read only FS/ lockless */
7251 rc = SQLITE_OK;
7252 }
7253 }
drh715ff302008-12-03 22:32:44 +00007254 }
7255 if( rc==SQLITE_OK && lockPath ){
7256 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7257 }
7258
7259 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007260 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7261 if( pCtx->dbPath==NULL ){
7262 rc = SQLITE_NOMEM;
7263 }
7264 }
7265 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007266 /* all memory is allocated, proxys are created and assigned,
7267 ** switch the locking context and pMethod then return.
7268 */
drh715ff302008-12-03 22:32:44 +00007269 pCtx->oldLockingContext = pFile->lockingContext;
7270 pFile->lockingContext = pCtx;
7271 pCtx->pOldMethod = pFile->pMethod;
7272 pFile->pMethod = &proxyIoMethods;
7273 }else{
7274 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007275 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007276 sqlite3_free(pCtx->conchFile);
7277 }
drhd56b1212010-08-11 06:14:15 +00007278 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007279 sqlite3_free(pCtx->conchFilePath);
7280 sqlite3_free(pCtx);
7281 }
drh308c2a52010-05-14 11:30:18 +00007282 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7283 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007284 return rc;
7285}
7286
7287
7288/*
7289** This routine handles sqlite3_file_control() calls that are specific
7290** to proxy locking.
7291*/
7292static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7293 switch( op ){
drh4bf66fd2015-02-19 02:43:02 +00007294 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007295 unixFile *pFile = (unixFile*)id;
7296 if( pFile->pMethod == &proxyIoMethods ){
7297 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7298 proxyTakeConch(pFile);
7299 if( pCtx->lockProxyPath ){
7300 *(const char **)pArg = pCtx->lockProxyPath;
7301 }else{
7302 *(const char **)pArg = ":auto: (not held)";
7303 }
7304 } else {
7305 *(const char **)pArg = NULL;
7306 }
7307 return SQLITE_OK;
7308 }
drh4bf66fd2015-02-19 02:43:02 +00007309 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007310 unixFile *pFile = (unixFile*)id;
7311 int rc = SQLITE_OK;
7312 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7313 if( pArg==NULL || (const char *)pArg==0 ){
7314 if( isProxyStyle ){
drh4bf66fd2015-02-19 02:43:02 +00007315 /* turn off proxy locking - not supported. If support is added for
7316 ** switching proxy locking mode off then it will need to fail if
7317 ** the journal mode is WAL mode.
7318 */
drh715ff302008-12-03 22:32:44 +00007319 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7320 }else{
7321 /* turn off proxy locking - already off - NOOP */
7322 rc = SQLITE_OK;
7323 }
7324 }else{
7325 const char *proxyPath = (const char *)pArg;
7326 if( isProxyStyle ){
7327 proxyLockingContext *pCtx =
7328 (proxyLockingContext*)pFile->lockingContext;
7329 if( !strcmp(pArg, ":auto:")
7330 || (pCtx->lockProxyPath &&
7331 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7332 ){
7333 rc = SQLITE_OK;
7334 }else{
7335 rc = switchLockProxyPath(pFile, proxyPath);
7336 }
7337 }else{
7338 /* turn on proxy file locking */
7339 rc = proxyTransformUnixFile(pFile, proxyPath);
7340 }
7341 }
7342 return rc;
7343 }
7344 default: {
7345 assert( 0 ); /* The call assures that only valid opcodes are sent */
7346 }
7347 }
7348 /*NOTREACHED*/
7349 return SQLITE_ERROR;
7350}
7351
7352/*
7353** Within this division (the proxying locking implementation) the procedures
7354** above this point are all utilities. The lock-related methods of the
7355** proxy-locking sqlite3_io_method object follow.
7356*/
7357
7358
7359/*
7360** This routine checks if there is a RESERVED lock held on the specified
7361** file by this or any other process. If such a lock is held, set *pResOut
7362** to a non-zero value otherwise *pResOut is set to zero. The return value
7363** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7364*/
7365static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7366 unixFile *pFile = (unixFile*)id;
7367 int rc = proxyTakeConch(pFile);
7368 if( rc==SQLITE_OK ){
7369 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007370 if( pCtx->conchHeld>0 ){
7371 unixFile *proxy = pCtx->lockProxy;
7372 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7373 }else{ /* conchHeld < 0 is lockless */
7374 pResOut=0;
7375 }
drh715ff302008-12-03 22:32:44 +00007376 }
7377 return rc;
7378}
7379
7380/*
drh308c2a52010-05-14 11:30:18 +00007381** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007382** of the following:
7383**
7384** (1) SHARED_LOCK
7385** (2) RESERVED_LOCK
7386** (3) PENDING_LOCK
7387** (4) EXCLUSIVE_LOCK
7388**
7389** Sometimes when requesting one lock state, additional lock states
7390** are inserted in between. The locking might fail on one of the later
7391** transitions leaving the lock state different from what it started but
7392** still short of its goal. The following chart shows the allowed
7393** transitions and the inserted intermediate states:
7394**
7395** UNLOCKED -> SHARED
7396** SHARED -> RESERVED
7397** SHARED -> (PENDING) -> EXCLUSIVE
7398** RESERVED -> (PENDING) -> EXCLUSIVE
7399** PENDING -> EXCLUSIVE
7400**
7401** This routine will only increase a lock. Use the sqlite3OsUnlock()
7402** routine to lower a locking level.
7403*/
drh308c2a52010-05-14 11:30:18 +00007404static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007405 unixFile *pFile = (unixFile*)id;
7406 int rc = proxyTakeConch(pFile);
7407 if( rc==SQLITE_OK ){
7408 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007409 if( pCtx->conchHeld>0 ){
7410 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007411 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7412 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007413 }else{
7414 /* conchHeld < 0 is lockless */
7415 }
drh715ff302008-12-03 22:32:44 +00007416 }
7417 return rc;
7418}
7419
7420
7421/*
drh308c2a52010-05-14 11:30:18 +00007422** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007423** must be either NO_LOCK or SHARED_LOCK.
7424**
7425** If the locking level of the file descriptor is already at or below
7426** the requested locking level, this routine is a no-op.
7427*/
drh308c2a52010-05-14 11:30:18 +00007428static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007429 unixFile *pFile = (unixFile*)id;
7430 int rc = proxyTakeConch(pFile);
7431 if( rc==SQLITE_OK ){
7432 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007433 if( pCtx->conchHeld>0 ){
7434 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007435 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7436 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007437 }else{
7438 /* conchHeld < 0 is lockless */
7439 }
drh715ff302008-12-03 22:32:44 +00007440 }
7441 return rc;
7442}
7443
7444/*
7445** Close a file that uses proxy locks.
7446*/
7447static int proxyClose(sqlite3_file *id) {
7448 if( id ){
7449 unixFile *pFile = (unixFile*)id;
7450 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7451 unixFile *lockProxy = pCtx->lockProxy;
7452 unixFile *conchFile = pCtx->conchFile;
7453 int rc = SQLITE_OK;
7454
7455 if( lockProxy ){
7456 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7457 if( rc ) return rc;
7458 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7459 if( rc ) return rc;
7460 sqlite3_free(lockProxy);
7461 pCtx->lockProxy = 0;
7462 }
7463 if( conchFile ){
7464 if( pCtx->conchHeld ){
7465 rc = proxyReleaseConch(pFile);
7466 if( rc ) return rc;
7467 }
7468 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7469 if( rc ) return rc;
7470 sqlite3_free(conchFile);
7471 }
drhd56b1212010-08-11 06:14:15 +00007472 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007473 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007474 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007475 /* restore the original locking context and pMethod then close it */
7476 pFile->lockingContext = pCtx->oldLockingContext;
7477 pFile->pMethod = pCtx->pOldMethod;
7478 sqlite3_free(pCtx);
7479 return pFile->pMethod->xClose(id);
7480 }
7481 return SQLITE_OK;
7482}
7483
7484
7485
drhd2cb50b2009-01-09 21:41:17 +00007486#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007487/*
7488** The proxy locking style is intended for use with AFP filesystems.
7489** And since AFP is only supported on MacOSX, the proxy locking is also
7490** restricted to MacOSX.
7491**
7492**
7493******************* End of the proxy lock implementation **********************
7494******************************************************************************/
7495
drh734c9862008-11-28 15:37:20 +00007496/*
danielk1977e339d652008-06-28 11:23:00 +00007497** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007498**
7499** This routine registers all VFS implementations for unix-like operating
7500** systems. This routine, and the sqlite3_os_end() routine that follows,
7501** should be the only routines in this file that are visible from other
7502** files.
drh6b9d6dd2008-12-03 19:34:47 +00007503**
7504** This routine is called once during SQLite initialization and by a
7505** single thread. The memory allocation and mutex subsystems have not
7506** necessarily been initialized when this routine is called, and so they
7507** should not be used.
drh153c62c2007-08-24 03:51:33 +00007508*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007509int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007510 /*
7511 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007512 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7513 ** to the "finder" function. (pAppData is a pointer to a pointer because
7514 ** silly C90 rules prohibit a void* from being cast to a function pointer
7515 ** and so we have to go through the intermediate pointer to avoid problems
7516 ** when compiling with -pedantic-errors on GCC.)
7517 **
7518 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007519 ** finder-function. The finder-function returns a pointer to the
7520 ** sqlite_io_methods object that implements the desired locking
7521 ** behaviors. See the division above that contains the IOMETHODS
7522 ** macro for addition information on finder-functions.
7523 **
7524 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7525 ** object. But the "autolockIoFinder" available on MacOSX does a little
7526 ** more than that; it looks at the filesystem type that hosts the
7527 ** database file and tries to choose an locking method appropriate for
7528 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007529 */
drh7708e972008-11-29 00:56:52 +00007530 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007531 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007532 sizeof(unixFile), /* szOsFile */ \
7533 MAX_PATHNAME, /* mxPathname */ \
7534 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007535 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007536 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007537 unixOpen, /* xOpen */ \
7538 unixDelete, /* xDelete */ \
7539 unixAccess, /* xAccess */ \
7540 unixFullPathname, /* xFullPathname */ \
7541 unixDlOpen, /* xDlOpen */ \
7542 unixDlError, /* xDlError */ \
7543 unixDlSym, /* xDlSym */ \
7544 unixDlClose, /* xDlClose */ \
7545 unixRandomness, /* xRandomness */ \
7546 unixSleep, /* xSleep */ \
7547 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007548 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007549 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007550 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007551 unixGetSystemCall, /* xGetSystemCall */ \
7552 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007553 }
7554
drh6b9d6dd2008-12-03 19:34:47 +00007555 /*
7556 ** All default VFSes for unix are contained in the following array.
7557 **
7558 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7559 ** by the SQLite core when the VFS is registered. So the following
7560 ** array cannot be const.
7561 */
danielk1977e339d652008-06-28 11:23:00 +00007562 static sqlite3_vfs aVfs[] = {
drhe89b2912015-03-03 20:42:01 +00007563#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007564 UNIXVFS("unix", autolockIoFinder ),
drhe89b2912015-03-03 20:42:01 +00007565#elif OS_VXWORKS
7566 UNIXVFS("unix", vxworksIoFinder ),
drh7708e972008-11-29 00:56:52 +00007567#else
7568 UNIXVFS("unix", posixIoFinder ),
7569#endif
7570 UNIXVFS("unix-none", nolockIoFinder ),
7571 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007572 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007573#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007574 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007575#endif
drhe89b2912015-03-03 20:42:01 +00007576#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007577 UNIXVFS("unix-posix", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007578#endif
drhe89b2912015-03-03 20:42:01 +00007579#if SQLITE_ENABLE_LOCKING_STYLE
7580 UNIXVFS("unix-flock", flockIoFinder ),
chw78a13182009-04-07 05:35:03 +00007581#endif
drhd2cb50b2009-01-09 21:41:17 +00007582#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007583 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007584 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007585 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007586#endif
drh153c62c2007-08-24 03:51:33 +00007587 };
drh6b9d6dd2008-12-03 19:34:47 +00007588 unsigned int i; /* Loop counter */
7589
drh2aa5a002011-04-13 13:42:25 +00007590 /* Double-check that the aSyscall[] array has been constructed
7591 ** correctly. See ticket [bb3a86e890c8e96ab] */
drh6226ca22015-11-24 15:06:28 +00007592 assert( ArraySize(aSyscall)==27 );
drh2aa5a002011-04-13 13:42:25 +00007593
drh6b9d6dd2008-12-03 19:34:47 +00007594 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007595 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007596 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007597 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007598 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007599}
danielk1977e339d652008-06-28 11:23:00 +00007600
7601/*
drh6b9d6dd2008-12-03 19:34:47 +00007602** Shutdown the operating system interface.
7603**
7604** Some operating systems might need to do some cleanup in this routine,
7605** to release dynamically allocated objects. But not on unix.
7606** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007607*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007608int sqlite3_os_end(void){
7609 return SQLITE_OK;
7610}
drhdce8bdb2007-08-16 13:01:44 +00007611
danielk197729bafea2008-06-26 10:41:19 +00007612#endif /* SQLITE_OS_UNIX */