blob: eb20041ed551f4b490035ad64e40deeb780fbd1a [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 );
drha8de1e12015-11-30 00:05:39 +00001353 assert( pFile->eFileLock<=SHARED_LOCK );
drh8af6c222010-05-14 12:43:01 +00001354 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001355
1356 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001357 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001358 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001359 }
1360
drh2ac3ee92004-06-07 16:27:46 +00001361 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001362 */
danielk197709480a92009-02-09 05:32:32 +00001363#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001364 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001365 struct flock lock;
1366 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001367 lock.l_start = RESERVED_BYTE;
1368 lock.l_len = 1;
1369 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001370 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1371 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001372 storeLastErrno(pFile, errno);
aswift5b1a2562008-08-22 00:22:35 +00001373 } else if( lock.l_type!=F_UNLCK ){
1374 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001375 }
1376 }
danielk197709480a92009-02-09 05:32:32 +00001377#endif
danielk197713adf8a2004-06-03 16:08:41 +00001378
drh6c7d5c52008-11-21 20:32:33 +00001379 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001380 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001381
aswift5b1a2562008-08-22 00:22:35 +00001382 *pResOut = reserved;
1383 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001384}
1385
1386/*
drha7e61d82011-03-12 17:02:57 +00001387** Attempt to set a system-lock on the file pFile. The lock is
1388** described by pLock.
1389**
drh77197112011-03-15 19:08:48 +00001390** If the pFile was opened read/write from unix-excl, then the only lock
1391** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001392** the first time any lock is attempted. All subsequent system locking
1393** operations become no-ops. Locking operations still happen internally,
1394** in order to coordinate access between separate database connections
1395** within this process, but all of that is handled in memory and the
1396** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001397**
1398** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1399** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1400** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001401**
1402** Zero is returned if the call completes successfully, or -1 if a call
1403** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001404*/
1405static int unixFileLock(unixFile *pFile, struct flock *pLock){
1406 int rc;
drh3cb93392011-03-12 18:10:44 +00001407 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001408 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001409 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001410 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1411 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1412 ){
drh3cb93392011-03-12 18:10:44 +00001413 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001414 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001415 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001416 lock.l_whence = SEEK_SET;
1417 lock.l_start = SHARED_FIRST;
1418 lock.l_len = SHARED_SIZE;
1419 lock.l_type = F_WRLCK;
1420 rc = osFcntl(pFile->h, F_SETLK, &lock);
1421 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001422 pInode->bProcessLock = 1;
1423 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001424 }else{
1425 rc = 0;
1426 }
1427 }else{
1428 rc = osFcntl(pFile->h, F_SETLK, pLock);
1429 }
1430 return rc;
1431}
1432
1433/*
drh308c2a52010-05-14 11:30:18 +00001434** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001435** of the following:
1436**
drh2ac3ee92004-06-07 16:27:46 +00001437** (1) SHARED_LOCK
1438** (2) RESERVED_LOCK
1439** (3) PENDING_LOCK
1440** (4) EXCLUSIVE_LOCK
1441**
drhb3e04342004-06-08 00:47:47 +00001442** Sometimes when requesting one lock state, additional lock states
1443** are inserted in between. The locking might fail on one of the later
1444** transitions leaving the lock state different from what it started but
1445** still short of its goal. The following chart shows the allowed
1446** transitions and the inserted intermediate states:
1447**
1448** UNLOCKED -> SHARED
1449** SHARED -> RESERVED
1450** SHARED -> (PENDING) -> EXCLUSIVE
1451** RESERVED -> (PENDING) -> EXCLUSIVE
1452** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001453**
drha6abd042004-06-09 17:37:22 +00001454** This routine will only increase a lock. Use the sqlite3OsUnlock()
1455** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001456*/
drh308c2a52010-05-14 11:30:18 +00001457static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001458 /* The following describes the implementation of the various locks and
1459 ** lock transitions in terms of the POSIX advisory shared and exclusive
1460 ** lock primitives (called read-locks and write-locks below, to avoid
1461 ** confusion with SQLite lock names). The algorithms are complicated
1462 ** slightly in order to be compatible with windows systems simultaneously
1463 ** accessing the same database file, in case that is ever required.
1464 **
1465 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1466 ** byte', each single bytes at well known offsets, and the 'shared byte
1467 ** range', a range of 510 bytes at a well known offset.
1468 **
1469 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1470 ** byte'. If this is successful, a random byte from the 'shared byte
1471 ** range' is read-locked and the lock on the 'pending byte' released.
1472 **
danielk197790ba3bd2004-06-25 08:32:25 +00001473 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1474 ** A RESERVED lock is implemented by grabbing a write-lock on the
1475 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001476 **
1477 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001478 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1479 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1480 ** obtained, but existing SHARED locks are allowed to persist. A process
1481 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1482 ** This property is used by the algorithm for rolling back a journal file
1483 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001484 **
danielk197790ba3bd2004-06-25 08:32:25 +00001485 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1486 ** implemented by obtaining a write-lock on the entire 'shared byte
1487 ** range'. Since all other locks require a read-lock on one of the bytes
1488 ** within this range, this ensures that no other locks are held on the
1489 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001490 **
1491 ** The reason a single byte cannot be used instead of the 'shared byte
1492 ** range' is that some versions of windows do not support read-locks. By
1493 ** locking a random byte from a range, concurrent SHARED locks may exist
1494 ** even if the locking primitive used is always a write-lock.
1495 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001496 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001497 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001498 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001499 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001500 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001501
drh054889e2005-11-30 03:20:31 +00001502 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001503 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1504 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh91eb93c2015-03-03 19:56:20 +00001505 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001506 osGetpid(0)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001507
1508 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001509 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001510 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001511 */
drh308c2a52010-05-14 11:30:18 +00001512 if( pFile->eFileLock>=eFileLock ){
1513 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1514 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001515 return SQLITE_OK;
1516 }
1517
drh0c2694b2009-09-03 16:23:44 +00001518 /* Make sure the locking sequence is correct.
1519 ** (1) We never move from unlocked to anything higher than shared lock.
1520 ** (2) SQLite never explicitly requests a pendig lock.
1521 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001522 */
drh308c2a52010-05-14 11:30:18 +00001523 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1524 assert( eFileLock!=PENDING_LOCK );
1525 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001526
drh8af6c222010-05-14 12:43:01 +00001527 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001528 */
drh6c7d5c52008-11-21 20:32:33 +00001529 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001530 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001531
danielk1977ad94b582007-08-20 06:44:22 +00001532 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001533 ** handle that precludes the requested lock, return BUSY.
1534 */
drh8af6c222010-05-14 12:43:01 +00001535 if( (pFile->eFileLock!=pInode->eFileLock &&
1536 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001537 ){
1538 rc = SQLITE_BUSY;
1539 goto end_lock;
1540 }
1541
1542 /* If a SHARED lock is requested, and some thread using this PID already
1543 ** has a SHARED or RESERVED lock, then increment reference counts and
1544 ** return SQLITE_OK.
1545 */
drh308c2a52010-05-14 11:30:18 +00001546 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001547 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001548 assert( eFileLock==SHARED_LOCK );
1549 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001550 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001551 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001552 pInode->nShared++;
1553 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001554 goto end_lock;
1555 }
1556
danielk19779a1d0ab2004-06-01 14:09:28 +00001557
drh3cde3bb2004-06-12 02:17:14 +00001558 /* A PENDING lock is needed before acquiring a SHARED lock and before
1559 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1560 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001561 */
drh0c2694b2009-09-03 16:23:44 +00001562 lock.l_len = 1L;
1563 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001564 if( eFileLock==SHARED_LOCK
1565 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001566 ){
drh308c2a52010-05-14 11:30:18 +00001567 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001568 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001569 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001570 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001571 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001572 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001573 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001574 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001575 goto end_lock;
1576 }
drh3cde3bb2004-06-12 02:17:14 +00001577 }
1578
1579
1580 /* If control gets to this point, then actually go ahead and make
1581 ** operating system calls for the specified lock.
1582 */
drh308c2a52010-05-14 11:30:18 +00001583 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001584 assert( pInode->nShared==0 );
1585 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001586 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001587
drh2ac3ee92004-06-07 16:27:46 +00001588 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001589 lock.l_start = SHARED_FIRST;
1590 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001591 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001592 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001593 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001594 }
dan661d71a2011-03-30 19:08:03 +00001595
drh2ac3ee92004-06-07 16:27:46 +00001596 /* Drop the temporary PENDING lock */
1597 lock.l_start = PENDING_BYTE;
1598 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001599 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001600 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1601 /* This could happen with a network mount */
1602 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001603 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001604 }
dan661d71a2011-03-30 19:08:03 +00001605
1606 if( rc ){
1607 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001608 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001609 }
dan661d71a2011-03-30 19:08:03 +00001610 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001611 }else{
drh308c2a52010-05-14 11:30:18 +00001612 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001613 pInode->nLock++;
1614 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001615 }
drh8af6c222010-05-14 12:43:01 +00001616 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001617 /* We are trying for an exclusive lock but another thread in this
1618 ** same process is still holding a shared lock. */
1619 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001620 }else{
drh3cde3bb2004-06-12 02:17:14 +00001621 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001622 ** assumed that there is a SHARED or greater lock on the file
1623 ** already.
1624 */
drh308c2a52010-05-14 11:30:18 +00001625 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001626 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001627
1628 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1629 if( eFileLock==RESERVED_LOCK ){
1630 lock.l_start = RESERVED_BYTE;
1631 lock.l_len = 1L;
1632 }else{
1633 lock.l_start = SHARED_FIRST;
1634 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001635 }
dan661d71a2011-03-30 19:08:03 +00001636
1637 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001638 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001639 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001640 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001641 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001642 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001643 }
drhbbd42a62004-05-22 17:41:58 +00001644 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001645
drh8f941bc2009-01-14 23:03:40 +00001646
drhd3d8c042012-05-29 17:02:40 +00001647#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001648 /* Set up the transaction-counter change checking flags when
1649 ** transitioning from a SHARED to a RESERVED lock. The change
1650 ** from SHARED to RESERVED marks the beginning of a normal
1651 ** write operation (not a hot journal rollback).
1652 */
1653 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001654 && pFile->eFileLock<=SHARED_LOCK
1655 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001656 ){
1657 pFile->transCntrChng = 0;
1658 pFile->dbUpdate = 0;
1659 pFile->inNormalWrite = 1;
1660 }
1661#endif
1662
1663
danielk1977ecb2a962004-06-02 06:30:16 +00001664 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001665 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001666 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001667 }else if( eFileLock==EXCLUSIVE_LOCK ){
1668 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001669 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001670 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001671
1672end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001673 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001674 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1675 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001676 return rc;
1677}
1678
1679/*
dan08da86a2009-08-21 17:18:03 +00001680** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001681** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001682*/
1683static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001684 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001685 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001686 p->pNext = pInode->pUnused;
1687 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001688 pFile->h = -1;
1689 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001690}
1691
1692/*
drh308c2a52010-05-14 11:30:18 +00001693** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001694** must be either NO_LOCK or SHARED_LOCK.
1695**
1696** If the locking level of the file descriptor is already at or below
1697** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001698**
1699** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1700** the byte range is divided into 2 parts and the first part is unlocked then
1701** set to a read lock, then the other part is simply unlocked. This works
1702** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1703** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001704*/
drha7e61d82011-03-12 17:02:57 +00001705static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001706 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001707 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001708 struct flock lock;
1709 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001710
drh054889e2005-11-30 03:20:31 +00001711 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001712 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001713 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001714 osGetpid(0)));
drha6abd042004-06-09 17:37:22 +00001715
drh308c2a52010-05-14 11:30:18 +00001716 assert( eFileLock<=SHARED_LOCK );
1717 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001718 return SQLITE_OK;
1719 }
drh6c7d5c52008-11-21 20:32:33 +00001720 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001721 pInode = pFile->pInode;
1722 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001723 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001724 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001725
drhd3d8c042012-05-29 17:02:40 +00001726#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001727 /* When reducing a lock such that other processes can start
1728 ** reading the database file again, make sure that the
1729 ** transaction counter was updated if any part of the database
1730 ** file changed. If the transaction counter is not updated,
1731 ** other connections to the same file might not realize that
1732 ** the file has changed and hence might not know to flush their
1733 ** cache. The use of a stale cache can lead to database corruption.
1734 */
drh8f941bc2009-01-14 23:03:40 +00001735 pFile->inNormalWrite = 0;
1736#endif
1737
drh7ed97b92010-01-20 13:07:21 +00001738 /* downgrading to a shared lock on NFS involves clearing the write lock
1739 ** before establishing the readlock - to avoid a race condition we downgrade
1740 ** the lock in 2 blocks, so that part of the range will be covered by a
1741 ** write lock until the rest is covered by a read lock:
1742 ** 1: [WWWWW]
1743 ** 2: [....W]
1744 ** 3: [RRRRW]
1745 ** 4: [RRRR.]
1746 */
drh308c2a52010-05-14 11:30:18 +00001747 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001748#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001749 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001750 assert( handleNFSUnlock==0 );
1751#endif
1752#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001753 if( handleNFSUnlock ){
drha712b4b2015-02-19 16:12:04 +00001754 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001755 off_t divSize = SHARED_SIZE - 1;
1756
1757 lock.l_type = F_UNLCK;
1758 lock.l_whence = SEEK_SET;
1759 lock.l_start = SHARED_FIRST;
1760 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001761 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001762 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001763 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001764 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001765 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001766 }
drh7ed97b92010-01-20 13:07:21 +00001767 lock.l_type = F_RDLCK;
1768 lock.l_whence = SEEK_SET;
1769 lock.l_start = SHARED_FIRST;
1770 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001771 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001772 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001773 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1774 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001775 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001776 }
1777 goto end_unlock;
1778 }
1779 lock.l_type = F_UNLCK;
1780 lock.l_whence = SEEK_SET;
1781 lock.l_start = SHARED_FIRST+divSize;
1782 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001783 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001784 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001785 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001786 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001787 goto end_unlock;
1788 }
drh30f776f2011-02-25 03:25:07 +00001789 }else
1790#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1791 {
drh7ed97b92010-01-20 13:07:21 +00001792 lock.l_type = F_RDLCK;
1793 lock.l_whence = SEEK_SET;
1794 lock.l_start = SHARED_FIRST;
1795 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001796 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001797 /* In theory, the call to unixFileLock() cannot fail because another
1798 ** process is holding an incompatible lock. If it does, this
1799 ** indicates that the other process is not following the locking
1800 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1801 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1802 ** an assert to fail). */
1803 rc = SQLITE_IOERR_RDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001804 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00001805 goto end_unlock;
1806 }
drh9c105bb2004-10-02 20:38:28 +00001807 }
1808 }
drhbbd42a62004-05-22 17:41:58 +00001809 lock.l_type = F_UNLCK;
1810 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001811 lock.l_start = PENDING_BYTE;
1812 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001813 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001814 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001815 }else{
danea83bc62011-04-01 11:56:32 +00001816 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001817 storeLastErrno(pFile, errno);
drhcd731cf2009-03-28 23:23:02 +00001818 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001819 }
drhbbd42a62004-05-22 17:41:58 +00001820 }
drh308c2a52010-05-14 11:30:18 +00001821 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001822 /* Decrement the shared lock counter. Release the lock using an
1823 ** OS call only when all threads in this same process have released
1824 ** the lock.
1825 */
drh8af6c222010-05-14 12:43:01 +00001826 pInode->nShared--;
1827 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001828 lock.l_type = F_UNLCK;
1829 lock.l_whence = SEEK_SET;
1830 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001831 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001832 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001833 }else{
danea83bc62011-04-01 11:56:32 +00001834 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001835 storeLastErrno(pFile, errno);
drh8af6c222010-05-14 12:43:01 +00001836 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001837 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001838 }
drha6abd042004-06-09 17:37:22 +00001839 }
1840
drhbbd42a62004-05-22 17:41:58 +00001841 /* Decrement the count of locks against this same file. When the
1842 ** count reaches zero, close any other file descriptors whose close
1843 ** was deferred because of outstanding locks.
1844 */
drh8af6c222010-05-14 12:43:01 +00001845 pInode->nLock--;
1846 assert( pInode->nLock>=0 );
1847 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001848 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001849 }
1850 }
drhf2f105d2012-08-20 15:53:54 +00001851
aswift5b1a2562008-08-22 00:22:35 +00001852end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001853 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001854 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001855 return rc;
drhbbd42a62004-05-22 17:41:58 +00001856}
1857
1858/*
drh308c2a52010-05-14 11:30:18 +00001859** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001860** must be either NO_LOCK or SHARED_LOCK.
1861**
1862** If the locking level of the file descriptor is already at or below
1863** the requested locking level, this routine is a no-op.
1864*/
drh308c2a52010-05-14 11:30:18 +00001865static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00001866#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00001867 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00001868#endif
drha7e61d82011-03-12 17:02:57 +00001869 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001870}
1871
mistachkine98844f2013-08-24 00:59:24 +00001872#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001873static int unixMapfile(unixFile *pFd, i64 nByte);
1874static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00001875#endif
danf23da962013-03-23 21:00:41 +00001876
drh7ed97b92010-01-20 13:07:21 +00001877/*
danielk1977e339d652008-06-28 11:23:00 +00001878** This function performs the parts of the "close file" operation
1879** common to all locking schemes. It closes the directory and file
1880** handles, if they are valid, and sets all fields of the unixFile
1881** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001882**
1883** It is *not* necessary to hold the mutex when this routine is called,
1884** even on VxWorks. A mutex will be acquired on VxWorks by the
1885** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001886*/
1887static int closeUnixFile(sqlite3_file *id){
1888 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00001889#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001890 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00001891#endif
dan661d71a2011-03-30 19:08:03 +00001892 if( pFile->h>=0 ){
1893 robust_close(pFile, pFile->h, __LINE__);
1894 pFile->h = -1;
1895 }
1896#if OS_VXWORKS
1897 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001898 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001899 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001900 }
1901 vxworksReleaseFileId(pFile->pId);
1902 pFile->pId = 0;
1903 }
1904#endif
drh0bdbc902014-06-16 18:35:06 +00001905#ifdef SQLITE_UNLINK_AFTER_CLOSE
1906 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
1907 osUnlink(pFile->zPath);
1908 sqlite3_free(*(char**)&pFile->zPath);
1909 pFile->zPath = 0;
1910 }
1911#endif
dan661d71a2011-03-30 19:08:03 +00001912 OSTRACE(("CLOSE %-3d\n", pFile->h));
1913 OpenCounter(-1);
1914 sqlite3_free(pFile->pUnused);
1915 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001916 return SQLITE_OK;
1917}
1918
1919/*
danielk1977e3026632004-06-22 11:29:02 +00001920** Close a file.
1921*/
danielk197762079062007-08-15 17:08:46 +00001922static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001923 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001924 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00001925 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00001926 unixUnlock(id, NO_LOCK);
1927 unixEnterMutex();
1928
1929 /* unixFile.pInode is always valid here. Otherwise, a different close
1930 ** routine (e.g. nolockClose()) would be called instead.
1931 */
1932 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1933 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1934 /* If there are outstanding locks, do not actually close the file just
1935 ** yet because that would clear those locks. Instead, add the file
1936 ** descriptor to pInode->pUnused list. It will be automatically closed
1937 ** when the last lock is cleared.
1938 */
1939 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001940 }
dan661d71a2011-03-30 19:08:03 +00001941 releaseInodeInfo(pFile);
1942 rc = closeUnixFile(id);
1943 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001944 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001945}
1946
drh734c9862008-11-28 15:37:20 +00001947/************** End of the posix advisory lock implementation *****************
1948******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001949
drh734c9862008-11-28 15:37:20 +00001950/******************************************************************************
1951****************************** No-op Locking **********************************
1952**
1953** Of the various locking implementations available, this is by far the
1954** simplest: locking is ignored. No attempt is made to lock the database
1955** file for reading or writing.
1956**
1957** This locking mode is appropriate for use on read-only databases
1958** (ex: databases that are burned into CD-ROM, for example.) It can
1959** also be used if the application employs some external mechanism to
1960** prevent simultaneous access of the same database by two or more
1961** database connections. But there is a serious risk of database
1962** corruption if this locking mode is used in situations where multiple
1963** database connections are accessing the same database file at the same
1964** time and one or more of those connections are writing.
1965*/
drhbfe66312006-10-03 17:40:40 +00001966
drh734c9862008-11-28 15:37:20 +00001967static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1968 UNUSED_PARAMETER(NotUsed);
1969 *pResOut = 0;
1970 return SQLITE_OK;
1971}
drh734c9862008-11-28 15:37:20 +00001972static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1973 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1974 return SQLITE_OK;
1975}
drh734c9862008-11-28 15:37:20 +00001976static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1977 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1978 return SQLITE_OK;
1979}
1980
1981/*
drh9b35ea62008-11-29 02:20:26 +00001982** Close the file.
drh734c9862008-11-28 15:37:20 +00001983*/
1984static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001985 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001986}
1987
1988/******************* End of the no-op lock implementation *********************
1989******************************************************************************/
1990
1991/******************************************************************************
1992************************* Begin dot-file Locking ******************************
1993**
mistachkin48864df2013-03-21 21:20:32 +00001994** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00001995** files (really a directory) to control access to the database. This works
1996** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00001997**
1998** (1) There is zero concurrency. A single reader blocks all other
1999** connections from reading or writing the database.
2000**
2001** (2) An application crash or power loss can leave stale lock files
2002** sitting around that need to be cleared manually.
2003**
2004** Nevertheless, a dotlock is an appropriate locking mode for use if no
2005** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002006**
drh9ef6bc42011-11-04 02:24:02 +00002007** Dotfile locking works by creating a subdirectory in the same directory as
2008** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002009** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002010** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002011*/
2012
2013/*
2014** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002015** lock directory.
drh734c9862008-11-28 15:37:20 +00002016*/
2017#define DOTLOCK_SUFFIX ".lock"
2018
drh7708e972008-11-29 00:56:52 +00002019/*
2020** This routine checks if there is a RESERVED lock held on the specified
2021** file by this or any other process. If such a lock is held, set *pResOut
2022** to a non-zero value otherwise *pResOut is set to zero. The return value
2023** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2024**
2025** In dotfile locking, either a lock exists or it does not. So in this
2026** variation of CheckReservedLock(), *pResOut is set to true if any lock
2027** is held on the file and false if the file is unlocked.
2028*/
drh734c9862008-11-28 15:37:20 +00002029static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2030 int rc = SQLITE_OK;
2031 int reserved = 0;
2032 unixFile *pFile = (unixFile*)id;
2033
2034 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2035
2036 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00002037 reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
drh308c2a52010-05-14 11:30:18 +00002038 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002039 *pResOut = reserved;
2040 return rc;
2041}
2042
drh7708e972008-11-29 00:56:52 +00002043/*
drh308c2a52010-05-14 11:30:18 +00002044** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002045** of the following:
2046**
2047** (1) SHARED_LOCK
2048** (2) RESERVED_LOCK
2049** (3) PENDING_LOCK
2050** (4) EXCLUSIVE_LOCK
2051**
2052** Sometimes when requesting one lock state, additional lock states
2053** are inserted in between. The locking might fail on one of the later
2054** transitions leaving the lock state different from what it started but
2055** still short of its goal. The following chart shows the allowed
2056** transitions and the inserted intermediate states:
2057**
2058** UNLOCKED -> SHARED
2059** SHARED -> RESERVED
2060** SHARED -> (PENDING) -> EXCLUSIVE
2061** RESERVED -> (PENDING) -> EXCLUSIVE
2062** PENDING -> EXCLUSIVE
2063**
2064** This routine will only increase a lock. Use the sqlite3OsUnlock()
2065** routine to lower a locking level.
2066**
2067** With dotfile locking, we really only support state (4): EXCLUSIVE.
2068** But we track the other locking levels internally.
2069*/
drh308c2a52010-05-14 11:30:18 +00002070static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002071 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002072 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002073 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002074
drh7708e972008-11-29 00:56:52 +00002075
2076 /* If we have any lock, then the lock file already exists. All we have
2077 ** to do is adjust our internal record of the lock level.
2078 */
drh308c2a52010-05-14 11:30:18 +00002079 if( pFile->eFileLock > NO_LOCK ){
2080 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002081 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002082#ifdef HAVE_UTIME
2083 utime(zLockFile, NULL);
2084#else
drh734c9862008-11-28 15:37:20 +00002085 utimes(zLockFile, NULL);
2086#endif
drh7708e972008-11-29 00:56:52 +00002087 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002088 }
2089
2090 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002091 rc = osMkdir(zLockFile, 0777);
2092 if( rc<0 ){
2093 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002094 int tErrno = errno;
2095 if( EEXIST == tErrno ){
2096 rc = SQLITE_BUSY;
2097 } else {
2098 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drha8de1e12015-11-30 00:05:39 +00002099 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00002100 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002101 }
2102 }
drh7708e972008-11-29 00:56:52 +00002103 return rc;
drh734c9862008-11-28 15:37:20 +00002104 }
drh734c9862008-11-28 15:37:20 +00002105
2106 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002107 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002108 return rc;
2109}
2110
drh7708e972008-11-29 00:56:52 +00002111/*
drh308c2a52010-05-14 11:30:18 +00002112** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002113** must be either NO_LOCK or SHARED_LOCK.
2114**
2115** If the locking level of the file descriptor is already at or below
2116** the requested locking level, this routine is a no-op.
2117**
2118** When the locking level reaches NO_LOCK, delete the lock file.
2119*/
drh308c2a52010-05-14 11:30:18 +00002120static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002121 unixFile *pFile = (unixFile*)id;
2122 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002123 int rc;
drh734c9862008-11-28 15:37:20 +00002124
2125 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002126 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002127 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002128 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002129
2130 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002131 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002132 return SQLITE_OK;
2133 }
drh7708e972008-11-29 00:56:52 +00002134
2135 /* To downgrade to shared, simply update our internal notion of the
2136 ** lock state. No need to mess with the file on disk.
2137 */
drh308c2a52010-05-14 11:30:18 +00002138 if( eFileLock==SHARED_LOCK ){
2139 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002140 return SQLITE_OK;
2141 }
2142
drh7708e972008-11-29 00:56:52 +00002143 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002144 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002145 rc = osRmdir(zLockFile);
drh9ef6bc42011-11-04 02:24:02 +00002146 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002147 int tErrno = errno;
drha8de1e12015-11-30 00:05:39 +00002148 if( tErrno==ENOENT ){
2149 rc = SQLITE_OK;
2150 }else{
danea83bc62011-04-01 11:56:32 +00002151 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002152 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002153 }
2154 return rc;
2155 }
drh308c2a52010-05-14 11:30:18 +00002156 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002157 return SQLITE_OK;
2158}
2159
2160/*
drh9b35ea62008-11-29 02:20:26 +00002161** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002162*/
2163static int dotlockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002164 unixFile *pFile = (unixFile*)id;
2165 assert( id!=0 );
2166 dotlockUnlock(id, NO_LOCK);
2167 sqlite3_free(pFile->lockingContext);
2168 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002169}
2170/****************** End of the dot-file lock implementation *******************
2171******************************************************************************/
2172
2173/******************************************************************************
2174************************** Begin flock Locking ********************************
2175**
2176** Use the flock() system call to do file locking.
2177**
drh6b9d6dd2008-12-03 19:34:47 +00002178** flock() locking is like dot-file locking in that the various
2179** fine-grain locking levels supported by SQLite are collapsed into
2180** a single exclusive lock. In other words, SHARED, RESERVED, and
2181** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2182** still works when you do this, but concurrency is reduced since
2183** only a single process can be reading the database at a time.
2184**
drhe89b2912015-03-03 20:42:01 +00002185** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
drh734c9862008-11-28 15:37:20 +00002186*/
drhe89b2912015-03-03 20:42:01 +00002187#if SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002188
drh6b9d6dd2008-12-03 19:34:47 +00002189/*
drhff812312011-02-23 13:33:46 +00002190** Retry flock() calls that fail with EINTR
2191*/
2192#ifdef EINTR
2193static int robust_flock(int fd, int op){
2194 int rc;
2195 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2196 return rc;
2197}
2198#else
drh5c819272011-02-23 14:00:12 +00002199# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002200#endif
2201
2202
2203/*
drh6b9d6dd2008-12-03 19:34:47 +00002204** This routine checks if there is a RESERVED lock held on the specified
2205** file by this or any other process. If such a lock is held, set *pResOut
2206** to a non-zero value otherwise *pResOut is set to zero. The return value
2207** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2208*/
drh734c9862008-11-28 15:37:20 +00002209static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2210 int rc = SQLITE_OK;
2211 int reserved = 0;
2212 unixFile *pFile = (unixFile*)id;
2213
2214 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2215
2216 assert( pFile );
2217
2218 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002219 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002220 reserved = 1;
2221 }
2222
2223 /* Otherwise see if some other process holds it. */
2224 if( !reserved ){
2225 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002226 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002227 if( !lrc ){
2228 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002229 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002230 if ( lrc ) {
2231 int tErrno = errno;
2232 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002233 lrc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00002234 storeLastErrno(pFile, tErrno);
2235 rc = lrc;
drh734c9862008-11-28 15:37:20 +00002236 }
2237 } else {
2238 int tErrno = errno;
2239 reserved = 1;
2240 /* someone else might have it reserved */
2241 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2242 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002243 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002244 rc = lrc;
2245 }
2246 }
2247 }
drh308c2a52010-05-14 11:30:18 +00002248 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002249
2250#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2251 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2252 rc = SQLITE_OK;
2253 reserved=1;
2254 }
2255#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2256 *pResOut = reserved;
2257 return rc;
2258}
2259
drh6b9d6dd2008-12-03 19:34:47 +00002260/*
drh308c2a52010-05-14 11:30:18 +00002261** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002262** of the following:
2263**
2264** (1) SHARED_LOCK
2265** (2) RESERVED_LOCK
2266** (3) PENDING_LOCK
2267** (4) EXCLUSIVE_LOCK
2268**
2269** Sometimes when requesting one lock state, additional lock states
2270** are inserted in between. The locking might fail on one of the later
2271** transitions leaving the lock state different from what it started but
2272** still short of its goal. The following chart shows the allowed
2273** transitions and the inserted intermediate states:
2274**
2275** UNLOCKED -> SHARED
2276** SHARED -> RESERVED
2277** SHARED -> (PENDING) -> EXCLUSIVE
2278** RESERVED -> (PENDING) -> EXCLUSIVE
2279** PENDING -> EXCLUSIVE
2280**
2281** flock() only really support EXCLUSIVE locks. We track intermediate
2282** lock states in the sqlite3_file structure, but all locks SHARED or
2283** above are really EXCLUSIVE locks and exclude all other processes from
2284** access the file.
2285**
2286** This routine will only increase a lock. Use the sqlite3OsUnlock()
2287** routine to lower a locking level.
2288*/
drh308c2a52010-05-14 11:30:18 +00002289static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002290 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002291 unixFile *pFile = (unixFile*)id;
2292
2293 assert( pFile );
2294
2295 /* if we already have a lock, it is exclusive.
2296 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002297 if (pFile->eFileLock > NO_LOCK) {
2298 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002299 return SQLITE_OK;
2300 }
2301
2302 /* grab an exclusive lock */
2303
drhff812312011-02-23 13:33:46 +00002304 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002305 int tErrno = errno;
2306 /* didn't get, must be busy */
2307 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2308 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002309 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002310 }
2311 } else {
2312 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002313 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002314 }
drh308c2a52010-05-14 11:30:18 +00002315 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2316 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002317#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2318 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2319 rc = SQLITE_BUSY;
2320 }
2321#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2322 return rc;
2323}
2324
drh6b9d6dd2008-12-03 19:34:47 +00002325
2326/*
drh308c2a52010-05-14 11:30:18 +00002327** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002328** must be either NO_LOCK or SHARED_LOCK.
2329**
2330** If the locking level of the file descriptor is already at or below
2331** the requested locking level, this routine is a no-op.
2332*/
drh308c2a52010-05-14 11:30:18 +00002333static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002334 unixFile *pFile = (unixFile*)id;
2335
2336 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002337 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002338 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002339 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002340
2341 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002342 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002343 return SQLITE_OK;
2344 }
2345
2346 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002347 if (eFileLock==SHARED_LOCK) {
2348 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002349 return SQLITE_OK;
2350 }
2351
2352 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002353 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002354#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002355 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002356#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002357 return SQLITE_IOERR_UNLOCK;
2358 }else{
drh308c2a52010-05-14 11:30:18 +00002359 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002360 return SQLITE_OK;
2361 }
2362}
2363
2364/*
2365** Close a file.
2366*/
2367static int flockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002368 assert( id!=0 );
2369 flockUnlock(id, NO_LOCK);
2370 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002371}
2372
2373#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2374
2375/******************* End of the flock lock implementation *********************
2376******************************************************************************/
2377
2378/******************************************************************************
2379************************ Begin Named Semaphore Locking ************************
2380**
2381** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002382**
2383** Semaphore locking is like dot-lock and flock in that it really only
2384** supports EXCLUSIVE locking. Only a single process can read or write
2385** the database file at a time. This reduces potential concurrency, but
2386** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002387*/
2388#if OS_VXWORKS
2389
drh6b9d6dd2008-12-03 19:34:47 +00002390/*
2391** This routine checks if there is a RESERVED lock held on the specified
2392** file by this or any other process. If such a lock is held, set *pResOut
2393** to a non-zero value otherwise *pResOut is set to zero. The return value
2394** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2395*/
drh8cd5b252015-03-02 22:06:43 +00002396static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
drh734c9862008-11-28 15:37:20 +00002397 int rc = SQLITE_OK;
2398 int reserved = 0;
2399 unixFile *pFile = (unixFile*)id;
2400
2401 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2402
2403 assert( pFile );
2404
2405 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002406 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002407 reserved = 1;
2408 }
2409
2410 /* Otherwise see if some other process holds it. */
2411 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002412 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002413
2414 if( sem_trywait(pSem)==-1 ){
2415 int tErrno = errno;
2416 if( EAGAIN != tErrno ){
2417 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
drh4bf66fd2015-02-19 02:43:02 +00002418 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002419 } else {
2420 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002421 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002422 }
2423 }else{
2424 /* we could have it if we want it */
2425 sem_post(pSem);
2426 }
2427 }
drh308c2a52010-05-14 11:30:18 +00002428 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002429
2430 *pResOut = reserved;
2431 return rc;
2432}
2433
drh6b9d6dd2008-12-03 19:34:47 +00002434/*
drh308c2a52010-05-14 11:30:18 +00002435** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002436** of the following:
2437**
2438** (1) SHARED_LOCK
2439** (2) RESERVED_LOCK
2440** (3) PENDING_LOCK
2441** (4) EXCLUSIVE_LOCK
2442**
2443** Sometimes when requesting one lock state, additional lock states
2444** are inserted in between. The locking might fail on one of the later
2445** transitions leaving the lock state different from what it started but
2446** still short of its goal. The following chart shows the allowed
2447** transitions and the inserted intermediate states:
2448**
2449** UNLOCKED -> SHARED
2450** SHARED -> RESERVED
2451** SHARED -> (PENDING) -> EXCLUSIVE
2452** RESERVED -> (PENDING) -> EXCLUSIVE
2453** PENDING -> EXCLUSIVE
2454**
2455** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2456** lock states in the sqlite3_file structure, but all locks SHARED or
2457** above are really EXCLUSIVE locks and exclude all other processes from
2458** access the file.
2459**
2460** This routine will only increase a lock. Use the sqlite3OsUnlock()
2461** routine to lower a locking level.
2462*/
drh8cd5b252015-03-02 22:06:43 +00002463static int semXLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002464 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002465 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002466 int rc = SQLITE_OK;
2467
2468 /* if we already have a lock, it is exclusive.
2469 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002470 if (pFile->eFileLock > NO_LOCK) {
2471 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002472 rc = SQLITE_OK;
2473 goto sem_end_lock;
2474 }
2475
2476 /* lock semaphore now but bail out when already locked. */
2477 if( sem_trywait(pSem)==-1 ){
2478 rc = SQLITE_BUSY;
2479 goto sem_end_lock;
2480 }
2481
2482 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002483 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002484
2485 sem_end_lock:
2486 return rc;
2487}
2488
drh6b9d6dd2008-12-03 19:34:47 +00002489/*
drh308c2a52010-05-14 11:30:18 +00002490** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002491** must be either NO_LOCK or SHARED_LOCK.
2492**
2493** If the locking level of the file descriptor is already at or below
2494** the requested locking level, this routine is a no-op.
2495*/
drh8cd5b252015-03-02 22:06:43 +00002496static int semXUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002497 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002498 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002499
2500 assert( pFile );
2501 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002502 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002503 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002504 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002505
2506 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002507 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002508 return SQLITE_OK;
2509 }
2510
2511 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002512 if (eFileLock==SHARED_LOCK) {
2513 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002514 return SQLITE_OK;
2515 }
2516
2517 /* no, really unlock. */
2518 if ( sem_post(pSem)==-1 ) {
2519 int rc, tErrno = errno;
2520 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2521 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002522 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002523 }
2524 return rc;
2525 }
drh308c2a52010-05-14 11:30:18 +00002526 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002527 return SQLITE_OK;
2528}
2529
2530/*
2531 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002532 */
drh8cd5b252015-03-02 22:06:43 +00002533static int semXClose(sqlite3_file *id) {
drh734c9862008-11-28 15:37:20 +00002534 if( id ){
2535 unixFile *pFile = (unixFile*)id;
drh8cd5b252015-03-02 22:06:43 +00002536 semXUnlock(id, NO_LOCK);
drh734c9862008-11-28 15:37:20 +00002537 assert( pFile );
2538 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002539 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002540 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002541 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002542 }
2543 return SQLITE_OK;
2544}
2545
2546#endif /* OS_VXWORKS */
2547/*
2548** Named semaphore locking is only available on VxWorks.
2549**
2550*************** End of the named semaphore lock implementation ****************
2551******************************************************************************/
2552
2553
2554/******************************************************************************
2555*************************** Begin AFP Locking *********************************
2556**
2557** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2558** on Apple Macintosh computers - both OS9 and OSX.
2559**
2560** Third-party implementations of AFP are available. But this code here
2561** only works on OSX.
2562*/
2563
drhd2cb50b2009-01-09 21:41:17 +00002564#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002565/*
2566** The afpLockingContext structure contains all afp lock specific state
2567*/
drhbfe66312006-10-03 17:40:40 +00002568typedef struct afpLockingContext afpLockingContext;
2569struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002570 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002571 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002572};
2573
2574struct ByteRangeLockPB2
2575{
2576 unsigned long long offset; /* offset to first byte to lock */
2577 unsigned long long length; /* nbr of bytes to lock */
2578 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2579 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2580 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2581 int fd; /* file desc to assoc this lock with */
2582};
2583
drhfd131da2007-08-07 17:13:03 +00002584#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002585
drh6b9d6dd2008-12-03 19:34:47 +00002586/*
2587** This is a utility for setting or clearing a bit-range lock on an
2588** AFP filesystem.
2589**
2590** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2591*/
2592static int afpSetLock(
2593 const char *path, /* Name of the file to be locked or unlocked */
2594 unixFile *pFile, /* Open file descriptor on path */
2595 unsigned long long offset, /* First byte to be locked */
2596 unsigned long long length, /* Number of bytes to lock */
2597 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002598){
drh6b9d6dd2008-12-03 19:34:47 +00002599 struct ByteRangeLockPB2 pb;
2600 int err;
drhbfe66312006-10-03 17:40:40 +00002601
2602 pb.unLockFlag = setLockFlag ? 0 : 1;
2603 pb.startEndFlag = 0;
2604 pb.offset = offset;
2605 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002606 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002607
drh308c2a52010-05-14 11:30:18 +00002608 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002609 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002610 offset, length));
drhbfe66312006-10-03 17:40:40 +00002611 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2612 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002613 int rc;
2614 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002615 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2616 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002617#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2618 rc = SQLITE_BUSY;
2619#else
drh734c9862008-11-28 15:37:20 +00002620 rc = sqliteErrorFromPosixError(tErrno,
2621 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002622#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002623 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002624 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00002625 }
2626 return rc;
drhbfe66312006-10-03 17:40:40 +00002627 } else {
aswift5b1a2562008-08-22 00:22:35 +00002628 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002629 }
2630}
2631
drh6b9d6dd2008-12-03 19:34:47 +00002632/*
2633** This routine checks if there is a RESERVED lock held on the specified
2634** file by this or any other process. If such a lock is held, set *pResOut
2635** to a non-zero value otherwise *pResOut is set to zero. The return value
2636** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2637*/
danielk1977e339d652008-06-28 11:23:00 +00002638static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002639 int rc = SQLITE_OK;
2640 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002641 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002642 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002643
aswift5b1a2562008-08-22 00:22:35 +00002644 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2645
2646 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002647 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002648 if( context->reserved ){
2649 *pResOut = 1;
2650 return SQLITE_OK;
2651 }
drh8af6c222010-05-14 12:43:01 +00002652 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002653
2654 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002655 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002656 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002657 }
2658
2659 /* Otherwise see if some other process holds it.
2660 */
aswift5b1a2562008-08-22 00:22:35 +00002661 if( !reserved ){
2662 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002663 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002664 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002665 /* if we succeeded in taking the reserved lock, unlock it to restore
2666 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002667 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002668 } else {
2669 /* if we failed to get the lock then someone else must have it */
2670 reserved = 1;
2671 }
2672 if( IS_LOCK_ERROR(lrc) ){
2673 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002674 }
2675 }
drhbfe66312006-10-03 17:40:40 +00002676
drh7ed97b92010-01-20 13:07:21 +00002677 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002678 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002679
2680 *pResOut = reserved;
2681 return rc;
drhbfe66312006-10-03 17:40:40 +00002682}
2683
drh6b9d6dd2008-12-03 19:34:47 +00002684/*
drh308c2a52010-05-14 11:30:18 +00002685** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002686** of the following:
2687**
2688** (1) SHARED_LOCK
2689** (2) RESERVED_LOCK
2690** (3) PENDING_LOCK
2691** (4) EXCLUSIVE_LOCK
2692**
2693** Sometimes when requesting one lock state, additional lock states
2694** are inserted in between. The locking might fail on one of the later
2695** transitions leaving the lock state different from what it started but
2696** still short of its goal. The following chart shows the allowed
2697** transitions and the inserted intermediate states:
2698**
2699** UNLOCKED -> SHARED
2700** SHARED -> RESERVED
2701** SHARED -> (PENDING) -> EXCLUSIVE
2702** RESERVED -> (PENDING) -> EXCLUSIVE
2703** PENDING -> EXCLUSIVE
2704**
2705** This routine will only increase a lock. Use the sqlite3OsUnlock()
2706** routine to lower a locking level.
2707*/
drh308c2a52010-05-14 11:30:18 +00002708static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002709 int rc = SQLITE_OK;
2710 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002711 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002712 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002713
2714 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002715 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2716 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh5ac93652015-03-21 20:59:43 +00002717 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
drh339eb0b2008-03-07 15:34:11 +00002718
drhbfe66312006-10-03 17:40:40 +00002719 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002720 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002721 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002722 */
drh308c2a52010-05-14 11:30:18 +00002723 if( pFile->eFileLock>=eFileLock ){
2724 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2725 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002726 return SQLITE_OK;
2727 }
2728
2729 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002730 ** (1) We never move from unlocked to anything higher than shared lock.
2731 ** (2) SQLite never explicitly requests a pendig lock.
2732 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002733 */
drh308c2a52010-05-14 11:30:18 +00002734 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2735 assert( eFileLock!=PENDING_LOCK );
2736 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002737
drh8af6c222010-05-14 12:43:01 +00002738 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002739 */
drh6c7d5c52008-11-21 20:32:33 +00002740 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002741 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002742
2743 /* If some thread using this PID has a lock via a different unixFile*
2744 ** handle that precludes the requested lock, return BUSY.
2745 */
drh8af6c222010-05-14 12:43:01 +00002746 if( (pFile->eFileLock!=pInode->eFileLock &&
2747 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002748 ){
2749 rc = SQLITE_BUSY;
2750 goto afp_end_lock;
2751 }
2752
2753 /* If a SHARED lock is requested, and some thread using this PID already
2754 ** has a SHARED or RESERVED lock, then increment reference counts and
2755 ** return SQLITE_OK.
2756 */
drh308c2a52010-05-14 11:30:18 +00002757 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002758 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002759 assert( eFileLock==SHARED_LOCK );
2760 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002761 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002762 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002763 pInode->nShared++;
2764 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002765 goto afp_end_lock;
2766 }
drhbfe66312006-10-03 17:40:40 +00002767
2768 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002769 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2770 ** be released.
2771 */
drh308c2a52010-05-14 11:30:18 +00002772 if( eFileLock==SHARED_LOCK
2773 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002774 ){
2775 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002776 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002777 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002778 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002779 goto afp_end_lock;
2780 }
2781 }
2782
2783 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002784 ** operating system calls for the specified lock.
2785 */
drh308c2a52010-05-14 11:30:18 +00002786 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002787 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002788 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002789
drh8af6c222010-05-14 12:43:01 +00002790 assert( pInode->nShared==0 );
2791 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002792
2793 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002794 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002795 /* note that the quality of the randomness doesn't matter that much */
2796 lk = random();
drh8af6c222010-05-14 12:43:01 +00002797 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002798 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002799 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002800 if( IS_LOCK_ERROR(lrc1) ){
2801 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002802 }
aswift5b1a2562008-08-22 00:22:35 +00002803 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002804 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002805
aswift5b1a2562008-08-22 00:22:35 +00002806 if( IS_LOCK_ERROR(lrc1) ) {
drh4bf66fd2015-02-19 02:43:02 +00002807 storeLastErrno(pFile, lrc1Errno);
aswift5b1a2562008-08-22 00:22:35 +00002808 rc = lrc1;
2809 goto afp_end_lock;
2810 } else if( IS_LOCK_ERROR(lrc2) ){
2811 rc = lrc2;
2812 goto afp_end_lock;
2813 } else if( lrc1 != SQLITE_OK ) {
2814 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002815 } else {
drh308c2a52010-05-14 11:30:18 +00002816 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002817 pInode->nLock++;
2818 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002819 }
drh8af6c222010-05-14 12:43:01 +00002820 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002821 /* We are trying for an exclusive lock but another thread in this
2822 ** same process is still holding a shared lock. */
2823 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002824 }else{
2825 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2826 ** assumed that there is a SHARED or greater lock on the file
2827 ** already.
2828 */
2829 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002830 assert( 0!=pFile->eFileLock );
2831 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002832 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002833 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002834 if( !failed ){
2835 context->reserved = 1;
2836 }
drhbfe66312006-10-03 17:40:40 +00002837 }
drh308c2a52010-05-14 11:30:18 +00002838 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002839 /* Acquire an EXCLUSIVE lock */
2840
2841 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002842 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002843 */
drh6b9d6dd2008-12-03 19:34:47 +00002844 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002845 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002846 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002847 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002848 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002849 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002850 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002851 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002852 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2853 ** a critical I/O error
2854 */
2855 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2856 SQLITE_IOERR_LOCK;
2857 goto afp_end_lock;
2858 }
2859 }else{
aswift5b1a2562008-08-22 00:22:35 +00002860 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002861 }
2862 }
aswift5b1a2562008-08-22 00:22:35 +00002863 if( failed ){
2864 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002865 }
2866 }
2867
2868 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002869 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002870 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002871 }else if( eFileLock==EXCLUSIVE_LOCK ){
2872 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002873 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002874 }
2875
2876afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002877 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002878 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2879 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002880 return rc;
2881}
2882
2883/*
drh308c2a52010-05-14 11:30:18 +00002884** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002885** must be either NO_LOCK or SHARED_LOCK.
2886**
2887** If the locking level of the file descriptor is already at or below
2888** the requested locking level, this routine is a no-op.
2889*/
drh308c2a52010-05-14 11:30:18 +00002890static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002891 int rc = SQLITE_OK;
2892 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002893 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002894 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2895 int skipShared = 0;
2896#ifdef SQLITE_TEST
2897 int h = pFile->h;
2898#endif
drhbfe66312006-10-03 17:40:40 +00002899
2900 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002901 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002902 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00002903 osGetpid(0)));
aswift5b1a2562008-08-22 00:22:35 +00002904
drh308c2a52010-05-14 11:30:18 +00002905 assert( eFileLock<=SHARED_LOCK );
2906 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002907 return SQLITE_OK;
2908 }
drh6c7d5c52008-11-21 20:32:33 +00002909 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002910 pInode = pFile->pInode;
2911 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002912 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002913 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002914 SimulateIOErrorBenign(1);
2915 SimulateIOError( h=(-1) )
2916 SimulateIOErrorBenign(0);
2917
drhd3d8c042012-05-29 17:02:40 +00002918#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002919 /* When reducing a lock such that other processes can start
2920 ** reading the database file again, make sure that the
2921 ** transaction counter was updated if any part of the database
2922 ** file changed. If the transaction counter is not updated,
2923 ** other connections to the same file might not realize that
2924 ** the file has changed and hence might not know to flush their
2925 ** cache. The use of a stale cache can lead to database corruption.
2926 */
2927 assert( pFile->inNormalWrite==0
2928 || pFile->dbUpdate==0
2929 || pFile->transCntrChng==1 );
2930 pFile->inNormalWrite = 0;
2931#endif
aswiftaebf4132008-11-21 00:10:35 +00002932
drh308c2a52010-05-14 11:30:18 +00002933 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002934 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002935 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002936 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002937 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002938 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2939 } else {
2940 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002941 }
2942 }
drh308c2a52010-05-14 11:30:18 +00002943 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002944 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002945 }
drh308c2a52010-05-14 11:30:18 +00002946 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002947 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2948 if( !rc ){
2949 context->reserved = 0;
2950 }
aswiftaebf4132008-11-21 00:10:35 +00002951 }
drh8af6c222010-05-14 12:43:01 +00002952 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2953 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002954 }
aswiftaebf4132008-11-21 00:10:35 +00002955 }
drh308c2a52010-05-14 11:30:18 +00002956 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002957
drh7ed97b92010-01-20 13:07:21 +00002958 /* Decrement the shared lock counter. Release the lock using an
2959 ** OS call only when all threads in this same process have released
2960 ** the lock.
2961 */
drh8af6c222010-05-14 12:43:01 +00002962 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2963 pInode->nShared--;
2964 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002965 SimulateIOErrorBenign(1);
2966 SimulateIOError( h=(-1) )
2967 SimulateIOErrorBenign(0);
2968 if( !skipShared ){
2969 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2970 }
2971 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002972 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002973 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002974 }
2975 }
2976 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002977 pInode->nLock--;
2978 assert( pInode->nLock>=0 );
2979 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002980 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002981 }
2982 }
drhbfe66312006-10-03 17:40:40 +00002983 }
drh7ed97b92010-01-20 13:07:21 +00002984
drh6c7d5c52008-11-21 20:32:33 +00002985 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002986 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002987 return rc;
2988}
2989
2990/*
drh339eb0b2008-03-07 15:34:11 +00002991** Close a file & cleanup AFP specific locking context
2992*/
danielk1977e339d652008-06-28 11:23:00 +00002993static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002994 int rc = SQLITE_OK;
drha8de1e12015-11-30 00:05:39 +00002995 unixFile *pFile = (unixFile*)id;
2996 assert( id!=0 );
2997 afpUnlock(id, NO_LOCK);
2998 unixEnterMutex();
2999 if( pFile->pInode && pFile->pInode->nLock ){
3000 /* If there are outstanding locks, do not actually close the file just
3001 ** yet because that would clear those locks. Instead, add the file
3002 ** descriptor to pInode->aPending. It will be automatically closed when
3003 ** the last lock is cleared.
3004 */
3005 setPendingFd(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003006 }
drha8de1e12015-11-30 00:05:39 +00003007 releaseInodeInfo(pFile);
3008 sqlite3_free(pFile->lockingContext);
3009 rc = closeUnixFile(id);
3010 unixLeaveMutex();
drh7ed97b92010-01-20 13:07:21 +00003011 return rc;
drhbfe66312006-10-03 17:40:40 +00003012}
3013
drhd2cb50b2009-01-09 21:41:17 +00003014#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003015/*
3016** The code above is the AFP lock implementation. The code is specific
3017** to MacOSX and does not work on other unix platforms. No alternative
3018** is available. If you don't compile for a mac, then the "unix-afp"
3019** VFS is not available.
3020**
3021********************* End of the AFP lock implementation **********************
3022******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003023
drh7ed97b92010-01-20 13:07:21 +00003024/******************************************************************************
3025*************************** Begin NFS Locking ********************************/
3026
3027#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3028/*
drh308c2a52010-05-14 11:30:18 +00003029 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003030 ** must be either NO_LOCK or SHARED_LOCK.
3031 **
3032 ** If the locking level of the file descriptor is already at or below
3033 ** the requested locking level, this routine is a no-op.
3034 */
drh308c2a52010-05-14 11:30:18 +00003035static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003036 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003037}
3038
3039#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3040/*
3041** The code above is the NFS lock implementation. The code is specific
3042** to MacOSX and does not work on other unix platforms. No alternative
3043** is available.
3044**
3045********************* End of the NFS lock implementation **********************
3046******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003047
3048/******************************************************************************
3049**************** Non-locking sqlite3_file methods *****************************
3050**
3051** The next division contains implementations for all methods of the
3052** sqlite3_file object other than the locking methods. The locking
3053** methods were defined in divisions above (one locking method per
3054** division). Those methods that are common to all locking modes
3055** are gather together into this division.
3056*/
drhbfe66312006-10-03 17:40:40 +00003057
3058/*
drh734c9862008-11-28 15:37:20 +00003059** Seek to the offset passed as the second argument, then read cnt
3060** bytes into pBuf. Return the number of bytes actually read.
3061**
3062** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3063** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3064** one system to another. Since SQLite does not define USE_PREAD
peter.d.reid60ec9142014-09-06 16:39:46 +00003065** in any form by default, we will not attempt to define _XOPEN_SOURCE.
drh734c9862008-11-28 15:37:20 +00003066** See tickets #2741 and #2681.
3067**
3068** To avoid stomping the errno value on a failed read the lastErrno value
3069** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003070*/
drh734c9862008-11-28 15:37:20 +00003071static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3072 int got;
drh58024642011-11-07 18:16:00 +00003073 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003074#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003075 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003076#endif
drh734c9862008-11-28 15:37:20 +00003077 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003078 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003079 assert( id->h>2 );
drh58024642011-11-07 18:16:00 +00003080 do{
drh734c9862008-11-28 15:37:20 +00003081#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003082 got = osPread(id->h, pBuf, cnt, offset);
3083 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003084#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003085 got = osPread64(id->h, pBuf, cnt, offset);
3086 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003087#else
drh58024642011-11-07 18:16:00 +00003088 newOffset = lseek(id->h, offset, SEEK_SET);
3089 SimulateIOError( newOffset-- );
3090 if( newOffset!=offset ){
3091 if( newOffset == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00003092 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003093 }else{
drh4bf66fd2015-02-19 02:43:02 +00003094 storeLastErrno((unixFile*)id, 0);
drh58024642011-11-07 18:16:00 +00003095 }
3096 return -1;
drh734c9862008-11-28 15:37:20 +00003097 }
drh58024642011-11-07 18:16:00 +00003098 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003099#endif
drh58024642011-11-07 18:16:00 +00003100 if( got==cnt ) break;
3101 if( got<0 ){
3102 if( errno==EINTR ){ got = 1; continue; }
3103 prior = 0;
drh4bf66fd2015-02-19 02:43:02 +00003104 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003105 break;
3106 }else if( got>0 ){
3107 cnt -= got;
3108 offset += got;
3109 prior += got;
3110 pBuf = (void*)(got + (char*)pBuf);
3111 }
3112 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003113 TIMER_END;
drh58024642011-11-07 18:16:00 +00003114 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3115 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3116 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003117}
3118
3119/*
drh734c9862008-11-28 15:37:20 +00003120** Read data from a file into a buffer. Return SQLITE_OK if all
3121** bytes were read successfully and SQLITE_IOERR if anything goes
3122** wrong.
drh339eb0b2008-03-07 15:34:11 +00003123*/
drh734c9862008-11-28 15:37:20 +00003124static int unixRead(
3125 sqlite3_file *id,
3126 void *pBuf,
3127 int amt,
3128 sqlite3_int64 offset
3129){
dan08da86a2009-08-21 17:18:03 +00003130 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003131 int got;
3132 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003133 assert( offset>=0 );
3134 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003135
dan08da86a2009-08-21 17:18:03 +00003136 /* If this is a database file (not a journal, master-journal or temp
3137 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003138#if 0
dane946c392009-08-22 11:39:46 +00003139 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003140 || offset>=PENDING_BYTE+512
3141 || offset+amt<=PENDING_BYTE
3142 );
dan7c246102010-04-12 19:00:29 +00003143#endif
drh08c6d442009-02-09 17:34:07 +00003144
drh9b4c59f2013-04-15 17:03:42 +00003145#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003146 /* Deal with as much of this read request as possible by transfering
3147 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003148 if( offset<pFile->mmapSize ){
3149 if( offset+amt <= pFile->mmapSize ){
3150 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3151 return SQLITE_OK;
3152 }else{
3153 int nCopy = pFile->mmapSize - offset;
3154 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3155 pBuf = &((u8 *)pBuf)[nCopy];
3156 amt -= nCopy;
3157 offset += nCopy;
3158 }
3159 }
drh6e0b6d52013-04-09 16:19:20 +00003160#endif
danf23da962013-03-23 21:00:41 +00003161
dan08da86a2009-08-21 17:18:03 +00003162 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003163 if( got==amt ){
3164 return SQLITE_OK;
3165 }else if( got<0 ){
3166 /* lastErrno set by seekAndRead */
3167 return SQLITE_IOERR_READ;
3168 }else{
drh4bf66fd2015-02-19 02:43:02 +00003169 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003170 /* Unread parts of the buffer must be zero-filled */
3171 memset(&((char*)pBuf)[got], 0, amt-got);
3172 return SQLITE_IOERR_SHORT_READ;
3173 }
3174}
3175
3176/*
dan47a2b4a2013-04-26 16:09:29 +00003177** Attempt to seek the file-descriptor passed as the first argument to
3178** absolute offset iOff, then attempt to write nBuf bytes of data from
3179** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3180** return the actual number of bytes written (which may be less than
3181** nBuf).
3182*/
3183static int seekAndWriteFd(
3184 int fd, /* File descriptor to write to */
3185 i64 iOff, /* File offset to begin writing at */
3186 const void *pBuf, /* Copy data from this buffer to the file */
3187 int nBuf, /* Size of buffer pBuf in bytes */
3188 int *piErrno /* OUT: Error number if error occurs */
3189){
3190 int rc = 0; /* Value returned by system call */
3191
3192 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003193 assert( fd>2 );
dan47a2b4a2013-04-26 16:09:29 +00003194 nBuf &= 0x1ffff;
3195 TIMER_START;
3196
3197#if defined(USE_PREAD)
drh2da47d32015-02-21 00:56:05 +00003198 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
dan47a2b4a2013-04-26 16:09:29 +00003199#elif defined(USE_PREAD64)
drh2da47d32015-02-21 00:56:05 +00003200 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
dan47a2b4a2013-04-26 16:09:29 +00003201#else
3202 do{
3203 i64 iSeek = lseek(fd, iOff, SEEK_SET);
3204 SimulateIOError( iSeek-- );
3205
3206 if( iSeek!=iOff ){
3207 if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
3208 return -1;
3209 }
3210 rc = osWrite(fd, pBuf, nBuf);
3211 }while( rc<0 && errno==EINTR );
3212#endif
3213
3214 TIMER_END;
3215 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3216
3217 if( rc<0 && piErrno ) *piErrno = errno;
3218 return rc;
3219}
3220
3221
3222/*
drh734c9862008-11-28 15:37:20 +00003223** Seek to the offset in id->offset then read cnt bytes into pBuf.
3224** Return the number of bytes actually read. Update the offset.
3225**
3226** To avoid stomping the errno value on a failed write the lastErrno value
3227** is set before returning.
3228*/
3229static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003230 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003231}
3232
3233
3234/*
3235** Write data from a buffer into a file. Return SQLITE_OK on success
3236** or some other error code on failure.
3237*/
3238static int unixWrite(
3239 sqlite3_file *id,
3240 const void *pBuf,
3241 int amt,
3242 sqlite3_int64 offset
3243){
dan08da86a2009-08-21 17:18:03 +00003244 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003245 int wrote = 0;
3246 assert( id );
3247 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003248
dan08da86a2009-08-21 17:18:03 +00003249 /* If this is a database file (not a journal, master-journal or temp
3250 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003251#if 0
dane946c392009-08-22 11:39:46 +00003252 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003253 || offset>=PENDING_BYTE+512
3254 || offset+amt<=PENDING_BYTE
3255 );
dan7c246102010-04-12 19:00:29 +00003256#endif
drh08c6d442009-02-09 17:34:07 +00003257
drhd3d8c042012-05-29 17:02:40 +00003258#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003259 /* If we are doing a normal write to a database file (as opposed to
3260 ** doing a hot-journal rollback or a write to some file other than a
3261 ** normal database file) then record the fact that the database
3262 ** has changed. If the transaction counter is modified, record that
3263 ** fact too.
3264 */
dan08da86a2009-08-21 17:18:03 +00003265 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003266 pFile->dbUpdate = 1; /* The database has been modified */
3267 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003268 int rc;
drh8f941bc2009-01-14 23:03:40 +00003269 char oldCntr[4];
3270 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003271 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003272 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003273 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003274 pFile->transCntrChng = 1; /* The transaction counter has changed */
3275 }
3276 }
3277 }
3278#endif
3279
danfe33e392015-11-17 20:56:06 +00003280#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003281 /* Deal with as much of this write request as possible by transfering
3282 ** data from the memory mapping using memcpy(). */
3283 if( offset<pFile->mmapSize ){
3284 if( offset+amt <= pFile->mmapSize ){
3285 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3286 return SQLITE_OK;
3287 }else{
3288 int nCopy = pFile->mmapSize - offset;
3289 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3290 pBuf = &((u8 *)pBuf)[nCopy];
3291 amt -= nCopy;
3292 offset += nCopy;
3293 }
3294 }
drh6e0b6d52013-04-09 16:19:20 +00003295#endif
drh02bf8b42015-09-01 23:51:53 +00003296
3297 while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
drh734c9862008-11-28 15:37:20 +00003298 amt -= wrote;
3299 offset += wrote;
3300 pBuf = &((char*)pBuf)[wrote];
3301 }
3302 SimulateIOError(( wrote=(-1), amt=1 ));
3303 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003304
drh02bf8b42015-09-01 23:51:53 +00003305 if( amt>wrote ){
drha21b83b2011-04-15 12:36:10 +00003306 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003307 /* lastErrno set by seekAndWrite */
3308 return SQLITE_IOERR_WRITE;
3309 }else{
drh4bf66fd2015-02-19 02:43:02 +00003310 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003311 return SQLITE_FULL;
3312 }
3313 }
dan6e09d692010-07-27 18:34:15 +00003314
drh734c9862008-11-28 15:37:20 +00003315 return SQLITE_OK;
3316}
3317
3318#ifdef SQLITE_TEST
3319/*
3320** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003321** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003322*/
3323int sqlite3_sync_count = 0;
3324int sqlite3_fullsync_count = 0;
3325#endif
3326
3327/*
drh89240432009-03-25 01:06:01 +00003328** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003329** Others do no. To be safe, we will stick with the (slightly slower)
3330** fsync(). If you know that your system does support fdatasync() correctly,
drhf7a4a1b2015-01-10 18:02:45 +00003331** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003332*/
drhf7a4a1b2015-01-10 18:02:45 +00003333#if !defined(fdatasync) && !HAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003334# define fdatasync fsync
3335#endif
3336
3337/*
3338** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3339** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3340** only available on Mac OS X. But that could change.
3341*/
3342#ifdef F_FULLFSYNC
3343# define HAVE_FULLFSYNC 1
3344#else
3345# define HAVE_FULLFSYNC 0
3346#endif
3347
3348
3349/*
3350** The fsync() system call does not work as advertised on many
3351** unix systems. The following procedure is an attempt to make
3352** it work better.
3353**
3354** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3355** for testing when we want to run through the test suite quickly.
3356** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3357** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3358** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003359**
3360** SQLite sets the dataOnly flag if the size of the file is unchanged.
3361** The idea behind dataOnly is that it should only write the file content
3362** to disk, not the inode. We only set dataOnly if the file size is
3363** unchanged since the file size is part of the inode. However,
3364** Ted Ts'o tells us that fdatasync() will also write the inode if the
3365** file size has changed. The only real difference between fdatasync()
3366** and fsync(), Ted tells us, is that fdatasync() will not flush the
3367** inode if the mtime or owner or other inode attributes have changed.
3368** We only care about the file size, not the other file attributes, so
3369** as far as SQLite is concerned, an fdatasync() is always adequate.
3370** So, we always use fdatasync() if it is available, regardless of
3371** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003372*/
3373static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003374 int rc;
drh734c9862008-11-28 15:37:20 +00003375
3376 /* The following "ifdef/elif/else/" block has the same structure as
3377 ** the one below. It is replicated here solely to avoid cluttering
3378 ** up the real code with the UNUSED_PARAMETER() macros.
3379 */
3380#ifdef SQLITE_NO_SYNC
3381 UNUSED_PARAMETER(fd);
3382 UNUSED_PARAMETER(fullSync);
3383 UNUSED_PARAMETER(dataOnly);
3384#elif HAVE_FULLFSYNC
3385 UNUSED_PARAMETER(dataOnly);
3386#else
3387 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003388 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003389#endif
3390
3391 /* Record the number of times that we do a normal fsync() and
3392 ** FULLSYNC. This is used during testing to verify that this procedure
3393 ** gets called with the correct arguments.
3394 */
3395#ifdef SQLITE_TEST
3396 if( fullSync ) sqlite3_fullsync_count++;
3397 sqlite3_sync_count++;
3398#endif
3399
3400 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3401 ** no-op
3402 */
3403#ifdef SQLITE_NO_SYNC
3404 rc = SQLITE_OK;
3405#elif HAVE_FULLFSYNC
3406 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003407 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003408 }else{
3409 rc = 1;
3410 }
3411 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003412 ** It shouldn't be possible for fullfsync to fail on the local
3413 ** file system (on OSX), so failure indicates that FULLFSYNC
3414 ** isn't supported for this file system. So, attempt an fsync
3415 ** and (for now) ignore the overhead of a superfluous fcntl call.
3416 ** It'd be better to detect fullfsync support once and avoid
3417 ** the fcntl call every time sync is called.
3418 */
drh734c9862008-11-28 15:37:20 +00003419 if( rc ) rc = fsync(fd);
3420
drh7ed97b92010-01-20 13:07:21 +00003421#elif defined(__APPLE__)
3422 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3423 ** so currently we default to the macro that redefines fdatasync to fsync
3424 */
3425 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003426#else
drh0b647ff2009-03-21 14:41:04 +00003427 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003428#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003429 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003430 rc = fsync(fd);
3431 }
drh0b647ff2009-03-21 14:41:04 +00003432#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003433#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3434
3435 if( OS_VXWORKS && rc!= -1 ){
3436 rc = 0;
3437 }
chw97185482008-11-17 08:05:31 +00003438 return rc;
drhbfe66312006-10-03 17:40:40 +00003439}
3440
drh734c9862008-11-28 15:37:20 +00003441/*
drh0059eae2011-08-08 23:48:40 +00003442** Open a file descriptor to the directory containing file zFilename.
3443** If successful, *pFd is set to the opened file descriptor and
3444** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3445** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3446** value.
3447**
drh90315a22011-08-10 01:52:12 +00003448** The directory file descriptor is used for only one thing - to
3449** fsync() a directory to make sure file creation and deletion events
3450** are flushed to disk. Such fsyncs are not needed on newer
3451** journaling filesystems, but are required on older filesystems.
3452**
3453** This routine can be overridden using the xSetSysCall interface.
3454** The ability to override this routine was added in support of the
3455** chromium sandbox. Opening a directory is a security risk (we are
3456** told) so making it overrideable allows the chromium sandbox to
3457** replace this routine with a harmless no-op. To make this routine
3458** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3459** *pFd set to a negative number.
3460**
drh0059eae2011-08-08 23:48:40 +00003461** If SQLITE_OK is returned, the caller is responsible for closing
3462** the file descriptor *pFd using close().
3463*/
3464static int openDirectory(const char *zFilename, int *pFd){
3465 int ii;
3466 int fd = -1;
3467 char zDirname[MAX_PATHNAME+1];
3468
3469 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3470 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3471 if( ii>0 ){
3472 zDirname[ii] = '\0';
3473 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3474 if( fd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003475 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3476 }
3477 }
3478 *pFd = fd;
drhacb6b282015-11-26 10:37:05 +00003479 if( fd>=0 ) return SQLITE_OK;
3480 return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
drh0059eae2011-08-08 23:48:40 +00003481}
3482
3483/*
drh734c9862008-11-28 15:37:20 +00003484** Make sure all writes to a particular file are committed to disk.
3485**
3486** If dataOnly==0 then both the file itself and its metadata (file
3487** size, access time, etc) are synced. If dataOnly!=0 then only the
3488** file data is synced.
3489**
3490** Under Unix, also make sure that the directory entry for the file
3491** has been created by fsync-ing the directory that contains the file.
3492** If we do not do this and we encounter a power failure, the directory
3493** entry for the journal might not exist after we reboot. The next
3494** SQLite to access the file will not know that the journal exists (because
3495** the directory entry for the journal was never created) and the transaction
3496** will not roll back - possibly leading to database corruption.
3497*/
3498static int unixSync(sqlite3_file *id, int flags){
3499 int rc;
3500 unixFile *pFile = (unixFile*)id;
3501
3502 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3503 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3504
3505 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3506 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3507 || (flags&0x0F)==SQLITE_SYNC_FULL
3508 );
3509
3510 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3511 ** line is to test that doing so does not cause any problems.
3512 */
3513 SimulateDiskfullError( return SQLITE_FULL );
3514
3515 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003516 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003517 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3518 SimulateIOError( rc=1 );
3519 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003520 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003521 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003522 }
drh0059eae2011-08-08 23:48:40 +00003523
3524 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003525 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003526 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003527 */
3528 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3529 int dirfd;
3530 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003531 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003532 rc = osOpenDirectory(pFile->zPath, &dirfd);
drhacb6b282015-11-26 10:37:05 +00003533 if( rc==SQLITE_OK ){
drh0059eae2011-08-08 23:48:40 +00003534 full_fsync(dirfd, 0, 0);
3535 robust_close(pFile, dirfd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00003536 }else{
3537 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00003538 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003539 }
drh0059eae2011-08-08 23:48:40 +00003540 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003541 }
3542 return rc;
3543}
3544
3545/*
3546** Truncate an open file to a specified size
3547*/
3548static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003549 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003550 int rc;
dan6e09d692010-07-27 18:34:15 +00003551 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003552 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003553
3554 /* If the user has configured a chunk-size for this file, truncate the
3555 ** file so that it consists of an integer number of chunks (i.e. the
3556 ** actual file size after the operation may be larger than the requested
3557 ** size).
3558 */
drhb8af4b72012-04-05 20:04:39 +00003559 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003560 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3561 }
3562
dan2ee53412014-09-06 16:49:40 +00003563 rc = robust_ftruncate(pFile->h, nByte);
drh734c9862008-11-28 15:37:20 +00003564 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003565 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003566 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003567 }else{
drhd3d8c042012-05-29 17:02:40 +00003568#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003569 /* If we are doing a normal write to a database file (as opposed to
3570 ** doing a hot-journal rollback or a write to some file other than a
3571 ** normal database file) and we truncate the file to zero length,
3572 ** that effectively updates the change counter. This might happen
3573 ** when restoring a database using the backup API from a zero-length
3574 ** source.
3575 */
dan6e09d692010-07-27 18:34:15 +00003576 if( pFile->inNormalWrite && nByte==0 ){
3577 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003578 }
danf23da962013-03-23 21:00:41 +00003579#endif
danc0003312013-03-22 17:46:11 +00003580
mistachkine98844f2013-08-24 00:59:24 +00003581#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003582 /* If the file was just truncated to a size smaller than the currently
3583 ** mapped region, reduce the effective mapping size as well. SQLite will
3584 ** use read() and write() to access data beyond this point from now on.
3585 */
3586 if( nByte<pFile->mmapSize ){
3587 pFile->mmapSize = nByte;
3588 }
mistachkine98844f2013-08-24 00:59:24 +00003589#endif
drh3313b142009-11-06 04:13:18 +00003590
drh734c9862008-11-28 15:37:20 +00003591 return SQLITE_OK;
3592 }
3593}
3594
3595/*
3596** Determine the current size of a file in bytes
3597*/
3598static int unixFileSize(sqlite3_file *id, i64 *pSize){
3599 int rc;
3600 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003601 assert( id );
3602 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003603 SimulateIOError( rc=1 );
3604 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00003605 storeLastErrno((unixFile*)id, errno);
drh734c9862008-11-28 15:37:20 +00003606 return SQLITE_IOERR_FSTAT;
3607 }
3608 *pSize = buf.st_size;
3609
drh8af6c222010-05-14 12:43:01 +00003610 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003611 ** writes a single byte into that file in order to work around a bug
3612 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3613 ** layers, we need to report this file size as zero even though it is
3614 ** really 1. Ticket #3260.
3615 */
3616 if( *pSize==1 ) *pSize = 0;
3617
3618
3619 return SQLITE_OK;
3620}
3621
drhd2cb50b2009-01-09 21:41:17 +00003622#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003623/*
3624** Handler for proxy-locking file-control verbs. Defined below in the
3625** proxying locking division.
3626*/
3627static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003628#endif
drh715ff302008-12-03 22:32:44 +00003629
dan502019c2010-07-28 14:26:17 +00003630/*
3631** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003632** file-control operation. Enlarge the database to nBytes in size
3633** (rounded up to the next chunk-size). If the database is already
3634** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003635*/
3636static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003637 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003638 i64 nSize; /* Required file size */
3639 struct stat buf; /* Used to hold return values of fstat() */
3640
drh4bf66fd2015-02-19 02:43:02 +00003641 if( osFstat(pFile->h, &buf) ){
3642 return SQLITE_IOERR_FSTAT;
3643 }
dan502019c2010-07-28 14:26:17 +00003644
3645 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3646 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003647
dan502019c2010-07-28 14:26:17 +00003648#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003649 /* The code below is handling the return value of osFallocate()
3650 ** correctly. posix_fallocate() is defined to "returns zero on success,
3651 ** or an error number on failure". See the manpage for details. */
3652 int err;
drhff812312011-02-23 13:33:46 +00003653 do{
dan661d71a2011-03-30 19:08:03 +00003654 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3655 }while( err==EINTR );
3656 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003657#else
dan592bf7f2014-12-30 19:58:31 +00003658 /* If the OS does not have posix_fallocate(), fake it. Write a
3659 ** single byte to the last byte in each block that falls entirely
3660 ** within the extended region. Then, if required, a single byte
3661 ** at offset (nSize-1), to set the size of the file correctly.
3662 ** This is a similar technique to that used by glibc on systems
3663 ** that do not have a real fallocate() call.
dan502019c2010-07-28 14:26:17 +00003664 */
3665 int nBlk = buf.st_blksize; /* File-system block size */
danef3d66c2015-01-06 21:31:47 +00003666 int nWrite = 0; /* Number of bytes written by seekAndWrite */
dan502019c2010-07-28 14:26:17 +00003667 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003668
dan502019c2010-07-28 14:26:17 +00003669 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dan592bf7f2014-12-30 19:58:31 +00003670 assert( iWrite>=buf.st_size );
3671 assert( (iWrite/nBlk)==((buf.st_size+nBlk-1)/nBlk) );
3672 assert( ((iWrite+1)%nBlk)==0 );
3673 for(/*no-op*/; iWrite<nSize; iWrite+=nBlk ){
danef3d66c2015-01-06 21:31:47 +00003674 nWrite = seekAndWrite(pFile, iWrite, "", 1);
dandc5df0f2011-04-06 19:15:45 +00003675 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dandc5df0f2011-04-06 19:15:45 +00003676 }
danef3d66c2015-01-06 21:31:47 +00003677 if( nWrite==0 || (nSize%nBlk) ){
3678 nWrite = seekAndWrite(pFile, nSize-1, "", 1);
dan592bf7f2014-12-30 19:58:31 +00003679 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dand348c662014-12-30 14:40:53 +00003680 }
dan502019c2010-07-28 14:26:17 +00003681#endif
3682 }
3683 }
3684
mistachkine98844f2013-08-24 00:59:24 +00003685#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003686 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003687 int rc;
3688 if( pFile->szChunk<=0 ){
3689 if( robust_ftruncate(pFile->h, nByte) ){
drh4bf66fd2015-02-19 02:43:02 +00003690 storeLastErrno(pFile, errno);
danf23da962013-03-23 21:00:41 +00003691 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3692 }
3693 }
3694
3695 rc = unixMapfile(pFile, nByte);
3696 return rc;
3697 }
mistachkine98844f2013-08-24 00:59:24 +00003698#endif
danf23da962013-03-23 21:00:41 +00003699
dan502019c2010-07-28 14:26:17 +00003700 return SQLITE_OK;
3701}
danielk1977ad94b582007-08-20 06:44:22 +00003702
danielk1977e3026632004-06-22 11:29:02 +00003703/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003704** If *pArg is initially negative then this is a query. Set *pArg to
drhf12b3f62011-12-21 14:42:29 +00003705** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3706**
3707** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3708*/
3709static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3710 if( *pArg<0 ){
3711 *pArg = (pFile->ctrlFlags & mask)!=0;
3712 }else if( (*pArg)==0 ){
3713 pFile->ctrlFlags &= ~mask;
3714 }else{
3715 pFile->ctrlFlags |= mask;
3716 }
3717}
3718
drh696b33e2012-12-06 19:01:42 +00003719/* Forward declaration */
3720static int unixGetTempname(int nBuf, char *zBuf);
3721
drhf12b3f62011-12-21 14:42:29 +00003722/*
drh9e33c2c2007-08-31 18:34:59 +00003723** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003724*/
drhcc6bb3e2007-08-31 16:11:35 +00003725static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003726 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003727 switch( op ){
drhc435cf72015-03-21 16:36:03 +00003728 case SQLITE_FCNTL_WAL_BLOCK: {
drh62ca61e2015-04-03 20:33:33 +00003729 /* pFile->ctrlFlags |= UNIXFILE_BLOCK; // Deferred feature */
drhc435cf72015-03-21 16:36:03 +00003730 return SQLITE_OK;
3731 }
drh9e33c2c2007-08-31 18:34:59 +00003732 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003733 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003734 return SQLITE_OK;
3735 }
drh4bf66fd2015-02-19 02:43:02 +00003736 case SQLITE_FCNTL_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003737 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003738 return SQLITE_OK;
3739 }
dan6e09d692010-07-27 18:34:15 +00003740 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003741 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003742 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003743 }
drh9ff27ec2010-05-19 19:26:05 +00003744 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003745 int rc;
3746 SimulateIOErrorBenign(1);
3747 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3748 SimulateIOErrorBenign(0);
3749 return rc;
drhf0b190d2011-07-26 16:03:07 +00003750 }
3751 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003752 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3753 return SQLITE_OK;
3754 }
drhcb15f352011-12-23 01:04:17 +00003755 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3756 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003757 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003758 }
drhde60fc22011-12-14 17:53:36 +00003759 case SQLITE_FCNTL_VFSNAME: {
3760 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3761 return SQLITE_OK;
3762 }
drh696b33e2012-12-06 19:01:42 +00003763 case SQLITE_FCNTL_TEMPFILENAME: {
drhf3cdcdc2015-04-29 16:50:28 +00003764 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
drh696b33e2012-12-06 19:01:42 +00003765 if( zTFile ){
3766 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3767 *(char**)pArg = zTFile;
3768 }
3769 return SQLITE_OK;
3770 }
drhb959a012013-12-07 12:29:22 +00003771 case SQLITE_FCNTL_HAS_MOVED: {
3772 *(int*)pArg = fileHasMoved(pFile);
3773 return SQLITE_OK;
3774 }
mistachkine98844f2013-08-24 00:59:24 +00003775#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003776 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003777 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003778 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003779 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3780 newLimit = sqlite3GlobalConfig.mxMmap;
3781 }
3782 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003783 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003784 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003785 if( pFile->mmapSize>0 ){
3786 unixUnmapfile(pFile);
3787 rc = unixMapfile(pFile, -1);
3788 }
danbcb8a862013-04-08 15:30:41 +00003789 }
drh34e258c2013-05-23 01:40:53 +00003790 return rc;
danb2d3de32013-03-14 18:34:37 +00003791 }
mistachkine98844f2013-08-24 00:59:24 +00003792#endif
drhd3d8c042012-05-29 17:02:40 +00003793#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003794 /* The pager calls this method to signal that it has done
3795 ** a rollback and that the database is therefore unchanged and
3796 ** it hence it is OK for the transaction change counter to be
3797 ** unchanged.
3798 */
3799 case SQLITE_FCNTL_DB_UNCHANGED: {
3800 ((unixFile*)id)->dbUpdate = 0;
3801 return SQLITE_OK;
3802 }
3803#endif
drhd2cb50b2009-01-09 21:41:17 +00003804#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh4bf66fd2015-02-19 02:43:02 +00003805 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
3806 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003807 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003808 }
drhd2cb50b2009-01-09 21:41:17 +00003809#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003810 }
drh0b52b7d2011-01-26 19:46:22 +00003811 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003812}
3813
3814/*
danielk1977a3d4c882007-03-23 10:08:38 +00003815** Return the sector size in bytes of the underlying block device for
3816** the specified file. This is almost always 512 bytes, but may be
3817** larger for some devices.
3818**
3819** SQLite code assumes this function cannot fail. It also assumes that
3820** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003821** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003822** same for both.
3823*/
drh537dddf2012-10-26 13:46:24 +00003824#ifndef __QNXNTO__
3825static int unixSectorSize(sqlite3_file *NotUsed){
3826 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003827 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003828}
drh537dddf2012-10-26 13:46:24 +00003829#endif
3830
3831/*
3832** The following version of unixSectorSize() is optimized for QNX.
3833*/
3834#ifdef __QNXNTO__
3835#include <sys/dcmd_blk.h>
3836#include <sys/statvfs.h>
3837static int unixSectorSize(sqlite3_file *id){
3838 unixFile *pFile = (unixFile*)id;
3839 if( pFile->sectorSize == 0 ){
3840 struct statvfs fsInfo;
3841
3842 /* Set defaults for non-supported filesystems */
3843 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3844 pFile->deviceCharacteristics = 0;
3845 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3846 return pFile->sectorSize;
3847 }
3848
3849 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3850 pFile->sectorSize = fsInfo.f_bsize;
3851 pFile->deviceCharacteristics =
3852 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3853 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3854 ** the write succeeds */
3855 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3856 ** so it is ordered */
3857 0;
3858 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3859 pFile->sectorSize = fsInfo.f_bsize;
3860 pFile->deviceCharacteristics =
3861 /* etfs cluster size writes are atomic */
3862 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3863 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3864 ** the write succeeds */
3865 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3866 ** so it is ordered */
3867 0;
3868 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3869 pFile->sectorSize = fsInfo.f_bsize;
3870 pFile->deviceCharacteristics =
3871 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3872 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3873 ** the write succeeds */
3874 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3875 ** so it is ordered */
3876 0;
3877 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3878 pFile->sectorSize = fsInfo.f_bsize;
3879 pFile->deviceCharacteristics =
3880 /* full bitset of atomics from max sector size and smaller */
3881 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3882 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3883 ** so it is ordered */
3884 0;
3885 }else if( strstr(fsInfo.f_basetype, "dos") ){
3886 pFile->sectorSize = fsInfo.f_bsize;
3887 pFile->deviceCharacteristics =
3888 /* full bitset of atomics from max sector size and smaller */
3889 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3890 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3891 ** so it is ordered */
3892 0;
3893 }else{
3894 pFile->deviceCharacteristics =
3895 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3896 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3897 ** the write succeeds */
3898 0;
3899 }
3900 }
3901 /* Last chance verification. If the sector size isn't a multiple of 512
3902 ** then it isn't valid.*/
3903 if( pFile->sectorSize % 512 != 0 ){
3904 pFile->deviceCharacteristics = 0;
3905 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3906 }
3907 return pFile->sectorSize;
3908}
3909#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003910
danielk197790949c22007-08-17 16:50:38 +00003911/*
drhf12b3f62011-12-21 14:42:29 +00003912** Return the device characteristics for the file.
3913**
drhcb15f352011-12-23 01:04:17 +00003914** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
peter.d.reid60ec9142014-09-06 16:39:46 +00003915** However, that choice is controversial since technically the underlying
drhcb15f352011-12-23 01:04:17 +00003916** file system does not always provide powersafe overwrites. (In other
3917** words, after a power-loss event, parts of the file that were never
3918** written might end up being altered.) However, non-PSOW behavior is very,
3919** very rare. And asserting PSOW makes a large reduction in the amount
3920** of required I/O for journaling, since a lot of padding is eliminated.
3921** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3922** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003923*/
drhf12b3f62011-12-21 14:42:29 +00003924static int unixDeviceCharacteristics(sqlite3_file *id){
3925 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003926 int rc = 0;
3927#ifdef __QNXNTO__
3928 if( p->sectorSize==0 ) unixSectorSize(id);
3929 rc = p->deviceCharacteristics;
3930#endif
drhcb15f352011-12-23 01:04:17 +00003931 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003932 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003933 }
drh537dddf2012-10-26 13:46:24 +00003934 return rc;
danielk197762079062007-08-15 17:08:46 +00003935}
3936
dan702eec12014-06-23 10:04:58 +00003937#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00003938
dan702eec12014-06-23 10:04:58 +00003939/*
3940** Return the system page size.
3941**
3942** This function should not be called directly by other code in this file.
3943** Instead, it should be called via macro osGetpagesize().
3944*/
3945static int unixGetpagesize(void){
drh8cd5b252015-03-02 22:06:43 +00003946#if OS_VXWORKS
3947 return 1024;
3948#elif defined(_BSD_SOURCE)
dan702eec12014-06-23 10:04:58 +00003949 return getpagesize();
3950#else
3951 return (int)sysconf(_SC_PAGESIZE);
3952#endif
3953}
3954
3955#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
3956
3957#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00003958
3959/*
drhd91c68f2010-05-14 14:52:25 +00003960** Object used to represent an shared memory buffer.
3961**
3962** When multiple threads all reference the same wal-index, each thread
3963** has its own unixShm object, but they all point to a single instance
3964** of this unixShmNode object. In other words, each wal-index is opened
3965** only once per process.
3966**
3967** Each unixShmNode object is connected to a single unixInodeInfo object.
3968** We could coalesce this object into unixInodeInfo, but that would mean
3969** every open file that does not use shared memory (in other words, most
3970** open files) would have to carry around this extra information. So
3971** the unixInodeInfo object contains a pointer to this unixShmNode object
3972** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003973**
3974** unixMutexHeld() must be true when creating or destroying
3975** this object or while reading or writing the following fields:
3976**
3977** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003978**
3979** The following fields are read-only after the object is created:
3980**
3981** fid
3982** zFilename
3983**
drhd91c68f2010-05-14 14:52:25 +00003984** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003985** unixMutexHeld() is true when reading or writing any other field
3986** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003987*/
drhd91c68f2010-05-14 14:52:25 +00003988struct unixShmNode {
3989 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003990 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003991 char *zFilename; /* Name of the mmapped file */
3992 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003993 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003994 u16 nRegion; /* Size of array apRegion */
3995 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003996 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003997 int nRef; /* Number of unixShm objects pointing to this */
3998 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003999#ifdef SQLITE_DEBUG
4000 u8 exclMask; /* Mask of exclusive locks held */
4001 u8 sharedMask; /* Mask of shared locks held */
4002 u8 nextShmId; /* Next available unixShm.id value */
4003#endif
4004};
4005
4006/*
drhd9e5c4f2010-05-12 18:01:39 +00004007** Structure used internally by this VFS to record the state of an
4008** open shared memory connection.
4009**
drhd91c68f2010-05-14 14:52:25 +00004010** The following fields are initialized when this object is created and
4011** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004012**
drhd91c68f2010-05-14 14:52:25 +00004013** unixShm.pFile
4014** unixShm.id
4015**
4016** All other fields are read/write. The unixShm.pFile->mutex must be held
4017** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004018*/
4019struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004020 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4021 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004022 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004023 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004024 u16 sharedMask; /* Mask of shared locks held */
4025 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004026};
4027
4028/*
drhd9e5c4f2010-05-12 18:01:39 +00004029** Constants used for locking
4030*/
drhbd9676c2010-06-23 17:58:38 +00004031#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004032#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004033
drhd9e5c4f2010-05-12 18:01:39 +00004034/*
drh73b64e42010-05-30 19:55:15 +00004035** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004036**
4037** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4038** otherwise.
4039*/
4040static int unixShmSystemLock(
drhbbf76ee2015-03-10 20:22:35 +00004041 unixFile *pFile, /* Open connection to the WAL file */
drhd91c68f2010-05-14 14:52:25 +00004042 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004043 int ofst, /* First byte of the locking range */
4044 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004045){
drhbbf76ee2015-03-10 20:22:35 +00004046 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4047 struct flock f; /* The posix advisory locking structure */
4048 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004049
drhd91c68f2010-05-14 14:52:25 +00004050 /* Access to the unixShmNode object is serialized by the caller */
drhbbf76ee2015-03-10 20:22:35 +00004051 pShmNode = pFile->pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004052 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004053
drh73b64e42010-05-30 19:55:15 +00004054 /* Shared locks never span more than one byte */
4055 assert( n==1 || lockType!=F_RDLCK );
4056
4057 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00004058 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004059
drh3cb93392011-03-12 18:10:44 +00004060 if( pShmNode->h>=0 ){
drhbbf76ee2015-03-10 20:22:35 +00004061 int lkType;
drh3cb93392011-03-12 18:10:44 +00004062 /* Initialize the locking parameters */
4063 memset(&f, 0, sizeof(f));
4064 f.l_type = lockType;
4065 f.l_whence = SEEK_SET;
4066 f.l_start = ofst;
4067 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004068
drhbbf76ee2015-03-10 20:22:35 +00004069 lkType = (pFile->ctrlFlags & UNIXFILE_BLOCK)!=0 ? F_SETLKW : F_SETLK;
4070 rc = osFcntl(pShmNode->h, lkType, &f);
drh3cb93392011-03-12 18:10:44 +00004071 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
drhbbf76ee2015-03-10 20:22:35 +00004072 pFile->ctrlFlags &= ~UNIXFILE_BLOCK;
drh3cb93392011-03-12 18:10:44 +00004073 }
drhd9e5c4f2010-05-12 18:01:39 +00004074
4075 /* Update the global lock state and do debug tracing */
4076#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004077 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004078 OSTRACE(("SHM-LOCK "));
drh693e6712014-01-24 22:58:00 +00004079 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004080 if( rc==SQLITE_OK ){
4081 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004082 OSTRACE(("unlock %d ok", ofst));
4083 pShmNode->exclMask &= ~mask;
4084 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004085 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004086 OSTRACE(("read-lock %d ok", ofst));
4087 pShmNode->exclMask &= ~mask;
4088 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004089 }else{
4090 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004091 OSTRACE(("write-lock %d ok", ofst));
4092 pShmNode->exclMask |= mask;
4093 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004094 }
4095 }else{
4096 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004097 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004098 }else if( lockType==F_RDLCK ){
4099 OSTRACE(("read-lock failed"));
4100 }else{
4101 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004102 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004103 }
4104 }
drh20e1f082010-05-31 16:10:12 +00004105 OSTRACE((" - afterwards %03x,%03x\n",
4106 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004107 }
drhd9e5c4f2010-05-12 18:01:39 +00004108#endif
4109
4110 return rc;
4111}
4112
dan781e34c2014-03-20 08:59:47 +00004113/*
dan781e34c2014-03-20 08:59:47 +00004114** Return the minimum number of 32KB shm regions that should be mapped at
4115** a time, assuming that each mapping must be an integer multiple of the
4116** current system page-size.
4117**
4118** Usually, this is 1. The exception seems to be systems that are configured
4119** to use 64KB pages - in this case each mapping must cover at least two
4120** shm regions.
4121*/
4122static int unixShmRegionPerMap(void){
4123 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004124 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004125 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4126 if( pgsz<shmsz ) return 1;
4127 return pgsz/shmsz;
4128}
drhd9e5c4f2010-05-12 18:01:39 +00004129
4130/*
drhd91c68f2010-05-14 14:52:25 +00004131** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004132**
4133** This is not a VFS shared-memory method; it is a utility function called
4134** by VFS shared-memory methods.
4135*/
drhd91c68f2010-05-14 14:52:25 +00004136static void unixShmPurge(unixFile *pFd){
4137 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004138 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00004139 if( p && p->nRef==0 ){
dan781e34c2014-03-20 08:59:47 +00004140 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004141 int i;
drhd91c68f2010-05-14 14:52:25 +00004142 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004143 sqlite3_mutex_free(p->mutex);
dan781e34c2014-03-20 08:59:47 +00004144 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh3cb93392011-03-12 18:10:44 +00004145 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004146 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004147 }else{
4148 sqlite3_free(p->apRegion[i]);
4149 }
dan13a3cb82010-06-11 19:04:21 +00004150 }
dan18801912010-06-14 14:07:50 +00004151 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004152 if( p->h>=0 ){
4153 robust_close(pFd, p->h, __LINE__);
4154 p->h = -1;
4155 }
drhd91c68f2010-05-14 14:52:25 +00004156 p->pInode->pShmNode = 0;
4157 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004158 }
4159}
4160
4161/*
danda9fe0c2010-07-13 18:44:03 +00004162** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004163** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004164**
drh7234c6d2010-06-19 15:10:09 +00004165** The file used to implement shared-memory is in the same directory
4166** as the open database file and has the same name as the open database
4167** file with the "-shm" suffix added. For example, if the database file
4168** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004169** for shared memory will be called "/home/user1/config.db-shm".
4170**
4171** Another approach to is to use files in /dev/shm or /dev/tmp or an
4172** some other tmpfs mount. But if a file in a different directory
4173** from the database file is used, then differing access permissions
4174** or a chroot() might cause two different processes on the same
4175** database to end up using different files for shared memory -
4176** meaning that their memory would not really be shared - resulting
4177** in database corruption. Nevertheless, this tmpfs file usage
4178** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4179** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4180** option results in an incompatible build of SQLite; builds of SQLite
4181** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4182** same database file at the same time, database corruption will likely
4183** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4184** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004185**
4186** When opening a new shared-memory file, if no other instances of that
4187** file are currently open, in this process or in other processes, then
4188** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004189**
4190** If the original database file (pDbFd) is using the "unix-excl" VFS
4191** that means that an exclusive lock is held on the database file and
4192** that no other processes are able to read or write the database. In
4193** that case, we do not really need shared memory. No shared memory
4194** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004195*/
danda9fe0c2010-07-13 18:44:03 +00004196static int unixOpenSharedMemory(unixFile *pDbFd){
4197 struct unixShm *p = 0; /* The connection to be opened */
4198 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4199 int rc; /* Result code */
4200 unixInodeInfo *pInode; /* The inode of fd */
4201 char *zShmFilename; /* Name of the file used for SHM */
4202 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004203
danda9fe0c2010-07-13 18:44:03 +00004204 /* Allocate space for the new unixShm object. */
drhf3cdcdc2015-04-29 16:50:28 +00004205 p = sqlite3_malloc64( sizeof(*p) );
drhd9e5c4f2010-05-12 18:01:39 +00004206 if( p==0 ) return SQLITE_NOMEM;
4207 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004208 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004209
danda9fe0c2010-07-13 18:44:03 +00004210 /* Check to see if a unixShmNode object already exists. Reuse an existing
4211 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004212 */
4213 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004214 pInode = pDbFd->pInode;
4215 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004216 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004217 struct stat sStat; /* fstat() info for database file */
drh4bf66fd2015-02-19 02:43:02 +00004218#ifndef SQLITE_SHM_DIRECTORY
4219 const char *zBasePath = pDbFd->zPath;
4220#endif
danddb0ac42010-07-14 14:48:58 +00004221
4222 /* Call fstat() to figure out the permissions on the database file. If
4223 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004224 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004225 */
drh3cb93392011-03-12 18:10:44 +00004226 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00004227 rc = SQLITE_IOERR_FSTAT;
4228 goto shm_open_err;
4229 }
4230
drha4ced192010-07-15 18:32:40 +00004231#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004232 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004233#else
drh4bf66fd2015-02-19 02:43:02 +00004234 nShmFilename = 6 + (int)strlen(zBasePath);
drha4ced192010-07-15 18:32:40 +00004235#endif
drhf3cdcdc2015-04-29 16:50:28 +00004236 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004237 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004238 rc = SQLITE_NOMEM;
4239 goto shm_open_err;
4240 }
drh9cb5a0d2012-01-05 21:19:54 +00004241 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004242 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004243#ifdef SQLITE_SHM_DIRECTORY
4244 sqlite3_snprintf(nShmFilename, zShmFilename,
4245 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4246 (u32)sStat.st_ino, (u32)sStat.st_dev);
4247#else
drh4bf66fd2015-02-19 02:43:02 +00004248 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
drh81cc5162011-05-17 20:36:21 +00004249 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004250#endif
drhd91c68f2010-05-14 14:52:25 +00004251 pShmNode->h = -1;
4252 pDbFd->pInode->pShmNode = pShmNode;
4253 pShmNode->pInode = pDbFd->pInode;
4254 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4255 if( pShmNode->mutex==0 ){
4256 rc = SQLITE_NOMEM;
4257 goto shm_open_err;
4258 }
drhd9e5c4f2010-05-12 18:01:39 +00004259
drh3cb93392011-03-12 18:10:44 +00004260 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004261 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004262 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004263 openFlags = O_RDONLY;
4264 pShmNode->isReadonly = 1;
4265 }
4266 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004267 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004268 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4269 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004270 }
drhac7c3ac2012-02-11 19:23:48 +00004271
4272 /* If this process is running as root, make sure that the SHM file
4273 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004274 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004275 */
drh6226ca22015-11-24 15:06:28 +00004276 robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004277
4278 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004279 ** If not, truncate the file to zero length.
4280 */
4281 rc = SQLITE_OK;
drhbbf76ee2015-03-10 20:22:35 +00004282 if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
drh66dfec8b2011-06-01 20:01:49 +00004283 if( robust_ftruncate(pShmNode->h, 0) ){
4284 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004285 }
4286 }
drh66dfec8b2011-06-01 20:01:49 +00004287 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004288 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
drh66dfec8b2011-06-01 20:01:49 +00004289 }
4290 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004291 }
drhd9e5c4f2010-05-12 18:01:39 +00004292 }
4293
drhd91c68f2010-05-14 14:52:25 +00004294 /* Make the new connection a child of the unixShmNode */
4295 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004296#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004297 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004298#endif
drhd91c68f2010-05-14 14:52:25 +00004299 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004300 pDbFd->pShm = p;
4301 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004302
4303 /* The reference count on pShmNode has already been incremented under
4304 ** the cover of the unixEnterMutex() mutex and the pointer from the
4305 ** new (struct unixShm) object to the pShmNode has been set. All that is
4306 ** left to do is to link the new object into the linked list starting
4307 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4308 ** mutex.
4309 */
4310 sqlite3_mutex_enter(pShmNode->mutex);
4311 p->pNext = pShmNode->pFirst;
4312 pShmNode->pFirst = p;
4313 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004314 return SQLITE_OK;
4315
4316 /* Jump here on any error */
4317shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004318 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004319 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004320 unixLeaveMutex();
4321 return rc;
4322}
4323
4324/*
danda9fe0c2010-07-13 18:44:03 +00004325** This function is called to obtain a pointer to region iRegion of the
4326** shared-memory associated with the database file fd. Shared-memory regions
4327** are numbered starting from zero. Each shared-memory region is szRegion
4328** bytes in size.
4329**
4330** If an error occurs, an error code is returned and *pp is set to NULL.
4331**
4332** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4333** region has not been allocated (by any client, including one running in a
4334** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4335** bExtend is non-zero and the requested shared-memory region has not yet
4336** been allocated, it is allocated by this function.
4337**
4338** If the shared-memory region has already been allocated or is allocated by
4339** this call as described above, then it is mapped into this processes
4340** address space (if it is not already), *pp is set to point to the mapped
4341** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004342*/
danda9fe0c2010-07-13 18:44:03 +00004343static int unixShmMap(
4344 sqlite3_file *fd, /* Handle open on database file */
4345 int iRegion, /* Region to retrieve */
4346 int szRegion, /* Size of regions */
4347 int bExtend, /* True to extend file if necessary */
4348 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004349){
danda9fe0c2010-07-13 18:44:03 +00004350 unixFile *pDbFd = (unixFile*)fd;
4351 unixShm *p;
4352 unixShmNode *pShmNode;
4353 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004354 int nShmPerMap = unixShmRegionPerMap();
4355 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004356
danda9fe0c2010-07-13 18:44:03 +00004357 /* If the shared-memory file has not yet been opened, open it now. */
4358 if( pDbFd->pShm==0 ){
4359 rc = unixOpenSharedMemory(pDbFd);
4360 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004361 }
drhd9e5c4f2010-05-12 18:01:39 +00004362
danda9fe0c2010-07-13 18:44:03 +00004363 p = pDbFd->pShm;
4364 pShmNode = p->pShmNode;
4365 sqlite3_mutex_enter(pShmNode->mutex);
4366 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004367 assert( pShmNode->pInode==pDbFd->pInode );
4368 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4369 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004370
dan781e34c2014-03-20 08:59:47 +00004371 /* Minimum number of regions required to be mapped. */
4372 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4373
4374 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004375 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004376 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004377 struct stat sStat; /* Used by fstat() */
4378
4379 pShmNode->szRegion = szRegion;
4380
drh3cb93392011-03-12 18:10:44 +00004381 if( pShmNode->h>=0 ){
4382 /* The requested region is not mapped into this processes address space.
4383 ** Check to see if it has been allocated (i.e. if the wal-index file is
4384 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004385 */
drh3cb93392011-03-12 18:10:44 +00004386 if( osFstat(pShmNode->h, &sStat) ){
4387 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004388 goto shmpage_out;
4389 }
drh3cb93392011-03-12 18:10:44 +00004390
4391 if( sStat.st_size<nByte ){
4392 /* The requested memory region does not exist. If bExtend is set to
4393 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004394 */
dan47a2b4a2013-04-26 16:09:29 +00004395 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004396 goto shmpage_out;
4397 }
dan47a2b4a2013-04-26 16:09:29 +00004398
4399 /* Alternatively, if bExtend is true, extend the file. Do this by
4400 ** writing a single byte to the end of each (OS) page being
4401 ** allocated or extended. Technically, we need only write to the
4402 ** last page in order to extend the file. But writing to all new
4403 ** pages forces the OS to allocate them immediately, which reduces
4404 ** the chances of SIGBUS while accessing the mapped region later on.
4405 */
4406 else{
4407 static const int pgsz = 4096;
4408 int iPg;
4409
4410 /* Write to the last byte of each newly allocated or extended page */
4411 assert( (nByte % pgsz)==0 );
4412 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
4413 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
4414 const char *zFile = pShmNode->zFilename;
4415 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4416 goto shmpage_out;
4417 }
4418 }
drh3cb93392011-03-12 18:10:44 +00004419 }
4420 }
danda9fe0c2010-07-13 18:44:03 +00004421 }
4422
4423 /* Map the requested memory region into this processes address space. */
4424 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004425 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004426 );
4427 if( !apNew ){
4428 rc = SQLITE_IOERR_NOMEM;
4429 goto shmpage_out;
4430 }
4431 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004432 while( pShmNode->nRegion<nReqRegion ){
4433 int nMap = szRegion*nShmPerMap;
4434 int i;
drh3cb93392011-03-12 18:10:44 +00004435 void *pMem;
4436 if( pShmNode->h>=0 ){
dan781e34c2014-03-20 08:59:47 +00004437 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004438 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004439 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004440 );
4441 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004442 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004443 goto shmpage_out;
4444 }
4445 }else{
drhf3cdcdc2015-04-29 16:50:28 +00004446 pMem = sqlite3_malloc64(szRegion);
drh3cb93392011-03-12 18:10:44 +00004447 if( pMem==0 ){
4448 rc = SQLITE_NOMEM;
4449 goto shmpage_out;
4450 }
4451 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004452 }
dan781e34c2014-03-20 08:59:47 +00004453
4454 for(i=0; i<nShmPerMap; i++){
4455 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4456 }
4457 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004458 }
4459 }
4460
4461shmpage_out:
4462 if( pShmNode->nRegion>iRegion ){
4463 *pp = pShmNode->apRegion[iRegion];
4464 }else{
4465 *pp = 0;
4466 }
drh66dfec8b2011-06-01 20:01:49 +00004467 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004468 sqlite3_mutex_leave(pShmNode->mutex);
4469 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004470}
4471
4472/*
drhd9e5c4f2010-05-12 18:01:39 +00004473** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004474**
4475** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4476** different here than in posix. In xShmLock(), one can go from unlocked
4477** to shared and back or from unlocked to exclusive and back. But one may
4478** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004479*/
4480static int unixShmLock(
4481 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004482 int ofst, /* First lock to acquire or release */
4483 int n, /* Number of locks to acquire or release */
4484 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004485){
drh73b64e42010-05-30 19:55:15 +00004486 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4487 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4488 unixShm *pX; /* For looping over all siblings */
4489 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4490 int rc = SQLITE_OK; /* Result code */
4491 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004492
drhd91c68f2010-05-14 14:52:25 +00004493 assert( pShmNode==pDbFd->pInode->pShmNode );
4494 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004495 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004496 assert( n>=1 );
4497 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4498 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4499 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4500 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4501 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004502 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4503 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004504
drhc99597c2010-05-31 01:41:15 +00004505 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004506 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004507 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004508 if( flags & SQLITE_SHM_UNLOCK ){
4509 u16 allMask = 0; /* Mask of locks held by siblings */
4510
4511 /* See if any siblings hold this same lock */
4512 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4513 if( pX==p ) continue;
4514 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4515 allMask |= pX->sharedMask;
4516 }
4517
4518 /* Unlock the system-level locks */
4519 if( (mask & allMask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004520 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004521 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004522 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004523 }
drh73b64e42010-05-30 19:55:15 +00004524
4525 /* Undo the local locks */
4526 if( rc==SQLITE_OK ){
4527 p->exclMask &= ~mask;
4528 p->sharedMask &= ~mask;
4529 }
4530 }else if( flags & SQLITE_SHM_SHARED ){
4531 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4532
4533 /* Find out which shared locks are already held by sibling connections.
4534 ** If any sibling already holds an exclusive lock, go ahead and return
4535 ** SQLITE_BUSY.
4536 */
4537 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004538 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004539 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004540 break;
4541 }
4542 allShared |= pX->sharedMask;
4543 }
4544
4545 /* Get shared locks at the system level, if necessary */
4546 if( rc==SQLITE_OK ){
4547 if( (allShared & mask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004548 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004549 }else{
drh73b64e42010-05-30 19:55:15 +00004550 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004551 }
drhd9e5c4f2010-05-12 18:01:39 +00004552 }
drh73b64e42010-05-30 19:55:15 +00004553
4554 /* Get the local shared locks */
4555 if( rc==SQLITE_OK ){
4556 p->sharedMask |= mask;
4557 }
4558 }else{
4559 /* Make sure no sibling connections hold locks that will block this
4560 ** lock. If any do, return SQLITE_BUSY right away.
4561 */
4562 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004563 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4564 rc = SQLITE_BUSY;
4565 break;
4566 }
4567 }
4568
4569 /* Get the exclusive locks at the system level. Then if successful
4570 ** also mark the local connection as being locked.
4571 */
4572 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004573 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004574 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004575 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004576 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004577 }
drhd9e5c4f2010-05-12 18:01:39 +00004578 }
4579 }
drhd91c68f2010-05-14 14:52:25 +00004580 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004581 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
drh5ac93652015-03-21 20:59:43 +00004582 p->id, osGetpid(0), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004583 return rc;
4584}
4585
drh286a2882010-05-20 23:51:06 +00004586/*
4587** Implement a memory barrier or memory fence on shared memory.
4588**
4589** All loads and stores begun before the barrier must complete before
4590** any load or store begun after the barrier.
4591*/
4592static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004593 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004594){
drhff828942010-06-26 21:34:06 +00004595 UNUSED_PARAMETER(fd);
drh22c733d2015-09-24 12:40:43 +00004596 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
4597 unixEnterMutex(); /* Also mutex, for redundancy */
drhb29ad852010-06-01 00:03:57 +00004598 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004599}
4600
dan18801912010-06-14 14:07:50 +00004601/*
danda9fe0c2010-07-13 18:44:03 +00004602** Close a connection to shared-memory. Delete the underlying
4603** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004604**
4605** If there is no shared memory associated with the connection then this
4606** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004607*/
danda9fe0c2010-07-13 18:44:03 +00004608static int unixShmUnmap(
4609 sqlite3_file *fd, /* The underlying database file */
4610 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004611){
danda9fe0c2010-07-13 18:44:03 +00004612 unixShm *p; /* The connection to be closed */
4613 unixShmNode *pShmNode; /* The underlying shared-memory file */
4614 unixShm **pp; /* For looping over sibling connections */
4615 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004616
danda9fe0c2010-07-13 18:44:03 +00004617 pDbFd = (unixFile*)fd;
4618 p = pDbFd->pShm;
4619 if( p==0 ) return SQLITE_OK;
4620 pShmNode = p->pShmNode;
4621
4622 assert( pShmNode==pDbFd->pInode->pShmNode );
4623 assert( pShmNode->pInode==pDbFd->pInode );
4624
4625 /* Remove connection p from the set of connections associated
4626 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004627 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004628 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4629 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004630
danda9fe0c2010-07-13 18:44:03 +00004631 /* Free the connection p */
4632 sqlite3_free(p);
4633 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004634 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004635
4636 /* If pShmNode->nRef has reached 0, then close the underlying
4637 ** shared-memory file, too */
4638 unixEnterMutex();
4639 assert( pShmNode->nRef>0 );
4640 pShmNode->nRef--;
4641 if( pShmNode->nRef==0 ){
drh4bf66fd2015-02-19 02:43:02 +00004642 if( deleteFlag && pShmNode->h>=0 ){
4643 osUnlink(pShmNode->zFilename);
4644 }
danda9fe0c2010-07-13 18:44:03 +00004645 unixShmPurge(pDbFd);
4646 }
4647 unixLeaveMutex();
4648
4649 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004650}
drh286a2882010-05-20 23:51:06 +00004651
danda9fe0c2010-07-13 18:44:03 +00004652
drhd9e5c4f2010-05-12 18:01:39 +00004653#else
drh6b017cc2010-06-14 18:01:46 +00004654# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004655# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004656# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004657# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004658#endif /* #ifndef SQLITE_OMIT_WAL */
4659
mistachkine98844f2013-08-24 00:59:24 +00004660#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004661/*
danaef49d72013-03-25 16:28:54 +00004662** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004663*/
danf23da962013-03-23 21:00:41 +00004664static void unixUnmapfile(unixFile *pFd){
4665 assert( pFd->nFetchOut==0 );
4666 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004667 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004668 pFd->pMapRegion = 0;
4669 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004670 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004671 }
4672}
dan5d8a1372013-03-19 19:28:06 +00004673
danaef49d72013-03-25 16:28:54 +00004674/*
dane6ecd662013-04-01 17:56:59 +00004675** Attempt to set the size of the memory mapping maintained by file
4676** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4677**
4678** If successful, this function sets the following variables:
4679**
4680** unixFile.pMapRegion
4681** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004682** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004683**
4684** If unsuccessful, an error message is logged via sqlite3_log() and
4685** the three variables above are zeroed. In this case SQLite should
4686** continue accessing the database using the xRead() and xWrite()
4687** methods.
4688*/
4689static void unixRemapfile(
4690 unixFile *pFd, /* File descriptor object */
4691 i64 nNew /* Required mapping size */
4692){
dan4ff7bc42013-04-02 12:04:09 +00004693 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004694 int h = pFd->h; /* File descriptor open on db file */
4695 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004696 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004697 u8 *pNew = 0; /* Location of new mapping */
4698 int flags = PROT_READ; /* Flags to pass to mmap() */
4699
4700 assert( pFd->nFetchOut==0 );
4701 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004702 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004703 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004704 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004705 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004706
danfe33e392015-11-17 20:56:06 +00004707#ifdef SQLITE_MMAP_READWRITE
dane6ecd662013-04-01 17:56:59 +00004708 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
danfe33e392015-11-17 20:56:06 +00004709#endif
dane6ecd662013-04-01 17:56:59 +00004710
4711 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00004712#if HAVE_MREMAP
4713 i64 nReuse = pFd->mmapSize;
4714#else
danbc760632014-03-20 09:42:09 +00004715 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00004716 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00004717#endif
dane6ecd662013-04-01 17:56:59 +00004718 u8 *pReq = &pOrig[nReuse];
4719
4720 /* Unmap any pages of the existing mapping that cannot be reused. */
4721 if( nReuse!=nOrig ){
4722 osMunmap(pReq, nOrig-nReuse);
4723 }
4724
4725#if HAVE_MREMAP
4726 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004727 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004728#else
4729 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4730 if( pNew!=MAP_FAILED ){
4731 if( pNew!=pReq ){
4732 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004733 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004734 }else{
4735 pNew = pOrig;
4736 }
4737 }
4738#endif
4739
dan48ccef82013-04-02 20:55:01 +00004740 /* The attempt to extend the existing mapping failed. Free it. */
4741 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004742 osMunmap(pOrig, nReuse);
4743 }
4744 }
4745
4746 /* If pNew is still NULL, try to create an entirely new mapping. */
4747 if( pNew==0 ){
4748 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004749 }
4750
dan4ff7bc42013-04-02 12:04:09 +00004751 if( pNew==MAP_FAILED ){
4752 pNew = 0;
4753 nNew = 0;
4754 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4755
4756 /* If the mmap() above failed, assume that all subsequent mmap() calls
4757 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4758 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004759 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004760 }
dane6ecd662013-04-01 17:56:59 +00004761 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004762 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004763}
4764
4765/*
danaef49d72013-03-25 16:28:54 +00004766** Memory map or remap the file opened by file-descriptor pFd (if the file
4767** is already mapped, the existing mapping is replaced by the new). Or, if
4768** there already exists a mapping for this file, and there are still
4769** outstanding xFetch() references to it, this function is a no-op.
4770**
4771** If parameter nByte is non-negative, then it is the requested size of
4772** the mapping to create. Otherwise, if nByte is less than zero, then the
4773** requested size is the size of the file on disk. The actual size of the
4774** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004775** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004776**
4777** SQLITE_OK is returned if no error occurs (even if the mapping is not
4778** recreated as a result of outstanding references) or an SQLite error
4779** code otherwise.
4780*/
danf23da962013-03-23 21:00:41 +00004781static int unixMapfile(unixFile *pFd, i64 nByte){
4782 i64 nMap = nByte;
4783 int rc;
daneb97b292013-03-20 14:26:59 +00004784
danf23da962013-03-23 21:00:41 +00004785 assert( nMap>=0 || pFd->nFetchOut==0 );
4786 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4787
4788 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00004789 struct stat statbuf; /* Low-level file information */
4790 rc = osFstat(pFd->h, &statbuf);
danf23da962013-03-23 21:00:41 +00004791 if( rc!=SQLITE_OK ){
4792 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004793 }
drh3044b512014-06-16 16:41:52 +00004794 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00004795 }
drh9b4c59f2013-04-15 17:03:42 +00004796 if( nMap>pFd->mmapSizeMax ){
4797 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004798 }
4799
danf23da962013-03-23 21:00:41 +00004800 if( nMap!=pFd->mmapSize ){
dane6ecd662013-04-01 17:56:59 +00004801 if( nMap>0 ){
4802 unixRemapfile(pFd, nMap);
4803 }else{
danb7e3a322013-03-25 20:30:13 +00004804 unixUnmapfile(pFd);
dan5d8a1372013-03-19 19:28:06 +00004805 }
4806 }
4807
danf23da962013-03-23 21:00:41 +00004808 return SQLITE_OK;
4809}
mistachkine98844f2013-08-24 00:59:24 +00004810#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004811
danaef49d72013-03-25 16:28:54 +00004812/*
4813** If possible, return a pointer to a mapping of file fd starting at offset
4814** iOff. The mapping must be valid for at least nAmt bytes.
4815**
4816** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4817** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4818** Finally, if an error does occur, return an SQLite error code. The final
4819** value of *pp is undefined in this case.
4820**
4821** If this function does return a pointer, the caller must eventually
4822** release the reference by calling unixUnfetch().
4823*/
danf23da962013-03-23 21:00:41 +00004824static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004825#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004826 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004827#endif
danf23da962013-03-23 21:00:41 +00004828 *pp = 0;
4829
drh9b4c59f2013-04-15 17:03:42 +00004830#if SQLITE_MAX_MMAP_SIZE>0
4831 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004832 if( pFd->pMapRegion==0 ){
4833 int rc = unixMapfile(pFd, -1);
4834 if( rc!=SQLITE_OK ) return rc;
4835 }
4836 if( pFd->mmapSize >= iOff+nAmt ){
4837 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4838 pFd->nFetchOut++;
4839 }
4840 }
drh6e0b6d52013-04-09 16:19:20 +00004841#endif
danf23da962013-03-23 21:00:41 +00004842 return SQLITE_OK;
4843}
4844
danaef49d72013-03-25 16:28:54 +00004845/*
dandf737fe2013-03-25 17:00:24 +00004846** If the third argument is non-NULL, then this function releases a
4847** reference obtained by an earlier call to unixFetch(). The second
4848** argument passed to this function must be the same as the corresponding
4849** argument that was passed to the unixFetch() invocation.
4850**
4851** Or, if the third argument is NULL, then this function is being called
4852** to inform the VFS layer that, according to POSIX, any existing mapping
4853** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004854*/
dandf737fe2013-03-25 17:00:24 +00004855static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00004856#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00004857 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00004858 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00004859
danaef49d72013-03-25 16:28:54 +00004860 /* If p==0 (unmap the entire file) then there must be no outstanding
4861 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4862 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004863 assert( (p==0)==(pFd->nFetchOut==0) );
4864
dandf737fe2013-03-25 17:00:24 +00004865 /* If p!=0, it must match the iOff value. */
4866 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4867
danf23da962013-03-23 21:00:41 +00004868 if( p ){
4869 pFd->nFetchOut--;
4870 }else{
4871 unixUnmapfile(pFd);
4872 }
4873
4874 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00004875#else
4876 UNUSED_PARAMETER(fd);
4877 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00004878 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00004879#endif
danf23da962013-03-23 21:00:41 +00004880 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004881}
4882
4883/*
drh734c9862008-11-28 15:37:20 +00004884** Here ends the implementation of all sqlite3_file methods.
4885**
4886********************** End sqlite3_file Methods *******************************
4887******************************************************************************/
4888
4889/*
drh6b9d6dd2008-12-03 19:34:47 +00004890** This division contains definitions of sqlite3_io_methods objects that
4891** implement various file locking strategies. It also contains definitions
4892** of "finder" functions. A finder-function is used to locate the appropriate
4893** sqlite3_io_methods object for a particular database file. The pAppData
4894** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4895** the correct finder-function for that VFS.
4896**
4897** Most finder functions return a pointer to a fixed sqlite3_io_methods
4898** object. The only interesting finder-function is autolockIoFinder, which
4899** looks at the filesystem type and tries to guess the best locking
4900** strategy from that.
4901**
peter.d.reid60ec9142014-09-06 16:39:46 +00004902** For finder-function F, two objects are created:
drh1875f7a2008-12-08 18:19:17 +00004903**
4904** (1) The real finder-function named "FImpt()".
4905**
dane946c392009-08-22 11:39:46 +00004906** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004907**
4908**
4909** A pointer to the F pointer is used as the pAppData value for VFS
4910** objects. We have to do this instead of letting pAppData point
4911** directly at the finder-function since C90 rules prevent a void*
4912** from be cast into a function pointer.
4913**
drh6b9d6dd2008-12-03 19:34:47 +00004914**
drh7708e972008-11-29 00:56:52 +00004915** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004916**
drh7708e972008-11-29 00:56:52 +00004917** * A constant sqlite3_io_methods object call METHOD that has locking
4918** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4919**
4920** * An I/O method finder function called FINDER that returns a pointer
4921** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004922*/
drhe6d41732015-02-21 00:49:00 +00004923#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
drh7708e972008-11-29 00:56:52 +00004924static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004925 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004926 CLOSE, /* xClose */ \
4927 unixRead, /* xRead */ \
4928 unixWrite, /* xWrite */ \
4929 unixTruncate, /* xTruncate */ \
4930 unixSync, /* xSync */ \
4931 unixFileSize, /* xFileSize */ \
4932 LOCK, /* xLock */ \
4933 UNLOCK, /* xUnlock */ \
4934 CKLOCK, /* xCheckReservedLock */ \
4935 unixFileControl, /* xFileControl */ \
4936 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004937 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drhd9f94412014-09-22 03:22:27 +00004938 SHMMAP, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004939 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004940 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00004941 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00004942 unixFetch, /* xFetch */ \
4943 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00004944}; \
drh0c2694b2009-09-03 16:23:44 +00004945static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4946 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004947 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004948} \
drh0c2694b2009-09-03 16:23:44 +00004949static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004950 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004951
4952/*
4953** Here are all of the sqlite3_io_methods objects for each of the
4954** locking strategies. Functions that return pointers to these methods
4955** are also created.
4956*/
4957IOMETHODS(
4958 posixIoFinder, /* Finder function name */
4959 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00004960 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00004961 unixClose, /* xClose method */
4962 unixLock, /* xLock method */
4963 unixUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004964 unixCheckReservedLock, /* xCheckReservedLock method */
4965 unixShmMap /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004966)
drh7708e972008-11-29 00:56:52 +00004967IOMETHODS(
4968 nolockIoFinder, /* Finder function name */
4969 nolockIoMethods, /* sqlite3_io_methods object name */
drh142341c2014-09-19 19:00:48 +00004970 3, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004971 nolockClose, /* xClose method */
4972 nolockLock, /* xLock method */
4973 nolockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004974 nolockCheckReservedLock, /* xCheckReservedLock method */
4975 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004976)
drh7708e972008-11-29 00:56:52 +00004977IOMETHODS(
4978 dotlockIoFinder, /* Finder function name */
4979 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004980 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004981 dotlockClose, /* xClose method */
4982 dotlockLock, /* xLock method */
4983 dotlockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004984 dotlockCheckReservedLock, /* xCheckReservedLock method */
4985 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004986)
drh7708e972008-11-29 00:56:52 +00004987
drhe89b2912015-03-03 20:42:01 +00004988#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004989IOMETHODS(
4990 flockIoFinder, /* Finder function name */
4991 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004992 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004993 flockClose, /* xClose method */
4994 flockLock, /* xLock method */
4995 flockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004996 flockCheckReservedLock, /* xCheckReservedLock method */
4997 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004998)
drh7708e972008-11-29 00:56:52 +00004999#endif
5000
drh6c7d5c52008-11-21 20:32:33 +00005001#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005002IOMETHODS(
5003 semIoFinder, /* Finder function name */
5004 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005005 1, /* shared memory is disabled */
drh8cd5b252015-03-02 22:06:43 +00005006 semXClose, /* xClose method */
5007 semXLock, /* xLock method */
5008 semXUnlock, /* xUnlock method */
5009 semXCheckReservedLock, /* xCheckReservedLock method */
drhd9f94412014-09-22 03:22:27 +00005010 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005011)
aswiftaebf4132008-11-21 00:10:35 +00005012#endif
drh7708e972008-11-29 00:56:52 +00005013
drhd2cb50b2009-01-09 21:41:17 +00005014#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005015IOMETHODS(
5016 afpIoFinder, /* Finder function name */
5017 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005018 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005019 afpClose, /* xClose method */
5020 afpLock, /* xLock method */
5021 afpUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005022 afpCheckReservedLock, /* xCheckReservedLock method */
5023 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005024)
drh715ff302008-12-03 22:32:44 +00005025#endif
5026
5027/*
5028** The proxy locking method is a "super-method" in the sense that it
5029** opens secondary file descriptors for the conch and lock files and
5030** it uses proxy, dot-file, AFP, and flock() locking methods on those
5031** secondary files. For this reason, the division that implements
5032** proxy locking is located much further down in the file. But we need
5033** to go ahead and define the sqlite3_io_methods and finder function
5034** for proxy locking here. So we forward declare the I/O methods.
5035*/
drhd2cb50b2009-01-09 21:41:17 +00005036#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005037static int proxyClose(sqlite3_file*);
5038static int proxyLock(sqlite3_file*, int);
5039static int proxyUnlock(sqlite3_file*, int);
5040static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005041IOMETHODS(
5042 proxyIoFinder, /* Finder function name */
5043 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005044 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005045 proxyClose, /* xClose method */
5046 proxyLock, /* xLock method */
5047 proxyUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005048 proxyCheckReservedLock, /* xCheckReservedLock method */
5049 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005050)
aswiftaebf4132008-11-21 00:10:35 +00005051#endif
drh7708e972008-11-29 00:56:52 +00005052
drh7ed97b92010-01-20 13:07:21 +00005053/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5054#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5055IOMETHODS(
5056 nfsIoFinder, /* Finder function name */
5057 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005058 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005059 unixClose, /* xClose method */
5060 unixLock, /* xLock method */
5061 nfsUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005062 unixCheckReservedLock, /* xCheckReservedLock method */
5063 0 /* xShmMap method */
drh7ed97b92010-01-20 13:07:21 +00005064)
5065#endif
drh7708e972008-11-29 00:56:52 +00005066
drhd2cb50b2009-01-09 21:41:17 +00005067#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005068/*
drh6b9d6dd2008-12-03 19:34:47 +00005069** This "finder" function attempts to determine the best locking strategy
5070** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005071** object that implements that strategy.
5072**
5073** This is for MacOSX only.
5074*/
drh1875f7a2008-12-08 18:19:17 +00005075static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005076 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005077 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005078){
5079 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005080 const char *zFilesystem; /* Filesystem type name */
5081 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005082 } aMap[] = {
5083 { "hfs", &posixIoMethods },
5084 { "ufs", &posixIoMethods },
5085 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005086 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005087 { "webdav", &nolockIoMethods },
5088 { 0, 0 }
5089 };
5090 int i;
5091 struct statfs fsInfo;
5092 struct flock lockInfo;
5093
5094 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005095 /* If filePath==NULL that means we are dealing with a transient file
5096 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005097 return &nolockIoMethods;
5098 }
5099 if( statfs(filePath, &fsInfo) != -1 ){
5100 if( fsInfo.f_flags & MNT_RDONLY ){
5101 return &nolockIoMethods;
5102 }
5103 for(i=0; aMap[i].zFilesystem; i++){
5104 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5105 return aMap[i].pMethods;
5106 }
5107 }
5108 }
5109
5110 /* Default case. Handles, amongst others, "nfs".
5111 ** Test byte-range lock using fcntl(). If the call succeeds,
5112 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005113 */
drh7708e972008-11-29 00:56:52 +00005114 lockInfo.l_len = 1;
5115 lockInfo.l_start = 0;
5116 lockInfo.l_whence = SEEK_SET;
5117 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005118 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005119 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5120 return &nfsIoMethods;
5121 } else {
5122 return &posixIoMethods;
5123 }
drh7708e972008-11-29 00:56:52 +00005124 }else{
5125 return &dotlockIoMethods;
5126 }
5127}
drh0c2694b2009-09-03 16:23:44 +00005128static const sqlite3_io_methods
5129 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005130
drhd2cb50b2009-01-09 21:41:17 +00005131#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005132
drhe89b2912015-03-03 20:42:01 +00005133#if OS_VXWORKS
5134/*
5135** This "finder" function for VxWorks checks to see if posix advisory
5136** locking works. If it does, then that is what is used. If it does not
5137** work, then fallback to named semaphore locking.
chw78a13182009-04-07 05:35:03 +00005138*/
drhe89b2912015-03-03 20:42:01 +00005139static const sqlite3_io_methods *vxworksIoFinderImpl(
chw78a13182009-04-07 05:35:03 +00005140 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005141 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005142){
5143 struct flock lockInfo;
5144
5145 if( !filePath ){
5146 /* If filePath==NULL that means we are dealing with a transient file
5147 ** that does not need to be locked. */
5148 return &nolockIoMethods;
5149 }
5150
5151 /* Test if fcntl() is supported and use POSIX style locks.
5152 ** Otherwise fall back to the named semaphore method.
5153 */
5154 lockInfo.l_len = 1;
5155 lockInfo.l_start = 0;
5156 lockInfo.l_whence = SEEK_SET;
5157 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005158 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005159 return &posixIoMethods;
5160 }else{
5161 return &semIoMethods;
5162 }
5163}
drh0c2694b2009-09-03 16:23:44 +00005164static const sqlite3_io_methods
drhe89b2912015-03-03 20:42:01 +00005165 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005166
drhe89b2912015-03-03 20:42:01 +00005167#endif /* OS_VXWORKS */
chw78a13182009-04-07 05:35:03 +00005168
drh7708e972008-11-29 00:56:52 +00005169/*
peter.d.reid60ec9142014-09-06 16:39:46 +00005170** An abstract type for a pointer to an IO method finder function:
drh7708e972008-11-29 00:56:52 +00005171*/
drh0c2694b2009-09-03 16:23:44 +00005172typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005173
aswiftaebf4132008-11-21 00:10:35 +00005174
drh734c9862008-11-28 15:37:20 +00005175/****************************************************************************
5176**************************** sqlite3_vfs methods ****************************
5177**
5178** This division contains the implementation of methods on the
5179** sqlite3_vfs object.
5180*/
5181
danielk1977a3d4c882007-03-23 10:08:38 +00005182/*
danielk1977e339d652008-06-28 11:23:00 +00005183** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005184*/
5185static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005186 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005187 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005188 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005189 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005190 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005191){
drh7708e972008-11-29 00:56:52 +00005192 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005193 unixFile *pNew = (unixFile *)pId;
5194 int rc = SQLITE_OK;
5195
drh8af6c222010-05-14 12:43:01 +00005196 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005197
dan00157392010-10-05 11:33:15 +00005198 /* Usually the path zFilename should not be a relative pathname. The
5199 ** exception is when opening the proxy "conch" file in builds that
5200 ** include the special Apple locking styles.
5201 */
dan00157392010-10-05 11:33:15 +00005202#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005203 assert( zFilename==0 || zFilename[0]=='/'
5204 || pVfs->pAppData==(void*)&autolockIoFinder );
5205#else
5206 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005207#endif
dan00157392010-10-05 11:33:15 +00005208
drhb07028f2011-10-14 21:49:18 +00005209 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005210 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005211
drh308c2a52010-05-14 11:30:18 +00005212 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005213 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005214 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005215 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005216 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005217#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005218 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005219#endif
drhc02a43a2012-01-10 23:18:38 +00005220 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5221 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005222 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005223 }
drh503a6862013-03-01 01:07:17 +00005224 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005225 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005226 }
drh339eb0b2008-03-07 15:34:11 +00005227
drh6c7d5c52008-11-21 20:32:33 +00005228#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005229 pNew->pId = vxworksFindFileId(zFilename);
5230 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005231 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00005232 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00005233 }
5234#endif
5235
drhc02a43a2012-01-10 23:18:38 +00005236 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005237 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005238 }else{
drh0c2694b2009-09-03 16:23:44 +00005239 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005240#if SQLITE_ENABLE_LOCKING_STYLE
5241 /* Cache zFilename in the locking context (AFP and dotlock override) for
5242 ** proxyLock activation is possible (remote proxy is based on db name)
5243 ** zFilename remains valid until file is closed, to support */
5244 pNew->lockingContext = (void*)zFilename;
5245#endif
drhda0e7682008-07-30 15:27:54 +00005246 }
danielk1977e339d652008-06-28 11:23:00 +00005247
drh7ed97b92010-01-20 13:07:21 +00005248 if( pLockingStyle == &posixIoMethods
5249#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5250 || pLockingStyle == &nfsIoMethods
5251#endif
5252 ){
drh7708e972008-11-29 00:56:52 +00005253 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005254 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005255 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005256 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005257 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005258 ** in two scenarios:
5259 **
5260 ** (a) A call to fstat() failed.
5261 ** (b) A malloc failed.
5262 **
5263 ** Scenario (b) may only occur if the process is holding no other
5264 ** file descriptors open on the same file. If there were other file
5265 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005266 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005267 ** handle h - as it is guaranteed that no posix locks will be released
5268 ** by doing so.
5269 **
5270 ** If scenario (a) caused the error then things are not so safe. The
5271 ** implicit assumption here is that if fstat() fails, things are in
5272 ** such bad shape that dropping a lock or two doesn't matter much.
5273 */
drh0e9365c2011-03-02 02:08:13 +00005274 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005275 h = -1;
5276 }
drh7708e972008-11-29 00:56:52 +00005277 unixLeaveMutex();
5278 }
danielk1977e339d652008-06-28 11:23:00 +00005279
drhd2cb50b2009-01-09 21:41:17 +00005280#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005281 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005282 /* AFP locking uses the file path so it needs to be included in
5283 ** the afpLockingContext.
5284 */
5285 afpLockingContext *pCtx;
drhf3cdcdc2015-04-29 16:50:28 +00005286 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh7708e972008-11-29 00:56:52 +00005287 if( pCtx==0 ){
5288 rc = SQLITE_NOMEM;
5289 }else{
5290 /* NB: zFilename exists and remains valid until the file is closed
5291 ** according to requirement F11141. So we do not need to make a
5292 ** copy of the filename. */
5293 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005294 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005295 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005296 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005297 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005298 if( rc!=SQLITE_OK ){
5299 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005300 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005301 h = -1;
5302 }
drh7708e972008-11-29 00:56:52 +00005303 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005304 }
drh7708e972008-11-29 00:56:52 +00005305 }
5306#endif
danielk1977e339d652008-06-28 11:23:00 +00005307
drh7708e972008-11-29 00:56:52 +00005308 else if( pLockingStyle == &dotlockIoMethods ){
5309 /* Dotfile locking uses the file path so it needs to be included in
5310 ** the dotlockLockingContext
5311 */
5312 char *zLockFile;
5313 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005314 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005315 nFilename = (int)strlen(zFilename) + 6;
drhf3cdcdc2015-04-29 16:50:28 +00005316 zLockFile = (char *)sqlite3_malloc64(nFilename);
drh7708e972008-11-29 00:56:52 +00005317 if( zLockFile==0 ){
5318 rc = SQLITE_NOMEM;
5319 }else{
5320 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005321 }
drh7708e972008-11-29 00:56:52 +00005322 pNew->lockingContext = zLockFile;
5323 }
danielk1977e339d652008-06-28 11:23:00 +00005324
drh6c7d5c52008-11-21 20:32:33 +00005325#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005326 else if( pLockingStyle == &semIoMethods ){
5327 /* Named semaphore locking uses the file path so it needs to be
5328 ** included in the semLockingContext
5329 */
5330 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005331 rc = findInodeInfo(pNew, &pNew->pInode);
5332 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5333 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005334 int n;
drh2238dcc2009-08-27 17:56:20 +00005335 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005336 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005337 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005338 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005339 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5340 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00005341 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00005342 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005343 }
chw97185482008-11-17 08:05:31 +00005344 }
drh7708e972008-11-29 00:56:52 +00005345 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005346 }
drh7708e972008-11-29 00:56:52 +00005347#endif
aswift5b1a2562008-08-22 00:22:35 +00005348
drh4bf66fd2015-02-19 02:43:02 +00005349 storeLastErrno(pNew, 0);
drh6c7d5c52008-11-21 20:32:33 +00005350#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005351 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005352 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005353 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005354 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005355 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005356 }
chw97185482008-11-17 08:05:31 +00005357#endif
danielk1977e339d652008-06-28 11:23:00 +00005358 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005359 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005360 }else{
drh7708e972008-11-29 00:56:52 +00005361 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005362 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005363 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005364 }
danielk1977e339d652008-06-28 11:23:00 +00005365 return rc;
drh054889e2005-11-30 03:20:31 +00005366}
drh9c06c952005-11-26 00:25:00 +00005367
danielk1977ad94b582007-08-20 06:44:22 +00005368/*
drh8b3cf822010-06-01 21:02:51 +00005369** Return the name of a directory in which to put temporary files.
5370** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005371*/
drh7234c6d2010-06-19 15:10:09 +00005372static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005373 static const char *azDirs[] = {
5374 0,
aswiftaebf4132008-11-21 00:10:35 +00005375 0,
danielk197717b90b52008-06-06 11:11:25 +00005376 "/var/tmp",
5377 "/usr/tmp",
5378 "/tmp",
drhb7e50ad2015-11-28 21:49:53 +00005379 "."
danielk197717b90b52008-06-06 11:11:25 +00005380 };
drh8b3cf822010-06-01 21:02:51 +00005381 unsigned int i;
5382 struct stat buf;
drhb7e50ad2015-11-28 21:49:53 +00005383 const char *zDir = sqlite3_temp_directory;
drh8b3cf822010-06-01 21:02:51 +00005384
drhb7e50ad2015-11-28 21:49:53 +00005385 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
5386 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005387 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005388 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005389 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005390 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005391 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005392 break;
5393 }
5394 return zDir;
5395}
5396
5397/*
5398** Create a temporary file name in zBuf. zBuf must be allocated
5399** by the calling process and must be big enough to hold at least
5400** pVfs->mxPathname bytes.
5401*/
5402static int unixGetTempname(int nBuf, char *zBuf){
drh8b3cf822010-06-01 21:02:51 +00005403 const char *zDir;
drhb7e50ad2015-11-28 21:49:53 +00005404 int iLimit = 0;
danielk197717b90b52008-06-06 11:11:25 +00005405
5406 /* It's odd to simulate an io-error here, but really this is just
5407 ** using the io-error infrastructure to test that SQLite handles this
5408 ** function failing.
5409 */
5410 SimulateIOError( return SQLITE_IOERR );
5411
drh7234c6d2010-06-19 15:10:09 +00005412 zDir = unixTempFileDir();
danielk197717b90b52008-06-06 11:11:25 +00005413 do{
drh970942e2015-11-25 23:13:14 +00005414 u64 r;
5415 sqlite3_randomness(sizeof(r), &r);
5416 assert( nBuf>2 );
5417 zBuf[nBuf-2] = 0;
5418 sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
5419 zDir, r, 0);
drhb7e50ad2015-11-28 21:49:53 +00005420 if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
drh99ab3b12011-03-02 15:09:07 +00005421 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005422 return SQLITE_OK;
5423}
5424
drhd2cb50b2009-01-09 21:41:17 +00005425#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005426/*
5427** Routine to transform a unixFile into a proxy-locking unixFile.
5428** Implementation in the proxy-lock division, but used by unixOpen()
5429** if SQLITE_PREFER_PROXY_LOCKING is defined.
5430*/
5431static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005432#endif
drhc66d5b62008-12-03 22:48:32 +00005433
dan08da86a2009-08-21 17:18:03 +00005434/*
5435** Search for an unused file descriptor that was opened on the database
5436** file (not a journal or master-journal file) identified by pathname
5437** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5438** argument to this function.
5439**
5440** Such a file descriptor may exist if a database connection was closed
5441** but the associated file descriptor could not be closed because some
5442** other file descriptor open on the same file is holding a file-lock.
5443** Refer to comments in the unixClose() function and the lengthy comment
5444** describing "Posix Advisory Locking" at the start of this file for
5445** further details. Also, ticket #4018.
5446**
5447** If a suitable file descriptor is found, then it is returned. If no
5448** such file descriptor is located, -1 is returned.
5449*/
dane946c392009-08-22 11:39:46 +00005450static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5451 UnixUnusedFd *pUnused = 0;
5452
5453 /* Do not search for an unused file descriptor on vxworks. Not because
5454 ** vxworks would not benefit from the change (it might, we're not sure),
5455 ** but because no way to test it is currently available. It is better
5456 ** not to risk breaking vxworks support for the sake of such an obscure
5457 ** feature. */
5458#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005459 struct stat sStat; /* Results of stat() call */
5460
5461 /* A stat() call may fail for various reasons. If this happens, it is
5462 ** almost certain that an open() call on the same path will also fail.
5463 ** For this reason, if an error occurs in the stat() call here, it is
5464 ** ignored and -1 is returned. The caller will try to open a new file
5465 ** descriptor on the same path, fail, and return an error to SQLite.
5466 **
5467 ** Even if a subsequent open() call does succeed, the consequences of
peter.d.reid60ec9142014-09-06 16:39:46 +00005468 ** not searching for a reusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005469 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005470 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005471
5472 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005473 pInode = inodeList;
5474 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5475 || pInode->fileId.ino!=sStat.st_ino) ){
5476 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005477 }
drh8af6c222010-05-14 12:43:01 +00005478 if( pInode ){
dane946c392009-08-22 11:39:46 +00005479 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005480 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005481 pUnused = *pp;
5482 if( pUnused ){
5483 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005484 }
5485 }
5486 unixLeaveMutex();
5487 }
dane946c392009-08-22 11:39:46 +00005488#endif /* if !OS_VXWORKS */
5489 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005490}
danielk197717b90b52008-06-06 11:11:25 +00005491
5492/*
danddb0ac42010-07-14 14:48:58 +00005493** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005494** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005495** and a value suitable for passing as the third argument to open(2) is
5496** written to *pMode. If an IO error occurs, an SQLite error code is
5497** returned and the value of *pMode is not modified.
5498**
peter.d.reid60ec9142014-09-06 16:39:46 +00005499** In most cases, this routine sets *pMode to 0, which will become
drh8c815d12012-02-13 20:16:37 +00005500** an indication to robust_open() to create the file using
5501** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5502** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005503** this function queries the file-system for the permissions on the
5504** corresponding database file and sets *pMode to this value. Whenever
5505** possible, WAL and journal files are created using the same permissions
5506** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005507**
5508** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5509** original filename is unavailable. But 8_3_NAMES is only used for
5510** FAT filesystems and permissions do not matter there, so just use
5511** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005512*/
5513static int findCreateFileMode(
5514 const char *zPath, /* Path of file (possibly) being created */
5515 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005516 mode_t *pMode, /* OUT: Permissions to open file with */
5517 uid_t *pUid, /* OUT: uid to set on the file */
5518 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005519){
5520 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005521 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005522 *pUid = 0;
5523 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005524 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005525 char zDb[MAX_PATHNAME+1]; /* Database file path */
5526 int nDb; /* Number of valid bytes in zDb */
5527 struct stat sStat; /* Output of stat() on database file */
5528
dana0c989d2010-11-05 18:07:37 +00005529 /* zPath is a path to a WAL or journal file. The following block derives
5530 ** the path to the associated database file from zPath. This block handles
5531 ** the following naming conventions:
5532 **
5533 ** "<path to db>-journal"
5534 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005535 ** "<path to db>-journalNN"
5536 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005537 **
drhd337c5b2011-10-20 18:23:35 +00005538 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005539 ** used by the test_multiplex.c module.
5540 */
5541 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005542#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00005543 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00005544 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005545#else
5546 while( zPath[nDb]!='-' ){
5547 assert( nDb>0 );
5548 assert( zPath[nDb]!='\n' );
5549 nDb--;
5550 }
5551#endif
danddb0ac42010-07-14 14:48:58 +00005552 memcpy(zDb, zPath, nDb);
5553 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005554
drh58384f12011-07-28 00:14:45 +00005555 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005556 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005557 *pUid = sStat.st_uid;
5558 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005559 }else{
5560 rc = SQLITE_IOERR_FSTAT;
5561 }
5562 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5563 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005564 }
5565 return rc;
5566}
5567
5568/*
danielk1977ad94b582007-08-20 06:44:22 +00005569** Open the file zPath.
5570**
danielk1977b4b47412007-08-17 15:53:36 +00005571** Previously, the SQLite OS layer used three functions in place of this
5572** one:
5573**
5574** sqlite3OsOpenReadWrite();
5575** sqlite3OsOpenReadOnly();
5576** sqlite3OsOpenExclusive();
5577**
5578** These calls correspond to the following combinations of flags:
5579**
5580** ReadWrite() -> (READWRITE | CREATE)
5581** ReadOnly() -> (READONLY)
5582** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5583**
5584** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5585** true, the file was configured to be automatically deleted when the
5586** file handle closed. To achieve the same effect using this new
5587** interface, add the DELETEONCLOSE flag to those specified above for
5588** OpenExclusive().
5589*/
5590static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005591 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5592 const char *zPath, /* Pathname of file to be opened */
5593 sqlite3_file *pFile, /* The file descriptor to be filled in */
5594 int flags, /* Input flags to control the opening */
5595 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005596){
dan08da86a2009-08-21 17:18:03 +00005597 unixFile *p = (unixFile *)pFile;
5598 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005599 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005600 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005601 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005602 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005603 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005604
5605 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5606 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5607 int isCreate = (flags & SQLITE_OPEN_CREATE);
5608 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5609 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005610#if SQLITE_ENABLE_LOCKING_STYLE
5611 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5612#endif
drh3d4435b2011-08-26 20:55:50 +00005613#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5614 struct statfs fsInfo;
5615#endif
danielk1977b4b47412007-08-17 15:53:36 +00005616
danielk1977fee2d252007-08-18 10:59:19 +00005617 /* If creating a master or main-file journal, this function will open
5618 ** a file-descriptor on the directory too. The first time unixSync()
5619 ** is called the directory file descriptor will be fsync()ed and close()d.
5620 */
drh0059eae2011-08-08 23:48:40 +00005621 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005622 eType==SQLITE_OPEN_MASTER_JOURNAL
5623 || eType==SQLITE_OPEN_MAIN_JOURNAL
5624 || eType==SQLITE_OPEN_WAL
5625 ));
danielk1977fee2d252007-08-18 10:59:19 +00005626
danielk197717b90b52008-06-06 11:11:25 +00005627 /* If argument zPath is a NULL pointer, this function is required to open
5628 ** a temporary file. Use this buffer to store the file name in.
5629 */
drhc02a43a2012-01-10 23:18:38 +00005630 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005631 const char *zName = zPath;
5632
danielk1977fee2d252007-08-18 10:59:19 +00005633 /* Check the following statements are true:
5634 **
5635 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5636 ** (b) if CREATE is set, then READWRITE must also be set, and
5637 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005638 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005639 */
danielk1977b4b47412007-08-17 15:53:36 +00005640 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005641 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005642 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005643 assert(isDelete==0 || isCreate);
5644
danddb0ac42010-07-14 14:48:58 +00005645 /* The main DB, main journal, WAL file and master journal are never
5646 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005647 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5648 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5649 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005650 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005651
danielk1977fee2d252007-08-18 10:59:19 +00005652 /* Assert that the upper layer has set one of the "file-type" flags. */
5653 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5654 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5655 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005656 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005657 );
5658
drhb00d8622014-01-01 15:18:36 +00005659 /* Detect a pid change and reset the PRNG. There is a race condition
5660 ** here such that two or more threads all trying to open databases at
5661 ** the same instant might all reset the PRNG. But multiple resets
5662 ** are harmless.
5663 */
drh5ac93652015-03-21 20:59:43 +00005664 if( randomnessPid!=osGetpid(0) ){
5665 randomnessPid = osGetpid(0);
drhb00d8622014-01-01 15:18:36 +00005666 sqlite3_randomness(0,0);
5667 }
5668
dan08da86a2009-08-21 17:18:03 +00005669 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005670
dan08da86a2009-08-21 17:18:03 +00005671 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005672 UnixUnusedFd *pUnused;
5673 pUnused = findReusableFd(zName, flags);
5674 if( pUnused ){
5675 fd = pUnused->fd;
5676 }else{
drhf3cdcdc2015-04-29 16:50:28 +00005677 pUnused = sqlite3_malloc64(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005678 if( !pUnused ){
5679 return SQLITE_NOMEM;
5680 }
5681 }
5682 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005683
5684 /* Database filenames are double-zero terminated if they are not
5685 ** URIs with parameters. Hence, they can always be passed into
5686 ** sqlite3_uri_parameter(). */
5687 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5688
dan08da86a2009-08-21 17:18:03 +00005689 }else if( !zName ){
5690 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005691 assert(isDelete && !syncDir);
drhb7e50ad2015-11-28 21:49:53 +00005692 rc = unixGetTempname(pVfs->mxPathname, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005693 if( rc!=SQLITE_OK ){
5694 return rc;
5695 }
5696 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005697
5698 /* Generated temporary filenames are always double-zero terminated
5699 ** for use by sqlite3_uri_parameter(). */
5700 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005701 }
5702
dan08da86a2009-08-21 17:18:03 +00005703 /* Determine the value of the flags parameter passed to POSIX function
5704 ** open(). These must be calculated even if open() is not called, as
5705 ** they may be stored as part of the file handle and used by the
5706 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005707 if( isReadonly ) openFlags |= O_RDONLY;
5708 if( isReadWrite ) openFlags |= O_RDWR;
5709 if( isCreate ) openFlags |= O_CREAT;
5710 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5711 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005712
danielk1977b4b47412007-08-17 15:53:36 +00005713 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005714 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005715 uid_t uid; /* Userid for the file */
5716 gid_t gid; /* Groupid for the file */
5717 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005718 if( rc!=SQLITE_OK ){
5719 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005720 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005721 return rc;
5722 }
drhad4f1e52011-03-04 15:43:57 +00005723 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005724 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
drh5a2d9702015-11-26 02:21:05 +00005725 assert( !isExclusive || (openFlags & O_CREAT)!=0 );
5726 if( fd<0 && errno!=EISDIR && isReadWrite ){
dan08da86a2009-08-21 17:18:03 +00005727 /* Failed to open the file for read/write access. Try read-only. */
5728 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005729 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005730 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005731 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005732 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005733 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005734 }
5735 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005736 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005737 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005738 }
drhac7c3ac2012-02-11 19:23:48 +00005739
5740 /* If this process is running as root and if creating a new rollback
5741 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005742 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005743 */
5744 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drh6226ca22015-11-24 15:06:28 +00005745 robustFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005746 }
danielk1977b4b47412007-08-17 15:53:36 +00005747 }
dan08da86a2009-08-21 17:18:03 +00005748 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005749 if( pOutFlags ){
5750 *pOutFlags = flags;
5751 }
5752
dane946c392009-08-22 11:39:46 +00005753 if( p->pUnused ){
5754 p->pUnused->fd = fd;
5755 p->pUnused->flags = flags;
5756 }
5757
danielk1977b4b47412007-08-17 15:53:36 +00005758 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005759#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005760 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00005761#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
5762 zPath = sqlite3_mprintf("%s", zName);
5763 if( zPath==0 ){
5764 robust_close(p, fd, __LINE__);
5765 return SQLITE_NOMEM;
5766 }
chw97185482008-11-17 08:05:31 +00005767#else
drh036ac7f2011-08-08 23:18:05 +00005768 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005769#endif
danielk1977b4b47412007-08-17 15:53:36 +00005770 }
drh41022642008-11-21 00:24:42 +00005771#if SQLITE_ENABLE_LOCKING_STYLE
5772 else{
dan08da86a2009-08-21 17:18:03 +00005773 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005774 }
5775#endif
5776
drhda0e7682008-07-30 15:27:54 +00005777 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005778
drh7ed97b92010-01-20 13:07:21 +00005779
5780#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005781 if( fstatfs(fd, &fsInfo) == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00005782 storeLastErrno(p, errno);
drh0e9365c2011-03-02 02:08:13 +00005783 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005784 return SQLITE_IOERR_ACCESS;
5785 }
5786 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5787 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5788 }
drh4bf66fd2015-02-19 02:43:02 +00005789 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
5790 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5791 }
drh7ed97b92010-01-20 13:07:21 +00005792#endif
drhc02a43a2012-01-10 23:18:38 +00005793
5794 /* Set up appropriate ctrlFlags */
5795 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5796 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5797 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5798 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5799 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5800
drh7ed97b92010-01-20 13:07:21 +00005801#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005802#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005803 isAutoProxy = 1;
5804#endif
5805 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005806 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5807 int useProxy = 0;
5808
dan08da86a2009-08-21 17:18:03 +00005809 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5810 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005811 if( envforce!=NULL ){
5812 useProxy = atoi(envforce)>0;
5813 }else{
aswiftaebf4132008-11-21 00:10:35 +00005814 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5815 }
5816 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005817 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005818 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005819 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005820 if( rc!=SQLITE_OK ){
5821 /* Use unixClose to clean up the resources added in fillInUnixFile
5822 ** and clear all the structure's references. Specifically,
5823 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5824 */
5825 unixClose(pFile);
5826 return rc;
5827 }
aswiftaebf4132008-11-21 00:10:35 +00005828 }
dane946c392009-08-22 11:39:46 +00005829 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005830 }
5831 }
5832#endif
5833
drhc02a43a2012-01-10 23:18:38 +00005834 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5835
dane946c392009-08-22 11:39:46 +00005836open_finished:
5837 if( rc!=SQLITE_OK ){
5838 sqlite3_free(p->pUnused);
5839 }
5840 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005841}
5842
dane946c392009-08-22 11:39:46 +00005843
danielk1977b4b47412007-08-17 15:53:36 +00005844/*
danielk1977fee2d252007-08-18 10:59:19 +00005845** Delete the file at zPath. If the dirSync argument is true, fsync()
5846** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005847*/
drh6b9d6dd2008-12-03 19:34:47 +00005848static int unixDelete(
5849 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5850 const char *zPath, /* Name of file to be deleted */
5851 int dirSync /* If true, fsync() directory after deleting file */
5852){
danielk1977fee2d252007-08-18 10:59:19 +00005853 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005854 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005855 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005856 if( osUnlink(zPath)==(-1) ){
drhbd945542014-08-13 11:39:42 +00005857 if( errno==ENOENT
5858#if OS_VXWORKS
drh19541f32014-09-01 13:37:55 +00005859 || osAccess(zPath,0)!=0
drhbd945542014-08-13 11:39:42 +00005860#endif
5861 ){
dan9fc5b4a2012-11-09 20:17:26 +00005862 rc = SQLITE_IOERR_DELETE_NOENT;
5863 }else{
drhb4308162012-11-09 21:40:02 +00005864 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005865 }
drhb4308162012-11-09 21:40:02 +00005866 return rc;
drh5d4feff2010-07-14 01:45:22 +00005867 }
danielk1977d39fa702008-10-16 13:27:40 +00005868#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005869 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005870 int fd;
drh90315a22011-08-10 01:52:12 +00005871 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005872 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005873#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005874 if( fsync(fd)==-1 )
5875#else
5876 if( fsync(fd) )
5877#endif
5878 {
dane18d4952011-02-21 11:46:24 +00005879 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005880 }
drh0e9365c2011-03-02 02:08:13 +00005881 robust_close(0, fd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00005882 }else{
5883 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00005884 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005885 }
5886 }
danielk1977d138dd82008-10-15 16:02:48 +00005887#endif
danielk1977fee2d252007-08-18 10:59:19 +00005888 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005889}
5890
danielk197790949c22007-08-17 16:50:38 +00005891/*
mistachkin48864df2013-03-21 21:20:32 +00005892** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00005893** test performed depends on the value of flags:
5894**
5895** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5896** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5897** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5898**
5899** Otherwise return 0.
5900*/
danielk1977861f7452008-06-05 11:39:11 +00005901static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005902 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5903 const char *zPath, /* Path of the file to examine */
5904 int flags, /* What do we want to learn about the zPath file? */
5905 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005906){
danielk1977397d65f2008-11-19 11:35:39 +00005907 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005908 SimulateIOError( return SQLITE_IOERR_ACCESS; );
drhd260b5b2015-11-25 18:03:33 +00005909 assert( pResOut!=0 );
danielk1977b4b47412007-08-17 15:53:36 +00005910
drhd260b5b2015-11-25 18:03:33 +00005911 /* The spec says there are three possible values for flags. But only
5912 ** two of them are actually used */
5913 assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
5914
5915 if( flags==SQLITE_ACCESS_EXISTS ){
dan83acd422010-06-18 11:10:06 +00005916 struct stat buf;
drhd260b5b2015-11-25 18:03:33 +00005917 *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
5918 }else{
5919 *pResOut = osAccess(zPath, W_OK|R_OK)==0;
dan83acd422010-06-18 11:10:06 +00005920 }
danielk1977861f7452008-06-05 11:39:11 +00005921 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005922}
5923
danielk1977b4b47412007-08-17 15:53:36 +00005924
5925/*
5926** Turn a relative pathname into a full pathname. The relative path
5927** is stored as a nul-terminated string in the buffer pointed to by
5928** zPath.
5929**
5930** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5931** (in this case, MAX_PATHNAME bytes). The full-path is written to
5932** this buffer before returning.
5933*/
danielk1977adfb9b02007-09-17 07:02:56 +00005934static int unixFullPathname(
5935 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5936 const char *zPath, /* Possibly relative input path */
5937 int nOut, /* Size of output buffer in bytes */
5938 char *zOut /* Output buffer */
5939){
dan245fdc62015-10-31 17:58:33 +00005940 int nByte;
danielk1977843e65f2007-09-01 16:16:15 +00005941
5942 /* It's odd to simulate an io-error here, but really this is just
5943 ** using the io-error infrastructure to test that SQLite handles this
5944 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005945 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005946 */
5947 SimulateIOError( return SQLITE_ERROR );
5948
drh153c62c2007-08-24 03:51:33 +00005949 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005950 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005951
dan245fdc62015-10-31 17:58:33 +00005952 /* Attempt to resolve the path as if it were a symbolic link. If it is
5953 ** a symbolic link, the resolved path is stored in buffer zOut[]. Or, if
5954 ** the identified file is not a symbolic link or does not exist, then
5955 ** zPath is copied directly into zOut. Either way, nByte is left set to
5956 ** the size of the string copied into zOut[] in bytes. */
5957 nByte = osReadlink(zPath, zOut, nOut-1);
5958 if( nByte<0 ){
5959 if( errno!=EINVAL && errno!=ENOENT ){
5960 return unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zPath);
5961 }
drhd260b5b2015-11-25 18:03:33 +00005962 sqlite3_snprintf(nOut, zOut, "%s", zPath);
dan245fdc62015-10-31 17:58:33 +00005963 nByte = sqlite3Strlen30(zOut);
danielk1977b4b47412007-08-17 15:53:36 +00005964 }else{
dan245fdc62015-10-31 17:58:33 +00005965 zOut[nByte] = '\0';
5966 }
5967
5968 /* If buffer zOut[] now contains an absolute path there is nothing more
5969 ** to do. If it contains a relative path, do the following:
5970 **
5971 ** * move the relative path string so that it is at the end of th
5972 ** zOut[] buffer.
5973 ** * Call getcwd() to read the path of the current working directory
5974 ** into the start of the zOut[] buffer.
5975 ** * Append a '/' character to the cwd string and move the
5976 ** relative path back within the buffer so that it immediately
5977 ** follows the '/'.
5978 **
5979 ** This code is written so that if the combination of the CWD and relative
5980 ** path are larger than the allocated size of zOut[] the CWD is silently
5981 ** truncated to make it fit. This is Ok, as SQLite refuses to open any
5982 ** file for which this function returns a full path larger than (nOut-8)
5983 ** bytes in size. */
5984 if( zOut[0]!='/' ){
danielk1977b4b47412007-08-17 15:53:36 +00005985 int nCwd;
dan245fdc62015-10-31 17:58:33 +00005986 int nRem = nOut-nByte-1;
5987 memmove(&zOut[nRem], zOut, nByte+1);
5988 zOut[nRem-1] = '\0';
5989 if( osGetcwd(zOut, nRem-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005990 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005991 }
dan245fdc62015-10-31 17:58:33 +00005992 nCwd = sqlite3Strlen30(zOut);
5993 assert( nCwd<=nRem-1 );
5994 zOut[nCwd] = '/';
5995 memmove(&zOut[nCwd+1], &zOut[nRem], nByte+1);
danielk1977b4b47412007-08-17 15:53:36 +00005996 }
dan245fdc62015-10-31 17:58:33 +00005997
danielk1977b4b47412007-08-17 15:53:36 +00005998 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005999}
6000
drh0ccebe72005-06-07 22:22:50 +00006001
drh761df872006-12-21 01:29:22 +00006002#ifndef SQLITE_OMIT_LOAD_EXTENSION
6003/*
6004** Interfaces for opening a shared library, finding entry points
6005** within the shared library, and closing the shared library.
6006*/
6007#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00006008static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6009 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00006010 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6011}
danielk197795c8a542007-09-01 06:51:27 +00006012
6013/*
6014** SQLite calls this function immediately after a call to unixDlSym() or
6015** unixDlOpen() fails (returns a null pointer). If a more detailed error
6016** message is available, it is written to zBufOut. If no error message
6017** is available, zBufOut is left unmodified and SQLite uses a default
6018** error message.
6019*/
danielk1977397d65f2008-11-19 11:35:39 +00006020static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006021 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006022 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006023 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006024 zErr = dlerror();
6025 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006026 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006027 }
drh6c7d5c52008-11-21 20:32:33 +00006028 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006029}
drh1875f7a2008-12-08 18:19:17 +00006030static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6031 /*
6032 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6033 ** cast into a pointer to a function. And yet the library dlsym() routine
6034 ** returns a void* which is really a pointer to a function. So how do we
6035 ** use dlsym() with -pedantic-errors?
6036 **
6037 ** Variable x below is defined to be a pointer to a function taking
6038 ** parameters void* and const char* and returning a pointer to a function.
6039 ** We initialize x by assigning it a pointer to the dlsym() function.
6040 ** (That assignment requires a cast.) Then we call the function that
6041 ** x points to.
6042 **
6043 ** This work-around is unlikely to work correctly on any system where
6044 ** you really cannot cast a function pointer into void*. But then, on the
6045 ** other hand, dlsym() will not work on such a system either, so we have
6046 ** not really lost anything.
6047 */
6048 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006049 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006050 x = (void(*(*)(void*,const char*))(void))dlsym;
6051 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006052}
danielk1977397d65f2008-11-19 11:35:39 +00006053static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6054 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006055 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006056}
danielk1977b4b47412007-08-17 15:53:36 +00006057#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6058 #define unixDlOpen 0
6059 #define unixDlError 0
6060 #define unixDlSym 0
6061 #define unixDlClose 0
6062#endif
6063
6064/*
danielk197790949c22007-08-17 16:50:38 +00006065** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006066*/
danielk1977397d65f2008-11-19 11:35:39 +00006067static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6068 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006069 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006070
drhbbd42a62004-05-22 17:41:58 +00006071 /* We have to initialize zBuf to prevent valgrind from reporting
6072 ** errors. The reports issued by valgrind are incorrect - we would
6073 ** prefer that the randomness be increased by making use of the
6074 ** uninitialized space in zBuf - but valgrind errors tend to worry
6075 ** some users. Rather than argue, it seems easier just to initialize
6076 ** the whole array and silence valgrind, even if that means less randomness
6077 ** in the random seed.
6078 **
6079 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006080 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006081 ** tests repeatable.
6082 */
danielk1977b4b47412007-08-17 15:53:36 +00006083 memset(zBuf, 0, nBuf);
drh5ac93652015-03-21 20:59:43 +00006084 randomnessPid = osGetpid(0);
drh6a412b82015-04-30 12:31:49 +00006085#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
drhbbd42a62004-05-22 17:41:58 +00006086 {
drhb00d8622014-01-01 15:18:36 +00006087 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006088 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006089 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006090 time_t t;
6091 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006092 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006093 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6094 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6095 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006096 }else{
drhc18b4042012-02-10 03:10:27 +00006097 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006098 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006099 }
drhbbd42a62004-05-22 17:41:58 +00006100 }
6101#endif
drh72cbd072008-10-14 17:58:38 +00006102 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006103}
6104
danielk1977b4b47412007-08-17 15:53:36 +00006105
drhbbd42a62004-05-22 17:41:58 +00006106/*
6107** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006108** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006109** The return value is the number of microseconds of sleep actually
6110** requested from the underlying operating system, a number which
6111** might be greater than or equal to the argument, but not less
6112** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006113*/
danielk1977397d65f2008-11-19 11:35:39 +00006114static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006115#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006116 struct timespec sp;
6117
6118 sp.tv_sec = microseconds / 1000000;
6119 sp.tv_nsec = (microseconds % 1000000) * 1000;
6120 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006121 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006122 return microseconds;
6123#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006124 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006125 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006126 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006127#else
danielk1977b4b47412007-08-17 15:53:36 +00006128 int seconds = (microseconds+999999)/1000000;
6129 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006130 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006131 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006132#endif
drh88f474a2006-01-02 20:00:12 +00006133}
6134
6135/*
drh6b9d6dd2008-12-03 19:34:47 +00006136** The following variable, if set to a non-zero value, is interpreted as
6137** the number of seconds since 1970 and is used to set the result of
6138** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006139*/
6140#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006141int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006142#endif
6143
6144/*
drhb7e8ea22010-05-03 14:32:30 +00006145** Find the current time (in Universal Coordinated Time). Write into *piNow
6146** the current time and date as a Julian Day number times 86_400_000. In
6147** other words, write into *piNow the number of milliseconds since the Julian
6148** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6149** proleptic Gregorian calendar.
6150**
drh31702252011-10-12 23:13:43 +00006151** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6152** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006153*/
6154static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6155 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006156 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006157#if defined(NO_GETTOD)
6158 time_t t;
6159 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006160 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006161#elif OS_VXWORKS
6162 struct timespec sNow;
6163 clock_gettime(CLOCK_REALTIME, &sNow);
6164 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6165#else
6166 struct timeval sNow;
drh970942e2015-11-25 23:13:14 +00006167 (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
6168 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
drhb7e8ea22010-05-03 14:32:30 +00006169#endif
6170
6171#ifdef SQLITE_TEST
6172 if( sqlite3_current_time ){
6173 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6174 }
6175#endif
6176 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006177 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006178}
6179
drh5337dac2015-11-25 15:15:03 +00006180#if 0 /* Not used */
drhb7e8ea22010-05-03 14:32:30 +00006181/*
drhbbd42a62004-05-22 17:41:58 +00006182** Find the current time (in Universal Coordinated Time). Write the
6183** current time and date as a Julian Day number into *prNow and
6184** return 0. Return 1 if the time and date cannot be found.
6185*/
danielk1977397d65f2008-11-19 11:35:39 +00006186static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006187 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006188 int rc;
drhff828942010-06-26 21:34:06 +00006189 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006190 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006191 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006192 return rc;
drhbbd42a62004-05-22 17:41:58 +00006193}
drh5337dac2015-11-25 15:15:03 +00006194#else
6195# define unixCurrentTime 0
6196#endif
danielk1977b4b47412007-08-17 15:53:36 +00006197
drh5337dac2015-11-25 15:15:03 +00006198#if 0 /* Not used */
drh6b9d6dd2008-12-03 19:34:47 +00006199/*
6200** We added the xGetLastError() method with the intention of providing
6201** better low-level error messages when operating-system problems come up
6202** during SQLite operation. But so far, none of that has been implemented
6203** in the core. So this routine is never called. For now, it is merely
6204** a place-holder.
6205*/
danielk1977397d65f2008-11-19 11:35:39 +00006206static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6207 UNUSED_PARAMETER(NotUsed);
6208 UNUSED_PARAMETER(NotUsed2);
6209 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00006210 return 0;
6211}
drh5337dac2015-11-25 15:15:03 +00006212#else
6213# define unixGetLastError 0
6214#endif
danielk1977bcb97fe2008-06-06 15:49:29 +00006215
drhf2424c52010-04-26 00:04:55 +00006216
6217/*
drh734c9862008-11-28 15:37:20 +00006218************************ End of sqlite3_vfs methods ***************************
6219******************************************************************************/
6220
drh715ff302008-12-03 22:32:44 +00006221/******************************************************************************
6222************************** Begin Proxy Locking ********************************
6223**
6224** Proxy locking is a "uber-locking-method" in this sense: It uses the
6225** other locking methods on secondary lock files. Proxy locking is a
6226** meta-layer over top of the primitive locking implemented above. For
6227** this reason, the division that implements of proxy locking is deferred
6228** until late in the file (here) after all of the other I/O methods have
6229** been defined - so that the primitive locking methods are available
6230** as services to help with the implementation of proxy locking.
6231**
6232****
6233**
6234** The default locking schemes in SQLite use byte-range locks on the
6235** database file to coordinate safe, concurrent access by multiple readers
6236** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6237** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6238** as POSIX read & write locks over fixed set of locations (via fsctl),
6239** on AFP and SMB only exclusive byte-range locks are available via fsctl
6240** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6241** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6242** address in the shared range is taken for a SHARED lock, the entire
6243** shared range is taken for an EXCLUSIVE lock):
6244**
drhf2f105d2012-08-20 15:53:54 +00006245** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006246** RESERVED_BYTE 0x40000001
6247** SHARED_RANGE 0x40000002 -> 0x40000200
6248**
6249** This works well on the local file system, but shows a nearly 100x
6250** slowdown in read performance on AFP because the AFP client disables
6251** the read cache when byte-range locks are present. Enabling the read
6252** cache exposes a cache coherency problem that is present on all OS X
6253** supported network file systems. NFS and AFP both observe the
6254** close-to-open semantics for ensuring cache coherency
6255** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6256** address the requirements for concurrent database access by multiple
6257** readers and writers
6258** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6259**
6260** To address the performance and cache coherency issues, proxy file locking
6261** changes the way database access is controlled by limiting access to a
6262** single host at a time and moving file locks off of the database file
6263** and onto a proxy file on the local file system.
6264**
6265**
6266** Using proxy locks
6267** -----------------
6268**
6269** C APIs
6270**
drh4bf66fd2015-02-19 02:43:02 +00006271** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
drh715ff302008-12-03 22:32:44 +00006272** <proxy_path> | ":auto:");
drh4bf66fd2015-02-19 02:43:02 +00006273** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6274** &<proxy_path>);
drh715ff302008-12-03 22:32:44 +00006275**
6276**
6277** SQL pragmas
6278**
6279** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6280** PRAGMA [database.]lock_proxy_file
6281**
6282** Specifying ":auto:" means that if there is a conch file with a matching
6283** host ID in it, the proxy path in the conch file will be used, otherwise
6284** a proxy path based on the user's temp dir
6285** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6286** actual proxy file name is generated from the name and path of the
6287** database file. For example:
6288**
6289** For database path "/Users/me/foo.db"
6290** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6291**
6292** Once a lock proxy is configured for a database connection, it can not
6293** be removed, however it may be switched to a different proxy path via
6294** the above APIs (assuming the conch file is not being held by another
6295** connection or process).
6296**
6297**
6298** How proxy locking works
6299** -----------------------
6300**
6301** Proxy file locking relies primarily on two new supporting files:
6302**
6303** * conch file to limit access to the database file to a single host
6304** at a time
6305**
6306** * proxy file to act as a proxy for the advisory locks normally
6307** taken on the database
6308**
6309** The conch file - to use a proxy file, sqlite must first "hold the conch"
6310** by taking an sqlite-style shared lock on the conch file, reading the
6311** contents and comparing the host's unique host ID (see below) and lock
6312** proxy path against the values stored in the conch. The conch file is
6313** stored in the same directory as the database file and the file name
6314** is patterned after the database file name as ".<databasename>-conch".
peter.d.reid60ec9142014-09-06 16:39:46 +00006315** If the conch file does not exist, or its contents do not match the
drh715ff302008-12-03 22:32:44 +00006316** host ID and/or proxy path, then the lock is escalated to an exclusive
6317** lock and the conch file contents is updated with the host ID and proxy
6318** path and the lock is downgraded to a shared lock again. If the conch
6319** is held by another process (with a shared lock), the exclusive lock
6320** will fail and SQLITE_BUSY is returned.
6321**
6322** The proxy file - a single-byte file used for all advisory file locks
6323** normally taken on the database file. This allows for safe sharing
6324** of the database file for multiple readers and writers on the same
6325** host (the conch ensures that they all use the same local lock file).
6326**
drh715ff302008-12-03 22:32:44 +00006327** Requesting the lock proxy does not immediately take the conch, it is
6328** only taken when the first request to lock database file is made.
6329** This matches the semantics of the traditional locking behavior, where
6330** opening a connection to a database file does not take a lock on it.
6331** The shared lock and an open file descriptor are maintained until
6332** the connection to the database is closed.
6333**
6334** The proxy file and the lock file are never deleted so they only need
6335** to be created the first time they are used.
6336**
6337** Configuration options
6338** ---------------------
6339**
6340** SQLITE_PREFER_PROXY_LOCKING
6341**
6342** Database files accessed on non-local file systems are
6343** automatically configured for proxy locking, lock files are
6344** named automatically using the same logic as
6345** PRAGMA lock_proxy_file=":auto:"
6346**
6347** SQLITE_PROXY_DEBUG
6348**
6349** Enables the logging of error messages during host id file
6350** retrieval and creation
6351**
drh715ff302008-12-03 22:32:44 +00006352** LOCKPROXYDIR
6353**
6354** Overrides the default directory used for lock proxy files that
6355** are named automatically via the ":auto:" setting
6356**
6357** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6358**
6359** Permissions to use when creating a directory for storing the
6360** lock proxy files, only used when LOCKPROXYDIR is not set.
6361**
6362**
6363** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6364** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6365** force proxy locking to be used for every database file opened, and 0
6366** will force automatic proxy locking to be disabled for all database
drh4bf66fd2015-02-19 02:43:02 +00006367** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
drh715ff302008-12-03 22:32:44 +00006368** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6369*/
6370
6371/*
6372** Proxy locking is only available on MacOSX
6373*/
drhd2cb50b2009-01-09 21:41:17 +00006374#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006375
drh715ff302008-12-03 22:32:44 +00006376/*
6377** The proxyLockingContext has the path and file structures for the remote
6378** and local proxy files in it
6379*/
6380typedef struct proxyLockingContext proxyLockingContext;
6381struct proxyLockingContext {
6382 unixFile *conchFile; /* Open conch file */
6383 char *conchFilePath; /* Name of the conch file */
6384 unixFile *lockProxy; /* Open proxy lock file */
6385 char *lockProxyPath; /* Name of the proxy lock file */
6386 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006387 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh4bf66fd2015-02-19 02:43:02 +00006388 int nFails; /* Number of conch taking failures */
drh715ff302008-12-03 22:32:44 +00006389 void *oldLockingContext; /* Original lockingcontext to restore on close */
6390 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6391};
6392
drh7ed97b92010-01-20 13:07:21 +00006393/*
6394** The proxy lock file path for the database at dbPath is written into lPath,
6395** which must point to valid, writable memory large enough for a maxLen length
6396** file path.
drh715ff302008-12-03 22:32:44 +00006397*/
drh715ff302008-12-03 22:32:44 +00006398static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6399 int len;
6400 int dbLen;
6401 int i;
6402
6403#ifdef LOCKPROXYDIR
6404 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6405#else
6406# ifdef _CS_DARWIN_USER_TEMP_DIR
6407 {
drh7ed97b92010-01-20 13:07:21 +00006408 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006409 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006410 lPath, errno, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006411 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006412 }
drh7ed97b92010-01-20 13:07:21 +00006413 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006414 }
6415# else
6416 len = strlcpy(lPath, "/tmp/", maxLen);
6417# endif
6418#endif
6419
6420 if( lPath[len-1]!='/' ){
6421 len = strlcat(lPath, "/", maxLen);
6422 }
6423
6424 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006425 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006426 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006427 char c = dbPath[i];
6428 lPath[i+len] = (c=='/')?'_':c;
6429 }
6430 lPath[i+len]='\0';
6431 strlcat(lPath, ":auto:", maxLen);
drh5ac93652015-03-21 20:59:43 +00006432 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006433 return SQLITE_OK;
6434}
6435
drh7ed97b92010-01-20 13:07:21 +00006436/*
6437 ** Creates the lock file and any missing directories in lockPath
6438 */
6439static int proxyCreateLockPath(const char *lockPath){
6440 int i, len;
6441 char buf[MAXPATHLEN];
6442 int start = 0;
6443
6444 assert(lockPath!=NULL);
6445 /* try to create all the intermediate directories */
6446 len = (int)strlen(lockPath);
6447 buf[0] = lockPath[0];
6448 for( i=1; i<len; i++ ){
6449 if( lockPath[i] == '/' && (i - start > 0) ){
6450 /* only mkdir if leaf dir != "." or "/" or ".." */
6451 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6452 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6453 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006454 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006455 int err=errno;
6456 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006457 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006458 "'%s' proxy lock path=%s pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006459 buf, strerror(err), lockPath, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006460 return err;
6461 }
6462 }
6463 }
6464 start=i+1;
6465 }
6466 buf[i] = lockPath[i];
6467 }
drh62aaa6c2015-11-21 17:27:42 +00006468 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006469 return 0;
6470}
6471
drh715ff302008-12-03 22:32:44 +00006472/*
6473** Create a new VFS file descriptor (stored in memory obtained from
6474** sqlite3_malloc) and open the file named "path" in the file descriptor.
6475**
6476** The caller is responsible not only for closing the file descriptor
6477** but also for freeing the memory associated with the file descriptor.
6478*/
drh7ed97b92010-01-20 13:07:21 +00006479static int proxyCreateUnixFile(
6480 const char *path, /* path for the new unixFile */
6481 unixFile **ppFile, /* unixFile created and returned by ref */
6482 int islockfile /* if non zero missing dirs will be created */
6483) {
6484 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006485 unixFile *pNew;
6486 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006487 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006488 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006489 int terrno = 0;
6490 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006491
drh7ed97b92010-01-20 13:07:21 +00006492 /* 1. first try to open/create the file
6493 ** 2. if that fails, and this is a lock file (not-conch), try creating
6494 ** the parent directories and then try again.
6495 ** 3. if that fails, try to open the file read-only
6496 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6497 */
6498 pUnused = findReusableFd(path, openFlags);
6499 if( pUnused ){
6500 fd = pUnused->fd;
6501 }else{
drhf3cdcdc2015-04-29 16:50:28 +00006502 pUnused = sqlite3_malloc64(sizeof(*pUnused));
drh7ed97b92010-01-20 13:07:21 +00006503 if( !pUnused ){
6504 return SQLITE_NOMEM;
6505 }
6506 }
6507 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006508 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006509 terrno = errno;
6510 if( fd<0 && errno==ENOENT && islockfile ){
6511 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006512 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006513 }
6514 }
6515 }
6516 if( fd<0 ){
6517 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006518 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006519 terrno = errno;
6520 }
6521 if( fd<0 ){
6522 if( islockfile ){
6523 return SQLITE_BUSY;
6524 }
6525 switch (terrno) {
6526 case EACCES:
6527 return SQLITE_PERM;
6528 case EIO:
6529 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6530 default:
drh9978c972010-02-23 17:36:32 +00006531 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006532 }
6533 }
6534
drhf3cdcdc2015-04-29 16:50:28 +00006535 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
drh7ed97b92010-01-20 13:07:21 +00006536 if( pNew==NULL ){
6537 rc = SQLITE_NOMEM;
6538 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006539 }
6540 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006541 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006542 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006543 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006544 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006545 pUnused->fd = fd;
6546 pUnused->flags = openFlags;
6547 pNew->pUnused = pUnused;
6548
drhc02a43a2012-01-10 23:18:38 +00006549 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006550 if( rc==SQLITE_OK ){
6551 *ppFile = pNew;
6552 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006553 }
drh7ed97b92010-01-20 13:07:21 +00006554end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006555 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006556 sqlite3_free(pNew);
6557 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006558 return rc;
6559}
6560
drh7ed97b92010-01-20 13:07:21 +00006561#ifdef SQLITE_TEST
6562/* simulate multiple hosts by creating unique hostid file paths */
6563int sqlite3_hostid_num = 0;
6564#endif
6565
6566#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6567
drh6bca6512015-04-13 23:05:28 +00006568#ifdef HAVE_GETHOSTUUID
drh0ab216a2010-07-02 17:10:40 +00006569/* Not always defined in the headers as it ought to be */
6570extern int gethostuuid(uuid_t id, const struct timespec *wait);
drh6bca6512015-04-13 23:05:28 +00006571#endif
drh0ab216a2010-07-02 17:10:40 +00006572
drh7ed97b92010-01-20 13:07:21 +00006573/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6574** bytes of writable memory.
6575*/
6576static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006577 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6578 memset(pHostID, 0, PROXY_HOSTIDLEN);
drh6bca6512015-04-13 23:05:28 +00006579#ifdef HAVE_GETHOSTUUID
drh29ecd8a2010-12-21 00:16:40 +00006580 {
drh4bf66fd2015-02-19 02:43:02 +00006581 struct timespec timeout = {1, 0}; /* 1 sec timeout */
drh29ecd8a2010-12-21 00:16:40 +00006582 if( gethostuuid(pHostID, &timeout) ){
6583 int err = errno;
6584 if( pError ){
6585 *pError = err;
6586 }
6587 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006588 }
drh7ed97b92010-01-20 13:07:21 +00006589 }
drh3d4435b2011-08-26 20:55:50 +00006590#else
6591 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006592#endif
drh7ed97b92010-01-20 13:07:21 +00006593#ifdef SQLITE_TEST
6594 /* simulate multiple hosts by creating unique hostid file paths */
6595 if( sqlite3_hostid_num != 0){
6596 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6597 }
6598#endif
6599
6600 return SQLITE_OK;
6601}
6602
6603/* The conch file contains the header, host id and lock file path
6604 */
6605#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6606#define PROXY_HEADERLEN 1 /* conch file header length */
6607#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6608#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6609
6610/*
6611** Takes an open conch file, copies the contents to a new path and then moves
6612** it back. The newly created file's file descriptor is assigned to the
6613** conch file structure and finally the original conch file descriptor is
6614** closed. Returns zero if successful.
6615*/
6616static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6617 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6618 unixFile *conchFile = pCtx->conchFile;
6619 char tPath[MAXPATHLEN];
6620 char buf[PROXY_MAXCONCHLEN];
6621 char *cPath = pCtx->conchFilePath;
6622 size_t readLen = 0;
6623 size_t pathLen = 0;
6624 char errmsg[64] = "";
6625 int fd = -1;
6626 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006627 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006628
6629 /* create a new path by replace the trailing '-conch' with '-break' */
6630 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6631 if( pathLen>MAXPATHLEN || pathLen<6 ||
6632 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006633 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006634 goto end_breaklock;
6635 }
6636 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006637 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006638 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006639 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006640 goto end_breaklock;
6641 }
6642 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006643 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006644 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006645 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006646 goto end_breaklock;
6647 }
drhe562be52011-03-02 18:01:10 +00006648 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006649 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006650 goto end_breaklock;
6651 }
6652 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006653 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006654 goto end_breaklock;
6655 }
6656 rc = 0;
6657 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006658 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006659 conchFile->h = fd;
6660 conchFile->openFlags = O_RDWR | O_CREAT;
6661
6662end_breaklock:
6663 if( rc ){
6664 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006665 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006666 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006667 }
6668 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6669 }
6670 return rc;
6671}
6672
6673/* Take the requested lock on the conch file and break a stale lock if the
6674** host id matches.
6675*/
6676static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6677 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6678 unixFile *conchFile = pCtx->conchFile;
6679 int rc = SQLITE_OK;
6680 int nTries = 0;
6681 struct timespec conchModTime;
6682
drh3d4435b2011-08-26 20:55:50 +00006683 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006684 do {
6685 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6686 nTries ++;
6687 if( rc==SQLITE_BUSY ){
6688 /* If the lock failed (busy):
6689 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6690 * 2nd try: fail if the mod time changed or host id is different, wait
6691 * 10 sec and try again
6692 * 3rd try: break the lock unless the mod time has changed.
6693 */
6694 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006695 if( osFstat(conchFile->h, &buf) ){
drh4bf66fd2015-02-19 02:43:02 +00006696 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006697 return SQLITE_IOERR_LOCK;
6698 }
6699
6700 if( nTries==1 ){
6701 conchModTime = buf.st_mtimespec;
6702 usleep(500000); /* wait 0.5 sec and try the lock again*/
6703 continue;
6704 }
6705
6706 assert( nTries>1 );
6707 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6708 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6709 return SQLITE_BUSY;
6710 }
6711
6712 if( nTries==2 ){
6713 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006714 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006715 if( len<0 ){
drh4bf66fd2015-02-19 02:43:02 +00006716 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006717 return SQLITE_IOERR_LOCK;
6718 }
6719 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6720 /* don't break the lock if the host id doesn't match */
6721 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6722 return SQLITE_BUSY;
6723 }
6724 }else{
6725 /* don't break the lock on short read or a version mismatch */
6726 return SQLITE_BUSY;
6727 }
6728 usleep(10000000); /* wait 10 sec and try the lock again */
6729 continue;
6730 }
6731
6732 assert( nTries==3 );
6733 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6734 rc = SQLITE_OK;
6735 if( lockType==EXCLUSIVE_LOCK ){
drhe6d41732015-02-21 00:49:00 +00006736 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
drh7ed97b92010-01-20 13:07:21 +00006737 }
6738 if( !rc ){
6739 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6740 }
6741 }
6742 }
6743 } while( rc==SQLITE_BUSY && nTries<3 );
6744
6745 return rc;
6746}
6747
6748/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006749** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6750** lockPath means that the lockPath in the conch file will be used if the
6751** host IDs match, or a new lock path will be generated automatically
6752** and written to the conch file.
6753*/
6754static int proxyTakeConch(unixFile *pFile){
6755 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6756
drh7ed97b92010-01-20 13:07:21 +00006757 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006758 return SQLITE_OK;
6759 }else{
6760 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006761 uuid_t myHostID;
6762 int pError = 0;
6763 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006764 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006765 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006766 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006767 int createConch = 0;
6768 int hostIdMatch = 0;
6769 int readLen = 0;
6770 int tryOldLockPath = 0;
6771 int forceNewLockPath = 0;
6772
drh308c2a52010-05-14 11:30:18 +00006773 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
drh91eb93c2015-03-03 19:56:20 +00006774 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00006775 osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006776
drh7ed97b92010-01-20 13:07:21 +00006777 rc = proxyGetHostID(myHostID, &pError);
6778 if( (rc&0xff)==SQLITE_IOERR ){
drh4bf66fd2015-02-19 02:43:02 +00006779 storeLastErrno(pFile, pError);
drh7ed97b92010-01-20 13:07:21 +00006780 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006781 }
drh7ed97b92010-01-20 13:07:21 +00006782 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006783 if( rc!=SQLITE_OK ){
6784 goto end_takeconch;
6785 }
drh7ed97b92010-01-20 13:07:21 +00006786 /* read the existing conch file */
6787 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6788 if( readLen<0 ){
6789 /* I/O error: lastErrno set by seekAndRead */
drh4bf66fd2015-02-19 02:43:02 +00006790 storeLastErrno(pFile, conchFile->lastErrno);
drh7ed97b92010-01-20 13:07:21 +00006791 rc = SQLITE_IOERR_READ;
6792 goto end_takeconch;
6793 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6794 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6795 /* a short read or version format mismatch means we need to create a new
6796 ** conch file.
6797 */
6798 createConch = 1;
6799 }
6800 /* if the host id matches and the lock path already exists in the conch
6801 ** we'll try to use the path there, if we can't open that path, we'll
6802 ** retry with a new auto-generated path
6803 */
6804 do { /* in case we need to try again for an :auto: named lock file */
6805
6806 if( !createConch && !forceNewLockPath ){
6807 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6808 PROXY_HOSTIDLEN);
6809 /* if the conch has data compare the contents */
6810 if( !pCtx->lockProxyPath ){
6811 /* for auto-named local lock file, just check the host ID and we'll
6812 ** use the local lock file path that's already in there
6813 */
6814 if( hostIdMatch ){
6815 size_t pathLen = (readLen - PROXY_PATHINDEX);
6816
6817 if( pathLen>=MAXPATHLEN ){
6818 pathLen=MAXPATHLEN-1;
6819 }
6820 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6821 lockPath[pathLen] = 0;
6822 tempLockPath = lockPath;
6823 tryOldLockPath = 1;
6824 /* create a copy of the lock path if the conch is taken */
6825 goto end_takeconch;
6826 }
6827 }else if( hostIdMatch
6828 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6829 readLen-PROXY_PATHINDEX)
6830 ){
6831 /* conch host and lock path match */
6832 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006833 }
drh7ed97b92010-01-20 13:07:21 +00006834 }
6835
6836 /* if the conch isn't writable and doesn't match, we can't take it */
6837 if( (conchFile->openFlags&O_RDWR) == 0 ){
6838 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006839 goto end_takeconch;
6840 }
drh7ed97b92010-01-20 13:07:21 +00006841
6842 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006843 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006844 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6845 tempLockPath = lockPath;
6846 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006847 }
drh7ed97b92010-01-20 13:07:21 +00006848
6849 /* update conch with host and path (this will fail if other process
6850 ** has a shared lock already), if the host id matches, use the big
6851 ** stick.
drh715ff302008-12-03 22:32:44 +00006852 */
drh7ed97b92010-01-20 13:07:21 +00006853 futimes(conchFile->h, NULL);
6854 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006855 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006856 /* We are trying for an exclusive lock but another thread in this
6857 ** same process is still holding a shared lock. */
6858 rc = SQLITE_BUSY;
6859 } else {
6860 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006861 }
drh715ff302008-12-03 22:32:44 +00006862 }else{
drh4bf66fd2015-02-19 02:43:02 +00006863 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006864 }
drh7ed97b92010-01-20 13:07:21 +00006865 if( rc==SQLITE_OK ){
6866 char writeBuffer[PROXY_MAXCONCHLEN];
6867 int writeSize = 0;
6868
6869 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6870 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6871 if( pCtx->lockProxyPath!=NULL ){
drh4bf66fd2015-02-19 02:43:02 +00006872 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
6873 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00006874 }else{
6875 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6876 }
6877 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006878 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006879 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6880 fsync(conchFile->h);
6881 /* If we created a new conch file (not just updated the contents of a
6882 ** valid conch file), try to match the permissions of the database
6883 */
6884 if( rc==SQLITE_OK && createConch ){
6885 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006886 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006887 if( err==0 ){
6888 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6889 S_IROTH|S_IWOTH);
6890 /* try to match the database file R/W permissions, ignore failure */
6891#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006892 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006893#else
drhff812312011-02-23 13:33:46 +00006894 do{
drhe562be52011-03-02 18:01:10 +00006895 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006896 }while( rc==(-1) && errno==EINTR );
6897 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006898 int code = errno;
6899 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6900 cmode, code, strerror(code));
6901 } else {
6902 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6903 }
6904 }else{
6905 int code = errno;
6906 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6907 err, code, strerror(code));
6908#endif
6909 }
drh715ff302008-12-03 22:32:44 +00006910 }
6911 }
drh7ed97b92010-01-20 13:07:21 +00006912 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6913
6914 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006915 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006916 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006917 int fd;
drh7ed97b92010-01-20 13:07:21 +00006918 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006919 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006920 }
6921 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006922 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006923 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006924 if( fd>=0 ){
6925 pFile->h = fd;
6926 }else{
drh9978c972010-02-23 17:36:32 +00006927 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006928 during locking */
6929 }
6930 }
6931 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6932 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6933 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6934 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6935 /* we couldn't create the proxy lock file with the old lock file path
6936 ** so try again via auto-naming
6937 */
6938 forceNewLockPath = 1;
6939 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006940 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006941 }
6942 }
6943 if( rc==SQLITE_OK ){
6944 /* Need to make a copy of path if we extracted the value
6945 ** from the conch file or the path was allocated on the stack
6946 */
6947 if( tempLockPath ){
6948 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6949 if( !pCtx->lockProxyPath ){
6950 rc = SQLITE_NOMEM;
6951 }
6952 }
6953 }
6954 if( rc==SQLITE_OK ){
6955 pCtx->conchHeld = 1;
6956
6957 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6958 afpLockingContext *afpCtx;
6959 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6960 afpCtx->dbPath = pCtx->lockProxyPath;
6961 }
6962 } else {
6963 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6964 }
drh308c2a52010-05-14 11:30:18 +00006965 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6966 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006967 return rc;
drh308c2a52010-05-14 11:30:18 +00006968 } while (1); /* in case we need to retry the :auto: lock file -
6969 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006970 }
6971}
6972
6973/*
6974** If pFile holds a lock on a conch file, then release that lock.
6975*/
6976static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006977 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006978 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6979 unixFile *conchFile; /* Name of the conch file */
6980
6981 pCtx = (proxyLockingContext *)pFile->lockingContext;
6982 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006983 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006984 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00006985 osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006986 if( pCtx->conchHeld>0 ){
6987 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6988 }
drh715ff302008-12-03 22:32:44 +00006989 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006990 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6991 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006992 return rc;
6993}
6994
6995/*
6996** Given the name of a database file, compute the name of its conch file.
drhf3cdcdc2015-04-29 16:50:28 +00006997** Store the conch filename in memory obtained from sqlite3_malloc64().
drh715ff302008-12-03 22:32:44 +00006998** Make *pConchPath point to the new name. Return SQLITE_OK on success
6999** or SQLITE_NOMEM if unable to obtain memory.
7000**
7001** The caller is responsible for ensuring that the allocated memory
7002** space is eventually freed.
7003**
7004** *pConchPath is set to NULL if a memory allocation error occurs.
7005*/
7006static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7007 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00007008 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00007009 char *conchPath; /* buffer in which to construct conch name */
7010
7011 /* Allocate space for the conch filename and initialize the name to
7012 ** the name of the original database file. */
drhf3cdcdc2015-04-29 16:50:28 +00007013 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
drh715ff302008-12-03 22:32:44 +00007014 if( conchPath==0 ){
7015 return SQLITE_NOMEM;
7016 }
7017 memcpy(conchPath, dbPath, len+1);
7018
7019 /* now insert a "." before the last / character */
7020 for( i=(len-1); i>=0; i-- ){
7021 if( conchPath[i]=='/' ){
7022 i++;
7023 break;
7024 }
7025 }
7026 conchPath[i]='.';
7027 while ( i<len ){
7028 conchPath[i+1]=dbPath[i];
7029 i++;
7030 }
7031
7032 /* append the "-conch" suffix to the file */
7033 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007034 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007035
7036 return SQLITE_OK;
7037}
7038
7039
7040/* Takes a fully configured proxy locking-style unix file and switches
7041** the local lock file path
7042*/
7043static int switchLockProxyPath(unixFile *pFile, const char *path) {
7044 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7045 char *oldPath = pCtx->lockProxyPath;
7046 int rc = SQLITE_OK;
7047
drh308c2a52010-05-14 11:30:18 +00007048 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007049 return SQLITE_BUSY;
7050 }
7051
7052 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7053 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7054 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7055 return SQLITE_OK;
7056 }else{
7057 unixFile *lockProxy = pCtx->lockProxy;
7058 pCtx->lockProxy=NULL;
7059 pCtx->conchHeld = 0;
7060 if( lockProxy!=NULL ){
7061 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7062 if( rc ) return rc;
7063 sqlite3_free(lockProxy);
7064 }
7065 sqlite3_free(oldPath);
7066 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7067 }
7068
7069 return rc;
7070}
7071
7072/*
7073** pFile is a file that has been opened by a prior xOpen call. dbPath
7074** is a string buffer at least MAXPATHLEN+1 characters in size.
7075**
7076** This routine find the filename associated with pFile and writes it
7077** int dbPath.
7078*/
7079static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007080#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007081 if( pFile->pMethod == &afpIoMethods ){
7082 /* afp style keeps a reference to the db path in the filePath field
7083 ** of the struct */
drhea678832008-12-10 19:26:22 +00007084 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh4bf66fd2015-02-19 02:43:02 +00007085 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7086 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007087 } else
drh715ff302008-12-03 22:32:44 +00007088#endif
7089 if( pFile->pMethod == &dotlockIoMethods ){
7090 /* dot lock style uses the locking context to store the dot lock
7091 ** file path */
7092 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7093 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7094 }else{
7095 /* all other styles use the locking context to store the db file path */
7096 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007097 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007098 }
7099 return SQLITE_OK;
7100}
7101
7102/*
7103** Takes an already filled in unix file and alters it so all file locking
7104** will be performed on the local proxy lock file. The following fields
7105** are preserved in the locking context so that they can be restored and
7106** the unix structure properly cleaned up at close time:
7107** ->lockingContext
7108** ->pMethod
7109*/
7110static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7111 proxyLockingContext *pCtx;
7112 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7113 char *lockPath=NULL;
7114 int rc = SQLITE_OK;
7115
drh308c2a52010-05-14 11:30:18 +00007116 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007117 return SQLITE_BUSY;
7118 }
7119 proxyGetDbPathForUnixFile(pFile, dbPath);
7120 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7121 lockPath=NULL;
7122 }else{
7123 lockPath=(char *)path;
7124 }
7125
drh308c2a52010-05-14 11:30:18 +00007126 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
drh5ac93652015-03-21 20:59:43 +00007127 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007128
drhf3cdcdc2015-04-29 16:50:28 +00007129 pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh715ff302008-12-03 22:32:44 +00007130 if( pCtx==0 ){
7131 return SQLITE_NOMEM;
7132 }
7133 memset(pCtx, 0, sizeof(*pCtx));
7134
7135 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7136 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007137 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7138 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7139 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7140 ** (c) the file system is read-only, then enable no-locking access.
7141 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7142 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7143 */
7144 struct statfs fsInfo;
7145 struct stat conchInfo;
7146 int goLockless = 0;
7147
drh99ab3b12011-03-02 15:09:07 +00007148 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007149 int err = errno;
7150 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7151 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7152 }
7153 }
7154 if( goLockless ){
7155 pCtx->conchHeld = -1; /* read only FS/ lockless */
7156 rc = SQLITE_OK;
7157 }
7158 }
drh715ff302008-12-03 22:32:44 +00007159 }
7160 if( rc==SQLITE_OK && lockPath ){
7161 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7162 }
7163
7164 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007165 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7166 if( pCtx->dbPath==NULL ){
7167 rc = SQLITE_NOMEM;
7168 }
7169 }
7170 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007171 /* all memory is allocated, proxys are created and assigned,
7172 ** switch the locking context and pMethod then return.
7173 */
drh715ff302008-12-03 22:32:44 +00007174 pCtx->oldLockingContext = pFile->lockingContext;
7175 pFile->lockingContext = pCtx;
7176 pCtx->pOldMethod = pFile->pMethod;
7177 pFile->pMethod = &proxyIoMethods;
7178 }else{
7179 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007180 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007181 sqlite3_free(pCtx->conchFile);
7182 }
drhd56b1212010-08-11 06:14:15 +00007183 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007184 sqlite3_free(pCtx->conchFilePath);
7185 sqlite3_free(pCtx);
7186 }
drh308c2a52010-05-14 11:30:18 +00007187 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7188 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007189 return rc;
7190}
7191
7192
7193/*
7194** This routine handles sqlite3_file_control() calls that are specific
7195** to proxy locking.
7196*/
7197static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7198 switch( op ){
drh4bf66fd2015-02-19 02:43:02 +00007199 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007200 unixFile *pFile = (unixFile*)id;
7201 if( pFile->pMethod == &proxyIoMethods ){
7202 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7203 proxyTakeConch(pFile);
7204 if( pCtx->lockProxyPath ){
7205 *(const char **)pArg = pCtx->lockProxyPath;
7206 }else{
7207 *(const char **)pArg = ":auto: (not held)";
7208 }
7209 } else {
7210 *(const char **)pArg = NULL;
7211 }
7212 return SQLITE_OK;
7213 }
drh4bf66fd2015-02-19 02:43:02 +00007214 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007215 unixFile *pFile = (unixFile*)id;
7216 int rc = SQLITE_OK;
7217 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7218 if( pArg==NULL || (const char *)pArg==0 ){
7219 if( isProxyStyle ){
drh4bf66fd2015-02-19 02:43:02 +00007220 /* turn off proxy locking - not supported. If support is added for
7221 ** switching proxy locking mode off then it will need to fail if
7222 ** the journal mode is WAL mode.
7223 */
drh715ff302008-12-03 22:32:44 +00007224 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7225 }else{
7226 /* turn off proxy locking - already off - NOOP */
7227 rc = SQLITE_OK;
7228 }
7229 }else{
7230 const char *proxyPath = (const char *)pArg;
7231 if( isProxyStyle ){
7232 proxyLockingContext *pCtx =
7233 (proxyLockingContext*)pFile->lockingContext;
7234 if( !strcmp(pArg, ":auto:")
7235 || (pCtx->lockProxyPath &&
7236 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7237 ){
7238 rc = SQLITE_OK;
7239 }else{
7240 rc = switchLockProxyPath(pFile, proxyPath);
7241 }
7242 }else{
7243 /* turn on proxy file locking */
7244 rc = proxyTransformUnixFile(pFile, proxyPath);
7245 }
7246 }
7247 return rc;
7248 }
7249 default: {
7250 assert( 0 ); /* The call assures that only valid opcodes are sent */
7251 }
7252 }
7253 /*NOTREACHED*/
7254 return SQLITE_ERROR;
7255}
7256
7257/*
7258** Within this division (the proxying locking implementation) the procedures
7259** above this point are all utilities. The lock-related methods of the
7260** proxy-locking sqlite3_io_method object follow.
7261*/
7262
7263
7264/*
7265** This routine checks if there is a RESERVED lock held on the specified
7266** file by this or any other process. If such a lock is held, set *pResOut
7267** to a non-zero value otherwise *pResOut is set to zero. The return value
7268** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7269*/
7270static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7271 unixFile *pFile = (unixFile*)id;
7272 int rc = proxyTakeConch(pFile);
7273 if( rc==SQLITE_OK ){
7274 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007275 if( pCtx->conchHeld>0 ){
7276 unixFile *proxy = pCtx->lockProxy;
7277 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7278 }else{ /* conchHeld < 0 is lockless */
7279 pResOut=0;
7280 }
drh715ff302008-12-03 22:32:44 +00007281 }
7282 return rc;
7283}
7284
7285/*
drh308c2a52010-05-14 11:30:18 +00007286** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007287** of the following:
7288**
7289** (1) SHARED_LOCK
7290** (2) RESERVED_LOCK
7291** (3) PENDING_LOCK
7292** (4) EXCLUSIVE_LOCK
7293**
7294** Sometimes when requesting one lock state, additional lock states
7295** are inserted in between. The locking might fail on one of the later
7296** transitions leaving the lock state different from what it started but
7297** still short of its goal. The following chart shows the allowed
7298** transitions and the inserted intermediate states:
7299**
7300** UNLOCKED -> SHARED
7301** SHARED -> RESERVED
7302** SHARED -> (PENDING) -> EXCLUSIVE
7303** RESERVED -> (PENDING) -> EXCLUSIVE
7304** PENDING -> EXCLUSIVE
7305**
7306** This routine will only increase a lock. Use the sqlite3OsUnlock()
7307** routine to lower a locking level.
7308*/
drh308c2a52010-05-14 11:30:18 +00007309static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007310 unixFile *pFile = (unixFile*)id;
7311 int rc = proxyTakeConch(pFile);
7312 if( rc==SQLITE_OK ){
7313 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007314 if( pCtx->conchHeld>0 ){
7315 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007316 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7317 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007318 }else{
7319 /* conchHeld < 0 is lockless */
7320 }
drh715ff302008-12-03 22:32:44 +00007321 }
7322 return rc;
7323}
7324
7325
7326/*
drh308c2a52010-05-14 11:30:18 +00007327** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007328** must be either NO_LOCK or SHARED_LOCK.
7329**
7330** If the locking level of the file descriptor is already at or below
7331** the requested locking level, this routine is a no-op.
7332*/
drh308c2a52010-05-14 11:30:18 +00007333static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007334 unixFile *pFile = (unixFile*)id;
7335 int rc = proxyTakeConch(pFile);
7336 if( rc==SQLITE_OK ){
7337 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007338 if( pCtx->conchHeld>0 ){
7339 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007340 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7341 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007342 }else{
7343 /* conchHeld < 0 is lockless */
7344 }
drh715ff302008-12-03 22:32:44 +00007345 }
7346 return rc;
7347}
7348
7349/*
7350** Close a file that uses proxy locks.
7351*/
7352static int proxyClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00007353 if( ALWAYS(id) ){
drh715ff302008-12-03 22:32:44 +00007354 unixFile *pFile = (unixFile*)id;
7355 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7356 unixFile *lockProxy = pCtx->lockProxy;
7357 unixFile *conchFile = pCtx->conchFile;
7358 int rc = SQLITE_OK;
7359
7360 if( lockProxy ){
7361 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7362 if( rc ) return rc;
7363 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7364 if( rc ) return rc;
7365 sqlite3_free(lockProxy);
7366 pCtx->lockProxy = 0;
7367 }
7368 if( conchFile ){
7369 if( pCtx->conchHeld ){
7370 rc = proxyReleaseConch(pFile);
7371 if( rc ) return rc;
7372 }
7373 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7374 if( rc ) return rc;
7375 sqlite3_free(conchFile);
7376 }
drhd56b1212010-08-11 06:14:15 +00007377 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007378 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007379 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007380 /* restore the original locking context and pMethod then close it */
7381 pFile->lockingContext = pCtx->oldLockingContext;
7382 pFile->pMethod = pCtx->pOldMethod;
7383 sqlite3_free(pCtx);
7384 return pFile->pMethod->xClose(id);
7385 }
7386 return SQLITE_OK;
7387}
7388
7389
7390
drhd2cb50b2009-01-09 21:41:17 +00007391#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007392/*
7393** The proxy locking style is intended for use with AFP filesystems.
7394** And since AFP is only supported on MacOSX, the proxy locking is also
7395** restricted to MacOSX.
7396**
7397**
7398******************* End of the proxy lock implementation **********************
7399******************************************************************************/
7400
drh734c9862008-11-28 15:37:20 +00007401/*
danielk1977e339d652008-06-28 11:23:00 +00007402** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007403**
7404** This routine registers all VFS implementations for unix-like operating
7405** systems. This routine, and the sqlite3_os_end() routine that follows,
7406** should be the only routines in this file that are visible from other
7407** files.
drh6b9d6dd2008-12-03 19:34:47 +00007408**
7409** This routine is called once during SQLite initialization and by a
7410** single thread. The memory allocation and mutex subsystems have not
7411** necessarily been initialized when this routine is called, and so they
7412** should not be used.
drh153c62c2007-08-24 03:51:33 +00007413*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007414int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007415 /*
7416 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007417 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7418 ** to the "finder" function. (pAppData is a pointer to a pointer because
7419 ** silly C90 rules prohibit a void* from being cast to a function pointer
7420 ** and so we have to go through the intermediate pointer to avoid problems
7421 ** when compiling with -pedantic-errors on GCC.)
7422 **
7423 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007424 ** finder-function. The finder-function returns a pointer to the
7425 ** sqlite_io_methods object that implements the desired locking
7426 ** behaviors. See the division above that contains the IOMETHODS
7427 ** macro for addition information on finder-functions.
7428 **
7429 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7430 ** object. But the "autolockIoFinder" available on MacOSX does a little
7431 ** more than that; it looks at the filesystem type that hosts the
7432 ** database file and tries to choose an locking method appropriate for
7433 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007434 */
drh7708e972008-11-29 00:56:52 +00007435 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007436 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007437 sizeof(unixFile), /* szOsFile */ \
7438 MAX_PATHNAME, /* mxPathname */ \
7439 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007440 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007441 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007442 unixOpen, /* xOpen */ \
7443 unixDelete, /* xDelete */ \
7444 unixAccess, /* xAccess */ \
7445 unixFullPathname, /* xFullPathname */ \
7446 unixDlOpen, /* xDlOpen */ \
7447 unixDlError, /* xDlError */ \
7448 unixDlSym, /* xDlSym */ \
7449 unixDlClose, /* xDlClose */ \
7450 unixRandomness, /* xRandomness */ \
7451 unixSleep, /* xSleep */ \
7452 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007453 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007454 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007455 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007456 unixGetSystemCall, /* xGetSystemCall */ \
7457 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007458 }
7459
drh6b9d6dd2008-12-03 19:34:47 +00007460 /*
7461 ** All default VFSes for unix are contained in the following array.
7462 **
7463 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7464 ** by the SQLite core when the VFS is registered. So the following
7465 ** array cannot be const.
7466 */
danielk1977e339d652008-06-28 11:23:00 +00007467 static sqlite3_vfs aVfs[] = {
drhe89b2912015-03-03 20:42:01 +00007468#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007469 UNIXVFS("unix", autolockIoFinder ),
drhe89b2912015-03-03 20:42:01 +00007470#elif OS_VXWORKS
7471 UNIXVFS("unix", vxworksIoFinder ),
drh7708e972008-11-29 00:56:52 +00007472#else
7473 UNIXVFS("unix", posixIoFinder ),
7474#endif
7475 UNIXVFS("unix-none", nolockIoFinder ),
7476 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007477 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007478#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007479 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007480#endif
drhe89b2912015-03-03 20:42:01 +00007481#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007482 UNIXVFS("unix-posix", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007483#endif
drhe89b2912015-03-03 20:42:01 +00007484#if SQLITE_ENABLE_LOCKING_STYLE
7485 UNIXVFS("unix-flock", flockIoFinder ),
chw78a13182009-04-07 05:35:03 +00007486#endif
drhd2cb50b2009-01-09 21:41:17 +00007487#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007488 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007489 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007490 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007491#endif
drh153c62c2007-08-24 03:51:33 +00007492 };
drh6b9d6dd2008-12-03 19:34:47 +00007493 unsigned int i; /* Loop counter */
7494
drh2aa5a002011-04-13 13:42:25 +00007495 /* Double-check that the aSyscall[] array has been constructed
7496 ** correctly. See ticket [bb3a86e890c8e96ab] */
drh6226ca22015-11-24 15:06:28 +00007497 assert( ArraySize(aSyscall)==27 );
drh2aa5a002011-04-13 13:42:25 +00007498
drh6b9d6dd2008-12-03 19:34:47 +00007499 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007500 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007501 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007502 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007503 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007504}
danielk1977e339d652008-06-28 11:23:00 +00007505
7506/*
drh6b9d6dd2008-12-03 19:34:47 +00007507** Shutdown the operating system interface.
7508**
7509** Some operating systems might need to do some cleanup in this routine,
7510** to release dynamically allocated objects. But not on unix.
7511** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007512*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007513int sqlite3_os_end(void){
7514 return SQLITE_OK;
7515}
drhdce8bdb2007-08-16 13:01:44 +00007516
danielk197729bafea2008-06-26 10:41:19 +00007517#endif /* SQLITE_OS_UNIX */