blob: 43eec4c1f576922d17f6469f7acc345b49cbb9fd [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 */
drh5a8d1902015-11-24 16:40:23 +0000261#define UNIXFILE_BLOCK 0x0100 /* Next SHM lock might block */
drha7e61d82011-03-12 17:02:57 +0000262
263/*
drh198bf392006-01-06 21:52:49 +0000264** Include code that is common to all os_*.c files
265*/
266#include "os_common.h"
267
268/*
drh0ccebe72005-06-07 22:22:50 +0000269** Define various macros that are missing from some systems.
270*/
drhbbd42a62004-05-22 17:41:58 +0000271#ifndef O_LARGEFILE
272# define O_LARGEFILE 0
273#endif
274#ifdef SQLITE_DISABLE_LFS
275# undef O_LARGEFILE
276# define O_LARGEFILE 0
277#endif
278#ifndef O_NOFOLLOW
279# define O_NOFOLLOW 0
280#endif
281#ifndef O_BINARY
282# define O_BINARY 0
283#endif
284
285/*
drh2b4b5962005-06-15 17:47:55 +0000286** The threadid macro resolves to the thread-id or to 0. Used for
287** testing and debugging only.
288*/
drhd677b3d2007-08-20 22:48:41 +0000289#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000290#define threadid pthread_self()
291#else
292#define threadid 0
293#endif
294
drh99ab3b12011-03-02 15:09:07 +0000295/*
dane6ecd662013-04-01 17:56:59 +0000296** HAVE_MREMAP defaults to true on Linux and false everywhere else.
297*/
298#if !defined(HAVE_MREMAP)
299# if defined(__linux__) && defined(_GNU_SOURCE)
300# define HAVE_MREMAP 1
301# else
302# define HAVE_MREMAP 0
303# endif
304#endif
305
306/*
dan2ee53412014-09-06 16:49:40 +0000307** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
308** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
309*/
310#ifdef __ANDROID__
311# define lseek lseek64
312#endif
313
314/*
drh9a3baf12011-04-25 18:01:27 +0000315** Different Unix systems declare open() in different ways. Same use
316** open(const char*,int,mode_t). Others use open(const char*,int,...).
317** The difference is important when using a pointer to the function.
318**
319** The safest way to deal with the problem is to always use this wrapper
320** which always has the same well-defined interface.
321*/
322static int posixOpen(const char *zFile, int flags, int mode){
323 return open(zFile, flags, mode);
324}
325
drh90315a22011-08-10 01:52:12 +0000326/* Forward reference */
327static int openDirectory(const char*, int*);
danbc760632014-03-20 09:42:09 +0000328static int unixGetpagesize(void);
drh90315a22011-08-10 01:52:12 +0000329
drh9a3baf12011-04-25 18:01:27 +0000330/*
drh99ab3b12011-03-02 15:09:07 +0000331** Many system calls are accessed through pointer-to-functions so that
332** they may be overridden at runtime to facilitate fault injection during
333** testing and sandboxing. The following array holds the names and pointers
334** to all overrideable system calls.
335*/
336static struct unix_syscall {
mistachkin48864df2013-03-21 21:20:32 +0000337 const char *zName; /* Name of the system call */
drh58ad5802011-03-23 22:02:23 +0000338 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
339 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000340} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000341 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
342#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000343
drh58ad5802011-03-23 22:02:23 +0000344 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000345#define osClose ((int(*)(int))aSyscall[1].pCurrent)
346
drh58ad5802011-03-23 22:02:23 +0000347 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000348#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
349
drh58ad5802011-03-23 22:02:23 +0000350 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000351#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
352
drh58ad5802011-03-23 22:02:23 +0000353 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000354#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
355
356/*
357** The DJGPP compiler environment looks mostly like Unix, but it
358** lacks the fcntl() system call. So redefine fcntl() to be something
359** that always succeeds. This means that locking does not occur under
360** DJGPP. But it is DOS - what did you expect?
361*/
362#ifdef __DJGPP__
363 { "fstat", 0, 0 },
364#define osFstat(a,b,c) 0
365#else
drh58ad5802011-03-23 22:02:23 +0000366 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000367#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
368#endif
369
drh58ad5802011-03-23 22:02:23 +0000370 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000371#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
372
drh58ad5802011-03-23 22:02:23 +0000373 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000374#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000375
drh58ad5802011-03-23 22:02:23 +0000376 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000377#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
378
drhe89b2912015-03-03 20:42:01 +0000379#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000380 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000381#else
drh58ad5802011-03-23 22:02:23 +0000382 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000383#endif
384#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
385
386#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000387 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000388#else
drh58ad5802011-03-23 22:02:23 +0000389 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000390#endif
391#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
392
drh58ad5802011-03-23 22:02:23 +0000393 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000394#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
395
drhe89b2912015-03-03 20:42:01 +0000396#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000397 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000398#else
drh58ad5802011-03-23 22:02:23 +0000399 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000400#endif
401#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
402 aSyscall[12].pCurrent)
403
404#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000405 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000406#else
drh58ad5802011-03-23 22:02:23 +0000407 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000408#endif
409#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
410 aSyscall[13].pCurrent)
411
drh6226ca22015-11-24 15:06:28 +0000412 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000413#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000414
415#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000416 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000417#else
drh58ad5802011-03-23 22:02:23 +0000418 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000419#endif
dan0fd7d862011-03-29 10:04:23 +0000420#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000421
drh036ac7f2011-08-08 23:18:05 +0000422 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
423#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
424
drh90315a22011-08-10 01:52:12 +0000425 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
426#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
427
drh9ef6bc42011-11-04 02:24:02 +0000428 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
429#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
430
431 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
432#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
433
drh6226ca22015-11-24 15:06:28 +0000434 { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
dand3eaebd2012-02-13 08:50:23 +0000435#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000436
drh6226ca22015-11-24 15:06:28 +0000437 { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
438#define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
439
dan4dd51442013-08-26 14:30:25 +0000440#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
dan893c0ff2013-03-25 19:05:07 +0000441 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
drh6226ca22015-11-24 15:06:28 +0000442#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
dan893c0ff2013-03-25 19:05:07 +0000443
drhd1ab8062013-03-25 20:50:25 +0000444 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
drh6226ca22015-11-24 15:06:28 +0000445#define osMunmap ((void*(*)(void*,size_t))aSyscall[23].pCurrent)
drhd1ab8062013-03-25 20:50:25 +0000446
dane6ecd662013-04-01 17:56:59 +0000447#if HAVE_MREMAP
drhd1ab8062013-03-25 20:50:25 +0000448 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
449#else
450 { "mremap", (sqlite3_syscall_ptr)0, 0 },
451#endif
drh6226ca22015-11-24 15:06:28 +0000452#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
453
danbc760632014-03-20 09:42:09 +0000454 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
drh6226ca22015-11-24 15:06:28 +0000455#define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
danbc760632014-03-20 09:42:09 +0000456
dan245fdc62015-10-31 17:58:33 +0000457 { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
drh6226ca22015-11-24 15:06:28 +0000458#define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
dan245fdc62015-10-31 17:58:33 +0000459
dan702eec12014-06-23 10:04:58 +0000460#endif
461
drhe562be52011-03-02 18:01:10 +0000462}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000463
drh6226ca22015-11-24 15:06:28 +0000464
465/*
466** On some systems, calls to fchown() will trigger a message in a security
467** log if they come from non-root processes. So avoid calling fchown() if
468** we are not running as root.
469*/
470static int robustFchown(int fd, uid_t uid, gid_t gid){
471#if OS_VXWORKS
472 return 0;
473#else
474 return osGeteuid() ? 0 : osFchown(fd,uid,gid);
475#endif
476}
477
drh99ab3b12011-03-02 15:09:07 +0000478/*
479** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000480** "unix" VFSes. Return SQLITE_OK opon successfully updating the
481** system call pointer, or SQLITE_NOTFOUND if there is no configurable
482** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000483*/
484static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000485 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
486 const char *zName, /* Name of system call to override */
487 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000488){
drh58ad5802011-03-23 22:02:23 +0000489 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000490 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000491
492 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000493 if( zName==0 ){
494 /* If no zName is given, restore all system calls to their default
495 ** settings and return NULL
496 */
dan51438a72011-04-02 17:00:47 +0000497 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000498 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
499 if( aSyscall[i].pDefault ){
500 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000501 }
502 }
503 }else{
504 /* If zName is specified, operate on only the one system call
505 ** specified.
506 */
507 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
508 if( strcmp(zName, aSyscall[i].zName)==0 ){
509 if( aSyscall[i].pDefault==0 ){
510 aSyscall[i].pDefault = aSyscall[i].pCurrent;
511 }
drh1df30962011-03-02 19:06:42 +0000512 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000513 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
514 aSyscall[i].pCurrent = pNewFunc;
515 break;
516 }
517 }
518 }
519 return rc;
520}
521
drh1df30962011-03-02 19:06:42 +0000522/*
523** Return the value of a system call. Return NULL if zName is not a
524** recognized system call name. NULL is also returned if the system call
525** is currently undefined.
526*/
drh58ad5802011-03-23 22:02:23 +0000527static sqlite3_syscall_ptr unixGetSystemCall(
528 sqlite3_vfs *pNotUsed,
529 const char *zName
530){
531 unsigned int i;
532
533 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000534 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
535 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
536 }
537 return 0;
538}
539
540/*
541** Return the name of the first system call after zName. If zName==NULL
542** then return the name of the first system call. Return NULL if zName
543** is the last system call or if zName is not the name of a valid
544** system call.
545*/
546static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000547 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000548
549 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000550 if( zName ){
551 for(i=0; i<ArraySize(aSyscall)-1; i++){
552 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000553 }
554 }
dan0fd7d862011-03-29 10:04:23 +0000555 for(i++; i<ArraySize(aSyscall); i++){
556 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000557 }
558 return 0;
559}
560
drhad4f1e52011-03-04 15:43:57 +0000561/*
drh77a3fdc2013-08-30 14:24:12 +0000562** Do not accept any file descriptor less than this value, in order to avoid
563** opening database file using file descriptors that are commonly used for
564** standard input, output, and error.
565*/
566#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
567# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
568#endif
569
570/*
drh8c815d12012-02-13 20:16:37 +0000571** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000572** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000573**
574** If the file creation mode "m" is 0 then set it to the default for
575** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
576** 0644) as modified by the system umask. If m is not 0, then
577** make the file creation mode be exactly m ignoring the umask.
578**
579** The m parameter will be non-zero only when creating -wal, -journal,
580** and -shm files. We want those files to have *exactly* the same
581** permissions as their original database, unadulterated by the umask.
582** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
583** transaction crashes and leaves behind hot journals, then any
584** process that is able to write to the database will also be able to
585** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000586*/
drh8c815d12012-02-13 20:16:37 +0000587static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000588 int fd;
drhe1186ab2013-01-04 20:45:13 +0000589 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5128d002013-08-30 06:20:23 +0000590 while(1){
drh5adc60b2012-04-14 13:25:11 +0000591#if defined(O_CLOEXEC)
592 fd = osOpen(z,f|O_CLOEXEC,m2);
593#else
594 fd = osOpen(z,f,m2);
595#endif
drh5128d002013-08-30 06:20:23 +0000596 if( fd<0 ){
597 if( errno==EINTR ) continue;
598 break;
599 }
drh77a3fdc2013-08-30 14:24:12 +0000600 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
drh5128d002013-08-30 06:20:23 +0000601 osClose(fd);
602 sqlite3_log(SQLITE_WARNING,
603 "attempt to open \"%s\" as file descriptor %d", z, fd);
604 fd = -1;
605 if( osOpen("/dev/null", f, m)<0 ) break;
606 }
drhe1186ab2013-01-04 20:45:13 +0000607 if( fd>=0 ){
608 if( m!=0 ){
609 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000610 if( osFstat(fd, &statbuf)==0
611 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000612 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000613 ){
drhe1186ab2013-01-04 20:45:13 +0000614 osFchmod(fd, m);
615 }
616 }
drh5adc60b2012-04-14 13:25:11 +0000617#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000618 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000619#endif
drhe1186ab2013-01-04 20:45:13 +0000620 }
drh5adc60b2012-04-14 13:25:11 +0000621 return fd;
drhad4f1e52011-03-04 15:43:57 +0000622}
danielk197713adf8a2004-06-03 16:08:41 +0000623
drh107886a2008-11-21 22:21:50 +0000624/*
dan9359c7b2009-08-21 08:29:10 +0000625** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000626** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000627** vxworksFileId objects used by this file, all of which may be
628** shared by multiple threads.
629**
630** Function unixMutexHeld() is used to assert() that the global mutex
631** is held when required. This function is only used as part of assert()
632** statements. e.g.
633**
634** unixEnterMutex()
635** assert( unixMutexHeld() );
636** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000637*/
638static void unixEnterMutex(void){
mistachkin93de6532015-07-03 21:38:09 +0000639 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
drh107886a2008-11-21 22:21:50 +0000640}
641static void unixLeaveMutex(void){
mistachkin93de6532015-07-03 21:38:09 +0000642 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
drh107886a2008-11-21 22:21:50 +0000643}
dan9359c7b2009-08-21 08:29:10 +0000644#ifdef SQLITE_DEBUG
645static int unixMutexHeld(void) {
mistachkin93de6532015-07-03 21:38:09 +0000646 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
dan9359c7b2009-08-21 08:29:10 +0000647}
648#endif
drh107886a2008-11-21 22:21:50 +0000649
drh734c9862008-11-28 15:37:20 +0000650
mistachkinfb383e92015-04-16 03:24:38 +0000651#ifdef SQLITE_HAVE_OS_TRACE
drh734c9862008-11-28 15:37:20 +0000652/*
653** Helper function for printing out trace information from debugging
peter.d.reid60ec9142014-09-06 16:39:46 +0000654** binaries. This returns the string representation of the supplied
drh734c9862008-11-28 15:37:20 +0000655** integer lock-type.
656*/
drh308c2a52010-05-14 11:30:18 +0000657static const char *azFileLock(int eFileLock){
658 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000659 case NO_LOCK: return "NONE";
660 case SHARED_LOCK: return "SHARED";
661 case RESERVED_LOCK: return "RESERVED";
662 case PENDING_LOCK: return "PENDING";
663 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000664 }
665 return "ERROR";
666}
667#endif
668
669#ifdef SQLITE_LOCK_TRACE
670/*
671** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000672**
drh734c9862008-11-28 15:37:20 +0000673** This routine is used for troubleshooting locks on multithreaded
674** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
675** command-line option on the compiler. This code is normally
676** turned off.
677*/
678static int lockTrace(int fd, int op, struct flock *p){
679 char *zOpName, *zType;
680 int s;
681 int savedErrno;
682 if( op==F_GETLK ){
683 zOpName = "GETLK";
684 }else if( op==F_SETLK ){
685 zOpName = "SETLK";
686 }else{
drh99ab3b12011-03-02 15:09:07 +0000687 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000688 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
689 return s;
690 }
691 if( p->l_type==F_RDLCK ){
692 zType = "RDLCK";
693 }else if( p->l_type==F_WRLCK ){
694 zType = "WRLCK";
695 }else if( p->l_type==F_UNLCK ){
696 zType = "UNLCK";
697 }else{
698 assert( 0 );
699 }
700 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000701 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000702 savedErrno = errno;
703 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
704 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
705 (int)p->l_pid, s);
706 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
707 struct flock l2;
708 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000709 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000710 if( l2.l_type==F_RDLCK ){
711 zType = "RDLCK";
712 }else if( l2.l_type==F_WRLCK ){
713 zType = "WRLCK";
714 }else if( l2.l_type==F_UNLCK ){
715 zType = "UNLCK";
716 }else{
717 assert( 0 );
718 }
719 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
720 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
721 }
722 errno = savedErrno;
723 return s;
724}
drh99ab3b12011-03-02 15:09:07 +0000725#undef osFcntl
726#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000727#endif /* SQLITE_LOCK_TRACE */
728
drhff812312011-02-23 13:33:46 +0000729/*
730** Retry ftruncate() calls that fail due to EINTR
dan2ee53412014-09-06 16:49:40 +0000731**
drhe6d41732015-02-21 00:49:00 +0000732** All calls to ftruncate() within this file should be made through
733** this wrapper. On the Android platform, bypassing the logic below
734** could lead to a corrupt database.
drhff812312011-02-23 13:33:46 +0000735*/
drhff812312011-02-23 13:33:46 +0000736static int robust_ftruncate(int h, sqlite3_int64 sz){
737 int rc;
dan2ee53412014-09-06 16:49:40 +0000738#ifdef __ANDROID__
739 /* On Android, ftruncate() always uses 32-bit offsets, even if
740 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
dan524a7332014-09-06 17:06:13 +0000741 ** truncate a file to any size larger than 2GiB. Silently ignore any
dan2ee53412014-09-06 16:49:40 +0000742 ** such attempts. */
743 if( sz>(sqlite3_int64)0x7FFFFFFF ){
744 rc = SQLITE_OK;
745 }else
746#endif
drh99ab3b12011-03-02 15:09:07 +0000747 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000748 return rc;
749}
drh734c9862008-11-28 15:37:20 +0000750
751/*
752** This routine translates a standard POSIX errno code into something
753** useful to the clients of the sqlite3 functions. Specifically, it is
754** intended to translate a variety of "try again" errors into SQLITE_BUSY
755** and a variety of "please close the file descriptor NOW" errors into
756** SQLITE_IOERR
757**
758** Errors during initialization of locks, or file system support for locks,
759** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
760*/
761static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
drh91c4def2015-11-25 14:00:07 +0000762 assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
763 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
764 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
765 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
drh734c9862008-11-28 15:37:20 +0000766 switch (posixError) {
drh91c4def2015-11-25 14:00:07 +0000767 case EACCES:
drh734c9862008-11-28 15:37:20 +0000768 case EAGAIN:
769 case ETIMEDOUT:
770 case EBUSY:
771 case EINTR:
772 case ENOLCK:
773 /* random NFS retry error, unless during file system support
774 * introspection, in which it actually means what it says */
775 return SQLITE_BUSY;
776
drh734c9862008-11-28 15:37:20 +0000777 case EPERM:
778 return SQLITE_PERM;
779
drh734c9862008-11-28 15:37:20 +0000780 default:
781 return sqliteIOErr;
782 }
783}
784
785
drh734c9862008-11-28 15:37:20 +0000786/******************************************************************************
787****************** Begin Unique File ID Utility Used By VxWorks ***************
788**
789** On most versions of unix, we can get a unique ID for a file by concatenating
790** the device number and the inode number. But this does not work on VxWorks.
791** On VxWorks, a unique file id must be based on the canonical filename.
792**
793** A pointer to an instance of the following structure can be used as a
794** unique file ID in VxWorks. Each instance of this structure contains
795** a copy of the canonical filename. There is also a reference count.
796** The structure is reclaimed when the number of pointers to it drops to
797** zero.
798**
799** There are never very many files open at one time and lookups are not
800** a performance-critical path, so it is sufficient to put these
801** structures on a linked list.
802*/
803struct vxworksFileId {
804 struct vxworksFileId *pNext; /* Next in a list of them all */
805 int nRef; /* Number of references to this one */
806 int nName; /* Length of the zCanonicalName[] string */
807 char *zCanonicalName; /* Canonical filename */
808};
809
810#if OS_VXWORKS
811/*
drh9b35ea62008-11-29 02:20:26 +0000812** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000813** variable:
814*/
815static struct vxworksFileId *vxworksFileList = 0;
816
817/*
818** Simplify a filename into its canonical form
819** by making the following changes:
820**
821** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000822** * convert /./ into just /
823** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000824**
825** Changes are made in-place. Return the new name length.
826**
827** The original filename is in z[0..n-1]. Return the number of
828** characters in the simplified name.
829*/
830static int vxworksSimplifyName(char *z, int n){
831 int i, j;
832 while( n>1 && z[n-1]=='/' ){ n--; }
833 for(i=j=0; i<n; i++){
834 if( z[i]=='/' ){
835 if( z[i+1]=='/' ) continue;
836 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
837 i += 1;
838 continue;
839 }
840 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
841 while( j>0 && z[j-1]!='/' ){ j--; }
842 if( j>0 ){ j--; }
843 i += 2;
844 continue;
845 }
846 }
847 z[j++] = z[i];
848 }
849 z[j] = 0;
850 return j;
851}
852
853/*
854** Find a unique file ID for the given absolute pathname. Return
855** a pointer to the vxworksFileId object. This pointer is the unique
856** file ID.
857**
858** The nRef field of the vxworksFileId object is incremented before
859** the object is returned. A new vxworksFileId object is created
860** and added to the global list if necessary.
861**
862** If a memory allocation error occurs, return NULL.
863*/
864static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
865 struct vxworksFileId *pNew; /* search key and new file ID */
866 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
867 int n; /* Length of zAbsoluteName string */
868
869 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000870 n = (int)strlen(zAbsoluteName);
drhf3cdcdc2015-04-29 16:50:28 +0000871 pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
drh734c9862008-11-28 15:37:20 +0000872 if( pNew==0 ) return 0;
873 pNew->zCanonicalName = (char*)&pNew[1];
874 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
875 n = vxworksSimplifyName(pNew->zCanonicalName, n);
876
877 /* Search for an existing entry that matching the canonical name.
878 ** If found, increment the reference count and return a pointer to
879 ** the existing file ID.
880 */
881 unixEnterMutex();
882 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
883 if( pCandidate->nName==n
884 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
885 ){
886 sqlite3_free(pNew);
887 pCandidate->nRef++;
888 unixLeaveMutex();
889 return pCandidate;
890 }
891 }
892
893 /* No match was found. We will make a new file ID */
894 pNew->nRef = 1;
895 pNew->nName = n;
896 pNew->pNext = vxworksFileList;
897 vxworksFileList = pNew;
898 unixLeaveMutex();
899 return pNew;
900}
901
902/*
903** Decrement the reference count on a vxworksFileId object. Free
904** the object when the reference count reaches zero.
905*/
906static void vxworksReleaseFileId(struct vxworksFileId *pId){
907 unixEnterMutex();
908 assert( pId->nRef>0 );
909 pId->nRef--;
910 if( pId->nRef==0 ){
911 struct vxworksFileId **pp;
912 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
913 assert( *pp==pId );
914 *pp = pId->pNext;
915 sqlite3_free(pId);
916 }
917 unixLeaveMutex();
918}
919#endif /* OS_VXWORKS */
920/*************** End of Unique File ID Utility Used By VxWorks ****************
921******************************************************************************/
922
923
924/******************************************************************************
925*************************** Posix Advisory Locking ****************************
926**
drh9b35ea62008-11-29 02:20:26 +0000927** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000928** section 6.5.2.2 lines 483 through 490 specify that when a process
929** sets or clears a lock, that operation overrides any prior locks set
930** by the same process. It does not explicitly say so, but this implies
931** that it overrides locks set by the same process using a different
932** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000933**
934** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000935** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
936**
937** Suppose ./file1 and ./file2 are really the same file (because
938** one is a hard or symbolic link to the other) then if you set
939** an exclusive lock on fd1, then try to get an exclusive lock
940** on fd2, it works. I would have expected the second lock to
941** fail since there was already a lock on the file due to fd1.
942** But not so. Since both locks came from the same process, the
943** second overrides the first, even though they were on different
944** file descriptors opened on different file names.
945**
drh734c9862008-11-28 15:37:20 +0000946** This means that we cannot use POSIX locks to synchronize file access
947** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000948** to synchronize access for threads in separate processes, but not
949** threads within the same process.
950**
951** To work around the problem, SQLite has to manage file locks internally
952** on its own. Whenever a new database is opened, we have to find the
953** specific inode of the database file (the inode is determined by the
954** st_dev and st_ino fields of the stat structure that fstat() fills in)
955** and check for locks already existing on that inode. When locks are
956** created or removed, we have to look at our own internal record of the
957** locks to see if another thread has previously set a lock on that same
958** inode.
959**
drh9b35ea62008-11-29 02:20:26 +0000960** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
961** For VxWorks, we have to use the alternative unique ID system based on
962** canonical filename and implemented in the previous division.)
963**
danielk1977ad94b582007-08-20 06:44:22 +0000964** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000965** descriptor. It is now a structure that holds the integer file
966** descriptor and a pointer to a structure that describes the internal
967** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000968** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000969** point to the same locking structure. The locking structure keeps
970** a reference count (so we will know when to delete it) and a "cnt"
971** field that tells us its internal lock status. cnt==0 means the
972** file is unlocked. cnt==-1 means the file has an exclusive lock.
973** cnt>0 means there are cnt shared locks on the file.
974**
975** Any attempt to lock or unlock a file first checks the locking
976** structure. The fcntl() system call is only invoked to set a
977** POSIX lock if the internal lock structure transitions between
978** a locked and an unlocked state.
979**
drh734c9862008-11-28 15:37:20 +0000980** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000981**
982** If you close a file descriptor that points to a file that has locks,
983** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000984** released. To work around this problem, each unixInodeInfo object
985** maintains a count of the number of pending locks on tha inode.
986** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000987** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000988** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000989** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000990** be closed and that list is walked (and cleared) when the last lock
991** clears.
992**
drh9b35ea62008-11-29 02:20:26 +0000993** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000994**
drh9b35ea62008-11-29 02:20:26 +0000995** Many older versions of linux use the LinuxThreads library which is
996** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000997** A cannot be modified or overridden by a different thread B.
998** Only thread A can modify the lock. Locking behavior is correct
999** if the appliation uses the newer Native Posix Thread Library (NPTL)
1000** on linux - with NPTL a lock created by thread A can override locks
1001** in thread B. But there is no way to know at compile-time which
1002** threading library is being used. So there is no way to know at
1003** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001004** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001005** current process.
drh5fdae772004-06-29 03:29:00 +00001006**
drh8af6c222010-05-14 12:43:01 +00001007** SQLite used to support LinuxThreads. But support for LinuxThreads
1008** was dropped beginning with version 3.7.0. SQLite will still work with
1009** LinuxThreads provided that (1) there is no more than one connection
1010** per database file in the same process and (2) database connections
1011** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001012*/
1013
1014/*
1015** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001016** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001017*/
1018struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001019 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001020#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001021 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001022#else
drh107886a2008-11-21 22:21:50 +00001023 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001024#endif
1025};
1026
1027/*
drhbbd42a62004-05-22 17:41:58 +00001028** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001029** inode. Or, on LinuxThreads, there is one of these structures for
1030** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001031**
danielk1977ad94b582007-08-20 06:44:22 +00001032** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001033** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001034** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001035*/
drh8af6c222010-05-14 12:43:01 +00001036struct unixInodeInfo {
1037 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001038 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001039 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1040 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001041 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001042 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1043 int nLock; /* Number of outstanding file locks */
1044 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1045 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1046 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001047#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001048 unsigned long long sharedByte; /* for AFP simulated shared lock */
1049#endif
drh6c7d5c52008-11-21 20:32:33 +00001050#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001051 sem_t *pSem; /* Named POSIX semaphore */
1052 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001053#endif
drhbbd42a62004-05-22 17:41:58 +00001054};
1055
drhda0e7682008-07-30 15:27:54 +00001056/*
drh8af6c222010-05-14 12:43:01 +00001057** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001058*/
drhd91c68f2010-05-14 14:52:25 +00001059static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001060
drh5fdae772004-06-29 03:29:00 +00001061/*
dane18d4952011-02-21 11:46:24 +00001062**
drhaaeaa182015-11-24 15:12:47 +00001063** This function - unixLogErrorAtLine(), is only ever called via the macro
dane18d4952011-02-21 11:46:24 +00001064** unixLogError().
1065**
1066** It is invoked after an error occurs in an OS function and errno has been
1067** set. It logs a message using sqlite3_log() containing the current value of
1068** errno and, if possible, the human-readable equivalent from strerror() or
1069** strerror_r().
1070**
1071** The first argument passed to the macro should be the error code that
1072** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1073** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001074** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001075** if any.
1076*/
drh0e9365c2011-03-02 02:08:13 +00001077#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1078static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001079 int errcode, /* SQLite error code */
1080 const char *zFunc, /* Name of OS function that failed */
1081 const char *zPath, /* File path associated with error */
1082 int iLine /* Source line number where error occurred */
1083){
1084 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001085 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001086
1087 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1088 ** the strerror() function to obtain the human-readable error message
1089 ** equivalent to errno. Otherwise, use strerror_r().
1090 */
1091#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1092 char aErr[80];
1093 memset(aErr, 0, sizeof(aErr));
1094 zErr = aErr;
1095
1096 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001097 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001098 ** returns a pointer to a buffer containing the error message. That pointer
1099 ** may point to aErr[], or it may point to some static storage somewhere.
1100 ** Otherwise, assume that the system provides the POSIX version of
1101 ** strerror_r(), which always writes an error message into aErr[].
1102 **
1103 ** If the code incorrectly assumes that it is the POSIX version that is
1104 ** available, the error message will often be an empty string. Not a
1105 ** huge problem. Incorrectly concluding that the GNU version is available
1106 ** could lead to a segfault though.
1107 */
1108#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1109 zErr =
1110# endif
drh0e9365c2011-03-02 02:08:13 +00001111 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001112
1113#elif SQLITE_THREADSAFE
1114 /* This is a threadsafe build, but strerror_r() is not available. */
1115 zErr = "";
1116#else
1117 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001118 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001119#endif
1120
drh0e9365c2011-03-02 02:08:13 +00001121 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001122 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001123 "os_unix.c:%d: (%d) %s(%s) - %s",
1124 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001125 );
1126
1127 return errcode;
1128}
1129
drh0e9365c2011-03-02 02:08:13 +00001130/*
1131** Close a file descriptor.
1132**
1133** We assume that close() almost always works, since it is only in a
1134** very sick application or on a very sick platform that it might fail.
1135** If it does fail, simply leak the file descriptor, but do log the
1136** error.
1137**
1138** Note that it is not safe to retry close() after EINTR since the
1139** file descriptor might have already been reused by another thread.
1140** So we don't even try to recover from an EINTR. Just log the error
1141** and move on.
1142*/
1143static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001144 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001145 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1146 pFile ? pFile->zPath : 0, lineno);
1147 }
1148}
dane18d4952011-02-21 11:46:24 +00001149
1150/*
drhe6d41732015-02-21 00:49:00 +00001151** Set the pFile->lastErrno. Do this in a subroutine as that provides
1152** a convenient place to set a breakpoint.
drh4bf66fd2015-02-19 02:43:02 +00001153*/
1154static void storeLastErrno(unixFile *pFile, int error){
1155 pFile->lastErrno = error;
1156}
1157
1158/*
danb0ac3e32010-06-16 10:55:42 +00001159** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001160*/
drh0e9365c2011-03-02 02:08:13 +00001161static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001162 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001163 UnixUnusedFd *p;
1164 UnixUnusedFd *pNext;
1165 for(p=pInode->pUnused; p; p=pNext){
1166 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001167 robust_close(pFile, p->fd, __LINE__);
1168 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001169 }
drh0e9365c2011-03-02 02:08:13 +00001170 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001171}
1172
1173/*
drh8af6c222010-05-14 12:43:01 +00001174** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001175**
1176** The mutex entered using the unixEnterMutex() function must be held
1177** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001178*/
danb0ac3e32010-06-16 10:55:42 +00001179static void releaseInodeInfo(unixFile *pFile){
1180 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001181 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001182 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001183 pInode->nRef--;
1184 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001185 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001186 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001187 if( pInode->pPrev ){
1188 assert( pInode->pPrev->pNext==pInode );
1189 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001190 }else{
drh8af6c222010-05-14 12:43:01 +00001191 assert( inodeList==pInode );
1192 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001193 }
drh8af6c222010-05-14 12:43:01 +00001194 if( pInode->pNext ){
1195 assert( pInode->pNext->pPrev==pInode );
1196 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001197 }
drh8af6c222010-05-14 12:43:01 +00001198 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001199 }
drhbbd42a62004-05-22 17:41:58 +00001200 }
1201}
1202
1203/*
drh8af6c222010-05-14 12:43:01 +00001204** Given a file descriptor, locate the unixInodeInfo object that
1205** describes that file descriptor. Create a new one if necessary. The
1206** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001207**
dan9359c7b2009-08-21 08:29:10 +00001208** The mutex entered using the unixEnterMutex() function must be held
1209** when this function is called.
1210**
drh6c7d5c52008-11-21 20:32:33 +00001211** Return an appropriate error code.
1212*/
drh8af6c222010-05-14 12:43:01 +00001213static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001214 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001215 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001216){
1217 int rc; /* System call return code */
1218 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001219 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1220 struct stat statbuf; /* Low-level file information */
1221 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001222
dan9359c7b2009-08-21 08:29:10 +00001223 assert( unixMutexHeld() );
1224
drh6c7d5c52008-11-21 20:32:33 +00001225 /* Get low-level information about the file that we can used to
1226 ** create a unique name for the file.
1227 */
1228 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001229 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001230 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001231 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001232#ifdef EOVERFLOW
1233 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1234#endif
1235 return SQLITE_IOERR;
1236 }
1237
drheb0d74f2009-02-03 15:27:02 +00001238#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001239 /* On OS X on an msdos filesystem, the inode number is reported
1240 ** incorrectly for zero-size files. See ticket #3260. To work
1241 ** around this problem (we consider it a bug in OS X, not SQLite)
1242 ** we always increase the file size to 1 by writing a single byte
1243 ** prior to accessing the inode number. The one byte written is
1244 ** an ASCII 'S' character which also happens to be the first byte
1245 ** in the header of every SQLite database. In this way, if there
1246 ** is a race condition such that another thread has already populated
1247 ** the first page of the database, no damage is done.
1248 */
drh7ed97b92010-01-20 13:07:21 +00001249 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001250 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001251 if( rc!=1 ){
drh4bf66fd2015-02-19 02:43:02 +00001252 storeLastErrno(pFile, errno);
drheb0d74f2009-02-03 15:27:02 +00001253 return SQLITE_IOERR;
1254 }
drh99ab3b12011-03-02 15:09:07 +00001255 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001256 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001257 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001258 return SQLITE_IOERR;
1259 }
1260 }
drheb0d74f2009-02-03 15:27:02 +00001261#endif
drh6c7d5c52008-11-21 20:32:33 +00001262
drh8af6c222010-05-14 12:43:01 +00001263 memset(&fileId, 0, sizeof(fileId));
1264 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001265#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001266 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001267#else
drh8af6c222010-05-14 12:43:01 +00001268 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001269#endif
drh8af6c222010-05-14 12:43:01 +00001270 pInode = inodeList;
1271 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1272 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001273 }
drh8af6c222010-05-14 12:43:01 +00001274 if( pInode==0 ){
drhf3cdcdc2015-04-29 16:50:28 +00001275 pInode = sqlite3_malloc64( sizeof(*pInode) );
drh8af6c222010-05-14 12:43:01 +00001276 if( pInode==0 ){
1277 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001278 }
drh8af6c222010-05-14 12:43:01 +00001279 memset(pInode, 0, sizeof(*pInode));
1280 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1281 pInode->nRef = 1;
1282 pInode->pNext = inodeList;
1283 pInode->pPrev = 0;
1284 if( inodeList ) inodeList->pPrev = pInode;
1285 inodeList = pInode;
1286 }else{
1287 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001288 }
drh8af6c222010-05-14 12:43:01 +00001289 *ppInode = pInode;
1290 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001291}
drh6c7d5c52008-11-21 20:32:33 +00001292
drhb959a012013-12-07 12:29:22 +00001293/*
1294** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1295*/
1296static int fileHasMoved(unixFile *pFile){
drh61ffea52014-08-12 12:19:25 +00001297#if OS_VXWORKS
1298 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1299#else
drhb959a012013-12-07 12:29:22 +00001300 struct stat buf;
1301 return pFile->pInode!=0 &&
drh61ffea52014-08-12 12:19:25 +00001302 (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
drh91be7dc2014-08-11 13:53:30 +00001303#endif
drhb959a012013-12-07 12:29:22 +00001304}
1305
aswift5b1a2562008-08-22 00:22:35 +00001306
1307/*
drhfbc7e882013-04-11 01:16:15 +00001308** Check a unixFile that is a database. Verify the following:
1309**
1310** (1) There is exactly one hard link on the file
1311** (2) The file is not a symbolic link
1312** (3) The file has not been renamed or unlinked
1313**
1314** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1315*/
1316static void verifyDbFile(unixFile *pFile){
1317 struct stat buf;
1318 int rc;
drhfbc7e882013-04-11 01:16:15 +00001319 rc = osFstat(pFile->h, &buf);
1320 if( rc!=0 ){
1321 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001322 return;
1323 }
drh3044b512014-06-16 16:41:52 +00001324 if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
drhfbc7e882013-04-11 01:16:15 +00001325 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001326 return;
1327 }
1328 if( buf.st_nlink>1 ){
1329 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001330 return;
1331 }
drhb959a012013-12-07 12:29:22 +00001332 if( fileHasMoved(pFile) ){
drhfbc7e882013-04-11 01:16:15 +00001333 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001334 return;
1335 }
1336}
1337
1338
1339/*
danielk197713adf8a2004-06-03 16:08:41 +00001340** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001341** file by this or any other process. If such a lock is held, set *pResOut
1342** to a non-zero value otherwise *pResOut is set to zero. The return value
1343** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001344*/
danielk1977861f7452008-06-05 11:39:11 +00001345static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001346 int rc = SQLITE_OK;
1347 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001348 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001349
danielk1977861f7452008-06-05 11:39:11 +00001350 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1351
drh054889e2005-11-30 03:20:31 +00001352 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001353 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001354
1355 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001356 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001357 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001358 }
1359
drh2ac3ee92004-06-07 16:27:46 +00001360 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001361 */
danielk197709480a92009-02-09 05:32:32 +00001362#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001363 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001364 struct flock lock;
1365 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001366 lock.l_start = RESERVED_BYTE;
1367 lock.l_len = 1;
1368 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001369 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1370 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001371 storeLastErrno(pFile, errno);
aswift5b1a2562008-08-22 00:22:35 +00001372 } else if( lock.l_type!=F_UNLCK ){
1373 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001374 }
1375 }
danielk197709480a92009-02-09 05:32:32 +00001376#endif
danielk197713adf8a2004-06-03 16:08:41 +00001377
drh6c7d5c52008-11-21 20:32:33 +00001378 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001379 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001380
aswift5b1a2562008-08-22 00:22:35 +00001381 *pResOut = reserved;
1382 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001383}
1384
1385/*
drha7e61d82011-03-12 17:02:57 +00001386** Attempt to set a system-lock on the file pFile. The lock is
1387** described by pLock.
1388**
drh77197112011-03-15 19:08:48 +00001389** If the pFile was opened read/write from unix-excl, then the only lock
1390** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001391** the first time any lock is attempted. All subsequent system locking
1392** operations become no-ops. Locking operations still happen internally,
1393** in order to coordinate access between separate database connections
1394** within this process, but all of that is handled in memory and the
1395** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001396**
1397** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1398** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1399** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001400**
1401** Zero is returned if the call completes successfully, or -1 if a call
1402** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001403*/
1404static int unixFileLock(unixFile *pFile, struct flock *pLock){
1405 int rc;
drh3cb93392011-03-12 18:10:44 +00001406 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001407 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001408 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001409 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1410 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1411 ){
drh3cb93392011-03-12 18:10:44 +00001412 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001413 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001414 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001415 lock.l_whence = SEEK_SET;
1416 lock.l_start = SHARED_FIRST;
1417 lock.l_len = SHARED_SIZE;
1418 lock.l_type = F_WRLCK;
1419 rc = osFcntl(pFile->h, F_SETLK, &lock);
1420 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001421 pInode->bProcessLock = 1;
1422 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001423 }else{
1424 rc = 0;
1425 }
1426 }else{
1427 rc = osFcntl(pFile->h, F_SETLK, pLock);
1428 }
1429 return rc;
1430}
1431
1432/*
drh308c2a52010-05-14 11:30:18 +00001433** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001434** of the following:
1435**
drh2ac3ee92004-06-07 16:27:46 +00001436** (1) SHARED_LOCK
1437** (2) RESERVED_LOCK
1438** (3) PENDING_LOCK
1439** (4) EXCLUSIVE_LOCK
1440**
drhb3e04342004-06-08 00:47:47 +00001441** Sometimes when requesting one lock state, additional lock states
1442** are inserted in between. The locking might fail on one of the later
1443** transitions leaving the lock state different from what it started but
1444** still short of its goal. The following chart shows the allowed
1445** transitions and the inserted intermediate states:
1446**
1447** UNLOCKED -> SHARED
1448** SHARED -> RESERVED
1449** SHARED -> (PENDING) -> EXCLUSIVE
1450** RESERVED -> (PENDING) -> EXCLUSIVE
1451** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001452**
drha6abd042004-06-09 17:37:22 +00001453** This routine will only increase a lock. Use the sqlite3OsUnlock()
1454** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001455*/
drh308c2a52010-05-14 11:30:18 +00001456static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001457 /* The following describes the implementation of the various locks and
1458 ** lock transitions in terms of the POSIX advisory shared and exclusive
1459 ** lock primitives (called read-locks and write-locks below, to avoid
1460 ** confusion with SQLite lock names). The algorithms are complicated
1461 ** slightly in order to be compatible with windows systems simultaneously
1462 ** accessing the same database file, in case that is ever required.
1463 **
1464 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1465 ** byte', each single bytes at well known offsets, and the 'shared byte
1466 ** range', a range of 510 bytes at a well known offset.
1467 **
1468 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1469 ** byte'. If this is successful, a random byte from the 'shared byte
1470 ** range' is read-locked and the lock on the 'pending byte' released.
1471 **
danielk197790ba3bd2004-06-25 08:32:25 +00001472 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1473 ** A RESERVED lock is implemented by grabbing a write-lock on the
1474 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001475 **
1476 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001477 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1478 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1479 ** obtained, but existing SHARED locks are allowed to persist. A process
1480 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1481 ** This property is used by the algorithm for rolling back a journal file
1482 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001483 **
danielk197790ba3bd2004-06-25 08:32:25 +00001484 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1485 ** implemented by obtaining a write-lock on the entire 'shared byte
1486 ** range'. Since all other locks require a read-lock on one of the bytes
1487 ** within this range, this ensures that no other locks are held on the
1488 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001489 **
1490 ** The reason a single byte cannot be used instead of the 'shared byte
1491 ** range' is that some versions of windows do not support read-locks. By
1492 ** locking a random byte from a range, concurrent SHARED locks may exist
1493 ** even if the locking primitive used is always a write-lock.
1494 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001495 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001496 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001497 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001498 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001499 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001500
drh054889e2005-11-30 03:20:31 +00001501 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001502 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1503 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh91eb93c2015-03-03 19:56:20 +00001504 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001505 osGetpid(0)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001506
1507 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001508 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001509 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001510 */
drh308c2a52010-05-14 11:30:18 +00001511 if( pFile->eFileLock>=eFileLock ){
1512 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1513 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001514 return SQLITE_OK;
1515 }
1516
drh0c2694b2009-09-03 16:23:44 +00001517 /* Make sure the locking sequence is correct.
1518 ** (1) We never move from unlocked to anything higher than shared lock.
1519 ** (2) SQLite never explicitly requests a pendig lock.
1520 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001521 */
drh308c2a52010-05-14 11:30:18 +00001522 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1523 assert( eFileLock!=PENDING_LOCK );
1524 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001525
drh8af6c222010-05-14 12:43:01 +00001526 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001527 */
drh6c7d5c52008-11-21 20:32:33 +00001528 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001529 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001530
danielk1977ad94b582007-08-20 06:44:22 +00001531 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001532 ** handle that precludes the requested lock, return BUSY.
1533 */
drh8af6c222010-05-14 12:43:01 +00001534 if( (pFile->eFileLock!=pInode->eFileLock &&
1535 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001536 ){
1537 rc = SQLITE_BUSY;
1538 goto end_lock;
1539 }
1540
1541 /* If a SHARED lock is requested, and some thread using this PID already
1542 ** has a SHARED or RESERVED lock, then increment reference counts and
1543 ** return SQLITE_OK.
1544 */
drh308c2a52010-05-14 11:30:18 +00001545 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001546 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001547 assert( eFileLock==SHARED_LOCK );
1548 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001549 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001550 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001551 pInode->nShared++;
1552 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001553 goto end_lock;
1554 }
1555
danielk19779a1d0ab2004-06-01 14:09:28 +00001556
drh3cde3bb2004-06-12 02:17:14 +00001557 /* A PENDING lock is needed before acquiring a SHARED lock and before
1558 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1559 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001560 */
drh0c2694b2009-09-03 16:23:44 +00001561 lock.l_len = 1L;
1562 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001563 if( eFileLock==SHARED_LOCK
1564 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001565 ){
drh308c2a52010-05-14 11:30:18 +00001566 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001567 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001568 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001569 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001570 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001571 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001572 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001573 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001574 goto end_lock;
1575 }
drh3cde3bb2004-06-12 02:17:14 +00001576 }
1577
1578
1579 /* If control gets to this point, then actually go ahead and make
1580 ** operating system calls for the specified lock.
1581 */
drh308c2a52010-05-14 11:30:18 +00001582 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001583 assert( pInode->nShared==0 );
1584 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001585 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001586
drh2ac3ee92004-06-07 16:27:46 +00001587 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001588 lock.l_start = SHARED_FIRST;
1589 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001590 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001591 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001592 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001593 }
dan661d71a2011-03-30 19:08:03 +00001594
drh2ac3ee92004-06-07 16:27:46 +00001595 /* Drop the temporary PENDING lock */
1596 lock.l_start = PENDING_BYTE;
1597 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001598 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001599 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1600 /* This could happen with a network mount */
1601 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001602 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001603 }
dan661d71a2011-03-30 19:08:03 +00001604
1605 if( rc ){
1606 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001607 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001608 }
dan661d71a2011-03-30 19:08:03 +00001609 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001610 }else{
drh308c2a52010-05-14 11:30:18 +00001611 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001612 pInode->nLock++;
1613 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001614 }
drh8af6c222010-05-14 12:43:01 +00001615 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001616 /* We are trying for an exclusive lock but another thread in this
1617 ** same process is still holding a shared lock. */
1618 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001619 }else{
drh3cde3bb2004-06-12 02:17:14 +00001620 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001621 ** assumed that there is a SHARED or greater lock on the file
1622 ** already.
1623 */
drh308c2a52010-05-14 11:30:18 +00001624 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001625 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001626
1627 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1628 if( eFileLock==RESERVED_LOCK ){
1629 lock.l_start = RESERVED_BYTE;
1630 lock.l_len = 1L;
1631 }else{
1632 lock.l_start = SHARED_FIRST;
1633 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001634 }
dan661d71a2011-03-30 19:08:03 +00001635
1636 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001637 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001638 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001639 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001640 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001641 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001642 }
drhbbd42a62004-05-22 17:41:58 +00001643 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001644
drh8f941bc2009-01-14 23:03:40 +00001645
drhd3d8c042012-05-29 17:02:40 +00001646#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001647 /* Set up the transaction-counter change checking flags when
1648 ** transitioning from a SHARED to a RESERVED lock. The change
1649 ** from SHARED to RESERVED marks the beginning of a normal
1650 ** write operation (not a hot journal rollback).
1651 */
1652 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001653 && pFile->eFileLock<=SHARED_LOCK
1654 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001655 ){
1656 pFile->transCntrChng = 0;
1657 pFile->dbUpdate = 0;
1658 pFile->inNormalWrite = 1;
1659 }
1660#endif
1661
1662
danielk1977ecb2a962004-06-02 06:30:16 +00001663 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001664 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001665 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001666 }else if( eFileLock==EXCLUSIVE_LOCK ){
1667 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001668 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001669 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001670
1671end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001672 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001673 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1674 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001675 return rc;
1676}
1677
1678/*
dan08da86a2009-08-21 17:18:03 +00001679** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001680** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001681*/
1682static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001683 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001684 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001685 p->pNext = pInode->pUnused;
1686 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001687 pFile->h = -1;
1688 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001689}
1690
1691/*
drh308c2a52010-05-14 11:30:18 +00001692** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001693** must be either NO_LOCK or SHARED_LOCK.
1694**
1695** If the locking level of the file descriptor is already at or below
1696** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001697**
1698** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1699** the byte range is divided into 2 parts and the first part is unlocked then
1700** set to a read lock, then the other part is simply unlocked. This works
1701** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1702** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001703*/
drha7e61d82011-03-12 17:02:57 +00001704static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001705 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001706 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001707 struct flock lock;
1708 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001709
drh054889e2005-11-30 03:20:31 +00001710 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001711 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001712 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001713 osGetpid(0)));
drha6abd042004-06-09 17:37:22 +00001714
drh308c2a52010-05-14 11:30:18 +00001715 assert( eFileLock<=SHARED_LOCK );
1716 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001717 return SQLITE_OK;
1718 }
drh6c7d5c52008-11-21 20:32:33 +00001719 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001720 pInode = pFile->pInode;
1721 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001722 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001723 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001724
drhd3d8c042012-05-29 17:02:40 +00001725#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001726 /* When reducing a lock such that other processes can start
1727 ** reading the database file again, make sure that the
1728 ** transaction counter was updated if any part of the database
1729 ** file changed. If the transaction counter is not updated,
1730 ** other connections to the same file might not realize that
1731 ** the file has changed and hence might not know to flush their
1732 ** cache. The use of a stale cache can lead to database corruption.
1733 */
drh8f941bc2009-01-14 23:03:40 +00001734 pFile->inNormalWrite = 0;
1735#endif
1736
drh7ed97b92010-01-20 13:07:21 +00001737 /* downgrading to a shared lock on NFS involves clearing the write lock
1738 ** before establishing the readlock - to avoid a race condition we downgrade
1739 ** the lock in 2 blocks, so that part of the range will be covered by a
1740 ** write lock until the rest is covered by a read lock:
1741 ** 1: [WWWWW]
1742 ** 2: [....W]
1743 ** 3: [RRRRW]
1744 ** 4: [RRRR.]
1745 */
drh308c2a52010-05-14 11:30:18 +00001746 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001747#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001748 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001749 assert( handleNFSUnlock==0 );
1750#endif
1751#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001752 if( handleNFSUnlock ){
drha712b4b2015-02-19 16:12:04 +00001753 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001754 off_t divSize = SHARED_SIZE - 1;
1755
1756 lock.l_type = F_UNLCK;
1757 lock.l_whence = SEEK_SET;
1758 lock.l_start = SHARED_FIRST;
1759 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001760 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001761 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001762 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001763 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001764 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001765 }
1766 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001767 }
drh7ed97b92010-01-20 13:07:21 +00001768 lock.l_type = F_RDLCK;
1769 lock.l_whence = SEEK_SET;
1770 lock.l_start = SHARED_FIRST;
1771 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001772 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001773 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001774 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1775 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001776 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001777 }
1778 goto end_unlock;
1779 }
1780 lock.l_type = F_UNLCK;
1781 lock.l_whence = SEEK_SET;
1782 lock.l_start = SHARED_FIRST+divSize;
1783 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001784 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001785 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001786 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001787 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001788 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001789 }
1790 goto end_unlock;
1791 }
drh30f776f2011-02-25 03:25:07 +00001792 }else
1793#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1794 {
drh7ed97b92010-01-20 13:07:21 +00001795 lock.l_type = F_RDLCK;
1796 lock.l_whence = SEEK_SET;
1797 lock.l_start = SHARED_FIRST;
1798 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001799 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001800 /* In theory, the call to unixFileLock() cannot fail because another
1801 ** process is holding an incompatible lock. If it does, this
1802 ** indicates that the other process is not following the locking
1803 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1804 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1805 ** an assert to fail). */
1806 rc = SQLITE_IOERR_RDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001807 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00001808 goto end_unlock;
1809 }
drh9c105bb2004-10-02 20:38:28 +00001810 }
1811 }
drhbbd42a62004-05-22 17:41:58 +00001812 lock.l_type = F_UNLCK;
1813 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001814 lock.l_start = PENDING_BYTE;
1815 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001816 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001817 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001818 }else{
danea83bc62011-04-01 11:56:32 +00001819 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001820 storeLastErrno(pFile, errno);
drhcd731cf2009-03-28 23:23:02 +00001821 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001822 }
drhbbd42a62004-05-22 17:41:58 +00001823 }
drh308c2a52010-05-14 11:30:18 +00001824 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001825 /* Decrement the shared lock counter. Release the lock using an
1826 ** OS call only when all threads in this same process have released
1827 ** the lock.
1828 */
drh8af6c222010-05-14 12:43:01 +00001829 pInode->nShared--;
1830 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001831 lock.l_type = F_UNLCK;
1832 lock.l_whence = SEEK_SET;
1833 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001834 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001835 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001836 }else{
danea83bc62011-04-01 11:56:32 +00001837 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001838 storeLastErrno(pFile, errno);
drh8af6c222010-05-14 12:43:01 +00001839 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001840 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001841 }
drha6abd042004-06-09 17:37:22 +00001842 }
1843
drhbbd42a62004-05-22 17:41:58 +00001844 /* Decrement the count of locks against this same file. When the
1845 ** count reaches zero, close any other file descriptors whose close
1846 ** was deferred because of outstanding locks.
1847 */
drh8af6c222010-05-14 12:43:01 +00001848 pInode->nLock--;
1849 assert( pInode->nLock>=0 );
1850 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001851 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001852 }
1853 }
drhf2f105d2012-08-20 15:53:54 +00001854
aswift5b1a2562008-08-22 00:22:35 +00001855end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001856 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001857 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001858 return rc;
drhbbd42a62004-05-22 17:41:58 +00001859}
1860
1861/*
drh308c2a52010-05-14 11:30:18 +00001862** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001863** must be either NO_LOCK or SHARED_LOCK.
1864**
1865** If the locking level of the file descriptor is already at or below
1866** the requested locking level, this routine is a no-op.
1867*/
drh308c2a52010-05-14 11:30:18 +00001868static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00001869#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00001870 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00001871#endif
drha7e61d82011-03-12 17:02:57 +00001872 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001873}
1874
mistachkine98844f2013-08-24 00:59:24 +00001875#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001876static int unixMapfile(unixFile *pFd, i64 nByte);
1877static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00001878#endif
danf23da962013-03-23 21:00:41 +00001879
drh7ed97b92010-01-20 13:07:21 +00001880/*
danielk1977e339d652008-06-28 11:23:00 +00001881** This function performs the parts of the "close file" operation
1882** common to all locking schemes. It closes the directory and file
1883** handles, if they are valid, and sets all fields of the unixFile
1884** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001885**
1886** It is *not* necessary to hold the mutex when this routine is called,
1887** even on VxWorks. A mutex will be acquired on VxWorks by the
1888** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001889*/
1890static int closeUnixFile(sqlite3_file *id){
1891 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00001892#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001893 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00001894#endif
dan661d71a2011-03-30 19:08:03 +00001895 if( pFile->h>=0 ){
1896 robust_close(pFile, pFile->h, __LINE__);
1897 pFile->h = -1;
1898 }
1899#if OS_VXWORKS
1900 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001901 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001902 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001903 }
1904 vxworksReleaseFileId(pFile->pId);
1905 pFile->pId = 0;
1906 }
1907#endif
drh0bdbc902014-06-16 18:35:06 +00001908#ifdef SQLITE_UNLINK_AFTER_CLOSE
1909 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
1910 osUnlink(pFile->zPath);
1911 sqlite3_free(*(char**)&pFile->zPath);
1912 pFile->zPath = 0;
1913 }
1914#endif
dan661d71a2011-03-30 19:08:03 +00001915 OSTRACE(("CLOSE %-3d\n", pFile->h));
1916 OpenCounter(-1);
1917 sqlite3_free(pFile->pUnused);
1918 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001919 return SQLITE_OK;
1920}
1921
1922/*
danielk1977e3026632004-06-22 11:29:02 +00001923** Close a file.
1924*/
danielk197762079062007-08-15 17:08:46 +00001925static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001926 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001927 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00001928 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00001929 unixUnlock(id, NO_LOCK);
1930 unixEnterMutex();
1931
1932 /* unixFile.pInode is always valid here. Otherwise, a different close
1933 ** routine (e.g. nolockClose()) would be called instead.
1934 */
1935 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1936 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1937 /* If there are outstanding locks, do not actually close the file just
1938 ** yet because that would clear those locks. Instead, add the file
1939 ** descriptor to pInode->pUnused list. It will be automatically closed
1940 ** when the last lock is cleared.
1941 */
1942 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001943 }
dan661d71a2011-03-30 19:08:03 +00001944 releaseInodeInfo(pFile);
1945 rc = closeUnixFile(id);
1946 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001947 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001948}
1949
drh734c9862008-11-28 15:37:20 +00001950/************** End of the posix advisory lock implementation *****************
1951******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001952
drh734c9862008-11-28 15:37:20 +00001953/******************************************************************************
1954****************************** No-op Locking **********************************
1955**
1956** Of the various locking implementations available, this is by far the
1957** simplest: locking is ignored. No attempt is made to lock the database
1958** file for reading or writing.
1959**
1960** This locking mode is appropriate for use on read-only databases
1961** (ex: databases that are burned into CD-ROM, for example.) It can
1962** also be used if the application employs some external mechanism to
1963** prevent simultaneous access of the same database by two or more
1964** database connections. But there is a serious risk of database
1965** corruption if this locking mode is used in situations where multiple
1966** database connections are accessing the same database file at the same
1967** time and one or more of those connections are writing.
1968*/
drhbfe66312006-10-03 17:40:40 +00001969
drh734c9862008-11-28 15:37:20 +00001970static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1971 UNUSED_PARAMETER(NotUsed);
1972 *pResOut = 0;
1973 return SQLITE_OK;
1974}
drh734c9862008-11-28 15:37:20 +00001975static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1976 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1977 return SQLITE_OK;
1978}
drh734c9862008-11-28 15:37:20 +00001979static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1980 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1981 return SQLITE_OK;
1982}
1983
1984/*
drh9b35ea62008-11-29 02:20:26 +00001985** Close the file.
drh734c9862008-11-28 15:37:20 +00001986*/
1987static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001988 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001989}
1990
1991/******************* End of the no-op lock implementation *********************
1992******************************************************************************/
1993
1994/******************************************************************************
1995************************* Begin dot-file Locking ******************************
1996**
mistachkin48864df2013-03-21 21:20:32 +00001997** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00001998** files (really a directory) to control access to the database. This works
1999** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002000**
2001** (1) There is zero concurrency. A single reader blocks all other
2002** connections from reading or writing the database.
2003**
2004** (2) An application crash or power loss can leave stale lock files
2005** sitting around that need to be cleared manually.
2006**
2007** Nevertheless, a dotlock is an appropriate locking mode for use if no
2008** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002009**
drh9ef6bc42011-11-04 02:24:02 +00002010** Dotfile locking works by creating a subdirectory in the same directory as
2011** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002012** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002013** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002014*/
2015
2016/*
2017** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002018** lock directory.
drh734c9862008-11-28 15:37:20 +00002019*/
2020#define DOTLOCK_SUFFIX ".lock"
2021
drh7708e972008-11-29 00:56:52 +00002022/*
2023** This routine checks if there is a RESERVED lock held on the specified
2024** file by this or any other process. If such a lock is held, set *pResOut
2025** to a non-zero value otherwise *pResOut is set to zero. The return value
2026** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2027**
2028** In dotfile locking, either a lock exists or it does not. So in this
2029** variation of CheckReservedLock(), *pResOut is set to true if any lock
2030** is held on the file and false if the file is unlocked.
2031*/
drh734c9862008-11-28 15:37:20 +00002032static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2033 int rc = SQLITE_OK;
2034 int reserved = 0;
2035 unixFile *pFile = (unixFile*)id;
2036
2037 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2038
2039 assert( pFile );
2040
2041 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002042 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00002043 /* Either this connection or some other connection in the same process
2044 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00002045 reserved = 1;
drh7708e972008-11-29 00:56:52 +00002046 }else{
2047 /* The lock is held if and only if the lockfile exists */
2048 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00002049 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00002050 }
drh308c2a52010-05-14 11:30:18 +00002051 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002052 *pResOut = reserved;
2053 return rc;
2054}
2055
drh7708e972008-11-29 00:56:52 +00002056/*
drh308c2a52010-05-14 11:30:18 +00002057** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002058** of the following:
2059**
2060** (1) SHARED_LOCK
2061** (2) RESERVED_LOCK
2062** (3) PENDING_LOCK
2063** (4) EXCLUSIVE_LOCK
2064**
2065** Sometimes when requesting one lock state, additional lock states
2066** are inserted in between. The locking might fail on one of the later
2067** transitions leaving the lock state different from what it started but
2068** still short of its goal. The following chart shows the allowed
2069** transitions and the inserted intermediate states:
2070**
2071** UNLOCKED -> SHARED
2072** SHARED -> RESERVED
2073** SHARED -> (PENDING) -> EXCLUSIVE
2074** RESERVED -> (PENDING) -> EXCLUSIVE
2075** PENDING -> EXCLUSIVE
2076**
2077** This routine will only increase a lock. Use the sqlite3OsUnlock()
2078** routine to lower a locking level.
2079**
2080** With dotfile locking, we really only support state (4): EXCLUSIVE.
2081** But we track the other locking levels internally.
2082*/
drh308c2a52010-05-14 11:30:18 +00002083static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002084 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002085 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002086 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002087
drh7708e972008-11-29 00:56:52 +00002088
2089 /* If we have any lock, then the lock file already exists. All we have
2090 ** to do is adjust our internal record of the lock level.
2091 */
drh308c2a52010-05-14 11:30:18 +00002092 if( pFile->eFileLock > NO_LOCK ){
2093 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002094 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002095#ifdef HAVE_UTIME
2096 utime(zLockFile, NULL);
2097#else
drh734c9862008-11-28 15:37:20 +00002098 utimes(zLockFile, NULL);
2099#endif
drh7708e972008-11-29 00:56:52 +00002100 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002101 }
2102
2103 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002104 rc = osMkdir(zLockFile, 0777);
2105 if( rc<0 ){
2106 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002107 int tErrno = errno;
2108 if( EEXIST == tErrno ){
2109 rc = SQLITE_BUSY;
2110 } else {
2111 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2112 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002113 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002114 }
2115 }
drh7708e972008-11-29 00:56:52 +00002116 return rc;
drh734c9862008-11-28 15:37:20 +00002117 }
drh734c9862008-11-28 15:37:20 +00002118
2119 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002120 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002121 return rc;
2122}
2123
drh7708e972008-11-29 00:56:52 +00002124/*
drh308c2a52010-05-14 11:30:18 +00002125** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002126** must be either NO_LOCK or SHARED_LOCK.
2127**
2128** If the locking level of the file descriptor is already at or below
2129** the requested locking level, this routine is a no-op.
2130**
2131** When the locking level reaches NO_LOCK, delete the lock file.
2132*/
drh308c2a52010-05-14 11:30:18 +00002133static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002134 unixFile *pFile = (unixFile*)id;
2135 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002136 int rc;
drh734c9862008-11-28 15:37:20 +00002137
2138 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002139 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002140 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002141 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002142
2143 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002144 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002145 return SQLITE_OK;
2146 }
drh7708e972008-11-29 00:56:52 +00002147
2148 /* To downgrade to shared, simply update our internal notion of the
2149 ** lock state. No need to mess with the file on disk.
2150 */
drh308c2a52010-05-14 11:30:18 +00002151 if( eFileLock==SHARED_LOCK ){
2152 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002153 return SQLITE_OK;
2154 }
2155
drh7708e972008-11-29 00:56:52 +00002156 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002157 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002158 rc = osRmdir(zLockFile);
2159 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
2160 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002161 int tErrno = errno;
drh13e0ea92011-12-11 02:29:25 +00002162 rc = 0;
drh734c9862008-11-28 15:37:20 +00002163 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002164 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002165 }
2166 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002167 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002168 }
2169 return rc;
2170 }
drh308c2a52010-05-14 11:30:18 +00002171 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002172 return SQLITE_OK;
2173}
2174
2175/*
drh9b35ea62008-11-29 02:20:26 +00002176** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002177*/
2178static int dotlockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002179 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002180 if( id ){
2181 unixFile *pFile = (unixFile*)id;
2182 dotlockUnlock(id, NO_LOCK);
2183 sqlite3_free(pFile->lockingContext);
drh5a05be12012-10-09 18:51:44 +00002184 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002185 }
drh734c9862008-11-28 15:37:20 +00002186 return rc;
2187}
2188/****************** End of the dot-file lock implementation *******************
2189******************************************************************************/
2190
2191/******************************************************************************
2192************************** Begin flock Locking ********************************
2193**
2194** Use the flock() system call to do file locking.
2195**
drh6b9d6dd2008-12-03 19:34:47 +00002196** flock() locking is like dot-file locking in that the various
2197** fine-grain locking levels supported by SQLite are collapsed into
2198** a single exclusive lock. In other words, SHARED, RESERVED, and
2199** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2200** still works when you do this, but concurrency is reduced since
2201** only a single process can be reading the database at a time.
2202**
drhe89b2912015-03-03 20:42:01 +00002203** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
drh734c9862008-11-28 15:37:20 +00002204*/
drhe89b2912015-03-03 20:42:01 +00002205#if SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002206
drh6b9d6dd2008-12-03 19:34:47 +00002207/*
drhff812312011-02-23 13:33:46 +00002208** Retry flock() calls that fail with EINTR
2209*/
2210#ifdef EINTR
2211static int robust_flock(int fd, int op){
2212 int rc;
2213 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2214 return rc;
2215}
2216#else
drh5c819272011-02-23 14:00:12 +00002217# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002218#endif
2219
2220
2221/*
drh6b9d6dd2008-12-03 19:34:47 +00002222** This routine checks if there is a RESERVED lock held on the specified
2223** file by this or any other process. If such a lock is held, set *pResOut
2224** to a non-zero value otherwise *pResOut is set to zero. The return value
2225** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2226*/
drh734c9862008-11-28 15:37:20 +00002227static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2228 int rc = SQLITE_OK;
2229 int reserved = 0;
2230 unixFile *pFile = (unixFile*)id;
2231
2232 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2233
2234 assert( pFile );
2235
2236 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002237 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002238 reserved = 1;
2239 }
2240
2241 /* Otherwise see if some other process holds it. */
2242 if( !reserved ){
2243 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002244 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002245 if( !lrc ){
2246 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002247 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002248 if ( lrc ) {
2249 int tErrno = errno;
2250 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002251 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002252 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002253 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002254 rc = lrc;
2255 }
2256 }
2257 } else {
2258 int tErrno = errno;
2259 reserved = 1;
2260 /* someone else might have it reserved */
2261 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2262 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002263 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002264 rc = lrc;
2265 }
2266 }
2267 }
drh308c2a52010-05-14 11:30:18 +00002268 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002269
2270#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2271 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2272 rc = SQLITE_OK;
2273 reserved=1;
2274 }
2275#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2276 *pResOut = reserved;
2277 return rc;
2278}
2279
drh6b9d6dd2008-12-03 19:34:47 +00002280/*
drh308c2a52010-05-14 11:30:18 +00002281** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002282** of the following:
2283**
2284** (1) SHARED_LOCK
2285** (2) RESERVED_LOCK
2286** (3) PENDING_LOCK
2287** (4) EXCLUSIVE_LOCK
2288**
2289** Sometimes when requesting one lock state, additional lock states
2290** are inserted in between. The locking might fail on one of the later
2291** transitions leaving the lock state different from what it started but
2292** still short of its goal. The following chart shows the allowed
2293** transitions and the inserted intermediate states:
2294**
2295** UNLOCKED -> SHARED
2296** SHARED -> RESERVED
2297** SHARED -> (PENDING) -> EXCLUSIVE
2298** RESERVED -> (PENDING) -> EXCLUSIVE
2299** PENDING -> EXCLUSIVE
2300**
2301** flock() only really support EXCLUSIVE locks. We track intermediate
2302** lock states in the sqlite3_file structure, but all locks SHARED or
2303** above are really EXCLUSIVE locks and exclude all other processes from
2304** access the file.
2305**
2306** This routine will only increase a lock. Use the sqlite3OsUnlock()
2307** routine to lower a locking level.
2308*/
drh308c2a52010-05-14 11:30:18 +00002309static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002310 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002311 unixFile *pFile = (unixFile*)id;
2312
2313 assert( pFile );
2314
2315 /* if we already have a lock, it is exclusive.
2316 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002317 if (pFile->eFileLock > NO_LOCK) {
2318 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002319 return SQLITE_OK;
2320 }
2321
2322 /* grab an exclusive lock */
2323
drhff812312011-02-23 13:33:46 +00002324 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002325 int tErrno = errno;
2326 /* didn't get, must be busy */
2327 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2328 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002329 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002330 }
2331 } else {
2332 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002333 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002334 }
drh308c2a52010-05-14 11:30:18 +00002335 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2336 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002337#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2338 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2339 rc = SQLITE_BUSY;
2340 }
2341#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2342 return rc;
2343}
2344
drh6b9d6dd2008-12-03 19:34:47 +00002345
2346/*
drh308c2a52010-05-14 11:30:18 +00002347** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002348** must be either NO_LOCK or SHARED_LOCK.
2349**
2350** If the locking level of the file descriptor is already at or below
2351** the requested locking level, this routine is a no-op.
2352*/
drh308c2a52010-05-14 11:30:18 +00002353static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002354 unixFile *pFile = (unixFile*)id;
2355
2356 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002357 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002358 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002359 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002360
2361 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002362 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002363 return SQLITE_OK;
2364 }
2365
2366 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002367 if (eFileLock==SHARED_LOCK) {
2368 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002369 return SQLITE_OK;
2370 }
2371
2372 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002373 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002374#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002375 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002376#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002377 return SQLITE_IOERR_UNLOCK;
2378 }else{
drh308c2a52010-05-14 11:30:18 +00002379 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002380 return SQLITE_OK;
2381 }
2382}
2383
2384/*
2385** Close a file.
2386*/
2387static int flockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002388 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002389 if( id ){
2390 flockUnlock(id, NO_LOCK);
drh5a05be12012-10-09 18:51:44 +00002391 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002392 }
drh5a05be12012-10-09 18:51:44 +00002393 return rc;
drh734c9862008-11-28 15:37:20 +00002394}
2395
2396#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2397
2398/******************* End of the flock lock implementation *********************
2399******************************************************************************/
2400
2401/******************************************************************************
2402************************ Begin Named Semaphore Locking ************************
2403**
2404** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002405**
2406** Semaphore locking is like dot-lock and flock in that it really only
2407** supports EXCLUSIVE locking. Only a single process can read or write
2408** the database file at a time. This reduces potential concurrency, but
2409** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002410*/
2411#if OS_VXWORKS
2412
drh6b9d6dd2008-12-03 19:34:47 +00002413/*
2414** This routine checks if there is a RESERVED lock held on the specified
2415** file by this or any other process. If such a lock is held, set *pResOut
2416** to a non-zero value otherwise *pResOut is set to zero. The return value
2417** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2418*/
drh8cd5b252015-03-02 22:06:43 +00002419static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
drh734c9862008-11-28 15:37:20 +00002420 int rc = SQLITE_OK;
2421 int reserved = 0;
2422 unixFile *pFile = (unixFile*)id;
2423
2424 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2425
2426 assert( pFile );
2427
2428 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002429 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002430 reserved = 1;
2431 }
2432
2433 /* Otherwise see if some other process holds it. */
2434 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002435 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002436
2437 if( sem_trywait(pSem)==-1 ){
2438 int tErrno = errno;
2439 if( EAGAIN != tErrno ){
2440 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
drh4bf66fd2015-02-19 02:43:02 +00002441 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002442 } else {
2443 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002444 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002445 }
2446 }else{
2447 /* we could have it if we want it */
2448 sem_post(pSem);
2449 }
2450 }
drh308c2a52010-05-14 11:30:18 +00002451 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002452
2453 *pResOut = reserved;
2454 return rc;
2455}
2456
drh6b9d6dd2008-12-03 19:34:47 +00002457/*
drh308c2a52010-05-14 11:30:18 +00002458** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002459** of the following:
2460**
2461** (1) SHARED_LOCK
2462** (2) RESERVED_LOCK
2463** (3) PENDING_LOCK
2464** (4) EXCLUSIVE_LOCK
2465**
2466** Sometimes when requesting one lock state, additional lock states
2467** are inserted in between. The locking might fail on one of the later
2468** transitions leaving the lock state different from what it started but
2469** still short of its goal. The following chart shows the allowed
2470** transitions and the inserted intermediate states:
2471**
2472** UNLOCKED -> SHARED
2473** SHARED -> RESERVED
2474** SHARED -> (PENDING) -> EXCLUSIVE
2475** RESERVED -> (PENDING) -> EXCLUSIVE
2476** PENDING -> EXCLUSIVE
2477**
2478** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2479** lock states in the sqlite3_file structure, but all locks SHARED or
2480** above are really EXCLUSIVE locks and exclude all other processes from
2481** access the file.
2482**
2483** This routine will only increase a lock. Use the sqlite3OsUnlock()
2484** routine to lower a locking level.
2485*/
drh8cd5b252015-03-02 22:06:43 +00002486static int semXLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002487 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002488 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002489 int rc = SQLITE_OK;
2490
2491 /* if we already have a lock, it is exclusive.
2492 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002493 if (pFile->eFileLock > NO_LOCK) {
2494 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002495 rc = SQLITE_OK;
2496 goto sem_end_lock;
2497 }
2498
2499 /* lock semaphore now but bail out when already locked. */
2500 if( sem_trywait(pSem)==-1 ){
2501 rc = SQLITE_BUSY;
2502 goto sem_end_lock;
2503 }
2504
2505 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002506 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002507
2508 sem_end_lock:
2509 return rc;
2510}
2511
drh6b9d6dd2008-12-03 19:34:47 +00002512/*
drh308c2a52010-05-14 11:30:18 +00002513** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002514** must be either NO_LOCK or SHARED_LOCK.
2515**
2516** If the locking level of the file descriptor is already at or below
2517** the requested locking level, this routine is a no-op.
2518*/
drh8cd5b252015-03-02 22:06:43 +00002519static int semXUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002520 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002521 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002522
2523 assert( pFile );
2524 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002525 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002526 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002527 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002528
2529 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002530 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002531 return SQLITE_OK;
2532 }
2533
2534 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002535 if (eFileLock==SHARED_LOCK) {
2536 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002537 return SQLITE_OK;
2538 }
2539
2540 /* no, really unlock. */
2541 if ( sem_post(pSem)==-1 ) {
2542 int rc, tErrno = errno;
2543 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2544 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002545 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002546 }
2547 return rc;
2548 }
drh308c2a52010-05-14 11:30:18 +00002549 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002550 return SQLITE_OK;
2551}
2552
2553/*
2554 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002555 */
drh8cd5b252015-03-02 22:06:43 +00002556static int semXClose(sqlite3_file *id) {
drh734c9862008-11-28 15:37:20 +00002557 if( id ){
2558 unixFile *pFile = (unixFile*)id;
drh8cd5b252015-03-02 22:06:43 +00002559 semXUnlock(id, NO_LOCK);
drh734c9862008-11-28 15:37:20 +00002560 assert( pFile );
2561 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002562 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002563 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002564 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002565 }
2566 return SQLITE_OK;
2567}
2568
2569#endif /* OS_VXWORKS */
2570/*
2571** Named semaphore locking is only available on VxWorks.
2572**
2573*************** End of the named semaphore lock implementation ****************
2574******************************************************************************/
2575
2576
2577/******************************************************************************
2578*************************** Begin AFP Locking *********************************
2579**
2580** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2581** on Apple Macintosh computers - both OS9 and OSX.
2582**
2583** Third-party implementations of AFP are available. But this code here
2584** only works on OSX.
2585*/
2586
drhd2cb50b2009-01-09 21:41:17 +00002587#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002588/*
2589** The afpLockingContext structure contains all afp lock specific state
2590*/
drhbfe66312006-10-03 17:40:40 +00002591typedef struct afpLockingContext afpLockingContext;
2592struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002593 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002594 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002595};
2596
2597struct ByteRangeLockPB2
2598{
2599 unsigned long long offset; /* offset to first byte to lock */
2600 unsigned long long length; /* nbr of bytes to lock */
2601 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2602 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2603 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2604 int fd; /* file desc to assoc this lock with */
2605};
2606
drhfd131da2007-08-07 17:13:03 +00002607#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002608
drh6b9d6dd2008-12-03 19:34:47 +00002609/*
2610** This is a utility for setting or clearing a bit-range lock on an
2611** AFP filesystem.
2612**
2613** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2614*/
2615static int afpSetLock(
2616 const char *path, /* Name of the file to be locked or unlocked */
2617 unixFile *pFile, /* Open file descriptor on path */
2618 unsigned long long offset, /* First byte to be locked */
2619 unsigned long long length, /* Number of bytes to lock */
2620 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002621){
drh6b9d6dd2008-12-03 19:34:47 +00002622 struct ByteRangeLockPB2 pb;
2623 int err;
drhbfe66312006-10-03 17:40:40 +00002624
2625 pb.unLockFlag = setLockFlag ? 0 : 1;
2626 pb.startEndFlag = 0;
2627 pb.offset = offset;
2628 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002629 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002630
drh308c2a52010-05-14 11:30:18 +00002631 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002632 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002633 offset, length));
drhbfe66312006-10-03 17:40:40 +00002634 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2635 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002636 int rc;
2637 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002638 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2639 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002640#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2641 rc = SQLITE_BUSY;
2642#else
drh734c9862008-11-28 15:37:20 +00002643 rc = sqliteErrorFromPosixError(tErrno,
2644 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002645#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002646 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002647 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00002648 }
2649 return rc;
drhbfe66312006-10-03 17:40:40 +00002650 } else {
aswift5b1a2562008-08-22 00:22:35 +00002651 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002652 }
2653}
2654
drh6b9d6dd2008-12-03 19:34:47 +00002655/*
2656** This routine checks if there is a RESERVED lock held on the specified
2657** file by this or any other process. If such a lock is held, set *pResOut
2658** to a non-zero value otherwise *pResOut is set to zero. The return value
2659** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2660*/
danielk1977e339d652008-06-28 11:23:00 +00002661static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002662 int rc = SQLITE_OK;
2663 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002664 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002665 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002666
aswift5b1a2562008-08-22 00:22:35 +00002667 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2668
2669 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002670 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002671 if( context->reserved ){
2672 *pResOut = 1;
2673 return SQLITE_OK;
2674 }
drh8af6c222010-05-14 12:43:01 +00002675 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002676
2677 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002678 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002679 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002680 }
2681
2682 /* Otherwise see if some other process holds it.
2683 */
aswift5b1a2562008-08-22 00:22:35 +00002684 if( !reserved ){
2685 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002686 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002687 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002688 /* if we succeeded in taking the reserved lock, unlock it to restore
2689 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002690 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002691 } else {
2692 /* if we failed to get the lock then someone else must have it */
2693 reserved = 1;
2694 }
2695 if( IS_LOCK_ERROR(lrc) ){
2696 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002697 }
2698 }
drhbfe66312006-10-03 17:40:40 +00002699
drh7ed97b92010-01-20 13:07:21 +00002700 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002701 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002702
2703 *pResOut = reserved;
2704 return rc;
drhbfe66312006-10-03 17:40:40 +00002705}
2706
drh6b9d6dd2008-12-03 19:34:47 +00002707/*
drh308c2a52010-05-14 11:30:18 +00002708** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002709** of the following:
2710**
2711** (1) SHARED_LOCK
2712** (2) RESERVED_LOCK
2713** (3) PENDING_LOCK
2714** (4) EXCLUSIVE_LOCK
2715**
2716** Sometimes when requesting one lock state, additional lock states
2717** are inserted in between. The locking might fail on one of the later
2718** transitions leaving the lock state different from what it started but
2719** still short of its goal. The following chart shows the allowed
2720** transitions and the inserted intermediate states:
2721**
2722** UNLOCKED -> SHARED
2723** SHARED -> RESERVED
2724** SHARED -> (PENDING) -> EXCLUSIVE
2725** RESERVED -> (PENDING) -> EXCLUSIVE
2726** PENDING -> EXCLUSIVE
2727**
2728** This routine will only increase a lock. Use the sqlite3OsUnlock()
2729** routine to lower a locking level.
2730*/
drh308c2a52010-05-14 11:30:18 +00002731static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002732 int rc = SQLITE_OK;
2733 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002734 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002735 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002736
2737 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002738 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2739 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh5ac93652015-03-21 20:59:43 +00002740 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
drh339eb0b2008-03-07 15:34:11 +00002741
drhbfe66312006-10-03 17:40:40 +00002742 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002743 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002744 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002745 */
drh308c2a52010-05-14 11:30:18 +00002746 if( pFile->eFileLock>=eFileLock ){
2747 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2748 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002749 return SQLITE_OK;
2750 }
2751
2752 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002753 ** (1) We never move from unlocked to anything higher than shared lock.
2754 ** (2) SQLite never explicitly requests a pendig lock.
2755 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002756 */
drh308c2a52010-05-14 11:30:18 +00002757 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2758 assert( eFileLock!=PENDING_LOCK );
2759 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002760
drh8af6c222010-05-14 12:43:01 +00002761 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002762 */
drh6c7d5c52008-11-21 20:32:33 +00002763 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002764 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002765
2766 /* If some thread using this PID has a lock via a different unixFile*
2767 ** handle that precludes the requested lock, return BUSY.
2768 */
drh8af6c222010-05-14 12:43:01 +00002769 if( (pFile->eFileLock!=pInode->eFileLock &&
2770 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002771 ){
2772 rc = SQLITE_BUSY;
2773 goto afp_end_lock;
2774 }
2775
2776 /* If a SHARED lock is requested, and some thread using this PID already
2777 ** has a SHARED or RESERVED lock, then increment reference counts and
2778 ** return SQLITE_OK.
2779 */
drh308c2a52010-05-14 11:30:18 +00002780 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002781 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002782 assert( eFileLock==SHARED_LOCK );
2783 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002784 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002785 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002786 pInode->nShared++;
2787 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002788 goto afp_end_lock;
2789 }
drhbfe66312006-10-03 17:40:40 +00002790
2791 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002792 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2793 ** be released.
2794 */
drh308c2a52010-05-14 11:30:18 +00002795 if( eFileLock==SHARED_LOCK
2796 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002797 ){
2798 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002799 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002800 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002801 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002802 goto afp_end_lock;
2803 }
2804 }
2805
2806 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002807 ** operating system calls for the specified lock.
2808 */
drh308c2a52010-05-14 11:30:18 +00002809 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002810 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002811 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002812
drh8af6c222010-05-14 12:43:01 +00002813 assert( pInode->nShared==0 );
2814 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002815
2816 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002817 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002818 /* note that the quality of the randomness doesn't matter that much */
2819 lk = random();
drh8af6c222010-05-14 12:43:01 +00002820 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002821 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002822 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002823 if( IS_LOCK_ERROR(lrc1) ){
2824 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002825 }
aswift5b1a2562008-08-22 00:22:35 +00002826 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002827 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002828
aswift5b1a2562008-08-22 00:22:35 +00002829 if( IS_LOCK_ERROR(lrc1) ) {
drh4bf66fd2015-02-19 02:43:02 +00002830 storeLastErrno(pFile, lrc1Errno);
aswift5b1a2562008-08-22 00:22:35 +00002831 rc = lrc1;
2832 goto afp_end_lock;
2833 } else if( IS_LOCK_ERROR(lrc2) ){
2834 rc = lrc2;
2835 goto afp_end_lock;
2836 } else if( lrc1 != SQLITE_OK ) {
2837 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002838 } else {
drh308c2a52010-05-14 11:30:18 +00002839 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002840 pInode->nLock++;
2841 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002842 }
drh8af6c222010-05-14 12:43:01 +00002843 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002844 /* We are trying for an exclusive lock but another thread in this
2845 ** same process is still holding a shared lock. */
2846 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002847 }else{
2848 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2849 ** assumed that there is a SHARED or greater lock on the file
2850 ** already.
2851 */
2852 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002853 assert( 0!=pFile->eFileLock );
2854 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002855 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002856 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002857 if( !failed ){
2858 context->reserved = 1;
2859 }
drhbfe66312006-10-03 17:40:40 +00002860 }
drh308c2a52010-05-14 11:30:18 +00002861 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002862 /* Acquire an EXCLUSIVE lock */
2863
2864 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002865 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002866 */
drh6b9d6dd2008-12-03 19:34:47 +00002867 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002868 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002869 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002870 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002871 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002872 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002873 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002874 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002875 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2876 ** a critical I/O error
2877 */
2878 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2879 SQLITE_IOERR_LOCK;
2880 goto afp_end_lock;
2881 }
2882 }else{
aswift5b1a2562008-08-22 00:22:35 +00002883 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002884 }
2885 }
aswift5b1a2562008-08-22 00:22:35 +00002886 if( failed ){
2887 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002888 }
2889 }
2890
2891 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002892 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002893 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002894 }else if( eFileLock==EXCLUSIVE_LOCK ){
2895 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002896 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002897 }
2898
2899afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002900 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002901 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2902 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002903 return rc;
2904}
2905
2906/*
drh308c2a52010-05-14 11:30:18 +00002907** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002908** must be either NO_LOCK or SHARED_LOCK.
2909**
2910** If the locking level of the file descriptor is already at or below
2911** the requested locking level, this routine is a no-op.
2912*/
drh308c2a52010-05-14 11:30:18 +00002913static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002914 int rc = SQLITE_OK;
2915 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002916 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002917 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2918 int skipShared = 0;
2919#ifdef SQLITE_TEST
2920 int h = pFile->h;
2921#endif
drhbfe66312006-10-03 17:40:40 +00002922
2923 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002924 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002925 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00002926 osGetpid(0)));
aswift5b1a2562008-08-22 00:22:35 +00002927
drh308c2a52010-05-14 11:30:18 +00002928 assert( eFileLock<=SHARED_LOCK );
2929 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002930 return SQLITE_OK;
2931 }
drh6c7d5c52008-11-21 20:32:33 +00002932 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002933 pInode = pFile->pInode;
2934 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002935 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002936 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002937 SimulateIOErrorBenign(1);
2938 SimulateIOError( h=(-1) )
2939 SimulateIOErrorBenign(0);
2940
drhd3d8c042012-05-29 17:02:40 +00002941#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002942 /* When reducing a lock such that other processes can start
2943 ** reading the database file again, make sure that the
2944 ** transaction counter was updated if any part of the database
2945 ** file changed. If the transaction counter is not updated,
2946 ** other connections to the same file might not realize that
2947 ** the file has changed and hence might not know to flush their
2948 ** cache. The use of a stale cache can lead to database corruption.
2949 */
2950 assert( pFile->inNormalWrite==0
2951 || pFile->dbUpdate==0
2952 || pFile->transCntrChng==1 );
2953 pFile->inNormalWrite = 0;
2954#endif
aswiftaebf4132008-11-21 00:10:35 +00002955
drh308c2a52010-05-14 11:30:18 +00002956 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002957 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002958 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002959 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002960 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002961 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2962 } else {
2963 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002964 }
2965 }
drh308c2a52010-05-14 11:30:18 +00002966 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002967 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002968 }
drh308c2a52010-05-14 11:30:18 +00002969 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002970 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2971 if( !rc ){
2972 context->reserved = 0;
2973 }
aswiftaebf4132008-11-21 00:10:35 +00002974 }
drh8af6c222010-05-14 12:43:01 +00002975 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2976 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002977 }
aswiftaebf4132008-11-21 00:10:35 +00002978 }
drh308c2a52010-05-14 11:30:18 +00002979 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002980
drh7ed97b92010-01-20 13:07:21 +00002981 /* Decrement the shared lock counter. Release the lock using an
2982 ** OS call only when all threads in this same process have released
2983 ** the lock.
2984 */
drh8af6c222010-05-14 12:43:01 +00002985 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2986 pInode->nShared--;
2987 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002988 SimulateIOErrorBenign(1);
2989 SimulateIOError( h=(-1) )
2990 SimulateIOErrorBenign(0);
2991 if( !skipShared ){
2992 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2993 }
2994 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002995 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002996 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002997 }
2998 }
2999 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00003000 pInode->nLock--;
3001 assert( pInode->nLock>=0 );
3002 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00003003 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00003004 }
3005 }
drhbfe66312006-10-03 17:40:40 +00003006 }
drh7ed97b92010-01-20 13:07:21 +00003007
drh6c7d5c52008-11-21 20:32:33 +00003008 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00003009 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00003010 return rc;
3011}
3012
3013/*
drh339eb0b2008-03-07 15:34:11 +00003014** Close a file & cleanup AFP specific locking context
3015*/
danielk1977e339d652008-06-28 11:23:00 +00003016static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003017 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00003018 if( id ){
3019 unixFile *pFile = (unixFile*)id;
3020 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00003021 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00003022 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00003023 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00003024 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00003025 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00003026 ** the last lock is cleared.
3027 */
dan08da86a2009-08-21 17:18:03 +00003028 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00003029 }
danb0ac3e32010-06-16 10:55:42 +00003030 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003031 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00003032 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00003033 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00003034 }
drh7ed97b92010-01-20 13:07:21 +00003035 return rc;
drhbfe66312006-10-03 17:40:40 +00003036}
3037
drhd2cb50b2009-01-09 21:41:17 +00003038#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003039/*
3040** The code above is the AFP lock implementation. The code is specific
3041** to MacOSX and does not work on other unix platforms. No alternative
3042** is available. If you don't compile for a mac, then the "unix-afp"
3043** VFS is not available.
3044**
3045********************* End of the AFP lock implementation **********************
3046******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003047
drh7ed97b92010-01-20 13:07:21 +00003048/******************************************************************************
3049*************************** Begin NFS Locking ********************************/
3050
3051#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3052/*
drh308c2a52010-05-14 11:30:18 +00003053 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003054 ** must be either NO_LOCK or SHARED_LOCK.
3055 **
3056 ** If the locking level of the file descriptor is already at or below
3057 ** the requested locking level, this routine is a no-op.
3058 */
drh308c2a52010-05-14 11:30:18 +00003059static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003060 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003061}
3062
3063#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3064/*
3065** The code above is the NFS lock implementation. The code is specific
3066** to MacOSX and does not work on other unix platforms. No alternative
3067** is available.
3068**
3069********************* End of the NFS lock implementation **********************
3070******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003071
3072/******************************************************************************
3073**************** Non-locking sqlite3_file methods *****************************
3074**
3075** The next division contains implementations for all methods of the
3076** sqlite3_file object other than the locking methods. The locking
3077** methods were defined in divisions above (one locking method per
3078** division). Those methods that are common to all locking modes
3079** are gather together into this division.
3080*/
drhbfe66312006-10-03 17:40:40 +00003081
3082/*
drh734c9862008-11-28 15:37:20 +00003083** Seek to the offset passed as the second argument, then read cnt
3084** bytes into pBuf. Return the number of bytes actually read.
3085**
3086** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3087** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3088** one system to another. Since SQLite does not define USE_PREAD
peter.d.reid60ec9142014-09-06 16:39:46 +00003089** in any form by default, we will not attempt to define _XOPEN_SOURCE.
drh734c9862008-11-28 15:37:20 +00003090** See tickets #2741 and #2681.
3091**
3092** To avoid stomping the errno value on a failed read the lastErrno value
3093** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003094*/
drh734c9862008-11-28 15:37:20 +00003095static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3096 int got;
drh58024642011-11-07 18:16:00 +00003097 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003098#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003099 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003100#endif
drh734c9862008-11-28 15:37:20 +00003101 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003102 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003103 assert( id->h>2 );
drh58024642011-11-07 18:16:00 +00003104 do{
drh734c9862008-11-28 15:37:20 +00003105#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003106 got = osPread(id->h, pBuf, cnt, offset);
3107 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003108#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003109 got = osPread64(id->h, pBuf, cnt, offset);
3110 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003111#else
drh58024642011-11-07 18:16:00 +00003112 newOffset = lseek(id->h, offset, SEEK_SET);
3113 SimulateIOError( newOffset-- );
3114 if( newOffset!=offset ){
3115 if( newOffset == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00003116 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003117 }else{
drh4bf66fd2015-02-19 02:43:02 +00003118 storeLastErrno((unixFile*)id, 0);
drh58024642011-11-07 18:16:00 +00003119 }
3120 return -1;
drh734c9862008-11-28 15:37:20 +00003121 }
drh58024642011-11-07 18:16:00 +00003122 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003123#endif
drh58024642011-11-07 18:16:00 +00003124 if( got==cnt ) break;
3125 if( got<0 ){
3126 if( errno==EINTR ){ got = 1; continue; }
3127 prior = 0;
drh4bf66fd2015-02-19 02:43:02 +00003128 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003129 break;
3130 }else if( got>0 ){
3131 cnt -= got;
3132 offset += got;
3133 prior += got;
3134 pBuf = (void*)(got + (char*)pBuf);
3135 }
3136 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003137 TIMER_END;
drh58024642011-11-07 18:16:00 +00003138 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3139 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3140 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003141}
3142
3143/*
drh734c9862008-11-28 15:37:20 +00003144** Read data from a file into a buffer. Return SQLITE_OK if all
3145** bytes were read successfully and SQLITE_IOERR if anything goes
3146** wrong.
drh339eb0b2008-03-07 15:34:11 +00003147*/
drh734c9862008-11-28 15:37:20 +00003148static int unixRead(
3149 sqlite3_file *id,
3150 void *pBuf,
3151 int amt,
3152 sqlite3_int64 offset
3153){
dan08da86a2009-08-21 17:18:03 +00003154 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003155 int got;
3156 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003157 assert( offset>=0 );
3158 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003159
dan08da86a2009-08-21 17:18:03 +00003160 /* If this is a database file (not a journal, master-journal or temp
3161 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003162#if 0
dane946c392009-08-22 11:39:46 +00003163 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003164 || offset>=PENDING_BYTE+512
3165 || offset+amt<=PENDING_BYTE
3166 );
dan7c246102010-04-12 19:00:29 +00003167#endif
drh08c6d442009-02-09 17:34:07 +00003168
drh9b4c59f2013-04-15 17:03:42 +00003169#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003170 /* Deal with as much of this read request as possible by transfering
3171 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003172 if( offset<pFile->mmapSize ){
3173 if( offset+amt <= pFile->mmapSize ){
3174 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3175 return SQLITE_OK;
3176 }else{
3177 int nCopy = pFile->mmapSize - offset;
3178 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3179 pBuf = &((u8 *)pBuf)[nCopy];
3180 amt -= nCopy;
3181 offset += nCopy;
3182 }
3183 }
drh6e0b6d52013-04-09 16:19:20 +00003184#endif
danf23da962013-03-23 21:00:41 +00003185
dan08da86a2009-08-21 17:18:03 +00003186 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003187 if( got==amt ){
3188 return SQLITE_OK;
3189 }else if( got<0 ){
3190 /* lastErrno set by seekAndRead */
3191 return SQLITE_IOERR_READ;
3192 }else{
drh4bf66fd2015-02-19 02:43:02 +00003193 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003194 /* Unread parts of the buffer must be zero-filled */
3195 memset(&((char*)pBuf)[got], 0, amt-got);
3196 return SQLITE_IOERR_SHORT_READ;
3197 }
3198}
3199
3200/*
dan47a2b4a2013-04-26 16:09:29 +00003201** Attempt to seek the file-descriptor passed as the first argument to
3202** absolute offset iOff, then attempt to write nBuf bytes of data from
3203** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3204** return the actual number of bytes written (which may be less than
3205** nBuf).
3206*/
3207static int seekAndWriteFd(
3208 int fd, /* File descriptor to write to */
3209 i64 iOff, /* File offset to begin writing at */
3210 const void *pBuf, /* Copy data from this buffer to the file */
3211 int nBuf, /* Size of buffer pBuf in bytes */
3212 int *piErrno /* OUT: Error number if error occurs */
3213){
3214 int rc = 0; /* Value returned by system call */
3215
3216 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003217 assert( fd>2 );
dan47a2b4a2013-04-26 16:09:29 +00003218 nBuf &= 0x1ffff;
3219 TIMER_START;
3220
3221#if defined(USE_PREAD)
drh2da47d32015-02-21 00:56:05 +00003222 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
dan47a2b4a2013-04-26 16:09:29 +00003223#elif defined(USE_PREAD64)
drh2da47d32015-02-21 00:56:05 +00003224 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
dan47a2b4a2013-04-26 16:09:29 +00003225#else
3226 do{
3227 i64 iSeek = lseek(fd, iOff, SEEK_SET);
3228 SimulateIOError( iSeek-- );
3229
3230 if( iSeek!=iOff ){
3231 if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
3232 return -1;
3233 }
3234 rc = osWrite(fd, pBuf, nBuf);
3235 }while( rc<0 && errno==EINTR );
3236#endif
3237
3238 TIMER_END;
3239 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3240
3241 if( rc<0 && piErrno ) *piErrno = errno;
3242 return rc;
3243}
3244
3245
3246/*
drh734c9862008-11-28 15:37:20 +00003247** Seek to the offset in id->offset then read cnt bytes into pBuf.
3248** Return the number of bytes actually read. Update the offset.
3249**
3250** To avoid stomping the errno value on a failed write the lastErrno value
3251** is set before returning.
3252*/
3253static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003254 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003255}
3256
3257
3258/*
3259** Write data from a buffer into a file. Return SQLITE_OK on success
3260** or some other error code on failure.
3261*/
3262static int unixWrite(
3263 sqlite3_file *id,
3264 const void *pBuf,
3265 int amt,
3266 sqlite3_int64 offset
3267){
dan08da86a2009-08-21 17:18:03 +00003268 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003269 int wrote = 0;
3270 assert( id );
3271 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003272
dan08da86a2009-08-21 17:18:03 +00003273 /* If this is a database file (not a journal, master-journal or temp
3274 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003275#if 0
dane946c392009-08-22 11:39:46 +00003276 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003277 || offset>=PENDING_BYTE+512
3278 || offset+amt<=PENDING_BYTE
3279 );
dan7c246102010-04-12 19:00:29 +00003280#endif
drh08c6d442009-02-09 17:34:07 +00003281
drhd3d8c042012-05-29 17:02:40 +00003282#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003283 /* If we are doing a normal write to a database file (as opposed to
3284 ** doing a hot-journal rollback or a write to some file other than a
3285 ** normal database file) then record the fact that the database
3286 ** has changed. If the transaction counter is modified, record that
3287 ** fact too.
3288 */
dan08da86a2009-08-21 17:18:03 +00003289 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003290 pFile->dbUpdate = 1; /* The database has been modified */
3291 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003292 int rc;
drh8f941bc2009-01-14 23:03:40 +00003293 char oldCntr[4];
3294 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003295 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003296 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003297 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003298 pFile->transCntrChng = 1; /* The transaction counter has changed */
3299 }
3300 }
3301 }
3302#endif
3303
danfe33e392015-11-17 20:56:06 +00003304#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003305 /* Deal with as much of this write request as possible by transfering
3306 ** data from the memory mapping using memcpy(). */
3307 if( offset<pFile->mmapSize ){
3308 if( offset+amt <= pFile->mmapSize ){
3309 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3310 return SQLITE_OK;
3311 }else{
3312 int nCopy = pFile->mmapSize - offset;
3313 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3314 pBuf = &((u8 *)pBuf)[nCopy];
3315 amt -= nCopy;
3316 offset += nCopy;
3317 }
3318 }
drh6e0b6d52013-04-09 16:19:20 +00003319#endif
drh02bf8b42015-09-01 23:51:53 +00003320
3321 while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
drh734c9862008-11-28 15:37:20 +00003322 amt -= wrote;
3323 offset += wrote;
3324 pBuf = &((char*)pBuf)[wrote];
3325 }
3326 SimulateIOError(( wrote=(-1), amt=1 ));
3327 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003328
drh02bf8b42015-09-01 23:51:53 +00003329 if( amt>wrote ){
drha21b83b2011-04-15 12:36:10 +00003330 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003331 /* lastErrno set by seekAndWrite */
3332 return SQLITE_IOERR_WRITE;
3333 }else{
drh4bf66fd2015-02-19 02:43:02 +00003334 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003335 return SQLITE_FULL;
3336 }
3337 }
dan6e09d692010-07-27 18:34:15 +00003338
drh734c9862008-11-28 15:37:20 +00003339 return SQLITE_OK;
3340}
3341
3342#ifdef SQLITE_TEST
3343/*
3344** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003345** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003346*/
3347int sqlite3_sync_count = 0;
3348int sqlite3_fullsync_count = 0;
3349#endif
3350
3351/*
drh89240432009-03-25 01:06:01 +00003352** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003353** Others do no. To be safe, we will stick with the (slightly slower)
3354** fsync(). If you know that your system does support fdatasync() correctly,
drhf7a4a1b2015-01-10 18:02:45 +00003355** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003356*/
drhf7a4a1b2015-01-10 18:02:45 +00003357#if !defined(fdatasync) && !HAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003358# define fdatasync fsync
3359#endif
3360
3361/*
3362** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3363** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3364** only available on Mac OS X. But that could change.
3365*/
3366#ifdef F_FULLFSYNC
3367# define HAVE_FULLFSYNC 1
3368#else
3369# define HAVE_FULLFSYNC 0
3370#endif
3371
3372
3373/*
3374** The fsync() system call does not work as advertised on many
3375** unix systems. The following procedure is an attempt to make
3376** it work better.
3377**
3378** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3379** for testing when we want to run through the test suite quickly.
3380** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3381** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3382** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003383**
3384** SQLite sets the dataOnly flag if the size of the file is unchanged.
3385** The idea behind dataOnly is that it should only write the file content
3386** to disk, not the inode. We only set dataOnly if the file size is
3387** unchanged since the file size is part of the inode. However,
3388** Ted Ts'o tells us that fdatasync() will also write the inode if the
3389** file size has changed. The only real difference between fdatasync()
3390** and fsync(), Ted tells us, is that fdatasync() will not flush the
3391** inode if the mtime or owner or other inode attributes have changed.
3392** We only care about the file size, not the other file attributes, so
3393** as far as SQLite is concerned, an fdatasync() is always adequate.
3394** So, we always use fdatasync() if it is available, regardless of
3395** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003396*/
3397static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003398 int rc;
drh734c9862008-11-28 15:37:20 +00003399
3400 /* The following "ifdef/elif/else/" block has the same structure as
3401 ** the one below. It is replicated here solely to avoid cluttering
3402 ** up the real code with the UNUSED_PARAMETER() macros.
3403 */
3404#ifdef SQLITE_NO_SYNC
3405 UNUSED_PARAMETER(fd);
3406 UNUSED_PARAMETER(fullSync);
3407 UNUSED_PARAMETER(dataOnly);
3408#elif HAVE_FULLFSYNC
3409 UNUSED_PARAMETER(dataOnly);
3410#else
3411 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003412 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003413#endif
3414
3415 /* Record the number of times that we do a normal fsync() and
3416 ** FULLSYNC. This is used during testing to verify that this procedure
3417 ** gets called with the correct arguments.
3418 */
3419#ifdef SQLITE_TEST
3420 if( fullSync ) sqlite3_fullsync_count++;
3421 sqlite3_sync_count++;
3422#endif
3423
3424 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3425 ** no-op
3426 */
3427#ifdef SQLITE_NO_SYNC
3428 rc = SQLITE_OK;
3429#elif HAVE_FULLFSYNC
3430 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003431 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003432 }else{
3433 rc = 1;
3434 }
3435 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003436 ** It shouldn't be possible for fullfsync to fail on the local
3437 ** file system (on OSX), so failure indicates that FULLFSYNC
3438 ** isn't supported for this file system. So, attempt an fsync
3439 ** and (for now) ignore the overhead of a superfluous fcntl call.
3440 ** It'd be better to detect fullfsync support once and avoid
3441 ** the fcntl call every time sync is called.
3442 */
drh734c9862008-11-28 15:37:20 +00003443 if( rc ) rc = fsync(fd);
3444
drh7ed97b92010-01-20 13:07:21 +00003445#elif defined(__APPLE__)
3446 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3447 ** so currently we default to the macro that redefines fdatasync to fsync
3448 */
3449 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003450#else
drh0b647ff2009-03-21 14:41:04 +00003451 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003452#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003453 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003454 rc = fsync(fd);
3455 }
drh0b647ff2009-03-21 14:41:04 +00003456#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003457#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3458
3459 if( OS_VXWORKS && rc!= -1 ){
3460 rc = 0;
3461 }
chw97185482008-11-17 08:05:31 +00003462 return rc;
drhbfe66312006-10-03 17:40:40 +00003463}
3464
drh734c9862008-11-28 15:37:20 +00003465/*
drh0059eae2011-08-08 23:48:40 +00003466** Open a file descriptor to the directory containing file zFilename.
3467** If successful, *pFd is set to the opened file descriptor and
3468** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3469** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3470** value.
3471**
drh90315a22011-08-10 01:52:12 +00003472** The directory file descriptor is used for only one thing - to
3473** fsync() a directory to make sure file creation and deletion events
3474** are flushed to disk. Such fsyncs are not needed on newer
3475** journaling filesystems, but are required on older filesystems.
3476**
3477** This routine can be overridden using the xSetSysCall interface.
3478** The ability to override this routine was added in support of the
3479** chromium sandbox. Opening a directory is a security risk (we are
3480** told) so making it overrideable allows the chromium sandbox to
3481** replace this routine with a harmless no-op. To make this routine
3482** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3483** *pFd set to a negative number.
3484**
drh0059eae2011-08-08 23:48:40 +00003485** If SQLITE_OK is returned, the caller is responsible for closing
3486** the file descriptor *pFd using close().
3487*/
3488static int openDirectory(const char *zFilename, int *pFd){
3489 int ii;
3490 int fd = -1;
3491 char zDirname[MAX_PATHNAME+1];
3492
3493 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3494 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3495 if( ii>0 ){
3496 zDirname[ii] = '\0';
3497 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3498 if( fd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003499 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3500 }
3501 }
3502 *pFd = fd;
drhacb6b282015-11-26 10:37:05 +00003503 if( fd>=0 ) return SQLITE_OK;
3504 return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
drh0059eae2011-08-08 23:48:40 +00003505}
3506
3507/*
drh734c9862008-11-28 15:37:20 +00003508** Make sure all writes to a particular file are committed to disk.
3509**
3510** If dataOnly==0 then both the file itself and its metadata (file
3511** size, access time, etc) are synced. If dataOnly!=0 then only the
3512** file data is synced.
3513**
3514** Under Unix, also make sure that the directory entry for the file
3515** has been created by fsync-ing the directory that contains the file.
3516** If we do not do this and we encounter a power failure, the directory
3517** entry for the journal might not exist after we reboot. The next
3518** SQLite to access the file will not know that the journal exists (because
3519** the directory entry for the journal was never created) and the transaction
3520** will not roll back - possibly leading to database corruption.
3521*/
3522static int unixSync(sqlite3_file *id, int flags){
3523 int rc;
3524 unixFile *pFile = (unixFile*)id;
3525
3526 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3527 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3528
3529 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3530 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3531 || (flags&0x0F)==SQLITE_SYNC_FULL
3532 );
3533
3534 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3535 ** line is to test that doing so does not cause any problems.
3536 */
3537 SimulateDiskfullError( return SQLITE_FULL );
3538
3539 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003540 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003541 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3542 SimulateIOError( rc=1 );
3543 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003544 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003545 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003546 }
drh0059eae2011-08-08 23:48:40 +00003547
3548 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003549 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003550 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003551 */
3552 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3553 int dirfd;
3554 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003555 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003556 rc = osOpenDirectory(pFile->zPath, &dirfd);
drhacb6b282015-11-26 10:37:05 +00003557 if( rc==SQLITE_OK ){
drh0059eae2011-08-08 23:48:40 +00003558 full_fsync(dirfd, 0, 0);
3559 robust_close(pFile, dirfd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00003560 }else{
3561 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00003562 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003563 }
drh0059eae2011-08-08 23:48:40 +00003564 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003565 }
3566 return rc;
3567}
3568
3569/*
3570** Truncate an open file to a specified size
3571*/
3572static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003573 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003574 int rc;
dan6e09d692010-07-27 18:34:15 +00003575 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003576 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003577
3578 /* If the user has configured a chunk-size for this file, truncate the
3579 ** file so that it consists of an integer number of chunks (i.e. the
3580 ** actual file size after the operation may be larger than the requested
3581 ** size).
3582 */
drhb8af4b72012-04-05 20:04:39 +00003583 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003584 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3585 }
3586
dan2ee53412014-09-06 16:49:40 +00003587 rc = robust_ftruncate(pFile->h, nByte);
drh734c9862008-11-28 15:37:20 +00003588 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003589 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003590 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003591 }else{
drhd3d8c042012-05-29 17:02:40 +00003592#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003593 /* If we are doing a normal write to a database file (as opposed to
3594 ** doing a hot-journal rollback or a write to some file other than a
3595 ** normal database file) and we truncate the file to zero length,
3596 ** that effectively updates the change counter. This might happen
3597 ** when restoring a database using the backup API from a zero-length
3598 ** source.
3599 */
dan6e09d692010-07-27 18:34:15 +00003600 if( pFile->inNormalWrite && nByte==0 ){
3601 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003602 }
danf23da962013-03-23 21:00:41 +00003603#endif
danc0003312013-03-22 17:46:11 +00003604
mistachkine98844f2013-08-24 00:59:24 +00003605#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003606 /* If the file was just truncated to a size smaller than the currently
3607 ** mapped region, reduce the effective mapping size as well. SQLite will
3608 ** use read() and write() to access data beyond this point from now on.
3609 */
3610 if( nByte<pFile->mmapSize ){
3611 pFile->mmapSize = nByte;
3612 }
mistachkine98844f2013-08-24 00:59:24 +00003613#endif
drh3313b142009-11-06 04:13:18 +00003614
drh734c9862008-11-28 15:37:20 +00003615 return SQLITE_OK;
3616 }
3617}
3618
3619/*
3620** Determine the current size of a file in bytes
3621*/
3622static int unixFileSize(sqlite3_file *id, i64 *pSize){
3623 int rc;
3624 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003625 assert( id );
3626 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003627 SimulateIOError( rc=1 );
3628 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00003629 storeLastErrno((unixFile*)id, errno);
drh734c9862008-11-28 15:37:20 +00003630 return SQLITE_IOERR_FSTAT;
3631 }
3632 *pSize = buf.st_size;
3633
drh8af6c222010-05-14 12:43:01 +00003634 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003635 ** writes a single byte into that file in order to work around a bug
3636 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3637 ** layers, we need to report this file size as zero even though it is
3638 ** really 1. Ticket #3260.
3639 */
3640 if( *pSize==1 ) *pSize = 0;
3641
3642
3643 return SQLITE_OK;
3644}
3645
drhd2cb50b2009-01-09 21:41:17 +00003646#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003647/*
3648** Handler for proxy-locking file-control verbs. Defined below in the
3649** proxying locking division.
3650*/
3651static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003652#endif
drh715ff302008-12-03 22:32:44 +00003653
dan502019c2010-07-28 14:26:17 +00003654/*
3655** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003656** file-control operation. Enlarge the database to nBytes in size
3657** (rounded up to the next chunk-size). If the database is already
3658** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003659*/
3660static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003661 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003662 i64 nSize; /* Required file size */
3663 struct stat buf; /* Used to hold return values of fstat() */
3664
drh4bf66fd2015-02-19 02:43:02 +00003665 if( osFstat(pFile->h, &buf) ){
3666 return SQLITE_IOERR_FSTAT;
3667 }
dan502019c2010-07-28 14:26:17 +00003668
3669 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3670 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003671
dan502019c2010-07-28 14:26:17 +00003672#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003673 /* The code below is handling the return value of osFallocate()
3674 ** correctly. posix_fallocate() is defined to "returns zero on success,
3675 ** or an error number on failure". See the manpage for details. */
3676 int err;
drhff812312011-02-23 13:33:46 +00003677 do{
dan661d71a2011-03-30 19:08:03 +00003678 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3679 }while( err==EINTR );
3680 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003681#else
dan592bf7f2014-12-30 19:58:31 +00003682 /* If the OS does not have posix_fallocate(), fake it. Write a
3683 ** single byte to the last byte in each block that falls entirely
3684 ** within the extended region. Then, if required, a single byte
3685 ** at offset (nSize-1), to set the size of the file correctly.
3686 ** This is a similar technique to that used by glibc on systems
3687 ** that do not have a real fallocate() call.
dan502019c2010-07-28 14:26:17 +00003688 */
3689 int nBlk = buf.st_blksize; /* File-system block size */
danef3d66c2015-01-06 21:31:47 +00003690 int nWrite = 0; /* Number of bytes written by seekAndWrite */
dan502019c2010-07-28 14:26:17 +00003691 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003692
dan502019c2010-07-28 14:26:17 +00003693 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dan592bf7f2014-12-30 19:58:31 +00003694 assert( iWrite>=buf.st_size );
3695 assert( (iWrite/nBlk)==((buf.st_size+nBlk-1)/nBlk) );
3696 assert( ((iWrite+1)%nBlk)==0 );
3697 for(/*no-op*/; iWrite<nSize; iWrite+=nBlk ){
danef3d66c2015-01-06 21:31:47 +00003698 nWrite = seekAndWrite(pFile, iWrite, "", 1);
dandc5df0f2011-04-06 19:15:45 +00003699 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dandc5df0f2011-04-06 19:15:45 +00003700 }
danef3d66c2015-01-06 21:31:47 +00003701 if( nWrite==0 || (nSize%nBlk) ){
3702 nWrite = seekAndWrite(pFile, nSize-1, "", 1);
dan592bf7f2014-12-30 19:58:31 +00003703 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dand348c662014-12-30 14:40:53 +00003704 }
dan502019c2010-07-28 14:26:17 +00003705#endif
3706 }
3707 }
3708
mistachkine98844f2013-08-24 00:59:24 +00003709#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003710 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003711 int rc;
3712 if( pFile->szChunk<=0 ){
3713 if( robust_ftruncate(pFile->h, nByte) ){
drh4bf66fd2015-02-19 02:43:02 +00003714 storeLastErrno(pFile, errno);
danf23da962013-03-23 21:00:41 +00003715 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3716 }
3717 }
3718
3719 rc = unixMapfile(pFile, nByte);
3720 return rc;
3721 }
mistachkine98844f2013-08-24 00:59:24 +00003722#endif
danf23da962013-03-23 21:00:41 +00003723
dan502019c2010-07-28 14:26:17 +00003724 return SQLITE_OK;
3725}
danielk1977ad94b582007-08-20 06:44:22 +00003726
danielk1977e3026632004-06-22 11:29:02 +00003727/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003728** If *pArg is initially negative then this is a query. Set *pArg to
drhf12b3f62011-12-21 14:42:29 +00003729** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3730**
3731** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3732*/
3733static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3734 if( *pArg<0 ){
3735 *pArg = (pFile->ctrlFlags & mask)!=0;
3736 }else if( (*pArg)==0 ){
3737 pFile->ctrlFlags &= ~mask;
3738 }else{
3739 pFile->ctrlFlags |= mask;
3740 }
3741}
3742
drh696b33e2012-12-06 19:01:42 +00003743/* Forward declaration */
3744static int unixGetTempname(int nBuf, char *zBuf);
3745
drhf12b3f62011-12-21 14:42:29 +00003746/*
drh9e33c2c2007-08-31 18:34:59 +00003747** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003748*/
drhcc6bb3e2007-08-31 16:11:35 +00003749static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003750 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003751 switch( op ){
drhc435cf72015-03-21 16:36:03 +00003752 case SQLITE_FCNTL_WAL_BLOCK: {
drh62ca61e2015-04-03 20:33:33 +00003753 /* pFile->ctrlFlags |= UNIXFILE_BLOCK; // Deferred feature */
drhc435cf72015-03-21 16:36:03 +00003754 return SQLITE_OK;
3755 }
drh9e33c2c2007-08-31 18:34:59 +00003756 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003757 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003758 return SQLITE_OK;
3759 }
drh4bf66fd2015-02-19 02:43:02 +00003760 case SQLITE_FCNTL_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003761 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003762 return SQLITE_OK;
3763 }
dan6e09d692010-07-27 18:34:15 +00003764 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003765 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003766 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003767 }
drh9ff27ec2010-05-19 19:26:05 +00003768 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003769 int rc;
3770 SimulateIOErrorBenign(1);
3771 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3772 SimulateIOErrorBenign(0);
3773 return rc;
drhf0b190d2011-07-26 16:03:07 +00003774 }
3775 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003776 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3777 return SQLITE_OK;
3778 }
drhcb15f352011-12-23 01:04:17 +00003779 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3780 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003781 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003782 }
drhde60fc22011-12-14 17:53:36 +00003783 case SQLITE_FCNTL_VFSNAME: {
3784 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3785 return SQLITE_OK;
3786 }
drh696b33e2012-12-06 19:01:42 +00003787 case SQLITE_FCNTL_TEMPFILENAME: {
drhf3cdcdc2015-04-29 16:50:28 +00003788 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
drh696b33e2012-12-06 19:01:42 +00003789 if( zTFile ){
3790 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3791 *(char**)pArg = zTFile;
3792 }
3793 return SQLITE_OK;
3794 }
drhb959a012013-12-07 12:29:22 +00003795 case SQLITE_FCNTL_HAS_MOVED: {
3796 *(int*)pArg = fileHasMoved(pFile);
3797 return SQLITE_OK;
3798 }
mistachkine98844f2013-08-24 00:59:24 +00003799#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003800 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003801 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003802 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003803 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3804 newLimit = sqlite3GlobalConfig.mxMmap;
3805 }
3806 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003807 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003808 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003809 if( pFile->mmapSize>0 ){
3810 unixUnmapfile(pFile);
3811 rc = unixMapfile(pFile, -1);
3812 }
danbcb8a862013-04-08 15:30:41 +00003813 }
drh34e258c2013-05-23 01:40:53 +00003814 return rc;
danb2d3de32013-03-14 18:34:37 +00003815 }
mistachkine98844f2013-08-24 00:59:24 +00003816#endif
drhd3d8c042012-05-29 17:02:40 +00003817#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003818 /* The pager calls this method to signal that it has done
3819 ** a rollback and that the database is therefore unchanged and
3820 ** it hence it is OK for the transaction change counter to be
3821 ** unchanged.
3822 */
3823 case SQLITE_FCNTL_DB_UNCHANGED: {
3824 ((unixFile*)id)->dbUpdate = 0;
3825 return SQLITE_OK;
3826 }
3827#endif
drhd2cb50b2009-01-09 21:41:17 +00003828#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh4bf66fd2015-02-19 02:43:02 +00003829 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
3830 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003831 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003832 }
drhd2cb50b2009-01-09 21:41:17 +00003833#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003834 }
drh0b52b7d2011-01-26 19:46:22 +00003835 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003836}
3837
3838/*
danielk1977a3d4c882007-03-23 10:08:38 +00003839** Return the sector size in bytes of the underlying block device for
3840** the specified file. This is almost always 512 bytes, but may be
3841** larger for some devices.
3842**
3843** SQLite code assumes this function cannot fail. It also assumes that
3844** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003845** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003846** same for both.
3847*/
drh537dddf2012-10-26 13:46:24 +00003848#ifndef __QNXNTO__
3849static int unixSectorSize(sqlite3_file *NotUsed){
3850 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003851 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003852}
drh537dddf2012-10-26 13:46:24 +00003853#endif
3854
3855/*
3856** The following version of unixSectorSize() is optimized for QNX.
3857*/
3858#ifdef __QNXNTO__
3859#include <sys/dcmd_blk.h>
3860#include <sys/statvfs.h>
3861static int unixSectorSize(sqlite3_file *id){
3862 unixFile *pFile = (unixFile*)id;
3863 if( pFile->sectorSize == 0 ){
3864 struct statvfs fsInfo;
3865
3866 /* Set defaults for non-supported filesystems */
3867 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3868 pFile->deviceCharacteristics = 0;
3869 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3870 return pFile->sectorSize;
3871 }
3872
3873 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3874 pFile->sectorSize = fsInfo.f_bsize;
3875 pFile->deviceCharacteristics =
3876 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3877 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3878 ** the write succeeds */
3879 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3880 ** so it is ordered */
3881 0;
3882 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3883 pFile->sectorSize = fsInfo.f_bsize;
3884 pFile->deviceCharacteristics =
3885 /* etfs cluster size writes are atomic */
3886 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3887 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3888 ** the write succeeds */
3889 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3890 ** so it is ordered */
3891 0;
3892 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3893 pFile->sectorSize = fsInfo.f_bsize;
3894 pFile->deviceCharacteristics =
3895 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3896 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3897 ** the write succeeds */
3898 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3899 ** so it is ordered */
3900 0;
3901 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3902 pFile->sectorSize = fsInfo.f_bsize;
3903 pFile->deviceCharacteristics =
3904 /* full bitset of atomics from max sector size and smaller */
3905 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3906 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3907 ** so it is ordered */
3908 0;
3909 }else if( strstr(fsInfo.f_basetype, "dos") ){
3910 pFile->sectorSize = fsInfo.f_bsize;
3911 pFile->deviceCharacteristics =
3912 /* full bitset of atomics from max sector size and smaller */
3913 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3914 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3915 ** so it is ordered */
3916 0;
3917 }else{
3918 pFile->deviceCharacteristics =
3919 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3920 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3921 ** the write succeeds */
3922 0;
3923 }
3924 }
3925 /* Last chance verification. If the sector size isn't a multiple of 512
3926 ** then it isn't valid.*/
3927 if( pFile->sectorSize % 512 != 0 ){
3928 pFile->deviceCharacteristics = 0;
3929 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3930 }
3931 return pFile->sectorSize;
3932}
3933#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003934
danielk197790949c22007-08-17 16:50:38 +00003935/*
drhf12b3f62011-12-21 14:42:29 +00003936** Return the device characteristics for the file.
3937**
drhcb15f352011-12-23 01:04:17 +00003938** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
peter.d.reid60ec9142014-09-06 16:39:46 +00003939** However, that choice is controversial since technically the underlying
drhcb15f352011-12-23 01:04:17 +00003940** file system does not always provide powersafe overwrites. (In other
3941** words, after a power-loss event, parts of the file that were never
3942** written might end up being altered.) However, non-PSOW behavior is very,
3943** very rare. And asserting PSOW makes a large reduction in the amount
3944** of required I/O for journaling, since a lot of padding is eliminated.
3945** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3946** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003947*/
drhf12b3f62011-12-21 14:42:29 +00003948static int unixDeviceCharacteristics(sqlite3_file *id){
3949 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003950 int rc = 0;
3951#ifdef __QNXNTO__
3952 if( p->sectorSize==0 ) unixSectorSize(id);
3953 rc = p->deviceCharacteristics;
3954#endif
drhcb15f352011-12-23 01:04:17 +00003955 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003956 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003957 }
drh537dddf2012-10-26 13:46:24 +00003958 return rc;
danielk197762079062007-08-15 17:08:46 +00003959}
3960
dan702eec12014-06-23 10:04:58 +00003961#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00003962
dan702eec12014-06-23 10:04:58 +00003963/*
3964** Return the system page size.
3965**
3966** This function should not be called directly by other code in this file.
3967** Instead, it should be called via macro osGetpagesize().
3968*/
3969static int unixGetpagesize(void){
drh8cd5b252015-03-02 22:06:43 +00003970#if OS_VXWORKS
3971 return 1024;
3972#elif defined(_BSD_SOURCE)
dan702eec12014-06-23 10:04:58 +00003973 return getpagesize();
3974#else
3975 return (int)sysconf(_SC_PAGESIZE);
3976#endif
3977}
3978
3979#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
3980
3981#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00003982
3983/*
drhd91c68f2010-05-14 14:52:25 +00003984** Object used to represent an shared memory buffer.
3985**
3986** When multiple threads all reference the same wal-index, each thread
3987** has its own unixShm object, but they all point to a single instance
3988** of this unixShmNode object. In other words, each wal-index is opened
3989** only once per process.
3990**
3991** Each unixShmNode object is connected to a single unixInodeInfo object.
3992** We could coalesce this object into unixInodeInfo, but that would mean
3993** every open file that does not use shared memory (in other words, most
3994** open files) would have to carry around this extra information. So
3995** the unixInodeInfo object contains a pointer to this unixShmNode object
3996** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003997**
3998** unixMutexHeld() must be true when creating or destroying
3999** this object or while reading or writing the following fields:
4000**
4001** nRef
drhd9e5c4f2010-05-12 18:01:39 +00004002**
4003** The following fields are read-only after the object is created:
4004**
4005** fid
4006** zFilename
4007**
drhd91c68f2010-05-14 14:52:25 +00004008** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00004009** unixMutexHeld() is true when reading or writing any other field
4010** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00004011*/
drhd91c68f2010-05-14 14:52:25 +00004012struct unixShmNode {
4013 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00004014 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00004015 char *zFilename; /* Name of the mmapped file */
4016 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00004017 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00004018 u16 nRegion; /* Size of array apRegion */
4019 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00004020 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00004021 int nRef; /* Number of unixShm objects pointing to this */
4022 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00004023#ifdef SQLITE_DEBUG
4024 u8 exclMask; /* Mask of exclusive locks held */
4025 u8 sharedMask; /* Mask of shared locks held */
4026 u8 nextShmId; /* Next available unixShm.id value */
4027#endif
4028};
4029
4030/*
drhd9e5c4f2010-05-12 18:01:39 +00004031** Structure used internally by this VFS to record the state of an
4032** open shared memory connection.
4033**
drhd91c68f2010-05-14 14:52:25 +00004034** The following fields are initialized when this object is created and
4035** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004036**
drhd91c68f2010-05-14 14:52:25 +00004037** unixShm.pFile
4038** unixShm.id
4039**
4040** All other fields are read/write. The unixShm.pFile->mutex must be held
4041** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004042*/
4043struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004044 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4045 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004046 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004047 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004048 u16 sharedMask; /* Mask of shared locks held */
4049 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004050};
4051
4052/*
drhd9e5c4f2010-05-12 18:01:39 +00004053** Constants used for locking
4054*/
drhbd9676c2010-06-23 17:58:38 +00004055#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004056#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004057
drhd9e5c4f2010-05-12 18:01:39 +00004058/*
drh73b64e42010-05-30 19:55:15 +00004059** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004060**
4061** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4062** otherwise.
4063*/
4064static int unixShmSystemLock(
drhbbf76ee2015-03-10 20:22:35 +00004065 unixFile *pFile, /* Open connection to the WAL file */
drhd91c68f2010-05-14 14:52:25 +00004066 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004067 int ofst, /* First byte of the locking range */
4068 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004069){
drhbbf76ee2015-03-10 20:22:35 +00004070 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4071 struct flock f; /* The posix advisory locking structure */
4072 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004073
drhd91c68f2010-05-14 14:52:25 +00004074 /* Access to the unixShmNode object is serialized by the caller */
drhbbf76ee2015-03-10 20:22:35 +00004075 pShmNode = pFile->pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004076 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004077
drh73b64e42010-05-30 19:55:15 +00004078 /* Shared locks never span more than one byte */
4079 assert( n==1 || lockType!=F_RDLCK );
4080
4081 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00004082 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004083
drh3cb93392011-03-12 18:10:44 +00004084 if( pShmNode->h>=0 ){
drhbbf76ee2015-03-10 20:22:35 +00004085 int lkType;
drh3cb93392011-03-12 18:10:44 +00004086 /* Initialize the locking parameters */
4087 memset(&f, 0, sizeof(f));
4088 f.l_type = lockType;
4089 f.l_whence = SEEK_SET;
4090 f.l_start = ofst;
4091 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004092
drhbbf76ee2015-03-10 20:22:35 +00004093 lkType = (pFile->ctrlFlags & UNIXFILE_BLOCK)!=0 ? F_SETLKW : F_SETLK;
4094 rc = osFcntl(pShmNode->h, lkType, &f);
drh3cb93392011-03-12 18:10:44 +00004095 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
drhbbf76ee2015-03-10 20:22:35 +00004096 pFile->ctrlFlags &= ~UNIXFILE_BLOCK;
drh3cb93392011-03-12 18:10:44 +00004097 }
drhd9e5c4f2010-05-12 18:01:39 +00004098
4099 /* Update the global lock state and do debug tracing */
4100#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004101 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004102 OSTRACE(("SHM-LOCK "));
drh693e6712014-01-24 22:58:00 +00004103 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004104 if( rc==SQLITE_OK ){
4105 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004106 OSTRACE(("unlock %d ok", ofst));
4107 pShmNode->exclMask &= ~mask;
4108 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004109 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004110 OSTRACE(("read-lock %d ok", ofst));
4111 pShmNode->exclMask &= ~mask;
4112 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004113 }else{
4114 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004115 OSTRACE(("write-lock %d ok", ofst));
4116 pShmNode->exclMask |= mask;
4117 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004118 }
4119 }else{
4120 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004121 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004122 }else if( lockType==F_RDLCK ){
4123 OSTRACE(("read-lock failed"));
4124 }else{
4125 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004126 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004127 }
4128 }
drh20e1f082010-05-31 16:10:12 +00004129 OSTRACE((" - afterwards %03x,%03x\n",
4130 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004131 }
drhd9e5c4f2010-05-12 18:01:39 +00004132#endif
4133
4134 return rc;
4135}
4136
dan781e34c2014-03-20 08:59:47 +00004137/*
dan781e34c2014-03-20 08:59:47 +00004138** Return the minimum number of 32KB shm regions that should be mapped at
4139** a time, assuming that each mapping must be an integer multiple of the
4140** current system page-size.
4141**
4142** Usually, this is 1. The exception seems to be systems that are configured
4143** to use 64KB pages - in this case each mapping must cover at least two
4144** shm regions.
4145*/
4146static int unixShmRegionPerMap(void){
4147 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004148 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004149 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4150 if( pgsz<shmsz ) return 1;
4151 return pgsz/shmsz;
4152}
drhd9e5c4f2010-05-12 18:01:39 +00004153
4154/*
drhd91c68f2010-05-14 14:52:25 +00004155** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004156**
4157** This is not a VFS shared-memory method; it is a utility function called
4158** by VFS shared-memory methods.
4159*/
drhd91c68f2010-05-14 14:52:25 +00004160static void unixShmPurge(unixFile *pFd){
4161 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004162 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00004163 if( p && p->nRef==0 ){
dan781e34c2014-03-20 08:59:47 +00004164 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004165 int i;
drhd91c68f2010-05-14 14:52:25 +00004166 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004167 sqlite3_mutex_free(p->mutex);
dan781e34c2014-03-20 08:59:47 +00004168 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh3cb93392011-03-12 18:10:44 +00004169 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004170 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004171 }else{
4172 sqlite3_free(p->apRegion[i]);
4173 }
dan13a3cb82010-06-11 19:04:21 +00004174 }
dan18801912010-06-14 14:07:50 +00004175 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004176 if( p->h>=0 ){
4177 robust_close(pFd, p->h, __LINE__);
4178 p->h = -1;
4179 }
drhd91c68f2010-05-14 14:52:25 +00004180 p->pInode->pShmNode = 0;
4181 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004182 }
4183}
4184
4185/*
danda9fe0c2010-07-13 18:44:03 +00004186** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004187** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004188**
drh7234c6d2010-06-19 15:10:09 +00004189** The file used to implement shared-memory is in the same directory
4190** as the open database file and has the same name as the open database
4191** file with the "-shm" suffix added. For example, if the database file
4192** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004193** for shared memory will be called "/home/user1/config.db-shm".
4194**
4195** Another approach to is to use files in /dev/shm or /dev/tmp or an
4196** some other tmpfs mount. But if a file in a different directory
4197** from the database file is used, then differing access permissions
4198** or a chroot() might cause two different processes on the same
4199** database to end up using different files for shared memory -
4200** meaning that their memory would not really be shared - resulting
4201** in database corruption. Nevertheless, this tmpfs file usage
4202** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4203** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4204** option results in an incompatible build of SQLite; builds of SQLite
4205** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4206** same database file at the same time, database corruption will likely
4207** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4208** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004209**
4210** When opening a new shared-memory file, if no other instances of that
4211** file are currently open, in this process or in other processes, then
4212** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004213**
4214** If the original database file (pDbFd) is using the "unix-excl" VFS
4215** that means that an exclusive lock is held on the database file and
4216** that no other processes are able to read or write the database. In
4217** that case, we do not really need shared memory. No shared memory
4218** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004219*/
danda9fe0c2010-07-13 18:44:03 +00004220static int unixOpenSharedMemory(unixFile *pDbFd){
4221 struct unixShm *p = 0; /* The connection to be opened */
4222 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4223 int rc; /* Result code */
4224 unixInodeInfo *pInode; /* The inode of fd */
4225 char *zShmFilename; /* Name of the file used for SHM */
4226 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004227
danda9fe0c2010-07-13 18:44:03 +00004228 /* Allocate space for the new unixShm object. */
drhf3cdcdc2015-04-29 16:50:28 +00004229 p = sqlite3_malloc64( sizeof(*p) );
drhd9e5c4f2010-05-12 18:01:39 +00004230 if( p==0 ) return SQLITE_NOMEM;
4231 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004232 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004233
danda9fe0c2010-07-13 18:44:03 +00004234 /* Check to see if a unixShmNode object already exists. Reuse an existing
4235 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004236 */
4237 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004238 pInode = pDbFd->pInode;
4239 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004240 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004241 struct stat sStat; /* fstat() info for database file */
drh4bf66fd2015-02-19 02:43:02 +00004242#ifndef SQLITE_SHM_DIRECTORY
4243 const char *zBasePath = pDbFd->zPath;
4244#endif
danddb0ac42010-07-14 14:48:58 +00004245
4246 /* Call fstat() to figure out the permissions on the database file. If
4247 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004248 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004249 */
drh3cb93392011-03-12 18:10:44 +00004250 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00004251 rc = SQLITE_IOERR_FSTAT;
4252 goto shm_open_err;
4253 }
4254
drha4ced192010-07-15 18:32:40 +00004255#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004256 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004257#else
drh4bf66fd2015-02-19 02:43:02 +00004258 nShmFilename = 6 + (int)strlen(zBasePath);
drha4ced192010-07-15 18:32:40 +00004259#endif
drhf3cdcdc2015-04-29 16:50:28 +00004260 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004261 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004262 rc = SQLITE_NOMEM;
4263 goto shm_open_err;
4264 }
drh9cb5a0d2012-01-05 21:19:54 +00004265 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004266 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004267#ifdef SQLITE_SHM_DIRECTORY
4268 sqlite3_snprintf(nShmFilename, zShmFilename,
4269 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4270 (u32)sStat.st_ino, (u32)sStat.st_dev);
4271#else
drh4bf66fd2015-02-19 02:43:02 +00004272 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
drh81cc5162011-05-17 20:36:21 +00004273 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004274#endif
drhd91c68f2010-05-14 14:52:25 +00004275 pShmNode->h = -1;
4276 pDbFd->pInode->pShmNode = pShmNode;
4277 pShmNode->pInode = pDbFd->pInode;
4278 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4279 if( pShmNode->mutex==0 ){
4280 rc = SQLITE_NOMEM;
4281 goto shm_open_err;
4282 }
drhd9e5c4f2010-05-12 18:01:39 +00004283
drh3cb93392011-03-12 18:10:44 +00004284 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004285 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004286 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004287 openFlags = O_RDONLY;
4288 pShmNode->isReadonly = 1;
4289 }
4290 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004291 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004292 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4293 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004294 }
drhac7c3ac2012-02-11 19:23:48 +00004295
4296 /* If this process is running as root, make sure that the SHM file
4297 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004298 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004299 */
drh6226ca22015-11-24 15:06:28 +00004300 robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004301
4302 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004303 ** If not, truncate the file to zero length.
4304 */
4305 rc = SQLITE_OK;
drhbbf76ee2015-03-10 20:22:35 +00004306 if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
drh66dfec8b2011-06-01 20:01:49 +00004307 if( robust_ftruncate(pShmNode->h, 0) ){
4308 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004309 }
4310 }
drh66dfec8b2011-06-01 20:01:49 +00004311 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004312 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
drh66dfec8b2011-06-01 20:01:49 +00004313 }
4314 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004315 }
drhd9e5c4f2010-05-12 18:01:39 +00004316 }
4317
drhd91c68f2010-05-14 14:52:25 +00004318 /* Make the new connection a child of the unixShmNode */
4319 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004320#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004321 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004322#endif
drhd91c68f2010-05-14 14:52:25 +00004323 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004324 pDbFd->pShm = p;
4325 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004326
4327 /* The reference count on pShmNode has already been incremented under
4328 ** the cover of the unixEnterMutex() mutex and the pointer from the
4329 ** new (struct unixShm) object to the pShmNode has been set. All that is
4330 ** left to do is to link the new object into the linked list starting
4331 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4332 ** mutex.
4333 */
4334 sqlite3_mutex_enter(pShmNode->mutex);
4335 p->pNext = pShmNode->pFirst;
4336 pShmNode->pFirst = p;
4337 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004338 return SQLITE_OK;
4339
4340 /* Jump here on any error */
4341shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004342 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004343 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004344 unixLeaveMutex();
4345 return rc;
4346}
4347
4348/*
danda9fe0c2010-07-13 18:44:03 +00004349** This function is called to obtain a pointer to region iRegion of the
4350** shared-memory associated with the database file fd. Shared-memory regions
4351** are numbered starting from zero. Each shared-memory region is szRegion
4352** bytes in size.
4353**
4354** If an error occurs, an error code is returned and *pp is set to NULL.
4355**
4356** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4357** region has not been allocated (by any client, including one running in a
4358** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4359** bExtend is non-zero and the requested shared-memory region has not yet
4360** been allocated, it is allocated by this function.
4361**
4362** If the shared-memory region has already been allocated or is allocated by
4363** this call as described above, then it is mapped into this processes
4364** address space (if it is not already), *pp is set to point to the mapped
4365** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004366*/
danda9fe0c2010-07-13 18:44:03 +00004367static int unixShmMap(
4368 sqlite3_file *fd, /* Handle open on database file */
4369 int iRegion, /* Region to retrieve */
4370 int szRegion, /* Size of regions */
4371 int bExtend, /* True to extend file if necessary */
4372 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004373){
danda9fe0c2010-07-13 18:44:03 +00004374 unixFile *pDbFd = (unixFile*)fd;
4375 unixShm *p;
4376 unixShmNode *pShmNode;
4377 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004378 int nShmPerMap = unixShmRegionPerMap();
4379 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004380
danda9fe0c2010-07-13 18:44:03 +00004381 /* If the shared-memory file has not yet been opened, open it now. */
4382 if( pDbFd->pShm==0 ){
4383 rc = unixOpenSharedMemory(pDbFd);
4384 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004385 }
drhd9e5c4f2010-05-12 18:01:39 +00004386
danda9fe0c2010-07-13 18:44:03 +00004387 p = pDbFd->pShm;
4388 pShmNode = p->pShmNode;
4389 sqlite3_mutex_enter(pShmNode->mutex);
4390 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004391 assert( pShmNode->pInode==pDbFd->pInode );
4392 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4393 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004394
dan781e34c2014-03-20 08:59:47 +00004395 /* Minimum number of regions required to be mapped. */
4396 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4397
4398 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004399 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004400 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004401 struct stat sStat; /* Used by fstat() */
4402
4403 pShmNode->szRegion = szRegion;
4404
drh3cb93392011-03-12 18:10:44 +00004405 if( pShmNode->h>=0 ){
4406 /* The requested region is not mapped into this processes address space.
4407 ** Check to see if it has been allocated (i.e. if the wal-index file is
4408 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004409 */
drh3cb93392011-03-12 18:10:44 +00004410 if( osFstat(pShmNode->h, &sStat) ){
4411 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004412 goto shmpage_out;
4413 }
drh3cb93392011-03-12 18:10:44 +00004414
4415 if( sStat.st_size<nByte ){
4416 /* The requested memory region does not exist. If bExtend is set to
4417 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004418 */
dan47a2b4a2013-04-26 16:09:29 +00004419 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004420 goto shmpage_out;
4421 }
dan47a2b4a2013-04-26 16:09:29 +00004422
4423 /* Alternatively, if bExtend is true, extend the file. Do this by
4424 ** writing a single byte to the end of each (OS) page being
4425 ** allocated or extended. Technically, we need only write to the
4426 ** last page in order to extend the file. But writing to all new
4427 ** pages forces the OS to allocate them immediately, which reduces
4428 ** the chances of SIGBUS while accessing the mapped region later on.
4429 */
4430 else{
4431 static const int pgsz = 4096;
4432 int iPg;
4433
4434 /* Write to the last byte of each newly allocated or extended page */
4435 assert( (nByte % pgsz)==0 );
4436 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
4437 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
4438 const char *zFile = pShmNode->zFilename;
4439 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4440 goto shmpage_out;
4441 }
4442 }
drh3cb93392011-03-12 18:10:44 +00004443 }
4444 }
danda9fe0c2010-07-13 18:44:03 +00004445 }
4446
4447 /* Map the requested memory region into this processes address space. */
4448 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004449 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004450 );
4451 if( !apNew ){
4452 rc = SQLITE_IOERR_NOMEM;
4453 goto shmpage_out;
4454 }
4455 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004456 while( pShmNode->nRegion<nReqRegion ){
4457 int nMap = szRegion*nShmPerMap;
4458 int i;
drh3cb93392011-03-12 18:10:44 +00004459 void *pMem;
4460 if( pShmNode->h>=0 ){
dan781e34c2014-03-20 08:59:47 +00004461 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004462 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004463 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004464 );
4465 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004466 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004467 goto shmpage_out;
4468 }
4469 }else{
drhf3cdcdc2015-04-29 16:50:28 +00004470 pMem = sqlite3_malloc64(szRegion);
drh3cb93392011-03-12 18:10:44 +00004471 if( pMem==0 ){
4472 rc = SQLITE_NOMEM;
4473 goto shmpage_out;
4474 }
4475 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004476 }
dan781e34c2014-03-20 08:59:47 +00004477
4478 for(i=0; i<nShmPerMap; i++){
4479 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4480 }
4481 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004482 }
4483 }
4484
4485shmpage_out:
4486 if( pShmNode->nRegion>iRegion ){
4487 *pp = pShmNode->apRegion[iRegion];
4488 }else{
4489 *pp = 0;
4490 }
drh66dfec8b2011-06-01 20:01:49 +00004491 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004492 sqlite3_mutex_leave(pShmNode->mutex);
4493 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004494}
4495
4496/*
drhd9e5c4f2010-05-12 18:01:39 +00004497** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004498**
4499** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4500** different here than in posix. In xShmLock(), one can go from unlocked
4501** to shared and back or from unlocked to exclusive and back. But one may
4502** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004503*/
4504static int unixShmLock(
4505 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004506 int ofst, /* First lock to acquire or release */
4507 int n, /* Number of locks to acquire or release */
4508 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004509){
drh73b64e42010-05-30 19:55:15 +00004510 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4511 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4512 unixShm *pX; /* For looping over all siblings */
4513 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4514 int rc = SQLITE_OK; /* Result code */
4515 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004516
drhd91c68f2010-05-14 14:52:25 +00004517 assert( pShmNode==pDbFd->pInode->pShmNode );
4518 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004519 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004520 assert( n>=1 );
4521 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4522 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4523 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4524 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4525 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004526 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4527 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004528
drhc99597c2010-05-31 01:41:15 +00004529 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004530 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004531 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004532 if( flags & SQLITE_SHM_UNLOCK ){
4533 u16 allMask = 0; /* Mask of locks held by siblings */
4534
4535 /* See if any siblings hold this same lock */
4536 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4537 if( pX==p ) continue;
4538 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4539 allMask |= pX->sharedMask;
4540 }
4541
4542 /* Unlock the system-level locks */
4543 if( (mask & allMask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004544 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004545 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004546 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004547 }
drh73b64e42010-05-30 19:55:15 +00004548
4549 /* Undo the local locks */
4550 if( rc==SQLITE_OK ){
4551 p->exclMask &= ~mask;
4552 p->sharedMask &= ~mask;
4553 }
4554 }else if( flags & SQLITE_SHM_SHARED ){
4555 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4556
4557 /* Find out which shared locks are already held by sibling connections.
4558 ** If any sibling already holds an exclusive lock, go ahead and return
4559 ** SQLITE_BUSY.
4560 */
4561 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004562 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004563 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004564 break;
4565 }
4566 allShared |= pX->sharedMask;
4567 }
4568
4569 /* Get shared locks at the system level, if necessary */
4570 if( rc==SQLITE_OK ){
4571 if( (allShared & mask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004572 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004573 }else{
drh73b64e42010-05-30 19:55:15 +00004574 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004575 }
drhd9e5c4f2010-05-12 18:01:39 +00004576 }
drh73b64e42010-05-30 19:55:15 +00004577
4578 /* Get the local shared locks */
4579 if( rc==SQLITE_OK ){
4580 p->sharedMask |= mask;
4581 }
4582 }else{
4583 /* Make sure no sibling connections hold locks that will block this
4584 ** lock. If any do, return SQLITE_BUSY right away.
4585 */
4586 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004587 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4588 rc = SQLITE_BUSY;
4589 break;
4590 }
4591 }
4592
4593 /* Get the exclusive locks at the system level. Then if successful
4594 ** also mark the local connection as being locked.
4595 */
4596 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004597 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004598 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004599 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004600 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004601 }
drhd9e5c4f2010-05-12 18:01:39 +00004602 }
4603 }
drhd91c68f2010-05-14 14:52:25 +00004604 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004605 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
drh5ac93652015-03-21 20:59:43 +00004606 p->id, osGetpid(0), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004607 return rc;
4608}
4609
drh286a2882010-05-20 23:51:06 +00004610/*
4611** Implement a memory barrier or memory fence on shared memory.
4612**
4613** All loads and stores begun before the barrier must complete before
4614** any load or store begun after the barrier.
4615*/
4616static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004617 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004618){
drhff828942010-06-26 21:34:06 +00004619 UNUSED_PARAMETER(fd);
drh22c733d2015-09-24 12:40:43 +00004620 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
4621 unixEnterMutex(); /* Also mutex, for redundancy */
drhb29ad852010-06-01 00:03:57 +00004622 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004623}
4624
dan18801912010-06-14 14:07:50 +00004625/*
danda9fe0c2010-07-13 18:44:03 +00004626** Close a connection to shared-memory. Delete the underlying
4627** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004628**
4629** If there is no shared memory associated with the connection then this
4630** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004631*/
danda9fe0c2010-07-13 18:44:03 +00004632static int unixShmUnmap(
4633 sqlite3_file *fd, /* The underlying database file */
4634 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004635){
danda9fe0c2010-07-13 18:44:03 +00004636 unixShm *p; /* The connection to be closed */
4637 unixShmNode *pShmNode; /* The underlying shared-memory file */
4638 unixShm **pp; /* For looping over sibling connections */
4639 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004640
danda9fe0c2010-07-13 18:44:03 +00004641 pDbFd = (unixFile*)fd;
4642 p = pDbFd->pShm;
4643 if( p==0 ) return SQLITE_OK;
4644 pShmNode = p->pShmNode;
4645
4646 assert( pShmNode==pDbFd->pInode->pShmNode );
4647 assert( pShmNode->pInode==pDbFd->pInode );
4648
4649 /* Remove connection p from the set of connections associated
4650 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004651 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004652 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4653 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004654
danda9fe0c2010-07-13 18:44:03 +00004655 /* Free the connection p */
4656 sqlite3_free(p);
4657 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004658 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004659
4660 /* If pShmNode->nRef has reached 0, then close the underlying
4661 ** shared-memory file, too */
4662 unixEnterMutex();
4663 assert( pShmNode->nRef>0 );
4664 pShmNode->nRef--;
4665 if( pShmNode->nRef==0 ){
drh4bf66fd2015-02-19 02:43:02 +00004666 if( deleteFlag && pShmNode->h>=0 ){
4667 osUnlink(pShmNode->zFilename);
4668 }
danda9fe0c2010-07-13 18:44:03 +00004669 unixShmPurge(pDbFd);
4670 }
4671 unixLeaveMutex();
4672
4673 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004674}
drh286a2882010-05-20 23:51:06 +00004675
danda9fe0c2010-07-13 18:44:03 +00004676
drhd9e5c4f2010-05-12 18:01:39 +00004677#else
drh6b017cc2010-06-14 18:01:46 +00004678# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004679# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004680# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004681# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004682#endif /* #ifndef SQLITE_OMIT_WAL */
4683
mistachkine98844f2013-08-24 00:59:24 +00004684#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004685/*
danaef49d72013-03-25 16:28:54 +00004686** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004687*/
danf23da962013-03-23 21:00:41 +00004688static void unixUnmapfile(unixFile *pFd){
4689 assert( pFd->nFetchOut==0 );
4690 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004691 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004692 pFd->pMapRegion = 0;
4693 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004694 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004695 }
4696}
dan5d8a1372013-03-19 19:28:06 +00004697
danaef49d72013-03-25 16:28:54 +00004698/*
dane6ecd662013-04-01 17:56:59 +00004699** Attempt to set the size of the memory mapping maintained by file
4700** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4701**
4702** If successful, this function sets the following variables:
4703**
4704** unixFile.pMapRegion
4705** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004706** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004707**
4708** If unsuccessful, an error message is logged via sqlite3_log() and
4709** the three variables above are zeroed. In this case SQLite should
4710** continue accessing the database using the xRead() and xWrite()
4711** methods.
4712*/
4713static void unixRemapfile(
4714 unixFile *pFd, /* File descriptor object */
4715 i64 nNew /* Required mapping size */
4716){
dan4ff7bc42013-04-02 12:04:09 +00004717 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004718 int h = pFd->h; /* File descriptor open on db file */
4719 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004720 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004721 u8 *pNew = 0; /* Location of new mapping */
4722 int flags = PROT_READ; /* Flags to pass to mmap() */
4723
4724 assert( pFd->nFetchOut==0 );
4725 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004726 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004727 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004728 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004729 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004730
danfe33e392015-11-17 20:56:06 +00004731#ifdef SQLITE_MMAP_READWRITE
dane6ecd662013-04-01 17:56:59 +00004732 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
danfe33e392015-11-17 20:56:06 +00004733#endif
dane6ecd662013-04-01 17:56:59 +00004734
4735 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00004736#if HAVE_MREMAP
4737 i64 nReuse = pFd->mmapSize;
4738#else
danbc760632014-03-20 09:42:09 +00004739 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00004740 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00004741#endif
dane6ecd662013-04-01 17:56:59 +00004742 u8 *pReq = &pOrig[nReuse];
4743
4744 /* Unmap any pages of the existing mapping that cannot be reused. */
4745 if( nReuse!=nOrig ){
4746 osMunmap(pReq, nOrig-nReuse);
4747 }
4748
4749#if HAVE_MREMAP
4750 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004751 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004752#else
4753 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4754 if( pNew!=MAP_FAILED ){
4755 if( pNew!=pReq ){
4756 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004757 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004758 }else{
4759 pNew = pOrig;
4760 }
4761 }
4762#endif
4763
dan48ccef82013-04-02 20:55:01 +00004764 /* The attempt to extend the existing mapping failed. Free it. */
4765 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004766 osMunmap(pOrig, nReuse);
4767 }
4768 }
4769
4770 /* If pNew is still NULL, try to create an entirely new mapping. */
4771 if( pNew==0 ){
4772 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004773 }
4774
dan4ff7bc42013-04-02 12:04:09 +00004775 if( pNew==MAP_FAILED ){
4776 pNew = 0;
4777 nNew = 0;
4778 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4779
4780 /* If the mmap() above failed, assume that all subsequent mmap() calls
4781 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4782 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004783 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004784 }
dane6ecd662013-04-01 17:56:59 +00004785 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004786 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004787}
4788
4789/*
danaef49d72013-03-25 16:28:54 +00004790** Memory map or remap the file opened by file-descriptor pFd (if the file
4791** is already mapped, the existing mapping is replaced by the new). Or, if
4792** there already exists a mapping for this file, and there are still
4793** outstanding xFetch() references to it, this function is a no-op.
4794**
4795** If parameter nByte is non-negative, then it is the requested size of
4796** the mapping to create. Otherwise, if nByte is less than zero, then the
4797** requested size is the size of the file on disk. The actual size of the
4798** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004799** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004800**
4801** SQLITE_OK is returned if no error occurs (even if the mapping is not
4802** recreated as a result of outstanding references) or an SQLite error
4803** code otherwise.
4804*/
danf23da962013-03-23 21:00:41 +00004805static int unixMapfile(unixFile *pFd, i64 nByte){
4806 i64 nMap = nByte;
4807 int rc;
daneb97b292013-03-20 14:26:59 +00004808
danf23da962013-03-23 21:00:41 +00004809 assert( nMap>=0 || pFd->nFetchOut==0 );
4810 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4811
4812 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00004813 struct stat statbuf; /* Low-level file information */
4814 rc = osFstat(pFd->h, &statbuf);
danf23da962013-03-23 21:00:41 +00004815 if( rc!=SQLITE_OK ){
4816 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004817 }
drh3044b512014-06-16 16:41:52 +00004818 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00004819 }
drh9b4c59f2013-04-15 17:03:42 +00004820 if( nMap>pFd->mmapSizeMax ){
4821 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004822 }
4823
danf23da962013-03-23 21:00:41 +00004824 if( nMap!=pFd->mmapSize ){
dane6ecd662013-04-01 17:56:59 +00004825 if( nMap>0 ){
4826 unixRemapfile(pFd, nMap);
4827 }else{
danb7e3a322013-03-25 20:30:13 +00004828 unixUnmapfile(pFd);
dan5d8a1372013-03-19 19:28:06 +00004829 }
4830 }
4831
danf23da962013-03-23 21:00:41 +00004832 return SQLITE_OK;
4833}
mistachkine98844f2013-08-24 00:59:24 +00004834#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004835
danaef49d72013-03-25 16:28:54 +00004836/*
4837** If possible, return a pointer to a mapping of file fd starting at offset
4838** iOff. The mapping must be valid for at least nAmt bytes.
4839**
4840** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4841** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4842** Finally, if an error does occur, return an SQLite error code. The final
4843** value of *pp is undefined in this case.
4844**
4845** If this function does return a pointer, the caller must eventually
4846** release the reference by calling unixUnfetch().
4847*/
danf23da962013-03-23 21:00:41 +00004848static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004849#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004850 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004851#endif
danf23da962013-03-23 21:00:41 +00004852 *pp = 0;
4853
drh9b4c59f2013-04-15 17:03:42 +00004854#if SQLITE_MAX_MMAP_SIZE>0
4855 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004856 if( pFd->pMapRegion==0 ){
4857 int rc = unixMapfile(pFd, -1);
4858 if( rc!=SQLITE_OK ) return rc;
4859 }
4860 if( pFd->mmapSize >= iOff+nAmt ){
4861 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4862 pFd->nFetchOut++;
4863 }
4864 }
drh6e0b6d52013-04-09 16:19:20 +00004865#endif
danf23da962013-03-23 21:00:41 +00004866 return SQLITE_OK;
4867}
4868
danaef49d72013-03-25 16:28:54 +00004869/*
dandf737fe2013-03-25 17:00:24 +00004870** If the third argument is non-NULL, then this function releases a
4871** reference obtained by an earlier call to unixFetch(). The second
4872** argument passed to this function must be the same as the corresponding
4873** argument that was passed to the unixFetch() invocation.
4874**
4875** Or, if the third argument is NULL, then this function is being called
4876** to inform the VFS layer that, according to POSIX, any existing mapping
4877** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004878*/
dandf737fe2013-03-25 17:00:24 +00004879static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00004880#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00004881 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00004882 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00004883
danaef49d72013-03-25 16:28:54 +00004884 /* If p==0 (unmap the entire file) then there must be no outstanding
4885 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4886 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004887 assert( (p==0)==(pFd->nFetchOut==0) );
4888
dandf737fe2013-03-25 17:00:24 +00004889 /* If p!=0, it must match the iOff value. */
4890 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4891
danf23da962013-03-23 21:00:41 +00004892 if( p ){
4893 pFd->nFetchOut--;
4894 }else{
4895 unixUnmapfile(pFd);
4896 }
4897
4898 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00004899#else
4900 UNUSED_PARAMETER(fd);
4901 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00004902 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00004903#endif
danf23da962013-03-23 21:00:41 +00004904 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004905}
4906
4907/*
drh734c9862008-11-28 15:37:20 +00004908** Here ends the implementation of all sqlite3_file methods.
4909**
4910********************** End sqlite3_file Methods *******************************
4911******************************************************************************/
4912
4913/*
drh6b9d6dd2008-12-03 19:34:47 +00004914** This division contains definitions of sqlite3_io_methods objects that
4915** implement various file locking strategies. It also contains definitions
4916** of "finder" functions. A finder-function is used to locate the appropriate
4917** sqlite3_io_methods object for a particular database file. The pAppData
4918** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4919** the correct finder-function for that VFS.
4920**
4921** Most finder functions return a pointer to a fixed sqlite3_io_methods
4922** object. The only interesting finder-function is autolockIoFinder, which
4923** looks at the filesystem type and tries to guess the best locking
4924** strategy from that.
4925**
peter.d.reid60ec9142014-09-06 16:39:46 +00004926** For finder-function F, two objects are created:
drh1875f7a2008-12-08 18:19:17 +00004927**
4928** (1) The real finder-function named "FImpt()".
4929**
dane946c392009-08-22 11:39:46 +00004930** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004931**
4932**
4933** A pointer to the F pointer is used as the pAppData value for VFS
4934** objects. We have to do this instead of letting pAppData point
4935** directly at the finder-function since C90 rules prevent a void*
4936** from be cast into a function pointer.
4937**
drh6b9d6dd2008-12-03 19:34:47 +00004938**
drh7708e972008-11-29 00:56:52 +00004939** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004940**
drh7708e972008-11-29 00:56:52 +00004941** * A constant sqlite3_io_methods object call METHOD that has locking
4942** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4943**
4944** * An I/O method finder function called FINDER that returns a pointer
4945** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004946*/
drhe6d41732015-02-21 00:49:00 +00004947#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
drh7708e972008-11-29 00:56:52 +00004948static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004949 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004950 CLOSE, /* xClose */ \
4951 unixRead, /* xRead */ \
4952 unixWrite, /* xWrite */ \
4953 unixTruncate, /* xTruncate */ \
4954 unixSync, /* xSync */ \
4955 unixFileSize, /* xFileSize */ \
4956 LOCK, /* xLock */ \
4957 UNLOCK, /* xUnlock */ \
4958 CKLOCK, /* xCheckReservedLock */ \
4959 unixFileControl, /* xFileControl */ \
4960 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004961 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drhd9f94412014-09-22 03:22:27 +00004962 SHMMAP, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004963 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004964 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00004965 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00004966 unixFetch, /* xFetch */ \
4967 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00004968}; \
drh0c2694b2009-09-03 16:23:44 +00004969static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4970 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004971 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004972} \
drh0c2694b2009-09-03 16:23:44 +00004973static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004974 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004975
4976/*
4977** Here are all of the sqlite3_io_methods objects for each of the
4978** locking strategies. Functions that return pointers to these methods
4979** are also created.
4980*/
4981IOMETHODS(
4982 posixIoFinder, /* Finder function name */
4983 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00004984 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00004985 unixClose, /* xClose method */
4986 unixLock, /* xLock method */
4987 unixUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004988 unixCheckReservedLock, /* xCheckReservedLock method */
4989 unixShmMap /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004990)
drh7708e972008-11-29 00:56:52 +00004991IOMETHODS(
4992 nolockIoFinder, /* Finder function name */
4993 nolockIoMethods, /* sqlite3_io_methods object name */
drh142341c2014-09-19 19:00:48 +00004994 3, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004995 nolockClose, /* xClose method */
4996 nolockLock, /* xLock method */
4997 nolockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004998 nolockCheckReservedLock, /* xCheckReservedLock method */
4999 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005000)
drh7708e972008-11-29 00:56:52 +00005001IOMETHODS(
5002 dotlockIoFinder, /* Finder function name */
5003 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005004 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005005 dotlockClose, /* xClose method */
5006 dotlockLock, /* xLock method */
5007 dotlockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005008 dotlockCheckReservedLock, /* xCheckReservedLock method */
5009 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005010)
drh7708e972008-11-29 00:56:52 +00005011
drhe89b2912015-03-03 20:42:01 +00005012#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005013IOMETHODS(
5014 flockIoFinder, /* Finder function name */
5015 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005016 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005017 flockClose, /* xClose method */
5018 flockLock, /* xLock method */
5019 flockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005020 flockCheckReservedLock, /* xCheckReservedLock method */
5021 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005022)
drh7708e972008-11-29 00:56:52 +00005023#endif
5024
drh6c7d5c52008-11-21 20:32:33 +00005025#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005026IOMETHODS(
5027 semIoFinder, /* Finder function name */
5028 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005029 1, /* shared memory is disabled */
drh8cd5b252015-03-02 22:06:43 +00005030 semXClose, /* xClose method */
5031 semXLock, /* xLock method */
5032 semXUnlock, /* xUnlock method */
5033 semXCheckReservedLock, /* xCheckReservedLock method */
drhd9f94412014-09-22 03:22:27 +00005034 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005035)
aswiftaebf4132008-11-21 00:10:35 +00005036#endif
drh7708e972008-11-29 00:56:52 +00005037
drhd2cb50b2009-01-09 21:41:17 +00005038#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005039IOMETHODS(
5040 afpIoFinder, /* Finder function name */
5041 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005042 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005043 afpClose, /* xClose method */
5044 afpLock, /* xLock method */
5045 afpUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005046 afpCheckReservedLock, /* xCheckReservedLock method */
5047 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005048)
drh715ff302008-12-03 22:32:44 +00005049#endif
5050
5051/*
5052** The proxy locking method is a "super-method" in the sense that it
5053** opens secondary file descriptors for the conch and lock files and
5054** it uses proxy, dot-file, AFP, and flock() locking methods on those
5055** secondary files. For this reason, the division that implements
5056** proxy locking is located much further down in the file. But we need
5057** to go ahead and define the sqlite3_io_methods and finder function
5058** for proxy locking here. So we forward declare the I/O methods.
5059*/
drhd2cb50b2009-01-09 21:41:17 +00005060#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005061static int proxyClose(sqlite3_file*);
5062static int proxyLock(sqlite3_file*, int);
5063static int proxyUnlock(sqlite3_file*, int);
5064static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005065IOMETHODS(
5066 proxyIoFinder, /* Finder function name */
5067 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005068 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005069 proxyClose, /* xClose method */
5070 proxyLock, /* xLock method */
5071 proxyUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005072 proxyCheckReservedLock, /* xCheckReservedLock method */
5073 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005074)
aswiftaebf4132008-11-21 00:10:35 +00005075#endif
drh7708e972008-11-29 00:56:52 +00005076
drh7ed97b92010-01-20 13:07:21 +00005077/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5078#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5079IOMETHODS(
5080 nfsIoFinder, /* Finder function name */
5081 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005082 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005083 unixClose, /* xClose method */
5084 unixLock, /* xLock method */
5085 nfsUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005086 unixCheckReservedLock, /* xCheckReservedLock method */
5087 0 /* xShmMap method */
drh7ed97b92010-01-20 13:07:21 +00005088)
5089#endif
drh7708e972008-11-29 00:56:52 +00005090
drhd2cb50b2009-01-09 21:41:17 +00005091#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005092/*
drh6b9d6dd2008-12-03 19:34:47 +00005093** This "finder" function attempts to determine the best locking strategy
5094** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005095** object that implements that strategy.
5096**
5097** This is for MacOSX only.
5098*/
drh1875f7a2008-12-08 18:19:17 +00005099static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005100 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005101 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005102){
5103 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005104 const char *zFilesystem; /* Filesystem type name */
5105 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005106 } aMap[] = {
5107 { "hfs", &posixIoMethods },
5108 { "ufs", &posixIoMethods },
5109 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005110 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005111 { "webdav", &nolockIoMethods },
5112 { 0, 0 }
5113 };
5114 int i;
5115 struct statfs fsInfo;
5116 struct flock lockInfo;
5117
5118 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005119 /* If filePath==NULL that means we are dealing with a transient file
5120 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005121 return &nolockIoMethods;
5122 }
5123 if( statfs(filePath, &fsInfo) != -1 ){
5124 if( fsInfo.f_flags & MNT_RDONLY ){
5125 return &nolockIoMethods;
5126 }
5127 for(i=0; aMap[i].zFilesystem; i++){
5128 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5129 return aMap[i].pMethods;
5130 }
5131 }
5132 }
5133
5134 /* Default case. Handles, amongst others, "nfs".
5135 ** Test byte-range lock using fcntl(). If the call succeeds,
5136 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005137 */
drh7708e972008-11-29 00:56:52 +00005138 lockInfo.l_len = 1;
5139 lockInfo.l_start = 0;
5140 lockInfo.l_whence = SEEK_SET;
5141 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005142 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005143 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5144 return &nfsIoMethods;
5145 } else {
5146 return &posixIoMethods;
5147 }
drh7708e972008-11-29 00:56:52 +00005148 }else{
5149 return &dotlockIoMethods;
5150 }
5151}
drh0c2694b2009-09-03 16:23:44 +00005152static const sqlite3_io_methods
5153 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005154
drhd2cb50b2009-01-09 21:41:17 +00005155#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005156
drhe89b2912015-03-03 20:42:01 +00005157#if OS_VXWORKS
5158/*
5159** This "finder" function for VxWorks checks to see if posix advisory
5160** locking works. If it does, then that is what is used. If it does not
5161** work, then fallback to named semaphore locking.
chw78a13182009-04-07 05:35:03 +00005162*/
drhe89b2912015-03-03 20:42:01 +00005163static const sqlite3_io_methods *vxworksIoFinderImpl(
chw78a13182009-04-07 05:35:03 +00005164 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005165 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005166){
5167 struct flock lockInfo;
5168
5169 if( !filePath ){
5170 /* If filePath==NULL that means we are dealing with a transient file
5171 ** that does not need to be locked. */
5172 return &nolockIoMethods;
5173 }
5174
5175 /* Test if fcntl() is supported and use POSIX style locks.
5176 ** Otherwise fall back to the named semaphore method.
5177 */
5178 lockInfo.l_len = 1;
5179 lockInfo.l_start = 0;
5180 lockInfo.l_whence = SEEK_SET;
5181 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005182 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005183 return &posixIoMethods;
5184 }else{
5185 return &semIoMethods;
5186 }
5187}
drh0c2694b2009-09-03 16:23:44 +00005188static const sqlite3_io_methods
drhe89b2912015-03-03 20:42:01 +00005189 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005190
drhe89b2912015-03-03 20:42:01 +00005191#endif /* OS_VXWORKS */
chw78a13182009-04-07 05:35:03 +00005192
drh7708e972008-11-29 00:56:52 +00005193/*
peter.d.reid60ec9142014-09-06 16:39:46 +00005194** An abstract type for a pointer to an IO method finder function:
drh7708e972008-11-29 00:56:52 +00005195*/
drh0c2694b2009-09-03 16:23:44 +00005196typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005197
aswiftaebf4132008-11-21 00:10:35 +00005198
drh734c9862008-11-28 15:37:20 +00005199/****************************************************************************
5200**************************** sqlite3_vfs methods ****************************
5201**
5202** This division contains the implementation of methods on the
5203** sqlite3_vfs object.
5204*/
5205
danielk1977a3d4c882007-03-23 10:08:38 +00005206/*
danielk1977e339d652008-06-28 11:23:00 +00005207** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005208*/
5209static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005210 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005211 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005212 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005213 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005214 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005215){
drh7708e972008-11-29 00:56:52 +00005216 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005217 unixFile *pNew = (unixFile *)pId;
5218 int rc = SQLITE_OK;
5219
drh8af6c222010-05-14 12:43:01 +00005220 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005221
dan00157392010-10-05 11:33:15 +00005222 /* Usually the path zFilename should not be a relative pathname. The
5223 ** exception is when opening the proxy "conch" file in builds that
5224 ** include the special Apple locking styles.
5225 */
dan00157392010-10-05 11:33:15 +00005226#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005227 assert( zFilename==0 || zFilename[0]=='/'
5228 || pVfs->pAppData==(void*)&autolockIoFinder );
5229#else
5230 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005231#endif
dan00157392010-10-05 11:33:15 +00005232
drhb07028f2011-10-14 21:49:18 +00005233 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005234 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005235
drh308c2a52010-05-14 11:30:18 +00005236 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005237 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005238 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005239 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005240 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005241#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005242 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005243#endif
drhc02a43a2012-01-10 23:18:38 +00005244 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5245 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005246 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005247 }
drh503a6862013-03-01 01:07:17 +00005248 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005249 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005250 }
drh339eb0b2008-03-07 15:34:11 +00005251
drh6c7d5c52008-11-21 20:32:33 +00005252#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005253 pNew->pId = vxworksFindFileId(zFilename);
5254 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005255 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00005256 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00005257 }
5258#endif
5259
drhc02a43a2012-01-10 23:18:38 +00005260 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005261 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005262 }else{
drh0c2694b2009-09-03 16:23:44 +00005263 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005264#if SQLITE_ENABLE_LOCKING_STYLE
5265 /* Cache zFilename in the locking context (AFP and dotlock override) for
5266 ** proxyLock activation is possible (remote proxy is based on db name)
5267 ** zFilename remains valid until file is closed, to support */
5268 pNew->lockingContext = (void*)zFilename;
5269#endif
drhda0e7682008-07-30 15:27:54 +00005270 }
danielk1977e339d652008-06-28 11:23:00 +00005271
drh7ed97b92010-01-20 13:07:21 +00005272 if( pLockingStyle == &posixIoMethods
5273#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5274 || pLockingStyle == &nfsIoMethods
5275#endif
5276 ){
drh7708e972008-11-29 00:56:52 +00005277 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005278 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005279 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005280 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005281 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005282 ** in two scenarios:
5283 **
5284 ** (a) A call to fstat() failed.
5285 ** (b) A malloc failed.
5286 **
5287 ** Scenario (b) may only occur if the process is holding no other
5288 ** file descriptors open on the same file. If there were other file
5289 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005290 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005291 ** handle h - as it is guaranteed that no posix locks will be released
5292 ** by doing so.
5293 **
5294 ** If scenario (a) caused the error then things are not so safe. The
5295 ** implicit assumption here is that if fstat() fails, things are in
5296 ** such bad shape that dropping a lock or two doesn't matter much.
5297 */
drh0e9365c2011-03-02 02:08:13 +00005298 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005299 h = -1;
5300 }
drh7708e972008-11-29 00:56:52 +00005301 unixLeaveMutex();
5302 }
danielk1977e339d652008-06-28 11:23:00 +00005303
drhd2cb50b2009-01-09 21:41:17 +00005304#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005305 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005306 /* AFP locking uses the file path so it needs to be included in
5307 ** the afpLockingContext.
5308 */
5309 afpLockingContext *pCtx;
drhf3cdcdc2015-04-29 16:50:28 +00005310 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh7708e972008-11-29 00:56:52 +00005311 if( pCtx==0 ){
5312 rc = SQLITE_NOMEM;
5313 }else{
5314 /* NB: zFilename exists and remains valid until the file is closed
5315 ** according to requirement F11141. So we do not need to make a
5316 ** copy of the filename. */
5317 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005318 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005319 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005320 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005321 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005322 if( rc!=SQLITE_OK ){
5323 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005324 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005325 h = -1;
5326 }
drh7708e972008-11-29 00:56:52 +00005327 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005328 }
drh7708e972008-11-29 00:56:52 +00005329 }
5330#endif
danielk1977e339d652008-06-28 11:23:00 +00005331
drh7708e972008-11-29 00:56:52 +00005332 else if( pLockingStyle == &dotlockIoMethods ){
5333 /* Dotfile locking uses the file path so it needs to be included in
5334 ** the dotlockLockingContext
5335 */
5336 char *zLockFile;
5337 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005338 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005339 nFilename = (int)strlen(zFilename) + 6;
drhf3cdcdc2015-04-29 16:50:28 +00005340 zLockFile = (char *)sqlite3_malloc64(nFilename);
drh7708e972008-11-29 00:56:52 +00005341 if( zLockFile==0 ){
5342 rc = SQLITE_NOMEM;
5343 }else{
5344 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005345 }
drh7708e972008-11-29 00:56:52 +00005346 pNew->lockingContext = zLockFile;
5347 }
danielk1977e339d652008-06-28 11:23:00 +00005348
drh6c7d5c52008-11-21 20:32:33 +00005349#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005350 else if( pLockingStyle == &semIoMethods ){
5351 /* Named semaphore locking uses the file path so it needs to be
5352 ** included in the semLockingContext
5353 */
5354 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005355 rc = findInodeInfo(pNew, &pNew->pInode);
5356 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5357 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005358 int n;
drh2238dcc2009-08-27 17:56:20 +00005359 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005360 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005361 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005362 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005363 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5364 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00005365 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00005366 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005367 }
chw97185482008-11-17 08:05:31 +00005368 }
drh7708e972008-11-29 00:56:52 +00005369 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005370 }
drh7708e972008-11-29 00:56:52 +00005371#endif
aswift5b1a2562008-08-22 00:22:35 +00005372
drh4bf66fd2015-02-19 02:43:02 +00005373 storeLastErrno(pNew, 0);
drh6c7d5c52008-11-21 20:32:33 +00005374#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005375 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005376 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005377 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005378 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005379 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005380 }
chw97185482008-11-17 08:05:31 +00005381#endif
danielk1977e339d652008-06-28 11:23:00 +00005382 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005383 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005384 }else{
drh7708e972008-11-29 00:56:52 +00005385 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005386 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005387 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005388 }
danielk1977e339d652008-06-28 11:23:00 +00005389 return rc;
drh054889e2005-11-30 03:20:31 +00005390}
drh9c06c952005-11-26 00:25:00 +00005391
danielk1977ad94b582007-08-20 06:44:22 +00005392/*
drh8b3cf822010-06-01 21:02:51 +00005393** Return the name of a directory in which to put temporary files.
5394** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005395*/
drh7234c6d2010-06-19 15:10:09 +00005396static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005397 static const char *azDirs[] = {
5398 0,
aswiftaebf4132008-11-21 00:10:35 +00005399 0,
mistachkind95a3d32013-08-30 21:52:38 +00005400 0,
danielk197717b90b52008-06-06 11:11:25 +00005401 "/var/tmp",
5402 "/usr/tmp",
5403 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00005404 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00005405 };
drh8b3cf822010-06-01 21:02:51 +00005406 unsigned int i;
5407 struct stat buf;
5408 const char *zDir = 0;
5409
5410 azDirs[0] = sqlite3_temp_directory;
mistachkind95a3d32013-08-30 21:52:38 +00005411 if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
5412 if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005413 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005414 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005415 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005416 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005417 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005418 break;
5419 }
5420 return zDir;
5421}
5422
5423/*
5424** Create a temporary file name in zBuf. zBuf must be allocated
5425** by the calling process and must be big enough to hold at least
5426** pVfs->mxPathname bytes.
5427*/
5428static int unixGetTempname(int nBuf, char *zBuf){
drh8b3cf822010-06-01 21:02:51 +00005429 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00005430
5431 /* It's odd to simulate an io-error here, but really this is just
5432 ** using the io-error infrastructure to test that SQLite handles this
5433 ** function failing.
5434 */
5435 SimulateIOError( return SQLITE_IOERR );
5436
drh7234c6d2010-06-19 15:10:09 +00005437 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00005438 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00005439 do{
drh970942e2015-11-25 23:13:14 +00005440 u64 r;
5441 sqlite3_randomness(sizeof(r), &r);
5442 assert( nBuf>2 );
5443 zBuf[nBuf-2] = 0;
5444 sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
5445 zDir, r, 0);
5446 if( zBuf[nBuf-2]!=0 ) return SQLITE_ERROR;
drh99ab3b12011-03-02 15:09:07 +00005447 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005448 return SQLITE_OK;
5449}
5450
drhd2cb50b2009-01-09 21:41:17 +00005451#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005452/*
5453** Routine to transform a unixFile into a proxy-locking unixFile.
5454** Implementation in the proxy-lock division, but used by unixOpen()
5455** if SQLITE_PREFER_PROXY_LOCKING is defined.
5456*/
5457static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005458#endif
drhc66d5b62008-12-03 22:48:32 +00005459
dan08da86a2009-08-21 17:18:03 +00005460/*
5461** Search for an unused file descriptor that was opened on the database
5462** file (not a journal or master-journal file) identified by pathname
5463** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5464** argument to this function.
5465**
5466** Such a file descriptor may exist if a database connection was closed
5467** but the associated file descriptor could not be closed because some
5468** other file descriptor open on the same file is holding a file-lock.
5469** Refer to comments in the unixClose() function and the lengthy comment
5470** describing "Posix Advisory Locking" at the start of this file for
5471** further details. Also, ticket #4018.
5472**
5473** If a suitable file descriptor is found, then it is returned. If no
5474** such file descriptor is located, -1 is returned.
5475*/
dane946c392009-08-22 11:39:46 +00005476static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5477 UnixUnusedFd *pUnused = 0;
5478
5479 /* Do not search for an unused file descriptor on vxworks. Not because
5480 ** vxworks would not benefit from the change (it might, we're not sure),
5481 ** but because no way to test it is currently available. It is better
5482 ** not to risk breaking vxworks support for the sake of such an obscure
5483 ** feature. */
5484#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005485 struct stat sStat; /* Results of stat() call */
5486
5487 /* A stat() call may fail for various reasons. If this happens, it is
5488 ** almost certain that an open() call on the same path will also fail.
5489 ** For this reason, if an error occurs in the stat() call here, it is
5490 ** ignored and -1 is returned. The caller will try to open a new file
5491 ** descriptor on the same path, fail, and return an error to SQLite.
5492 **
5493 ** Even if a subsequent open() call does succeed, the consequences of
peter.d.reid60ec9142014-09-06 16:39:46 +00005494 ** not searching for a reusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005495 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005496 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005497
5498 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005499 pInode = inodeList;
5500 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5501 || pInode->fileId.ino!=sStat.st_ino) ){
5502 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005503 }
drh8af6c222010-05-14 12:43:01 +00005504 if( pInode ){
dane946c392009-08-22 11:39:46 +00005505 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005506 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005507 pUnused = *pp;
5508 if( pUnused ){
5509 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005510 }
5511 }
5512 unixLeaveMutex();
5513 }
dane946c392009-08-22 11:39:46 +00005514#endif /* if !OS_VXWORKS */
5515 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005516}
danielk197717b90b52008-06-06 11:11:25 +00005517
5518/*
danddb0ac42010-07-14 14:48:58 +00005519** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005520** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005521** and a value suitable for passing as the third argument to open(2) is
5522** written to *pMode. If an IO error occurs, an SQLite error code is
5523** returned and the value of *pMode is not modified.
5524**
peter.d.reid60ec9142014-09-06 16:39:46 +00005525** In most cases, this routine sets *pMode to 0, which will become
drh8c815d12012-02-13 20:16:37 +00005526** an indication to robust_open() to create the file using
5527** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5528** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005529** this function queries the file-system for the permissions on the
5530** corresponding database file and sets *pMode to this value. Whenever
5531** possible, WAL and journal files are created using the same permissions
5532** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005533**
5534** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5535** original filename is unavailable. But 8_3_NAMES is only used for
5536** FAT filesystems and permissions do not matter there, so just use
5537** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005538*/
5539static int findCreateFileMode(
5540 const char *zPath, /* Path of file (possibly) being created */
5541 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005542 mode_t *pMode, /* OUT: Permissions to open file with */
5543 uid_t *pUid, /* OUT: uid to set on the file */
5544 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005545){
5546 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005547 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005548 *pUid = 0;
5549 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005550 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005551 char zDb[MAX_PATHNAME+1]; /* Database file path */
5552 int nDb; /* Number of valid bytes in zDb */
5553 struct stat sStat; /* Output of stat() on database file */
5554
dana0c989d2010-11-05 18:07:37 +00005555 /* zPath is a path to a WAL or journal file. The following block derives
5556 ** the path to the associated database file from zPath. This block handles
5557 ** the following naming conventions:
5558 **
5559 ** "<path to db>-journal"
5560 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005561 ** "<path to db>-journalNN"
5562 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005563 **
drhd337c5b2011-10-20 18:23:35 +00005564 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005565 ** used by the test_multiplex.c module.
5566 */
5567 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005568#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00005569 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00005570 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005571#else
5572 while( zPath[nDb]!='-' ){
5573 assert( nDb>0 );
5574 assert( zPath[nDb]!='\n' );
5575 nDb--;
5576 }
5577#endif
danddb0ac42010-07-14 14:48:58 +00005578 memcpy(zDb, zPath, nDb);
5579 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005580
drh58384f12011-07-28 00:14:45 +00005581 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005582 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005583 *pUid = sStat.st_uid;
5584 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005585 }else{
5586 rc = SQLITE_IOERR_FSTAT;
5587 }
5588 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5589 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005590 }
5591 return rc;
5592}
5593
5594/*
danielk1977ad94b582007-08-20 06:44:22 +00005595** Open the file zPath.
5596**
danielk1977b4b47412007-08-17 15:53:36 +00005597** Previously, the SQLite OS layer used three functions in place of this
5598** one:
5599**
5600** sqlite3OsOpenReadWrite();
5601** sqlite3OsOpenReadOnly();
5602** sqlite3OsOpenExclusive();
5603**
5604** These calls correspond to the following combinations of flags:
5605**
5606** ReadWrite() -> (READWRITE | CREATE)
5607** ReadOnly() -> (READONLY)
5608** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5609**
5610** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5611** true, the file was configured to be automatically deleted when the
5612** file handle closed. To achieve the same effect using this new
5613** interface, add the DELETEONCLOSE flag to those specified above for
5614** OpenExclusive().
5615*/
5616static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005617 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5618 const char *zPath, /* Pathname of file to be opened */
5619 sqlite3_file *pFile, /* The file descriptor to be filled in */
5620 int flags, /* Input flags to control the opening */
5621 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005622){
dan08da86a2009-08-21 17:18:03 +00005623 unixFile *p = (unixFile *)pFile;
5624 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005625 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005626 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005627 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005628 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005629 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005630
5631 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5632 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5633 int isCreate = (flags & SQLITE_OPEN_CREATE);
5634 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5635 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005636#if SQLITE_ENABLE_LOCKING_STYLE
5637 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5638#endif
drh3d4435b2011-08-26 20:55:50 +00005639#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5640 struct statfs fsInfo;
5641#endif
danielk1977b4b47412007-08-17 15:53:36 +00005642
danielk1977fee2d252007-08-18 10:59:19 +00005643 /* If creating a master or main-file journal, this function will open
5644 ** a file-descriptor on the directory too. The first time unixSync()
5645 ** is called the directory file descriptor will be fsync()ed and close()d.
5646 */
drh0059eae2011-08-08 23:48:40 +00005647 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005648 eType==SQLITE_OPEN_MASTER_JOURNAL
5649 || eType==SQLITE_OPEN_MAIN_JOURNAL
5650 || eType==SQLITE_OPEN_WAL
5651 ));
danielk1977fee2d252007-08-18 10:59:19 +00005652
danielk197717b90b52008-06-06 11:11:25 +00005653 /* If argument zPath is a NULL pointer, this function is required to open
5654 ** a temporary file. Use this buffer to store the file name in.
5655 */
drhc02a43a2012-01-10 23:18:38 +00005656 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005657 const char *zName = zPath;
5658
danielk1977fee2d252007-08-18 10:59:19 +00005659 /* Check the following statements are true:
5660 **
5661 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5662 ** (b) if CREATE is set, then READWRITE must also be set, and
5663 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005664 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005665 */
danielk1977b4b47412007-08-17 15:53:36 +00005666 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005667 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005668 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005669 assert(isDelete==0 || isCreate);
5670
danddb0ac42010-07-14 14:48:58 +00005671 /* The main DB, main journal, WAL file and master journal are never
5672 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005673 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5674 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5675 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005676 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005677
danielk1977fee2d252007-08-18 10:59:19 +00005678 /* Assert that the upper layer has set one of the "file-type" flags. */
5679 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5680 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5681 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005682 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005683 );
5684
drhb00d8622014-01-01 15:18:36 +00005685 /* Detect a pid change and reset the PRNG. There is a race condition
5686 ** here such that two or more threads all trying to open databases at
5687 ** the same instant might all reset the PRNG. But multiple resets
5688 ** are harmless.
5689 */
drh5ac93652015-03-21 20:59:43 +00005690 if( randomnessPid!=osGetpid(0) ){
5691 randomnessPid = osGetpid(0);
drhb00d8622014-01-01 15:18:36 +00005692 sqlite3_randomness(0,0);
5693 }
5694
dan08da86a2009-08-21 17:18:03 +00005695 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005696
dan08da86a2009-08-21 17:18:03 +00005697 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005698 UnixUnusedFd *pUnused;
5699 pUnused = findReusableFd(zName, flags);
5700 if( pUnused ){
5701 fd = pUnused->fd;
5702 }else{
drhf3cdcdc2015-04-29 16:50:28 +00005703 pUnused = sqlite3_malloc64(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005704 if( !pUnused ){
5705 return SQLITE_NOMEM;
5706 }
5707 }
5708 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005709
5710 /* Database filenames are double-zero terminated if they are not
5711 ** URIs with parameters. Hence, they can always be passed into
5712 ** sqlite3_uri_parameter(). */
5713 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5714
dan08da86a2009-08-21 17:18:03 +00005715 }else if( !zName ){
5716 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005717 assert(isDelete && !syncDir);
drhc02a43a2012-01-10 23:18:38 +00005718 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005719 if( rc!=SQLITE_OK ){
5720 return rc;
5721 }
5722 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005723
5724 /* Generated temporary filenames are always double-zero terminated
5725 ** for use by sqlite3_uri_parameter(). */
5726 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005727 }
5728
dan08da86a2009-08-21 17:18:03 +00005729 /* Determine the value of the flags parameter passed to POSIX function
5730 ** open(). These must be calculated even if open() is not called, as
5731 ** they may be stored as part of the file handle and used by the
5732 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005733 if( isReadonly ) openFlags |= O_RDONLY;
5734 if( isReadWrite ) openFlags |= O_RDWR;
5735 if( isCreate ) openFlags |= O_CREAT;
5736 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5737 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005738
danielk1977b4b47412007-08-17 15:53:36 +00005739 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005740 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005741 uid_t uid; /* Userid for the file */
5742 gid_t gid; /* Groupid for the file */
5743 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005744 if( rc!=SQLITE_OK ){
5745 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005746 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005747 return rc;
5748 }
drhad4f1e52011-03-04 15:43:57 +00005749 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005750 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
drh5a2d9702015-11-26 02:21:05 +00005751 assert( !isExclusive || (openFlags & O_CREAT)!=0 );
5752 if( fd<0 && errno!=EISDIR && isReadWrite ){
dan08da86a2009-08-21 17:18:03 +00005753 /* Failed to open the file for read/write access. Try read-only. */
5754 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005755 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005756 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005757 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005758 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005759 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005760 }
5761 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005762 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005763 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005764 }
drhac7c3ac2012-02-11 19:23:48 +00005765
5766 /* If this process is running as root and if creating a new rollback
5767 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005768 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005769 */
5770 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drh6226ca22015-11-24 15:06:28 +00005771 robustFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005772 }
danielk1977b4b47412007-08-17 15:53:36 +00005773 }
dan08da86a2009-08-21 17:18:03 +00005774 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005775 if( pOutFlags ){
5776 *pOutFlags = flags;
5777 }
5778
dane946c392009-08-22 11:39:46 +00005779 if( p->pUnused ){
5780 p->pUnused->fd = fd;
5781 p->pUnused->flags = flags;
5782 }
5783
danielk1977b4b47412007-08-17 15:53:36 +00005784 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005785#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005786 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00005787#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
5788 zPath = sqlite3_mprintf("%s", zName);
5789 if( zPath==0 ){
5790 robust_close(p, fd, __LINE__);
5791 return SQLITE_NOMEM;
5792 }
chw97185482008-11-17 08:05:31 +00005793#else
drh036ac7f2011-08-08 23:18:05 +00005794 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005795#endif
danielk1977b4b47412007-08-17 15:53:36 +00005796 }
drh41022642008-11-21 00:24:42 +00005797#if SQLITE_ENABLE_LOCKING_STYLE
5798 else{
dan08da86a2009-08-21 17:18:03 +00005799 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005800 }
5801#endif
5802
drhda0e7682008-07-30 15:27:54 +00005803 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005804
drh7ed97b92010-01-20 13:07:21 +00005805
5806#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005807 if( fstatfs(fd, &fsInfo) == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00005808 storeLastErrno(p, errno);
drh0e9365c2011-03-02 02:08:13 +00005809 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005810 return SQLITE_IOERR_ACCESS;
5811 }
5812 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5813 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5814 }
drh4bf66fd2015-02-19 02:43:02 +00005815 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
5816 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5817 }
drh7ed97b92010-01-20 13:07:21 +00005818#endif
drhc02a43a2012-01-10 23:18:38 +00005819
5820 /* Set up appropriate ctrlFlags */
5821 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5822 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5823 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5824 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5825 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5826
drh7ed97b92010-01-20 13:07:21 +00005827#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005828#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005829 isAutoProxy = 1;
5830#endif
5831 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005832 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5833 int useProxy = 0;
5834
dan08da86a2009-08-21 17:18:03 +00005835 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5836 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005837 if( envforce!=NULL ){
5838 useProxy = atoi(envforce)>0;
5839 }else{
aswiftaebf4132008-11-21 00:10:35 +00005840 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5841 }
5842 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005843 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005844 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005845 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005846 if( rc!=SQLITE_OK ){
5847 /* Use unixClose to clean up the resources added in fillInUnixFile
5848 ** and clear all the structure's references. Specifically,
5849 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5850 */
5851 unixClose(pFile);
5852 return rc;
5853 }
aswiftaebf4132008-11-21 00:10:35 +00005854 }
dane946c392009-08-22 11:39:46 +00005855 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005856 }
5857 }
5858#endif
5859
drhc02a43a2012-01-10 23:18:38 +00005860 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5861
dane946c392009-08-22 11:39:46 +00005862open_finished:
5863 if( rc!=SQLITE_OK ){
5864 sqlite3_free(p->pUnused);
5865 }
5866 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005867}
5868
dane946c392009-08-22 11:39:46 +00005869
danielk1977b4b47412007-08-17 15:53:36 +00005870/*
danielk1977fee2d252007-08-18 10:59:19 +00005871** Delete the file at zPath. If the dirSync argument is true, fsync()
5872** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005873*/
drh6b9d6dd2008-12-03 19:34:47 +00005874static int unixDelete(
5875 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5876 const char *zPath, /* Name of file to be deleted */
5877 int dirSync /* If true, fsync() directory after deleting file */
5878){
danielk1977fee2d252007-08-18 10:59:19 +00005879 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005880 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005881 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005882 if( osUnlink(zPath)==(-1) ){
drhbd945542014-08-13 11:39:42 +00005883 if( errno==ENOENT
5884#if OS_VXWORKS
drh19541f32014-09-01 13:37:55 +00005885 || osAccess(zPath,0)!=0
drhbd945542014-08-13 11:39:42 +00005886#endif
5887 ){
dan9fc5b4a2012-11-09 20:17:26 +00005888 rc = SQLITE_IOERR_DELETE_NOENT;
5889 }else{
drhb4308162012-11-09 21:40:02 +00005890 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005891 }
drhb4308162012-11-09 21:40:02 +00005892 return rc;
drh5d4feff2010-07-14 01:45:22 +00005893 }
danielk1977d39fa702008-10-16 13:27:40 +00005894#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005895 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005896 int fd;
drh90315a22011-08-10 01:52:12 +00005897 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005898 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005899#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005900 if( fsync(fd)==-1 )
5901#else
5902 if( fsync(fd) )
5903#endif
5904 {
dane18d4952011-02-21 11:46:24 +00005905 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005906 }
drh0e9365c2011-03-02 02:08:13 +00005907 robust_close(0, fd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00005908 }else{
5909 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00005910 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005911 }
5912 }
danielk1977d138dd82008-10-15 16:02:48 +00005913#endif
danielk1977fee2d252007-08-18 10:59:19 +00005914 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005915}
5916
danielk197790949c22007-08-17 16:50:38 +00005917/*
mistachkin48864df2013-03-21 21:20:32 +00005918** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00005919** test performed depends on the value of flags:
5920**
5921** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5922** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5923** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5924**
5925** Otherwise return 0.
5926*/
danielk1977861f7452008-06-05 11:39:11 +00005927static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005928 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5929 const char *zPath, /* Path of the file to examine */
5930 int flags, /* What do we want to learn about the zPath file? */
5931 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005932){
danielk1977397d65f2008-11-19 11:35:39 +00005933 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005934 SimulateIOError( return SQLITE_IOERR_ACCESS; );
drhd260b5b2015-11-25 18:03:33 +00005935 assert( pResOut!=0 );
danielk1977b4b47412007-08-17 15:53:36 +00005936
drhd260b5b2015-11-25 18:03:33 +00005937 /* The spec says there are three possible values for flags. But only
5938 ** two of them are actually used */
5939 assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
5940
5941 if( flags==SQLITE_ACCESS_EXISTS ){
dan83acd422010-06-18 11:10:06 +00005942 struct stat buf;
drhd260b5b2015-11-25 18:03:33 +00005943 *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
5944 }else{
5945 *pResOut = osAccess(zPath, W_OK|R_OK)==0;
dan83acd422010-06-18 11:10:06 +00005946 }
danielk1977861f7452008-06-05 11:39:11 +00005947 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005948}
5949
danielk1977b4b47412007-08-17 15:53:36 +00005950
5951/*
5952** Turn a relative pathname into a full pathname. The relative path
5953** is stored as a nul-terminated string in the buffer pointed to by
5954** zPath.
5955**
5956** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5957** (in this case, MAX_PATHNAME bytes). The full-path is written to
5958** this buffer before returning.
5959*/
danielk1977adfb9b02007-09-17 07:02:56 +00005960static int unixFullPathname(
5961 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5962 const char *zPath, /* Possibly relative input path */
5963 int nOut, /* Size of output buffer in bytes */
5964 char *zOut /* Output buffer */
5965){
dan245fdc62015-10-31 17:58:33 +00005966 int nByte;
danielk1977843e65f2007-09-01 16:16:15 +00005967
5968 /* It's odd to simulate an io-error here, but really this is just
5969 ** using the io-error infrastructure to test that SQLite handles this
5970 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005971 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005972 */
5973 SimulateIOError( return SQLITE_ERROR );
5974
drh153c62c2007-08-24 03:51:33 +00005975 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005976 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005977
dan245fdc62015-10-31 17:58:33 +00005978 /* Attempt to resolve the path as if it were a symbolic link. If it is
5979 ** a symbolic link, the resolved path is stored in buffer zOut[]. Or, if
5980 ** the identified file is not a symbolic link or does not exist, then
5981 ** zPath is copied directly into zOut. Either way, nByte is left set to
5982 ** the size of the string copied into zOut[] in bytes. */
5983 nByte = osReadlink(zPath, zOut, nOut-1);
5984 if( nByte<0 ){
5985 if( errno!=EINVAL && errno!=ENOENT ){
5986 return unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zPath);
5987 }
drhd260b5b2015-11-25 18:03:33 +00005988 sqlite3_snprintf(nOut, zOut, "%s", zPath);
dan245fdc62015-10-31 17:58:33 +00005989 nByte = sqlite3Strlen30(zOut);
danielk1977b4b47412007-08-17 15:53:36 +00005990 }else{
dan245fdc62015-10-31 17:58:33 +00005991 zOut[nByte] = '\0';
5992 }
5993
5994 /* If buffer zOut[] now contains an absolute path there is nothing more
5995 ** to do. If it contains a relative path, do the following:
5996 **
5997 ** * move the relative path string so that it is at the end of th
5998 ** zOut[] buffer.
5999 ** * Call getcwd() to read the path of the current working directory
6000 ** into the start of the zOut[] buffer.
6001 ** * Append a '/' character to the cwd string and move the
6002 ** relative path back within the buffer so that it immediately
6003 ** follows the '/'.
6004 **
6005 ** This code is written so that if the combination of the CWD and relative
6006 ** path are larger than the allocated size of zOut[] the CWD is silently
6007 ** truncated to make it fit. This is Ok, as SQLite refuses to open any
6008 ** file for which this function returns a full path larger than (nOut-8)
6009 ** bytes in size. */
6010 if( zOut[0]!='/' ){
danielk1977b4b47412007-08-17 15:53:36 +00006011 int nCwd;
dan245fdc62015-10-31 17:58:33 +00006012 int nRem = nOut-nByte-1;
6013 memmove(&zOut[nRem], zOut, nByte+1);
6014 zOut[nRem-1] = '\0';
6015 if( osGetcwd(zOut, nRem-1)==0 ){
dane18d4952011-02-21 11:46:24 +00006016 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006017 }
dan245fdc62015-10-31 17:58:33 +00006018 nCwd = sqlite3Strlen30(zOut);
6019 assert( nCwd<=nRem-1 );
6020 zOut[nCwd] = '/';
6021 memmove(&zOut[nCwd+1], &zOut[nRem], nByte+1);
danielk1977b4b47412007-08-17 15:53:36 +00006022 }
dan245fdc62015-10-31 17:58:33 +00006023
danielk1977b4b47412007-08-17 15:53:36 +00006024 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006025}
6026
drh0ccebe72005-06-07 22:22:50 +00006027
drh761df872006-12-21 01:29:22 +00006028#ifndef SQLITE_OMIT_LOAD_EXTENSION
6029/*
6030** Interfaces for opening a shared library, finding entry points
6031** within the shared library, and closing the shared library.
6032*/
6033#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00006034static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6035 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00006036 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6037}
danielk197795c8a542007-09-01 06:51:27 +00006038
6039/*
6040** SQLite calls this function immediately after a call to unixDlSym() or
6041** unixDlOpen() fails (returns a null pointer). If a more detailed error
6042** message is available, it is written to zBufOut. If no error message
6043** is available, zBufOut is left unmodified and SQLite uses a default
6044** error message.
6045*/
danielk1977397d65f2008-11-19 11:35:39 +00006046static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006047 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006048 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006049 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006050 zErr = dlerror();
6051 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006052 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006053 }
drh6c7d5c52008-11-21 20:32:33 +00006054 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006055}
drh1875f7a2008-12-08 18:19:17 +00006056static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6057 /*
6058 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6059 ** cast into a pointer to a function. And yet the library dlsym() routine
6060 ** returns a void* which is really a pointer to a function. So how do we
6061 ** use dlsym() with -pedantic-errors?
6062 **
6063 ** Variable x below is defined to be a pointer to a function taking
6064 ** parameters void* and const char* and returning a pointer to a function.
6065 ** We initialize x by assigning it a pointer to the dlsym() function.
6066 ** (That assignment requires a cast.) Then we call the function that
6067 ** x points to.
6068 **
6069 ** This work-around is unlikely to work correctly on any system where
6070 ** you really cannot cast a function pointer into void*. But then, on the
6071 ** other hand, dlsym() will not work on such a system either, so we have
6072 ** not really lost anything.
6073 */
6074 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006075 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006076 x = (void(*(*)(void*,const char*))(void))dlsym;
6077 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006078}
danielk1977397d65f2008-11-19 11:35:39 +00006079static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6080 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006081 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006082}
danielk1977b4b47412007-08-17 15:53:36 +00006083#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6084 #define unixDlOpen 0
6085 #define unixDlError 0
6086 #define unixDlSym 0
6087 #define unixDlClose 0
6088#endif
6089
6090/*
danielk197790949c22007-08-17 16:50:38 +00006091** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006092*/
danielk1977397d65f2008-11-19 11:35:39 +00006093static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6094 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006095 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006096
drhbbd42a62004-05-22 17:41:58 +00006097 /* We have to initialize zBuf to prevent valgrind from reporting
6098 ** errors. The reports issued by valgrind are incorrect - we would
6099 ** prefer that the randomness be increased by making use of the
6100 ** uninitialized space in zBuf - but valgrind errors tend to worry
6101 ** some users. Rather than argue, it seems easier just to initialize
6102 ** the whole array and silence valgrind, even if that means less randomness
6103 ** in the random seed.
6104 **
6105 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006106 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006107 ** tests repeatable.
6108 */
danielk1977b4b47412007-08-17 15:53:36 +00006109 memset(zBuf, 0, nBuf);
drh5ac93652015-03-21 20:59:43 +00006110 randomnessPid = osGetpid(0);
drh6a412b82015-04-30 12:31:49 +00006111#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
drhbbd42a62004-05-22 17:41:58 +00006112 {
drhb00d8622014-01-01 15:18:36 +00006113 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006114 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006115 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006116 time_t t;
6117 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006118 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006119 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6120 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6121 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006122 }else{
drhc18b4042012-02-10 03:10:27 +00006123 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006124 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006125 }
drhbbd42a62004-05-22 17:41:58 +00006126 }
6127#endif
drh72cbd072008-10-14 17:58:38 +00006128 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006129}
6130
danielk1977b4b47412007-08-17 15:53:36 +00006131
drhbbd42a62004-05-22 17:41:58 +00006132/*
6133** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006134** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006135** The return value is the number of microseconds of sleep actually
6136** requested from the underlying operating system, a number which
6137** might be greater than or equal to the argument, but not less
6138** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006139*/
danielk1977397d65f2008-11-19 11:35:39 +00006140static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006141#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006142 struct timespec sp;
6143
6144 sp.tv_sec = microseconds / 1000000;
6145 sp.tv_nsec = (microseconds % 1000000) * 1000;
6146 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006147 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006148 return microseconds;
6149#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006150 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006151 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006152 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006153#else
danielk1977b4b47412007-08-17 15:53:36 +00006154 int seconds = (microseconds+999999)/1000000;
6155 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006156 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006157 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006158#endif
drh88f474a2006-01-02 20:00:12 +00006159}
6160
6161/*
drh6b9d6dd2008-12-03 19:34:47 +00006162** The following variable, if set to a non-zero value, is interpreted as
6163** the number of seconds since 1970 and is used to set the result of
6164** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006165*/
6166#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006167int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006168#endif
6169
6170/*
drhb7e8ea22010-05-03 14:32:30 +00006171** Find the current time (in Universal Coordinated Time). Write into *piNow
6172** the current time and date as a Julian Day number times 86_400_000. In
6173** other words, write into *piNow the number of milliseconds since the Julian
6174** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6175** proleptic Gregorian calendar.
6176**
drh31702252011-10-12 23:13:43 +00006177** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6178** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006179*/
6180static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6181 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006182 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006183#if defined(NO_GETTOD)
6184 time_t t;
6185 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006186 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006187#elif OS_VXWORKS
6188 struct timespec sNow;
6189 clock_gettime(CLOCK_REALTIME, &sNow);
6190 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6191#else
6192 struct timeval sNow;
drh970942e2015-11-25 23:13:14 +00006193 (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
6194 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
drhb7e8ea22010-05-03 14:32:30 +00006195#endif
6196
6197#ifdef SQLITE_TEST
6198 if( sqlite3_current_time ){
6199 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6200 }
6201#endif
6202 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006203 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006204}
6205
drh5337dac2015-11-25 15:15:03 +00006206#if 0 /* Not used */
drhb7e8ea22010-05-03 14:32:30 +00006207/*
drhbbd42a62004-05-22 17:41:58 +00006208** Find the current time (in Universal Coordinated Time). Write the
6209** current time and date as a Julian Day number into *prNow and
6210** return 0. Return 1 if the time and date cannot be found.
6211*/
danielk1977397d65f2008-11-19 11:35:39 +00006212static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006213 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006214 int rc;
drhff828942010-06-26 21:34:06 +00006215 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006216 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006217 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006218 return rc;
drhbbd42a62004-05-22 17:41:58 +00006219}
drh5337dac2015-11-25 15:15:03 +00006220#else
6221# define unixCurrentTime 0
6222#endif
danielk1977b4b47412007-08-17 15:53:36 +00006223
drh5337dac2015-11-25 15:15:03 +00006224#if 0 /* Not used */
drh6b9d6dd2008-12-03 19:34:47 +00006225/*
6226** We added the xGetLastError() method with the intention of providing
6227** better low-level error messages when operating-system problems come up
6228** during SQLite operation. But so far, none of that has been implemented
6229** in the core. So this routine is never called. For now, it is merely
6230** a place-holder.
6231*/
danielk1977397d65f2008-11-19 11:35:39 +00006232static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6233 UNUSED_PARAMETER(NotUsed);
6234 UNUSED_PARAMETER(NotUsed2);
6235 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00006236 return 0;
6237}
drh5337dac2015-11-25 15:15:03 +00006238#else
6239# define unixGetLastError 0
6240#endif
danielk1977bcb97fe2008-06-06 15:49:29 +00006241
drhf2424c52010-04-26 00:04:55 +00006242
6243/*
drh734c9862008-11-28 15:37:20 +00006244************************ End of sqlite3_vfs methods ***************************
6245******************************************************************************/
6246
drh715ff302008-12-03 22:32:44 +00006247/******************************************************************************
6248************************** Begin Proxy Locking ********************************
6249**
6250** Proxy locking is a "uber-locking-method" in this sense: It uses the
6251** other locking methods on secondary lock files. Proxy locking is a
6252** meta-layer over top of the primitive locking implemented above. For
6253** this reason, the division that implements of proxy locking is deferred
6254** until late in the file (here) after all of the other I/O methods have
6255** been defined - so that the primitive locking methods are available
6256** as services to help with the implementation of proxy locking.
6257**
6258****
6259**
6260** The default locking schemes in SQLite use byte-range locks on the
6261** database file to coordinate safe, concurrent access by multiple readers
6262** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6263** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6264** as POSIX read & write locks over fixed set of locations (via fsctl),
6265** on AFP and SMB only exclusive byte-range locks are available via fsctl
6266** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6267** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6268** address in the shared range is taken for a SHARED lock, the entire
6269** shared range is taken for an EXCLUSIVE lock):
6270**
drhf2f105d2012-08-20 15:53:54 +00006271** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006272** RESERVED_BYTE 0x40000001
6273** SHARED_RANGE 0x40000002 -> 0x40000200
6274**
6275** This works well on the local file system, but shows a nearly 100x
6276** slowdown in read performance on AFP because the AFP client disables
6277** the read cache when byte-range locks are present. Enabling the read
6278** cache exposes a cache coherency problem that is present on all OS X
6279** supported network file systems. NFS and AFP both observe the
6280** close-to-open semantics for ensuring cache coherency
6281** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6282** address the requirements for concurrent database access by multiple
6283** readers and writers
6284** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6285**
6286** To address the performance and cache coherency issues, proxy file locking
6287** changes the way database access is controlled by limiting access to a
6288** single host at a time and moving file locks off of the database file
6289** and onto a proxy file on the local file system.
6290**
6291**
6292** Using proxy locks
6293** -----------------
6294**
6295** C APIs
6296**
drh4bf66fd2015-02-19 02:43:02 +00006297** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
drh715ff302008-12-03 22:32:44 +00006298** <proxy_path> | ":auto:");
drh4bf66fd2015-02-19 02:43:02 +00006299** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6300** &<proxy_path>);
drh715ff302008-12-03 22:32:44 +00006301**
6302**
6303** SQL pragmas
6304**
6305** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6306** PRAGMA [database.]lock_proxy_file
6307**
6308** Specifying ":auto:" means that if there is a conch file with a matching
6309** host ID in it, the proxy path in the conch file will be used, otherwise
6310** a proxy path based on the user's temp dir
6311** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6312** actual proxy file name is generated from the name and path of the
6313** database file. For example:
6314**
6315** For database path "/Users/me/foo.db"
6316** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6317**
6318** Once a lock proxy is configured for a database connection, it can not
6319** be removed, however it may be switched to a different proxy path via
6320** the above APIs (assuming the conch file is not being held by another
6321** connection or process).
6322**
6323**
6324** How proxy locking works
6325** -----------------------
6326**
6327** Proxy file locking relies primarily on two new supporting files:
6328**
6329** * conch file to limit access to the database file to a single host
6330** at a time
6331**
6332** * proxy file to act as a proxy for the advisory locks normally
6333** taken on the database
6334**
6335** The conch file - to use a proxy file, sqlite must first "hold the conch"
6336** by taking an sqlite-style shared lock on the conch file, reading the
6337** contents and comparing the host's unique host ID (see below) and lock
6338** proxy path against the values stored in the conch. The conch file is
6339** stored in the same directory as the database file and the file name
6340** is patterned after the database file name as ".<databasename>-conch".
peter.d.reid60ec9142014-09-06 16:39:46 +00006341** If the conch file does not exist, or its contents do not match the
drh715ff302008-12-03 22:32:44 +00006342** host ID and/or proxy path, then the lock is escalated to an exclusive
6343** lock and the conch file contents is updated with the host ID and proxy
6344** path and the lock is downgraded to a shared lock again. If the conch
6345** is held by another process (with a shared lock), the exclusive lock
6346** will fail and SQLITE_BUSY is returned.
6347**
6348** The proxy file - a single-byte file used for all advisory file locks
6349** normally taken on the database file. This allows for safe sharing
6350** of the database file for multiple readers and writers on the same
6351** host (the conch ensures that they all use the same local lock file).
6352**
drh715ff302008-12-03 22:32:44 +00006353** Requesting the lock proxy does not immediately take the conch, it is
6354** only taken when the first request to lock database file is made.
6355** This matches the semantics of the traditional locking behavior, where
6356** opening a connection to a database file does not take a lock on it.
6357** The shared lock and an open file descriptor are maintained until
6358** the connection to the database is closed.
6359**
6360** The proxy file and the lock file are never deleted so they only need
6361** to be created the first time they are used.
6362**
6363** Configuration options
6364** ---------------------
6365**
6366** SQLITE_PREFER_PROXY_LOCKING
6367**
6368** Database files accessed on non-local file systems are
6369** automatically configured for proxy locking, lock files are
6370** named automatically using the same logic as
6371** PRAGMA lock_proxy_file=":auto:"
6372**
6373** SQLITE_PROXY_DEBUG
6374**
6375** Enables the logging of error messages during host id file
6376** retrieval and creation
6377**
drh715ff302008-12-03 22:32:44 +00006378** LOCKPROXYDIR
6379**
6380** Overrides the default directory used for lock proxy files that
6381** are named automatically via the ":auto:" setting
6382**
6383** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6384**
6385** Permissions to use when creating a directory for storing the
6386** lock proxy files, only used when LOCKPROXYDIR is not set.
6387**
6388**
6389** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6390** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6391** force proxy locking to be used for every database file opened, and 0
6392** will force automatic proxy locking to be disabled for all database
drh4bf66fd2015-02-19 02:43:02 +00006393** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
drh715ff302008-12-03 22:32:44 +00006394** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6395*/
6396
6397/*
6398** Proxy locking is only available on MacOSX
6399*/
drhd2cb50b2009-01-09 21:41:17 +00006400#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006401
drh715ff302008-12-03 22:32:44 +00006402/*
6403** The proxyLockingContext has the path and file structures for the remote
6404** and local proxy files in it
6405*/
6406typedef struct proxyLockingContext proxyLockingContext;
6407struct proxyLockingContext {
6408 unixFile *conchFile; /* Open conch file */
6409 char *conchFilePath; /* Name of the conch file */
6410 unixFile *lockProxy; /* Open proxy lock file */
6411 char *lockProxyPath; /* Name of the proxy lock file */
6412 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006413 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh4bf66fd2015-02-19 02:43:02 +00006414 int nFails; /* Number of conch taking failures */
drh715ff302008-12-03 22:32:44 +00006415 void *oldLockingContext; /* Original lockingcontext to restore on close */
6416 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6417};
6418
drh7ed97b92010-01-20 13:07:21 +00006419/*
6420** The proxy lock file path for the database at dbPath is written into lPath,
6421** which must point to valid, writable memory large enough for a maxLen length
6422** file path.
drh715ff302008-12-03 22:32:44 +00006423*/
drh715ff302008-12-03 22:32:44 +00006424static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6425 int len;
6426 int dbLen;
6427 int i;
6428
6429#ifdef LOCKPROXYDIR
6430 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6431#else
6432# ifdef _CS_DARWIN_USER_TEMP_DIR
6433 {
drh7ed97b92010-01-20 13:07:21 +00006434 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006435 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006436 lPath, errno, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006437 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006438 }
drh7ed97b92010-01-20 13:07:21 +00006439 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006440 }
6441# else
6442 len = strlcpy(lPath, "/tmp/", maxLen);
6443# endif
6444#endif
6445
6446 if( lPath[len-1]!='/' ){
6447 len = strlcat(lPath, "/", maxLen);
6448 }
6449
6450 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006451 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006452 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006453 char c = dbPath[i];
6454 lPath[i+len] = (c=='/')?'_':c;
6455 }
6456 lPath[i+len]='\0';
6457 strlcat(lPath, ":auto:", maxLen);
drh5ac93652015-03-21 20:59:43 +00006458 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006459 return SQLITE_OK;
6460}
6461
drh7ed97b92010-01-20 13:07:21 +00006462/*
6463 ** Creates the lock file and any missing directories in lockPath
6464 */
6465static int proxyCreateLockPath(const char *lockPath){
6466 int i, len;
6467 char buf[MAXPATHLEN];
6468 int start = 0;
6469
6470 assert(lockPath!=NULL);
6471 /* try to create all the intermediate directories */
6472 len = (int)strlen(lockPath);
6473 buf[0] = lockPath[0];
6474 for( i=1; i<len; i++ ){
6475 if( lockPath[i] == '/' && (i - start > 0) ){
6476 /* only mkdir if leaf dir != "." or "/" or ".." */
6477 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6478 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6479 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006480 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006481 int err=errno;
6482 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006483 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006484 "'%s' proxy lock path=%s pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006485 buf, strerror(err), lockPath, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006486 return err;
6487 }
6488 }
6489 }
6490 start=i+1;
6491 }
6492 buf[i] = lockPath[i];
6493 }
drh62aaa6c2015-11-21 17:27:42 +00006494 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006495 return 0;
6496}
6497
drh715ff302008-12-03 22:32:44 +00006498/*
6499** Create a new VFS file descriptor (stored in memory obtained from
6500** sqlite3_malloc) and open the file named "path" in the file descriptor.
6501**
6502** The caller is responsible not only for closing the file descriptor
6503** but also for freeing the memory associated with the file descriptor.
6504*/
drh7ed97b92010-01-20 13:07:21 +00006505static int proxyCreateUnixFile(
6506 const char *path, /* path for the new unixFile */
6507 unixFile **ppFile, /* unixFile created and returned by ref */
6508 int islockfile /* if non zero missing dirs will be created */
6509) {
6510 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006511 unixFile *pNew;
6512 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006513 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006514 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006515 int terrno = 0;
6516 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006517
drh7ed97b92010-01-20 13:07:21 +00006518 /* 1. first try to open/create the file
6519 ** 2. if that fails, and this is a lock file (not-conch), try creating
6520 ** the parent directories and then try again.
6521 ** 3. if that fails, try to open the file read-only
6522 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6523 */
6524 pUnused = findReusableFd(path, openFlags);
6525 if( pUnused ){
6526 fd = pUnused->fd;
6527 }else{
drhf3cdcdc2015-04-29 16:50:28 +00006528 pUnused = sqlite3_malloc64(sizeof(*pUnused));
drh7ed97b92010-01-20 13:07:21 +00006529 if( !pUnused ){
6530 return SQLITE_NOMEM;
6531 }
6532 }
6533 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006534 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006535 terrno = errno;
6536 if( fd<0 && errno==ENOENT && islockfile ){
6537 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006538 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006539 }
6540 }
6541 }
6542 if( fd<0 ){
6543 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006544 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006545 terrno = errno;
6546 }
6547 if( fd<0 ){
6548 if( islockfile ){
6549 return SQLITE_BUSY;
6550 }
6551 switch (terrno) {
6552 case EACCES:
6553 return SQLITE_PERM;
6554 case EIO:
6555 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6556 default:
drh9978c972010-02-23 17:36:32 +00006557 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006558 }
6559 }
6560
drhf3cdcdc2015-04-29 16:50:28 +00006561 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
drh7ed97b92010-01-20 13:07:21 +00006562 if( pNew==NULL ){
6563 rc = SQLITE_NOMEM;
6564 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006565 }
6566 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006567 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006568 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006569 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006570 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006571 pUnused->fd = fd;
6572 pUnused->flags = openFlags;
6573 pNew->pUnused = pUnused;
6574
drhc02a43a2012-01-10 23:18:38 +00006575 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006576 if( rc==SQLITE_OK ){
6577 *ppFile = pNew;
6578 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006579 }
drh7ed97b92010-01-20 13:07:21 +00006580end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006581 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006582 sqlite3_free(pNew);
6583 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006584 return rc;
6585}
6586
drh7ed97b92010-01-20 13:07:21 +00006587#ifdef SQLITE_TEST
6588/* simulate multiple hosts by creating unique hostid file paths */
6589int sqlite3_hostid_num = 0;
6590#endif
6591
6592#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6593
drh6bca6512015-04-13 23:05:28 +00006594#ifdef HAVE_GETHOSTUUID
drh0ab216a2010-07-02 17:10:40 +00006595/* Not always defined in the headers as it ought to be */
6596extern int gethostuuid(uuid_t id, const struct timespec *wait);
drh6bca6512015-04-13 23:05:28 +00006597#endif
drh0ab216a2010-07-02 17:10:40 +00006598
drh7ed97b92010-01-20 13:07:21 +00006599/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6600** bytes of writable memory.
6601*/
6602static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006603 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6604 memset(pHostID, 0, PROXY_HOSTIDLEN);
drh6bca6512015-04-13 23:05:28 +00006605#ifdef HAVE_GETHOSTUUID
drh29ecd8a2010-12-21 00:16:40 +00006606 {
drh4bf66fd2015-02-19 02:43:02 +00006607 struct timespec timeout = {1, 0}; /* 1 sec timeout */
drh29ecd8a2010-12-21 00:16:40 +00006608 if( gethostuuid(pHostID, &timeout) ){
6609 int err = errno;
6610 if( pError ){
6611 *pError = err;
6612 }
6613 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006614 }
drh7ed97b92010-01-20 13:07:21 +00006615 }
drh3d4435b2011-08-26 20:55:50 +00006616#else
6617 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006618#endif
drh7ed97b92010-01-20 13:07:21 +00006619#ifdef SQLITE_TEST
6620 /* simulate multiple hosts by creating unique hostid file paths */
6621 if( sqlite3_hostid_num != 0){
6622 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6623 }
6624#endif
6625
6626 return SQLITE_OK;
6627}
6628
6629/* The conch file contains the header, host id and lock file path
6630 */
6631#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6632#define PROXY_HEADERLEN 1 /* conch file header length */
6633#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6634#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6635
6636/*
6637** Takes an open conch file, copies the contents to a new path and then moves
6638** it back. The newly created file's file descriptor is assigned to the
6639** conch file structure and finally the original conch file descriptor is
6640** closed. Returns zero if successful.
6641*/
6642static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6643 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6644 unixFile *conchFile = pCtx->conchFile;
6645 char tPath[MAXPATHLEN];
6646 char buf[PROXY_MAXCONCHLEN];
6647 char *cPath = pCtx->conchFilePath;
6648 size_t readLen = 0;
6649 size_t pathLen = 0;
6650 char errmsg[64] = "";
6651 int fd = -1;
6652 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006653 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006654
6655 /* create a new path by replace the trailing '-conch' with '-break' */
6656 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6657 if( pathLen>MAXPATHLEN || pathLen<6 ||
6658 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006659 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006660 goto end_breaklock;
6661 }
6662 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006663 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006664 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006665 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006666 goto end_breaklock;
6667 }
6668 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006669 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006670 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006671 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006672 goto end_breaklock;
6673 }
drhe562be52011-03-02 18:01:10 +00006674 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006675 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006676 goto end_breaklock;
6677 }
6678 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006679 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006680 goto end_breaklock;
6681 }
6682 rc = 0;
6683 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006684 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006685 conchFile->h = fd;
6686 conchFile->openFlags = O_RDWR | O_CREAT;
6687
6688end_breaklock:
6689 if( rc ){
6690 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006691 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006692 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006693 }
6694 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6695 }
6696 return rc;
6697}
6698
6699/* Take the requested lock on the conch file and break a stale lock if the
6700** host id matches.
6701*/
6702static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6703 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6704 unixFile *conchFile = pCtx->conchFile;
6705 int rc = SQLITE_OK;
6706 int nTries = 0;
6707 struct timespec conchModTime;
6708
drh3d4435b2011-08-26 20:55:50 +00006709 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006710 do {
6711 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6712 nTries ++;
6713 if( rc==SQLITE_BUSY ){
6714 /* If the lock failed (busy):
6715 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6716 * 2nd try: fail if the mod time changed or host id is different, wait
6717 * 10 sec and try again
6718 * 3rd try: break the lock unless the mod time has changed.
6719 */
6720 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006721 if( osFstat(conchFile->h, &buf) ){
drh4bf66fd2015-02-19 02:43:02 +00006722 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006723 return SQLITE_IOERR_LOCK;
6724 }
6725
6726 if( nTries==1 ){
6727 conchModTime = buf.st_mtimespec;
6728 usleep(500000); /* wait 0.5 sec and try the lock again*/
6729 continue;
6730 }
6731
6732 assert( nTries>1 );
6733 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6734 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6735 return SQLITE_BUSY;
6736 }
6737
6738 if( nTries==2 ){
6739 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006740 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006741 if( len<0 ){
drh4bf66fd2015-02-19 02:43:02 +00006742 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006743 return SQLITE_IOERR_LOCK;
6744 }
6745 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6746 /* don't break the lock if the host id doesn't match */
6747 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6748 return SQLITE_BUSY;
6749 }
6750 }else{
6751 /* don't break the lock on short read or a version mismatch */
6752 return SQLITE_BUSY;
6753 }
6754 usleep(10000000); /* wait 10 sec and try the lock again */
6755 continue;
6756 }
6757
6758 assert( nTries==3 );
6759 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6760 rc = SQLITE_OK;
6761 if( lockType==EXCLUSIVE_LOCK ){
drhe6d41732015-02-21 00:49:00 +00006762 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
drh7ed97b92010-01-20 13:07:21 +00006763 }
6764 if( !rc ){
6765 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6766 }
6767 }
6768 }
6769 } while( rc==SQLITE_BUSY && nTries<3 );
6770
6771 return rc;
6772}
6773
6774/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006775** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6776** lockPath means that the lockPath in the conch file will be used if the
6777** host IDs match, or a new lock path will be generated automatically
6778** and written to the conch file.
6779*/
6780static int proxyTakeConch(unixFile *pFile){
6781 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6782
drh7ed97b92010-01-20 13:07:21 +00006783 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006784 return SQLITE_OK;
6785 }else{
6786 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006787 uuid_t myHostID;
6788 int pError = 0;
6789 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006790 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006791 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006792 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006793 int createConch = 0;
6794 int hostIdMatch = 0;
6795 int readLen = 0;
6796 int tryOldLockPath = 0;
6797 int forceNewLockPath = 0;
6798
drh308c2a52010-05-14 11:30:18 +00006799 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
drh91eb93c2015-03-03 19:56:20 +00006800 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00006801 osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006802
drh7ed97b92010-01-20 13:07:21 +00006803 rc = proxyGetHostID(myHostID, &pError);
6804 if( (rc&0xff)==SQLITE_IOERR ){
drh4bf66fd2015-02-19 02:43:02 +00006805 storeLastErrno(pFile, pError);
drh7ed97b92010-01-20 13:07:21 +00006806 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006807 }
drh7ed97b92010-01-20 13:07:21 +00006808 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006809 if( rc!=SQLITE_OK ){
6810 goto end_takeconch;
6811 }
drh7ed97b92010-01-20 13:07:21 +00006812 /* read the existing conch file */
6813 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6814 if( readLen<0 ){
6815 /* I/O error: lastErrno set by seekAndRead */
drh4bf66fd2015-02-19 02:43:02 +00006816 storeLastErrno(pFile, conchFile->lastErrno);
drh7ed97b92010-01-20 13:07:21 +00006817 rc = SQLITE_IOERR_READ;
6818 goto end_takeconch;
6819 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6820 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6821 /* a short read or version format mismatch means we need to create a new
6822 ** conch file.
6823 */
6824 createConch = 1;
6825 }
6826 /* if the host id matches and the lock path already exists in the conch
6827 ** we'll try to use the path there, if we can't open that path, we'll
6828 ** retry with a new auto-generated path
6829 */
6830 do { /* in case we need to try again for an :auto: named lock file */
6831
6832 if( !createConch && !forceNewLockPath ){
6833 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6834 PROXY_HOSTIDLEN);
6835 /* if the conch has data compare the contents */
6836 if( !pCtx->lockProxyPath ){
6837 /* for auto-named local lock file, just check the host ID and we'll
6838 ** use the local lock file path that's already in there
6839 */
6840 if( hostIdMatch ){
6841 size_t pathLen = (readLen - PROXY_PATHINDEX);
6842
6843 if( pathLen>=MAXPATHLEN ){
6844 pathLen=MAXPATHLEN-1;
6845 }
6846 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6847 lockPath[pathLen] = 0;
6848 tempLockPath = lockPath;
6849 tryOldLockPath = 1;
6850 /* create a copy of the lock path if the conch is taken */
6851 goto end_takeconch;
6852 }
6853 }else if( hostIdMatch
6854 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6855 readLen-PROXY_PATHINDEX)
6856 ){
6857 /* conch host and lock path match */
6858 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006859 }
drh7ed97b92010-01-20 13:07:21 +00006860 }
6861
6862 /* if the conch isn't writable and doesn't match, we can't take it */
6863 if( (conchFile->openFlags&O_RDWR) == 0 ){
6864 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006865 goto end_takeconch;
6866 }
drh7ed97b92010-01-20 13:07:21 +00006867
6868 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006869 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006870 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6871 tempLockPath = lockPath;
6872 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006873 }
drh7ed97b92010-01-20 13:07:21 +00006874
6875 /* update conch with host and path (this will fail if other process
6876 ** has a shared lock already), if the host id matches, use the big
6877 ** stick.
drh715ff302008-12-03 22:32:44 +00006878 */
drh7ed97b92010-01-20 13:07:21 +00006879 futimes(conchFile->h, NULL);
6880 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006881 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006882 /* We are trying for an exclusive lock but another thread in this
6883 ** same process is still holding a shared lock. */
6884 rc = SQLITE_BUSY;
6885 } else {
6886 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006887 }
drh715ff302008-12-03 22:32:44 +00006888 }else{
drh4bf66fd2015-02-19 02:43:02 +00006889 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006890 }
drh7ed97b92010-01-20 13:07:21 +00006891 if( rc==SQLITE_OK ){
6892 char writeBuffer[PROXY_MAXCONCHLEN];
6893 int writeSize = 0;
6894
6895 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6896 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6897 if( pCtx->lockProxyPath!=NULL ){
drh4bf66fd2015-02-19 02:43:02 +00006898 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
6899 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00006900 }else{
6901 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6902 }
6903 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006904 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006905 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6906 fsync(conchFile->h);
6907 /* If we created a new conch file (not just updated the contents of a
6908 ** valid conch file), try to match the permissions of the database
6909 */
6910 if( rc==SQLITE_OK && createConch ){
6911 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006912 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006913 if( err==0 ){
6914 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6915 S_IROTH|S_IWOTH);
6916 /* try to match the database file R/W permissions, ignore failure */
6917#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006918 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006919#else
drhff812312011-02-23 13:33:46 +00006920 do{
drhe562be52011-03-02 18:01:10 +00006921 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006922 }while( rc==(-1) && errno==EINTR );
6923 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006924 int code = errno;
6925 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6926 cmode, code, strerror(code));
6927 } else {
6928 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6929 }
6930 }else{
6931 int code = errno;
6932 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6933 err, code, strerror(code));
6934#endif
6935 }
drh715ff302008-12-03 22:32:44 +00006936 }
6937 }
drh7ed97b92010-01-20 13:07:21 +00006938 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6939
6940 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006941 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006942 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006943 int fd;
drh7ed97b92010-01-20 13:07:21 +00006944 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006945 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006946 }
6947 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006948 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006949 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006950 if( fd>=0 ){
6951 pFile->h = fd;
6952 }else{
drh9978c972010-02-23 17:36:32 +00006953 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006954 during locking */
6955 }
6956 }
6957 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6958 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6959 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6960 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6961 /* we couldn't create the proxy lock file with the old lock file path
6962 ** so try again via auto-naming
6963 */
6964 forceNewLockPath = 1;
6965 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006966 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006967 }
6968 }
6969 if( rc==SQLITE_OK ){
6970 /* Need to make a copy of path if we extracted the value
6971 ** from the conch file or the path was allocated on the stack
6972 */
6973 if( tempLockPath ){
6974 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6975 if( !pCtx->lockProxyPath ){
6976 rc = SQLITE_NOMEM;
6977 }
6978 }
6979 }
6980 if( rc==SQLITE_OK ){
6981 pCtx->conchHeld = 1;
6982
6983 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6984 afpLockingContext *afpCtx;
6985 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6986 afpCtx->dbPath = pCtx->lockProxyPath;
6987 }
6988 } else {
6989 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6990 }
drh308c2a52010-05-14 11:30:18 +00006991 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6992 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006993 return rc;
drh308c2a52010-05-14 11:30:18 +00006994 } while (1); /* in case we need to retry the :auto: lock file -
6995 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006996 }
6997}
6998
6999/*
7000** If pFile holds a lock on a conch file, then release that lock.
7001*/
7002static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00007003 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00007004 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
7005 unixFile *conchFile; /* Name of the conch file */
7006
7007 pCtx = (proxyLockingContext *)pFile->lockingContext;
7008 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00007009 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00007010 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00007011 osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00007012 if( pCtx->conchHeld>0 ){
7013 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7014 }
drh715ff302008-12-03 22:32:44 +00007015 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00007016 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
7017 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007018 return rc;
7019}
7020
7021/*
7022** Given the name of a database file, compute the name of its conch file.
drhf3cdcdc2015-04-29 16:50:28 +00007023** Store the conch filename in memory obtained from sqlite3_malloc64().
drh715ff302008-12-03 22:32:44 +00007024** Make *pConchPath point to the new name. Return SQLITE_OK on success
7025** or SQLITE_NOMEM if unable to obtain memory.
7026**
7027** The caller is responsible for ensuring that the allocated memory
7028** space is eventually freed.
7029**
7030** *pConchPath is set to NULL if a memory allocation error occurs.
7031*/
7032static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7033 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00007034 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00007035 char *conchPath; /* buffer in which to construct conch name */
7036
7037 /* Allocate space for the conch filename and initialize the name to
7038 ** the name of the original database file. */
drhf3cdcdc2015-04-29 16:50:28 +00007039 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
drh715ff302008-12-03 22:32:44 +00007040 if( conchPath==0 ){
7041 return SQLITE_NOMEM;
7042 }
7043 memcpy(conchPath, dbPath, len+1);
7044
7045 /* now insert a "." before the last / character */
7046 for( i=(len-1); i>=0; i-- ){
7047 if( conchPath[i]=='/' ){
7048 i++;
7049 break;
7050 }
7051 }
7052 conchPath[i]='.';
7053 while ( i<len ){
7054 conchPath[i+1]=dbPath[i];
7055 i++;
7056 }
7057
7058 /* append the "-conch" suffix to the file */
7059 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007060 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007061
7062 return SQLITE_OK;
7063}
7064
7065
7066/* Takes a fully configured proxy locking-style unix file and switches
7067** the local lock file path
7068*/
7069static int switchLockProxyPath(unixFile *pFile, const char *path) {
7070 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7071 char *oldPath = pCtx->lockProxyPath;
7072 int rc = SQLITE_OK;
7073
drh308c2a52010-05-14 11:30:18 +00007074 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007075 return SQLITE_BUSY;
7076 }
7077
7078 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7079 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7080 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7081 return SQLITE_OK;
7082 }else{
7083 unixFile *lockProxy = pCtx->lockProxy;
7084 pCtx->lockProxy=NULL;
7085 pCtx->conchHeld = 0;
7086 if( lockProxy!=NULL ){
7087 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7088 if( rc ) return rc;
7089 sqlite3_free(lockProxy);
7090 }
7091 sqlite3_free(oldPath);
7092 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7093 }
7094
7095 return rc;
7096}
7097
7098/*
7099** pFile is a file that has been opened by a prior xOpen call. dbPath
7100** is a string buffer at least MAXPATHLEN+1 characters in size.
7101**
7102** This routine find the filename associated with pFile and writes it
7103** int dbPath.
7104*/
7105static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007106#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007107 if( pFile->pMethod == &afpIoMethods ){
7108 /* afp style keeps a reference to the db path in the filePath field
7109 ** of the struct */
drhea678832008-12-10 19:26:22 +00007110 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh4bf66fd2015-02-19 02:43:02 +00007111 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7112 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007113 } else
drh715ff302008-12-03 22:32:44 +00007114#endif
7115 if( pFile->pMethod == &dotlockIoMethods ){
7116 /* dot lock style uses the locking context to store the dot lock
7117 ** file path */
7118 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7119 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7120 }else{
7121 /* all other styles use the locking context to store the db file path */
7122 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007123 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007124 }
7125 return SQLITE_OK;
7126}
7127
7128/*
7129** Takes an already filled in unix file and alters it so all file locking
7130** will be performed on the local proxy lock file. The following fields
7131** are preserved in the locking context so that they can be restored and
7132** the unix structure properly cleaned up at close time:
7133** ->lockingContext
7134** ->pMethod
7135*/
7136static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7137 proxyLockingContext *pCtx;
7138 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7139 char *lockPath=NULL;
7140 int rc = SQLITE_OK;
7141
drh308c2a52010-05-14 11:30:18 +00007142 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007143 return SQLITE_BUSY;
7144 }
7145 proxyGetDbPathForUnixFile(pFile, dbPath);
7146 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7147 lockPath=NULL;
7148 }else{
7149 lockPath=(char *)path;
7150 }
7151
drh308c2a52010-05-14 11:30:18 +00007152 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
drh5ac93652015-03-21 20:59:43 +00007153 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007154
drhf3cdcdc2015-04-29 16:50:28 +00007155 pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh715ff302008-12-03 22:32:44 +00007156 if( pCtx==0 ){
7157 return SQLITE_NOMEM;
7158 }
7159 memset(pCtx, 0, sizeof(*pCtx));
7160
7161 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7162 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007163 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7164 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7165 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7166 ** (c) the file system is read-only, then enable no-locking access.
7167 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7168 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7169 */
7170 struct statfs fsInfo;
7171 struct stat conchInfo;
7172 int goLockless = 0;
7173
drh99ab3b12011-03-02 15:09:07 +00007174 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007175 int err = errno;
7176 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7177 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7178 }
7179 }
7180 if( goLockless ){
7181 pCtx->conchHeld = -1; /* read only FS/ lockless */
7182 rc = SQLITE_OK;
7183 }
7184 }
drh715ff302008-12-03 22:32:44 +00007185 }
7186 if( rc==SQLITE_OK && lockPath ){
7187 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7188 }
7189
7190 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007191 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7192 if( pCtx->dbPath==NULL ){
7193 rc = SQLITE_NOMEM;
7194 }
7195 }
7196 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007197 /* all memory is allocated, proxys are created and assigned,
7198 ** switch the locking context and pMethod then return.
7199 */
drh715ff302008-12-03 22:32:44 +00007200 pCtx->oldLockingContext = pFile->lockingContext;
7201 pFile->lockingContext = pCtx;
7202 pCtx->pOldMethod = pFile->pMethod;
7203 pFile->pMethod = &proxyIoMethods;
7204 }else{
7205 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007206 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007207 sqlite3_free(pCtx->conchFile);
7208 }
drhd56b1212010-08-11 06:14:15 +00007209 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007210 sqlite3_free(pCtx->conchFilePath);
7211 sqlite3_free(pCtx);
7212 }
drh308c2a52010-05-14 11:30:18 +00007213 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7214 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007215 return rc;
7216}
7217
7218
7219/*
7220** This routine handles sqlite3_file_control() calls that are specific
7221** to proxy locking.
7222*/
7223static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7224 switch( op ){
drh4bf66fd2015-02-19 02:43:02 +00007225 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007226 unixFile *pFile = (unixFile*)id;
7227 if( pFile->pMethod == &proxyIoMethods ){
7228 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7229 proxyTakeConch(pFile);
7230 if( pCtx->lockProxyPath ){
7231 *(const char **)pArg = pCtx->lockProxyPath;
7232 }else{
7233 *(const char **)pArg = ":auto: (not held)";
7234 }
7235 } else {
7236 *(const char **)pArg = NULL;
7237 }
7238 return SQLITE_OK;
7239 }
drh4bf66fd2015-02-19 02:43:02 +00007240 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007241 unixFile *pFile = (unixFile*)id;
7242 int rc = SQLITE_OK;
7243 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7244 if( pArg==NULL || (const char *)pArg==0 ){
7245 if( isProxyStyle ){
drh4bf66fd2015-02-19 02:43:02 +00007246 /* turn off proxy locking - not supported. If support is added for
7247 ** switching proxy locking mode off then it will need to fail if
7248 ** the journal mode is WAL mode.
7249 */
drh715ff302008-12-03 22:32:44 +00007250 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7251 }else{
7252 /* turn off proxy locking - already off - NOOP */
7253 rc = SQLITE_OK;
7254 }
7255 }else{
7256 const char *proxyPath = (const char *)pArg;
7257 if( isProxyStyle ){
7258 proxyLockingContext *pCtx =
7259 (proxyLockingContext*)pFile->lockingContext;
7260 if( !strcmp(pArg, ":auto:")
7261 || (pCtx->lockProxyPath &&
7262 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7263 ){
7264 rc = SQLITE_OK;
7265 }else{
7266 rc = switchLockProxyPath(pFile, proxyPath);
7267 }
7268 }else{
7269 /* turn on proxy file locking */
7270 rc = proxyTransformUnixFile(pFile, proxyPath);
7271 }
7272 }
7273 return rc;
7274 }
7275 default: {
7276 assert( 0 ); /* The call assures that only valid opcodes are sent */
7277 }
7278 }
7279 /*NOTREACHED*/
7280 return SQLITE_ERROR;
7281}
7282
7283/*
7284** Within this division (the proxying locking implementation) the procedures
7285** above this point are all utilities. The lock-related methods of the
7286** proxy-locking sqlite3_io_method object follow.
7287*/
7288
7289
7290/*
7291** This routine checks if there is a RESERVED lock held on the specified
7292** file by this or any other process. If such a lock is held, set *pResOut
7293** to a non-zero value otherwise *pResOut is set to zero. The return value
7294** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7295*/
7296static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7297 unixFile *pFile = (unixFile*)id;
7298 int rc = proxyTakeConch(pFile);
7299 if( rc==SQLITE_OK ){
7300 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007301 if( pCtx->conchHeld>0 ){
7302 unixFile *proxy = pCtx->lockProxy;
7303 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7304 }else{ /* conchHeld < 0 is lockless */
7305 pResOut=0;
7306 }
drh715ff302008-12-03 22:32:44 +00007307 }
7308 return rc;
7309}
7310
7311/*
drh308c2a52010-05-14 11:30:18 +00007312** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007313** of the following:
7314**
7315** (1) SHARED_LOCK
7316** (2) RESERVED_LOCK
7317** (3) PENDING_LOCK
7318** (4) EXCLUSIVE_LOCK
7319**
7320** Sometimes when requesting one lock state, additional lock states
7321** are inserted in between. The locking might fail on one of the later
7322** transitions leaving the lock state different from what it started but
7323** still short of its goal. The following chart shows the allowed
7324** transitions and the inserted intermediate states:
7325**
7326** UNLOCKED -> SHARED
7327** SHARED -> RESERVED
7328** SHARED -> (PENDING) -> EXCLUSIVE
7329** RESERVED -> (PENDING) -> EXCLUSIVE
7330** PENDING -> EXCLUSIVE
7331**
7332** This routine will only increase a lock. Use the sqlite3OsUnlock()
7333** routine to lower a locking level.
7334*/
drh308c2a52010-05-14 11:30:18 +00007335static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007336 unixFile *pFile = (unixFile*)id;
7337 int rc = proxyTakeConch(pFile);
7338 if( rc==SQLITE_OK ){
7339 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007340 if( pCtx->conchHeld>0 ){
7341 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007342 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7343 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007344 }else{
7345 /* conchHeld < 0 is lockless */
7346 }
drh715ff302008-12-03 22:32:44 +00007347 }
7348 return rc;
7349}
7350
7351
7352/*
drh308c2a52010-05-14 11:30:18 +00007353** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007354** must be either NO_LOCK or SHARED_LOCK.
7355**
7356** If the locking level of the file descriptor is already at or below
7357** the requested locking level, this routine is a no-op.
7358*/
drh308c2a52010-05-14 11:30:18 +00007359static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007360 unixFile *pFile = (unixFile*)id;
7361 int rc = proxyTakeConch(pFile);
7362 if( rc==SQLITE_OK ){
7363 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007364 if( pCtx->conchHeld>0 ){
7365 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007366 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7367 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007368 }else{
7369 /* conchHeld < 0 is lockless */
7370 }
drh715ff302008-12-03 22:32:44 +00007371 }
7372 return rc;
7373}
7374
7375/*
7376** Close a file that uses proxy locks.
7377*/
7378static int proxyClose(sqlite3_file *id) {
7379 if( id ){
7380 unixFile *pFile = (unixFile*)id;
7381 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7382 unixFile *lockProxy = pCtx->lockProxy;
7383 unixFile *conchFile = pCtx->conchFile;
7384 int rc = SQLITE_OK;
7385
7386 if( lockProxy ){
7387 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7388 if( rc ) return rc;
7389 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7390 if( rc ) return rc;
7391 sqlite3_free(lockProxy);
7392 pCtx->lockProxy = 0;
7393 }
7394 if( conchFile ){
7395 if( pCtx->conchHeld ){
7396 rc = proxyReleaseConch(pFile);
7397 if( rc ) return rc;
7398 }
7399 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7400 if( rc ) return rc;
7401 sqlite3_free(conchFile);
7402 }
drhd56b1212010-08-11 06:14:15 +00007403 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007404 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007405 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007406 /* restore the original locking context and pMethod then close it */
7407 pFile->lockingContext = pCtx->oldLockingContext;
7408 pFile->pMethod = pCtx->pOldMethod;
7409 sqlite3_free(pCtx);
7410 return pFile->pMethod->xClose(id);
7411 }
7412 return SQLITE_OK;
7413}
7414
7415
7416
drhd2cb50b2009-01-09 21:41:17 +00007417#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007418/*
7419** The proxy locking style is intended for use with AFP filesystems.
7420** And since AFP is only supported on MacOSX, the proxy locking is also
7421** restricted to MacOSX.
7422**
7423**
7424******************* End of the proxy lock implementation **********************
7425******************************************************************************/
7426
drh734c9862008-11-28 15:37:20 +00007427/*
danielk1977e339d652008-06-28 11:23:00 +00007428** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007429**
7430** This routine registers all VFS implementations for unix-like operating
7431** systems. This routine, and the sqlite3_os_end() routine that follows,
7432** should be the only routines in this file that are visible from other
7433** files.
drh6b9d6dd2008-12-03 19:34:47 +00007434**
7435** This routine is called once during SQLite initialization and by a
7436** single thread. The memory allocation and mutex subsystems have not
7437** necessarily been initialized when this routine is called, and so they
7438** should not be used.
drh153c62c2007-08-24 03:51:33 +00007439*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007440int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007441 /*
7442 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007443 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7444 ** to the "finder" function. (pAppData is a pointer to a pointer because
7445 ** silly C90 rules prohibit a void* from being cast to a function pointer
7446 ** and so we have to go through the intermediate pointer to avoid problems
7447 ** when compiling with -pedantic-errors on GCC.)
7448 **
7449 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007450 ** finder-function. The finder-function returns a pointer to the
7451 ** sqlite_io_methods object that implements the desired locking
7452 ** behaviors. See the division above that contains the IOMETHODS
7453 ** macro for addition information on finder-functions.
7454 **
7455 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7456 ** object. But the "autolockIoFinder" available on MacOSX does a little
7457 ** more than that; it looks at the filesystem type that hosts the
7458 ** database file and tries to choose an locking method appropriate for
7459 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007460 */
drh7708e972008-11-29 00:56:52 +00007461 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007462 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007463 sizeof(unixFile), /* szOsFile */ \
7464 MAX_PATHNAME, /* mxPathname */ \
7465 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007466 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007467 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007468 unixOpen, /* xOpen */ \
7469 unixDelete, /* xDelete */ \
7470 unixAccess, /* xAccess */ \
7471 unixFullPathname, /* xFullPathname */ \
7472 unixDlOpen, /* xDlOpen */ \
7473 unixDlError, /* xDlError */ \
7474 unixDlSym, /* xDlSym */ \
7475 unixDlClose, /* xDlClose */ \
7476 unixRandomness, /* xRandomness */ \
7477 unixSleep, /* xSleep */ \
7478 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007479 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007480 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007481 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007482 unixGetSystemCall, /* xGetSystemCall */ \
7483 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007484 }
7485
drh6b9d6dd2008-12-03 19:34:47 +00007486 /*
7487 ** All default VFSes for unix are contained in the following array.
7488 **
7489 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7490 ** by the SQLite core when the VFS is registered. So the following
7491 ** array cannot be const.
7492 */
danielk1977e339d652008-06-28 11:23:00 +00007493 static sqlite3_vfs aVfs[] = {
drhe89b2912015-03-03 20:42:01 +00007494#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007495 UNIXVFS("unix", autolockIoFinder ),
drhe89b2912015-03-03 20:42:01 +00007496#elif OS_VXWORKS
7497 UNIXVFS("unix", vxworksIoFinder ),
drh7708e972008-11-29 00:56:52 +00007498#else
7499 UNIXVFS("unix", posixIoFinder ),
7500#endif
7501 UNIXVFS("unix-none", nolockIoFinder ),
7502 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007503 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007504#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007505 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007506#endif
drhe89b2912015-03-03 20:42:01 +00007507#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007508 UNIXVFS("unix-posix", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007509#endif
drhe89b2912015-03-03 20:42:01 +00007510#if SQLITE_ENABLE_LOCKING_STYLE
7511 UNIXVFS("unix-flock", flockIoFinder ),
chw78a13182009-04-07 05:35:03 +00007512#endif
drhd2cb50b2009-01-09 21:41:17 +00007513#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007514 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007515 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007516 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007517#endif
drh153c62c2007-08-24 03:51:33 +00007518 };
drh6b9d6dd2008-12-03 19:34:47 +00007519 unsigned int i; /* Loop counter */
7520
drh2aa5a002011-04-13 13:42:25 +00007521 /* Double-check that the aSyscall[] array has been constructed
7522 ** correctly. See ticket [bb3a86e890c8e96ab] */
drh6226ca22015-11-24 15:06:28 +00007523 assert( ArraySize(aSyscall)==27 );
drh2aa5a002011-04-13 13:42:25 +00007524
drh6b9d6dd2008-12-03 19:34:47 +00007525 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007526 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007527 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007528 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007529 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007530}
danielk1977e339d652008-06-28 11:23:00 +00007531
7532/*
drh6b9d6dd2008-12-03 19:34:47 +00007533** Shutdown the operating system interface.
7534**
7535** Some operating systems might need to do some cleanup in this routine,
7536** to release dynamically allocated objects. But not on unix.
7537** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007538*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007539int sqlite3_os_end(void){
7540 return SQLITE_OK;
7541}
drhdce8bdb2007-08-16 13:01:44 +00007542
danielk197729bafea2008-06-26 10:41:19 +00007543#endif /* SQLITE_OS_UNIX */