blob: 3745827f69ce08264b6f673231e4fdb08c3f777e [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;
3503 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3504}
3505
3506/*
drh734c9862008-11-28 15:37:20 +00003507** Make sure all writes to a particular file are committed to disk.
3508**
3509** If dataOnly==0 then both the file itself and its metadata (file
3510** size, access time, etc) are synced. If dataOnly!=0 then only the
3511** file data is synced.
3512**
3513** Under Unix, also make sure that the directory entry for the file
3514** has been created by fsync-ing the directory that contains the file.
3515** If we do not do this and we encounter a power failure, the directory
3516** entry for the journal might not exist after we reboot. The next
3517** SQLite to access the file will not know that the journal exists (because
3518** the directory entry for the journal was never created) and the transaction
3519** will not roll back - possibly leading to database corruption.
3520*/
3521static int unixSync(sqlite3_file *id, int flags){
3522 int rc;
3523 unixFile *pFile = (unixFile*)id;
3524
3525 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3526 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3527
3528 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3529 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3530 || (flags&0x0F)==SQLITE_SYNC_FULL
3531 );
3532
3533 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3534 ** line is to test that doing so does not cause any problems.
3535 */
3536 SimulateDiskfullError( return SQLITE_FULL );
3537
3538 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003539 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003540 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3541 SimulateIOError( rc=1 );
3542 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003543 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003544 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003545 }
drh0059eae2011-08-08 23:48:40 +00003546
3547 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003548 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003549 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003550 */
3551 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3552 int dirfd;
3553 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003554 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003555 rc = osOpenDirectory(pFile->zPath, &dirfd);
3556 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003557 full_fsync(dirfd, 0, 0);
3558 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003559 }else if( rc==SQLITE_CANTOPEN ){
3560 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003561 }
drh0059eae2011-08-08 23:48:40 +00003562 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003563 }
3564 return rc;
3565}
3566
3567/*
3568** Truncate an open file to a specified size
3569*/
3570static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003571 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003572 int rc;
dan6e09d692010-07-27 18:34:15 +00003573 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003574 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003575
3576 /* If the user has configured a chunk-size for this file, truncate the
3577 ** file so that it consists of an integer number of chunks (i.e. the
3578 ** actual file size after the operation may be larger than the requested
3579 ** size).
3580 */
drhb8af4b72012-04-05 20:04:39 +00003581 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003582 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3583 }
3584
dan2ee53412014-09-06 16:49:40 +00003585 rc = robust_ftruncate(pFile->h, nByte);
drh734c9862008-11-28 15:37:20 +00003586 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003587 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003588 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003589 }else{
drhd3d8c042012-05-29 17:02:40 +00003590#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003591 /* If we are doing a normal write to a database file (as opposed to
3592 ** doing a hot-journal rollback or a write to some file other than a
3593 ** normal database file) and we truncate the file to zero length,
3594 ** that effectively updates the change counter. This might happen
3595 ** when restoring a database using the backup API from a zero-length
3596 ** source.
3597 */
dan6e09d692010-07-27 18:34:15 +00003598 if( pFile->inNormalWrite && nByte==0 ){
3599 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003600 }
danf23da962013-03-23 21:00:41 +00003601#endif
danc0003312013-03-22 17:46:11 +00003602
mistachkine98844f2013-08-24 00:59:24 +00003603#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003604 /* If the file was just truncated to a size smaller than the currently
3605 ** mapped region, reduce the effective mapping size as well. SQLite will
3606 ** use read() and write() to access data beyond this point from now on.
3607 */
3608 if( nByte<pFile->mmapSize ){
3609 pFile->mmapSize = nByte;
3610 }
mistachkine98844f2013-08-24 00:59:24 +00003611#endif
drh3313b142009-11-06 04:13:18 +00003612
drh734c9862008-11-28 15:37:20 +00003613 return SQLITE_OK;
3614 }
3615}
3616
3617/*
3618** Determine the current size of a file in bytes
3619*/
3620static int unixFileSize(sqlite3_file *id, i64 *pSize){
3621 int rc;
3622 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003623 assert( id );
3624 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003625 SimulateIOError( rc=1 );
3626 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00003627 storeLastErrno((unixFile*)id, errno);
drh734c9862008-11-28 15:37:20 +00003628 return SQLITE_IOERR_FSTAT;
3629 }
3630 *pSize = buf.st_size;
3631
drh8af6c222010-05-14 12:43:01 +00003632 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003633 ** writes a single byte into that file in order to work around a bug
3634 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3635 ** layers, we need to report this file size as zero even though it is
3636 ** really 1. Ticket #3260.
3637 */
3638 if( *pSize==1 ) *pSize = 0;
3639
3640
3641 return SQLITE_OK;
3642}
3643
drhd2cb50b2009-01-09 21:41:17 +00003644#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003645/*
3646** Handler for proxy-locking file-control verbs. Defined below in the
3647** proxying locking division.
3648*/
3649static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003650#endif
drh715ff302008-12-03 22:32:44 +00003651
dan502019c2010-07-28 14:26:17 +00003652/*
3653** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003654** file-control operation. Enlarge the database to nBytes in size
3655** (rounded up to the next chunk-size). If the database is already
3656** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003657*/
3658static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003659 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003660 i64 nSize; /* Required file size */
3661 struct stat buf; /* Used to hold return values of fstat() */
3662
drh4bf66fd2015-02-19 02:43:02 +00003663 if( osFstat(pFile->h, &buf) ){
3664 return SQLITE_IOERR_FSTAT;
3665 }
dan502019c2010-07-28 14:26:17 +00003666
3667 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3668 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003669
dan502019c2010-07-28 14:26:17 +00003670#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003671 /* The code below is handling the return value of osFallocate()
3672 ** correctly. posix_fallocate() is defined to "returns zero on success,
3673 ** or an error number on failure". See the manpage for details. */
3674 int err;
drhff812312011-02-23 13:33:46 +00003675 do{
dan661d71a2011-03-30 19:08:03 +00003676 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3677 }while( err==EINTR );
3678 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003679#else
dan592bf7f2014-12-30 19:58:31 +00003680 /* If the OS does not have posix_fallocate(), fake it. Write a
3681 ** single byte to the last byte in each block that falls entirely
3682 ** within the extended region. Then, if required, a single byte
3683 ** at offset (nSize-1), to set the size of the file correctly.
3684 ** This is a similar technique to that used by glibc on systems
3685 ** that do not have a real fallocate() call.
dan502019c2010-07-28 14:26:17 +00003686 */
3687 int nBlk = buf.st_blksize; /* File-system block size */
danef3d66c2015-01-06 21:31:47 +00003688 int nWrite = 0; /* Number of bytes written by seekAndWrite */
dan502019c2010-07-28 14:26:17 +00003689 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003690
dan502019c2010-07-28 14:26:17 +00003691 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dan592bf7f2014-12-30 19:58:31 +00003692 assert( iWrite>=buf.st_size );
3693 assert( (iWrite/nBlk)==((buf.st_size+nBlk-1)/nBlk) );
3694 assert( ((iWrite+1)%nBlk)==0 );
3695 for(/*no-op*/; iWrite<nSize; iWrite+=nBlk ){
danef3d66c2015-01-06 21:31:47 +00003696 nWrite = seekAndWrite(pFile, iWrite, "", 1);
dandc5df0f2011-04-06 19:15:45 +00003697 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dandc5df0f2011-04-06 19:15:45 +00003698 }
danef3d66c2015-01-06 21:31:47 +00003699 if( nWrite==0 || (nSize%nBlk) ){
3700 nWrite = seekAndWrite(pFile, nSize-1, "", 1);
dan592bf7f2014-12-30 19:58:31 +00003701 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dand348c662014-12-30 14:40:53 +00003702 }
dan502019c2010-07-28 14:26:17 +00003703#endif
3704 }
3705 }
3706
mistachkine98844f2013-08-24 00:59:24 +00003707#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003708 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003709 int rc;
3710 if( pFile->szChunk<=0 ){
3711 if( robust_ftruncate(pFile->h, nByte) ){
drh4bf66fd2015-02-19 02:43:02 +00003712 storeLastErrno(pFile, errno);
danf23da962013-03-23 21:00:41 +00003713 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3714 }
3715 }
3716
3717 rc = unixMapfile(pFile, nByte);
3718 return rc;
3719 }
mistachkine98844f2013-08-24 00:59:24 +00003720#endif
danf23da962013-03-23 21:00:41 +00003721
dan502019c2010-07-28 14:26:17 +00003722 return SQLITE_OK;
3723}
danielk1977ad94b582007-08-20 06:44:22 +00003724
danielk1977e3026632004-06-22 11:29:02 +00003725/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003726** If *pArg is initially negative then this is a query. Set *pArg to
drhf12b3f62011-12-21 14:42:29 +00003727** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3728**
3729** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3730*/
3731static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3732 if( *pArg<0 ){
3733 *pArg = (pFile->ctrlFlags & mask)!=0;
3734 }else if( (*pArg)==0 ){
3735 pFile->ctrlFlags &= ~mask;
3736 }else{
3737 pFile->ctrlFlags |= mask;
3738 }
3739}
3740
drh696b33e2012-12-06 19:01:42 +00003741/* Forward declaration */
3742static int unixGetTempname(int nBuf, char *zBuf);
3743
drhf12b3f62011-12-21 14:42:29 +00003744/*
drh9e33c2c2007-08-31 18:34:59 +00003745** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003746*/
drhcc6bb3e2007-08-31 16:11:35 +00003747static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003748 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003749 switch( op ){
drhc435cf72015-03-21 16:36:03 +00003750 case SQLITE_FCNTL_WAL_BLOCK: {
drh62ca61e2015-04-03 20:33:33 +00003751 /* pFile->ctrlFlags |= UNIXFILE_BLOCK; // Deferred feature */
drhc435cf72015-03-21 16:36:03 +00003752 return SQLITE_OK;
3753 }
drh9e33c2c2007-08-31 18:34:59 +00003754 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003755 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003756 return SQLITE_OK;
3757 }
drh4bf66fd2015-02-19 02:43:02 +00003758 case SQLITE_FCNTL_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003759 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003760 return SQLITE_OK;
3761 }
dan6e09d692010-07-27 18:34:15 +00003762 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003763 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003764 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003765 }
drh9ff27ec2010-05-19 19:26:05 +00003766 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003767 int rc;
3768 SimulateIOErrorBenign(1);
3769 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3770 SimulateIOErrorBenign(0);
3771 return rc;
drhf0b190d2011-07-26 16:03:07 +00003772 }
3773 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003774 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3775 return SQLITE_OK;
3776 }
drhcb15f352011-12-23 01:04:17 +00003777 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3778 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003779 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003780 }
drhde60fc22011-12-14 17:53:36 +00003781 case SQLITE_FCNTL_VFSNAME: {
3782 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3783 return SQLITE_OK;
3784 }
drh696b33e2012-12-06 19:01:42 +00003785 case SQLITE_FCNTL_TEMPFILENAME: {
drhf3cdcdc2015-04-29 16:50:28 +00003786 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
drh696b33e2012-12-06 19:01:42 +00003787 if( zTFile ){
3788 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3789 *(char**)pArg = zTFile;
3790 }
3791 return SQLITE_OK;
3792 }
drhb959a012013-12-07 12:29:22 +00003793 case SQLITE_FCNTL_HAS_MOVED: {
3794 *(int*)pArg = fileHasMoved(pFile);
3795 return SQLITE_OK;
3796 }
mistachkine98844f2013-08-24 00:59:24 +00003797#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003798 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003799 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003800 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003801 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3802 newLimit = sqlite3GlobalConfig.mxMmap;
3803 }
3804 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003805 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003806 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003807 if( pFile->mmapSize>0 ){
3808 unixUnmapfile(pFile);
3809 rc = unixMapfile(pFile, -1);
3810 }
danbcb8a862013-04-08 15:30:41 +00003811 }
drh34e258c2013-05-23 01:40:53 +00003812 return rc;
danb2d3de32013-03-14 18:34:37 +00003813 }
mistachkine98844f2013-08-24 00:59:24 +00003814#endif
drhd3d8c042012-05-29 17:02:40 +00003815#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003816 /* The pager calls this method to signal that it has done
3817 ** a rollback and that the database is therefore unchanged and
3818 ** it hence it is OK for the transaction change counter to be
3819 ** unchanged.
3820 */
3821 case SQLITE_FCNTL_DB_UNCHANGED: {
3822 ((unixFile*)id)->dbUpdate = 0;
3823 return SQLITE_OK;
3824 }
3825#endif
drhd2cb50b2009-01-09 21:41:17 +00003826#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh4bf66fd2015-02-19 02:43:02 +00003827 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
3828 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003829 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003830 }
drhd2cb50b2009-01-09 21:41:17 +00003831#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003832 }
drh0b52b7d2011-01-26 19:46:22 +00003833 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003834}
3835
3836/*
danielk1977a3d4c882007-03-23 10:08:38 +00003837** Return the sector size in bytes of the underlying block device for
3838** the specified file. This is almost always 512 bytes, but may be
3839** larger for some devices.
3840**
3841** SQLite code assumes this function cannot fail. It also assumes that
3842** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003843** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003844** same for both.
3845*/
drh537dddf2012-10-26 13:46:24 +00003846#ifndef __QNXNTO__
3847static int unixSectorSize(sqlite3_file *NotUsed){
3848 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003849 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003850}
drh537dddf2012-10-26 13:46:24 +00003851#endif
3852
3853/*
3854** The following version of unixSectorSize() is optimized for QNX.
3855*/
3856#ifdef __QNXNTO__
3857#include <sys/dcmd_blk.h>
3858#include <sys/statvfs.h>
3859static int unixSectorSize(sqlite3_file *id){
3860 unixFile *pFile = (unixFile*)id;
3861 if( pFile->sectorSize == 0 ){
3862 struct statvfs fsInfo;
3863
3864 /* Set defaults for non-supported filesystems */
3865 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3866 pFile->deviceCharacteristics = 0;
3867 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3868 return pFile->sectorSize;
3869 }
3870
3871 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3872 pFile->sectorSize = fsInfo.f_bsize;
3873 pFile->deviceCharacteristics =
3874 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3875 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3876 ** the write succeeds */
3877 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3878 ** so it is ordered */
3879 0;
3880 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3881 pFile->sectorSize = fsInfo.f_bsize;
3882 pFile->deviceCharacteristics =
3883 /* etfs cluster size writes are atomic */
3884 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3885 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3886 ** the write succeeds */
3887 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3888 ** so it is ordered */
3889 0;
3890 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3891 pFile->sectorSize = fsInfo.f_bsize;
3892 pFile->deviceCharacteristics =
3893 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3894 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3895 ** the write succeeds */
3896 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3897 ** so it is ordered */
3898 0;
3899 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3900 pFile->sectorSize = fsInfo.f_bsize;
3901 pFile->deviceCharacteristics =
3902 /* full bitset of atomics from max sector size and smaller */
3903 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3904 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3905 ** so it is ordered */
3906 0;
3907 }else if( strstr(fsInfo.f_basetype, "dos") ){
3908 pFile->sectorSize = fsInfo.f_bsize;
3909 pFile->deviceCharacteristics =
3910 /* full bitset of atomics from max sector size and smaller */
3911 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3912 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3913 ** so it is ordered */
3914 0;
3915 }else{
3916 pFile->deviceCharacteristics =
3917 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3918 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3919 ** the write succeeds */
3920 0;
3921 }
3922 }
3923 /* Last chance verification. If the sector size isn't a multiple of 512
3924 ** then it isn't valid.*/
3925 if( pFile->sectorSize % 512 != 0 ){
3926 pFile->deviceCharacteristics = 0;
3927 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3928 }
3929 return pFile->sectorSize;
3930}
3931#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003932
danielk197790949c22007-08-17 16:50:38 +00003933/*
drhf12b3f62011-12-21 14:42:29 +00003934** Return the device characteristics for the file.
3935**
drhcb15f352011-12-23 01:04:17 +00003936** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
peter.d.reid60ec9142014-09-06 16:39:46 +00003937** However, that choice is controversial since technically the underlying
drhcb15f352011-12-23 01:04:17 +00003938** file system does not always provide powersafe overwrites. (In other
3939** words, after a power-loss event, parts of the file that were never
3940** written might end up being altered.) However, non-PSOW behavior is very,
3941** very rare. And asserting PSOW makes a large reduction in the amount
3942** of required I/O for journaling, since a lot of padding is eliminated.
3943** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3944** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003945*/
drhf12b3f62011-12-21 14:42:29 +00003946static int unixDeviceCharacteristics(sqlite3_file *id){
3947 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003948 int rc = 0;
3949#ifdef __QNXNTO__
3950 if( p->sectorSize==0 ) unixSectorSize(id);
3951 rc = p->deviceCharacteristics;
3952#endif
drhcb15f352011-12-23 01:04:17 +00003953 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003954 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003955 }
drh537dddf2012-10-26 13:46:24 +00003956 return rc;
danielk197762079062007-08-15 17:08:46 +00003957}
3958
dan702eec12014-06-23 10:04:58 +00003959#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00003960
dan702eec12014-06-23 10:04:58 +00003961/*
3962** Return the system page size.
3963**
3964** This function should not be called directly by other code in this file.
3965** Instead, it should be called via macro osGetpagesize().
3966*/
3967static int unixGetpagesize(void){
drh8cd5b252015-03-02 22:06:43 +00003968#if OS_VXWORKS
3969 return 1024;
3970#elif defined(_BSD_SOURCE)
dan702eec12014-06-23 10:04:58 +00003971 return getpagesize();
3972#else
3973 return (int)sysconf(_SC_PAGESIZE);
3974#endif
3975}
3976
3977#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
3978
3979#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00003980
3981/*
drhd91c68f2010-05-14 14:52:25 +00003982** Object used to represent an shared memory buffer.
3983**
3984** When multiple threads all reference the same wal-index, each thread
3985** has its own unixShm object, but they all point to a single instance
3986** of this unixShmNode object. In other words, each wal-index is opened
3987** only once per process.
3988**
3989** Each unixShmNode object is connected to a single unixInodeInfo object.
3990** We could coalesce this object into unixInodeInfo, but that would mean
3991** every open file that does not use shared memory (in other words, most
3992** open files) would have to carry around this extra information. So
3993** the unixInodeInfo object contains a pointer to this unixShmNode object
3994** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003995**
3996** unixMutexHeld() must be true when creating or destroying
3997** this object or while reading or writing the following fields:
3998**
3999** nRef
drhd9e5c4f2010-05-12 18:01:39 +00004000**
4001** The following fields are read-only after the object is created:
4002**
4003** fid
4004** zFilename
4005**
drhd91c68f2010-05-14 14:52:25 +00004006** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00004007** unixMutexHeld() is true when reading or writing any other field
4008** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00004009*/
drhd91c68f2010-05-14 14:52:25 +00004010struct unixShmNode {
4011 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00004012 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00004013 char *zFilename; /* Name of the mmapped file */
4014 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00004015 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00004016 u16 nRegion; /* Size of array apRegion */
4017 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00004018 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00004019 int nRef; /* Number of unixShm objects pointing to this */
4020 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00004021#ifdef SQLITE_DEBUG
4022 u8 exclMask; /* Mask of exclusive locks held */
4023 u8 sharedMask; /* Mask of shared locks held */
4024 u8 nextShmId; /* Next available unixShm.id value */
4025#endif
4026};
4027
4028/*
drhd9e5c4f2010-05-12 18:01:39 +00004029** Structure used internally by this VFS to record the state of an
4030** open shared memory connection.
4031**
drhd91c68f2010-05-14 14:52:25 +00004032** The following fields are initialized when this object is created and
4033** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004034**
drhd91c68f2010-05-14 14:52:25 +00004035** unixShm.pFile
4036** unixShm.id
4037**
4038** All other fields are read/write. The unixShm.pFile->mutex must be held
4039** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004040*/
4041struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004042 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4043 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004044 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004045 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004046 u16 sharedMask; /* Mask of shared locks held */
4047 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004048};
4049
4050/*
drhd9e5c4f2010-05-12 18:01:39 +00004051** Constants used for locking
4052*/
drhbd9676c2010-06-23 17:58:38 +00004053#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004054#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004055
drhd9e5c4f2010-05-12 18:01:39 +00004056/*
drh73b64e42010-05-30 19:55:15 +00004057** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004058**
4059** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4060** otherwise.
4061*/
4062static int unixShmSystemLock(
drhbbf76ee2015-03-10 20:22:35 +00004063 unixFile *pFile, /* Open connection to the WAL file */
drhd91c68f2010-05-14 14:52:25 +00004064 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004065 int ofst, /* First byte of the locking range */
4066 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004067){
drhbbf76ee2015-03-10 20:22:35 +00004068 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4069 struct flock f; /* The posix advisory locking structure */
4070 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004071
drhd91c68f2010-05-14 14:52:25 +00004072 /* Access to the unixShmNode object is serialized by the caller */
drhbbf76ee2015-03-10 20:22:35 +00004073 pShmNode = pFile->pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004074 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004075
drh73b64e42010-05-30 19:55:15 +00004076 /* Shared locks never span more than one byte */
4077 assert( n==1 || lockType!=F_RDLCK );
4078
4079 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00004080 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004081
drh3cb93392011-03-12 18:10:44 +00004082 if( pShmNode->h>=0 ){
drhbbf76ee2015-03-10 20:22:35 +00004083 int lkType;
drh3cb93392011-03-12 18:10:44 +00004084 /* Initialize the locking parameters */
4085 memset(&f, 0, sizeof(f));
4086 f.l_type = lockType;
4087 f.l_whence = SEEK_SET;
4088 f.l_start = ofst;
4089 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004090
drhbbf76ee2015-03-10 20:22:35 +00004091 lkType = (pFile->ctrlFlags & UNIXFILE_BLOCK)!=0 ? F_SETLKW : F_SETLK;
4092 rc = osFcntl(pShmNode->h, lkType, &f);
drh3cb93392011-03-12 18:10:44 +00004093 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
drhbbf76ee2015-03-10 20:22:35 +00004094 pFile->ctrlFlags &= ~UNIXFILE_BLOCK;
drh3cb93392011-03-12 18:10:44 +00004095 }
drhd9e5c4f2010-05-12 18:01:39 +00004096
4097 /* Update the global lock state and do debug tracing */
4098#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004099 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004100 OSTRACE(("SHM-LOCK "));
drh693e6712014-01-24 22:58:00 +00004101 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004102 if( rc==SQLITE_OK ){
4103 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004104 OSTRACE(("unlock %d ok", ofst));
4105 pShmNode->exclMask &= ~mask;
4106 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004107 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004108 OSTRACE(("read-lock %d ok", ofst));
4109 pShmNode->exclMask &= ~mask;
4110 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004111 }else{
4112 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004113 OSTRACE(("write-lock %d ok", ofst));
4114 pShmNode->exclMask |= mask;
4115 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004116 }
4117 }else{
4118 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004119 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004120 }else if( lockType==F_RDLCK ){
4121 OSTRACE(("read-lock failed"));
4122 }else{
4123 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004124 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004125 }
4126 }
drh20e1f082010-05-31 16:10:12 +00004127 OSTRACE((" - afterwards %03x,%03x\n",
4128 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004129 }
drhd9e5c4f2010-05-12 18:01:39 +00004130#endif
4131
4132 return rc;
4133}
4134
dan781e34c2014-03-20 08:59:47 +00004135/*
dan781e34c2014-03-20 08:59:47 +00004136** Return the minimum number of 32KB shm regions that should be mapped at
4137** a time, assuming that each mapping must be an integer multiple of the
4138** current system page-size.
4139**
4140** Usually, this is 1. The exception seems to be systems that are configured
4141** to use 64KB pages - in this case each mapping must cover at least two
4142** shm regions.
4143*/
4144static int unixShmRegionPerMap(void){
4145 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004146 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004147 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4148 if( pgsz<shmsz ) return 1;
4149 return pgsz/shmsz;
4150}
drhd9e5c4f2010-05-12 18:01:39 +00004151
4152/*
drhd91c68f2010-05-14 14:52:25 +00004153** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004154**
4155** This is not a VFS shared-memory method; it is a utility function called
4156** by VFS shared-memory methods.
4157*/
drhd91c68f2010-05-14 14:52:25 +00004158static void unixShmPurge(unixFile *pFd){
4159 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004160 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00004161 if( p && p->nRef==0 ){
dan781e34c2014-03-20 08:59:47 +00004162 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004163 int i;
drhd91c68f2010-05-14 14:52:25 +00004164 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004165 sqlite3_mutex_free(p->mutex);
dan781e34c2014-03-20 08:59:47 +00004166 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh3cb93392011-03-12 18:10:44 +00004167 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004168 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004169 }else{
4170 sqlite3_free(p->apRegion[i]);
4171 }
dan13a3cb82010-06-11 19:04:21 +00004172 }
dan18801912010-06-14 14:07:50 +00004173 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004174 if( p->h>=0 ){
4175 robust_close(pFd, p->h, __LINE__);
4176 p->h = -1;
4177 }
drhd91c68f2010-05-14 14:52:25 +00004178 p->pInode->pShmNode = 0;
4179 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004180 }
4181}
4182
4183/*
danda9fe0c2010-07-13 18:44:03 +00004184** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004185** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004186**
drh7234c6d2010-06-19 15:10:09 +00004187** The file used to implement shared-memory is in the same directory
4188** as the open database file and has the same name as the open database
4189** file with the "-shm" suffix added. For example, if the database file
4190** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004191** for shared memory will be called "/home/user1/config.db-shm".
4192**
4193** Another approach to is to use files in /dev/shm or /dev/tmp or an
4194** some other tmpfs mount. But if a file in a different directory
4195** from the database file is used, then differing access permissions
4196** or a chroot() might cause two different processes on the same
4197** database to end up using different files for shared memory -
4198** meaning that their memory would not really be shared - resulting
4199** in database corruption. Nevertheless, this tmpfs file usage
4200** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4201** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4202** option results in an incompatible build of SQLite; builds of SQLite
4203** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4204** same database file at the same time, database corruption will likely
4205** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4206** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004207**
4208** When opening a new shared-memory file, if no other instances of that
4209** file are currently open, in this process or in other processes, then
4210** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004211**
4212** If the original database file (pDbFd) is using the "unix-excl" VFS
4213** that means that an exclusive lock is held on the database file and
4214** that no other processes are able to read or write the database. In
4215** that case, we do not really need shared memory. No shared memory
4216** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004217*/
danda9fe0c2010-07-13 18:44:03 +00004218static int unixOpenSharedMemory(unixFile *pDbFd){
4219 struct unixShm *p = 0; /* The connection to be opened */
4220 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4221 int rc; /* Result code */
4222 unixInodeInfo *pInode; /* The inode of fd */
4223 char *zShmFilename; /* Name of the file used for SHM */
4224 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004225
danda9fe0c2010-07-13 18:44:03 +00004226 /* Allocate space for the new unixShm object. */
drhf3cdcdc2015-04-29 16:50:28 +00004227 p = sqlite3_malloc64( sizeof(*p) );
drhd9e5c4f2010-05-12 18:01:39 +00004228 if( p==0 ) return SQLITE_NOMEM;
4229 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004230 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004231
danda9fe0c2010-07-13 18:44:03 +00004232 /* Check to see if a unixShmNode object already exists. Reuse an existing
4233 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004234 */
4235 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004236 pInode = pDbFd->pInode;
4237 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004238 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004239 struct stat sStat; /* fstat() info for database file */
drh4bf66fd2015-02-19 02:43:02 +00004240#ifndef SQLITE_SHM_DIRECTORY
4241 const char *zBasePath = pDbFd->zPath;
4242#endif
danddb0ac42010-07-14 14:48:58 +00004243
4244 /* Call fstat() to figure out the permissions on the database file. If
4245 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004246 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004247 */
drh3cb93392011-03-12 18:10:44 +00004248 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00004249 rc = SQLITE_IOERR_FSTAT;
4250 goto shm_open_err;
4251 }
4252
drha4ced192010-07-15 18:32:40 +00004253#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004254 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004255#else
drh4bf66fd2015-02-19 02:43:02 +00004256 nShmFilename = 6 + (int)strlen(zBasePath);
drha4ced192010-07-15 18:32:40 +00004257#endif
drhf3cdcdc2015-04-29 16:50:28 +00004258 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004259 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004260 rc = SQLITE_NOMEM;
4261 goto shm_open_err;
4262 }
drh9cb5a0d2012-01-05 21:19:54 +00004263 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004264 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004265#ifdef SQLITE_SHM_DIRECTORY
4266 sqlite3_snprintf(nShmFilename, zShmFilename,
4267 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4268 (u32)sStat.st_ino, (u32)sStat.st_dev);
4269#else
drh4bf66fd2015-02-19 02:43:02 +00004270 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
drh81cc5162011-05-17 20:36:21 +00004271 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004272#endif
drhd91c68f2010-05-14 14:52:25 +00004273 pShmNode->h = -1;
4274 pDbFd->pInode->pShmNode = pShmNode;
4275 pShmNode->pInode = pDbFd->pInode;
4276 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4277 if( pShmNode->mutex==0 ){
4278 rc = SQLITE_NOMEM;
4279 goto shm_open_err;
4280 }
drhd9e5c4f2010-05-12 18:01:39 +00004281
drh3cb93392011-03-12 18:10:44 +00004282 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004283 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004284 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004285 openFlags = O_RDONLY;
4286 pShmNode->isReadonly = 1;
4287 }
4288 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004289 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004290 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4291 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004292 }
drhac7c3ac2012-02-11 19:23:48 +00004293
4294 /* If this process is running as root, make sure that the SHM file
4295 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004296 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004297 */
drh6226ca22015-11-24 15:06:28 +00004298 robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004299
4300 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004301 ** If not, truncate the file to zero length.
4302 */
4303 rc = SQLITE_OK;
drhbbf76ee2015-03-10 20:22:35 +00004304 if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
drh66dfec8b2011-06-01 20:01:49 +00004305 if( robust_ftruncate(pShmNode->h, 0) ){
4306 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004307 }
4308 }
drh66dfec8b2011-06-01 20:01:49 +00004309 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004310 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
drh66dfec8b2011-06-01 20:01:49 +00004311 }
4312 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004313 }
drhd9e5c4f2010-05-12 18:01:39 +00004314 }
4315
drhd91c68f2010-05-14 14:52:25 +00004316 /* Make the new connection a child of the unixShmNode */
4317 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004318#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004319 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004320#endif
drhd91c68f2010-05-14 14:52:25 +00004321 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004322 pDbFd->pShm = p;
4323 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004324
4325 /* The reference count on pShmNode has already been incremented under
4326 ** the cover of the unixEnterMutex() mutex and the pointer from the
4327 ** new (struct unixShm) object to the pShmNode has been set. All that is
4328 ** left to do is to link the new object into the linked list starting
4329 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4330 ** mutex.
4331 */
4332 sqlite3_mutex_enter(pShmNode->mutex);
4333 p->pNext = pShmNode->pFirst;
4334 pShmNode->pFirst = p;
4335 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004336 return SQLITE_OK;
4337
4338 /* Jump here on any error */
4339shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004340 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004341 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004342 unixLeaveMutex();
4343 return rc;
4344}
4345
4346/*
danda9fe0c2010-07-13 18:44:03 +00004347** This function is called to obtain a pointer to region iRegion of the
4348** shared-memory associated with the database file fd. Shared-memory regions
4349** are numbered starting from zero. Each shared-memory region is szRegion
4350** bytes in size.
4351**
4352** If an error occurs, an error code is returned and *pp is set to NULL.
4353**
4354** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4355** region has not been allocated (by any client, including one running in a
4356** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4357** bExtend is non-zero and the requested shared-memory region has not yet
4358** been allocated, it is allocated by this function.
4359**
4360** If the shared-memory region has already been allocated or is allocated by
4361** this call as described above, then it is mapped into this processes
4362** address space (if it is not already), *pp is set to point to the mapped
4363** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004364*/
danda9fe0c2010-07-13 18:44:03 +00004365static int unixShmMap(
4366 sqlite3_file *fd, /* Handle open on database file */
4367 int iRegion, /* Region to retrieve */
4368 int szRegion, /* Size of regions */
4369 int bExtend, /* True to extend file if necessary */
4370 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004371){
danda9fe0c2010-07-13 18:44:03 +00004372 unixFile *pDbFd = (unixFile*)fd;
4373 unixShm *p;
4374 unixShmNode *pShmNode;
4375 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004376 int nShmPerMap = unixShmRegionPerMap();
4377 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004378
danda9fe0c2010-07-13 18:44:03 +00004379 /* If the shared-memory file has not yet been opened, open it now. */
4380 if( pDbFd->pShm==0 ){
4381 rc = unixOpenSharedMemory(pDbFd);
4382 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004383 }
drhd9e5c4f2010-05-12 18:01:39 +00004384
danda9fe0c2010-07-13 18:44:03 +00004385 p = pDbFd->pShm;
4386 pShmNode = p->pShmNode;
4387 sqlite3_mutex_enter(pShmNode->mutex);
4388 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004389 assert( pShmNode->pInode==pDbFd->pInode );
4390 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4391 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004392
dan781e34c2014-03-20 08:59:47 +00004393 /* Minimum number of regions required to be mapped. */
4394 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4395
4396 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004397 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004398 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004399 struct stat sStat; /* Used by fstat() */
4400
4401 pShmNode->szRegion = szRegion;
4402
drh3cb93392011-03-12 18:10:44 +00004403 if( pShmNode->h>=0 ){
4404 /* The requested region is not mapped into this processes address space.
4405 ** Check to see if it has been allocated (i.e. if the wal-index file is
4406 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004407 */
drh3cb93392011-03-12 18:10:44 +00004408 if( osFstat(pShmNode->h, &sStat) ){
4409 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004410 goto shmpage_out;
4411 }
drh3cb93392011-03-12 18:10:44 +00004412
4413 if( sStat.st_size<nByte ){
4414 /* The requested memory region does not exist. If bExtend is set to
4415 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004416 */
dan47a2b4a2013-04-26 16:09:29 +00004417 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004418 goto shmpage_out;
4419 }
dan47a2b4a2013-04-26 16:09:29 +00004420
4421 /* Alternatively, if bExtend is true, extend the file. Do this by
4422 ** writing a single byte to the end of each (OS) page being
4423 ** allocated or extended. Technically, we need only write to the
4424 ** last page in order to extend the file. But writing to all new
4425 ** pages forces the OS to allocate them immediately, which reduces
4426 ** the chances of SIGBUS while accessing the mapped region later on.
4427 */
4428 else{
4429 static const int pgsz = 4096;
4430 int iPg;
4431
4432 /* Write to the last byte of each newly allocated or extended page */
4433 assert( (nByte % pgsz)==0 );
4434 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
4435 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
4436 const char *zFile = pShmNode->zFilename;
4437 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4438 goto shmpage_out;
4439 }
4440 }
drh3cb93392011-03-12 18:10:44 +00004441 }
4442 }
danda9fe0c2010-07-13 18:44:03 +00004443 }
4444
4445 /* Map the requested memory region into this processes address space. */
4446 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004447 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004448 );
4449 if( !apNew ){
4450 rc = SQLITE_IOERR_NOMEM;
4451 goto shmpage_out;
4452 }
4453 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004454 while( pShmNode->nRegion<nReqRegion ){
4455 int nMap = szRegion*nShmPerMap;
4456 int i;
drh3cb93392011-03-12 18:10:44 +00004457 void *pMem;
4458 if( pShmNode->h>=0 ){
dan781e34c2014-03-20 08:59:47 +00004459 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004460 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004461 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004462 );
4463 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004464 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004465 goto shmpage_out;
4466 }
4467 }else{
drhf3cdcdc2015-04-29 16:50:28 +00004468 pMem = sqlite3_malloc64(szRegion);
drh3cb93392011-03-12 18:10:44 +00004469 if( pMem==0 ){
4470 rc = SQLITE_NOMEM;
4471 goto shmpage_out;
4472 }
4473 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004474 }
dan781e34c2014-03-20 08:59:47 +00004475
4476 for(i=0; i<nShmPerMap; i++){
4477 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4478 }
4479 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004480 }
4481 }
4482
4483shmpage_out:
4484 if( pShmNode->nRegion>iRegion ){
4485 *pp = pShmNode->apRegion[iRegion];
4486 }else{
4487 *pp = 0;
4488 }
drh66dfec8b2011-06-01 20:01:49 +00004489 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004490 sqlite3_mutex_leave(pShmNode->mutex);
4491 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004492}
4493
4494/*
drhd9e5c4f2010-05-12 18:01:39 +00004495** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004496**
4497** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4498** different here than in posix. In xShmLock(), one can go from unlocked
4499** to shared and back or from unlocked to exclusive and back. But one may
4500** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004501*/
4502static int unixShmLock(
4503 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004504 int ofst, /* First lock to acquire or release */
4505 int n, /* Number of locks to acquire or release */
4506 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004507){
drh73b64e42010-05-30 19:55:15 +00004508 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4509 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4510 unixShm *pX; /* For looping over all siblings */
4511 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4512 int rc = SQLITE_OK; /* Result code */
4513 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004514
drhd91c68f2010-05-14 14:52:25 +00004515 assert( pShmNode==pDbFd->pInode->pShmNode );
4516 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004517 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004518 assert( n>=1 );
4519 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4520 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4521 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4522 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4523 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004524 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4525 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004526
drhc99597c2010-05-31 01:41:15 +00004527 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004528 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004529 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004530 if( flags & SQLITE_SHM_UNLOCK ){
4531 u16 allMask = 0; /* Mask of locks held by siblings */
4532
4533 /* See if any siblings hold this same lock */
4534 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4535 if( pX==p ) continue;
4536 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4537 allMask |= pX->sharedMask;
4538 }
4539
4540 /* Unlock the system-level locks */
4541 if( (mask & allMask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004542 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004543 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004544 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004545 }
drh73b64e42010-05-30 19:55:15 +00004546
4547 /* Undo the local locks */
4548 if( rc==SQLITE_OK ){
4549 p->exclMask &= ~mask;
4550 p->sharedMask &= ~mask;
4551 }
4552 }else if( flags & SQLITE_SHM_SHARED ){
4553 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4554
4555 /* Find out which shared locks are already held by sibling connections.
4556 ** If any sibling already holds an exclusive lock, go ahead and return
4557 ** SQLITE_BUSY.
4558 */
4559 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004560 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004561 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004562 break;
4563 }
4564 allShared |= pX->sharedMask;
4565 }
4566
4567 /* Get shared locks at the system level, if necessary */
4568 if( rc==SQLITE_OK ){
4569 if( (allShared & mask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004570 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004571 }else{
drh73b64e42010-05-30 19:55:15 +00004572 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004573 }
drhd9e5c4f2010-05-12 18:01:39 +00004574 }
drh73b64e42010-05-30 19:55:15 +00004575
4576 /* Get the local shared locks */
4577 if( rc==SQLITE_OK ){
4578 p->sharedMask |= mask;
4579 }
4580 }else{
4581 /* Make sure no sibling connections hold locks that will block this
4582 ** lock. If any do, return SQLITE_BUSY right away.
4583 */
4584 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004585 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4586 rc = SQLITE_BUSY;
4587 break;
4588 }
4589 }
4590
4591 /* Get the exclusive locks at the system level. Then if successful
4592 ** also mark the local connection as being locked.
4593 */
4594 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004595 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004596 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004597 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004598 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004599 }
drhd9e5c4f2010-05-12 18:01:39 +00004600 }
4601 }
drhd91c68f2010-05-14 14:52:25 +00004602 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004603 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
drh5ac93652015-03-21 20:59:43 +00004604 p->id, osGetpid(0), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004605 return rc;
4606}
4607
drh286a2882010-05-20 23:51:06 +00004608/*
4609** Implement a memory barrier or memory fence on shared memory.
4610**
4611** All loads and stores begun before the barrier must complete before
4612** any load or store begun after the barrier.
4613*/
4614static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004615 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004616){
drhff828942010-06-26 21:34:06 +00004617 UNUSED_PARAMETER(fd);
drh22c733d2015-09-24 12:40:43 +00004618 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
4619 unixEnterMutex(); /* Also mutex, for redundancy */
drhb29ad852010-06-01 00:03:57 +00004620 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004621}
4622
dan18801912010-06-14 14:07:50 +00004623/*
danda9fe0c2010-07-13 18:44:03 +00004624** Close a connection to shared-memory. Delete the underlying
4625** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004626**
4627** If there is no shared memory associated with the connection then this
4628** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004629*/
danda9fe0c2010-07-13 18:44:03 +00004630static int unixShmUnmap(
4631 sqlite3_file *fd, /* The underlying database file */
4632 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004633){
danda9fe0c2010-07-13 18:44:03 +00004634 unixShm *p; /* The connection to be closed */
4635 unixShmNode *pShmNode; /* The underlying shared-memory file */
4636 unixShm **pp; /* For looping over sibling connections */
4637 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004638
danda9fe0c2010-07-13 18:44:03 +00004639 pDbFd = (unixFile*)fd;
4640 p = pDbFd->pShm;
4641 if( p==0 ) return SQLITE_OK;
4642 pShmNode = p->pShmNode;
4643
4644 assert( pShmNode==pDbFd->pInode->pShmNode );
4645 assert( pShmNode->pInode==pDbFd->pInode );
4646
4647 /* Remove connection p from the set of connections associated
4648 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004649 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004650 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4651 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004652
danda9fe0c2010-07-13 18:44:03 +00004653 /* Free the connection p */
4654 sqlite3_free(p);
4655 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004656 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004657
4658 /* If pShmNode->nRef has reached 0, then close the underlying
4659 ** shared-memory file, too */
4660 unixEnterMutex();
4661 assert( pShmNode->nRef>0 );
4662 pShmNode->nRef--;
4663 if( pShmNode->nRef==0 ){
drh4bf66fd2015-02-19 02:43:02 +00004664 if( deleteFlag && pShmNode->h>=0 ){
4665 osUnlink(pShmNode->zFilename);
4666 }
danda9fe0c2010-07-13 18:44:03 +00004667 unixShmPurge(pDbFd);
4668 }
4669 unixLeaveMutex();
4670
4671 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004672}
drh286a2882010-05-20 23:51:06 +00004673
danda9fe0c2010-07-13 18:44:03 +00004674
drhd9e5c4f2010-05-12 18:01:39 +00004675#else
drh6b017cc2010-06-14 18:01:46 +00004676# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004677# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004678# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004679# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004680#endif /* #ifndef SQLITE_OMIT_WAL */
4681
mistachkine98844f2013-08-24 00:59:24 +00004682#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004683/*
danaef49d72013-03-25 16:28:54 +00004684** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004685*/
danf23da962013-03-23 21:00:41 +00004686static void unixUnmapfile(unixFile *pFd){
4687 assert( pFd->nFetchOut==0 );
4688 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004689 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004690 pFd->pMapRegion = 0;
4691 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004692 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004693 }
4694}
dan5d8a1372013-03-19 19:28:06 +00004695
danaef49d72013-03-25 16:28:54 +00004696/*
dane6ecd662013-04-01 17:56:59 +00004697** Attempt to set the size of the memory mapping maintained by file
4698** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4699**
4700** If successful, this function sets the following variables:
4701**
4702** unixFile.pMapRegion
4703** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004704** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004705**
4706** If unsuccessful, an error message is logged via sqlite3_log() and
4707** the three variables above are zeroed. In this case SQLite should
4708** continue accessing the database using the xRead() and xWrite()
4709** methods.
4710*/
4711static void unixRemapfile(
4712 unixFile *pFd, /* File descriptor object */
4713 i64 nNew /* Required mapping size */
4714){
dan4ff7bc42013-04-02 12:04:09 +00004715 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004716 int h = pFd->h; /* File descriptor open on db file */
4717 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004718 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004719 u8 *pNew = 0; /* Location of new mapping */
4720 int flags = PROT_READ; /* Flags to pass to mmap() */
4721
4722 assert( pFd->nFetchOut==0 );
4723 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004724 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004725 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004726 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004727 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004728
danfe33e392015-11-17 20:56:06 +00004729#ifdef SQLITE_MMAP_READWRITE
dane6ecd662013-04-01 17:56:59 +00004730 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
danfe33e392015-11-17 20:56:06 +00004731#endif
dane6ecd662013-04-01 17:56:59 +00004732
4733 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00004734#if HAVE_MREMAP
4735 i64 nReuse = pFd->mmapSize;
4736#else
danbc760632014-03-20 09:42:09 +00004737 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00004738 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00004739#endif
dane6ecd662013-04-01 17:56:59 +00004740 u8 *pReq = &pOrig[nReuse];
4741
4742 /* Unmap any pages of the existing mapping that cannot be reused. */
4743 if( nReuse!=nOrig ){
4744 osMunmap(pReq, nOrig-nReuse);
4745 }
4746
4747#if HAVE_MREMAP
4748 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004749 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004750#else
4751 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4752 if( pNew!=MAP_FAILED ){
4753 if( pNew!=pReq ){
4754 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004755 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004756 }else{
4757 pNew = pOrig;
4758 }
4759 }
4760#endif
4761
dan48ccef82013-04-02 20:55:01 +00004762 /* The attempt to extend the existing mapping failed. Free it. */
4763 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004764 osMunmap(pOrig, nReuse);
4765 }
4766 }
4767
4768 /* If pNew is still NULL, try to create an entirely new mapping. */
4769 if( pNew==0 ){
4770 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004771 }
4772
dan4ff7bc42013-04-02 12:04:09 +00004773 if( pNew==MAP_FAILED ){
4774 pNew = 0;
4775 nNew = 0;
4776 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4777
4778 /* If the mmap() above failed, assume that all subsequent mmap() calls
4779 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4780 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004781 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004782 }
dane6ecd662013-04-01 17:56:59 +00004783 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004784 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004785}
4786
4787/*
danaef49d72013-03-25 16:28:54 +00004788** Memory map or remap the file opened by file-descriptor pFd (if the file
4789** is already mapped, the existing mapping is replaced by the new). Or, if
4790** there already exists a mapping for this file, and there are still
4791** outstanding xFetch() references to it, this function is a no-op.
4792**
4793** If parameter nByte is non-negative, then it is the requested size of
4794** the mapping to create. Otherwise, if nByte is less than zero, then the
4795** requested size is the size of the file on disk. The actual size of the
4796** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004797** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004798**
4799** SQLITE_OK is returned if no error occurs (even if the mapping is not
4800** recreated as a result of outstanding references) or an SQLite error
4801** code otherwise.
4802*/
danf23da962013-03-23 21:00:41 +00004803static int unixMapfile(unixFile *pFd, i64 nByte){
4804 i64 nMap = nByte;
4805 int rc;
daneb97b292013-03-20 14:26:59 +00004806
danf23da962013-03-23 21:00:41 +00004807 assert( nMap>=0 || pFd->nFetchOut==0 );
4808 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4809
4810 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00004811 struct stat statbuf; /* Low-level file information */
4812 rc = osFstat(pFd->h, &statbuf);
danf23da962013-03-23 21:00:41 +00004813 if( rc!=SQLITE_OK ){
4814 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004815 }
drh3044b512014-06-16 16:41:52 +00004816 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00004817 }
drh9b4c59f2013-04-15 17:03:42 +00004818 if( nMap>pFd->mmapSizeMax ){
4819 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004820 }
4821
danf23da962013-03-23 21:00:41 +00004822 if( nMap!=pFd->mmapSize ){
dane6ecd662013-04-01 17:56:59 +00004823 if( nMap>0 ){
4824 unixRemapfile(pFd, nMap);
4825 }else{
danb7e3a322013-03-25 20:30:13 +00004826 unixUnmapfile(pFd);
dan5d8a1372013-03-19 19:28:06 +00004827 }
4828 }
4829
danf23da962013-03-23 21:00:41 +00004830 return SQLITE_OK;
4831}
mistachkine98844f2013-08-24 00:59:24 +00004832#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004833
danaef49d72013-03-25 16:28:54 +00004834/*
4835** If possible, return a pointer to a mapping of file fd starting at offset
4836** iOff. The mapping must be valid for at least nAmt bytes.
4837**
4838** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4839** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4840** Finally, if an error does occur, return an SQLite error code. The final
4841** value of *pp is undefined in this case.
4842**
4843** If this function does return a pointer, the caller must eventually
4844** release the reference by calling unixUnfetch().
4845*/
danf23da962013-03-23 21:00:41 +00004846static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004847#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004848 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004849#endif
danf23da962013-03-23 21:00:41 +00004850 *pp = 0;
4851
drh9b4c59f2013-04-15 17:03:42 +00004852#if SQLITE_MAX_MMAP_SIZE>0
4853 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004854 if( pFd->pMapRegion==0 ){
4855 int rc = unixMapfile(pFd, -1);
4856 if( rc!=SQLITE_OK ) return rc;
4857 }
4858 if( pFd->mmapSize >= iOff+nAmt ){
4859 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4860 pFd->nFetchOut++;
4861 }
4862 }
drh6e0b6d52013-04-09 16:19:20 +00004863#endif
danf23da962013-03-23 21:00:41 +00004864 return SQLITE_OK;
4865}
4866
danaef49d72013-03-25 16:28:54 +00004867/*
dandf737fe2013-03-25 17:00:24 +00004868** If the third argument is non-NULL, then this function releases a
4869** reference obtained by an earlier call to unixFetch(). The second
4870** argument passed to this function must be the same as the corresponding
4871** argument that was passed to the unixFetch() invocation.
4872**
4873** Or, if the third argument is NULL, then this function is being called
4874** to inform the VFS layer that, according to POSIX, any existing mapping
4875** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004876*/
dandf737fe2013-03-25 17:00:24 +00004877static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00004878#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00004879 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00004880 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00004881
danaef49d72013-03-25 16:28:54 +00004882 /* If p==0 (unmap the entire file) then there must be no outstanding
4883 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4884 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004885 assert( (p==0)==(pFd->nFetchOut==0) );
4886
dandf737fe2013-03-25 17:00:24 +00004887 /* If p!=0, it must match the iOff value. */
4888 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4889
danf23da962013-03-23 21:00:41 +00004890 if( p ){
4891 pFd->nFetchOut--;
4892 }else{
4893 unixUnmapfile(pFd);
4894 }
4895
4896 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00004897#else
4898 UNUSED_PARAMETER(fd);
4899 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00004900 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00004901#endif
danf23da962013-03-23 21:00:41 +00004902 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004903}
4904
4905/*
drh734c9862008-11-28 15:37:20 +00004906** Here ends the implementation of all sqlite3_file methods.
4907**
4908********************** End sqlite3_file Methods *******************************
4909******************************************************************************/
4910
4911/*
drh6b9d6dd2008-12-03 19:34:47 +00004912** This division contains definitions of sqlite3_io_methods objects that
4913** implement various file locking strategies. It also contains definitions
4914** of "finder" functions. A finder-function is used to locate the appropriate
4915** sqlite3_io_methods object for a particular database file. The pAppData
4916** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4917** the correct finder-function for that VFS.
4918**
4919** Most finder functions return a pointer to a fixed sqlite3_io_methods
4920** object. The only interesting finder-function is autolockIoFinder, which
4921** looks at the filesystem type and tries to guess the best locking
4922** strategy from that.
4923**
peter.d.reid60ec9142014-09-06 16:39:46 +00004924** For finder-function F, two objects are created:
drh1875f7a2008-12-08 18:19:17 +00004925**
4926** (1) The real finder-function named "FImpt()".
4927**
dane946c392009-08-22 11:39:46 +00004928** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004929**
4930**
4931** A pointer to the F pointer is used as the pAppData value for VFS
4932** objects. We have to do this instead of letting pAppData point
4933** directly at the finder-function since C90 rules prevent a void*
4934** from be cast into a function pointer.
4935**
drh6b9d6dd2008-12-03 19:34:47 +00004936**
drh7708e972008-11-29 00:56:52 +00004937** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004938**
drh7708e972008-11-29 00:56:52 +00004939** * A constant sqlite3_io_methods object call METHOD that has locking
4940** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4941**
4942** * An I/O method finder function called FINDER that returns a pointer
4943** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004944*/
drhe6d41732015-02-21 00:49:00 +00004945#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
drh7708e972008-11-29 00:56:52 +00004946static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004947 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004948 CLOSE, /* xClose */ \
4949 unixRead, /* xRead */ \
4950 unixWrite, /* xWrite */ \
4951 unixTruncate, /* xTruncate */ \
4952 unixSync, /* xSync */ \
4953 unixFileSize, /* xFileSize */ \
4954 LOCK, /* xLock */ \
4955 UNLOCK, /* xUnlock */ \
4956 CKLOCK, /* xCheckReservedLock */ \
4957 unixFileControl, /* xFileControl */ \
4958 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004959 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drhd9f94412014-09-22 03:22:27 +00004960 SHMMAP, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004961 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004962 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00004963 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00004964 unixFetch, /* xFetch */ \
4965 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00004966}; \
drh0c2694b2009-09-03 16:23:44 +00004967static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4968 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004969 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004970} \
drh0c2694b2009-09-03 16:23:44 +00004971static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004972 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004973
4974/*
4975** Here are all of the sqlite3_io_methods objects for each of the
4976** locking strategies. Functions that return pointers to these methods
4977** are also created.
4978*/
4979IOMETHODS(
4980 posixIoFinder, /* Finder function name */
4981 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00004982 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00004983 unixClose, /* xClose method */
4984 unixLock, /* xLock method */
4985 unixUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004986 unixCheckReservedLock, /* xCheckReservedLock method */
4987 unixShmMap /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004988)
drh7708e972008-11-29 00:56:52 +00004989IOMETHODS(
4990 nolockIoFinder, /* Finder function name */
4991 nolockIoMethods, /* sqlite3_io_methods object name */
drh142341c2014-09-19 19:00:48 +00004992 3, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004993 nolockClose, /* xClose method */
4994 nolockLock, /* xLock method */
4995 nolockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004996 nolockCheckReservedLock, /* xCheckReservedLock method */
4997 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004998)
drh7708e972008-11-29 00:56:52 +00004999IOMETHODS(
5000 dotlockIoFinder, /* Finder function name */
5001 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005002 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005003 dotlockClose, /* xClose method */
5004 dotlockLock, /* xLock method */
5005 dotlockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005006 dotlockCheckReservedLock, /* xCheckReservedLock method */
5007 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005008)
drh7708e972008-11-29 00:56:52 +00005009
drhe89b2912015-03-03 20:42:01 +00005010#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005011IOMETHODS(
5012 flockIoFinder, /* Finder function name */
5013 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005014 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005015 flockClose, /* xClose method */
5016 flockLock, /* xLock method */
5017 flockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005018 flockCheckReservedLock, /* xCheckReservedLock method */
5019 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005020)
drh7708e972008-11-29 00:56:52 +00005021#endif
5022
drh6c7d5c52008-11-21 20:32:33 +00005023#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005024IOMETHODS(
5025 semIoFinder, /* Finder function name */
5026 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005027 1, /* shared memory is disabled */
drh8cd5b252015-03-02 22:06:43 +00005028 semXClose, /* xClose method */
5029 semXLock, /* xLock method */
5030 semXUnlock, /* xUnlock method */
5031 semXCheckReservedLock, /* xCheckReservedLock method */
drhd9f94412014-09-22 03:22:27 +00005032 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005033)
aswiftaebf4132008-11-21 00:10:35 +00005034#endif
drh7708e972008-11-29 00:56:52 +00005035
drhd2cb50b2009-01-09 21:41:17 +00005036#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005037IOMETHODS(
5038 afpIoFinder, /* Finder function name */
5039 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005040 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005041 afpClose, /* xClose method */
5042 afpLock, /* xLock method */
5043 afpUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005044 afpCheckReservedLock, /* xCheckReservedLock method */
5045 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005046)
drh715ff302008-12-03 22:32:44 +00005047#endif
5048
5049/*
5050** The proxy locking method is a "super-method" in the sense that it
5051** opens secondary file descriptors for the conch and lock files and
5052** it uses proxy, dot-file, AFP, and flock() locking methods on those
5053** secondary files. For this reason, the division that implements
5054** proxy locking is located much further down in the file. But we need
5055** to go ahead and define the sqlite3_io_methods and finder function
5056** for proxy locking here. So we forward declare the I/O methods.
5057*/
drhd2cb50b2009-01-09 21:41:17 +00005058#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005059static int proxyClose(sqlite3_file*);
5060static int proxyLock(sqlite3_file*, int);
5061static int proxyUnlock(sqlite3_file*, int);
5062static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005063IOMETHODS(
5064 proxyIoFinder, /* Finder function name */
5065 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005066 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005067 proxyClose, /* xClose method */
5068 proxyLock, /* xLock method */
5069 proxyUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005070 proxyCheckReservedLock, /* xCheckReservedLock method */
5071 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005072)
aswiftaebf4132008-11-21 00:10:35 +00005073#endif
drh7708e972008-11-29 00:56:52 +00005074
drh7ed97b92010-01-20 13:07:21 +00005075/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5076#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5077IOMETHODS(
5078 nfsIoFinder, /* Finder function name */
5079 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005080 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005081 unixClose, /* xClose method */
5082 unixLock, /* xLock method */
5083 nfsUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005084 unixCheckReservedLock, /* xCheckReservedLock method */
5085 0 /* xShmMap method */
drh7ed97b92010-01-20 13:07:21 +00005086)
5087#endif
drh7708e972008-11-29 00:56:52 +00005088
drhd2cb50b2009-01-09 21:41:17 +00005089#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005090/*
drh6b9d6dd2008-12-03 19:34:47 +00005091** This "finder" function attempts to determine the best locking strategy
5092** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005093** object that implements that strategy.
5094**
5095** This is for MacOSX only.
5096*/
drh1875f7a2008-12-08 18:19:17 +00005097static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005098 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005099 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005100){
5101 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005102 const char *zFilesystem; /* Filesystem type name */
5103 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005104 } aMap[] = {
5105 { "hfs", &posixIoMethods },
5106 { "ufs", &posixIoMethods },
5107 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005108 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005109 { "webdav", &nolockIoMethods },
5110 { 0, 0 }
5111 };
5112 int i;
5113 struct statfs fsInfo;
5114 struct flock lockInfo;
5115
5116 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005117 /* If filePath==NULL that means we are dealing with a transient file
5118 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005119 return &nolockIoMethods;
5120 }
5121 if( statfs(filePath, &fsInfo) != -1 ){
5122 if( fsInfo.f_flags & MNT_RDONLY ){
5123 return &nolockIoMethods;
5124 }
5125 for(i=0; aMap[i].zFilesystem; i++){
5126 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5127 return aMap[i].pMethods;
5128 }
5129 }
5130 }
5131
5132 /* Default case. Handles, amongst others, "nfs".
5133 ** Test byte-range lock using fcntl(). If the call succeeds,
5134 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005135 */
drh7708e972008-11-29 00:56:52 +00005136 lockInfo.l_len = 1;
5137 lockInfo.l_start = 0;
5138 lockInfo.l_whence = SEEK_SET;
5139 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005140 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005141 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5142 return &nfsIoMethods;
5143 } else {
5144 return &posixIoMethods;
5145 }
drh7708e972008-11-29 00:56:52 +00005146 }else{
5147 return &dotlockIoMethods;
5148 }
5149}
drh0c2694b2009-09-03 16:23:44 +00005150static const sqlite3_io_methods
5151 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005152
drhd2cb50b2009-01-09 21:41:17 +00005153#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005154
drhe89b2912015-03-03 20:42:01 +00005155#if OS_VXWORKS
5156/*
5157** This "finder" function for VxWorks checks to see if posix advisory
5158** locking works. If it does, then that is what is used. If it does not
5159** work, then fallback to named semaphore locking.
chw78a13182009-04-07 05:35:03 +00005160*/
drhe89b2912015-03-03 20:42:01 +00005161static const sqlite3_io_methods *vxworksIoFinderImpl(
chw78a13182009-04-07 05:35:03 +00005162 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005163 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005164){
5165 struct flock lockInfo;
5166
5167 if( !filePath ){
5168 /* If filePath==NULL that means we are dealing with a transient file
5169 ** that does not need to be locked. */
5170 return &nolockIoMethods;
5171 }
5172
5173 /* Test if fcntl() is supported and use POSIX style locks.
5174 ** Otherwise fall back to the named semaphore method.
5175 */
5176 lockInfo.l_len = 1;
5177 lockInfo.l_start = 0;
5178 lockInfo.l_whence = SEEK_SET;
5179 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005180 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005181 return &posixIoMethods;
5182 }else{
5183 return &semIoMethods;
5184 }
5185}
drh0c2694b2009-09-03 16:23:44 +00005186static const sqlite3_io_methods
drhe89b2912015-03-03 20:42:01 +00005187 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005188
drhe89b2912015-03-03 20:42:01 +00005189#endif /* OS_VXWORKS */
chw78a13182009-04-07 05:35:03 +00005190
drh7708e972008-11-29 00:56:52 +00005191/*
peter.d.reid60ec9142014-09-06 16:39:46 +00005192** An abstract type for a pointer to an IO method finder function:
drh7708e972008-11-29 00:56:52 +00005193*/
drh0c2694b2009-09-03 16:23:44 +00005194typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005195
aswiftaebf4132008-11-21 00:10:35 +00005196
drh734c9862008-11-28 15:37:20 +00005197/****************************************************************************
5198**************************** sqlite3_vfs methods ****************************
5199**
5200** This division contains the implementation of methods on the
5201** sqlite3_vfs object.
5202*/
5203
danielk1977a3d4c882007-03-23 10:08:38 +00005204/*
danielk1977e339d652008-06-28 11:23:00 +00005205** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005206*/
5207static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005208 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005209 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005210 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005211 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005212 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005213){
drh7708e972008-11-29 00:56:52 +00005214 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005215 unixFile *pNew = (unixFile *)pId;
5216 int rc = SQLITE_OK;
5217
drh8af6c222010-05-14 12:43:01 +00005218 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005219
dan00157392010-10-05 11:33:15 +00005220 /* Usually the path zFilename should not be a relative pathname. The
5221 ** exception is when opening the proxy "conch" file in builds that
5222 ** include the special Apple locking styles.
5223 */
dan00157392010-10-05 11:33:15 +00005224#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005225 assert( zFilename==0 || zFilename[0]=='/'
5226 || pVfs->pAppData==(void*)&autolockIoFinder );
5227#else
5228 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005229#endif
dan00157392010-10-05 11:33:15 +00005230
drhb07028f2011-10-14 21:49:18 +00005231 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005232 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005233
drh308c2a52010-05-14 11:30:18 +00005234 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005235 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005236 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005237 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005238 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005239#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005240 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005241#endif
drhc02a43a2012-01-10 23:18:38 +00005242 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5243 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005244 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005245 }
drh503a6862013-03-01 01:07:17 +00005246 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005247 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005248 }
drh339eb0b2008-03-07 15:34:11 +00005249
drh6c7d5c52008-11-21 20:32:33 +00005250#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005251 pNew->pId = vxworksFindFileId(zFilename);
5252 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005253 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00005254 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00005255 }
5256#endif
5257
drhc02a43a2012-01-10 23:18:38 +00005258 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005259 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005260 }else{
drh0c2694b2009-09-03 16:23:44 +00005261 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005262#if SQLITE_ENABLE_LOCKING_STYLE
5263 /* Cache zFilename in the locking context (AFP and dotlock override) for
5264 ** proxyLock activation is possible (remote proxy is based on db name)
5265 ** zFilename remains valid until file is closed, to support */
5266 pNew->lockingContext = (void*)zFilename;
5267#endif
drhda0e7682008-07-30 15:27:54 +00005268 }
danielk1977e339d652008-06-28 11:23:00 +00005269
drh7ed97b92010-01-20 13:07:21 +00005270 if( pLockingStyle == &posixIoMethods
5271#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5272 || pLockingStyle == &nfsIoMethods
5273#endif
5274 ){
drh7708e972008-11-29 00:56:52 +00005275 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005276 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005277 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005278 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005279 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005280 ** in two scenarios:
5281 **
5282 ** (a) A call to fstat() failed.
5283 ** (b) A malloc failed.
5284 **
5285 ** Scenario (b) may only occur if the process is holding no other
5286 ** file descriptors open on the same file. If there were other file
5287 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005288 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005289 ** handle h - as it is guaranteed that no posix locks will be released
5290 ** by doing so.
5291 **
5292 ** If scenario (a) caused the error then things are not so safe. The
5293 ** implicit assumption here is that if fstat() fails, things are in
5294 ** such bad shape that dropping a lock or two doesn't matter much.
5295 */
drh0e9365c2011-03-02 02:08:13 +00005296 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005297 h = -1;
5298 }
drh7708e972008-11-29 00:56:52 +00005299 unixLeaveMutex();
5300 }
danielk1977e339d652008-06-28 11:23:00 +00005301
drhd2cb50b2009-01-09 21:41:17 +00005302#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005303 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005304 /* AFP locking uses the file path so it needs to be included in
5305 ** the afpLockingContext.
5306 */
5307 afpLockingContext *pCtx;
drhf3cdcdc2015-04-29 16:50:28 +00005308 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh7708e972008-11-29 00:56:52 +00005309 if( pCtx==0 ){
5310 rc = SQLITE_NOMEM;
5311 }else{
5312 /* NB: zFilename exists and remains valid until the file is closed
5313 ** according to requirement F11141. So we do not need to make a
5314 ** copy of the filename. */
5315 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005316 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005317 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005318 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005319 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005320 if( rc!=SQLITE_OK ){
5321 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005322 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005323 h = -1;
5324 }
drh7708e972008-11-29 00:56:52 +00005325 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005326 }
drh7708e972008-11-29 00:56:52 +00005327 }
5328#endif
danielk1977e339d652008-06-28 11:23:00 +00005329
drh7708e972008-11-29 00:56:52 +00005330 else if( pLockingStyle == &dotlockIoMethods ){
5331 /* Dotfile locking uses the file path so it needs to be included in
5332 ** the dotlockLockingContext
5333 */
5334 char *zLockFile;
5335 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005336 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005337 nFilename = (int)strlen(zFilename) + 6;
drhf3cdcdc2015-04-29 16:50:28 +00005338 zLockFile = (char *)sqlite3_malloc64(nFilename);
drh7708e972008-11-29 00:56:52 +00005339 if( zLockFile==0 ){
5340 rc = SQLITE_NOMEM;
5341 }else{
5342 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005343 }
drh7708e972008-11-29 00:56:52 +00005344 pNew->lockingContext = zLockFile;
5345 }
danielk1977e339d652008-06-28 11:23:00 +00005346
drh6c7d5c52008-11-21 20:32:33 +00005347#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005348 else if( pLockingStyle == &semIoMethods ){
5349 /* Named semaphore locking uses the file path so it needs to be
5350 ** included in the semLockingContext
5351 */
5352 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005353 rc = findInodeInfo(pNew, &pNew->pInode);
5354 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5355 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005356 int n;
drh2238dcc2009-08-27 17:56:20 +00005357 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005358 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005359 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005360 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005361 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5362 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00005363 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00005364 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005365 }
chw97185482008-11-17 08:05:31 +00005366 }
drh7708e972008-11-29 00:56:52 +00005367 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005368 }
drh7708e972008-11-29 00:56:52 +00005369#endif
aswift5b1a2562008-08-22 00:22:35 +00005370
drh4bf66fd2015-02-19 02:43:02 +00005371 storeLastErrno(pNew, 0);
drh6c7d5c52008-11-21 20:32:33 +00005372#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005373 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005374 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005375 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005376 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005377 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005378 }
chw97185482008-11-17 08:05:31 +00005379#endif
danielk1977e339d652008-06-28 11:23:00 +00005380 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005381 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005382 }else{
drh7708e972008-11-29 00:56:52 +00005383 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005384 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005385 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005386 }
danielk1977e339d652008-06-28 11:23:00 +00005387 return rc;
drh054889e2005-11-30 03:20:31 +00005388}
drh9c06c952005-11-26 00:25:00 +00005389
danielk1977ad94b582007-08-20 06:44:22 +00005390/*
drh8b3cf822010-06-01 21:02:51 +00005391** Return the name of a directory in which to put temporary files.
5392** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005393*/
drh7234c6d2010-06-19 15:10:09 +00005394static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005395 static const char *azDirs[] = {
5396 0,
aswiftaebf4132008-11-21 00:10:35 +00005397 0,
mistachkind95a3d32013-08-30 21:52:38 +00005398 0,
danielk197717b90b52008-06-06 11:11:25 +00005399 "/var/tmp",
5400 "/usr/tmp",
5401 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00005402 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00005403 };
drh8b3cf822010-06-01 21:02:51 +00005404 unsigned int i;
5405 struct stat buf;
5406 const char *zDir = 0;
5407
5408 azDirs[0] = sqlite3_temp_directory;
mistachkind95a3d32013-08-30 21:52:38 +00005409 if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
5410 if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005411 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005412 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005413 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005414 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005415 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005416 break;
5417 }
5418 return zDir;
5419}
5420
5421/*
5422** Create a temporary file name in zBuf. zBuf must be allocated
5423** by the calling process and must be big enough to hold at least
5424** pVfs->mxPathname bytes.
5425*/
5426static int unixGetTempname(int nBuf, char *zBuf){
drh8b3cf822010-06-01 21:02:51 +00005427 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00005428
5429 /* It's odd to simulate an io-error here, but really this is just
5430 ** using the io-error infrastructure to test that SQLite handles this
5431 ** function failing.
5432 */
5433 SimulateIOError( return SQLITE_IOERR );
5434
drh7234c6d2010-06-19 15:10:09 +00005435 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00005436 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00005437 do{
drh970942e2015-11-25 23:13:14 +00005438 u64 r;
5439 sqlite3_randomness(sizeof(r), &r);
5440 assert( nBuf>2 );
5441 zBuf[nBuf-2] = 0;
5442 sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
5443 zDir, r, 0);
5444 if( zBuf[nBuf-2]!=0 ) return SQLITE_ERROR;
drh99ab3b12011-03-02 15:09:07 +00005445 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005446 return SQLITE_OK;
5447}
5448
drhd2cb50b2009-01-09 21:41:17 +00005449#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005450/*
5451** Routine to transform a unixFile into a proxy-locking unixFile.
5452** Implementation in the proxy-lock division, but used by unixOpen()
5453** if SQLITE_PREFER_PROXY_LOCKING is defined.
5454*/
5455static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005456#endif
drhc66d5b62008-12-03 22:48:32 +00005457
dan08da86a2009-08-21 17:18:03 +00005458/*
5459** Search for an unused file descriptor that was opened on the database
5460** file (not a journal or master-journal file) identified by pathname
5461** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5462** argument to this function.
5463**
5464** Such a file descriptor may exist if a database connection was closed
5465** but the associated file descriptor could not be closed because some
5466** other file descriptor open on the same file is holding a file-lock.
5467** Refer to comments in the unixClose() function and the lengthy comment
5468** describing "Posix Advisory Locking" at the start of this file for
5469** further details. Also, ticket #4018.
5470**
5471** If a suitable file descriptor is found, then it is returned. If no
5472** such file descriptor is located, -1 is returned.
5473*/
dane946c392009-08-22 11:39:46 +00005474static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5475 UnixUnusedFd *pUnused = 0;
5476
5477 /* Do not search for an unused file descriptor on vxworks. Not because
5478 ** vxworks would not benefit from the change (it might, we're not sure),
5479 ** but because no way to test it is currently available. It is better
5480 ** not to risk breaking vxworks support for the sake of such an obscure
5481 ** feature. */
5482#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005483 struct stat sStat; /* Results of stat() call */
5484
5485 /* A stat() call may fail for various reasons. If this happens, it is
5486 ** almost certain that an open() call on the same path will also fail.
5487 ** For this reason, if an error occurs in the stat() call here, it is
5488 ** ignored and -1 is returned. The caller will try to open a new file
5489 ** descriptor on the same path, fail, and return an error to SQLite.
5490 **
5491 ** Even if a subsequent open() call does succeed, the consequences of
peter.d.reid60ec9142014-09-06 16:39:46 +00005492 ** not searching for a reusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005493 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005494 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005495
5496 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005497 pInode = inodeList;
5498 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5499 || pInode->fileId.ino!=sStat.st_ino) ){
5500 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005501 }
drh8af6c222010-05-14 12:43:01 +00005502 if( pInode ){
dane946c392009-08-22 11:39:46 +00005503 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005504 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005505 pUnused = *pp;
5506 if( pUnused ){
5507 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005508 }
5509 }
5510 unixLeaveMutex();
5511 }
dane946c392009-08-22 11:39:46 +00005512#endif /* if !OS_VXWORKS */
5513 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005514}
danielk197717b90b52008-06-06 11:11:25 +00005515
5516/*
danddb0ac42010-07-14 14:48:58 +00005517** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005518** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005519** and a value suitable for passing as the third argument to open(2) is
5520** written to *pMode. If an IO error occurs, an SQLite error code is
5521** returned and the value of *pMode is not modified.
5522**
peter.d.reid60ec9142014-09-06 16:39:46 +00005523** In most cases, this routine sets *pMode to 0, which will become
drh8c815d12012-02-13 20:16:37 +00005524** an indication to robust_open() to create the file using
5525** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5526** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005527** this function queries the file-system for the permissions on the
5528** corresponding database file and sets *pMode to this value. Whenever
5529** possible, WAL and journal files are created using the same permissions
5530** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005531**
5532** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5533** original filename is unavailable. But 8_3_NAMES is only used for
5534** FAT filesystems and permissions do not matter there, so just use
5535** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005536*/
5537static int findCreateFileMode(
5538 const char *zPath, /* Path of file (possibly) being created */
5539 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005540 mode_t *pMode, /* OUT: Permissions to open file with */
5541 uid_t *pUid, /* OUT: uid to set on the file */
5542 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005543){
5544 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005545 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005546 *pUid = 0;
5547 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005548 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005549 char zDb[MAX_PATHNAME+1]; /* Database file path */
5550 int nDb; /* Number of valid bytes in zDb */
5551 struct stat sStat; /* Output of stat() on database file */
5552
dana0c989d2010-11-05 18:07:37 +00005553 /* zPath is a path to a WAL or journal file. The following block derives
5554 ** the path to the associated database file from zPath. This block handles
5555 ** the following naming conventions:
5556 **
5557 ** "<path to db>-journal"
5558 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005559 ** "<path to db>-journalNN"
5560 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005561 **
drhd337c5b2011-10-20 18:23:35 +00005562 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005563 ** used by the test_multiplex.c module.
5564 */
5565 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005566#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00005567 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00005568 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005569#else
5570 while( zPath[nDb]!='-' ){
5571 assert( nDb>0 );
5572 assert( zPath[nDb]!='\n' );
5573 nDb--;
5574 }
5575#endif
danddb0ac42010-07-14 14:48:58 +00005576 memcpy(zDb, zPath, nDb);
5577 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005578
drh58384f12011-07-28 00:14:45 +00005579 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005580 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005581 *pUid = sStat.st_uid;
5582 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005583 }else{
5584 rc = SQLITE_IOERR_FSTAT;
5585 }
5586 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5587 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005588 }
5589 return rc;
5590}
5591
5592/*
danielk1977ad94b582007-08-20 06:44:22 +00005593** Open the file zPath.
5594**
danielk1977b4b47412007-08-17 15:53:36 +00005595** Previously, the SQLite OS layer used three functions in place of this
5596** one:
5597**
5598** sqlite3OsOpenReadWrite();
5599** sqlite3OsOpenReadOnly();
5600** sqlite3OsOpenExclusive();
5601**
5602** These calls correspond to the following combinations of flags:
5603**
5604** ReadWrite() -> (READWRITE | CREATE)
5605** ReadOnly() -> (READONLY)
5606** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5607**
5608** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5609** true, the file was configured to be automatically deleted when the
5610** file handle closed. To achieve the same effect using this new
5611** interface, add the DELETEONCLOSE flag to those specified above for
5612** OpenExclusive().
5613*/
5614static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005615 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5616 const char *zPath, /* Pathname of file to be opened */
5617 sqlite3_file *pFile, /* The file descriptor to be filled in */
5618 int flags, /* Input flags to control the opening */
5619 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005620){
dan08da86a2009-08-21 17:18:03 +00005621 unixFile *p = (unixFile *)pFile;
5622 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005623 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005624 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005625 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005626 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005627 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005628
5629 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5630 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5631 int isCreate = (flags & SQLITE_OPEN_CREATE);
5632 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5633 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005634#if SQLITE_ENABLE_LOCKING_STYLE
5635 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5636#endif
drh3d4435b2011-08-26 20:55:50 +00005637#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5638 struct statfs fsInfo;
5639#endif
danielk1977b4b47412007-08-17 15:53:36 +00005640
danielk1977fee2d252007-08-18 10:59:19 +00005641 /* If creating a master or main-file journal, this function will open
5642 ** a file-descriptor on the directory too. The first time unixSync()
5643 ** is called the directory file descriptor will be fsync()ed and close()d.
5644 */
drh0059eae2011-08-08 23:48:40 +00005645 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005646 eType==SQLITE_OPEN_MASTER_JOURNAL
5647 || eType==SQLITE_OPEN_MAIN_JOURNAL
5648 || eType==SQLITE_OPEN_WAL
5649 ));
danielk1977fee2d252007-08-18 10:59:19 +00005650
danielk197717b90b52008-06-06 11:11:25 +00005651 /* If argument zPath is a NULL pointer, this function is required to open
5652 ** a temporary file. Use this buffer to store the file name in.
5653 */
drhc02a43a2012-01-10 23:18:38 +00005654 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005655 const char *zName = zPath;
5656
danielk1977fee2d252007-08-18 10:59:19 +00005657 /* Check the following statements are true:
5658 **
5659 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5660 ** (b) if CREATE is set, then READWRITE must also be set, and
5661 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005662 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005663 */
danielk1977b4b47412007-08-17 15:53:36 +00005664 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005665 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005666 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005667 assert(isDelete==0 || isCreate);
5668
danddb0ac42010-07-14 14:48:58 +00005669 /* The main DB, main journal, WAL file and master journal are never
5670 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005671 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5672 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5673 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005674 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005675
danielk1977fee2d252007-08-18 10:59:19 +00005676 /* Assert that the upper layer has set one of the "file-type" flags. */
5677 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5678 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5679 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005680 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005681 );
5682
drhb00d8622014-01-01 15:18:36 +00005683 /* Detect a pid change and reset the PRNG. There is a race condition
5684 ** here such that two or more threads all trying to open databases at
5685 ** the same instant might all reset the PRNG. But multiple resets
5686 ** are harmless.
5687 */
drh5ac93652015-03-21 20:59:43 +00005688 if( randomnessPid!=osGetpid(0) ){
5689 randomnessPid = osGetpid(0);
drhb00d8622014-01-01 15:18:36 +00005690 sqlite3_randomness(0,0);
5691 }
5692
dan08da86a2009-08-21 17:18:03 +00005693 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005694
dan08da86a2009-08-21 17:18:03 +00005695 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005696 UnixUnusedFd *pUnused;
5697 pUnused = findReusableFd(zName, flags);
5698 if( pUnused ){
5699 fd = pUnused->fd;
5700 }else{
drhf3cdcdc2015-04-29 16:50:28 +00005701 pUnused = sqlite3_malloc64(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005702 if( !pUnused ){
5703 return SQLITE_NOMEM;
5704 }
5705 }
5706 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005707
5708 /* Database filenames are double-zero terminated if they are not
5709 ** URIs with parameters. Hence, they can always be passed into
5710 ** sqlite3_uri_parameter(). */
5711 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5712
dan08da86a2009-08-21 17:18:03 +00005713 }else if( !zName ){
5714 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005715 assert(isDelete && !syncDir);
drhc02a43a2012-01-10 23:18:38 +00005716 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005717 if( rc!=SQLITE_OK ){
5718 return rc;
5719 }
5720 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005721
5722 /* Generated temporary filenames are always double-zero terminated
5723 ** for use by sqlite3_uri_parameter(). */
5724 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005725 }
5726
dan08da86a2009-08-21 17:18:03 +00005727 /* Determine the value of the flags parameter passed to POSIX function
5728 ** open(). These must be calculated even if open() is not called, as
5729 ** they may be stored as part of the file handle and used by the
5730 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005731 if( isReadonly ) openFlags |= O_RDONLY;
5732 if( isReadWrite ) openFlags |= O_RDWR;
5733 if( isCreate ) openFlags |= O_CREAT;
5734 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5735 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005736
danielk1977b4b47412007-08-17 15:53:36 +00005737 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005738 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005739 uid_t uid; /* Userid for the file */
5740 gid_t gid; /* Groupid for the file */
5741 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005742 if( rc!=SQLITE_OK ){
5743 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005744 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005745 return rc;
5746 }
drhad4f1e52011-03-04 15:43:57 +00005747 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005748 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005749 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5750 /* Failed to open the file for read/write access. Try read-only. */
5751 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005752 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005753 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005754 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005755 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005756 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005757 }
5758 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005759 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005760 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005761 }
drhac7c3ac2012-02-11 19:23:48 +00005762
5763 /* If this process is running as root and if creating a new rollback
5764 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005765 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005766 */
5767 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drh6226ca22015-11-24 15:06:28 +00005768 robustFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005769 }
danielk1977b4b47412007-08-17 15:53:36 +00005770 }
dan08da86a2009-08-21 17:18:03 +00005771 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005772 if( pOutFlags ){
5773 *pOutFlags = flags;
5774 }
5775
dane946c392009-08-22 11:39:46 +00005776 if( p->pUnused ){
5777 p->pUnused->fd = fd;
5778 p->pUnused->flags = flags;
5779 }
5780
danielk1977b4b47412007-08-17 15:53:36 +00005781 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005782#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005783 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00005784#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
5785 zPath = sqlite3_mprintf("%s", zName);
5786 if( zPath==0 ){
5787 robust_close(p, fd, __LINE__);
5788 return SQLITE_NOMEM;
5789 }
chw97185482008-11-17 08:05:31 +00005790#else
drh036ac7f2011-08-08 23:18:05 +00005791 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005792#endif
danielk1977b4b47412007-08-17 15:53:36 +00005793 }
drh41022642008-11-21 00:24:42 +00005794#if SQLITE_ENABLE_LOCKING_STYLE
5795 else{
dan08da86a2009-08-21 17:18:03 +00005796 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005797 }
5798#endif
5799
drhda0e7682008-07-30 15:27:54 +00005800 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005801
drh7ed97b92010-01-20 13:07:21 +00005802
5803#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005804 if( fstatfs(fd, &fsInfo) == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00005805 storeLastErrno(p, errno);
drh0e9365c2011-03-02 02:08:13 +00005806 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005807 return SQLITE_IOERR_ACCESS;
5808 }
5809 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5810 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5811 }
drh4bf66fd2015-02-19 02:43:02 +00005812 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
5813 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5814 }
drh7ed97b92010-01-20 13:07:21 +00005815#endif
drhc02a43a2012-01-10 23:18:38 +00005816
5817 /* Set up appropriate ctrlFlags */
5818 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5819 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5820 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5821 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5822 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5823
drh7ed97b92010-01-20 13:07:21 +00005824#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005825#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005826 isAutoProxy = 1;
5827#endif
5828 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005829 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5830 int useProxy = 0;
5831
dan08da86a2009-08-21 17:18:03 +00005832 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5833 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005834 if( envforce!=NULL ){
5835 useProxy = atoi(envforce)>0;
5836 }else{
aswiftaebf4132008-11-21 00:10:35 +00005837 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5838 }
5839 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005840 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005841 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005842 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005843 if( rc!=SQLITE_OK ){
5844 /* Use unixClose to clean up the resources added in fillInUnixFile
5845 ** and clear all the structure's references. Specifically,
5846 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5847 */
5848 unixClose(pFile);
5849 return rc;
5850 }
aswiftaebf4132008-11-21 00:10:35 +00005851 }
dane946c392009-08-22 11:39:46 +00005852 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005853 }
5854 }
5855#endif
5856
drhc02a43a2012-01-10 23:18:38 +00005857 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5858
dane946c392009-08-22 11:39:46 +00005859open_finished:
5860 if( rc!=SQLITE_OK ){
5861 sqlite3_free(p->pUnused);
5862 }
5863 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005864}
5865
dane946c392009-08-22 11:39:46 +00005866
danielk1977b4b47412007-08-17 15:53:36 +00005867/*
danielk1977fee2d252007-08-18 10:59:19 +00005868** Delete the file at zPath. If the dirSync argument is true, fsync()
5869** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005870*/
drh6b9d6dd2008-12-03 19:34:47 +00005871static int unixDelete(
5872 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5873 const char *zPath, /* Name of file to be deleted */
5874 int dirSync /* If true, fsync() directory after deleting file */
5875){
danielk1977fee2d252007-08-18 10:59:19 +00005876 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005877 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005878 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005879 if( osUnlink(zPath)==(-1) ){
drhbd945542014-08-13 11:39:42 +00005880 if( errno==ENOENT
5881#if OS_VXWORKS
drh19541f32014-09-01 13:37:55 +00005882 || osAccess(zPath,0)!=0
drhbd945542014-08-13 11:39:42 +00005883#endif
5884 ){
dan9fc5b4a2012-11-09 20:17:26 +00005885 rc = SQLITE_IOERR_DELETE_NOENT;
5886 }else{
drhb4308162012-11-09 21:40:02 +00005887 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005888 }
drhb4308162012-11-09 21:40:02 +00005889 return rc;
drh5d4feff2010-07-14 01:45:22 +00005890 }
danielk1977d39fa702008-10-16 13:27:40 +00005891#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005892 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005893 int fd;
drh90315a22011-08-10 01:52:12 +00005894 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005895 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005896#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005897 if( fsync(fd)==-1 )
5898#else
5899 if( fsync(fd) )
5900#endif
5901 {
dane18d4952011-02-21 11:46:24 +00005902 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005903 }
drh0e9365c2011-03-02 02:08:13 +00005904 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005905 }else if( rc==SQLITE_CANTOPEN ){
5906 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005907 }
5908 }
danielk1977d138dd82008-10-15 16:02:48 +00005909#endif
danielk1977fee2d252007-08-18 10:59:19 +00005910 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005911}
5912
danielk197790949c22007-08-17 16:50:38 +00005913/*
mistachkin48864df2013-03-21 21:20:32 +00005914** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00005915** test performed depends on the value of flags:
5916**
5917** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5918** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5919** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5920**
5921** Otherwise return 0.
5922*/
danielk1977861f7452008-06-05 11:39:11 +00005923static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005924 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5925 const char *zPath, /* Path of the file to examine */
5926 int flags, /* What do we want to learn about the zPath file? */
5927 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005928){
danielk1977397d65f2008-11-19 11:35:39 +00005929 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005930 SimulateIOError( return SQLITE_IOERR_ACCESS; );
drhd260b5b2015-11-25 18:03:33 +00005931 assert( pResOut!=0 );
danielk1977b4b47412007-08-17 15:53:36 +00005932
drhd260b5b2015-11-25 18:03:33 +00005933 /* The spec says there are three possible values for flags. But only
5934 ** two of them are actually used */
5935 assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
5936
5937 if( flags==SQLITE_ACCESS_EXISTS ){
dan83acd422010-06-18 11:10:06 +00005938 struct stat buf;
drhd260b5b2015-11-25 18:03:33 +00005939 *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
5940 }else{
5941 *pResOut = osAccess(zPath, W_OK|R_OK)==0;
dan83acd422010-06-18 11:10:06 +00005942 }
danielk1977861f7452008-06-05 11:39:11 +00005943 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005944}
5945
danielk1977b4b47412007-08-17 15:53:36 +00005946
5947/*
5948** Turn a relative pathname into a full pathname. The relative path
5949** is stored as a nul-terminated string in the buffer pointed to by
5950** zPath.
5951**
5952** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5953** (in this case, MAX_PATHNAME bytes). The full-path is written to
5954** this buffer before returning.
5955*/
danielk1977adfb9b02007-09-17 07:02:56 +00005956static int unixFullPathname(
5957 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5958 const char *zPath, /* Possibly relative input path */
5959 int nOut, /* Size of output buffer in bytes */
5960 char *zOut /* Output buffer */
5961){
dan245fdc62015-10-31 17:58:33 +00005962 int nByte;
danielk1977843e65f2007-09-01 16:16:15 +00005963
5964 /* It's odd to simulate an io-error here, but really this is just
5965 ** using the io-error infrastructure to test that SQLite handles this
5966 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005967 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005968 */
5969 SimulateIOError( return SQLITE_ERROR );
5970
drh153c62c2007-08-24 03:51:33 +00005971 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005972 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005973
dan245fdc62015-10-31 17:58:33 +00005974 /* Attempt to resolve the path as if it were a symbolic link. If it is
5975 ** a symbolic link, the resolved path is stored in buffer zOut[]. Or, if
5976 ** the identified file is not a symbolic link or does not exist, then
5977 ** zPath is copied directly into zOut. Either way, nByte is left set to
5978 ** the size of the string copied into zOut[] in bytes. */
5979 nByte = osReadlink(zPath, zOut, nOut-1);
5980 if( nByte<0 ){
5981 if( errno!=EINVAL && errno!=ENOENT ){
5982 return unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zPath);
5983 }
drhd260b5b2015-11-25 18:03:33 +00005984 sqlite3_snprintf(nOut, zOut, "%s", zPath);
dan245fdc62015-10-31 17:58:33 +00005985 nByte = sqlite3Strlen30(zOut);
danielk1977b4b47412007-08-17 15:53:36 +00005986 }else{
dan245fdc62015-10-31 17:58:33 +00005987 zOut[nByte] = '\0';
5988 }
5989
5990 /* If buffer zOut[] now contains an absolute path there is nothing more
5991 ** to do. If it contains a relative path, do the following:
5992 **
5993 ** * move the relative path string so that it is at the end of th
5994 ** zOut[] buffer.
5995 ** * Call getcwd() to read the path of the current working directory
5996 ** into the start of the zOut[] buffer.
5997 ** * Append a '/' character to the cwd string and move the
5998 ** relative path back within the buffer so that it immediately
5999 ** follows the '/'.
6000 **
6001 ** This code is written so that if the combination of the CWD and relative
6002 ** path are larger than the allocated size of zOut[] the CWD is silently
6003 ** truncated to make it fit. This is Ok, as SQLite refuses to open any
6004 ** file for which this function returns a full path larger than (nOut-8)
6005 ** bytes in size. */
6006 if( zOut[0]!='/' ){
danielk1977b4b47412007-08-17 15:53:36 +00006007 int nCwd;
dan245fdc62015-10-31 17:58:33 +00006008 int nRem = nOut-nByte-1;
6009 memmove(&zOut[nRem], zOut, nByte+1);
6010 zOut[nRem-1] = '\0';
6011 if( osGetcwd(zOut, nRem-1)==0 ){
dane18d4952011-02-21 11:46:24 +00006012 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006013 }
dan245fdc62015-10-31 17:58:33 +00006014 nCwd = sqlite3Strlen30(zOut);
6015 assert( nCwd<=nRem-1 );
6016 zOut[nCwd] = '/';
6017 memmove(&zOut[nCwd+1], &zOut[nRem], nByte+1);
danielk1977b4b47412007-08-17 15:53:36 +00006018 }
dan245fdc62015-10-31 17:58:33 +00006019
danielk1977b4b47412007-08-17 15:53:36 +00006020 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006021}
6022
drh0ccebe72005-06-07 22:22:50 +00006023
drh761df872006-12-21 01:29:22 +00006024#ifndef SQLITE_OMIT_LOAD_EXTENSION
6025/*
6026** Interfaces for opening a shared library, finding entry points
6027** within the shared library, and closing the shared library.
6028*/
6029#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00006030static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6031 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00006032 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6033}
danielk197795c8a542007-09-01 06:51:27 +00006034
6035/*
6036** SQLite calls this function immediately after a call to unixDlSym() or
6037** unixDlOpen() fails (returns a null pointer). If a more detailed error
6038** message is available, it is written to zBufOut. If no error message
6039** is available, zBufOut is left unmodified and SQLite uses a default
6040** error message.
6041*/
danielk1977397d65f2008-11-19 11:35:39 +00006042static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006043 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006044 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006045 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006046 zErr = dlerror();
6047 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006048 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006049 }
drh6c7d5c52008-11-21 20:32:33 +00006050 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006051}
drh1875f7a2008-12-08 18:19:17 +00006052static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6053 /*
6054 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6055 ** cast into a pointer to a function. And yet the library dlsym() routine
6056 ** returns a void* which is really a pointer to a function. So how do we
6057 ** use dlsym() with -pedantic-errors?
6058 **
6059 ** Variable x below is defined to be a pointer to a function taking
6060 ** parameters void* and const char* and returning a pointer to a function.
6061 ** We initialize x by assigning it a pointer to the dlsym() function.
6062 ** (That assignment requires a cast.) Then we call the function that
6063 ** x points to.
6064 **
6065 ** This work-around is unlikely to work correctly on any system where
6066 ** you really cannot cast a function pointer into void*. But then, on the
6067 ** other hand, dlsym() will not work on such a system either, so we have
6068 ** not really lost anything.
6069 */
6070 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006071 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006072 x = (void(*(*)(void*,const char*))(void))dlsym;
6073 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006074}
danielk1977397d65f2008-11-19 11:35:39 +00006075static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6076 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006077 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006078}
danielk1977b4b47412007-08-17 15:53:36 +00006079#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6080 #define unixDlOpen 0
6081 #define unixDlError 0
6082 #define unixDlSym 0
6083 #define unixDlClose 0
6084#endif
6085
6086/*
danielk197790949c22007-08-17 16:50:38 +00006087** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006088*/
danielk1977397d65f2008-11-19 11:35:39 +00006089static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6090 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006091 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006092
drhbbd42a62004-05-22 17:41:58 +00006093 /* We have to initialize zBuf to prevent valgrind from reporting
6094 ** errors. The reports issued by valgrind are incorrect - we would
6095 ** prefer that the randomness be increased by making use of the
6096 ** uninitialized space in zBuf - but valgrind errors tend to worry
6097 ** some users. Rather than argue, it seems easier just to initialize
6098 ** the whole array and silence valgrind, even if that means less randomness
6099 ** in the random seed.
6100 **
6101 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006102 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006103 ** tests repeatable.
6104 */
danielk1977b4b47412007-08-17 15:53:36 +00006105 memset(zBuf, 0, nBuf);
drh5ac93652015-03-21 20:59:43 +00006106 randomnessPid = osGetpid(0);
drh6a412b82015-04-30 12:31:49 +00006107#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
drhbbd42a62004-05-22 17:41:58 +00006108 {
drhb00d8622014-01-01 15:18:36 +00006109 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006110 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006111 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006112 time_t t;
6113 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006114 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006115 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6116 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6117 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006118 }else{
drhc18b4042012-02-10 03:10:27 +00006119 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006120 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006121 }
drhbbd42a62004-05-22 17:41:58 +00006122 }
6123#endif
drh72cbd072008-10-14 17:58:38 +00006124 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006125}
6126
danielk1977b4b47412007-08-17 15:53:36 +00006127
drhbbd42a62004-05-22 17:41:58 +00006128/*
6129** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006130** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006131** The return value is the number of microseconds of sleep actually
6132** requested from the underlying operating system, a number which
6133** might be greater than or equal to the argument, but not less
6134** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006135*/
danielk1977397d65f2008-11-19 11:35:39 +00006136static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006137#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006138 struct timespec sp;
6139
6140 sp.tv_sec = microseconds / 1000000;
6141 sp.tv_nsec = (microseconds % 1000000) * 1000;
6142 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006143 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006144 return microseconds;
6145#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006146 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006147 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006148 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006149#else
danielk1977b4b47412007-08-17 15:53:36 +00006150 int seconds = (microseconds+999999)/1000000;
6151 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006152 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006153 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006154#endif
drh88f474a2006-01-02 20:00:12 +00006155}
6156
6157/*
drh6b9d6dd2008-12-03 19:34:47 +00006158** The following variable, if set to a non-zero value, is interpreted as
6159** the number of seconds since 1970 and is used to set the result of
6160** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006161*/
6162#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006163int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006164#endif
6165
6166/*
drhb7e8ea22010-05-03 14:32:30 +00006167** Find the current time (in Universal Coordinated Time). Write into *piNow
6168** the current time and date as a Julian Day number times 86_400_000. In
6169** other words, write into *piNow the number of milliseconds since the Julian
6170** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6171** proleptic Gregorian calendar.
6172**
drh31702252011-10-12 23:13:43 +00006173** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6174** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006175*/
6176static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6177 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006178 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006179#if defined(NO_GETTOD)
6180 time_t t;
6181 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006182 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006183#elif OS_VXWORKS
6184 struct timespec sNow;
6185 clock_gettime(CLOCK_REALTIME, &sNow);
6186 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6187#else
6188 struct timeval sNow;
drh970942e2015-11-25 23:13:14 +00006189 (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
6190 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
drhb7e8ea22010-05-03 14:32:30 +00006191#endif
6192
6193#ifdef SQLITE_TEST
6194 if( sqlite3_current_time ){
6195 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6196 }
6197#endif
6198 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006199 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006200}
6201
drh5337dac2015-11-25 15:15:03 +00006202#if 0 /* Not used */
drhb7e8ea22010-05-03 14:32:30 +00006203/*
drhbbd42a62004-05-22 17:41:58 +00006204** Find the current time (in Universal Coordinated Time). Write the
6205** current time and date as a Julian Day number into *prNow and
6206** return 0. Return 1 if the time and date cannot be found.
6207*/
danielk1977397d65f2008-11-19 11:35:39 +00006208static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006209 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006210 int rc;
drhff828942010-06-26 21:34:06 +00006211 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006212 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006213 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006214 return rc;
drhbbd42a62004-05-22 17:41:58 +00006215}
drh5337dac2015-11-25 15:15:03 +00006216#else
6217# define unixCurrentTime 0
6218#endif
danielk1977b4b47412007-08-17 15:53:36 +00006219
drh5337dac2015-11-25 15:15:03 +00006220#if 0 /* Not used */
drh6b9d6dd2008-12-03 19:34:47 +00006221/*
6222** We added the xGetLastError() method with the intention of providing
6223** better low-level error messages when operating-system problems come up
6224** during SQLite operation. But so far, none of that has been implemented
6225** in the core. So this routine is never called. For now, it is merely
6226** a place-holder.
6227*/
danielk1977397d65f2008-11-19 11:35:39 +00006228static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6229 UNUSED_PARAMETER(NotUsed);
6230 UNUSED_PARAMETER(NotUsed2);
6231 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00006232 return 0;
6233}
drh5337dac2015-11-25 15:15:03 +00006234#else
6235# define unixGetLastError 0
6236#endif
danielk1977bcb97fe2008-06-06 15:49:29 +00006237
drhf2424c52010-04-26 00:04:55 +00006238
6239/*
drh734c9862008-11-28 15:37:20 +00006240************************ End of sqlite3_vfs methods ***************************
6241******************************************************************************/
6242
drh715ff302008-12-03 22:32:44 +00006243/******************************************************************************
6244************************** Begin Proxy Locking ********************************
6245**
6246** Proxy locking is a "uber-locking-method" in this sense: It uses the
6247** other locking methods on secondary lock files. Proxy locking is a
6248** meta-layer over top of the primitive locking implemented above. For
6249** this reason, the division that implements of proxy locking is deferred
6250** until late in the file (here) after all of the other I/O methods have
6251** been defined - so that the primitive locking methods are available
6252** as services to help with the implementation of proxy locking.
6253**
6254****
6255**
6256** The default locking schemes in SQLite use byte-range locks on the
6257** database file to coordinate safe, concurrent access by multiple readers
6258** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6259** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6260** as POSIX read & write locks over fixed set of locations (via fsctl),
6261** on AFP and SMB only exclusive byte-range locks are available via fsctl
6262** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6263** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6264** address in the shared range is taken for a SHARED lock, the entire
6265** shared range is taken for an EXCLUSIVE lock):
6266**
drhf2f105d2012-08-20 15:53:54 +00006267** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006268** RESERVED_BYTE 0x40000001
6269** SHARED_RANGE 0x40000002 -> 0x40000200
6270**
6271** This works well on the local file system, but shows a nearly 100x
6272** slowdown in read performance on AFP because the AFP client disables
6273** the read cache when byte-range locks are present. Enabling the read
6274** cache exposes a cache coherency problem that is present on all OS X
6275** supported network file systems. NFS and AFP both observe the
6276** close-to-open semantics for ensuring cache coherency
6277** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6278** address the requirements for concurrent database access by multiple
6279** readers and writers
6280** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6281**
6282** To address the performance and cache coherency issues, proxy file locking
6283** changes the way database access is controlled by limiting access to a
6284** single host at a time and moving file locks off of the database file
6285** and onto a proxy file on the local file system.
6286**
6287**
6288** Using proxy locks
6289** -----------------
6290**
6291** C APIs
6292**
drh4bf66fd2015-02-19 02:43:02 +00006293** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
drh715ff302008-12-03 22:32:44 +00006294** <proxy_path> | ":auto:");
drh4bf66fd2015-02-19 02:43:02 +00006295** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6296** &<proxy_path>);
drh715ff302008-12-03 22:32:44 +00006297**
6298**
6299** SQL pragmas
6300**
6301** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6302** PRAGMA [database.]lock_proxy_file
6303**
6304** Specifying ":auto:" means that if there is a conch file with a matching
6305** host ID in it, the proxy path in the conch file will be used, otherwise
6306** a proxy path based on the user's temp dir
6307** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6308** actual proxy file name is generated from the name and path of the
6309** database file. For example:
6310**
6311** For database path "/Users/me/foo.db"
6312** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6313**
6314** Once a lock proxy is configured for a database connection, it can not
6315** be removed, however it may be switched to a different proxy path via
6316** the above APIs (assuming the conch file is not being held by another
6317** connection or process).
6318**
6319**
6320** How proxy locking works
6321** -----------------------
6322**
6323** Proxy file locking relies primarily on two new supporting files:
6324**
6325** * conch file to limit access to the database file to a single host
6326** at a time
6327**
6328** * proxy file to act as a proxy for the advisory locks normally
6329** taken on the database
6330**
6331** The conch file - to use a proxy file, sqlite must first "hold the conch"
6332** by taking an sqlite-style shared lock on the conch file, reading the
6333** contents and comparing the host's unique host ID (see below) and lock
6334** proxy path against the values stored in the conch. The conch file is
6335** stored in the same directory as the database file and the file name
6336** is patterned after the database file name as ".<databasename>-conch".
peter.d.reid60ec9142014-09-06 16:39:46 +00006337** If the conch file does not exist, or its contents do not match the
drh715ff302008-12-03 22:32:44 +00006338** host ID and/or proxy path, then the lock is escalated to an exclusive
6339** lock and the conch file contents is updated with the host ID and proxy
6340** path and the lock is downgraded to a shared lock again. If the conch
6341** is held by another process (with a shared lock), the exclusive lock
6342** will fail and SQLITE_BUSY is returned.
6343**
6344** The proxy file - a single-byte file used for all advisory file locks
6345** normally taken on the database file. This allows for safe sharing
6346** of the database file for multiple readers and writers on the same
6347** host (the conch ensures that they all use the same local lock file).
6348**
drh715ff302008-12-03 22:32:44 +00006349** Requesting the lock proxy does not immediately take the conch, it is
6350** only taken when the first request to lock database file is made.
6351** This matches the semantics of the traditional locking behavior, where
6352** opening a connection to a database file does not take a lock on it.
6353** The shared lock and an open file descriptor are maintained until
6354** the connection to the database is closed.
6355**
6356** The proxy file and the lock file are never deleted so they only need
6357** to be created the first time they are used.
6358**
6359** Configuration options
6360** ---------------------
6361**
6362** SQLITE_PREFER_PROXY_LOCKING
6363**
6364** Database files accessed on non-local file systems are
6365** automatically configured for proxy locking, lock files are
6366** named automatically using the same logic as
6367** PRAGMA lock_proxy_file=":auto:"
6368**
6369** SQLITE_PROXY_DEBUG
6370**
6371** Enables the logging of error messages during host id file
6372** retrieval and creation
6373**
drh715ff302008-12-03 22:32:44 +00006374** LOCKPROXYDIR
6375**
6376** Overrides the default directory used for lock proxy files that
6377** are named automatically via the ":auto:" setting
6378**
6379** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6380**
6381** Permissions to use when creating a directory for storing the
6382** lock proxy files, only used when LOCKPROXYDIR is not set.
6383**
6384**
6385** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6386** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6387** force proxy locking to be used for every database file opened, and 0
6388** will force automatic proxy locking to be disabled for all database
drh4bf66fd2015-02-19 02:43:02 +00006389** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
drh715ff302008-12-03 22:32:44 +00006390** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6391*/
6392
6393/*
6394** Proxy locking is only available on MacOSX
6395*/
drhd2cb50b2009-01-09 21:41:17 +00006396#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006397
drh715ff302008-12-03 22:32:44 +00006398/*
6399** The proxyLockingContext has the path and file structures for the remote
6400** and local proxy files in it
6401*/
6402typedef struct proxyLockingContext proxyLockingContext;
6403struct proxyLockingContext {
6404 unixFile *conchFile; /* Open conch file */
6405 char *conchFilePath; /* Name of the conch file */
6406 unixFile *lockProxy; /* Open proxy lock file */
6407 char *lockProxyPath; /* Name of the proxy lock file */
6408 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006409 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh4bf66fd2015-02-19 02:43:02 +00006410 int nFails; /* Number of conch taking failures */
drh715ff302008-12-03 22:32:44 +00006411 void *oldLockingContext; /* Original lockingcontext to restore on close */
6412 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6413};
6414
drh7ed97b92010-01-20 13:07:21 +00006415/*
6416** The proxy lock file path for the database at dbPath is written into lPath,
6417** which must point to valid, writable memory large enough for a maxLen length
6418** file path.
drh715ff302008-12-03 22:32:44 +00006419*/
drh715ff302008-12-03 22:32:44 +00006420static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6421 int len;
6422 int dbLen;
6423 int i;
6424
6425#ifdef LOCKPROXYDIR
6426 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6427#else
6428# ifdef _CS_DARWIN_USER_TEMP_DIR
6429 {
drh7ed97b92010-01-20 13:07:21 +00006430 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006431 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006432 lPath, errno, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006433 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006434 }
drh7ed97b92010-01-20 13:07:21 +00006435 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006436 }
6437# else
6438 len = strlcpy(lPath, "/tmp/", maxLen);
6439# endif
6440#endif
6441
6442 if( lPath[len-1]!='/' ){
6443 len = strlcat(lPath, "/", maxLen);
6444 }
6445
6446 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006447 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006448 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006449 char c = dbPath[i];
6450 lPath[i+len] = (c=='/')?'_':c;
6451 }
6452 lPath[i+len]='\0';
6453 strlcat(lPath, ":auto:", maxLen);
drh5ac93652015-03-21 20:59:43 +00006454 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006455 return SQLITE_OK;
6456}
6457
drh7ed97b92010-01-20 13:07:21 +00006458/*
6459 ** Creates the lock file and any missing directories in lockPath
6460 */
6461static int proxyCreateLockPath(const char *lockPath){
6462 int i, len;
6463 char buf[MAXPATHLEN];
6464 int start = 0;
6465
6466 assert(lockPath!=NULL);
6467 /* try to create all the intermediate directories */
6468 len = (int)strlen(lockPath);
6469 buf[0] = lockPath[0];
6470 for( i=1; i<len; i++ ){
6471 if( lockPath[i] == '/' && (i - start > 0) ){
6472 /* only mkdir if leaf dir != "." or "/" or ".." */
6473 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6474 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6475 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006476 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006477 int err=errno;
6478 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006479 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006480 "'%s' proxy lock path=%s pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006481 buf, strerror(err), lockPath, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006482 return err;
6483 }
6484 }
6485 }
6486 start=i+1;
6487 }
6488 buf[i] = lockPath[i];
6489 }
drh62aaa6c2015-11-21 17:27:42 +00006490 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006491 return 0;
6492}
6493
drh715ff302008-12-03 22:32:44 +00006494/*
6495** Create a new VFS file descriptor (stored in memory obtained from
6496** sqlite3_malloc) and open the file named "path" in the file descriptor.
6497**
6498** The caller is responsible not only for closing the file descriptor
6499** but also for freeing the memory associated with the file descriptor.
6500*/
drh7ed97b92010-01-20 13:07:21 +00006501static int proxyCreateUnixFile(
6502 const char *path, /* path for the new unixFile */
6503 unixFile **ppFile, /* unixFile created and returned by ref */
6504 int islockfile /* if non zero missing dirs will be created */
6505) {
6506 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006507 unixFile *pNew;
6508 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006509 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006510 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006511 int terrno = 0;
6512 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006513
drh7ed97b92010-01-20 13:07:21 +00006514 /* 1. first try to open/create the file
6515 ** 2. if that fails, and this is a lock file (not-conch), try creating
6516 ** the parent directories and then try again.
6517 ** 3. if that fails, try to open the file read-only
6518 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6519 */
6520 pUnused = findReusableFd(path, openFlags);
6521 if( pUnused ){
6522 fd = pUnused->fd;
6523 }else{
drhf3cdcdc2015-04-29 16:50:28 +00006524 pUnused = sqlite3_malloc64(sizeof(*pUnused));
drh7ed97b92010-01-20 13:07:21 +00006525 if( !pUnused ){
6526 return SQLITE_NOMEM;
6527 }
6528 }
6529 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006530 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006531 terrno = errno;
6532 if( fd<0 && errno==ENOENT && islockfile ){
6533 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006534 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006535 }
6536 }
6537 }
6538 if( fd<0 ){
6539 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006540 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006541 terrno = errno;
6542 }
6543 if( fd<0 ){
6544 if( islockfile ){
6545 return SQLITE_BUSY;
6546 }
6547 switch (terrno) {
6548 case EACCES:
6549 return SQLITE_PERM;
6550 case EIO:
6551 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6552 default:
drh9978c972010-02-23 17:36:32 +00006553 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006554 }
6555 }
6556
drhf3cdcdc2015-04-29 16:50:28 +00006557 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
drh7ed97b92010-01-20 13:07:21 +00006558 if( pNew==NULL ){
6559 rc = SQLITE_NOMEM;
6560 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006561 }
6562 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006563 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006564 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006565 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006566 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006567 pUnused->fd = fd;
6568 pUnused->flags = openFlags;
6569 pNew->pUnused = pUnused;
6570
drhc02a43a2012-01-10 23:18:38 +00006571 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006572 if( rc==SQLITE_OK ){
6573 *ppFile = pNew;
6574 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006575 }
drh7ed97b92010-01-20 13:07:21 +00006576end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006577 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006578 sqlite3_free(pNew);
6579 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006580 return rc;
6581}
6582
drh7ed97b92010-01-20 13:07:21 +00006583#ifdef SQLITE_TEST
6584/* simulate multiple hosts by creating unique hostid file paths */
6585int sqlite3_hostid_num = 0;
6586#endif
6587
6588#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6589
drh6bca6512015-04-13 23:05:28 +00006590#ifdef HAVE_GETHOSTUUID
drh0ab216a2010-07-02 17:10:40 +00006591/* Not always defined in the headers as it ought to be */
6592extern int gethostuuid(uuid_t id, const struct timespec *wait);
drh6bca6512015-04-13 23:05:28 +00006593#endif
drh0ab216a2010-07-02 17:10:40 +00006594
drh7ed97b92010-01-20 13:07:21 +00006595/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6596** bytes of writable memory.
6597*/
6598static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006599 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6600 memset(pHostID, 0, PROXY_HOSTIDLEN);
drh6bca6512015-04-13 23:05:28 +00006601#ifdef HAVE_GETHOSTUUID
drh29ecd8a2010-12-21 00:16:40 +00006602 {
drh4bf66fd2015-02-19 02:43:02 +00006603 struct timespec timeout = {1, 0}; /* 1 sec timeout */
drh29ecd8a2010-12-21 00:16:40 +00006604 if( gethostuuid(pHostID, &timeout) ){
6605 int err = errno;
6606 if( pError ){
6607 *pError = err;
6608 }
6609 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006610 }
drh7ed97b92010-01-20 13:07:21 +00006611 }
drh3d4435b2011-08-26 20:55:50 +00006612#else
6613 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006614#endif
drh7ed97b92010-01-20 13:07:21 +00006615#ifdef SQLITE_TEST
6616 /* simulate multiple hosts by creating unique hostid file paths */
6617 if( sqlite3_hostid_num != 0){
6618 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6619 }
6620#endif
6621
6622 return SQLITE_OK;
6623}
6624
6625/* The conch file contains the header, host id and lock file path
6626 */
6627#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6628#define PROXY_HEADERLEN 1 /* conch file header length */
6629#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6630#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6631
6632/*
6633** Takes an open conch file, copies the contents to a new path and then moves
6634** it back. The newly created file's file descriptor is assigned to the
6635** conch file structure and finally the original conch file descriptor is
6636** closed. Returns zero if successful.
6637*/
6638static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6639 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6640 unixFile *conchFile = pCtx->conchFile;
6641 char tPath[MAXPATHLEN];
6642 char buf[PROXY_MAXCONCHLEN];
6643 char *cPath = pCtx->conchFilePath;
6644 size_t readLen = 0;
6645 size_t pathLen = 0;
6646 char errmsg[64] = "";
6647 int fd = -1;
6648 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006649 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006650
6651 /* create a new path by replace the trailing '-conch' with '-break' */
6652 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6653 if( pathLen>MAXPATHLEN || pathLen<6 ||
6654 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006655 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006656 goto end_breaklock;
6657 }
6658 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006659 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006660 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006661 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006662 goto end_breaklock;
6663 }
6664 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006665 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006666 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006667 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006668 goto end_breaklock;
6669 }
drhe562be52011-03-02 18:01:10 +00006670 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006671 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006672 goto end_breaklock;
6673 }
6674 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006675 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006676 goto end_breaklock;
6677 }
6678 rc = 0;
6679 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006680 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006681 conchFile->h = fd;
6682 conchFile->openFlags = O_RDWR | O_CREAT;
6683
6684end_breaklock:
6685 if( rc ){
6686 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006687 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006688 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006689 }
6690 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6691 }
6692 return rc;
6693}
6694
6695/* Take the requested lock on the conch file and break a stale lock if the
6696** host id matches.
6697*/
6698static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6699 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6700 unixFile *conchFile = pCtx->conchFile;
6701 int rc = SQLITE_OK;
6702 int nTries = 0;
6703 struct timespec conchModTime;
6704
drh3d4435b2011-08-26 20:55:50 +00006705 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006706 do {
6707 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6708 nTries ++;
6709 if( rc==SQLITE_BUSY ){
6710 /* If the lock failed (busy):
6711 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6712 * 2nd try: fail if the mod time changed or host id is different, wait
6713 * 10 sec and try again
6714 * 3rd try: break the lock unless the mod time has changed.
6715 */
6716 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006717 if( osFstat(conchFile->h, &buf) ){
drh4bf66fd2015-02-19 02:43:02 +00006718 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006719 return SQLITE_IOERR_LOCK;
6720 }
6721
6722 if( nTries==1 ){
6723 conchModTime = buf.st_mtimespec;
6724 usleep(500000); /* wait 0.5 sec and try the lock again*/
6725 continue;
6726 }
6727
6728 assert( nTries>1 );
6729 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6730 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6731 return SQLITE_BUSY;
6732 }
6733
6734 if( nTries==2 ){
6735 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006736 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006737 if( len<0 ){
drh4bf66fd2015-02-19 02:43:02 +00006738 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006739 return SQLITE_IOERR_LOCK;
6740 }
6741 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6742 /* don't break the lock if the host id doesn't match */
6743 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6744 return SQLITE_BUSY;
6745 }
6746 }else{
6747 /* don't break the lock on short read or a version mismatch */
6748 return SQLITE_BUSY;
6749 }
6750 usleep(10000000); /* wait 10 sec and try the lock again */
6751 continue;
6752 }
6753
6754 assert( nTries==3 );
6755 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6756 rc = SQLITE_OK;
6757 if( lockType==EXCLUSIVE_LOCK ){
drhe6d41732015-02-21 00:49:00 +00006758 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
drh7ed97b92010-01-20 13:07:21 +00006759 }
6760 if( !rc ){
6761 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6762 }
6763 }
6764 }
6765 } while( rc==SQLITE_BUSY && nTries<3 );
6766
6767 return rc;
6768}
6769
6770/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006771** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6772** lockPath means that the lockPath in the conch file will be used if the
6773** host IDs match, or a new lock path will be generated automatically
6774** and written to the conch file.
6775*/
6776static int proxyTakeConch(unixFile *pFile){
6777 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6778
drh7ed97b92010-01-20 13:07:21 +00006779 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006780 return SQLITE_OK;
6781 }else{
6782 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006783 uuid_t myHostID;
6784 int pError = 0;
6785 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006786 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006787 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006788 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006789 int createConch = 0;
6790 int hostIdMatch = 0;
6791 int readLen = 0;
6792 int tryOldLockPath = 0;
6793 int forceNewLockPath = 0;
6794
drh308c2a52010-05-14 11:30:18 +00006795 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
drh91eb93c2015-03-03 19:56:20 +00006796 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00006797 osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006798
drh7ed97b92010-01-20 13:07:21 +00006799 rc = proxyGetHostID(myHostID, &pError);
6800 if( (rc&0xff)==SQLITE_IOERR ){
drh4bf66fd2015-02-19 02:43:02 +00006801 storeLastErrno(pFile, pError);
drh7ed97b92010-01-20 13:07:21 +00006802 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006803 }
drh7ed97b92010-01-20 13:07:21 +00006804 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006805 if( rc!=SQLITE_OK ){
6806 goto end_takeconch;
6807 }
drh7ed97b92010-01-20 13:07:21 +00006808 /* read the existing conch file */
6809 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6810 if( readLen<0 ){
6811 /* I/O error: lastErrno set by seekAndRead */
drh4bf66fd2015-02-19 02:43:02 +00006812 storeLastErrno(pFile, conchFile->lastErrno);
drh7ed97b92010-01-20 13:07:21 +00006813 rc = SQLITE_IOERR_READ;
6814 goto end_takeconch;
6815 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6816 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6817 /* a short read or version format mismatch means we need to create a new
6818 ** conch file.
6819 */
6820 createConch = 1;
6821 }
6822 /* if the host id matches and the lock path already exists in the conch
6823 ** we'll try to use the path there, if we can't open that path, we'll
6824 ** retry with a new auto-generated path
6825 */
6826 do { /* in case we need to try again for an :auto: named lock file */
6827
6828 if( !createConch && !forceNewLockPath ){
6829 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6830 PROXY_HOSTIDLEN);
6831 /* if the conch has data compare the contents */
6832 if( !pCtx->lockProxyPath ){
6833 /* for auto-named local lock file, just check the host ID and we'll
6834 ** use the local lock file path that's already in there
6835 */
6836 if( hostIdMatch ){
6837 size_t pathLen = (readLen - PROXY_PATHINDEX);
6838
6839 if( pathLen>=MAXPATHLEN ){
6840 pathLen=MAXPATHLEN-1;
6841 }
6842 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6843 lockPath[pathLen] = 0;
6844 tempLockPath = lockPath;
6845 tryOldLockPath = 1;
6846 /* create a copy of the lock path if the conch is taken */
6847 goto end_takeconch;
6848 }
6849 }else if( hostIdMatch
6850 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6851 readLen-PROXY_PATHINDEX)
6852 ){
6853 /* conch host and lock path match */
6854 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006855 }
drh7ed97b92010-01-20 13:07:21 +00006856 }
6857
6858 /* if the conch isn't writable and doesn't match, we can't take it */
6859 if( (conchFile->openFlags&O_RDWR) == 0 ){
6860 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006861 goto end_takeconch;
6862 }
drh7ed97b92010-01-20 13:07:21 +00006863
6864 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006865 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006866 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6867 tempLockPath = lockPath;
6868 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006869 }
drh7ed97b92010-01-20 13:07:21 +00006870
6871 /* update conch with host and path (this will fail if other process
6872 ** has a shared lock already), if the host id matches, use the big
6873 ** stick.
drh715ff302008-12-03 22:32:44 +00006874 */
drh7ed97b92010-01-20 13:07:21 +00006875 futimes(conchFile->h, NULL);
6876 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006877 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006878 /* We are trying for an exclusive lock but another thread in this
6879 ** same process is still holding a shared lock. */
6880 rc = SQLITE_BUSY;
6881 } else {
6882 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006883 }
drh715ff302008-12-03 22:32:44 +00006884 }else{
drh4bf66fd2015-02-19 02:43:02 +00006885 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006886 }
drh7ed97b92010-01-20 13:07:21 +00006887 if( rc==SQLITE_OK ){
6888 char writeBuffer[PROXY_MAXCONCHLEN];
6889 int writeSize = 0;
6890
6891 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6892 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6893 if( pCtx->lockProxyPath!=NULL ){
drh4bf66fd2015-02-19 02:43:02 +00006894 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
6895 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00006896 }else{
6897 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6898 }
6899 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006900 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006901 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6902 fsync(conchFile->h);
6903 /* If we created a new conch file (not just updated the contents of a
6904 ** valid conch file), try to match the permissions of the database
6905 */
6906 if( rc==SQLITE_OK && createConch ){
6907 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006908 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006909 if( err==0 ){
6910 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6911 S_IROTH|S_IWOTH);
6912 /* try to match the database file R/W permissions, ignore failure */
6913#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006914 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006915#else
drhff812312011-02-23 13:33:46 +00006916 do{
drhe562be52011-03-02 18:01:10 +00006917 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006918 }while( rc==(-1) && errno==EINTR );
6919 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006920 int code = errno;
6921 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6922 cmode, code, strerror(code));
6923 } else {
6924 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6925 }
6926 }else{
6927 int code = errno;
6928 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6929 err, code, strerror(code));
6930#endif
6931 }
drh715ff302008-12-03 22:32:44 +00006932 }
6933 }
drh7ed97b92010-01-20 13:07:21 +00006934 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6935
6936 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006937 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006938 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006939 int fd;
drh7ed97b92010-01-20 13:07:21 +00006940 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006941 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006942 }
6943 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006944 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006945 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006946 if( fd>=0 ){
6947 pFile->h = fd;
6948 }else{
drh9978c972010-02-23 17:36:32 +00006949 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006950 during locking */
6951 }
6952 }
6953 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6954 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6955 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6956 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6957 /* we couldn't create the proxy lock file with the old lock file path
6958 ** so try again via auto-naming
6959 */
6960 forceNewLockPath = 1;
6961 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006962 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006963 }
6964 }
6965 if( rc==SQLITE_OK ){
6966 /* Need to make a copy of path if we extracted the value
6967 ** from the conch file or the path was allocated on the stack
6968 */
6969 if( tempLockPath ){
6970 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6971 if( !pCtx->lockProxyPath ){
6972 rc = SQLITE_NOMEM;
6973 }
6974 }
6975 }
6976 if( rc==SQLITE_OK ){
6977 pCtx->conchHeld = 1;
6978
6979 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6980 afpLockingContext *afpCtx;
6981 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6982 afpCtx->dbPath = pCtx->lockProxyPath;
6983 }
6984 } else {
6985 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6986 }
drh308c2a52010-05-14 11:30:18 +00006987 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6988 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006989 return rc;
drh308c2a52010-05-14 11:30:18 +00006990 } while (1); /* in case we need to retry the :auto: lock file -
6991 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006992 }
6993}
6994
6995/*
6996** If pFile holds a lock on a conch file, then release that lock.
6997*/
6998static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006999 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00007000 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
7001 unixFile *conchFile; /* Name of the conch file */
7002
7003 pCtx = (proxyLockingContext *)pFile->lockingContext;
7004 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00007005 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00007006 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00007007 osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00007008 if( pCtx->conchHeld>0 ){
7009 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7010 }
drh715ff302008-12-03 22:32:44 +00007011 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00007012 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
7013 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007014 return rc;
7015}
7016
7017/*
7018** Given the name of a database file, compute the name of its conch file.
drhf3cdcdc2015-04-29 16:50:28 +00007019** Store the conch filename in memory obtained from sqlite3_malloc64().
drh715ff302008-12-03 22:32:44 +00007020** Make *pConchPath point to the new name. Return SQLITE_OK on success
7021** or SQLITE_NOMEM if unable to obtain memory.
7022**
7023** The caller is responsible for ensuring that the allocated memory
7024** space is eventually freed.
7025**
7026** *pConchPath is set to NULL if a memory allocation error occurs.
7027*/
7028static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7029 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00007030 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00007031 char *conchPath; /* buffer in which to construct conch name */
7032
7033 /* Allocate space for the conch filename and initialize the name to
7034 ** the name of the original database file. */
drhf3cdcdc2015-04-29 16:50:28 +00007035 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
drh715ff302008-12-03 22:32:44 +00007036 if( conchPath==0 ){
7037 return SQLITE_NOMEM;
7038 }
7039 memcpy(conchPath, dbPath, len+1);
7040
7041 /* now insert a "." before the last / character */
7042 for( i=(len-1); i>=0; i-- ){
7043 if( conchPath[i]=='/' ){
7044 i++;
7045 break;
7046 }
7047 }
7048 conchPath[i]='.';
7049 while ( i<len ){
7050 conchPath[i+1]=dbPath[i];
7051 i++;
7052 }
7053
7054 /* append the "-conch" suffix to the file */
7055 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007056 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007057
7058 return SQLITE_OK;
7059}
7060
7061
7062/* Takes a fully configured proxy locking-style unix file and switches
7063** the local lock file path
7064*/
7065static int switchLockProxyPath(unixFile *pFile, const char *path) {
7066 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7067 char *oldPath = pCtx->lockProxyPath;
7068 int rc = SQLITE_OK;
7069
drh308c2a52010-05-14 11:30:18 +00007070 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007071 return SQLITE_BUSY;
7072 }
7073
7074 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7075 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7076 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7077 return SQLITE_OK;
7078 }else{
7079 unixFile *lockProxy = pCtx->lockProxy;
7080 pCtx->lockProxy=NULL;
7081 pCtx->conchHeld = 0;
7082 if( lockProxy!=NULL ){
7083 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7084 if( rc ) return rc;
7085 sqlite3_free(lockProxy);
7086 }
7087 sqlite3_free(oldPath);
7088 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7089 }
7090
7091 return rc;
7092}
7093
7094/*
7095** pFile is a file that has been opened by a prior xOpen call. dbPath
7096** is a string buffer at least MAXPATHLEN+1 characters in size.
7097**
7098** This routine find the filename associated with pFile and writes it
7099** int dbPath.
7100*/
7101static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007102#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007103 if( pFile->pMethod == &afpIoMethods ){
7104 /* afp style keeps a reference to the db path in the filePath field
7105 ** of the struct */
drhea678832008-12-10 19:26:22 +00007106 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh4bf66fd2015-02-19 02:43:02 +00007107 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7108 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007109 } else
drh715ff302008-12-03 22:32:44 +00007110#endif
7111 if( pFile->pMethod == &dotlockIoMethods ){
7112 /* dot lock style uses the locking context to store the dot lock
7113 ** file path */
7114 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7115 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7116 }else{
7117 /* all other styles use the locking context to store the db file path */
7118 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007119 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007120 }
7121 return SQLITE_OK;
7122}
7123
7124/*
7125** Takes an already filled in unix file and alters it so all file locking
7126** will be performed on the local proxy lock file. The following fields
7127** are preserved in the locking context so that they can be restored and
7128** the unix structure properly cleaned up at close time:
7129** ->lockingContext
7130** ->pMethod
7131*/
7132static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7133 proxyLockingContext *pCtx;
7134 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7135 char *lockPath=NULL;
7136 int rc = SQLITE_OK;
7137
drh308c2a52010-05-14 11:30:18 +00007138 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007139 return SQLITE_BUSY;
7140 }
7141 proxyGetDbPathForUnixFile(pFile, dbPath);
7142 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7143 lockPath=NULL;
7144 }else{
7145 lockPath=(char *)path;
7146 }
7147
drh308c2a52010-05-14 11:30:18 +00007148 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
drh5ac93652015-03-21 20:59:43 +00007149 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007150
drhf3cdcdc2015-04-29 16:50:28 +00007151 pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh715ff302008-12-03 22:32:44 +00007152 if( pCtx==0 ){
7153 return SQLITE_NOMEM;
7154 }
7155 memset(pCtx, 0, sizeof(*pCtx));
7156
7157 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7158 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007159 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7160 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7161 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7162 ** (c) the file system is read-only, then enable no-locking access.
7163 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7164 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7165 */
7166 struct statfs fsInfo;
7167 struct stat conchInfo;
7168 int goLockless = 0;
7169
drh99ab3b12011-03-02 15:09:07 +00007170 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007171 int err = errno;
7172 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7173 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7174 }
7175 }
7176 if( goLockless ){
7177 pCtx->conchHeld = -1; /* read only FS/ lockless */
7178 rc = SQLITE_OK;
7179 }
7180 }
drh715ff302008-12-03 22:32:44 +00007181 }
7182 if( rc==SQLITE_OK && lockPath ){
7183 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7184 }
7185
7186 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007187 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7188 if( pCtx->dbPath==NULL ){
7189 rc = SQLITE_NOMEM;
7190 }
7191 }
7192 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007193 /* all memory is allocated, proxys are created and assigned,
7194 ** switch the locking context and pMethod then return.
7195 */
drh715ff302008-12-03 22:32:44 +00007196 pCtx->oldLockingContext = pFile->lockingContext;
7197 pFile->lockingContext = pCtx;
7198 pCtx->pOldMethod = pFile->pMethod;
7199 pFile->pMethod = &proxyIoMethods;
7200 }else{
7201 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007202 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007203 sqlite3_free(pCtx->conchFile);
7204 }
drhd56b1212010-08-11 06:14:15 +00007205 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007206 sqlite3_free(pCtx->conchFilePath);
7207 sqlite3_free(pCtx);
7208 }
drh308c2a52010-05-14 11:30:18 +00007209 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7210 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007211 return rc;
7212}
7213
7214
7215/*
7216** This routine handles sqlite3_file_control() calls that are specific
7217** to proxy locking.
7218*/
7219static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7220 switch( op ){
drh4bf66fd2015-02-19 02:43:02 +00007221 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007222 unixFile *pFile = (unixFile*)id;
7223 if( pFile->pMethod == &proxyIoMethods ){
7224 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7225 proxyTakeConch(pFile);
7226 if( pCtx->lockProxyPath ){
7227 *(const char **)pArg = pCtx->lockProxyPath;
7228 }else{
7229 *(const char **)pArg = ":auto: (not held)";
7230 }
7231 } else {
7232 *(const char **)pArg = NULL;
7233 }
7234 return SQLITE_OK;
7235 }
drh4bf66fd2015-02-19 02:43:02 +00007236 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007237 unixFile *pFile = (unixFile*)id;
7238 int rc = SQLITE_OK;
7239 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7240 if( pArg==NULL || (const char *)pArg==0 ){
7241 if( isProxyStyle ){
drh4bf66fd2015-02-19 02:43:02 +00007242 /* turn off proxy locking - not supported. If support is added for
7243 ** switching proxy locking mode off then it will need to fail if
7244 ** the journal mode is WAL mode.
7245 */
drh715ff302008-12-03 22:32:44 +00007246 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7247 }else{
7248 /* turn off proxy locking - already off - NOOP */
7249 rc = SQLITE_OK;
7250 }
7251 }else{
7252 const char *proxyPath = (const char *)pArg;
7253 if( isProxyStyle ){
7254 proxyLockingContext *pCtx =
7255 (proxyLockingContext*)pFile->lockingContext;
7256 if( !strcmp(pArg, ":auto:")
7257 || (pCtx->lockProxyPath &&
7258 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7259 ){
7260 rc = SQLITE_OK;
7261 }else{
7262 rc = switchLockProxyPath(pFile, proxyPath);
7263 }
7264 }else{
7265 /* turn on proxy file locking */
7266 rc = proxyTransformUnixFile(pFile, proxyPath);
7267 }
7268 }
7269 return rc;
7270 }
7271 default: {
7272 assert( 0 ); /* The call assures that only valid opcodes are sent */
7273 }
7274 }
7275 /*NOTREACHED*/
7276 return SQLITE_ERROR;
7277}
7278
7279/*
7280** Within this division (the proxying locking implementation) the procedures
7281** above this point are all utilities. The lock-related methods of the
7282** proxy-locking sqlite3_io_method object follow.
7283*/
7284
7285
7286/*
7287** This routine checks if there is a RESERVED lock held on the specified
7288** file by this or any other process. If such a lock is held, set *pResOut
7289** to a non-zero value otherwise *pResOut is set to zero. The return value
7290** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7291*/
7292static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7293 unixFile *pFile = (unixFile*)id;
7294 int rc = proxyTakeConch(pFile);
7295 if( rc==SQLITE_OK ){
7296 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007297 if( pCtx->conchHeld>0 ){
7298 unixFile *proxy = pCtx->lockProxy;
7299 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7300 }else{ /* conchHeld < 0 is lockless */
7301 pResOut=0;
7302 }
drh715ff302008-12-03 22:32:44 +00007303 }
7304 return rc;
7305}
7306
7307/*
drh308c2a52010-05-14 11:30:18 +00007308** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007309** of the following:
7310**
7311** (1) SHARED_LOCK
7312** (2) RESERVED_LOCK
7313** (3) PENDING_LOCK
7314** (4) EXCLUSIVE_LOCK
7315**
7316** Sometimes when requesting one lock state, additional lock states
7317** are inserted in between. The locking might fail on one of the later
7318** transitions leaving the lock state different from what it started but
7319** still short of its goal. The following chart shows the allowed
7320** transitions and the inserted intermediate states:
7321**
7322** UNLOCKED -> SHARED
7323** SHARED -> RESERVED
7324** SHARED -> (PENDING) -> EXCLUSIVE
7325** RESERVED -> (PENDING) -> EXCLUSIVE
7326** PENDING -> EXCLUSIVE
7327**
7328** This routine will only increase a lock. Use the sqlite3OsUnlock()
7329** routine to lower a locking level.
7330*/
drh308c2a52010-05-14 11:30:18 +00007331static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007332 unixFile *pFile = (unixFile*)id;
7333 int rc = proxyTakeConch(pFile);
7334 if( rc==SQLITE_OK ){
7335 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007336 if( pCtx->conchHeld>0 ){
7337 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007338 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7339 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007340 }else{
7341 /* conchHeld < 0 is lockless */
7342 }
drh715ff302008-12-03 22:32:44 +00007343 }
7344 return rc;
7345}
7346
7347
7348/*
drh308c2a52010-05-14 11:30:18 +00007349** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007350** must be either NO_LOCK or SHARED_LOCK.
7351**
7352** If the locking level of the file descriptor is already at or below
7353** the requested locking level, this routine is a no-op.
7354*/
drh308c2a52010-05-14 11:30:18 +00007355static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007356 unixFile *pFile = (unixFile*)id;
7357 int rc = proxyTakeConch(pFile);
7358 if( rc==SQLITE_OK ){
7359 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007360 if( pCtx->conchHeld>0 ){
7361 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007362 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7363 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007364 }else{
7365 /* conchHeld < 0 is lockless */
7366 }
drh715ff302008-12-03 22:32:44 +00007367 }
7368 return rc;
7369}
7370
7371/*
7372** Close a file that uses proxy locks.
7373*/
7374static int proxyClose(sqlite3_file *id) {
7375 if( id ){
7376 unixFile *pFile = (unixFile*)id;
7377 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7378 unixFile *lockProxy = pCtx->lockProxy;
7379 unixFile *conchFile = pCtx->conchFile;
7380 int rc = SQLITE_OK;
7381
7382 if( lockProxy ){
7383 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7384 if( rc ) return rc;
7385 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7386 if( rc ) return rc;
7387 sqlite3_free(lockProxy);
7388 pCtx->lockProxy = 0;
7389 }
7390 if( conchFile ){
7391 if( pCtx->conchHeld ){
7392 rc = proxyReleaseConch(pFile);
7393 if( rc ) return rc;
7394 }
7395 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7396 if( rc ) return rc;
7397 sqlite3_free(conchFile);
7398 }
drhd56b1212010-08-11 06:14:15 +00007399 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007400 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007401 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007402 /* restore the original locking context and pMethod then close it */
7403 pFile->lockingContext = pCtx->oldLockingContext;
7404 pFile->pMethod = pCtx->pOldMethod;
7405 sqlite3_free(pCtx);
7406 return pFile->pMethod->xClose(id);
7407 }
7408 return SQLITE_OK;
7409}
7410
7411
7412
drhd2cb50b2009-01-09 21:41:17 +00007413#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007414/*
7415** The proxy locking style is intended for use with AFP filesystems.
7416** And since AFP is only supported on MacOSX, the proxy locking is also
7417** restricted to MacOSX.
7418**
7419**
7420******************* End of the proxy lock implementation **********************
7421******************************************************************************/
7422
drh734c9862008-11-28 15:37:20 +00007423/*
danielk1977e339d652008-06-28 11:23:00 +00007424** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007425**
7426** This routine registers all VFS implementations for unix-like operating
7427** systems. This routine, and the sqlite3_os_end() routine that follows,
7428** should be the only routines in this file that are visible from other
7429** files.
drh6b9d6dd2008-12-03 19:34:47 +00007430**
7431** This routine is called once during SQLite initialization and by a
7432** single thread. The memory allocation and mutex subsystems have not
7433** necessarily been initialized when this routine is called, and so they
7434** should not be used.
drh153c62c2007-08-24 03:51:33 +00007435*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007436int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007437 /*
7438 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007439 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7440 ** to the "finder" function. (pAppData is a pointer to a pointer because
7441 ** silly C90 rules prohibit a void* from being cast to a function pointer
7442 ** and so we have to go through the intermediate pointer to avoid problems
7443 ** when compiling with -pedantic-errors on GCC.)
7444 **
7445 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007446 ** finder-function. The finder-function returns a pointer to the
7447 ** sqlite_io_methods object that implements the desired locking
7448 ** behaviors. See the division above that contains the IOMETHODS
7449 ** macro for addition information on finder-functions.
7450 **
7451 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7452 ** object. But the "autolockIoFinder" available on MacOSX does a little
7453 ** more than that; it looks at the filesystem type that hosts the
7454 ** database file and tries to choose an locking method appropriate for
7455 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007456 */
drh7708e972008-11-29 00:56:52 +00007457 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007458 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007459 sizeof(unixFile), /* szOsFile */ \
7460 MAX_PATHNAME, /* mxPathname */ \
7461 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007462 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007463 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007464 unixOpen, /* xOpen */ \
7465 unixDelete, /* xDelete */ \
7466 unixAccess, /* xAccess */ \
7467 unixFullPathname, /* xFullPathname */ \
7468 unixDlOpen, /* xDlOpen */ \
7469 unixDlError, /* xDlError */ \
7470 unixDlSym, /* xDlSym */ \
7471 unixDlClose, /* xDlClose */ \
7472 unixRandomness, /* xRandomness */ \
7473 unixSleep, /* xSleep */ \
7474 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007475 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007476 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007477 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007478 unixGetSystemCall, /* xGetSystemCall */ \
7479 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007480 }
7481
drh6b9d6dd2008-12-03 19:34:47 +00007482 /*
7483 ** All default VFSes for unix are contained in the following array.
7484 **
7485 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7486 ** by the SQLite core when the VFS is registered. So the following
7487 ** array cannot be const.
7488 */
danielk1977e339d652008-06-28 11:23:00 +00007489 static sqlite3_vfs aVfs[] = {
drhe89b2912015-03-03 20:42:01 +00007490#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007491 UNIXVFS("unix", autolockIoFinder ),
drhe89b2912015-03-03 20:42:01 +00007492#elif OS_VXWORKS
7493 UNIXVFS("unix", vxworksIoFinder ),
drh7708e972008-11-29 00:56:52 +00007494#else
7495 UNIXVFS("unix", posixIoFinder ),
7496#endif
7497 UNIXVFS("unix-none", nolockIoFinder ),
7498 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007499 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007500#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007501 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007502#endif
drhe89b2912015-03-03 20:42:01 +00007503#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007504 UNIXVFS("unix-posix", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007505#endif
drhe89b2912015-03-03 20:42:01 +00007506#if SQLITE_ENABLE_LOCKING_STYLE
7507 UNIXVFS("unix-flock", flockIoFinder ),
chw78a13182009-04-07 05:35:03 +00007508#endif
drhd2cb50b2009-01-09 21:41:17 +00007509#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007510 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007511 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007512 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007513#endif
drh153c62c2007-08-24 03:51:33 +00007514 };
drh6b9d6dd2008-12-03 19:34:47 +00007515 unsigned int i; /* Loop counter */
7516
drh2aa5a002011-04-13 13:42:25 +00007517 /* Double-check that the aSyscall[] array has been constructed
7518 ** correctly. See ticket [bb3a86e890c8e96ab] */
drh6226ca22015-11-24 15:06:28 +00007519 assert( ArraySize(aSyscall)==27 );
drh2aa5a002011-04-13 13:42:25 +00007520
drh6b9d6dd2008-12-03 19:34:47 +00007521 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007522 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007523 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007524 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007525 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007526}
danielk1977e339d652008-06-28 11:23:00 +00007527
7528/*
drh6b9d6dd2008-12-03 19:34:47 +00007529** Shutdown the operating system interface.
7530**
7531** Some operating systems might need to do some cleanup in this routine,
7532** to release dynamically allocated objects. But not on unix.
7533** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007534*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007535int sqlite3_os_end(void){
7536 return SQLITE_OK;
7537}
drhdce8bdb2007-08-16 13:01:44 +00007538
danielk197729bafea2008-06-26 10:41:19 +00007539#endif /* SQLITE_OS_UNIX */