blob: 31e3215b8a040c5acb91e4a30168f6103cf70040 [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 */
drha7e61d82011-03-12 17:02:57 +0000261
262/*
drh198bf392006-01-06 21:52:49 +0000263** Include code that is common to all os_*.c files
264*/
265#include "os_common.h"
266
267/*
drh0ccebe72005-06-07 22:22:50 +0000268** Define various macros that are missing from some systems.
269*/
drhbbd42a62004-05-22 17:41:58 +0000270#ifndef O_LARGEFILE
271# define O_LARGEFILE 0
272#endif
273#ifdef SQLITE_DISABLE_LFS
274# undef O_LARGEFILE
275# define O_LARGEFILE 0
276#endif
277#ifndef O_NOFOLLOW
278# define O_NOFOLLOW 0
279#endif
280#ifndef O_BINARY
281# define O_BINARY 0
282#endif
283
284/*
drh2b4b5962005-06-15 17:47:55 +0000285** The threadid macro resolves to the thread-id or to 0. Used for
286** testing and debugging only.
287*/
drhd677b3d2007-08-20 22:48:41 +0000288#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000289#define threadid pthread_self()
290#else
291#define threadid 0
292#endif
293
drh99ab3b12011-03-02 15:09:07 +0000294/*
dane6ecd662013-04-01 17:56:59 +0000295** HAVE_MREMAP defaults to true on Linux and false everywhere else.
296*/
297#if !defined(HAVE_MREMAP)
298# if defined(__linux__) && defined(_GNU_SOURCE)
299# define HAVE_MREMAP 1
300# else
301# define HAVE_MREMAP 0
302# endif
303#endif
304
305/*
dan2ee53412014-09-06 16:49:40 +0000306** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
307** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
308*/
309#ifdef __ANDROID__
310# define lseek lseek64
311#endif
312
313/*
drh9a3baf12011-04-25 18:01:27 +0000314** Different Unix systems declare open() in different ways. Same use
315** open(const char*,int,mode_t). Others use open(const char*,int,...).
316** The difference is important when using a pointer to the function.
317**
318** The safest way to deal with the problem is to always use this wrapper
319** which always has the same well-defined interface.
320*/
321static int posixOpen(const char *zFile, int flags, int mode){
322 return open(zFile, flags, mode);
323}
324
drh90315a22011-08-10 01:52:12 +0000325/* Forward reference */
326static int openDirectory(const char*, int*);
danbc760632014-03-20 09:42:09 +0000327static int unixGetpagesize(void);
drh90315a22011-08-10 01:52:12 +0000328
drh9a3baf12011-04-25 18:01:27 +0000329/*
drh99ab3b12011-03-02 15:09:07 +0000330** Many system calls are accessed through pointer-to-functions so that
331** they may be overridden at runtime to facilitate fault injection during
332** testing and sandboxing. The following array holds the names and pointers
333** to all overrideable system calls.
334*/
335static struct unix_syscall {
mistachkin48864df2013-03-21 21:20:32 +0000336 const char *zName; /* Name of the system call */
drh58ad5802011-03-23 22:02:23 +0000337 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
338 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000339} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000340 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
341#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000342
drh58ad5802011-03-23 22:02:23 +0000343 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000344#define osClose ((int(*)(int))aSyscall[1].pCurrent)
345
drh58ad5802011-03-23 22:02:23 +0000346 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000347#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
348
drh58ad5802011-03-23 22:02:23 +0000349 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000350#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
351
drh58ad5802011-03-23 22:02:23 +0000352 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000353#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
354
355/*
356** The DJGPP compiler environment looks mostly like Unix, but it
357** lacks the fcntl() system call. So redefine fcntl() to be something
358** that always succeeds. This means that locking does not occur under
359** DJGPP. But it is DOS - what did you expect?
360*/
361#ifdef __DJGPP__
362 { "fstat", 0, 0 },
363#define osFstat(a,b,c) 0
364#else
drh58ad5802011-03-23 22:02:23 +0000365 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000366#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
367#endif
368
drh58ad5802011-03-23 22:02:23 +0000369 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000370#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
371
drh58ad5802011-03-23 22:02:23 +0000372 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000373#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000374
drh58ad5802011-03-23 22:02:23 +0000375 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000376#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
377
drhe89b2912015-03-03 20:42:01 +0000378#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000379 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000380#else
drh58ad5802011-03-23 22:02:23 +0000381 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000382#endif
383#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
384
385#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000386 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000387#else
drh58ad5802011-03-23 22:02:23 +0000388 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000389#endif
390#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
391
drh58ad5802011-03-23 22:02:23 +0000392 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000393#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
394
drhe89b2912015-03-03 20:42:01 +0000395#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000396 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000397#else
drh58ad5802011-03-23 22:02:23 +0000398 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000399#endif
400#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
401 aSyscall[12].pCurrent)
402
403#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000404 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000405#else
drh58ad5802011-03-23 22:02:23 +0000406 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000407#endif
408#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
409 aSyscall[13].pCurrent)
410
drh6226ca22015-11-24 15:06:28 +0000411 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000412#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000413
414#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000415 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000416#else
drh58ad5802011-03-23 22:02:23 +0000417 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000418#endif
dan0fd7d862011-03-29 10:04:23 +0000419#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000420
drh036ac7f2011-08-08 23:18:05 +0000421 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
422#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
423
drh90315a22011-08-10 01:52:12 +0000424 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
425#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
426
drh9ef6bc42011-11-04 02:24:02 +0000427 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
428#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
429
430 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
431#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
432
drh6226ca22015-11-24 15:06:28 +0000433 { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
dand3eaebd2012-02-13 08:50:23 +0000434#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000435
drh6226ca22015-11-24 15:06:28 +0000436 { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
437#define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
438
dan4dd51442013-08-26 14:30:25 +0000439#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
dan893c0ff2013-03-25 19:05:07 +0000440 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
drh6226ca22015-11-24 15:06:28 +0000441#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
dan893c0ff2013-03-25 19:05:07 +0000442
drhd1ab8062013-03-25 20:50:25 +0000443 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
drh6226ca22015-11-24 15:06:28 +0000444#define osMunmap ((void*(*)(void*,size_t))aSyscall[23].pCurrent)
drhd1ab8062013-03-25 20:50:25 +0000445
dane6ecd662013-04-01 17:56:59 +0000446#if HAVE_MREMAP
drhd1ab8062013-03-25 20:50:25 +0000447 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
448#else
449 { "mremap", (sqlite3_syscall_ptr)0, 0 },
450#endif
drh6226ca22015-11-24 15:06:28 +0000451#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
452
danbc760632014-03-20 09:42:09 +0000453 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
drh6226ca22015-11-24 15:06:28 +0000454#define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
danbc760632014-03-20 09:42:09 +0000455
dan245fdc62015-10-31 17:58:33 +0000456 { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
drh6226ca22015-11-24 15:06:28 +0000457#define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
dan245fdc62015-10-31 17:58:33 +0000458
dan702eec12014-06-23 10:04:58 +0000459#endif
460
drhe562be52011-03-02 18:01:10 +0000461}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000462
drh6226ca22015-11-24 15:06:28 +0000463
464/*
465** On some systems, calls to fchown() will trigger a message in a security
466** log if they come from non-root processes. So avoid calling fchown() if
467** we are not running as root.
468*/
469static int robustFchown(int fd, uid_t uid, gid_t gid){
470#if OS_VXWORKS
471 return 0;
472#else
473 return osGeteuid() ? 0 : osFchown(fd,uid,gid);
474#endif
475}
476
drh99ab3b12011-03-02 15:09:07 +0000477/*
478** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000479** "unix" VFSes. Return SQLITE_OK opon successfully updating the
480** system call pointer, or SQLITE_NOTFOUND if there is no configurable
481** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000482*/
483static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000484 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
485 const char *zName, /* Name of system call to override */
486 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000487){
drh58ad5802011-03-23 22:02:23 +0000488 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000489 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000490
491 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000492 if( zName==0 ){
493 /* If no zName is given, restore all system calls to their default
494 ** settings and return NULL
495 */
dan51438a72011-04-02 17:00:47 +0000496 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000497 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
498 if( aSyscall[i].pDefault ){
499 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000500 }
501 }
502 }else{
503 /* If zName is specified, operate on only the one system call
504 ** specified.
505 */
506 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
507 if( strcmp(zName, aSyscall[i].zName)==0 ){
508 if( aSyscall[i].pDefault==0 ){
509 aSyscall[i].pDefault = aSyscall[i].pCurrent;
510 }
drh1df30962011-03-02 19:06:42 +0000511 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000512 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
513 aSyscall[i].pCurrent = pNewFunc;
514 break;
515 }
516 }
517 }
518 return rc;
519}
520
drh1df30962011-03-02 19:06:42 +0000521/*
522** Return the value of a system call. Return NULL if zName is not a
523** recognized system call name. NULL is also returned if the system call
524** is currently undefined.
525*/
drh58ad5802011-03-23 22:02:23 +0000526static sqlite3_syscall_ptr unixGetSystemCall(
527 sqlite3_vfs *pNotUsed,
528 const char *zName
529){
530 unsigned int i;
531
532 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000533 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
534 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
535 }
536 return 0;
537}
538
539/*
540** Return the name of the first system call after zName. If zName==NULL
541** then return the name of the first system call. Return NULL if zName
542** is the last system call or if zName is not the name of a valid
543** system call.
544*/
545static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000546 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000547
548 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000549 if( zName ){
550 for(i=0; i<ArraySize(aSyscall)-1; i++){
551 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000552 }
553 }
dan0fd7d862011-03-29 10:04:23 +0000554 for(i++; i<ArraySize(aSyscall); i++){
555 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000556 }
557 return 0;
558}
559
drhad4f1e52011-03-04 15:43:57 +0000560/*
drh77a3fdc2013-08-30 14:24:12 +0000561** Do not accept any file descriptor less than this value, in order to avoid
562** opening database file using file descriptors that are commonly used for
563** standard input, output, and error.
564*/
565#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
566# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
567#endif
568
569/*
drh8c815d12012-02-13 20:16:37 +0000570** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000571** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000572**
573** If the file creation mode "m" is 0 then set it to the default for
574** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
575** 0644) as modified by the system umask. If m is not 0, then
576** make the file creation mode be exactly m ignoring the umask.
577**
578** The m parameter will be non-zero only when creating -wal, -journal,
579** and -shm files. We want those files to have *exactly* the same
580** permissions as their original database, unadulterated by the umask.
581** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
582** transaction crashes and leaves behind hot journals, then any
583** process that is able to write to the database will also be able to
584** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000585*/
drh8c815d12012-02-13 20:16:37 +0000586static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000587 int fd;
drhe1186ab2013-01-04 20:45:13 +0000588 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5128d002013-08-30 06:20:23 +0000589 while(1){
drh5adc60b2012-04-14 13:25:11 +0000590#if defined(O_CLOEXEC)
591 fd = osOpen(z,f|O_CLOEXEC,m2);
592#else
593 fd = osOpen(z,f,m2);
594#endif
drh5128d002013-08-30 06:20:23 +0000595 if( fd<0 ){
596 if( errno==EINTR ) continue;
597 break;
598 }
drh77a3fdc2013-08-30 14:24:12 +0000599 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
drh5128d002013-08-30 06:20:23 +0000600 osClose(fd);
601 sqlite3_log(SQLITE_WARNING,
602 "attempt to open \"%s\" as file descriptor %d", z, fd);
603 fd = -1;
604 if( osOpen("/dev/null", f, m)<0 ) break;
605 }
drhe1186ab2013-01-04 20:45:13 +0000606 if( fd>=0 ){
607 if( m!=0 ){
608 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000609 if( osFstat(fd, &statbuf)==0
610 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000611 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000612 ){
drhe1186ab2013-01-04 20:45:13 +0000613 osFchmod(fd, m);
614 }
615 }
drh5adc60b2012-04-14 13:25:11 +0000616#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000617 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000618#endif
drhe1186ab2013-01-04 20:45:13 +0000619 }
drh5adc60b2012-04-14 13:25:11 +0000620 return fd;
drhad4f1e52011-03-04 15:43:57 +0000621}
danielk197713adf8a2004-06-03 16:08:41 +0000622
drh107886a2008-11-21 22:21:50 +0000623/*
dan9359c7b2009-08-21 08:29:10 +0000624** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000625** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000626** vxworksFileId objects used by this file, all of which may be
627** shared by multiple threads.
628**
629** Function unixMutexHeld() is used to assert() that the global mutex
630** is held when required. This function is only used as part of assert()
631** statements. e.g.
632**
633** unixEnterMutex()
634** assert( unixMutexHeld() );
635** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000636*/
637static void unixEnterMutex(void){
mistachkin93de6532015-07-03 21:38:09 +0000638 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
drh107886a2008-11-21 22:21:50 +0000639}
640static void unixLeaveMutex(void){
mistachkin93de6532015-07-03 21:38:09 +0000641 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
drh107886a2008-11-21 22:21:50 +0000642}
dan9359c7b2009-08-21 08:29:10 +0000643#ifdef SQLITE_DEBUG
644static int unixMutexHeld(void) {
mistachkin93de6532015-07-03 21:38:09 +0000645 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
dan9359c7b2009-08-21 08:29:10 +0000646}
647#endif
drh107886a2008-11-21 22:21:50 +0000648
drh734c9862008-11-28 15:37:20 +0000649
mistachkinfb383e92015-04-16 03:24:38 +0000650#ifdef SQLITE_HAVE_OS_TRACE
drh734c9862008-11-28 15:37:20 +0000651/*
652** Helper function for printing out trace information from debugging
peter.d.reid60ec9142014-09-06 16:39:46 +0000653** binaries. This returns the string representation of the supplied
drh734c9862008-11-28 15:37:20 +0000654** integer lock-type.
655*/
drh308c2a52010-05-14 11:30:18 +0000656static const char *azFileLock(int eFileLock){
657 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000658 case NO_LOCK: return "NONE";
659 case SHARED_LOCK: return "SHARED";
660 case RESERVED_LOCK: return "RESERVED";
661 case PENDING_LOCK: return "PENDING";
662 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000663 }
664 return "ERROR";
665}
666#endif
667
668#ifdef SQLITE_LOCK_TRACE
669/*
670** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000671**
drh734c9862008-11-28 15:37:20 +0000672** This routine is used for troubleshooting locks on multithreaded
673** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
674** command-line option on the compiler. This code is normally
675** turned off.
676*/
677static int lockTrace(int fd, int op, struct flock *p){
678 char *zOpName, *zType;
679 int s;
680 int savedErrno;
681 if( op==F_GETLK ){
682 zOpName = "GETLK";
683 }else if( op==F_SETLK ){
684 zOpName = "SETLK";
685 }else{
drh99ab3b12011-03-02 15:09:07 +0000686 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000687 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
688 return s;
689 }
690 if( p->l_type==F_RDLCK ){
691 zType = "RDLCK";
692 }else if( p->l_type==F_WRLCK ){
693 zType = "WRLCK";
694 }else if( p->l_type==F_UNLCK ){
695 zType = "UNLCK";
696 }else{
697 assert( 0 );
698 }
699 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000700 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000701 savedErrno = errno;
702 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
703 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
704 (int)p->l_pid, s);
705 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
706 struct flock l2;
707 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000708 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000709 if( l2.l_type==F_RDLCK ){
710 zType = "RDLCK";
711 }else if( l2.l_type==F_WRLCK ){
712 zType = "WRLCK";
713 }else if( l2.l_type==F_UNLCK ){
714 zType = "UNLCK";
715 }else{
716 assert( 0 );
717 }
718 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
719 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
720 }
721 errno = savedErrno;
722 return s;
723}
drh99ab3b12011-03-02 15:09:07 +0000724#undef osFcntl
725#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000726#endif /* SQLITE_LOCK_TRACE */
727
drhff812312011-02-23 13:33:46 +0000728/*
729** Retry ftruncate() calls that fail due to EINTR
dan2ee53412014-09-06 16:49:40 +0000730**
drhe6d41732015-02-21 00:49:00 +0000731** All calls to ftruncate() within this file should be made through
732** this wrapper. On the Android platform, bypassing the logic below
733** could lead to a corrupt database.
drhff812312011-02-23 13:33:46 +0000734*/
drhff812312011-02-23 13:33:46 +0000735static int robust_ftruncate(int h, sqlite3_int64 sz){
736 int rc;
dan2ee53412014-09-06 16:49:40 +0000737#ifdef __ANDROID__
738 /* On Android, ftruncate() always uses 32-bit offsets, even if
739 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
dan524a7332014-09-06 17:06:13 +0000740 ** truncate a file to any size larger than 2GiB. Silently ignore any
dan2ee53412014-09-06 16:49:40 +0000741 ** such attempts. */
742 if( sz>(sqlite3_int64)0x7FFFFFFF ){
743 rc = SQLITE_OK;
744 }else
745#endif
drh99ab3b12011-03-02 15:09:07 +0000746 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000747 return rc;
748}
drh734c9862008-11-28 15:37:20 +0000749
750/*
751** This routine translates a standard POSIX errno code into something
752** useful to the clients of the sqlite3 functions. Specifically, it is
753** intended to translate a variety of "try again" errors into SQLITE_BUSY
754** and a variety of "please close the file descriptor NOW" errors into
755** SQLITE_IOERR
756**
757** Errors during initialization of locks, or file system support for locks,
758** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
759*/
760static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
drh91c4def2015-11-25 14:00:07 +0000761 assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
762 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
763 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
764 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
drh734c9862008-11-28 15:37:20 +0000765 switch (posixError) {
drh91c4def2015-11-25 14:00:07 +0000766 case EACCES:
drh734c9862008-11-28 15:37:20 +0000767 case EAGAIN:
768 case ETIMEDOUT:
769 case EBUSY:
770 case EINTR:
771 case ENOLCK:
772 /* random NFS retry error, unless during file system support
773 * introspection, in which it actually means what it says */
774 return SQLITE_BUSY;
775
drh734c9862008-11-28 15:37:20 +0000776 case EPERM:
777 return SQLITE_PERM;
778
drh734c9862008-11-28 15:37:20 +0000779 default:
780 return sqliteIOErr;
781 }
782}
783
784
drh734c9862008-11-28 15:37:20 +0000785/******************************************************************************
786****************** Begin Unique File ID Utility Used By VxWorks ***************
787**
788** On most versions of unix, we can get a unique ID for a file by concatenating
789** the device number and the inode number. But this does not work on VxWorks.
790** On VxWorks, a unique file id must be based on the canonical filename.
791**
792** A pointer to an instance of the following structure can be used as a
793** unique file ID in VxWorks. Each instance of this structure contains
794** a copy of the canonical filename. There is also a reference count.
795** The structure is reclaimed when the number of pointers to it drops to
796** zero.
797**
798** There are never very many files open at one time and lookups are not
799** a performance-critical path, so it is sufficient to put these
800** structures on a linked list.
801*/
802struct vxworksFileId {
803 struct vxworksFileId *pNext; /* Next in a list of them all */
804 int nRef; /* Number of references to this one */
805 int nName; /* Length of the zCanonicalName[] string */
806 char *zCanonicalName; /* Canonical filename */
807};
808
809#if OS_VXWORKS
810/*
drh9b35ea62008-11-29 02:20:26 +0000811** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000812** variable:
813*/
814static struct vxworksFileId *vxworksFileList = 0;
815
816/*
817** Simplify a filename into its canonical form
818** by making the following changes:
819**
820** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000821** * convert /./ into just /
822** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000823**
824** Changes are made in-place. Return the new name length.
825**
826** The original filename is in z[0..n-1]. Return the number of
827** characters in the simplified name.
828*/
829static int vxworksSimplifyName(char *z, int n){
830 int i, j;
831 while( n>1 && z[n-1]=='/' ){ n--; }
832 for(i=j=0; i<n; i++){
833 if( z[i]=='/' ){
834 if( z[i+1]=='/' ) continue;
835 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
836 i += 1;
837 continue;
838 }
839 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
840 while( j>0 && z[j-1]!='/' ){ j--; }
841 if( j>0 ){ j--; }
842 i += 2;
843 continue;
844 }
845 }
846 z[j++] = z[i];
847 }
848 z[j] = 0;
849 return j;
850}
851
852/*
853** Find a unique file ID for the given absolute pathname. Return
854** a pointer to the vxworksFileId object. This pointer is the unique
855** file ID.
856**
857** The nRef field of the vxworksFileId object is incremented before
858** the object is returned. A new vxworksFileId object is created
859** and added to the global list if necessary.
860**
861** If a memory allocation error occurs, return NULL.
862*/
863static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
864 struct vxworksFileId *pNew; /* search key and new file ID */
865 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
866 int n; /* Length of zAbsoluteName string */
867
868 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000869 n = (int)strlen(zAbsoluteName);
drhf3cdcdc2015-04-29 16:50:28 +0000870 pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
drh734c9862008-11-28 15:37:20 +0000871 if( pNew==0 ) return 0;
872 pNew->zCanonicalName = (char*)&pNew[1];
873 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
874 n = vxworksSimplifyName(pNew->zCanonicalName, n);
875
876 /* Search for an existing entry that matching the canonical name.
877 ** If found, increment the reference count and return a pointer to
878 ** the existing file ID.
879 */
880 unixEnterMutex();
881 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
882 if( pCandidate->nName==n
883 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
884 ){
885 sqlite3_free(pNew);
886 pCandidate->nRef++;
887 unixLeaveMutex();
888 return pCandidate;
889 }
890 }
891
892 /* No match was found. We will make a new file ID */
893 pNew->nRef = 1;
894 pNew->nName = n;
895 pNew->pNext = vxworksFileList;
896 vxworksFileList = pNew;
897 unixLeaveMutex();
898 return pNew;
899}
900
901/*
902** Decrement the reference count on a vxworksFileId object. Free
903** the object when the reference count reaches zero.
904*/
905static void vxworksReleaseFileId(struct vxworksFileId *pId){
906 unixEnterMutex();
907 assert( pId->nRef>0 );
908 pId->nRef--;
909 if( pId->nRef==0 ){
910 struct vxworksFileId **pp;
911 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
912 assert( *pp==pId );
913 *pp = pId->pNext;
914 sqlite3_free(pId);
915 }
916 unixLeaveMutex();
917}
918#endif /* OS_VXWORKS */
919/*************** End of Unique File ID Utility Used By VxWorks ****************
920******************************************************************************/
921
922
923/******************************************************************************
924*************************** Posix Advisory Locking ****************************
925**
drh9b35ea62008-11-29 02:20:26 +0000926** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000927** section 6.5.2.2 lines 483 through 490 specify that when a process
928** sets or clears a lock, that operation overrides any prior locks set
929** by the same process. It does not explicitly say so, but this implies
930** that it overrides locks set by the same process using a different
931** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000932**
933** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000934** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
935**
936** Suppose ./file1 and ./file2 are really the same file (because
937** one is a hard or symbolic link to the other) then if you set
938** an exclusive lock on fd1, then try to get an exclusive lock
939** on fd2, it works. I would have expected the second lock to
940** fail since there was already a lock on the file due to fd1.
941** But not so. Since both locks came from the same process, the
942** second overrides the first, even though they were on different
943** file descriptors opened on different file names.
944**
drh734c9862008-11-28 15:37:20 +0000945** This means that we cannot use POSIX locks to synchronize file access
946** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000947** to synchronize access for threads in separate processes, but not
948** threads within the same process.
949**
950** To work around the problem, SQLite has to manage file locks internally
951** on its own. Whenever a new database is opened, we have to find the
952** specific inode of the database file (the inode is determined by the
953** st_dev and st_ino fields of the stat structure that fstat() fills in)
954** and check for locks already existing on that inode. When locks are
955** created or removed, we have to look at our own internal record of the
956** locks to see if another thread has previously set a lock on that same
957** inode.
958**
drh9b35ea62008-11-29 02:20:26 +0000959** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
960** For VxWorks, we have to use the alternative unique ID system based on
961** canonical filename and implemented in the previous division.)
962**
danielk1977ad94b582007-08-20 06:44:22 +0000963** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000964** descriptor. It is now a structure that holds the integer file
965** descriptor and a pointer to a structure that describes the internal
966** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000967** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000968** point to the same locking structure. The locking structure keeps
969** a reference count (so we will know when to delete it) and a "cnt"
970** field that tells us its internal lock status. cnt==0 means the
971** file is unlocked. cnt==-1 means the file has an exclusive lock.
972** cnt>0 means there are cnt shared locks on the file.
973**
974** Any attempt to lock or unlock a file first checks the locking
975** structure. The fcntl() system call is only invoked to set a
976** POSIX lock if the internal lock structure transitions between
977** a locked and an unlocked state.
978**
drh734c9862008-11-28 15:37:20 +0000979** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000980**
981** If you close a file descriptor that points to a file that has locks,
982** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000983** released. To work around this problem, each unixInodeInfo object
984** maintains a count of the number of pending locks on tha inode.
985** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000986** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000987** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000988** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000989** be closed and that list is walked (and cleared) when the last lock
990** clears.
991**
drh9b35ea62008-11-29 02:20:26 +0000992** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000993**
drh9b35ea62008-11-29 02:20:26 +0000994** Many older versions of linux use the LinuxThreads library which is
995** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000996** A cannot be modified or overridden by a different thread B.
997** Only thread A can modify the lock. Locking behavior is correct
998** if the appliation uses the newer Native Posix Thread Library (NPTL)
999** on linux - with NPTL a lock created by thread A can override locks
1000** in thread B. But there is no way to know at compile-time which
1001** threading library is being used. So there is no way to know at
1002** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001003** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001004** current process.
drh5fdae772004-06-29 03:29:00 +00001005**
drh8af6c222010-05-14 12:43:01 +00001006** SQLite used to support LinuxThreads. But support for LinuxThreads
1007** was dropped beginning with version 3.7.0. SQLite will still work with
1008** LinuxThreads provided that (1) there is no more than one connection
1009** per database file in the same process and (2) database connections
1010** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001011*/
1012
1013/*
1014** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001015** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001016*/
1017struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001018 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001019#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001020 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001021#else
drh107886a2008-11-21 22:21:50 +00001022 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001023#endif
1024};
1025
1026/*
drhbbd42a62004-05-22 17:41:58 +00001027** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001028** inode. Or, on LinuxThreads, there is one of these structures for
1029** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001030**
danielk1977ad94b582007-08-20 06:44:22 +00001031** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001032** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001033** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001034*/
drh8af6c222010-05-14 12:43:01 +00001035struct unixInodeInfo {
1036 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001037 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001038 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1039 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001040 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001041 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1042 int nLock; /* Number of outstanding file locks */
1043 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1044 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1045 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001046#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001047 unsigned long long sharedByte; /* for AFP simulated shared lock */
1048#endif
drh6c7d5c52008-11-21 20:32:33 +00001049#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001050 sem_t *pSem; /* Named POSIX semaphore */
1051 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001052#endif
drhbbd42a62004-05-22 17:41:58 +00001053};
1054
drhda0e7682008-07-30 15:27:54 +00001055/*
drh8af6c222010-05-14 12:43:01 +00001056** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001057*/
drhd91c68f2010-05-14 14:52:25 +00001058static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001059
drh5fdae772004-06-29 03:29:00 +00001060/*
dane18d4952011-02-21 11:46:24 +00001061**
drhaaeaa182015-11-24 15:12:47 +00001062** This function - unixLogErrorAtLine(), is only ever called via the macro
dane18d4952011-02-21 11:46:24 +00001063** unixLogError().
1064**
1065** It is invoked after an error occurs in an OS function and errno has been
1066** set. It logs a message using sqlite3_log() containing the current value of
1067** errno and, if possible, the human-readable equivalent from strerror() or
1068** strerror_r().
1069**
1070** The first argument passed to the macro should be the error code that
1071** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1072** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001073** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001074** if any.
1075*/
drh0e9365c2011-03-02 02:08:13 +00001076#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1077static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001078 int errcode, /* SQLite error code */
1079 const char *zFunc, /* Name of OS function that failed */
1080 const char *zPath, /* File path associated with error */
1081 int iLine /* Source line number where error occurred */
1082){
1083 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001084 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001085
1086 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1087 ** the strerror() function to obtain the human-readable error message
1088 ** equivalent to errno. Otherwise, use strerror_r().
1089 */
1090#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1091 char aErr[80];
1092 memset(aErr, 0, sizeof(aErr));
1093 zErr = aErr;
1094
1095 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001096 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001097 ** returns a pointer to a buffer containing the error message. That pointer
1098 ** may point to aErr[], or it may point to some static storage somewhere.
1099 ** Otherwise, assume that the system provides the POSIX version of
1100 ** strerror_r(), which always writes an error message into aErr[].
1101 **
1102 ** If the code incorrectly assumes that it is the POSIX version that is
1103 ** available, the error message will often be an empty string. Not a
1104 ** huge problem. Incorrectly concluding that the GNU version is available
1105 ** could lead to a segfault though.
1106 */
1107#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1108 zErr =
1109# endif
drh0e9365c2011-03-02 02:08:13 +00001110 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001111
1112#elif SQLITE_THREADSAFE
1113 /* This is a threadsafe build, but strerror_r() is not available. */
1114 zErr = "";
1115#else
1116 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001117 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001118#endif
1119
drh0e9365c2011-03-02 02:08:13 +00001120 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001121 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001122 "os_unix.c:%d: (%d) %s(%s) - %s",
1123 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001124 );
1125
1126 return errcode;
1127}
1128
drh0e9365c2011-03-02 02:08:13 +00001129/*
1130** Close a file descriptor.
1131**
1132** We assume that close() almost always works, since it is only in a
1133** very sick application or on a very sick platform that it might fail.
1134** If it does fail, simply leak the file descriptor, but do log the
1135** error.
1136**
1137** Note that it is not safe to retry close() after EINTR since the
1138** file descriptor might have already been reused by another thread.
1139** So we don't even try to recover from an EINTR. Just log the error
1140** and move on.
1141*/
1142static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001143 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001144 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1145 pFile ? pFile->zPath : 0, lineno);
1146 }
1147}
dane18d4952011-02-21 11:46:24 +00001148
1149/*
drhe6d41732015-02-21 00:49:00 +00001150** Set the pFile->lastErrno. Do this in a subroutine as that provides
1151** a convenient place to set a breakpoint.
drh4bf66fd2015-02-19 02:43:02 +00001152*/
1153static void storeLastErrno(unixFile *pFile, int error){
1154 pFile->lastErrno = error;
1155}
1156
1157/*
danb0ac3e32010-06-16 10:55:42 +00001158** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001159*/
drh0e9365c2011-03-02 02:08:13 +00001160static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001161 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001162 UnixUnusedFd *p;
1163 UnixUnusedFd *pNext;
1164 for(p=pInode->pUnused; p; p=pNext){
1165 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001166 robust_close(pFile, p->fd, __LINE__);
1167 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001168 }
drh0e9365c2011-03-02 02:08:13 +00001169 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001170}
1171
1172/*
drh8af6c222010-05-14 12:43:01 +00001173** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001174**
1175** The mutex entered using the unixEnterMutex() function must be held
1176** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001177*/
danb0ac3e32010-06-16 10:55:42 +00001178static void releaseInodeInfo(unixFile *pFile){
1179 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001180 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001181 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001182 pInode->nRef--;
1183 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001184 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001185 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001186 if( pInode->pPrev ){
1187 assert( pInode->pPrev->pNext==pInode );
1188 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001189 }else{
drh8af6c222010-05-14 12:43:01 +00001190 assert( inodeList==pInode );
1191 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001192 }
drh8af6c222010-05-14 12:43:01 +00001193 if( pInode->pNext ){
1194 assert( pInode->pNext->pPrev==pInode );
1195 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001196 }
drh8af6c222010-05-14 12:43:01 +00001197 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001198 }
drhbbd42a62004-05-22 17:41:58 +00001199 }
1200}
1201
1202/*
drh8af6c222010-05-14 12:43:01 +00001203** Given a file descriptor, locate the unixInodeInfo object that
1204** describes that file descriptor. Create a new one if necessary. The
1205** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001206**
dan9359c7b2009-08-21 08:29:10 +00001207** The mutex entered using the unixEnterMutex() function must be held
1208** when this function is called.
1209**
drh6c7d5c52008-11-21 20:32:33 +00001210** Return an appropriate error code.
1211*/
drh8af6c222010-05-14 12:43:01 +00001212static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001213 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001214 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001215){
1216 int rc; /* System call return code */
1217 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001218 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1219 struct stat statbuf; /* Low-level file information */
1220 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001221
dan9359c7b2009-08-21 08:29:10 +00001222 assert( unixMutexHeld() );
1223
drh6c7d5c52008-11-21 20:32:33 +00001224 /* Get low-level information about the file that we can used to
1225 ** create a unique name for the file.
1226 */
1227 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001228 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001229 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001230 storeLastErrno(pFile, errno);
drh40fe8d32015-11-30 20:36:26 +00001231#if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
drh6c7d5c52008-11-21 20:32:33 +00001232 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1233#endif
1234 return SQLITE_IOERR;
1235 }
1236
drheb0d74f2009-02-03 15:27:02 +00001237#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001238 /* On OS X on an msdos filesystem, the inode number is reported
1239 ** incorrectly for zero-size files. See ticket #3260. To work
1240 ** around this problem (we consider it a bug in OS X, not SQLite)
1241 ** we always increase the file size to 1 by writing a single byte
1242 ** prior to accessing the inode number. The one byte written is
1243 ** an ASCII 'S' character which also happens to be the first byte
1244 ** in the header of every SQLite database. In this way, if there
1245 ** is a race condition such that another thread has already populated
1246 ** the first page of the database, no damage is done.
1247 */
drh7ed97b92010-01-20 13:07:21 +00001248 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001249 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001250 if( rc!=1 ){
drh4bf66fd2015-02-19 02:43:02 +00001251 storeLastErrno(pFile, errno);
drheb0d74f2009-02-03 15:27:02 +00001252 return SQLITE_IOERR;
1253 }
drh99ab3b12011-03-02 15:09:07 +00001254 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001255 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001256 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001257 return SQLITE_IOERR;
1258 }
1259 }
drheb0d74f2009-02-03 15:27:02 +00001260#endif
drh6c7d5c52008-11-21 20:32:33 +00001261
drh8af6c222010-05-14 12:43:01 +00001262 memset(&fileId, 0, sizeof(fileId));
1263 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001264#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001265 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001266#else
drh8af6c222010-05-14 12:43:01 +00001267 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001268#endif
drh8af6c222010-05-14 12:43:01 +00001269 pInode = inodeList;
1270 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1271 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001272 }
drh8af6c222010-05-14 12:43:01 +00001273 if( pInode==0 ){
drhf3cdcdc2015-04-29 16:50:28 +00001274 pInode = sqlite3_malloc64( sizeof(*pInode) );
drh8af6c222010-05-14 12:43:01 +00001275 if( pInode==0 ){
1276 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001277 }
drh8af6c222010-05-14 12:43:01 +00001278 memset(pInode, 0, sizeof(*pInode));
1279 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1280 pInode->nRef = 1;
1281 pInode->pNext = inodeList;
1282 pInode->pPrev = 0;
1283 if( inodeList ) inodeList->pPrev = pInode;
1284 inodeList = pInode;
1285 }else{
1286 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001287 }
drh8af6c222010-05-14 12:43:01 +00001288 *ppInode = pInode;
1289 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001290}
drh6c7d5c52008-11-21 20:32:33 +00001291
drhb959a012013-12-07 12:29:22 +00001292/*
1293** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1294*/
1295static int fileHasMoved(unixFile *pFile){
drh61ffea52014-08-12 12:19:25 +00001296#if OS_VXWORKS
1297 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1298#else
drhb959a012013-12-07 12:29:22 +00001299 struct stat buf;
1300 return pFile->pInode!=0 &&
drh61ffea52014-08-12 12:19:25 +00001301 (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
drh91be7dc2014-08-11 13:53:30 +00001302#endif
drhb959a012013-12-07 12:29:22 +00001303}
1304
aswift5b1a2562008-08-22 00:22:35 +00001305
1306/*
drhfbc7e882013-04-11 01:16:15 +00001307** Check a unixFile that is a database. Verify the following:
1308**
1309** (1) There is exactly one hard link on the file
1310** (2) The file is not a symbolic link
1311** (3) The file has not been renamed or unlinked
1312**
1313** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1314*/
1315static void verifyDbFile(unixFile *pFile){
1316 struct stat buf;
1317 int rc;
drhfbc7e882013-04-11 01:16:15 +00001318 rc = osFstat(pFile->h, &buf);
1319 if( rc!=0 ){
1320 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001321 return;
1322 }
drh3044b512014-06-16 16:41:52 +00001323 if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
drhfbc7e882013-04-11 01:16:15 +00001324 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001325 return;
1326 }
1327 if( buf.st_nlink>1 ){
1328 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001329 return;
1330 }
drhb959a012013-12-07 12:29:22 +00001331 if( fileHasMoved(pFile) ){
drhfbc7e882013-04-11 01:16:15 +00001332 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001333 return;
1334 }
1335}
1336
1337
1338/*
danielk197713adf8a2004-06-03 16:08:41 +00001339** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001340** file by this or any other process. If such a lock is held, set *pResOut
1341** to a non-zero value otherwise *pResOut is set to zero. The return value
1342** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001343*/
danielk1977861f7452008-06-05 11:39:11 +00001344static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001345 int rc = SQLITE_OK;
1346 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001347 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001348
danielk1977861f7452008-06-05 11:39:11 +00001349 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1350
drh054889e2005-11-30 03:20:31 +00001351 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00001352 assert( pFile->eFileLock<=SHARED_LOCK );
drh8af6c222010-05-14 12:43:01 +00001353 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001354
1355 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001356 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001357 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001358 }
1359
drh2ac3ee92004-06-07 16:27:46 +00001360 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001361 */
danielk197709480a92009-02-09 05:32:32 +00001362#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001363 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001364 struct flock lock;
1365 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001366 lock.l_start = RESERVED_BYTE;
1367 lock.l_len = 1;
1368 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001369 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1370 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001371 storeLastErrno(pFile, errno);
aswift5b1a2562008-08-22 00:22:35 +00001372 } else if( lock.l_type!=F_UNLCK ){
1373 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001374 }
1375 }
danielk197709480a92009-02-09 05:32:32 +00001376#endif
danielk197713adf8a2004-06-03 16:08:41 +00001377
drh6c7d5c52008-11-21 20:32:33 +00001378 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001379 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001380
aswift5b1a2562008-08-22 00:22:35 +00001381 *pResOut = reserved;
1382 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001383}
1384
1385/*
drha7e61d82011-03-12 17:02:57 +00001386** Attempt to set a system-lock on the file pFile. The lock is
1387** described by pLock.
1388**
drh77197112011-03-15 19:08:48 +00001389** If the pFile was opened read/write from unix-excl, then the only lock
1390** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001391** the first time any lock is attempted. All subsequent system locking
1392** operations become no-ops. Locking operations still happen internally,
1393** in order to coordinate access between separate database connections
1394** within this process, but all of that is handled in memory and the
1395** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001396**
1397** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1398** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1399** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001400**
1401** Zero is returned if the call completes successfully, or -1 if a call
1402** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001403*/
1404static int unixFileLock(unixFile *pFile, struct flock *pLock){
1405 int rc;
drh3cb93392011-03-12 18:10:44 +00001406 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001407 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001408 assert( pInode!=0 );
drh50358ad2015-12-02 01:04:33 +00001409 if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
drh3cb93392011-03-12 18:10:44 +00001410 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001411 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001412 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001413 lock.l_whence = SEEK_SET;
1414 lock.l_start = SHARED_FIRST;
1415 lock.l_len = SHARED_SIZE;
1416 lock.l_type = F_WRLCK;
1417 rc = osFcntl(pFile->h, F_SETLK, &lock);
1418 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001419 pInode->bProcessLock = 1;
1420 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001421 }else{
1422 rc = 0;
1423 }
1424 }else{
1425 rc = osFcntl(pFile->h, F_SETLK, pLock);
1426 }
1427 return rc;
1428}
1429
1430/*
drh308c2a52010-05-14 11:30:18 +00001431** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001432** of the following:
1433**
drh2ac3ee92004-06-07 16:27:46 +00001434** (1) SHARED_LOCK
1435** (2) RESERVED_LOCK
1436** (3) PENDING_LOCK
1437** (4) EXCLUSIVE_LOCK
1438**
drhb3e04342004-06-08 00:47:47 +00001439** Sometimes when requesting one lock state, additional lock states
1440** are inserted in between. The locking might fail on one of the later
1441** transitions leaving the lock state different from what it started but
1442** still short of its goal. The following chart shows the allowed
1443** transitions and the inserted intermediate states:
1444**
1445** UNLOCKED -> SHARED
1446** SHARED -> RESERVED
1447** SHARED -> (PENDING) -> EXCLUSIVE
1448** RESERVED -> (PENDING) -> EXCLUSIVE
1449** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001450**
drha6abd042004-06-09 17:37:22 +00001451** This routine will only increase a lock. Use the sqlite3OsUnlock()
1452** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001453*/
drh308c2a52010-05-14 11:30:18 +00001454static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001455 /* The following describes the implementation of the various locks and
1456 ** lock transitions in terms of the POSIX advisory shared and exclusive
1457 ** lock primitives (called read-locks and write-locks below, to avoid
1458 ** confusion with SQLite lock names). The algorithms are complicated
1459 ** slightly in order to be compatible with windows systems simultaneously
1460 ** accessing the same database file, in case that is ever required.
1461 **
1462 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1463 ** byte', each single bytes at well known offsets, and the 'shared byte
1464 ** range', a range of 510 bytes at a well known offset.
1465 **
1466 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1467 ** byte'. If this is successful, a random byte from the 'shared byte
1468 ** range' is read-locked and the lock on the 'pending byte' released.
1469 **
danielk197790ba3bd2004-06-25 08:32:25 +00001470 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1471 ** A RESERVED lock is implemented by grabbing a write-lock on the
1472 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001473 **
1474 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001475 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1476 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1477 ** obtained, but existing SHARED locks are allowed to persist. A process
1478 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1479 ** This property is used by the algorithm for rolling back a journal file
1480 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001481 **
danielk197790ba3bd2004-06-25 08:32:25 +00001482 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1483 ** implemented by obtaining a write-lock on the entire 'shared byte
1484 ** range'. Since all other locks require a read-lock on one of the bytes
1485 ** within this range, this ensures that no other locks are held on the
1486 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001487 **
1488 ** The reason a single byte cannot be used instead of the 'shared byte
1489 ** range' is that some versions of windows do not support read-locks. By
1490 ** locking a random byte from a range, concurrent SHARED locks may exist
1491 ** even if the locking primitive used is always a write-lock.
1492 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001493 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001494 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001495 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001496 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001497 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001498
drh054889e2005-11-30 03:20:31 +00001499 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001500 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1501 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh91eb93c2015-03-03 19:56:20 +00001502 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001503 osGetpid(0)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001504
1505 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001506 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001507 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001508 */
drh308c2a52010-05-14 11:30:18 +00001509 if( pFile->eFileLock>=eFileLock ){
1510 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1511 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001512 return SQLITE_OK;
1513 }
1514
drh0c2694b2009-09-03 16:23:44 +00001515 /* Make sure the locking sequence is correct.
1516 ** (1) We never move from unlocked to anything higher than shared lock.
1517 ** (2) SQLite never explicitly requests a pendig lock.
1518 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001519 */
drh308c2a52010-05-14 11:30:18 +00001520 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1521 assert( eFileLock!=PENDING_LOCK );
1522 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001523
drh8af6c222010-05-14 12:43:01 +00001524 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001525 */
drh6c7d5c52008-11-21 20:32:33 +00001526 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001527 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001528
danielk1977ad94b582007-08-20 06:44:22 +00001529 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001530 ** handle that precludes the requested lock, return BUSY.
1531 */
drh8af6c222010-05-14 12:43:01 +00001532 if( (pFile->eFileLock!=pInode->eFileLock &&
1533 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001534 ){
1535 rc = SQLITE_BUSY;
1536 goto end_lock;
1537 }
1538
1539 /* If a SHARED lock is requested, and some thread using this PID already
1540 ** has a SHARED or RESERVED lock, then increment reference counts and
1541 ** return SQLITE_OK.
1542 */
drh308c2a52010-05-14 11:30:18 +00001543 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001544 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001545 assert( eFileLock==SHARED_LOCK );
1546 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001547 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001548 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001549 pInode->nShared++;
1550 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001551 goto end_lock;
1552 }
1553
danielk19779a1d0ab2004-06-01 14:09:28 +00001554
drh3cde3bb2004-06-12 02:17:14 +00001555 /* A PENDING lock is needed before acquiring a SHARED lock and before
1556 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1557 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001558 */
drh0c2694b2009-09-03 16:23:44 +00001559 lock.l_len = 1L;
1560 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001561 if( eFileLock==SHARED_LOCK
1562 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001563 ){
drh308c2a52010-05-14 11:30:18 +00001564 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001565 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001566 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001567 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001568 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001569 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001570 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001571 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001572 goto end_lock;
1573 }
drh3cde3bb2004-06-12 02:17:14 +00001574 }
1575
1576
1577 /* If control gets to this point, then actually go ahead and make
1578 ** operating system calls for the specified lock.
1579 */
drh308c2a52010-05-14 11:30:18 +00001580 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001581 assert( pInode->nShared==0 );
1582 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001583 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001584
drh2ac3ee92004-06-07 16:27:46 +00001585 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001586 lock.l_start = SHARED_FIRST;
1587 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001588 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001589 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001590 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001591 }
dan661d71a2011-03-30 19:08:03 +00001592
drh2ac3ee92004-06-07 16:27:46 +00001593 /* Drop the temporary PENDING lock */
1594 lock.l_start = PENDING_BYTE;
1595 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001596 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001597 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1598 /* This could happen with a network mount */
1599 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001600 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001601 }
dan661d71a2011-03-30 19:08:03 +00001602
1603 if( rc ){
1604 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001605 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001606 }
dan661d71a2011-03-30 19:08:03 +00001607 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001608 }else{
drh308c2a52010-05-14 11:30:18 +00001609 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001610 pInode->nLock++;
1611 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001612 }
drh8af6c222010-05-14 12:43:01 +00001613 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001614 /* We are trying for an exclusive lock but another thread in this
1615 ** same process is still holding a shared lock. */
1616 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001617 }else{
drh3cde3bb2004-06-12 02:17:14 +00001618 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001619 ** assumed that there is a SHARED or greater lock on the file
1620 ** already.
1621 */
drh308c2a52010-05-14 11:30:18 +00001622 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001623 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001624
1625 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1626 if( eFileLock==RESERVED_LOCK ){
1627 lock.l_start = RESERVED_BYTE;
1628 lock.l_len = 1L;
1629 }else{
1630 lock.l_start = SHARED_FIRST;
1631 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001632 }
dan661d71a2011-03-30 19:08:03 +00001633
1634 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001635 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001636 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001637 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001638 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001639 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001640 }
drhbbd42a62004-05-22 17:41:58 +00001641 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001642
drh8f941bc2009-01-14 23:03:40 +00001643
drhd3d8c042012-05-29 17:02:40 +00001644#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001645 /* Set up the transaction-counter change checking flags when
1646 ** transitioning from a SHARED to a RESERVED lock. The change
1647 ** from SHARED to RESERVED marks the beginning of a normal
1648 ** write operation (not a hot journal rollback).
1649 */
1650 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001651 && pFile->eFileLock<=SHARED_LOCK
1652 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001653 ){
1654 pFile->transCntrChng = 0;
1655 pFile->dbUpdate = 0;
1656 pFile->inNormalWrite = 1;
1657 }
1658#endif
1659
1660
danielk1977ecb2a962004-06-02 06:30:16 +00001661 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001662 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001663 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001664 }else if( eFileLock==EXCLUSIVE_LOCK ){
1665 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001666 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001667 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001668
1669end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001670 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001671 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1672 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001673 return rc;
1674}
1675
1676/*
dan08da86a2009-08-21 17:18:03 +00001677** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001678** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001679*/
1680static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001681 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001682 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001683 p->pNext = pInode->pUnused;
1684 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001685 pFile->h = -1;
1686 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001687}
1688
1689/*
drh308c2a52010-05-14 11:30:18 +00001690** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001691** must be either NO_LOCK or SHARED_LOCK.
1692**
1693** If the locking level of the file descriptor is already at or below
1694** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001695**
1696** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1697** the byte range is divided into 2 parts and the first part is unlocked then
1698** set to a read lock, then the other part is simply unlocked. This works
1699** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1700** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001701*/
drha7e61d82011-03-12 17:02:57 +00001702static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001703 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001704 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001705 struct flock lock;
1706 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001707
drh054889e2005-11-30 03:20:31 +00001708 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001709 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001710 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001711 osGetpid(0)));
drha6abd042004-06-09 17:37:22 +00001712
drh308c2a52010-05-14 11:30:18 +00001713 assert( eFileLock<=SHARED_LOCK );
1714 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001715 return SQLITE_OK;
1716 }
drh6c7d5c52008-11-21 20:32:33 +00001717 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001718 pInode = pFile->pInode;
1719 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001720 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001721 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001722
drhd3d8c042012-05-29 17:02:40 +00001723#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001724 /* When reducing a lock such that other processes can start
1725 ** reading the database file again, make sure that the
1726 ** transaction counter was updated if any part of the database
1727 ** file changed. If the transaction counter is not updated,
1728 ** other connections to the same file might not realize that
1729 ** the file has changed and hence might not know to flush their
1730 ** cache. The use of a stale cache can lead to database corruption.
1731 */
drh8f941bc2009-01-14 23:03:40 +00001732 pFile->inNormalWrite = 0;
1733#endif
1734
drh7ed97b92010-01-20 13:07:21 +00001735 /* downgrading to a shared lock on NFS involves clearing the write lock
1736 ** before establishing the readlock - to avoid a race condition we downgrade
1737 ** the lock in 2 blocks, so that part of the range will be covered by a
1738 ** write lock until the rest is covered by a read lock:
1739 ** 1: [WWWWW]
1740 ** 2: [....W]
1741 ** 3: [RRRRW]
1742 ** 4: [RRRR.]
1743 */
drh308c2a52010-05-14 11:30:18 +00001744 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001745#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001746 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001747 assert( handleNFSUnlock==0 );
1748#endif
1749#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001750 if( handleNFSUnlock ){
drha712b4b2015-02-19 16:12:04 +00001751 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001752 off_t divSize = SHARED_SIZE - 1;
1753
1754 lock.l_type = F_UNLCK;
1755 lock.l_whence = SEEK_SET;
1756 lock.l_start = SHARED_FIRST;
1757 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001758 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001759 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001760 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001761 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001762 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001763 }
drh7ed97b92010-01-20 13:07:21 +00001764 lock.l_type = F_RDLCK;
1765 lock.l_whence = SEEK_SET;
1766 lock.l_start = SHARED_FIRST;
1767 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001768 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001769 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001770 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1771 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001772 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001773 }
1774 goto end_unlock;
1775 }
1776 lock.l_type = F_UNLCK;
1777 lock.l_whence = SEEK_SET;
1778 lock.l_start = SHARED_FIRST+divSize;
1779 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001780 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001781 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001782 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001783 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001784 goto end_unlock;
1785 }
drh30f776f2011-02-25 03:25:07 +00001786 }else
1787#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1788 {
drh7ed97b92010-01-20 13:07:21 +00001789 lock.l_type = F_RDLCK;
1790 lock.l_whence = SEEK_SET;
1791 lock.l_start = SHARED_FIRST;
1792 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001793 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001794 /* In theory, the call to unixFileLock() cannot fail because another
1795 ** process is holding an incompatible lock. If it does, this
1796 ** indicates that the other process is not following the locking
1797 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1798 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1799 ** an assert to fail). */
1800 rc = SQLITE_IOERR_RDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001801 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00001802 goto end_unlock;
1803 }
drh9c105bb2004-10-02 20:38:28 +00001804 }
1805 }
drhbbd42a62004-05-22 17:41:58 +00001806 lock.l_type = F_UNLCK;
1807 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001808 lock.l_start = PENDING_BYTE;
1809 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001810 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001811 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001812 }else{
danea83bc62011-04-01 11:56:32 +00001813 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001814 storeLastErrno(pFile, errno);
drhcd731cf2009-03-28 23:23:02 +00001815 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001816 }
drhbbd42a62004-05-22 17:41:58 +00001817 }
drh308c2a52010-05-14 11:30:18 +00001818 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001819 /* Decrement the shared lock counter. Release the lock using an
1820 ** OS call only when all threads in this same process have released
1821 ** the lock.
1822 */
drh8af6c222010-05-14 12:43:01 +00001823 pInode->nShared--;
1824 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001825 lock.l_type = F_UNLCK;
1826 lock.l_whence = SEEK_SET;
1827 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001828 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001829 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001830 }else{
danea83bc62011-04-01 11:56:32 +00001831 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001832 storeLastErrno(pFile, errno);
drh8af6c222010-05-14 12:43:01 +00001833 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001834 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001835 }
drha6abd042004-06-09 17:37:22 +00001836 }
1837
drhbbd42a62004-05-22 17:41:58 +00001838 /* Decrement the count of locks against this same file. When the
1839 ** count reaches zero, close any other file descriptors whose close
1840 ** was deferred because of outstanding locks.
1841 */
drh8af6c222010-05-14 12:43:01 +00001842 pInode->nLock--;
1843 assert( pInode->nLock>=0 );
1844 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001845 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001846 }
1847 }
drhf2f105d2012-08-20 15:53:54 +00001848
aswift5b1a2562008-08-22 00:22:35 +00001849end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001850 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001851 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001852 return rc;
drhbbd42a62004-05-22 17:41:58 +00001853}
1854
1855/*
drh308c2a52010-05-14 11:30:18 +00001856** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001857** must be either NO_LOCK or SHARED_LOCK.
1858**
1859** If the locking level of the file descriptor is already at or below
1860** the requested locking level, this routine is a no-op.
1861*/
drh308c2a52010-05-14 11:30:18 +00001862static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00001863#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00001864 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00001865#endif
drha7e61d82011-03-12 17:02:57 +00001866 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001867}
1868
mistachkine98844f2013-08-24 00:59:24 +00001869#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001870static int unixMapfile(unixFile *pFd, i64 nByte);
1871static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00001872#endif
danf23da962013-03-23 21:00:41 +00001873
drh7ed97b92010-01-20 13:07:21 +00001874/*
danielk1977e339d652008-06-28 11:23:00 +00001875** This function performs the parts of the "close file" operation
1876** common to all locking schemes. It closes the directory and file
1877** handles, if they are valid, and sets all fields of the unixFile
1878** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001879**
1880** It is *not* necessary to hold the mutex when this routine is called,
1881** even on VxWorks. A mutex will be acquired on VxWorks by the
1882** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001883*/
1884static int closeUnixFile(sqlite3_file *id){
1885 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00001886#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001887 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00001888#endif
dan661d71a2011-03-30 19:08:03 +00001889 if( pFile->h>=0 ){
1890 robust_close(pFile, pFile->h, __LINE__);
1891 pFile->h = -1;
1892 }
1893#if OS_VXWORKS
1894 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001895 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001896 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001897 }
1898 vxworksReleaseFileId(pFile->pId);
1899 pFile->pId = 0;
1900 }
1901#endif
drh0bdbc902014-06-16 18:35:06 +00001902#ifdef SQLITE_UNLINK_AFTER_CLOSE
1903 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
1904 osUnlink(pFile->zPath);
1905 sqlite3_free(*(char**)&pFile->zPath);
1906 pFile->zPath = 0;
1907 }
1908#endif
dan661d71a2011-03-30 19:08:03 +00001909 OSTRACE(("CLOSE %-3d\n", pFile->h));
1910 OpenCounter(-1);
1911 sqlite3_free(pFile->pUnused);
1912 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001913 return SQLITE_OK;
1914}
1915
1916/*
danielk1977e3026632004-06-22 11:29:02 +00001917** Close a file.
1918*/
danielk197762079062007-08-15 17:08:46 +00001919static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001920 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001921 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00001922 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00001923 unixUnlock(id, NO_LOCK);
1924 unixEnterMutex();
1925
1926 /* unixFile.pInode is always valid here. Otherwise, a different close
1927 ** routine (e.g. nolockClose()) would be called instead.
1928 */
1929 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1930 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1931 /* If there are outstanding locks, do not actually close the file just
1932 ** yet because that would clear those locks. Instead, add the file
1933 ** descriptor to pInode->pUnused list. It will be automatically closed
1934 ** when the last lock is cleared.
1935 */
1936 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001937 }
dan661d71a2011-03-30 19:08:03 +00001938 releaseInodeInfo(pFile);
1939 rc = closeUnixFile(id);
1940 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001941 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001942}
1943
drh734c9862008-11-28 15:37:20 +00001944/************** End of the posix advisory lock implementation *****************
1945******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001946
drh734c9862008-11-28 15:37:20 +00001947/******************************************************************************
1948****************************** No-op Locking **********************************
1949**
1950** Of the various locking implementations available, this is by far the
1951** simplest: locking is ignored. No attempt is made to lock the database
1952** file for reading or writing.
1953**
1954** This locking mode is appropriate for use on read-only databases
1955** (ex: databases that are burned into CD-ROM, for example.) It can
1956** also be used if the application employs some external mechanism to
1957** prevent simultaneous access of the same database by two or more
1958** database connections. But there is a serious risk of database
1959** corruption if this locking mode is used in situations where multiple
1960** database connections are accessing the same database file at the same
1961** time and one or more of those connections are writing.
1962*/
drhbfe66312006-10-03 17:40:40 +00001963
drh734c9862008-11-28 15:37:20 +00001964static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1965 UNUSED_PARAMETER(NotUsed);
1966 *pResOut = 0;
1967 return SQLITE_OK;
1968}
drh734c9862008-11-28 15:37:20 +00001969static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1970 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1971 return SQLITE_OK;
1972}
drh734c9862008-11-28 15:37:20 +00001973static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1974 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1975 return SQLITE_OK;
1976}
1977
1978/*
drh9b35ea62008-11-29 02:20:26 +00001979** Close the file.
drh734c9862008-11-28 15:37:20 +00001980*/
1981static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001982 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001983}
1984
1985/******************* End of the no-op lock implementation *********************
1986******************************************************************************/
1987
1988/******************************************************************************
1989************************* Begin dot-file Locking ******************************
1990**
mistachkin48864df2013-03-21 21:20:32 +00001991** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00001992** files (really a directory) to control access to the database. This works
1993** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00001994**
1995** (1) There is zero concurrency. A single reader blocks all other
1996** connections from reading or writing the database.
1997**
1998** (2) An application crash or power loss can leave stale lock files
1999** sitting around that need to be cleared manually.
2000**
2001** Nevertheless, a dotlock is an appropriate locking mode for use if no
2002** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002003**
drh9ef6bc42011-11-04 02:24:02 +00002004** Dotfile locking works by creating a subdirectory in the same directory as
2005** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002006** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002007** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002008*/
2009
2010/*
2011** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002012** lock directory.
drh734c9862008-11-28 15:37:20 +00002013*/
2014#define DOTLOCK_SUFFIX ".lock"
2015
drh7708e972008-11-29 00:56:52 +00002016/*
2017** This routine checks if there is a RESERVED lock held on the specified
2018** file by this or any other process. If such a lock is held, set *pResOut
2019** to a non-zero value otherwise *pResOut is set to zero. The return value
2020** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2021**
2022** In dotfile locking, either a lock exists or it does not. So in this
2023** variation of CheckReservedLock(), *pResOut is set to true if any lock
2024** is held on the file and false if the file is unlocked.
2025*/
drh734c9862008-11-28 15:37:20 +00002026static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2027 int rc = SQLITE_OK;
2028 int reserved = 0;
2029 unixFile *pFile = (unixFile*)id;
2030
2031 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2032
2033 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00002034 reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
drh308c2a52010-05-14 11:30:18 +00002035 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002036 *pResOut = reserved;
2037 return rc;
2038}
2039
drh7708e972008-11-29 00:56:52 +00002040/*
drh308c2a52010-05-14 11:30:18 +00002041** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002042** of the following:
2043**
2044** (1) SHARED_LOCK
2045** (2) RESERVED_LOCK
2046** (3) PENDING_LOCK
2047** (4) EXCLUSIVE_LOCK
2048**
2049** Sometimes when requesting one lock state, additional lock states
2050** are inserted in between. The locking might fail on one of the later
2051** transitions leaving the lock state different from what it started but
2052** still short of its goal. The following chart shows the allowed
2053** transitions and the inserted intermediate states:
2054**
2055** UNLOCKED -> SHARED
2056** SHARED -> RESERVED
2057** SHARED -> (PENDING) -> EXCLUSIVE
2058** RESERVED -> (PENDING) -> EXCLUSIVE
2059** PENDING -> EXCLUSIVE
2060**
2061** This routine will only increase a lock. Use the sqlite3OsUnlock()
2062** routine to lower a locking level.
2063**
2064** With dotfile locking, we really only support state (4): EXCLUSIVE.
2065** But we track the other locking levels internally.
2066*/
drh308c2a52010-05-14 11:30:18 +00002067static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002068 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002069 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002070 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002071
drh7708e972008-11-29 00:56:52 +00002072
2073 /* If we have any lock, then the lock file already exists. All we have
2074 ** to do is adjust our internal record of the lock level.
2075 */
drh308c2a52010-05-14 11:30:18 +00002076 if( pFile->eFileLock > NO_LOCK ){
2077 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002078 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002079#ifdef HAVE_UTIME
2080 utime(zLockFile, NULL);
2081#else
drh734c9862008-11-28 15:37:20 +00002082 utimes(zLockFile, NULL);
2083#endif
drh7708e972008-11-29 00:56:52 +00002084 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002085 }
2086
2087 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002088 rc = osMkdir(zLockFile, 0777);
2089 if( rc<0 ){
2090 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002091 int tErrno = errno;
2092 if( EEXIST == tErrno ){
2093 rc = SQLITE_BUSY;
2094 } else {
2095 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drha8de1e12015-11-30 00:05:39 +00002096 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00002097 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002098 }
2099 }
drh7708e972008-11-29 00:56:52 +00002100 return rc;
drh734c9862008-11-28 15:37:20 +00002101 }
drh734c9862008-11-28 15:37:20 +00002102
2103 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002104 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002105 return rc;
2106}
2107
drh7708e972008-11-29 00:56:52 +00002108/*
drh308c2a52010-05-14 11:30:18 +00002109** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002110** must be either NO_LOCK or SHARED_LOCK.
2111**
2112** If the locking level of the file descriptor is already at or below
2113** the requested locking level, this routine is a no-op.
2114**
2115** When the locking level reaches NO_LOCK, delete the lock file.
2116*/
drh308c2a52010-05-14 11:30:18 +00002117static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002118 unixFile *pFile = (unixFile*)id;
2119 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002120 int rc;
drh734c9862008-11-28 15:37:20 +00002121
2122 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002123 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002124 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002125 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002126
2127 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002128 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002129 return SQLITE_OK;
2130 }
drh7708e972008-11-29 00:56:52 +00002131
2132 /* To downgrade to shared, simply update our internal notion of the
2133 ** lock state. No need to mess with the file on disk.
2134 */
drh308c2a52010-05-14 11:30:18 +00002135 if( eFileLock==SHARED_LOCK ){
2136 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002137 return SQLITE_OK;
2138 }
2139
drh7708e972008-11-29 00:56:52 +00002140 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002141 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002142 rc = osRmdir(zLockFile);
drh9ef6bc42011-11-04 02:24:02 +00002143 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002144 int tErrno = errno;
drha8de1e12015-11-30 00:05:39 +00002145 if( tErrno==ENOENT ){
2146 rc = SQLITE_OK;
2147 }else{
danea83bc62011-04-01 11:56:32 +00002148 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002149 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002150 }
2151 return rc;
2152 }
drh308c2a52010-05-14 11:30:18 +00002153 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002154 return SQLITE_OK;
2155}
2156
2157/*
drh9b35ea62008-11-29 02:20:26 +00002158** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002159*/
2160static int dotlockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002161 unixFile *pFile = (unixFile*)id;
2162 assert( id!=0 );
2163 dotlockUnlock(id, NO_LOCK);
2164 sqlite3_free(pFile->lockingContext);
2165 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002166}
2167/****************** End of the dot-file lock implementation *******************
2168******************************************************************************/
2169
2170/******************************************************************************
2171************************** Begin flock Locking ********************************
2172**
2173** Use the flock() system call to do file locking.
2174**
drh6b9d6dd2008-12-03 19:34:47 +00002175** flock() locking is like dot-file locking in that the various
2176** fine-grain locking levels supported by SQLite are collapsed into
2177** a single exclusive lock. In other words, SHARED, RESERVED, and
2178** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2179** still works when you do this, but concurrency is reduced since
2180** only a single process can be reading the database at a time.
2181**
drhe89b2912015-03-03 20:42:01 +00002182** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
drh734c9862008-11-28 15:37:20 +00002183*/
drhe89b2912015-03-03 20:42:01 +00002184#if SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002185
drh6b9d6dd2008-12-03 19:34:47 +00002186/*
drhff812312011-02-23 13:33:46 +00002187** Retry flock() calls that fail with EINTR
2188*/
2189#ifdef EINTR
2190static int robust_flock(int fd, int op){
2191 int rc;
2192 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2193 return rc;
2194}
2195#else
drh5c819272011-02-23 14:00:12 +00002196# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002197#endif
2198
2199
2200/*
drh6b9d6dd2008-12-03 19:34:47 +00002201** This routine checks if there is a RESERVED lock held on the specified
2202** file by this or any other process. If such a lock is held, set *pResOut
2203** to a non-zero value otherwise *pResOut is set to zero. The return value
2204** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2205*/
drh734c9862008-11-28 15:37:20 +00002206static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2207 int rc = SQLITE_OK;
2208 int reserved = 0;
2209 unixFile *pFile = (unixFile*)id;
2210
2211 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2212
2213 assert( pFile );
2214
2215 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002216 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002217 reserved = 1;
2218 }
2219
2220 /* Otherwise see if some other process holds it. */
2221 if( !reserved ){
2222 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002223 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002224 if( !lrc ){
2225 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002226 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002227 if ( lrc ) {
2228 int tErrno = errno;
2229 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002230 lrc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00002231 storeLastErrno(pFile, tErrno);
2232 rc = lrc;
drh734c9862008-11-28 15:37:20 +00002233 }
2234 } else {
2235 int tErrno = errno;
2236 reserved = 1;
2237 /* someone else might have it reserved */
2238 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2239 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002240 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002241 rc = lrc;
2242 }
2243 }
2244 }
drh308c2a52010-05-14 11:30:18 +00002245 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002246
2247#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2248 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2249 rc = SQLITE_OK;
2250 reserved=1;
2251 }
2252#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2253 *pResOut = reserved;
2254 return rc;
2255}
2256
drh6b9d6dd2008-12-03 19:34:47 +00002257/*
drh308c2a52010-05-14 11:30:18 +00002258** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002259** of the following:
2260**
2261** (1) SHARED_LOCK
2262** (2) RESERVED_LOCK
2263** (3) PENDING_LOCK
2264** (4) EXCLUSIVE_LOCK
2265**
2266** Sometimes when requesting one lock state, additional lock states
2267** are inserted in between. The locking might fail on one of the later
2268** transitions leaving the lock state different from what it started but
2269** still short of its goal. The following chart shows the allowed
2270** transitions and the inserted intermediate states:
2271**
2272** UNLOCKED -> SHARED
2273** SHARED -> RESERVED
2274** SHARED -> (PENDING) -> EXCLUSIVE
2275** RESERVED -> (PENDING) -> EXCLUSIVE
2276** PENDING -> EXCLUSIVE
2277**
2278** flock() only really support EXCLUSIVE locks. We track intermediate
2279** lock states in the sqlite3_file structure, but all locks SHARED or
2280** above are really EXCLUSIVE locks and exclude all other processes from
2281** access the file.
2282**
2283** This routine will only increase a lock. Use the sqlite3OsUnlock()
2284** routine to lower a locking level.
2285*/
drh308c2a52010-05-14 11:30:18 +00002286static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002287 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002288 unixFile *pFile = (unixFile*)id;
2289
2290 assert( pFile );
2291
2292 /* if we already have a lock, it is exclusive.
2293 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002294 if (pFile->eFileLock > NO_LOCK) {
2295 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002296 return SQLITE_OK;
2297 }
2298
2299 /* grab an exclusive lock */
2300
drhff812312011-02-23 13:33:46 +00002301 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002302 int tErrno = errno;
2303 /* didn't get, must be busy */
2304 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2305 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002306 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002307 }
2308 } else {
2309 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002310 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002311 }
drh308c2a52010-05-14 11:30:18 +00002312 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2313 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002314#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2315 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2316 rc = SQLITE_BUSY;
2317 }
2318#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2319 return rc;
2320}
2321
drh6b9d6dd2008-12-03 19:34:47 +00002322
2323/*
drh308c2a52010-05-14 11:30:18 +00002324** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002325** must be either NO_LOCK or SHARED_LOCK.
2326**
2327** If the locking level of the file descriptor is already at or below
2328** the requested locking level, this routine is a no-op.
2329*/
drh308c2a52010-05-14 11:30:18 +00002330static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002331 unixFile *pFile = (unixFile*)id;
2332
2333 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002334 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002335 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002336 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002337
2338 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002339 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002340 return SQLITE_OK;
2341 }
2342
2343 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002344 if (eFileLock==SHARED_LOCK) {
2345 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002346 return SQLITE_OK;
2347 }
2348
2349 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002350 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002351#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002352 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002353#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002354 return SQLITE_IOERR_UNLOCK;
2355 }else{
drh308c2a52010-05-14 11:30:18 +00002356 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002357 return SQLITE_OK;
2358 }
2359}
2360
2361/*
2362** Close a file.
2363*/
2364static int flockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002365 assert( id!=0 );
2366 flockUnlock(id, NO_LOCK);
2367 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002368}
2369
2370#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2371
2372/******************* End of the flock lock implementation *********************
2373******************************************************************************/
2374
2375/******************************************************************************
2376************************ Begin Named Semaphore Locking ************************
2377**
2378** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002379**
2380** Semaphore locking is like dot-lock and flock in that it really only
2381** supports EXCLUSIVE locking. Only a single process can read or write
2382** the database file at a time. This reduces potential concurrency, but
2383** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002384*/
2385#if OS_VXWORKS
2386
drh6b9d6dd2008-12-03 19:34:47 +00002387/*
2388** This routine checks if there is a RESERVED lock held on the specified
2389** file by this or any other process. If such a lock is held, set *pResOut
2390** to a non-zero value otherwise *pResOut is set to zero. The return value
2391** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2392*/
drh8cd5b252015-03-02 22:06:43 +00002393static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
drh734c9862008-11-28 15:37:20 +00002394 int rc = SQLITE_OK;
2395 int reserved = 0;
2396 unixFile *pFile = (unixFile*)id;
2397
2398 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2399
2400 assert( pFile );
2401
2402 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002403 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002404 reserved = 1;
2405 }
2406
2407 /* Otherwise see if some other process holds it. */
2408 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002409 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002410
2411 if( sem_trywait(pSem)==-1 ){
2412 int tErrno = errno;
2413 if( EAGAIN != tErrno ){
2414 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
drh4bf66fd2015-02-19 02:43:02 +00002415 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002416 } else {
2417 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002418 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002419 }
2420 }else{
2421 /* we could have it if we want it */
2422 sem_post(pSem);
2423 }
2424 }
drh308c2a52010-05-14 11:30:18 +00002425 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002426
2427 *pResOut = reserved;
2428 return rc;
2429}
2430
drh6b9d6dd2008-12-03 19:34:47 +00002431/*
drh308c2a52010-05-14 11:30:18 +00002432** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002433** of the following:
2434**
2435** (1) SHARED_LOCK
2436** (2) RESERVED_LOCK
2437** (3) PENDING_LOCK
2438** (4) EXCLUSIVE_LOCK
2439**
2440** Sometimes when requesting one lock state, additional lock states
2441** are inserted in between. The locking might fail on one of the later
2442** transitions leaving the lock state different from what it started but
2443** still short of its goal. The following chart shows the allowed
2444** transitions and the inserted intermediate states:
2445**
2446** UNLOCKED -> SHARED
2447** SHARED -> RESERVED
2448** SHARED -> (PENDING) -> EXCLUSIVE
2449** RESERVED -> (PENDING) -> EXCLUSIVE
2450** PENDING -> EXCLUSIVE
2451**
2452** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2453** lock states in the sqlite3_file structure, but all locks SHARED or
2454** above are really EXCLUSIVE locks and exclude all other processes from
2455** access the file.
2456**
2457** This routine will only increase a lock. Use the sqlite3OsUnlock()
2458** routine to lower a locking level.
2459*/
drh8cd5b252015-03-02 22:06:43 +00002460static int semXLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002461 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002462 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002463 int rc = SQLITE_OK;
2464
2465 /* if we already have a lock, it is exclusive.
2466 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002467 if (pFile->eFileLock > NO_LOCK) {
2468 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002469 rc = SQLITE_OK;
2470 goto sem_end_lock;
2471 }
2472
2473 /* lock semaphore now but bail out when already locked. */
2474 if( sem_trywait(pSem)==-1 ){
2475 rc = SQLITE_BUSY;
2476 goto sem_end_lock;
2477 }
2478
2479 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002480 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002481
2482 sem_end_lock:
2483 return rc;
2484}
2485
drh6b9d6dd2008-12-03 19:34:47 +00002486/*
drh308c2a52010-05-14 11:30:18 +00002487** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002488** must be either NO_LOCK or SHARED_LOCK.
2489**
2490** If the locking level of the file descriptor is already at or below
2491** the requested locking level, this routine is a no-op.
2492*/
drh8cd5b252015-03-02 22:06:43 +00002493static int semXUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002494 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002495 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002496
2497 assert( pFile );
2498 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002499 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002500 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002501 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002502
2503 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002504 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002505 return SQLITE_OK;
2506 }
2507
2508 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002509 if (eFileLock==SHARED_LOCK) {
2510 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002511 return SQLITE_OK;
2512 }
2513
2514 /* no, really unlock. */
2515 if ( sem_post(pSem)==-1 ) {
2516 int rc, tErrno = errno;
2517 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2518 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002519 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002520 }
2521 return rc;
2522 }
drh308c2a52010-05-14 11:30:18 +00002523 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002524 return SQLITE_OK;
2525}
2526
2527/*
2528 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002529 */
drh8cd5b252015-03-02 22:06:43 +00002530static int semXClose(sqlite3_file *id) {
drh734c9862008-11-28 15:37:20 +00002531 if( id ){
2532 unixFile *pFile = (unixFile*)id;
drh8cd5b252015-03-02 22:06:43 +00002533 semXUnlock(id, NO_LOCK);
drh734c9862008-11-28 15:37:20 +00002534 assert( pFile );
2535 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002536 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002537 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002538 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002539 }
2540 return SQLITE_OK;
2541}
2542
2543#endif /* OS_VXWORKS */
2544/*
2545** Named semaphore locking is only available on VxWorks.
2546**
2547*************** End of the named semaphore lock implementation ****************
2548******************************************************************************/
2549
2550
2551/******************************************************************************
2552*************************** Begin AFP Locking *********************************
2553**
2554** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2555** on Apple Macintosh computers - both OS9 and OSX.
2556**
2557** Third-party implementations of AFP are available. But this code here
2558** only works on OSX.
2559*/
2560
drhd2cb50b2009-01-09 21:41:17 +00002561#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002562/*
2563** The afpLockingContext structure contains all afp lock specific state
2564*/
drhbfe66312006-10-03 17:40:40 +00002565typedef struct afpLockingContext afpLockingContext;
2566struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002567 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002568 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002569};
2570
2571struct ByteRangeLockPB2
2572{
2573 unsigned long long offset; /* offset to first byte to lock */
2574 unsigned long long length; /* nbr of bytes to lock */
2575 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2576 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2577 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2578 int fd; /* file desc to assoc this lock with */
2579};
2580
drhfd131da2007-08-07 17:13:03 +00002581#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002582
drh6b9d6dd2008-12-03 19:34:47 +00002583/*
2584** This is a utility for setting or clearing a bit-range lock on an
2585** AFP filesystem.
2586**
2587** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2588*/
2589static int afpSetLock(
2590 const char *path, /* Name of the file to be locked or unlocked */
2591 unixFile *pFile, /* Open file descriptor on path */
2592 unsigned long long offset, /* First byte to be locked */
2593 unsigned long long length, /* Number of bytes to lock */
2594 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002595){
drh6b9d6dd2008-12-03 19:34:47 +00002596 struct ByteRangeLockPB2 pb;
2597 int err;
drhbfe66312006-10-03 17:40:40 +00002598
2599 pb.unLockFlag = setLockFlag ? 0 : 1;
2600 pb.startEndFlag = 0;
2601 pb.offset = offset;
2602 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002603 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002604
drh308c2a52010-05-14 11:30:18 +00002605 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002606 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002607 offset, length));
drhbfe66312006-10-03 17:40:40 +00002608 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2609 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002610 int rc;
2611 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002612 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2613 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002614#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2615 rc = SQLITE_BUSY;
2616#else
drh734c9862008-11-28 15:37:20 +00002617 rc = sqliteErrorFromPosixError(tErrno,
2618 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002619#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002620 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002621 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00002622 }
2623 return rc;
drhbfe66312006-10-03 17:40:40 +00002624 } else {
aswift5b1a2562008-08-22 00:22:35 +00002625 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002626 }
2627}
2628
drh6b9d6dd2008-12-03 19:34:47 +00002629/*
2630** This routine checks if there is a RESERVED lock held on the specified
2631** file by this or any other process. If such a lock is held, set *pResOut
2632** to a non-zero value otherwise *pResOut is set to zero. The return value
2633** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2634*/
danielk1977e339d652008-06-28 11:23:00 +00002635static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002636 int rc = SQLITE_OK;
2637 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002638 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002639 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002640
aswift5b1a2562008-08-22 00:22:35 +00002641 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2642
2643 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002644 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002645 if( context->reserved ){
2646 *pResOut = 1;
2647 return SQLITE_OK;
2648 }
drh8af6c222010-05-14 12:43:01 +00002649 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002650
2651 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002652 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002653 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002654 }
2655
2656 /* Otherwise see if some other process holds it.
2657 */
aswift5b1a2562008-08-22 00:22:35 +00002658 if( !reserved ){
2659 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002660 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002661 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002662 /* if we succeeded in taking the reserved lock, unlock it to restore
2663 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002664 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002665 } else {
2666 /* if we failed to get the lock then someone else must have it */
2667 reserved = 1;
2668 }
2669 if( IS_LOCK_ERROR(lrc) ){
2670 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002671 }
2672 }
drhbfe66312006-10-03 17:40:40 +00002673
drh7ed97b92010-01-20 13:07:21 +00002674 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002675 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002676
2677 *pResOut = reserved;
2678 return rc;
drhbfe66312006-10-03 17:40:40 +00002679}
2680
drh6b9d6dd2008-12-03 19:34:47 +00002681/*
drh308c2a52010-05-14 11:30:18 +00002682** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002683** of the following:
2684**
2685** (1) SHARED_LOCK
2686** (2) RESERVED_LOCK
2687** (3) PENDING_LOCK
2688** (4) EXCLUSIVE_LOCK
2689**
2690** Sometimes when requesting one lock state, additional lock states
2691** are inserted in between. The locking might fail on one of the later
2692** transitions leaving the lock state different from what it started but
2693** still short of its goal. The following chart shows the allowed
2694** transitions and the inserted intermediate states:
2695**
2696** UNLOCKED -> SHARED
2697** SHARED -> RESERVED
2698** SHARED -> (PENDING) -> EXCLUSIVE
2699** RESERVED -> (PENDING) -> EXCLUSIVE
2700** PENDING -> EXCLUSIVE
2701**
2702** This routine will only increase a lock. Use the sqlite3OsUnlock()
2703** routine to lower a locking level.
2704*/
drh308c2a52010-05-14 11:30:18 +00002705static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002706 int rc = SQLITE_OK;
2707 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002708 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002709 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002710
2711 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002712 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2713 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh5ac93652015-03-21 20:59:43 +00002714 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
drh339eb0b2008-03-07 15:34:11 +00002715
drhbfe66312006-10-03 17:40:40 +00002716 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002717 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002718 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002719 */
drh308c2a52010-05-14 11:30:18 +00002720 if( pFile->eFileLock>=eFileLock ){
2721 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2722 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002723 return SQLITE_OK;
2724 }
2725
2726 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002727 ** (1) We never move from unlocked to anything higher than shared lock.
2728 ** (2) SQLite never explicitly requests a pendig lock.
2729 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002730 */
drh308c2a52010-05-14 11:30:18 +00002731 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2732 assert( eFileLock!=PENDING_LOCK );
2733 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002734
drh8af6c222010-05-14 12:43:01 +00002735 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002736 */
drh6c7d5c52008-11-21 20:32:33 +00002737 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002738 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002739
2740 /* If some thread using this PID has a lock via a different unixFile*
2741 ** handle that precludes the requested lock, return BUSY.
2742 */
drh8af6c222010-05-14 12:43:01 +00002743 if( (pFile->eFileLock!=pInode->eFileLock &&
2744 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002745 ){
2746 rc = SQLITE_BUSY;
2747 goto afp_end_lock;
2748 }
2749
2750 /* If a SHARED lock is requested, and some thread using this PID already
2751 ** has a SHARED or RESERVED lock, then increment reference counts and
2752 ** return SQLITE_OK.
2753 */
drh308c2a52010-05-14 11:30:18 +00002754 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002755 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002756 assert( eFileLock==SHARED_LOCK );
2757 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002758 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002759 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002760 pInode->nShared++;
2761 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002762 goto afp_end_lock;
2763 }
drhbfe66312006-10-03 17:40:40 +00002764
2765 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002766 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2767 ** be released.
2768 */
drh308c2a52010-05-14 11:30:18 +00002769 if( eFileLock==SHARED_LOCK
2770 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002771 ){
2772 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002773 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002774 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002775 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002776 goto afp_end_lock;
2777 }
2778 }
2779
2780 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002781 ** operating system calls for the specified lock.
2782 */
drh308c2a52010-05-14 11:30:18 +00002783 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002784 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002785 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002786
drh8af6c222010-05-14 12:43:01 +00002787 assert( pInode->nShared==0 );
2788 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002789
2790 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002791 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002792 /* note that the quality of the randomness doesn't matter that much */
2793 lk = random();
drh8af6c222010-05-14 12:43:01 +00002794 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002795 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002796 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002797 if( IS_LOCK_ERROR(lrc1) ){
2798 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002799 }
aswift5b1a2562008-08-22 00:22:35 +00002800 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002801 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002802
aswift5b1a2562008-08-22 00:22:35 +00002803 if( IS_LOCK_ERROR(lrc1) ) {
drh4bf66fd2015-02-19 02:43:02 +00002804 storeLastErrno(pFile, lrc1Errno);
aswift5b1a2562008-08-22 00:22:35 +00002805 rc = lrc1;
2806 goto afp_end_lock;
2807 } else if( IS_LOCK_ERROR(lrc2) ){
2808 rc = lrc2;
2809 goto afp_end_lock;
2810 } else if( lrc1 != SQLITE_OK ) {
2811 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002812 } else {
drh308c2a52010-05-14 11:30:18 +00002813 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002814 pInode->nLock++;
2815 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002816 }
drh8af6c222010-05-14 12:43:01 +00002817 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002818 /* We are trying for an exclusive lock but another thread in this
2819 ** same process is still holding a shared lock. */
2820 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002821 }else{
2822 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2823 ** assumed that there is a SHARED or greater lock on the file
2824 ** already.
2825 */
2826 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002827 assert( 0!=pFile->eFileLock );
2828 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002829 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002830 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002831 if( !failed ){
2832 context->reserved = 1;
2833 }
drhbfe66312006-10-03 17:40:40 +00002834 }
drh308c2a52010-05-14 11:30:18 +00002835 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002836 /* Acquire an EXCLUSIVE lock */
2837
2838 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002839 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002840 */
drh6b9d6dd2008-12-03 19:34:47 +00002841 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002842 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002843 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002844 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002845 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002846 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002847 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002848 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002849 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2850 ** a critical I/O error
2851 */
2852 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2853 SQLITE_IOERR_LOCK;
2854 goto afp_end_lock;
2855 }
2856 }else{
aswift5b1a2562008-08-22 00:22:35 +00002857 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002858 }
2859 }
aswift5b1a2562008-08-22 00:22:35 +00002860 if( failed ){
2861 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002862 }
2863 }
2864
2865 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002866 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002867 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002868 }else if( eFileLock==EXCLUSIVE_LOCK ){
2869 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002870 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002871 }
2872
2873afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002874 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002875 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2876 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002877 return rc;
2878}
2879
2880/*
drh308c2a52010-05-14 11:30:18 +00002881** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002882** must be either NO_LOCK or SHARED_LOCK.
2883**
2884** If the locking level of the file descriptor is already at or below
2885** the requested locking level, this routine is a no-op.
2886*/
drh308c2a52010-05-14 11:30:18 +00002887static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002888 int rc = SQLITE_OK;
2889 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002890 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002891 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2892 int skipShared = 0;
2893#ifdef SQLITE_TEST
2894 int h = pFile->h;
2895#endif
drhbfe66312006-10-03 17:40:40 +00002896
2897 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002898 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002899 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00002900 osGetpid(0)));
aswift5b1a2562008-08-22 00:22:35 +00002901
drh308c2a52010-05-14 11:30:18 +00002902 assert( eFileLock<=SHARED_LOCK );
2903 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002904 return SQLITE_OK;
2905 }
drh6c7d5c52008-11-21 20:32:33 +00002906 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002907 pInode = pFile->pInode;
2908 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002909 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002910 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002911 SimulateIOErrorBenign(1);
2912 SimulateIOError( h=(-1) )
2913 SimulateIOErrorBenign(0);
2914
drhd3d8c042012-05-29 17:02:40 +00002915#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002916 /* When reducing a lock such that other processes can start
2917 ** reading the database file again, make sure that the
2918 ** transaction counter was updated if any part of the database
2919 ** file changed. If the transaction counter is not updated,
2920 ** other connections to the same file might not realize that
2921 ** the file has changed and hence might not know to flush their
2922 ** cache. The use of a stale cache can lead to database corruption.
2923 */
2924 assert( pFile->inNormalWrite==0
2925 || pFile->dbUpdate==0
2926 || pFile->transCntrChng==1 );
2927 pFile->inNormalWrite = 0;
2928#endif
aswiftaebf4132008-11-21 00:10:35 +00002929
drh308c2a52010-05-14 11:30:18 +00002930 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002931 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002932 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002933 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002934 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002935 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2936 } else {
2937 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002938 }
2939 }
drh308c2a52010-05-14 11:30:18 +00002940 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002941 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002942 }
drh308c2a52010-05-14 11:30:18 +00002943 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002944 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2945 if( !rc ){
2946 context->reserved = 0;
2947 }
aswiftaebf4132008-11-21 00:10:35 +00002948 }
drh8af6c222010-05-14 12:43:01 +00002949 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2950 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002951 }
aswiftaebf4132008-11-21 00:10:35 +00002952 }
drh308c2a52010-05-14 11:30:18 +00002953 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002954
drh7ed97b92010-01-20 13:07:21 +00002955 /* Decrement the shared lock counter. Release the lock using an
2956 ** OS call only when all threads in this same process have released
2957 ** the lock.
2958 */
drh8af6c222010-05-14 12:43:01 +00002959 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2960 pInode->nShared--;
2961 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002962 SimulateIOErrorBenign(1);
2963 SimulateIOError( h=(-1) )
2964 SimulateIOErrorBenign(0);
2965 if( !skipShared ){
2966 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2967 }
2968 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002969 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002970 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002971 }
2972 }
2973 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002974 pInode->nLock--;
2975 assert( pInode->nLock>=0 );
2976 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002977 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002978 }
2979 }
drhbfe66312006-10-03 17:40:40 +00002980 }
drh7ed97b92010-01-20 13:07:21 +00002981
drh6c7d5c52008-11-21 20:32:33 +00002982 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002983 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002984 return rc;
2985}
2986
2987/*
drh339eb0b2008-03-07 15:34:11 +00002988** Close a file & cleanup AFP specific locking context
2989*/
danielk1977e339d652008-06-28 11:23:00 +00002990static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002991 int rc = SQLITE_OK;
drha8de1e12015-11-30 00:05:39 +00002992 unixFile *pFile = (unixFile*)id;
2993 assert( id!=0 );
2994 afpUnlock(id, NO_LOCK);
2995 unixEnterMutex();
2996 if( pFile->pInode && pFile->pInode->nLock ){
2997 /* If there are outstanding locks, do not actually close the file just
2998 ** yet because that would clear those locks. Instead, add the file
2999 ** descriptor to pInode->aPending. It will be automatically closed when
3000 ** the last lock is cleared.
3001 */
3002 setPendingFd(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003003 }
drha8de1e12015-11-30 00:05:39 +00003004 releaseInodeInfo(pFile);
3005 sqlite3_free(pFile->lockingContext);
3006 rc = closeUnixFile(id);
3007 unixLeaveMutex();
drh7ed97b92010-01-20 13:07:21 +00003008 return rc;
drhbfe66312006-10-03 17:40:40 +00003009}
3010
drhd2cb50b2009-01-09 21:41:17 +00003011#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003012/*
3013** The code above is the AFP lock implementation. The code is specific
3014** to MacOSX and does not work on other unix platforms. No alternative
3015** is available. If you don't compile for a mac, then the "unix-afp"
3016** VFS is not available.
3017**
3018********************* End of the AFP lock implementation **********************
3019******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003020
drh7ed97b92010-01-20 13:07:21 +00003021/******************************************************************************
3022*************************** Begin NFS Locking ********************************/
3023
3024#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3025/*
drh308c2a52010-05-14 11:30:18 +00003026 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003027 ** must be either NO_LOCK or SHARED_LOCK.
3028 **
3029 ** If the locking level of the file descriptor is already at or below
3030 ** the requested locking level, this routine is a no-op.
3031 */
drh308c2a52010-05-14 11:30:18 +00003032static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003033 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003034}
3035
3036#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3037/*
3038** The code above is the NFS lock implementation. The code is specific
3039** to MacOSX and does not work on other unix platforms. No alternative
3040** is available.
3041**
3042********************* End of the NFS lock implementation **********************
3043******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003044
3045/******************************************************************************
3046**************** Non-locking sqlite3_file methods *****************************
3047**
3048** The next division contains implementations for all methods of the
3049** sqlite3_file object other than the locking methods. The locking
3050** methods were defined in divisions above (one locking method per
3051** division). Those methods that are common to all locking modes
3052** are gather together into this division.
3053*/
drhbfe66312006-10-03 17:40:40 +00003054
3055/*
drh734c9862008-11-28 15:37:20 +00003056** Seek to the offset passed as the second argument, then read cnt
3057** bytes into pBuf. Return the number of bytes actually read.
3058**
3059** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3060** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3061** one system to another. Since SQLite does not define USE_PREAD
peter.d.reid60ec9142014-09-06 16:39:46 +00003062** in any form by default, we will not attempt to define _XOPEN_SOURCE.
drh734c9862008-11-28 15:37:20 +00003063** See tickets #2741 and #2681.
3064**
3065** To avoid stomping the errno value on a failed read the lastErrno value
3066** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003067*/
drh734c9862008-11-28 15:37:20 +00003068static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3069 int got;
drh58024642011-11-07 18:16:00 +00003070 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003071#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003072 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003073#endif
drh734c9862008-11-28 15:37:20 +00003074 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003075 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003076 assert( id->h>2 );
drh58024642011-11-07 18:16:00 +00003077 do{
drh734c9862008-11-28 15:37:20 +00003078#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003079 got = osPread(id->h, pBuf, cnt, offset);
3080 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003081#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003082 got = osPread64(id->h, pBuf, cnt, offset);
3083 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003084#else
drh58024642011-11-07 18:16:00 +00003085 newOffset = lseek(id->h, offset, SEEK_SET);
drhe1818ec2015-12-01 16:21:35 +00003086 SimulateIOError( newOffset = -1 );
3087 if( newOffset<0 ){
3088 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003089 return -1;
drh734c9862008-11-28 15:37:20 +00003090 }
drh58024642011-11-07 18:16:00 +00003091 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003092#endif
drh58024642011-11-07 18:16:00 +00003093 if( got==cnt ) break;
3094 if( got<0 ){
3095 if( errno==EINTR ){ got = 1; continue; }
3096 prior = 0;
drh4bf66fd2015-02-19 02:43:02 +00003097 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003098 break;
3099 }else if( got>0 ){
3100 cnt -= got;
3101 offset += got;
3102 prior += got;
3103 pBuf = (void*)(got + (char*)pBuf);
3104 }
3105 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003106 TIMER_END;
drh58024642011-11-07 18:16:00 +00003107 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3108 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3109 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003110}
3111
3112/*
drh734c9862008-11-28 15:37:20 +00003113** Read data from a file into a buffer. Return SQLITE_OK if all
3114** bytes were read successfully and SQLITE_IOERR if anything goes
3115** wrong.
drh339eb0b2008-03-07 15:34:11 +00003116*/
drh734c9862008-11-28 15:37:20 +00003117static int unixRead(
3118 sqlite3_file *id,
3119 void *pBuf,
3120 int amt,
3121 sqlite3_int64 offset
3122){
dan08da86a2009-08-21 17:18:03 +00003123 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003124 int got;
3125 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003126 assert( offset>=0 );
3127 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003128
dan08da86a2009-08-21 17:18:03 +00003129 /* If this is a database file (not a journal, master-journal or temp
3130 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003131#if 0
dane946c392009-08-22 11:39:46 +00003132 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003133 || offset>=PENDING_BYTE+512
3134 || offset+amt<=PENDING_BYTE
3135 );
dan7c246102010-04-12 19:00:29 +00003136#endif
drh08c6d442009-02-09 17:34:07 +00003137
drh9b4c59f2013-04-15 17:03:42 +00003138#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003139 /* Deal with as much of this read request as possible by transfering
3140 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003141 if( offset<pFile->mmapSize ){
3142 if( offset+amt <= pFile->mmapSize ){
3143 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3144 return SQLITE_OK;
3145 }else{
3146 int nCopy = pFile->mmapSize - offset;
3147 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3148 pBuf = &((u8 *)pBuf)[nCopy];
3149 amt -= nCopy;
3150 offset += nCopy;
3151 }
3152 }
drh6e0b6d52013-04-09 16:19:20 +00003153#endif
danf23da962013-03-23 21:00:41 +00003154
dan08da86a2009-08-21 17:18:03 +00003155 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003156 if( got==amt ){
3157 return SQLITE_OK;
3158 }else if( got<0 ){
3159 /* lastErrno set by seekAndRead */
3160 return SQLITE_IOERR_READ;
3161 }else{
drh4bf66fd2015-02-19 02:43:02 +00003162 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003163 /* Unread parts of the buffer must be zero-filled */
3164 memset(&((char*)pBuf)[got], 0, amt-got);
3165 return SQLITE_IOERR_SHORT_READ;
3166 }
3167}
3168
3169/*
dan47a2b4a2013-04-26 16:09:29 +00003170** Attempt to seek the file-descriptor passed as the first argument to
3171** absolute offset iOff, then attempt to write nBuf bytes of data from
3172** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3173** return the actual number of bytes written (which may be less than
3174** nBuf).
3175*/
3176static int seekAndWriteFd(
3177 int fd, /* File descriptor to write to */
3178 i64 iOff, /* File offset to begin writing at */
3179 const void *pBuf, /* Copy data from this buffer to the file */
3180 int nBuf, /* Size of buffer pBuf in bytes */
3181 int *piErrno /* OUT: Error number if error occurs */
3182){
3183 int rc = 0; /* Value returned by system call */
3184
3185 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003186 assert( fd>2 );
drhe1818ec2015-12-01 16:21:35 +00003187 assert( piErrno!=0 );
dan47a2b4a2013-04-26 16:09:29 +00003188 nBuf &= 0x1ffff;
3189 TIMER_START;
3190
3191#if defined(USE_PREAD)
drh2da47d32015-02-21 00:56:05 +00003192 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
dan47a2b4a2013-04-26 16:09:29 +00003193#elif defined(USE_PREAD64)
drh2da47d32015-02-21 00:56:05 +00003194 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
dan47a2b4a2013-04-26 16:09:29 +00003195#else
3196 do{
3197 i64 iSeek = lseek(fd, iOff, SEEK_SET);
drhe1818ec2015-12-01 16:21:35 +00003198 SimulateIOError( iSeek = -1 );
3199 if( iSeek<0 ){
3200 rc = -1;
3201 break;
dan47a2b4a2013-04-26 16:09:29 +00003202 }
3203 rc = osWrite(fd, pBuf, nBuf);
3204 }while( rc<0 && errno==EINTR );
3205#endif
3206
3207 TIMER_END;
3208 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3209
drhe1818ec2015-12-01 16:21:35 +00003210 if( rc<0 ) *piErrno = errno;
dan47a2b4a2013-04-26 16:09:29 +00003211 return rc;
3212}
3213
3214
3215/*
drh734c9862008-11-28 15:37:20 +00003216** Seek to the offset in id->offset then read cnt bytes into pBuf.
3217** Return the number of bytes actually read. Update the offset.
3218**
3219** To avoid stomping the errno value on a failed write the lastErrno value
3220** is set before returning.
3221*/
3222static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003223 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003224}
3225
3226
3227/*
3228** Write data from a buffer into a file. Return SQLITE_OK on success
3229** or some other error code on failure.
3230*/
3231static int unixWrite(
3232 sqlite3_file *id,
3233 const void *pBuf,
3234 int amt,
3235 sqlite3_int64 offset
3236){
dan08da86a2009-08-21 17:18:03 +00003237 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003238 int wrote = 0;
3239 assert( id );
3240 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003241
dan08da86a2009-08-21 17:18:03 +00003242 /* If this is a database file (not a journal, master-journal or temp
3243 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003244#if 0
dane946c392009-08-22 11:39:46 +00003245 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003246 || offset>=PENDING_BYTE+512
3247 || offset+amt<=PENDING_BYTE
3248 );
dan7c246102010-04-12 19:00:29 +00003249#endif
drh08c6d442009-02-09 17:34:07 +00003250
drhd3d8c042012-05-29 17:02:40 +00003251#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003252 /* If we are doing a normal write to a database file (as opposed to
3253 ** doing a hot-journal rollback or a write to some file other than a
3254 ** normal database file) then record the fact that the database
3255 ** has changed. If the transaction counter is modified, record that
3256 ** fact too.
3257 */
dan08da86a2009-08-21 17:18:03 +00003258 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003259 pFile->dbUpdate = 1; /* The database has been modified */
3260 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003261 int rc;
drh8f941bc2009-01-14 23:03:40 +00003262 char oldCntr[4];
3263 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003264 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003265 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003266 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003267 pFile->transCntrChng = 1; /* The transaction counter has changed */
3268 }
3269 }
3270 }
3271#endif
3272
danfe33e392015-11-17 20:56:06 +00003273#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003274 /* Deal with as much of this write request as possible by transfering
3275 ** data from the memory mapping using memcpy(). */
3276 if( offset<pFile->mmapSize ){
3277 if( offset+amt <= pFile->mmapSize ){
3278 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3279 return SQLITE_OK;
3280 }else{
3281 int nCopy = pFile->mmapSize - offset;
3282 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3283 pBuf = &((u8 *)pBuf)[nCopy];
3284 amt -= nCopy;
3285 offset += nCopy;
3286 }
3287 }
drh6e0b6d52013-04-09 16:19:20 +00003288#endif
drh02bf8b42015-09-01 23:51:53 +00003289
3290 while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
drh734c9862008-11-28 15:37:20 +00003291 amt -= wrote;
3292 offset += wrote;
3293 pBuf = &((char*)pBuf)[wrote];
3294 }
3295 SimulateIOError(( wrote=(-1), amt=1 ));
3296 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003297
drh02bf8b42015-09-01 23:51:53 +00003298 if( amt>wrote ){
drha21b83b2011-04-15 12:36:10 +00003299 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003300 /* lastErrno set by seekAndWrite */
3301 return SQLITE_IOERR_WRITE;
3302 }else{
drh4bf66fd2015-02-19 02:43:02 +00003303 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003304 return SQLITE_FULL;
3305 }
3306 }
dan6e09d692010-07-27 18:34:15 +00003307
drh734c9862008-11-28 15:37:20 +00003308 return SQLITE_OK;
3309}
3310
3311#ifdef SQLITE_TEST
3312/*
3313** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003314** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003315*/
3316int sqlite3_sync_count = 0;
3317int sqlite3_fullsync_count = 0;
3318#endif
3319
3320/*
drh89240432009-03-25 01:06:01 +00003321** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003322** Others do no. To be safe, we will stick with the (slightly slower)
3323** fsync(). If you know that your system does support fdatasync() correctly,
drhf7a4a1b2015-01-10 18:02:45 +00003324** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003325*/
drhf7a4a1b2015-01-10 18:02:45 +00003326#if !defined(fdatasync) && !HAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003327# define fdatasync fsync
3328#endif
3329
3330/*
3331** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3332** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3333** only available on Mac OS X. But that could change.
3334*/
3335#ifdef F_FULLFSYNC
3336# define HAVE_FULLFSYNC 1
3337#else
3338# define HAVE_FULLFSYNC 0
3339#endif
3340
3341
3342/*
3343** The fsync() system call does not work as advertised on many
3344** unix systems. The following procedure is an attempt to make
3345** it work better.
3346**
3347** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3348** for testing when we want to run through the test suite quickly.
3349** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3350** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3351** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003352**
3353** SQLite sets the dataOnly flag if the size of the file is unchanged.
3354** The idea behind dataOnly is that it should only write the file content
3355** to disk, not the inode. We only set dataOnly if the file size is
3356** unchanged since the file size is part of the inode. However,
3357** Ted Ts'o tells us that fdatasync() will also write the inode if the
3358** file size has changed. The only real difference between fdatasync()
3359** and fsync(), Ted tells us, is that fdatasync() will not flush the
3360** inode if the mtime or owner or other inode attributes have changed.
3361** We only care about the file size, not the other file attributes, so
3362** as far as SQLite is concerned, an fdatasync() is always adequate.
3363** So, we always use fdatasync() if it is available, regardless of
3364** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003365*/
3366static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003367 int rc;
drh734c9862008-11-28 15:37:20 +00003368
3369 /* The following "ifdef/elif/else/" block has the same structure as
3370 ** the one below. It is replicated here solely to avoid cluttering
3371 ** up the real code with the UNUSED_PARAMETER() macros.
3372 */
3373#ifdef SQLITE_NO_SYNC
3374 UNUSED_PARAMETER(fd);
3375 UNUSED_PARAMETER(fullSync);
3376 UNUSED_PARAMETER(dataOnly);
3377#elif HAVE_FULLFSYNC
3378 UNUSED_PARAMETER(dataOnly);
3379#else
3380 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003381 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003382#endif
3383
3384 /* Record the number of times that we do a normal fsync() and
3385 ** FULLSYNC. This is used during testing to verify that this procedure
3386 ** gets called with the correct arguments.
3387 */
3388#ifdef SQLITE_TEST
3389 if( fullSync ) sqlite3_fullsync_count++;
3390 sqlite3_sync_count++;
3391#endif
3392
3393 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
drh2c8fd122015-12-02 02:33:36 +00003394 ** no-op. But go ahead and call fstat() to validate the file
3395 ** descriptor as we need a method to provoke a failure during
3396 ** coverate testing.
drh734c9862008-11-28 15:37:20 +00003397 */
3398#ifdef SQLITE_NO_SYNC
drh2c8fd122015-12-02 02:33:36 +00003399 {
3400 struct stat buf;
3401 rc = osFstat(fd, &buf);
3402 }
drh734c9862008-11-28 15:37:20 +00003403#elif HAVE_FULLFSYNC
3404 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003405 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003406 }else{
3407 rc = 1;
3408 }
3409 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003410 ** It shouldn't be possible for fullfsync to fail on the local
3411 ** file system (on OSX), so failure indicates that FULLFSYNC
3412 ** isn't supported for this file system. So, attempt an fsync
3413 ** and (for now) ignore the overhead of a superfluous fcntl call.
3414 ** It'd be better to detect fullfsync support once and avoid
3415 ** the fcntl call every time sync is called.
3416 */
drh734c9862008-11-28 15:37:20 +00003417 if( rc ) rc = fsync(fd);
3418
drh7ed97b92010-01-20 13:07:21 +00003419#elif defined(__APPLE__)
3420 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3421 ** so currently we default to the macro that redefines fdatasync to fsync
3422 */
3423 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003424#else
drh0b647ff2009-03-21 14:41:04 +00003425 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003426#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003427 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003428 rc = fsync(fd);
3429 }
drh0b647ff2009-03-21 14:41:04 +00003430#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003431#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3432
3433 if( OS_VXWORKS && rc!= -1 ){
3434 rc = 0;
3435 }
chw97185482008-11-17 08:05:31 +00003436 return rc;
drhbfe66312006-10-03 17:40:40 +00003437}
3438
drh734c9862008-11-28 15:37:20 +00003439/*
drh0059eae2011-08-08 23:48:40 +00003440** Open a file descriptor to the directory containing file zFilename.
3441** If successful, *pFd is set to the opened file descriptor and
3442** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3443** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3444** value.
3445**
drh90315a22011-08-10 01:52:12 +00003446** The directory file descriptor is used for only one thing - to
3447** fsync() a directory to make sure file creation and deletion events
3448** are flushed to disk. Such fsyncs are not needed on newer
3449** journaling filesystems, but are required on older filesystems.
3450**
3451** This routine can be overridden using the xSetSysCall interface.
3452** The ability to override this routine was added in support of the
3453** chromium sandbox. Opening a directory is a security risk (we are
3454** told) so making it overrideable allows the chromium sandbox to
3455** replace this routine with a harmless no-op. To make this routine
3456** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3457** *pFd set to a negative number.
3458**
drh0059eae2011-08-08 23:48:40 +00003459** If SQLITE_OK is returned, the caller is responsible for closing
3460** the file descriptor *pFd using close().
3461*/
3462static int openDirectory(const char *zFilename, int *pFd){
3463 int ii;
3464 int fd = -1;
3465 char zDirname[MAX_PATHNAME+1];
3466
3467 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3468 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
drhadfa22e2015-12-02 02:08:30 +00003469 if( ii>1 ){
drh0059eae2011-08-08 23:48:40 +00003470 zDirname[ii] = '\0';
3471 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3472 if( fd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003473 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3474 }
3475 }
3476 *pFd = fd;
drhacb6b282015-11-26 10:37:05 +00003477 if( fd>=0 ) return SQLITE_OK;
3478 return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
drh0059eae2011-08-08 23:48:40 +00003479}
3480
3481/*
drh734c9862008-11-28 15:37:20 +00003482** Make sure all writes to a particular file are committed to disk.
3483**
3484** If dataOnly==0 then both the file itself and its metadata (file
3485** size, access time, etc) are synced. If dataOnly!=0 then only the
3486** file data is synced.
3487**
3488** Under Unix, also make sure that the directory entry for the file
3489** has been created by fsync-ing the directory that contains the file.
3490** If we do not do this and we encounter a power failure, the directory
3491** entry for the journal might not exist after we reboot. The next
3492** SQLite to access the file will not know that the journal exists (because
3493** the directory entry for the journal was never created) and the transaction
3494** will not roll back - possibly leading to database corruption.
3495*/
3496static int unixSync(sqlite3_file *id, int flags){
3497 int rc;
3498 unixFile *pFile = (unixFile*)id;
3499
3500 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3501 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3502
3503 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3504 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3505 || (flags&0x0F)==SQLITE_SYNC_FULL
3506 );
3507
3508 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3509 ** line is to test that doing so does not cause any problems.
3510 */
3511 SimulateDiskfullError( return SQLITE_FULL );
3512
3513 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003514 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003515 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3516 SimulateIOError( rc=1 );
3517 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003518 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003519 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003520 }
drh0059eae2011-08-08 23:48:40 +00003521
3522 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003523 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003524 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003525 */
3526 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3527 int dirfd;
3528 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003529 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003530 rc = osOpenDirectory(pFile->zPath, &dirfd);
drhacb6b282015-11-26 10:37:05 +00003531 if( rc==SQLITE_OK ){
drh0059eae2011-08-08 23:48:40 +00003532 full_fsync(dirfd, 0, 0);
3533 robust_close(pFile, dirfd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00003534 }else{
3535 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00003536 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003537 }
drh0059eae2011-08-08 23:48:40 +00003538 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003539 }
3540 return rc;
3541}
3542
3543/*
3544** Truncate an open file to a specified size
3545*/
3546static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003547 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003548 int rc;
dan6e09d692010-07-27 18:34:15 +00003549 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003550 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003551
3552 /* If the user has configured a chunk-size for this file, truncate the
3553 ** file so that it consists of an integer number of chunks (i.e. the
3554 ** actual file size after the operation may be larger than the requested
3555 ** size).
3556 */
drhb8af4b72012-04-05 20:04:39 +00003557 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003558 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3559 }
3560
dan2ee53412014-09-06 16:49:40 +00003561 rc = robust_ftruncate(pFile->h, nByte);
drh734c9862008-11-28 15:37:20 +00003562 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003563 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003564 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003565 }else{
drhd3d8c042012-05-29 17:02:40 +00003566#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003567 /* If we are doing a normal write to a database file (as opposed to
3568 ** doing a hot-journal rollback or a write to some file other than a
3569 ** normal database file) and we truncate the file to zero length,
3570 ** that effectively updates the change counter. This might happen
3571 ** when restoring a database using the backup API from a zero-length
3572 ** source.
3573 */
dan6e09d692010-07-27 18:34:15 +00003574 if( pFile->inNormalWrite && nByte==0 ){
3575 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003576 }
danf23da962013-03-23 21:00:41 +00003577#endif
danc0003312013-03-22 17:46:11 +00003578
mistachkine98844f2013-08-24 00:59:24 +00003579#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003580 /* If the file was just truncated to a size smaller than the currently
3581 ** mapped region, reduce the effective mapping size as well. SQLite will
3582 ** use read() and write() to access data beyond this point from now on.
3583 */
3584 if( nByte<pFile->mmapSize ){
3585 pFile->mmapSize = nByte;
3586 }
mistachkine98844f2013-08-24 00:59:24 +00003587#endif
drh3313b142009-11-06 04:13:18 +00003588
drh734c9862008-11-28 15:37:20 +00003589 return SQLITE_OK;
3590 }
3591}
3592
3593/*
3594** Determine the current size of a file in bytes
3595*/
3596static int unixFileSize(sqlite3_file *id, i64 *pSize){
3597 int rc;
3598 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003599 assert( id );
3600 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003601 SimulateIOError( rc=1 );
3602 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00003603 storeLastErrno((unixFile*)id, errno);
drh734c9862008-11-28 15:37:20 +00003604 return SQLITE_IOERR_FSTAT;
3605 }
3606 *pSize = buf.st_size;
3607
drh8af6c222010-05-14 12:43:01 +00003608 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003609 ** writes a single byte into that file in order to work around a bug
3610 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3611 ** layers, we need to report this file size as zero even though it is
3612 ** really 1. Ticket #3260.
3613 */
3614 if( *pSize==1 ) *pSize = 0;
3615
3616
3617 return SQLITE_OK;
3618}
3619
drhd2cb50b2009-01-09 21:41:17 +00003620#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003621/*
3622** Handler for proxy-locking file-control verbs. Defined below in the
3623** proxying locking division.
3624*/
3625static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003626#endif
drh715ff302008-12-03 22:32:44 +00003627
dan502019c2010-07-28 14:26:17 +00003628/*
3629** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003630** file-control operation. Enlarge the database to nBytes in size
3631** (rounded up to the next chunk-size). If the database is already
3632** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003633*/
3634static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003635 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003636 i64 nSize; /* Required file size */
3637 struct stat buf; /* Used to hold return values of fstat() */
3638
drh4bf66fd2015-02-19 02:43:02 +00003639 if( osFstat(pFile->h, &buf) ){
3640 return SQLITE_IOERR_FSTAT;
3641 }
dan502019c2010-07-28 14:26:17 +00003642
3643 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3644 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003645
dan502019c2010-07-28 14:26:17 +00003646#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003647 /* The code below is handling the return value of osFallocate()
3648 ** correctly. posix_fallocate() is defined to "returns zero on success,
3649 ** or an error number on failure". See the manpage for details. */
3650 int err;
drhff812312011-02-23 13:33:46 +00003651 do{
dan661d71a2011-03-30 19:08:03 +00003652 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3653 }while( err==EINTR );
3654 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003655#else
dan592bf7f2014-12-30 19:58:31 +00003656 /* If the OS does not have posix_fallocate(), fake it. Write a
3657 ** single byte to the last byte in each block that falls entirely
3658 ** within the extended region. Then, if required, a single byte
3659 ** at offset (nSize-1), to set the size of the file correctly.
3660 ** This is a similar technique to that used by glibc on systems
3661 ** that do not have a real fallocate() call.
dan502019c2010-07-28 14:26:17 +00003662 */
3663 int nBlk = buf.st_blksize; /* File-system block size */
danef3d66c2015-01-06 21:31:47 +00003664 int nWrite = 0; /* Number of bytes written by seekAndWrite */
dan502019c2010-07-28 14:26:17 +00003665 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003666
drh053378d2015-12-01 22:09:42 +00003667 iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
dan592bf7f2014-12-30 19:58:31 +00003668 assert( iWrite>=buf.st_size );
dan592bf7f2014-12-30 19:58:31 +00003669 assert( ((iWrite+1)%nBlk)==0 );
drh053378d2015-12-01 22:09:42 +00003670 for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
3671 if( iWrite>=nSize ) iWrite = nSize - 1;
danef3d66c2015-01-06 21:31:47 +00003672 nWrite = seekAndWrite(pFile, iWrite, "", 1);
dandc5df0f2011-04-06 19:15:45 +00003673 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dandc5df0f2011-04-06 19:15:45 +00003674 }
dan502019c2010-07-28 14:26:17 +00003675#endif
3676 }
3677 }
3678
mistachkine98844f2013-08-24 00:59:24 +00003679#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003680 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003681 int rc;
3682 if( pFile->szChunk<=0 ){
3683 if( robust_ftruncate(pFile->h, nByte) ){
drh4bf66fd2015-02-19 02:43:02 +00003684 storeLastErrno(pFile, errno);
danf23da962013-03-23 21:00:41 +00003685 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3686 }
3687 }
3688
3689 rc = unixMapfile(pFile, nByte);
3690 return rc;
3691 }
mistachkine98844f2013-08-24 00:59:24 +00003692#endif
danf23da962013-03-23 21:00:41 +00003693
dan502019c2010-07-28 14:26:17 +00003694 return SQLITE_OK;
3695}
danielk1977ad94b582007-08-20 06:44:22 +00003696
danielk1977e3026632004-06-22 11:29:02 +00003697/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003698** If *pArg is initially negative then this is a query. Set *pArg to
drhf12b3f62011-12-21 14:42:29 +00003699** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3700**
3701** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3702*/
3703static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3704 if( *pArg<0 ){
3705 *pArg = (pFile->ctrlFlags & mask)!=0;
3706 }else if( (*pArg)==0 ){
3707 pFile->ctrlFlags &= ~mask;
3708 }else{
3709 pFile->ctrlFlags |= mask;
3710 }
3711}
3712
drh696b33e2012-12-06 19:01:42 +00003713/* Forward declaration */
3714static int unixGetTempname(int nBuf, char *zBuf);
3715
drhf12b3f62011-12-21 14:42:29 +00003716/*
drh9e33c2c2007-08-31 18:34:59 +00003717** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003718*/
drhcc6bb3e2007-08-31 16:11:35 +00003719static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003720 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003721 switch( op ){
3722 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003723 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003724 return SQLITE_OK;
3725 }
drh4bf66fd2015-02-19 02:43:02 +00003726 case SQLITE_FCNTL_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003727 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003728 return SQLITE_OK;
3729 }
dan6e09d692010-07-27 18:34:15 +00003730 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003731 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003732 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003733 }
drh9ff27ec2010-05-19 19:26:05 +00003734 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003735 int rc;
3736 SimulateIOErrorBenign(1);
3737 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3738 SimulateIOErrorBenign(0);
3739 return rc;
drhf0b190d2011-07-26 16:03:07 +00003740 }
3741 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003742 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3743 return SQLITE_OK;
3744 }
drhcb15f352011-12-23 01:04:17 +00003745 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3746 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003747 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003748 }
drhde60fc22011-12-14 17:53:36 +00003749 case SQLITE_FCNTL_VFSNAME: {
3750 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3751 return SQLITE_OK;
3752 }
drh696b33e2012-12-06 19:01:42 +00003753 case SQLITE_FCNTL_TEMPFILENAME: {
drhf3cdcdc2015-04-29 16:50:28 +00003754 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
drh696b33e2012-12-06 19:01:42 +00003755 if( zTFile ){
3756 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3757 *(char**)pArg = zTFile;
3758 }
3759 return SQLITE_OK;
3760 }
drhb959a012013-12-07 12:29:22 +00003761 case SQLITE_FCNTL_HAS_MOVED: {
3762 *(int*)pArg = fileHasMoved(pFile);
3763 return SQLITE_OK;
3764 }
mistachkine98844f2013-08-24 00:59:24 +00003765#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003766 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003767 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003768 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003769 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3770 newLimit = sqlite3GlobalConfig.mxMmap;
3771 }
3772 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003773 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003774 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003775 if( pFile->mmapSize>0 ){
3776 unixUnmapfile(pFile);
3777 rc = unixMapfile(pFile, -1);
3778 }
danbcb8a862013-04-08 15:30:41 +00003779 }
drh34e258c2013-05-23 01:40:53 +00003780 return rc;
danb2d3de32013-03-14 18:34:37 +00003781 }
mistachkine98844f2013-08-24 00:59:24 +00003782#endif
drhd3d8c042012-05-29 17:02:40 +00003783#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003784 /* The pager calls this method to signal that it has done
3785 ** a rollback and that the database is therefore unchanged and
3786 ** it hence it is OK for the transaction change counter to be
3787 ** unchanged.
3788 */
3789 case SQLITE_FCNTL_DB_UNCHANGED: {
3790 ((unixFile*)id)->dbUpdate = 0;
3791 return SQLITE_OK;
3792 }
3793#endif
drhd2cb50b2009-01-09 21:41:17 +00003794#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh4bf66fd2015-02-19 02:43:02 +00003795 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
3796 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003797 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003798 }
drhd2cb50b2009-01-09 21:41:17 +00003799#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003800 }
drh0b52b7d2011-01-26 19:46:22 +00003801 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003802}
3803
3804/*
danielk1977a3d4c882007-03-23 10:08:38 +00003805** Return the sector size in bytes of the underlying block device for
3806** the specified file. This is almost always 512 bytes, but may be
3807** larger for some devices.
3808**
3809** SQLite code assumes this function cannot fail. It also assumes that
3810** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003811** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003812** same for both.
3813*/
drh537dddf2012-10-26 13:46:24 +00003814#ifndef __QNXNTO__
3815static int unixSectorSize(sqlite3_file *NotUsed){
3816 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003817 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003818}
drh537dddf2012-10-26 13:46:24 +00003819#endif
3820
3821/*
3822** The following version of unixSectorSize() is optimized for QNX.
3823*/
3824#ifdef __QNXNTO__
3825#include <sys/dcmd_blk.h>
3826#include <sys/statvfs.h>
3827static int unixSectorSize(sqlite3_file *id){
3828 unixFile *pFile = (unixFile*)id;
3829 if( pFile->sectorSize == 0 ){
3830 struct statvfs fsInfo;
3831
3832 /* Set defaults for non-supported filesystems */
3833 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3834 pFile->deviceCharacteristics = 0;
3835 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3836 return pFile->sectorSize;
3837 }
3838
3839 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3840 pFile->sectorSize = fsInfo.f_bsize;
3841 pFile->deviceCharacteristics =
3842 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3843 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3844 ** the write succeeds */
3845 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3846 ** so it is ordered */
3847 0;
3848 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3849 pFile->sectorSize = fsInfo.f_bsize;
3850 pFile->deviceCharacteristics =
3851 /* etfs cluster size writes are atomic */
3852 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
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( !strcmp(fsInfo.f_basetype, "qnx6") ){
3859 pFile->sectorSize = fsInfo.f_bsize;
3860 pFile->deviceCharacteristics =
3861 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3862 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3863 ** the write succeeds */
3864 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3865 ** so it is ordered */
3866 0;
3867 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3868 pFile->sectorSize = fsInfo.f_bsize;
3869 pFile->deviceCharacteristics =
3870 /* full bitset of atomics from max sector size and smaller */
3871 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3872 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3873 ** so it is ordered */
3874 0;
3875 }else if( strstr(fsInfo.f_basetype, "dos") ){
3876 pFile->sectorSize = fsInfo.f_bsize;
3877 pFile->deviceCharacteristics =
3878 /* full bitset of atomics from max sector size and smaller */
3879 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3880 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3881 ** so it is ordered */
3882 0;
3883 }else{
3884 pFile->deviceCharacteristics =
3885 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3886 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3887 ** the write succeeds */
3888 0;
3889 }
3890 }
3891 /* Last chance verification. If the sector size isn't a multiple of 512
3892 ** then it isn't valid.*/
3893 if( pFile->sectorSize % 512 != 0 ){
3894 pFile->deviceCharacteristics = 0;
3895 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3896 }
3897 return pFile->sectorSize;
3898}
3899#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003900
danielk197790949c22007-08-17 16:50:38 +00003901/*
drhf12b3f62011-12-21 14:42:29 +00003902** Return the device characteristics for the file.
3903**
drhcb15f352011-12-23 01:04:17 +00003904** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
peter.d.reid60ec9142014-09-06 16:39:46 +00003905** However, that choice is controversial since technically the underlying
drhcb15f352011-12-23 01:04:17 +00003906** file system does not always provide powersafe overwrites. (In other
3907** words, after a power-loss event, parts of the file that were never
3908** written might end up being altered.) However, non-PSOW behavior is very,
3909** very rare. And asserting PSOW makes a large reduction in the amount
3910** of required I/O for journaling, since a lot of padding is eliminated.
3911** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3912** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003913*/
drhf12b3f62011-12-21 14:42:29 +00003914static int unixDeviceCharacteristics(sqlite3_file *id){
3915 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003916 int rc = 0;
3917#ifdef __QNXNTO__
3918 if( p->sectorSize==0 ) unixSectorSize(id);
3919 rc = p->deviceCharacteristics;
3920#endif
drhcb15f352011-12-23 01:04:17 +00003921 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003922 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003923 }
drh537dddf2012-10-26 13:46:24 +00003924 return rc;
danielk197762079062007-08-15 17:08:46 +00003925}
3926
dan702eec12014-06-23 10:04:58 +00003927#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00003928
dan702eec12014-06-23 10:04:58 +00003929/*
3930** Return the system page size.
3931**
3932** This function should not be called directly by other code in this file.
3933** Instead, it should be called via macro osGetpagesize().
3934*/
3935static int unixGetpagesize(void){
drh8cd5b252015-03-02 22:06:43 +00003936#if OS_VXWORKS
3937 return 1024;
3938#elif defined(_BSD_SOURCE)
dan702eec12014-06-23 10:04:58 +00003939 return getpagesize();
3940#else
3941 return (int)sysconf(_SC_PAGESIZE);
3942#endif
3943}
3944
3945#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
3946
3947#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00003948
3949/*
drhd91c68f2010-05-14 14:52:25 +00003950** Object used to represent an shared memory buffer.
3951**
3952** When multiple threads all reference the same wal-index, each thread
3953** has its own unixShm object, but they all point to a single instance
3954** of this unixShmNode object. In other words, each wal-index is opened
3955** only once per process.
3956**
3957** Each unixShmNode object is connected to a single unixInodeInfo object.
3958** We could coalesce this object into unixInodeInfo, but that would mean
3959** every open file that does not use shared memory (in other words, most
3960** open files) would have to carry around this extra information. So
3961** the unixInodeInfo object contains a pointer to this unixShmNode object
3962** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003963**
3964** unixMutexHeld() must be true when creating or destroying
3965** this object or while reading or writing the following fields:
3966**
3967** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003968**
3969** The following fields are read-only after the object is created:
3970**
3971** fid
3972** zFilename
3973**
drhd91c68f2010-05-14 14:52:25 +00003974** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003975** unixMutexHeld() is true when reading or writing any other field
3976** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003977*/
drhd91c68f2010-05-14 14:52:25 +00003978struct unixShmNode {
3979 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003980 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003981 char *zFilename; /* Name of the mmapped file */
3982 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003983 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003984 u16 nRegion; /* Size of array apRegion */
3985 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003986 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003987 int nRef; /* Number of unixShm objects pointing to this */
3988 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003989#ifdef SQLITE_DEBUG
3990 u8 exclMask; /* Mask of exclusive locks held */
3991 u8 sharedMask; /* Mask of shared locks held */
3992 u8 nextShmId; /* Next available unixShm.id value */
3993#endif
3994};
3995
3996/*
drhd9e5c4f2010-05-12 18:01:39 +00003997** Structure used internally by this VFS to record the state of an
3998** open shared memory connection.
3999**
drhd91c68f2010-05-14 14:52:25 +00004000** The following fields are initialized when this object is created and
4001** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004002**
drhd91c68f2010-05-14 14:52:25 +00004003** unixShm.pFile
4004** unixShm.id
4005**
4006** All other fields are read/write. The unixShm.pFile->mutex must be held
4007** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004008*/
4009struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004010 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4011 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004012 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004013 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004014 u16 sharedMask; /* Mask of shared locks held */
4015 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004016};
4017
4018/*
drhd9e5c4f2010-05-12 18:01:39 +00004019** Constants used for locking
4020*/
drhbd9676c2010-06-23 17:58:38 +00004021#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004022#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004023
drhd9e5c4f2010-05-12 18:01:39 +00004024/*
drh73b64e42010-05-30 19:55:15 +00004025** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004026**
4027** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4028** otherwise.
4029*/
4030static int unixShmSystemLock(
drhbbf76ee2015-03-10 20:22:35 +00004031 unixFile *pFile, /* Open connection to the WAL file */
drhd91c68f2010-05-14 14:52:25 +00004032 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004033 int ofst, /* First byte of the locking range */
4034 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004035){
drhbbf76ee2015-03-10 20:22:35 +00004036 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4037 struct flock f; /* The posix advisory locking structure */
4038 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004039
drhd91c68f2010-05-14 14:52:25 +00004040 /* Access to the unixShmNode object is serialized by the caller */
drhbbf76ee2015-03-10 20:22:35 +00004041 pShmNode = pFile->pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004042 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004043
drh73b64e42010-05-30 19:55:15 +00004044 /* Shared locks never span more than one byte */
4045 assert( n==1 || lockType!=F_RDLCK );
4046
4047 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00004048 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004049
drh3cb93392011-03-12 18:10:44 +00004050 if( pShmNode->h>=0 ){
4051 /* Initialize the locking parameters */
4052 memset(&f, 0, sizeof(f));
4053 f.l_type = lockType;
4054 f.l_whence = SEEK_SET;
4055 f.l_start = ofst;
4056 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004057
drhdcfb9652015-12-02 00:05:26 +00004058 rc = osFcntl(pShmNode->h, F_SETLK, &f);
drh3cb93392011-03-12 18:10:44 +00004059 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4060 }
drhd9e5c4f2010-05-12 18:01:39 +00004061
4062 /* Update the global lock state and do debug tracing */
4063#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004064 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004065 OSTRACE(("SHM-LOCK "));
drh693e6712014-01-24 22:58:00 +00004066 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004067 if( rc==SQLITE_OK ){
4068 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004069 OSTRACE(("unlock %d ok", ofst));
4070 pShmNode->exclMask &= ~mask;
4071 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004072 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004073 OSTRACE(("read-lock %d ok", ofst));
4074 pShmNode->exclMask &= ~mask;
4075 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004076 }else{
4077 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004078 OSTRACE(("write-lock %d ok", ofst));
4079 pShmNode->exclMask |= mask;
4080 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004081 }
4082 }else{
4083 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004084 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004085 }else if( lockType==F_RDLCK ){
4086 OSTRACE(("read-lock failed"));
4087 }else{
4088 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004089 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004090 }
4091 }
drh20e1f082010-05-31 16:10:12 +00004092 OSTRACE((" - afterwards %03x,%03x\n",
4093 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004094 }
drhd9e5c4f2010-05-12 18:01:39 +00004095#endif
4096
4097 return rc;
4098}
4099
dan781e34c2014-03-20 08:59:47 +00004100/*
dan781e34c2014-03-20 08:59:47 +00004101** Return the minimum number of 32KB shm regions that should be mapped at
4102** a time, assuming that each mapping must be an integer multiple of the
4103** current system page-size.
4104**
4105** Usually, this is 1. The exception seems to be systems that are configured
4106** to use 64KB pages - in this case each mapping must cover at least two
4107** shm regions.
4108*/
4109static int unixShmRegionPerMap(void){
4110 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004111 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004112 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4113 if( pgsz<shmsz ) return 1;
4114 return pgsz/shmsz;
4115}
drhd9e5c4f2010-05-12 18:01:39 +00004116
4117/*
drhd91c68f2010-05-14 14:52:25 +00004118** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004119**
4120** This is not a VFS shared-memory method; it is a utility function called
4121** by VFS shared-memory methods.
4122*/
drhd91c68f2010-05-14 14:52:25 +00004123static void unixShmPurge(unixFile *pFd){
4124 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004125 assert( unixMutexHeld() );
drhf3b1ed02015-12-02 13:11:03 +00004126 if( p && ALWAYS(p->nRef==0) ){
dan781e34c2014-03-20 08:59:47 +00004127 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004128 int i;
drhd91c68f2010-05-14 14:52:25 +00004129 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004130 sqlite3_mutex_free(p->mutex);
dan781e34c2014-03-20 08:59:47 +00004131 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh3cb93392011-03-12 18:10:44 +00004132 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004133 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004134 }else{
4135 sqlite3_free(p->apRegion[i]);
4136 }
dan13a3cb82010-06-11 19:04:21 +00004137 }
dan18801912010-06-14 14:07:50 +00004138 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004139 if( p->h>=0 ){
4140 robust_close(pFd, p->h, __LINE__);
4141 p->h = -1;
4142 }
drhd91c68f2010-05-14 14:52:25 +00004143 p->pInode->pShmNode = 0;
4144 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004145 }
4146}
4147
4148/*
danda9fe0c2010-07-13 18:44:03 +00004149** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004150** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004151**
drh7234c6d2010-06-19 15:10:09 +00004152** The file used to implement shared-memory is in the same directory
4153** as the open database file and has the same name as the open database
4154** file with the "-shm" suffix added. For example, if the database file
4155** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004156** for shared memory will be called "/home/user1/config.db-shm".
4157**
4158** Another approach to is to use files in /dev/shm or /dev/tmp or an
4159** some other tmpfs mount. But if a file in a different directory
4160** from the database file is used, then differing access permissions
4161** or a chroot() might cause two different processes on the same
4162** database to end up using different files for shared memory -
4163** meaning that their memory would not really be shared - resulting
4164** in database corruption. Nevertheless, this tmpfs file usage
4165** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4166** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4167** option results in an incompatible build of SQLite; builds of SQLite
4168** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4169** same database file at the same time, database corruption will likely
4170** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4171** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004172**
4173** When opening a new shared-memory file, if no other instances of that
4174** file are currently open, in this process or in other processes, then
4175** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004176**
4177** If the original database file (pDbFd) is using the "unix-excl" VFS
4178** that means that an exclusive lock is held on the database file and
4179** that no other processes are able to read or write the database. In
4180** that case, we do not really need shared memory. No shared memory
4181** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004182*/
danda9fe0c2010-07-13 18:44:03 +00004183static int unixOpenSharedMemory(unixFile *pDbFd){
4184 struct unixShm *p = 0; /* The connection to be opened */
4185 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4186 int rc; /* Result code */
4187 unixInodeInfo *pInode; /* The inode of fd */
4188 char *zShmFilename; /* Name of the file used for SHM */
4189 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004190
danda9fe0c2010-07-13 18:44:03 +00004191 /* Allocate space for the new unixShm object. */
drhf3cdcdc2015-04-29 16:50:28 +00004192 p = sqlite3_malloc64( sizeof(*p) );
drhd9e5c4f2010-05-12 18:01:39 +00004193 if( p==0 ) return SQLITE_NOMEM;
4194 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004195 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004196
danda9fe0c2010-07-13 18:44:03 +00004197 /* Check to see if a unixShmNode object already exists. Reuse an existing
4198 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004199 */
4200 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004201 pInode = pDbFd->pInode;
4202 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004203 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004204 struct stat sStat; /* fstat() info for database file */
drh4bf66fd2015-02-19 02:43:02 +00004205#ifndef SQLITE_SHM_DIRECTORY
4206 const char *zBasePath = pDbFd->zPath;
4207#endif
danddb0ac42010-07-14 14:48:58 +00004208
4209 /* Call fstat() to figure out the permissions on the database file. If
4210 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004211 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004212 */
drhf3b1ed02015-12-02 13:11:03 +00004213 if( osFstat(pDbFd->h, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004214 rc = SQLITE_IOERR_FSTAT;
4215 goto shm_open_err;
4216 }
4217
drha4ced192010-07-15 18:32:40 +00004218#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004219 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004220#else
drh4bf66fd2015-02-19 02:43:02 +00004221 nShmFilename = 6 + (int)strlen(zBasePath);
drha4ced192010-07-15 18:32:40 +00004222#endif
drhf3cdcdc2015-04-29 16:50:28 +00004223 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004224 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004225 rc = SQLITE_NOMEM;
4226 goto shm_open_err;
4227 }
drh9cb5a0d2012-01-05 21:19:54 +00004228 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004229 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004230#ifdef SQLITE_SHM_DIRECTORY
4231 sqlite3_snprintf(nShmFilename, zShmFilename,
4232 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4233 (u32)sStat.st_ino, (u32)sStat.st_dev);
4234#else
drh4bf66fd2015-02-19 02:43:02 +00004235 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
drh81cc5162011-05-17 20:36:21 +00004236 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004237#endif
drhd91c68f2010-05-14 14:52:25 +00004238 pShmNode->h = -1;
4239 pDbFd->pInode->pShmNode = pShmNode;
4240 pShmNode->pInode = pDbFd->pInode;
4241 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4242 if( pShmNode->mutex==0 ){
4243 rc = SQLITE_NOMEM;
4244 goto shm_open_err;
4245 }
drhd9e5c4f2010-05-12 18:01:39 +00004246
drh3cb93392011-03-12 18:10:44 +00004247 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004248 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004249 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004250 openFlags = O_RDONLY;
4251 pShmNode->isReadonly = 1;
4252 }
4253 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004254 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004255 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4256 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004257 }
drhac7c3ac2012-02-11 19:23:48 +00004258
4259 /* If this process is running as root, make sure that the SHM file
4260 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004261 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004262 */
drh6226ca22015-11-24 15:06:28 +00004263 robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004264
4265 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004266 ** If not, truncate the file to zero length.
4267 */
4268 rc = SQLITE_OK;
drhbbf76ee2015-03-10 20:22:35 +00004269 if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
drh66dfec8b2011-06-01 20:01:49 +00004270 if( robust_ftruncate(pShmNode->h, 0) ){
4271 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004272 }
4273 }
drh66dfec8b2011-06-01 20:01:49 +00004274 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004275 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
drh66dfec8b2011-06-01 20:01:49 +00004276 }
4277 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004278 }
drhd9e5c4f2010-05-12 18:01:39 +00004279 }
4280
drhd91c68f2010-05-14 14:52:25 +00004281 /* Make the new connection a child of the unixShmNode */
4282 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004283#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004284 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004285#endif
drhd91c68f2010-05-14 14:52:25 +00004286 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004287 pDbFd->pShm = p;
4288 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004289
4290 /* The reference count on pShmNode has already been incremented under
4291 ** the cover of the unixEnterMutex() mutex and the pointer from the
4292 ** new (struct unixShm) object to the pShmNode has been set. All that is
4293 ** left to do is to link the new object into the linked list starting
4294 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4295 ** mutex.
4296 */
4297 sqlite3_mutex_enter(pShmNode->mutex);
4298 p->pNext = pShmNode->pFirst;
4299 pShmNode->pFirst = p;
4300 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004301 return SQLITE_OK;
4302
4303 /* Jump here on any error */
4304shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004305 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004306 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004307 unixLeaveMutex();
4308 return rc;
4309}
4310
4311/*
danda9fe0c2010-07-13 18:44:03 +00004312** This function is called to obtain a pointer to region iRegion of the
4313** shared-memory associated with the database file fd. Shared-memory regions
4314** are numbered starting from zero. Each shared-memory region is szRegion
4315** bytes in size.
4316**
4317** If an error occurs, an error code is returned and *pp is set to NULL.
4318**
4319** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4320** region has not been allocated (by any client, including one running in a
4321** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4322** bExtend is non-zero and the requested shared-memory region has not yet
4323** been allocated, it is allocated by this function.
4324**
4325** If the shared-memory region has already been allocated or is allocated by
4326** this call as described above, then it is mapped into this processes
4327** address space (if it is not already), *pp is set to point to the mapped
4328** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004329*/
danda9fe0c2010-07-13 18:44:03 +00004330static int unixShmMap(
4331 sqlite3_file *fd, /* Handle open on database file */
4332 int iRegion, /* Region to retrieve */
4333 int szRegion, /* Size of regions */
4334 int bExtend, /* True to extend file if necessary */
4335 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004336){
danda9fe0c2010-07-13 18:44:03 +00004337 unixFile *pDbFd = (unixFile*)fd;
4338 unixShm *p;
4339 unixShmNode *pShmNode;
4340 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004341 int nShmPerMap = unixShmRegionPerMap();
4342 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004343
danda9fe0c2010-07-13 18:44:03 +00004344 /* If the shared-memory file has not yet been opened, open it now. */
4345 if( pDbFd->pShm==0 ){
4346 rc = unixOpenSharedMemory(pDbFd);
4347 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004348 }
drhd9e5c4f2010-05-12 18:01:39 +00004349
danda9fe0c2010-07-13 18:44:03 +00004350 p = pDbFd->pShm;
4351 pShmNode = p->pShmNode;
4352 sqlite3_mutex_enter(pShmNode->mutex);
4353 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004354 assert( pShmNode->pInode==pDbFd->pInode );
4355 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4356 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004357
dan781e34c2014-03-20 08:59:47 +00004358 /* Minimum number of regions required to be mapped. */
4359 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4360
4361 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004362 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004363 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004364 struct stat sStat; /* Used by fstat() */
4365
4366 pShmNode->szRegion = szRegion;
4367
drh3cb93392011-03-12 18:10:44 +00004368 if( pShmNode->h>=0 ){
4369 /* The requested region is not mapped into this processes address space.
4370 ** Check to see if it has been allocated (i.e. if the wal-index file is
4371 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004372 */
drh3cb93392011-03-12 18:10:44 +00004373 if( osFstat(pShmNode->h, &sStat) ){
4374 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004375 goto shmpage_out;
4376 }
drh3cb93392011-03-12 18:10:44 +00004377
4378 if( sStat.st_size<nByte ){
4379 /* The requested memory region does not exist. If bExtend is set to
4380 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004381 */
dan47a2b4a2013-04-26 16:09:29 +00004382 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004383 goto shmpage_out;
4384 }
dan47a2b4a2013-04-26 16:09:29 +00004385
4386 /* Alternatively, if bExtend is true, extend the file. Do this by
4387 ** writing a single byte to the end of each (OS) page being
4388 ** allocated or extended. Technically, we need only write to the
4389 ** last page in order to extend the file. But writing to all new
4390 ** pages forces the OS to allocate them immediately, which reduces
4391 ** the chances of SIGBUS while accessing the mapped region later on.
4392 */
4393 else{
4394 static const int pgsz = 4096;
4395 int iPg;
4396
4397 /* Write to the last byte of each newly allocated or extended page */
4398 assert( (nByte % pgsz)==0 );
4399 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
drhe1818ec2015-12-01 16:21:35 +00004400 int x = 0;
4401 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
dan47a2b4a2013-04-26 16:09:29 +00004402 const char *zFile = pShmNode->zFilename;
4403 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4404 goto shmpage_out;
4405 }
4406 }
drh3cb93392011-03-12 18:10:44 +00004407 }
4408 }
danda9fe0c2010-07-13 18:44:03 +00004409 }
4410
4411 /* Map the requested memory region into this processes address space. */
4412 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004413 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004414 );
4415 if( !apNew ){
4416 rc = SQLITE_IOERR_NOMEM;
4417 goto shmpage_out;
4418 }
4419 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004420 while( pShmNode->nRegion<nReqRegion ){
4421 int nMap = szRegion*nShmPerMap;
4422 int i;
drh3cb93392011-03-12 18:10:44 +00004423 void *pMem;
4424 if( pShmNode->h>=0 ){
dan781e34c2014-03-20 08:59:47 +00004425 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004426 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004427 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004428 );
4429 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004430 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004431 goto shmpage_out;
4432 }
4433 }else{
drhf3cdcdc2015-04-29 16:50:28 +00004434 pMem = sqlite3_malloc64(szRegion);
drh3cb93392011-03-12 18:10:44 +00004435 if( pMem==0 ){
4436 rc = SQLITE_NOMEM;
4437 goto shmpage_out;
4438 }
4439 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004440 }
dan781e34c2014-03-20 08:59:47 +00004441
4442 for(i=0; i<nShmPerMap; i++){
4443 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4444 }
4445 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004446 }
4447 }
4448
4449shmpage_out:
4450 if( pShmNode->nRegion>iRegion ){
4451 *pp = pShmNode->apRegion[iRegion];
4452 }else{
4453 *pp = 0;
4454 }
drh66dfec8b2011-06-01 20:01:49 +00004455 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004456 sqlite3_mutex_leave(pShmNode->mutex);
4457 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004458}
4459
4460/*
drhd9e5c4f2010-05-12 18:01:39 +00004461** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004462**
4463** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4464** different here than in posix. In xShmLock(), one can go from unlocked
4465** to shared and back or from unlocked to exclusive and back. But one may
4466** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004467*/
4468static int unixShmLock(
4469 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004470 int ofst, /* First lock to acquire or release */
4471 int n, /* Number of locks to acquire or release */
4472 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004473){
drh73b64e42010-05-30 19:55:15 +00004474 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4475 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4476 unixShm *pX; /* For looping over all siblings */
4477 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4478 int rc = SQLITE_OK; /* Result code */
4479 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004480
drhd91c68f2010-05-14 14:52:25 +00004481 assert( pShmNode==pDbFd->pInode->pShmNode );
4482 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004483 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004484 assert( n>=1 );
4485 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4486 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4487 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4488 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4489 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004490 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4491 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004492
drhc99597c2010-05-31 01:41:15 +00004493 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004494 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004495 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004496 if( flags & SQLITE_SHM_UNLOCK ){
4497 u16 allMask = 0; /* Mask of locks held by siblings */
4498
4499 /* See if any siblings hold this same lock */
4500 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4501 if( pX==p ) continue;
4502 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4503 allMask |= pX->sharedMask;
4504 }
4505
4506 /* Unlock the system-level locks */
4507 if( (mask & allMask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004508 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004509 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004510 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004511 }
drh73b64e42010-05-30 19:55:15 +00004512
4513 /* Undo the local locks */
4514 if( rc==SQLITE_OK ){
4515 p->exclMask &= ~mask;
4516 p->sharedMask &= ~mask;
4517 }
4518 }else if( flags & SQLITE_SHM_SHARED ){
4519 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4520
4521 /* Find out which shared locks are already held by sibling connections.
4522 ** If any sibling already holds an exclusive lock, go ahead and return
4523 ** SQLITE_BUSY.
4524 */
4525 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004526 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004527 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004528 break;
4529 }
4530 allShared |= pX->sharedMask;
4531 }
4532
4533 /* Get shared locks at the system level, if necessary */
4534 if( rc==SQLITE_OK ){
4535 if( (allShared & mask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004536 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004537 }else{
drh73b64e42010-05-30 19:55:15 +00004538 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004539 }
drhd9e5c4f2010-05-12 18:01:39 +00004540 }
drh73b64e42010-05-30 19:55:15 +00004541
4542 /* Get the local shared locks */
4543 if( rc==SQLITE_OK ){
4544 p->sharedMask |= mask;
4545 }
4546 }else{
4547 /* Make sure no sibling connections hold locks that will block this
4548 ** lock. If any do, return SQLITE_BUSY right away.
4549 */
4550 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004551 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4552 rc = SQLITE_BUSY;
4553 break;
4554 }
4555 }
4556
4557 /* Get the exclusive locks at the system level. Then if successful
4558 ** also mark the local connection as being locked.
4559 */
4560 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004561 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004562 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004563 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004564 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004565 }
drhd9e5c4f2010-05-12 18:01:39 +00004566 }
4567 }
drhd91c68f2010-05-14 14:52:25 +00004568 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004569 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
drh5ac93652015-03-21 20:59:43 +00004570 p->id, osGetpid(0), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004571 return rc;
4572}
4573
drh286a2882010-05-20 23:51:06 +00004574/*
4575** Implement a memory barrier or memory fence on shared memory.
4576**
4577** All loads and stores begun before the barrier must complete before
4578** any load or store begun after the barrier.
4579*/
4580static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004581 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004582){
drhff828942010-06-26 21:34:06 +00004583 UNUSED_PARAMETER(fd);
drh22c733d2015-09-24 12:40:43 +00004584 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
4585 unixEnterMutex(); /* Also mutex, for redundancy */
drhb29ad852010-06-01 00:03:57 +00004586 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004587}
4588
dan18801912010-06-14 14:07:50 +00004589/*
danda9fe0c2010-07-13 18:44:03 +00004590** Close a connection to shared-memory. Delete the underlying
4591** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004592**
4593** If there is no shared memory associated with the connection then this
4594** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004595*/
danda9fe0c2010-07-13 18:44:03 +00004596static int unixShmUnmap(
4597 sqlite3_file *fd, /* The underlying database file */
4598 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004599){
danda9fe0c2010-07-13 18:44:03 +00004600 unixShm *p; /* The connection to be closed */
4601 unixShmNode *pShmNode; /* The underlying shared-memory file */
4602 unixShm **pp; /* For looping over sibling connections */
4603 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004604
danda9fe0c2010-07-13 18:44:03 +00004605 pDbFd = (unixFile*)fd;
4606 p = pDbFd->pShm;
4607 if( p==0 ) return SQLITE_OK;
4608 pShmNode = p->pShmNode;
4609
4610 assert( pShmNode==pDbFd->pInode->pShmNode );
4611 assert( pShmNode->pInode==pDbFd->pInode );
4612
4613 /* Remove connection p from the set of connections associated
4614 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004615 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004616 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4617 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004618
danda9fe0c2010-07-13 18:44:03 +00004619 /* Free the connection p */
4620 sqlite3_free(p);
4621 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004622 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004623
4624 /* If pShmNode->nRef has reached 0, then close the underlying
4625 ** shared-memory file, too */
4626 unixEnterMutex();
4627 assert( pShmNode->nRef>0 );
4628 pShmNode->nRef--;
4629 if( pShmNode->nRef==0 ){
drh4bf66fd2015-02-19 02:43:02 +00004630 if( deleteFlag && pShmNode->h>=0 ){
4631 osUnlink(pShmNode->zFilename);
4632 }
danda9fe0c2010-07-13 18:44:03 +00004633 unixShmPurge(pDbFd);
4634 }
4635 unixLeaveMutex();
4636
4637 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004638}
drh286a2882010-05-20 23:51:06 +00004639
danda9fe0c2010-07-13 18:44:03 +00004640
drhd9e5c4f2010-05-12 18:01:39 +00004641#else
drh6b017cc2010-06-14 18:01:46 +00004642# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004643# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004644# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004645# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004646#endif /* #ifndef SQLITE_OMIT_WAL */
4647
mistachkine98844f2013-08-24 00:59:24 +00004648#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004649/*
danaef49d72013-03-25 16:28:54 +00004650** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004651*/
danf23da962013-03-23 21:00:41 +00004652static void unixUnmapfile(unixFile *pFd){
4653 assert( pFd->nFetchOut==0 );
4654 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004655 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004656 pFd->pMapRegion = 0;
4657 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004658 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004659 }
4660}
dan5d8a1372013-03-19 19:28:06 +00004661
danaef49d72013-03-25 16:28:54 +00004662/*
dane6ecd662013-04-01 17:56:59 +00004663** Attempt to set the size of the memory mapping maintained by file
4664** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4665**
4666** If successful, this function sets the following variables:
4667**
4668** unixFile.pMapRegion
4669** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004670** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004671**
4672** If unsuccessful, an error message is logged via sqlite3_log() and
4673** the three variables above are zeroed. In this case SQLite should
4674** continue accessing the database using the xRead() and xWrite()
4675** methods.
4676*/
4677static void unixRemapfile(
4678 unixFile *pFd, /* File descriptor object */
4679 i64 nNew /* Required mapping size */
4680){
dan4ff7bc42013-04-02 12:04:09 +00004681 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004682 int h = pFd->h; /* File descriptor open on db file */
4683 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004684 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004685 u8 *pNew = 0; /* Location of new mapping */
4686 int flags = PROT_READ; /* Flags to pass to mmap() */
4687
4688 assert( pFd->nFetchOut==0 );
4689 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004690 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004691 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004692 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004693 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004694
danfe33e392015-11-17 20:56:06 +00004695#ifdef SQLITE_MMAP_READWRITE
dane6ecd662013-04-01 17:56:59 +00004696 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
danfe33e392015-11-17 20:56:06 +00004697#endif
dane6ecd662013-04-01 17:56:59 +00004698
4699 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00004700#if HAVE_MREMAP
4701 i64 nReuse = pFd->mmapSize;
4702#else
danbc760632014-03-20 09:42:09 +00004703 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00004704 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00004705#endif
dane6ecd662013-04-01 17:56:59 +00004706 u8 *pReq = &pOrig[nReuse];
4707
4708 /* Unmap any pages of the existing mapping that cannot be reused. */
4709 if( nReuse!=nOrig ){
4710 osMunmap(pReq, nOrig-nReuse);
4711 }
4712
4713#if HAVE_MREMAP
4714 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004715 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004716#else
4717 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4718 if( pNew!=MAP_FAILED ){
4719 if( pNew!=pReq ){
4720 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004721 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004722 }else{
4723 pNew = pOrig;
4724 }
4725 }
4726#endif
4727
dan48ccef82013-04-02 20:55:01 +00004728 /* The attempt to extend the existing mapping failed. Free it. */
4729 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004730 osMunmap(pOrig, nReuse);
4731 }
4732 }
4733
4734 /* If pNew is still NULL, try to create an entirely new mapping. */
4735 if( pNew==0 ){
4736 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004737 }
4738
dan4ff7bc42013-04-02 12:04:09 +00004739 if( pNew==MAP_FAILED ){
4740 pNew = 0;
4741 nNew = 0;
4742 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4743
4744 /* If the mmap() above failed, assume that all subsequent mmap() calls
4745 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4746 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004747 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004748 }
dane6ecd662013-04-01 17:56:59 +00004749 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004750 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004751}
4752
4753/*
danaef49d72013-03-25 16:28:54 +00004754** Memory map or remap the file opened by file-descriptor pFd (if the file
4755** is already mapped, the existing mapping is replaced by the new). Or, if
4756** there already exists a mapping for this file, and there are still
4757** outstanding xFetch() references to it, this function is a no-op.
4758**
4759** If parameter nByte is non-negative, then it is the requested size of
4760** the mapping to create. Otherwise, if nByte is less than zero, then the
4761** requested size is the size of the file on disk. The actual size of the
4762** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004763** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004764**
4765** SQLITE_OK is returned if no error occurs (even if the mapping is not
4766** recreated as a result of outstanding references) or an SQLite error
4767** code otherwise.
4768*/
drhf3b1ed02015-12-02 13:11:03 +00004769static int unixMapfile(unixFile *pFd, i64 nMap){
danf23da962013-03-23 21:00:41 +00004770 assert( nMap>=0 || pFd->nFetchOut==0 );
drh333e6ca2015-12-02 15:44:39 +00004771 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00004772 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4773
4774 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00004775 struct stat statbuf; /* Low-level file information */
drhf3b1ed02015-12-02 13:11:03 +00004776 if( osFstat(pFd->h, &statbuf) ){
danf23da962013-03-23 21:00:41 +00004777 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004778 }
drh3044b512014-06-16 16:41:52 +00004779 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00004780 }
drh9b4c59f2013-04-15 17:03:42 +00004781 if( nMap>pFd->mmapSizeMax ){
4782 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004783 }
4784
drh333e6ca2015-12-02 15:44:39 +00004785 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00004786 if( nMap!=pFd->mmapSize ){
drh333e6ca2015-12-02 15:44:39 +00004787 unixRemapfile(pFd, nMap);
dan5d8a1372013-03-19 19:28:06 +00004788 }
4789
danf23da962013-03-23 21:00:41 +00004790 return SQLITE_OK;
4791}
mistachkine98844f2013-08-24 00:59:24 +00004792#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004793
danaef49d72013-03-25 16:28:54 +00004794/*
4795** If possible, return a pointer to a mapping of file fd starting at offset
4796** iOff. The mapping must be valid for at least nAmt bytes.
4797**
4798** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4799** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4800** Finally, if an error does occur, return an SQLite error code. The final
4801** value of *pp is undefined in this case.
4802**
4803** If this function does return a pointer, the caller must eventually
4804** release the reference by calling unixUnfetch().
4805*/
danf23da962013-03-23 21:00:41 +00004806static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004807#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004808 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004809#endif
danf23da962013-03-23 21:00:41 +00004810 *pp = 0;
4811
drh9b4c59f2013-04-15 17:03:42 +00004812#if SQLITE_MAX_MMAP_SIZE>0
4813 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004814 if( pFd->pMapRegion==0 ){
4815 int rc = unixMapfile(pFd, -1);
4816 if( rc!=SQLITE_OK ) return rc;
4817 }
4818 if( pFd->mmapSize >= iOff+nAmt ){
4819 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4820 pFd->nFetchOut++;
4821 }
4822 }
drh6e0b6d52013-04-09 16:19:20 +00004823#endif
danf23da962013-03-23 21:00:41 +00004824 return SQLITE_OK;
4825}
4826
danaef49d72013-03-25 16:28:54 +00004827/*
dandf737fe2013-03-25 17:00:24 +00004828** If the third argument is non-NULL, then this function releases a
4829** reference obtained by an earlier call to unixFetch(). The second
4830** argument passed to this function must be the same as the corresponding
4831** argument that was passed to the unixFetch() invocation.
4832**
4833** Or, if the third argument is NULL, then this function is being called
4834** to inform the VFS layer that, according to POSIX, any existing mapping
4835** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004836*/
dandf737fe2013-03-25 17:00:24 +00004837static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00004838#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00004839 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00004840 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00004841
danaef49d72013-03-25 16:28:54 +00004842 /* If p==0 (unmap the entire file) then there must be no outstanding
4843 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4844 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004845 assert( (p==0)==(pFd->nFetchOut==0) );
4846
dandf737fe2013-03-25 17:00:24 +00004847 /* If p!=0, it must match the iOff value. */
4848 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4849
danf23da962013-03-23 21:00:41 +00004850 if( p ){
4851 pFd->nFetchOut--;
4852 }else{
4853 unixUnmapfile(pFd);
4854 }
4855
4856 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00004857#else
4858 UNUSED_PARAMETER(fd);
4859 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00004860 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00004861#endif
danf23da962013-03-23 21:00:41 +00004862 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004863}
4864
4865/*
drh734c9862008-11-28 15:37:20 +00004866** Here ends the implementation of all sqlite3_file methods.
4867**
4868********************** End sqlite3_file Methods *******************************
4869******************************************************************************/
4870
4871/*
drh6b9d6dd2008-12-03 19:34:47 +00004872** This division contains definitions of sqlite3_io_methods objects that
4873** implement various file locking strategies. It also contains definitions
4874** of "finder" functions. A finder-function is used to locate the appropriate
4875** sqlite3_io_methods object for a particular database file. The pAppData
4876** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4877** the correct finder-function for that VFS.
4878**
4879** Most finder functions return a pointer to a fixed sqlite3_io_methods
4880** object. The only interesting finder-function is autolockIoFinder, which
4881** looks at the filesystem type and tries to guess the best locking
4882** strategy from that.
4883**
peter.d.reid60ec9142014-09-06 16:39:46 +00004884** For finder-function F, two objects are created:
drh1875f7a2008-12-08 18:19:17 +00004885**
4886** (1) The real finder-function named "FImpt()".
4887**
dane946c392009-08-22 11:39:46 +00004888** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004889**
4890**
4891** A pointer to the F pointer is used as the pAppData value for VFS
4892** objects. We have to do this instead of letting pAppData point
4893** directly at the finder-function since C90 rules prevent a void*
4894** from be cast into a function pointer.
4895**
drh6b9d6dd2008-12-03 19:34:47 +00004896**
drh7708e972008-11-29 00:56:52 +00004897** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004898**
drh7708e972008-11-29 00:56:52 +00004899** * A constant sqlite3_io_methods object call METHOD that has locking
4900** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4901**
4902** * An I/O method finder function called FINDER that returns a pointer
4903** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004904*/
drhe6d41732015-02-21 00:49:00 +00004905#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
drh7708e972008-11-29 00:56:52 +00004906static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004907 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004908 CLOSE, /* xClose */ \
4909 unixRead, /* xRead */ \
4910 unixWrite, /* xWrite */ \
4911 unixTruncate, /* xTruncate */ \
4912 unixSync, /* xSync */ \
4913 unixFileSize, /* xFileSize */ \
4914 LOCK, /* xLock */ \
4915 UNLOCK, /* xUnlock */ \
4916 CKLOCK, /* xCheckReservedLock */ \
4917 unixFileControl, /* xFileControl */ \
4918 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004919 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drhd9f94412014-09-22 03:22:27 +00004920 SHMMAP, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004921 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004922 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00004923 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00004924 unixFetch, /* xFetch */ \
4925 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00004926}; \
drh0c2694b2009-09-03 16:23:44 +00004927static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4928 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004929 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004930} \
drh0c2694b2009-09-03 16:23:44 +00004931static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004932 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004933
4934/*
4935** Here are all of the sqlite3_io_methods objects for each of the
4936** locking strategies. Functions that return pointers to these methods
4937** are also created.
4938*/
4939IOMETHODS(
4940 posixIoFinder, /* Finder function name */
4941 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00004942 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00004943 unixClose, /* xClose method */
4944 unixLock, /* xLock method */
4945 unixUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004946 unixCheckReservedLock, /* xCheckReservedLock method */
4947 unixShmMap /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004948)
drh7708e972008-11-29 00:56:52 +00004949IOMETHODS(
4950 nolockIoFinder, /* Finder function name */
4951 nolockIoMethods, /* sqlite3_io_methods object name */
drh142341c2014-09-19 19:00:48 +00004952 3, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004953 nolockClose, /* xClose method */
4954 nolockLock, /* xLock method */
4955 nolockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004956 nolockCheckReservedLock, /* xCheckReservedLock method */
4957 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004958)
drh7708e972008-11-29 00:56:52 +00004959IOMETHODS(
4960 dotlockIoFinder, /* Finder function name */
4961 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004962 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004963 dotlockClose, /* xClose method */
4964 dotlockLock, /* xLock method */
4965 dotlockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004966 dotlockCheckReservedLock, /* xCheckReservedLock method */
4967 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004968)
drh7708e972008-11-29 00:56:52 +00004969
drhe89b2912015-03-03 20:42:01 +00004970#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004971IOMETHODS(
4972 flockIoFinder, /* Finder function name */
4973 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004974 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004975 flockClose, /* xClose method */
4976 flockLock, /* xLock method */
4977 flockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004978 flockCheckReservedLock, /* xCheckReservedLock method */
4979 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004980)
drh7708e972008-11-29 00:56:52 +00004981#endif
4982
drh6c7d5c52008-11-21 20:32:33 +00004983#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004984IOMETHODS(
4985 semIoFinder, /* Finder function name */
4986 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004987 1, /* shared memory is disabled */
drh8cd5b252015-03-02 22:06:43 +00004988 semXClose, /* xClose method */
4989 semXLock, /* xLock method */
4990 semXUnlock, /* xUnlock method */
4991 semXCheckReservedLock, /* xCheckReservedLock method */
drhd9f94412014-09-22 03:22:27 +00004992 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004993)
aswiftaebf4132008-11-21 00:10:35 +00004994#endif
drh7708e972008-11-29 00:56:52 +00004995
drhd2cb50b2009-01-09 21:41:17 +00004996#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004997IOMETHODS(
4998 afpIoFinder, /* Finder function name */
4999 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005000 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005001 afpClose, /* xClose method */
5002 afpLock, /* xLock method */
5003 afpUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005004 afpCheckReservedLock, /* xCheckReservedLock method */
5005 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005006)
drh715ff302008-12-03 22:32:44 +00005007#endif
5008
5009/*
5010** The proxy locking method is a "super-method" in the sense that it
5011** opens secondary file descriptors for the conch and lock files and
5012** it uses proxy, dot-file, AFP, and flock() locking methods on those
5013** secondary files. For this reason, the division that implements
5014** proxy locking is located much further down in the file. But we need
5015** to go ahead and define the sqlite3_io_methods and finder function
5016** for proxy locking here. So we forward declare the I/O methods.
5017*/
drhd2cb50b2009-01-09 21:41:17 +00005018#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005019static int proxyClose(sqlite3_file*);
5020static int proxyLock(sqlite3_file*, int);
5021static int proxyUnlock(sqlite3_file*, int);
5022static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005023IOMETHODS(
5024 proxyIoFinder, /* Finder function name */
5025 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005026 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005027 proxyClose, /* xClose method */
5028 proxyLock, /* xLock method */
5029 proxyUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005030 proxyCheckReservedLock, /* xCheckReservedLock method */
5031 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005032)
aswiftaebf4132008-11-21 00:10:35 +00005033#endif
drh7708e972008-11-29 00:56:52 +00005034
drh7ed97b92010-01-20 13:07:21 +00005035/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5036#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5037IOMETHODS(
5038 nfsIoFinder, /* Finder function name */
5039 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005040 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005041 unixClose, /* xClose method */
5042 unixLock, /* xLock method */
5043 nfsUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005044 unixCheckReservedLock, /* xCheckReservedLock method */
5045 0 /* xShmMap method */
drh7ed97b92010-01-20 13:07:21 +00005046)
5047#endif
drh7708e972008-11-29 00:56:52 +00005048
drhd2cb50b2009-01-09 21:41:17 +00005049#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005050/*
drh6b9d6dd2008-12-03 19:34:47 +00005051** This "finder" function attempts to determine the best locking strategy
5052** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005053** object that implements that strategy.
5054**
5055** This is for MacOSX only.
5056*/
drh1875f7a2008-12-08 18:19:17 +00005057static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005058 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005059 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005060){
5061 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005062 const char *zFilesystem; /* Filesystem type name */
5063 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005064 } aMap[] = {
5065 { "hfs", &posixIoMethods },
5066 { "ufs", &posixIoMethods },
5067 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005068 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005069 { "webdav", &nolockIoMethods },
5070 { 0, 0 }
5071 };
5072 int i;
5073 struct statfs fsInfo;
5074 struct flock lockInfo;
5075
5076 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005077 /* If filePath==NULL that means we are dealing with a transient file
5078 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005079 return &nolockIoMethods;
5080 }
5081 if( statfs(filePath, &fsInfo) != -1 ){
5082 if( fsInfo.f_flags & MNT_RDONLY ){
5083 return &nolockIoMethods;
5084 }
5085 for(i=0; aMap[i].zFilesystem; i++){
5086 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5087 return aMap[i].pMethods;
5088 }
5089 }
5090 }
5091
5092 /* Default case. Handles, amongst others, "nfs".
5093 ** Test byte-range lock using fcntl(). If the call succeeds,
5094 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005095 */
drh7708e972008-11-29 00:56:52 +00005096 lockInfo.l_len = 1;
5097 lockInfo.l_start = 0;
5098 lockInfo.l_whence = SEEK_SET;
5099 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005100 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005101 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5102 return &nfsIoMethods;
5103 } else {
5104 return &posixIoMethods;
5105 }
drh7708e972008-11-29 00:56:52 +00005106 }else{
5107 return &dotlockIoMethods;
5108 }
5109}
drh0c2694b2009-09-03 16:23:44 +00005110static const sqlite3_io_methods
5111 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005112
drhd2cb50b2009-01-09 21:41:17 +00005113#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005114
drhe89b2912015-03-03 20:42:01 +00005115#if OS_VXWORKS
5116/*
5117** This "finder" function for VxWorks checks to see if posix advisory
5118** locking works. If it does, then that is what is used. If it does not
5119** work, then fallback to named semaphore locking.
chw78a13182009-04-07 05:35:03 +00005120*/
drhe89b2912015-03-03 20:42:01 +00005121static const sqlite3_io_methods *vxworksIoFinderImpl(
chw78a13182009-04-07 05:35:03 +00005122 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005123 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005124){
5125 struct flock lockInfo;
5126
5127 if( !filePath ){
5128 /* If filePath==NULL that means we are dealing with a transient file
5129 ** that does not need to be locked. */
5130 return &nolockIoMethods;
5131 }
5132
5133 /* Test if fcntl() is supported and use POSIX style locks.
5134 ** Otherwise fall back to the named semaphore method.
5135 */
5136 lockInfo.l_len = 1;
5137 lockInfo.l_start = 0;
5138 lockInfo.l_whence = SEEK_SET;
5139 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005140 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005141 return &posixIoMethods;
5142 }else{
5143 return &semIoMethods;
5144 }
5145}
drh0c2694b2009-09-03 16:23:44 +00005146static const sqlite3_io_methods
drhe89b2912015-03-03 20:42:01 +00005147 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005148
drhe89b2912015-03-03 20:42:01 +00005149#endif /* OS_VXWORKS */
chw78a13182009-04-07 05:35:03 +00005150
drh7708e972008-11-29 00:56:52 +00005151/*
peter.d.reid60ec9142014-09-06 16:39:46 +00005152** An abstract type for a pointer to an IO method finder function:
drh7708e972008-11-29 00:56:52 +00005153*/
drh0c2694b2009-09-03 16:23:44 +00005154typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005155
aswiftaebf4132008-11-21 00:10:35 +00005156
drh734c9862008-11-28 15:37:20 +00005157/****************************************************************************
5158**************************** sqlite3_vfs methods ****************************
5159**
5160** This division contains the implementation of methods on the
5161** sqlite3_vfs object.
5162*/
5163
danielk1977a3d4c882007-03-23 10:08:38 +00005164/*
danielk1977e339d652008-06-28 11:23:00 +00005165** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005166*/
5167static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005168 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005169 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005170 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005171 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005172 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005173){
drh7708e972008-11-29 00:56:52 +00005174 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005175 unixFile *pNew = (unixFile *)pId;
5176 int rc = SQLITE_OK;
5177
drh8af6c222010-05-14 12:43:01 +00005178 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005179
dan00157392010-10-05 11:33:15 +00005180 /* Usually the path zFilename should not be a relative pathname. The
5181 ** exception is when opening the proxy "conch" file in builds that
5182 ** include the special Apple locking styles.
5183 */
dan00157392010-10-05 11:33:15 +00005184#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005185 assert( zFilename==0 || zFilename[0]=='/'
5186 || pVfs->pAppData==(void*)&autolockIoFinder );
5187#else
5188 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005189#endif
dan00157392010-10-05 11:33:15 +00005190
drhb07028f2011-10-14 21:49:18 +00005191 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005192 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005193
drh308c2a52010-05-14 11:30:18 +00005194 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005195 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005196 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005197 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005198 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005199#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005200 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005201#endif
drhc02a43a2012-01-10 23:18:38 +00005202 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5203 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005204 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005205 }
drh503a6862013-03-01 01:07:17 +00005206 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005207 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005208 }
drh339eb0b2008-03-07 15:34:11 +00005209
drh6c7d5c52008-11-21 20:32:33 +00005210#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005211 pNew->pId = vxworksFindFileId(zFilename);
5212 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005213 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00005214 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00005215 }
5216#endif
5217
drhc02a43a2012-01-10 23:18:38 +00005218 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005219 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005220 }else{
drh0c2694b2009-09-03 16:23:44 +00005221 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005222#if SQLITE_ENABLE_LOCKING_STYLE
5223 /* Cache zFilename in the locking context (AFP and dotlock override) for
5224 ** proxyLock activation is possible (remote proxy is based on db name)
5225 ** zFilename remains valid until file is closed, to support */
5226 pNew->lockingContext = (void*)zFilename;
5227#endif
drhda0e7682008-07-30 15:27:54 +00005228 }
danielk1977e339d652008-06-28 11:23:00 +00005229
drh7ed97b92010-01-20 13:07:21 +00005230 if( pLockingStyle == &posixIoMethods
5231#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5232 || pLockingStyle == &nfsIoMethods
5233#endif
5234 ){
drh7708e972008-11-29 00:56:52 +00005235 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005236 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005237 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005238 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005239 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005240 ** in two scenarios:
5241 **
5242 ** (a) A call to fstat() failed.
5243 ** (b) A malloc failed.
5244 **
5245 ** Scenario (b) may only occur if the process is holding no other
5246 ** file descriptors open on the same file. If there were other file
5247 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005248 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005249 ** handle h - as it is guaranteed that no posix locks will be released
5250 ** by doing so.
5251 **
5252 ** If scenario (a) caused the error then things are not so safe. The
5253 ** implicit assumption here is that if fstat() fails, things are in
5254 ** such bad shape that dropping a lock or two doesn't matter much.
5255 */
drh0e9365c2011-03-02 02:08:13 +00005256 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005257 h = -1;
5258 }
drh7708e972008-11-29 00:56:52 +00005259 unixLeaveMutex();
5260 }
danielk1977e339d652008-06-28 11:23:00 +00005261
drhd2cb50b2009-01-09 21:41:17 +00005262#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005263 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005264 /* AFP locking uses the file path so it needs to be included in
5265 ** the afpLockingContext.
5266 */
5267 afpLockingContext *pCtx;
drhf3cdcdc2015-04-29 16:50:28 +00005268 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh7708e972008-11-29 00:56:52 +00005269 if( pCtx==0 ){
5270 rc = SQLITE_NOMEM;
5271 }else{
5272 /* NB: zFilename exists and remains valid until the file is closed
5273 ** according to requirement F11141. So we do not need to make a
5274 ** copy of the filename. */
5275 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005276 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005277 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005278 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005279 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005280 if( rc!=SQLITE_OK ){
5281 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005282 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005283 h = -1;
5284 }
drh7708e972008-11-29 00:56:52 +00005285 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005286 }
drh7708e972008-11-29 00:56:52 +00005287 }
5288#endif
danielk1977e339d652008-06-28 11:23:00 +00005289
drh7708e972008-11-29 00:56:52 +00005290 else if( pLockingStyle == &dotlockIoMethods ){
5291 /* Dotfile locking uses the file path so it needs to be included in
5292 ** the dotlockLockingContext
5293 */
5294 char *zLockFile;
5295 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005296 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005297 nFilename = (int)strlen(zFilename) + 6;
drhf3cdcdc2015-04-29 16:50:28 +00005298 zLockFile = (char *)sqlite3_malloc64(nFilename);
drh7708e972008-11-29 00:56:52 +00005299 if( zLockFile==0 ){
5300 rc = SQLITE_NOMEM;
5301 }else{
5302 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005303 }
drh7708e972008-11-29 00:56:52 +00005304 pNew->lockingContext = zLockFile;
5305 }
danielk1977e339d652008-06-28 11:23:00 +00005306
drh6c7d5c52008-11-21 20:32:33 +00005307#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005308 else if( pLockingStyle == &semIoMethods ){
5309 /* Named semaphore locking uses the file path so it needs to be
5310 ** included in the semLockingContext
5311 */
5312 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005313 rc = findInodeInfo(pNew, &pNew->pInode);
5314 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5315 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005316 int n;
drh2238dcc2009-08-27 17:56:20 +00005317 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005318 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005319 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005320 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005321 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5322 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00005323 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00005324 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005325 }
chw97185482008-11-17 08:05:31 +00005326 }
drh7708e972008-11-29 00:56:52 +00005327 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005328 }
drh7708e972008-11-29 00:56:52 +00005329#endif
aswift5b1a2562008-08-22 00:22:35 +00005330
drh4bf66fd2015-02-19 02:43:02 +00005331 storeLastErrno(pNew, 0);
drh6c7d5c52008-11-21 20:32:33 +00005332#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005333 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005334 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005335 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005336 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005337 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005338 }
chw97185482008-11-17 08:05:31 +00005339#endif
danielk1977e339d652008-06-28 11:23:00 +00005340 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005341 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005342 }else{
drh7708e972008-11-29 00:56:52 +00005343 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005344 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005345 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005346 }
danielk1977e339d652008-06-28 11:23:00 +00005347 return rc;
drh054889e2005-11-30 03:20:31 +00005348}
drh9c06c952005-11-26 00:25:00 +00005349
danielk1977ad94b582007-08-20 06:44:22 +00005350/*
drh8b3cf822010-06-01 21:02:51 +00005351** Return the name of a directory in which to put temporary files.
5352** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005353*/
drh7234c6d2010-06-19 15:10:09 +00005354static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005355 static const char *azDirs[] = {
5356 0,
aswiftaebf4132008-11-21 00:10:35 +00005357 0,
danielk197717b90b52008-06-06 11:11:25 +00005358 "/var/tmp",
5359 "/usr/tmp",
5360 "/tmp",
drhb7e50ad2015-11-28 21:49:53 +00005361 "."
danielk197717b90b52008-06-06 11:11:25 +00005362 };
drh8b3cf822010-06-01 21:02:51 +00005363 unsigned int i;
5364 struct stat buf;
drhb7e50ad2015-11-28 21:49:53 +00005365 const char *zDir = sqlite3_temp_directory;
drh8b3cf822010-06-01 21:02:51 +00005366
drhb7e50ad2015-11-28 21:49:53 +00005367 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
5368 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005369 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005370 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005371 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005372 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005373 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005374 break;
5375 }
5376 return zDir;
5377}
5378
5379/*
5380** Create a temporary file name in zBuf. zBuf must be allocated
5381** by the calling process and must be big enough to hold at least
5382** pVfs->mxPathname bytes.
5383*/
5384static int unixGetTempname(int nBuf, char *zBuf){
drh8b3cf822010-06-01 21:02:51 +00005385 const char *zDir;
drhb7e50ad2015-11-28 21:49:53 +00005386 int iLimit = 0;
danielk197717b90b52008-06-06 11:11:25 +00005387
5388 /* It's odd to simulate an io-error here, but really this is just
5389 ** using the io-error infrastructure to test that SQLite handles this
5390 ** function failing.
5391 */
5392 SimulateIOError( return SQLITE_IOERR );
5393
drh7234c6d2010-06-19 15:10:09 +00005394 zDir = unixTempFileDir();
danielk197717b90b52008-06-06 11:11:25 +00005395 do{
drh970942e2015-11-25 23:13:14 +00005396 u64 r;
5397 sqlite3_randomness(sizeof(r), &r);
5398 assert( nBuf>2 );
5399 zBuf[nBuf-2] = 0;
5400 sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
5401 zDir, r, 0);
drhb7e50ad2015-11-28 21:49:53 +00005402 if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
drh99ab3b12011-03-02 15:09:07 +00005403 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005404 return SQLITE_OK;
5405}
5406
drhd2cb50b2009-01-09 21:41:17 +00005407#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005408/*
5409** Routine to transform a unixFile into a proxy-locking unixFile.
5410** Implementation in the proxy-lock division, but used by unixOpen()
5411** if SQLITE_PREFER_PROXY_LOCKING is defined.
5412*/
5413static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005414#endif
drhc66d5b62008-12-03 22:48:32 +00005415
dan08da86a2009-08-21 17:18:03 +00005416/*
5417** Search for an unused file descriptor that was opened on the database
5418** file (not a journal or master-journal file) identified by pathname
5419** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5420** argument to this function.
5421**
5422** Such a file descriptor may exist if a database connection was closed
5423** but the associated file descriptor could not be closed because some
5424** other file descriptor open on the same file is holding a file-lock.
5425** Refer to comments in the unixClose() function and the lengthy comment
5426** describing "Posix Advisory Locking" at the start of this file for
5427** further details. Also, ticket #4018.
5428**
5429** If a suitable file descriptor is found, then it is returned. If no
5430** such file descriptor is located, -1 is returned.
5431*/
dane946c392009-08-22 11:39:46 +00005432static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5433 UnixUnusedFd *pUnused = 0;
5434
5435 /* Do not search for an unused file descriptor on vxworks. Not because
5436 ** vxworks would not benefit from the change (it might, we're not sure),
5437 ** but because no way to test it is currently available. It is better
5438 ** not to risk breaking vxworks support for the sake of such an obscure
5439 ** feature. */
5440#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005441 struct stat sStat; /* Results of stat() call */
5442
5443 /* A stat() call may fail for various reasons. If this happens, it is
5444 ** almost certain that an open() call on the same path will also fail.
5445 ** For this reason, if an error occurs in the stat() call here, it is
5446 ** ignored and -1 is returned. The caller will try to open a new file
5447 ** descriptor on the same path, fail, and return an error to SQLite.
5448 **
5449 ** Even if a subsequent open() call does succeed, the consequences of
peter.d.reid60ec9142014-09-06 16:39:46 +00005450 ** not searching for a reusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005451 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005452 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005453
5454 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005455 pInode = inodeList;
5456 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5457 || pInode->fileId.ino!=sStat.st_ino) ){
5458 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005459 }
drh8af6c222010-05-14 12:43:01 +00005460 if( pInode ){
dane946c392009-08-22 11:39:46 +00005461 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005462 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005463 pUnused = *pp;
5464 if( pUnused ){
5465 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005466 }
5467 }
5468 unixLeaveMutex();
5469 }
dane946c392009-08-22 11:39:46 +00005470#endif /* if !OS_VXWORKS */
5471 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005472}
danielk197717b90b52008-06-06 11:11:25 +00005473
5474/*
danddb0ac42010-07-14 14:48:58 +00005475** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005476** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005477** and a value suitable for passing as the third argument to open(2) is
5478** written to *pMode. If an IO error occurs, an SQLite error code is
5479** returned and the value of *pMode is not modified.
5480**
peter.d.reid60ec9142014-09-06 16:39:46 +00005481** In most cases, this routine sets *pMode to 0, which will become
drh8c815d12012-02-13 20:16:37 +00005482** an indication to robust_open() to create the file using
5483** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5484** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005485** this function queries the file-system for the permissions on the
5486** corresponding database file and sets *pMode to this value. Whenever
5487** possible, WAL and journal files are created using the same permissions
5488** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005489**
5490** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5491** original filename is unavailable. But 8_3_NAMES is only used for
5492** FAT filesystems and permissions do not matter there, so just use
5493** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005494*/
5495static int findCreateFileMode(
5496 const char *zPath, /* Path of file (possibly) being created */
5497 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005498 mode_t *pMode, /* OUT: Permissions to open file with */
5499 uid_t *pUid, /* OUT: uid to set on the file */
5500 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005501){
5502 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005503 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005504 *pUid = 0;
5505 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005506 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005507 char zDb[MAX_PATHNAME+1]; /* Database file path */
5508 int nDb; /* Number of valid bytes in zDb */
5509 struct stat sStat; /* Output of stat() on database file */
5510
dana0c989d2010-11-05 18:07:37 +00005511 /* zPath is a path to a WAL or journal file. The following block derives
5512 ** the path to the associated database file from zPath. This block handles
5513 ** the following naming conventions:
5514 **
5515 ** "<path to db>-journal"
5516 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005517 ** "<path to db>-journalNN"
5518 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005519 **
drhd337c5b2011-10-20 18:23:35 +00005520 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005521 ** used by the test_multiplex.c module.
5522 */
5523 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005524#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00005525 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00005526 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005527#else
5528 while( zPath[nDb]!='-' ){
5529 assert( nDb>0 );
5530 assert( zPath[nDb]!='\n' );
5531 nDb--;
5532 }
5533#endif
danddb0ac42010-07-14 14:48:58 +00005534 memcpy(zDb, zPath, nDb);
5535 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005536
drh58384f12011-07-28 00:14:45 +00005537 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005538 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005539 *pUid = sStat.st_uid;
5540 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005541 }else{
5542 rc = SQLITE_IOERR_FSTAT;
5543 }
5544 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5545 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005546 }
5547 return rc;
5548}
5549
5550/*
danielk1977ad94b582007-08-20 06:44:22 +00005551** Open the file zPath.
5552**
danielk1977b4b47412007-08-17 15:53:36 +00005553** Previously, the SQLite OS layer used three functions in place of this
5554** one:
5555**
5556** sqlite3OsOpenReadWrite();
5557** sqlite3OsOpenReadOnly();
5558** sqlite3OsOpenExclusive();
5559**
5560** These calls correspond to the following combinations of flags:
5561**
5562** ReadWrite() -> (READWRITE | CREATE)
5563** ReadOnly() -> (READONLY)
5564** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5565**
5566** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5567** true, the file was configured to be automatically deleted when the
5568** file handle closed. To achieve the same effect using this new
5569** interface, add the DELETEONCLOSE flag to those specified above for
5570** OpenExclusive().
5571*/
5572static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005573 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5574 const char *zPath, /* Pathname of file to be opened */
5575 sqlite3_file *pFile, /* The file descriptor to be filled in */
5576 int flags, /* Input flags to control the opening */
5577 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005578){
dan08da86a2009-08-21 17:18:03 +00005579 unixFile *p = (unixFile *)pFile;
5580 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005581 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005582 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005583 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005584 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005585 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005586
5587 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5588 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5589 int isCreate = (flags & SQLITE_OPEN_CREATE);
5590 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5591 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005592#if SQLITE_ENABLE_LOCKING_STYLE
5593 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5594#endif
drh3d4435b2011-08-26 20:55:50 +00005595#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5596 struct statfs fsInfo;
5597#endif
danielk1977b4b47412007-08-17 15:53:36 +00005598
danielk1977fee2d252007-08-18 10:59:19 +00005599 /* If creating a master or main-file journal, this function will open
5600 ** a file-descriptor on the directory too. The first time unixSync()
5601 ** is called the directory file descriptor will be fsync()ed and close()d.
5602 */
drh0059eae2011-08-08 23:48:40 +00005603 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005604 eType==SQLITE_OPEN_MASTER_JOURNAL
5605 || eType==SQLITE_OPEN_MAIN_JOURNAL
5606 || eType==SQLITE_OPEN_WAL
5607 ));
danielk1977fee2d252007-08-18 10:59:19 +00005608
danielk197717b90b52008-06-06 11:11:25 +00005609 /* If argument zPath is a NULL pointer, this function is required to open
5610 ** a temporary file. Use this buffer to store the file name in.
5611 */
drhc02a43a2012-01-10 23:18:38 +00005612 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005613 const char *zName = zPath;
5614
danielk1977fee2d252007-08-18 10:59:19 +00005615 /* Check the following statements are true:
5616 **
5617 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5618 ** (b) if CREATE is set, then READWRITE must also be set, and
5619 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005620 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005621 */
danielk1977b4b47412007-08-17 15:53:36 +00005622 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005623 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005624 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005625 assert(isDelete==0 || isCreate);
5626
danddb0ac42010-07-14 14:48:58 +00005627 /* The main DB, main journal, WAL file and master journal are never
5628 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005629 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5630 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5631 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005632 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005633
danielk1977fee2d252007-08-18 10:59:19 +00005634 /* Assert that the upper layer has set one of the "file-type" flags. */
5635 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5636 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5637 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005638 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005639 );
5640
drhb00d8622014-01-01 15:18:36 +00005641 /* Detect a pid change and reset the PRNG. There is a race condition
5642 ** here such that two or more threads all trying to open databases at
5643 ** the same instant might all reset the PRNG. But multiple resets
5644 ** are harmless.
5645 */
drh5ac93652015-03-21 20:59:43 +00005646 if( randomnessPid!=osGetpid(0) ){
5647 randomnessPid = osGetpid(0);
drhb00d8622014-01-01 15:18:36 +00005648 sqlite3_randomness(0,0);
5649 }
5650
dan08da86a2009-08-21 17:18:03 +00005651 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005652
dan08da86a2009-08-21 17:18:03 +00005653 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005654 UnixUnusedFd *pUnused;
5655 pUnused = findReusableFd(zName, flags);
5656 if( pUnused ){
5657 fd = pUnused->fd;
5658 }else{
drhf3cdcdc2015-04-29 16:50:28 +00005659 pUnused = sqlite3_malloc64(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005660 if( !pUnused ){
5661 return SQLITE_NOMEM;
5662 }
5663 }
5664 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005665
5666 /* Database filenames are double-zero terminated if they are not
5667 ** URIs with parameters. Hence, they can always be passed into
5668 ** sqlite3_uri_parameter(). */
5669 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5670
dan08da86a2009-08-21 17:18:03 +00005671 }else if( !zName ){
5672 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005673 assert(isDelete && !syncDir);
drhb7e50ad2015-11-28 21:49:53 +00005674 rc = unixGetTempname(pVfs->mxPathname, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005675 if( rc!=SQLITE_OK ){
5676 return rc;
5677 }
5678 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005679
5680 /* Generated temporary filenames are always double-zero terminated
5681 ** for use by sqlite3_uri_parameter(). */
5682 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005683 }
5684
dan08da86a2009-08-21 17:18:03 +00005685 /* Determine the value of the flags parameter passed to POSIX function
5686 ** open(). These must be calculated even if open() is not called, as
5687 ** they may be stored as part of the file handle and used by the
5688 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005689 if( isReadonly ) openFlags |= O_RDONLY;
5690 if( isReadWrite ) openFlags |= O_RDWR;
5691 if( isCreate ) openFlags |= O_CREAT;
5692 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5693 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005694
danielk1977b4b47412007-08-17 15:53:36 +00005695 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005696 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005697 uid_t uid; /* Userid for the file */
5698 gid_t gid; /* Groupid for the file */
5699 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005700 if( rc!=SQLITE_OK ){
5701 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005702 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005703 return rc;
5704 }
drhad4f1e52011-03-04 15:43:57 +00005705 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005706 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
drh5a2d9702015-11-26 02:21:05 +00005707 assert( !isExclusive || (openFlags & O_CREAT)!=0 );
5708 if( fd<0 && errno!=EISDIR && isReadWrite ){
dan08da86a2009-08-21 17:18:03 +00005709 /* Failed to open the file for read/write access. Try read-only. */
5710 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005711 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005712 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005713 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005714 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005715 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005716 }
5717 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005718 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005719 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005720 }
drhac7c3ac2012-02-11 19:23:48 +00005721
5722 /* If this process is running as root and if creating a new rollback
5723 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005724 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005725 */
5726 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drh6226ca22015-11-24 15:06:28 +00005727 robustFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005728 }
danielk1977b4b47412007-08-17 15:53:36 +00005729 }
dan08da86a2009-08-21 17:18:03 +00005730 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005731 if( pOutFlags ){
5732 *pOutFlags = flags;
5733 }
5734
dane946c392009-08-22 11:39:46 +00005735 if( p->pUnused ){
5736 p->pUnused->fd = fd;
5737 p->pUnused->flags = flags;
5738 }
5739
danielk1977b4b47412007-08-17 15:53:36 +00005740 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005741#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005742 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00005743#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
5744 zPath = sqlite3_mprintf("%s", zName);
5745 if( zPath==0 ){
5746 robust_close(p, fd, __LINE__);
5747 return SQLITE_NOMEM;
5748 }
chw97185482008-11-17 08:05:31 +00005749#else
drh036ac7f2011-08-08 23:18:05 +00005750 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005751#endif
danielk1977b4b47412007-08-17 15:53:36 +00005752 }
drh41022642008-11-21 00:24:42 +00005753#if SQLITE_ENABLE_LOCKING_STYLE
5754 else{
dan08da86a2009-08-21 17:18:03 +00005755 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005756 }
5757#endif
5758
drhda0e7682008-07-30 15:27:54 +00005759 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005760
drh7ed97b92010-01-20 13:07:21 +00005761
5762#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005763 if( fstatfs(fd, &fsInfo) == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00005764 storeLastErrno(p, errno);
drh0e9365c2011-03-02 02:08:13 +00005765 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005766 return SQLITE_IOERR_ACCESS;
5767 }
5768 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5769 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5770 }
drh4bf66fd2015-02-19 02:43:02 +00005771 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
5772 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5773 }
drh7ed97b92010-01-20 13:07:21 +00005774#endif
drhc02a43a2012-01-10 23:18:38 +00005775
5776 /* Set up appropriate ctrlFlags */
5777 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5778 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5779 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5780 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5781 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5782
drh7ed97b92010-01-20 13:07:21 +00005783#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005784#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005785 isAutoProxy = 1;
5786#endif
5787 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005788 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5789 int useProxy = 0;
5790
dan08da86a2009-08-21 17:18:03 +00005791 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5792 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005793 if( envforce!=NULL ){
5794 useProxy = atoi(envforce)>0;
5795 }else{
aswiftaebf4132008-11-21 00:10:35 +00005796 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5797 }
5798 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005799 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005800 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005801 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005802 if( rc!=SQLITE_OK ){
5803 /* Use unixClose to clean up the resources added in fillInUnixFile
5804 ** and clear all the structure's references. Specifically,
5805 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5806 */
5807 unixClose(pFile);
5808 return rc;
5809 }
aswiftaebf4132008-11-21 00:10:35 +00005810 }
dane946c392009-08-22 11:39:46 +00005811 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005812 }
5813 }
5814#endif
5815
drhc02a43a2012-01-10 23:18:38 +00005816 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5817
dane946c392009-08-22 11:39:46 +00005818open_finished:
5819 if( rc!=SQLITE_OK ){
5820 sqlite3_free(p->pUnused);
5821 }
5822 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005823}
5824
dane946c392009-08-22 11:39:46 +00005825
danielk1977b4b47412007-08-17 15:53:36 +00005826/*
danielk1977fee2d252007-08-18 10:59:19 +00005827** Delete the file at zPath. If the dirSync argument is true, fsync()
5828** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005829*/
drh6b9d6dd2008-12-03 19:34:47 +00005830static int unixDelete(
5831 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5832 const char *zPath, /* Name of file to be deleted */
5833 int dirSync /* If true, fsync() directory after deleting file */
5834){
danielk1977fee2d252007-08-18 10:59:19 +00005835 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005836 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005837 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005838 if( osUnlink(zPath)==(-1) ){
drhbd945542014-08-13 11:39:42 +00005839 if( errno==ENOENT
5840#if OS_VXWORKS
drh19541f32014-09-01 13:37:55 +00005841 || osAccess(zPath,0)!=0
drhbd945542014-08-13 11:39:42 +00005842#endif
5843 ){
dan9fc5b4a2012-11-09 20:17:26 +00005844 rc = SQLITE_IOERR_DELETE_NOENT;
5845 }else{
drhb4308162012-11-09 21:40:02 +00005846 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005847 }
drhb4308162012-11-09 21:40:02 +00005848 return rc;
drh5d4feff2010-07-14 01:45:22 +00005849 }
danielk1977d39fa702008-10-16 13:27:40 +00005850#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005851 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005852 int fd;
drh90315a22011-08-10 01:52:12 +00005853 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005854 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005855#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005856 if( fsync(fd)==-1 )
5857#else
5858 if( fsync(fd) )
5859#endif
5860 {
dane18d4952011-02-21 11:46:24 +00005861 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005862 }
drh0e9365c2011-03-02 02:08:13 +00005863 robust_close(0, fd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00005864 }else{
5865 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00005866 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005867 }
5868 }
danielk1977d138dd82008-10-15 16:02:48 +00005869#endif
danielk1977fee2d252007-08-18 10:59:19 +00005870 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005871}
5872
danielk197790949c22007-08-17 16:50:38 +00005873/*
mistachkin48864df2013-03-21 21:20:32 +00005874** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00005875** test performed depends on the value of flags:
5876**
5877** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5878** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5879** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5880**
5881** Otherwise return 0.
5882*/
danielk1977861f7452008-06-05 11:39:11 +00005883static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005884 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5885 const char *zPath, /* Path of the file to examine */
5886 int flags, /* What do we want to learn about the zPath file? */
5887 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005888){
danielk1977397d65f2008-11-19 11:35:39 +00005889 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005890 SimulateIOError( return SQLITE_IOERR_ACCESS; );
drhd260b5b2015-11-25 18:03:33 +00005891 assert( pResOut!=0 );
danielk1977b4b47412007-08-17 15:53:36 +00005892
drhd260b5b2015-11-25 18:03:33 +00005893 /* The spec says there are three possible values for flags. But only
5894 ** two of them are actually used */
5895 assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
5896
5897 if( flags==SQLITE_ACCESS_EXISTS ){
dan83acd422010-06-18 11:10:06 +00005898 struct stat buf;
drhd260b5b2015-11-25 18:03:33 +00005899 *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
5900 }else{
5901 *pResOut = osAccess(zPath, W_OK|R_OK)==0;
dan83acd422010-06-18 11:10:06 +00005902 }
danielk1977861f7452008-06-05 11:39:11 +00005903 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005904}
5905
danielk1977b4b47412007-08-17 15:53:36 +00005906
5907/*
5908** Turn a relative pathname into a full pathname. The relative path
5909** is stored as a nul-terminated string in the buffer pointed to by
5910** zPath.
5911**
5912** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5913** (in this case, MAX_PATHNAME bytes). The full-path is written to
5914** this buffer before returning.
5915*/
danielk1977adfb9b02007-09-17 07:02:56 +00005916static int unixFullPathname(
5917 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5918 const char *zPath, /* Possibly relative input path */
5919 int nOut, /* Size of output buffer in bytes */
5920 char *zOut /* Output buffer */
5921){
dan245fdc62015-10-31 17:58:33 +00005922 int nByte;
danielk1977843e65f2007-09-01 16:16:15 +00005923
5924 /* It's odd to simulate an io-error here, but really this is just
5925 ** using the io-error infrastructure to test that SQLite handles this
5926 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005927 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005928 */
5929 SimulateIOError( return SQLITE_ERROR );
5930
drh153c62c2007-08-24 03:51:33 +00005931 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005932 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005933
dan245fdc62015-10-31 17:58:33 +00005934 /* Attempt to resolve the path as if it were a symbolic link. If it is
5935 ** a symbolic link, the resolved path is stored in buffer zOut[]. Or, if
5936 ** the identified file is not a symbolic link or does not exist, then
5937 ** zPath is copied directly into zOut. Either way, nByte is left set to
5938 ** the size of the string copied into zOut[] in bytes. */
5939 nByte = osReadlink(zPath, zOut, nOut-1);
5940 if( nByte<0 ){
5941 if( errno!=EINVAL && errno!=ENOENT ){
5942 return unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zPath);
5943 }
drhd260b5b2015-11-25 18:03:33 +00005944 sqlite3_snprintf(nOut, zOut, "%s", zPath);
dan245fdc62015-10-31 17:58:33 +00005945 nByte = sqlite3Strlen30(zOut);
danielk1977b4b47412007-08-17 15:53:36 +00005946 }else{
dan245fdc62015-10-31 17:58:33 +00005947 zOut[nByte] = '\0';
5948 }
5949
5950 /* If buffer zOut[] now contains an absolute path there is nothing more
5951 ** to do. If it contains a relative path, do the following:
5952 **
5953 ** * move the relative path string so that it is at the end of th
5954 ** zOut[] buffer.
5955 ** * Call getcwd() to read the path of the current working directory
5956 ** into the start of the zOut[] buffer.
5957 ** * Append a '/' character to the cwd string and move the
5958 ** relative path back within the buffer so that it immediately
5959 ** follows the '/'.
5960 **
5961 ** This code is written so that if the combination of the CWD and relative
5962 ** path are larger than the allocated size of zOut[] the CWD is silently
5963 ** truncated to make it fit. This is Ok, as SQLite refuses to open any
5964 ** file for which this function returns a full path larger than (nOut-8)
5965 ** bytes in size. */
drh025d2f72015-11-30 22:22:23 +00005966 testcase( nByte==nOut-5 );
5967 testcase( nByte==nOut-4 );
5968 if( zOut[0]!='/' && nByte<nOut-4 ){
danielk1977b4b47412007-08-17 15:53:36 +00005969 int nCwd;
dan245fdc62015-10-31 17:58:33 +00005970 int nRem = nOut-nByte-1;
5971 memmove(&zOut[nRem], zOut, nByte+1);
5972 zOut[nRem-1] = '\0';
5973 if( osGetcwd(zOut, nRem-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005974 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005975 }
dan245fdc62015-10-31 17:58:33 +00005976 nCwd = sqlite3Strlen30(zOut);
5977 assert( nCwd<=nRem-1 );
5978 zOut[nCwd] = '/';
5979 memmove(&zOut[nCwd+1], &zOut[nRem], nByte+1);
danielk1977b4b47412007-08-17 15:53:36 +00005980 }
dan245fdc62015-10-31 17:58:33 +00005981
danielk1977b4b47412007-08-17 15:53:36 +00005982 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005983}
5984
drh0ccebe72005-06-07 22:22:50 +00005985
drh761df872006-12-21 01:29:22 +00005986#ifndef SQLITE_OMIT_LOAD_EXTENSION
5987/*
5988** Interfaces for opening a shared library, finding entry points
5989** within the shared library, and closing the shared library.
5990*/
5991#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005992static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5993 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005994 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5995}
danielk197795c8a542007-09-01 06:51:27 +00005996
5997/*
5998** SQLite calls this function immediately after a call to unixDlSym() or
5999** unixDlOpen() fails (returns a null pointer). If a more detailed error
6000** message is available, it is written to zBufOut. If no error message
6001** is available, zBufOut is left unmodified and SQLite uses a default
6002** error message.
6003*/
danielk1977397d65f2008-11-19 11:35:39 +00006004static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006005 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006006 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006007 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006008 zErr = dlerror();
6009 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006010 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006011 }
drh6c7d5c52008-11-21 20:32:33 +00006012 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006013}
drh1875f7a2008-12-08 18:19:17 +00006014static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6015 /*
6016 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6017 ** cast into a pointer to a function. And yet the library dlsym() routine
6018 ** returns a void* which is really a pointer to a function. So how do we
6019 ** use dlsym() with -pedantic-errors?
6020 **
6021 ** Variable x below is defined to be a pointer to a function taking
6022 ** parameters void* and const char* and returning a pointer to a function.
6023 ** We initialize x by assigning it a pointer to the dlsym() function.
6024 ** (That assignment requires a cast.) Then we call the function that
6025 ** x points to.
6026 **
6027 ** This work-around is unlikely to work correctly on any system where
6028 ** you really cannot cast a function pointer into void*. But then, on the
6029 ** other hand, dlsym() will not work on such a system either, so we have
6030 ** not really lost anything.
6031 */
6032 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006033 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006034 x = (void(*(*)(void*,const char*))(void))dlsym;
6035 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006036}
danielk1977397d65f2008-11-19 11:35:39 +00006037static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6038 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006039 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006040}
danielk1977b4b47412007-08-17 15:53:36 +00006041#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6042 #define unixDlOpen 0
6043 #define unixDlError 0
6044 #define unixDlSym 0
6045 #define unixDlClose 0
6046#endif
6047
6048/*
danielk197790949c22007-08-17 16:50:38 +00006049** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006050*/
danielk1977397d65f2008-11-19 11:35:39 +00006051static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6052 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006053 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006054
drhbbd42a62004-05-22 17:41:58 +00006055 /* We have to initialize zBuf to prevent valgrind from reporting
6056 ** errors. The reports issued by valgrind are incorrect - we would
6057 ** prefer that the randomness be increased by making use of the
6058 ** uninitialized space in zBuf - but valgrind errors tend to worry
6059 ** some users. Rather than argue, it seems easier just to initialize
6060 ** the whole array and silence valgrind, even if that means less randomness
6061 ** in the random seed.
6062 **
6063 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006064 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006065 ** tests repeatable.
6066 */
danielk1977b4b47412007-08-17 15:53:36 +00006067 memset(zBuf, 0, nBuf);
drh5ac93652015-03-21 20:59:43 +00006068 randomnessPid = osGetpid(0);
drh6a412b82015-04-30 12:31:49 +00006069#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
drhbbd42a62004-05-22 17:41:58 +00006070 {
drhb00d8622014-01-01 15:18:36 +00006071 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006072 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006073 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006074 time_t t;
6075 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006076 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006077 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6078 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6079 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006080 }else{
drhc18b4042012-02-10 03:10:27 +00006081 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006082 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006083 }
drhbbd42a62004-05-22 17:41:58 +00006084 }
6085#endif
drh72cbd072008-10-14 17:58:38 +00006086 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006087}
6088
danielk1977b4b47412007-08-17 15:53:36 +00006089
drhbbd42a62004-05-22 17:41:58 +00006090/*
6091** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006092** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006093** The return value is the number of microseconds of sleep actually
6094** requested from the underlying operating system, a number which
6095** might be greater than or equal to the argument, but not less
6096** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006097*/
danielk1977397d65f2008-11-19 11:35:39 +00006098static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006099#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006100 struct timespec sp;
6101
6102 sp.tv_sec = microseconds / 1000000;
6103 sp.tv_nsec = (microseconds % 1000000) * 1000;
6104 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006105 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006106 return microseconds;
6107#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006108 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006109 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006110 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006111#else
danielk1977b4b47412007-08-17 15:53:36 +00006112 int seconds = (microseconds+999999)/1000000;
6113 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006114 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006115 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006116#endif
drh88f474a2006-01-02 20:00:12 +00006117}
6118
6119/*
drh6b9d6dd2008-12-03 19:34:47 +00006120** The following variable, if set to a non-zero value, is interpreted as
6121** the number of seconds since 1970 and is used to set the result of
6122** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006123*/
6124#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006125int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006126#endif
6127
6128/*
drhb7e8ea22010-05-03 14:32:30 +00006129** Find the current time (in Universal Coordinated Time). Write into *piNow
6130** the current time and date as a Julian Day number times 86_400_000. In
6131** other words, write into *piNow the number of milliseconds since the Julian
6132** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6133** proleptic Gregorian calendar.
6134**
drh31702252011-10-12 23:13:43 +00006135** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6136** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006137*/
6138static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6139 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006140 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006141#if defined(NO_GETTOD)
6142 time_t t;
6143 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006144 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006145#elif OS_VXWORKS
6146 struct timespec sNow;
6147 clock_gettime(CLOCK_REALTIME, &sNow);
6148 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6149#else
6150 struct timeval sNow;
drh970942e2015-11-25 23:13:14 +00006151 (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
6152 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
drhb7e8ea22010-05-03 14:32:30 +00006153#endif
6154
6155#ifdef SQLITE_TEST
6156 if( sqlite3_current_time ){
6157 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6158 }
6159#endif
6160 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006161 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006162}
6163
drh5337dac2015-11-25 15:15:03 +00006164#if 0 /* Not used */
drhb7e8ea22010-05-03 14:32:30 +00006165/*
drhbbd42a62004-05-22 17:41:58 +00006166** Find the current time (in Universal Coordinated Time). Write the
6167** current time and date as a Julian Day number into *prNow and
6168** return 0. Return 1 if the time and date cannot be found.
6169*/
danielk1977397d65f2008-11-19 11:35:39 +00006170static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006171 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006172 int rc;
drhff828942010-06-26 21:34:06 +00006173 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006174 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006175 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006176 return rc;
drhbbd42a62004-05-22 17:41:58 +00006177}
drh5337dac2015-11-25 15:15:03 +00006178#else
6179# define unixCurrentTime 0
6180#endif
danielk1977b4b47412007-08-17 15:53:36 +00006181
drh5337dac2015-11-25 15:15:03 +00006182#if 0 /* Not used */
drh6b9d6dd2008-12-03 19:34:47 +00006183/*
6184** We added the xGetLastError() method with the intention of providing
6185** better low-level error messages when operating-system problems come up
6186** during SQLite operation. But so far, none of that has been implemented
6187** in the core. So this routine is never called. For now, it is merely
6188** a place-holder.
6189*/
danielk1977397d65f2008-11-19 11:35:39 +00006190static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6191 UNUSED_PARAMETER(NotUsed);
6192 UNUSED_PARAMETER(NotUsed2);
6193 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00006194 return 0;
6195}
drh5337dac2015-11-25 15:15:03 +00006196#else
6197# define unixGetLastError 0
6198#endif
danielk1977bcb97fe2008-06-06 15:49:29 +00006199
drhf2424c52010-04-26 00:04:55 +00006200
6201/*
drh734c9862008-11-28 15:37:20 +00006202************************ End of sqlite3_vfs methods ***************************
6203******************************************************************************/
6204
drh715ff302008-12-03 22:32:44 +00006205/******************************************************************************
6206************************** Begin Proxy Locking ********************************
6207**
6208** Proxy locking is a "uber-locking-method" in this sense: It uses the
6209** other locking methods on secondary lock files. Proxy locking is a
6210** meta-layer over top of the primitive locking implemented above. For
6211** this reason, the division that implements of proxy locking is deferred
6212** until late in the file (here) after all of the other I/O methods have
6213** been defined - so that the primitive locking methods are available
6214** as services to help with the implementation of proxy locking.
6215**
6216****
6217**
6218** The default locking schemes in SQLite use byte-range locks on the
6219** database file to coordinate safe, concurrent access by multiple readers
6220** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6221** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6222** as POSIX read & write locks over fixed set of locations (via fsctl),
6223** on AFP and SMB only exclusive byte-range locks are available via fsctl
6224** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6225** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6226** address in the shared range is taken for a SHARED lock, the entire
6227** shared range is taken for an EXCLUSIVE lock):
6228**
drhf2f105d2012-08-20 15:53:54 +00006229** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006230** RESERVED_BYTE 0x40000001
6231** SHARED_RANGE 0x40000002 -> 0x40000200
6232**
6233** This works well on the local file system, but shows a nearly 100x
6234** slowdown in read performance on AFP because the AFP client disables
6235** the read cache when byte-range locks are present. Enabling the read
6236** cache exposes a cache coherency problem that is present on all OS X
6237** supported network file systems. NFS and AFP both observe the
6238** close-to-open semantics for ensuring cache coherency
6239** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6240** address the requirements for concurrent database access by multiple
6241** readers and writers
6242** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6243**
6244** To address the performance and cache coherency issues, proxy file locking
6245** changes the way database access is controlled by limiting access to a
6246** single host at a time and moving file locks off of the database file
6247** and onto a proxy file on the local file system.
6248**
6249**
6250** Using proxy locks
6251** -----------------
6252**
6253** C APIs
6254**
drh4bf66fd2015-02-19 02:43:02 +00006255** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
drh715ff302008-12-03 22:32:44 +00006256** <proxy_path> | ":auto:");
drh4bf66fd2015-02-19 02:43:02 +00006257** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6258** &<proxy_path>);
drh715ff302008-12-03 22:32:44 +00006259**
6260**
6261** SQL pragmas
6262**
6263** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6264** PRAGMA [database.]lock_proxy_file
6265**
6266** Specifying ":auto:" means that if there is a conch file with a matching
6267** host ID in it, the proxy path in the conch file will be used, otherwise
6268** a proxy path based on the user's temp dir
6269** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6270** actual proxy file name is generated from the name and path of the
6271** database file. For example:
6272**
6273** For database path "/Users/me/foo.db"
6274** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6275**
6276** Once a lock proxy is configured for a database connection, it can not
6277** be removed, however it may be switched to a different proxy path via
6278** the above APIs (assuming the conch file is not being held by another
6279** connection or process).
6280**
6281**
6282** How proxy locking works
6283** -----------------------
6284**
6285** Proxy file locking relies primarily on two new supporting files:
6286**
6287** * conch file to limit access to the database file to a single host
6288** at a time
6289**
6290** * proxy file to act as a proxy for the advisory locks normally
6291** taken on the database
6292**
6293** The conch file - to use a proxy file, sqlite must first "hold the conch"
6294** by taking an sqlite-style shared lock on the conch file, reading the
6295** contents and comparing the host's unique host ID (see below) and lock
6296** proxy path against the values stored in the conch. The conch file is
6297** stored in the same directory as the database file and the file name
6298** is patterned after the database file name as ".<databasename>-conch".
peter.d.reid60ec9142014-09-06 16:39:46 +00006299** If the conch file does not exist, or its contents do not match the
drh715ff302008-12-03 22:32:44 +00006300** host ID and/or proxy path, then the lock is escalated to an exclusive
6301** lock and the conch file contents is updated with the host ID and proxy
6302** path and the lock is downgraded to a shared lock again. If the conch
6303** is held by another process (with a shared lock), the exclusive lock
6304** will fail and SQLITE_BUSY is returned.
6305**
6306** The proxy file - a single-byte file used for all advisory file locks
6307** normally taken on the database file. This allows for safe sharing
6308** of the database file for multiple readers and writers on the same
6309** host (the conch ensures that they all use the same local lock file).
6310**
drh715ff302008-12-03 22:32:44 +00006311** Requesting the lock proxy does not immediately take the conch, it is
6312** only taken when the first request to lock database file is made.
6313** This matches the semantics of the traditional locking behavior, where
6314** opening a connection to a database file does not take a lock on it.
6315** The shared lock and an open file descriptor are maintained until
6316** the connection to the database is closed.
6317**
6318** The proxy file and the lock file are never deleted so they only need
6319** to be created the first time they are used.
6320**
6321** Configuration options
6322** ---------------------
6323**
6324** SQLITE_PREFER_PROXY_LOCKING
6325**
6326** Database files accessed on non-local file systems are
6327** automatically configured for proxy locking, lock files are
6328** named automatically using the same logic as
6329** PRAGMA lock_proxy_file=":auto:"
6330**
6331** SQLITE_PROXY_DEBUG
6332**
6333** Enables the logging of error messages during host id file
6334** retrieval and creation
6335**
drh715ff302008-12-03 22:32:44 +00006336** LOCKPROXYDIR
6337**
6338** Overrides the default directory used for lock proxy files that
6339** are named automatically via the ":auto:" setting
6340**
6341** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6342**
6343** Permissions to use when creating a directory for storing the
6344** lock proxy files, only used when LOCKPROXYDIR is not set.
6345**
6346**
6347** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6348** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6349** force proxy locking to be used for every database file opened, and 0
6350** will force automatic proxy locking to be disabled for all database
drh4bf66fd2015-02-19 02:43:02 +00006351** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
drh715ff302008-12-03 22:32:44 +00006352** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6353*/
6354
6355/*
6356** Proxy locking is only available on MacOSX
6357*/
drhd2cb50b2009-01-09 21:41:17 +00006358#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006359
drh715ff302008-12-03 22:32:44 +00006360/*
6361** The proxyLockingContext has the path and file structures for the remote
6362** and local proxy files in it
6363*/
6364typedef struct proxyLockingContext proxyLockingContext;
6365struct proxyLockingContext {
6366 unixFile *conchFile; /* Open conch file */
6367 char *conchFilePath; /* Name of the conch file */
6368 unixFile *lockProxy; /* Open proxy lock file */
6369 char *lockProxyPath; /* Name of the proxy lock file */
6370 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006371 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh4bf66fd2015-02-19 02:43:02 +00006372 int nFails; /* Number of conch taking failures */
drh715ff302008-12-03 22:32:44 +00006373 void *oldLockingContext; /* Original lockingcontext to restore on close */
6374 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6375};
6376
drh7ed97b92010-01-20 13:07:21 +00006377/*
6378** The proxy lock file path for the database at dbPath is written into lPath,
6379** which must point to valid, writable memory large enough for a maxLen length
6380** file path.
drh715ff302008-12-03 22:32:44 +00006381*/
drh715ff302008-12-03 22:32:44 +00006382static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6383 int len;
6384 int dbLen;
6385 int i;
6386
6387#ifdef LOCKPROXYDIR
6388 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6389#else
6390# ifdef _CS_DARWIN_USER_TEMP_DIR
6391 {
drh7ed97b92010-01-20 13:07:21 +00006392 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006393 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006394 lPath, errno, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006395 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006396 }
drh7ed97b92010-01-20 13:07:21 +00006397 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006398 }
6399# else
6400 len = strlcpy(lPath, "/tmp/", maxLen);
6401# endif
6402#endif
6403
6404 if( lPath[len-1]!='/' ){
6405 len = strlcat(lPath, "/", maxLen);
6406 }
6407
6408 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006409 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006410 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006411 char c = dbPath[i];
6412 lPath[i+len] = (c=='/')?'_':c;
6413 }
6414 lPath[i+len]='\0';
6415 strlcat(lPath, ":auto:", maxLen);
drh5ac93652015-03-21 20:59:43 +00006416 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006417 return SQLITE_OK;
6418}
6419
drh7ed97b92010-01-20 13:07:21 +00006420/*
6421 ** Creates the lock file and any missing directories in lockPath
6422 */
6423static int proxyCreateLockPath(const char *lockPath){
6424 int i, len;
6425 char buf[MAXPATHLEN];
6426 int start = 0;
6427
6428 assert(lockPath!=NULL);
6429 /* try to create all the intermediate directories */
6430 len = (int)strlen(lockPath);
6431 buf[0] = lockPath[0];
6432 for( i=1; i<len; i++ ){
6433 if( lockPath[i] == '/' && (i - start > 0) ){
6434 /* only mkdir if leaf dir != "." or "/" or ".." */
6435 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6436 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6437 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006438 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006439 int err=errno;
6440 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006441 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006442 "'%s' proxy lock path=%s pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006443 buf, strerror(err), lockPath, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006444 return err;
6445 }
6446 }
6447 }
6448 start=i+1;
6449 }
6450 buf[i] = lockPath[i];
6451 }
drh62aaa6c2015-11-21 17:27:42 +00006452 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006453 return 0;
6454}
6455
drh715ff302008-12-03 22:32:44 +00006456/*
6457** Create a new VFS file descriptor (stored in memory obtained from
6458** sqlite3_malloc) and open the file named "path" in the file descriptor.
6459**
6460** The caller is responsible not only for closing the file descriptor
6461** but also for freeing the memory associated with the file descriptor.
6462*/
drh7ed97b92010-01-20 13:07:21 +00006463static int proxyCreateUnixFile(
6464 const char *path, /* path for the new unixFile */
6465 unixFile **ppFile, /* unixFile created and returned by ref */
6466 int islockfile /* if non zero missing dirs will be created */
6467) {
6468 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006469 unixFile *pNew;
6470 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006471 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006472 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006473 int terrno = 0;
6474 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006475
drh7ed97b92010-01-20 13:07:21 +00006476 /* 1. first try to open/create the file
6477 ** 2. if that fails, and this is a lock file (not-conch), try creating
6478 ** the parent directories and then try again.
6479 ** 3. if that fails, try to open the file read-only
6480 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6481 */
6482 pUnused = findReusableFd(path, openFlags);
6483 if( pUnused ){
6484 fd = pUnused->fd;
6485 }else{
drhf3cdcdc2015-04-29 16:50:28 +00006486 pUnused = sqlite3_malloc64(sizeof(*pUnused));
drh7ed97b92010-01-20 13:07:21 +00006487 if( !pUnused ){
6488 return SQLITE_NOMEM;
6489 }
6490 }
6491 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006492 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006493 terrno = errno;
6494 if( fd<0 && errno==ENOENT && islockfile ){
6495 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006496 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006497 }
6498 }
6499 }
6500 if( fd<0 ){
6501 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006502 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006503 terrno = errno;
6504 }
6505 if( fd<0 ){
6506 if( islockfile ){
6507 return SQLITE_BUSY;
6508 }
6509 switch (terrno) {
6510 case EACCES:
6511 return SQLITE_PERM;
6512 case EIO:
6513 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6514 default:
drh9978c972010-02-23 17:36:32 +00006515 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006516 }
6517 }
6518
drhf3cdcdc2015-04-29 16:50:28 +00006519 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
drh7ed97b92010-01-20 13:07:21 +00006520 if( pNew==NULL ){
6521 rc = SQLITE_NOMEM;
6522 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006523 }
6524 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006525 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006526 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006527 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006528 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006529 pUnused->fd = fd;
6530 pUnused->flags = openFlags;
6531 pNew->pUnused = pUnused;
6532
drhc02a43a2012-01-10 23:18:38 +00006533 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006534 if( rc==SQLITE_OK ){
6535 *ppFile = pNew;
6536 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006537 }
drh7ed97b92010-01-20 13:07:21 +00006538end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006539 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006540 sqlite3_free(pNew);
6541 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006542 return rc;
6543}
6544
drh7ed97b92010-01-20 13:07:21 +00006545#ifdef SQLITE_TEST
6546/* simulate multiple hosts by creating unique hostid file paths */
6547int sqlite3_hostid_num = 0;
6548#endif
6549
6550#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6551
drh6bca6512015-04-13 23:05:28 +00006552#ifdef HAVE_GETHOSTUUID
drh0ab216a2010-07-02 17:10:40 +00006553/* Not always defined in the headers as it ought to be */
6554extern int gethostuuid(uuid_t id, const struct timespec *wait);
drh6bca6512015-04-13 23:05:28 +00006555#endif
drh0ab216a2010-07-02 17:10:40 +00006556
drh7ed97b92010-01-20 13:07:21 +00006557/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6558** bytes of writable memory.
6559*/
6560static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006561 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6562 memset(pHostID, 0, PROXY_HOSTIDLEN);
drh6bca6512015-04-13 23:05:28 +00006563#ifdef HAVE_GETHOSTUUID
drh29ecd8a2010-12-21 00:16:40 +00006564 {
drh4bf66fd2015-02-19 02:43:02 +00006565 struct timespec timeout = {1, 0}; /* 1 sec timeout */
drh29ecd8a2010-12-21 00:16:40 +00006566 if( gethostuuid(pHostID, &timeout) ){
6567 int err = errno;
6568 if( pError ){
6569 *pError = err;
6570 }
6571 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006572 }
drh7ed97b92010-01-20 13:07:21 +00006573 }
drh3d4435b2011-08-26 20:55:50 +00006574#else
6575 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006576#endif
drh7ed97b92010-01-20 13:07:21 +00006577#ifdef SQLITE_TEST
6578 /* simulate multiple hosts by creating unique hostid file paths */
6579 if( sqlite3_hostid_num != 0){
6580 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6581 }
6582#endif
6583
6584 return SQLITE_OK;
6585}
6586
6587/* The conch file contains the header, host id and lock file path
6588 */
6589#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6590#define PROXY_HEADERLEN 1 /* conch file header length */
6591#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6592#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6593
6594/*
6595** Takes an open conch file, copies the contents to a new path and then moves
6596** it back. The newly created file's file descriptor is assigned to the
6597** conch file structure and finally the original conch file descriptor is
6598** closed. Returns zero if successful.
6599*/
6600static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6601 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6602 unixFile *conchFile = pCtx->conchFile;
6603 char tPath[MAXPATHLEN];
6604 char buf[PROXY_MAXCONCHLEN];
6605 char *cPath = pCtx->conchFilePath;
6606 size_t readLen = 0;
6607 size_t pathLen = 0;
6608 char errmsg[64] = "";
6609 int fd = -1;
6610 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006611 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006612
6613 /* create a new path by replace the trailing '-conch' with '-break' */
6614 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6615 if( pathLen>MAXPATHLEN || pathLen<6 ||
6616 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006617 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006618 goto end_breaklock;
6619 }
6620 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006621 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006622 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006623 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006624 goto end_breaklock;
6625 }
6626 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006627 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006628 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006629 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006630 goto end_breaklock;
6631 }
drhe562be52011-03-02 18:01:10 +00006632 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006633 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006634 goto end_breaklock;
6635 }
6636 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006637 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006638 goto end_breaklock;
6639 }
6640 rc = 0;
6641 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006642 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006643 conchFile->h = fd;
6644 conchFile->openFlags = O_RDWR | O_CREAT;
6645
6646end_breaklock:
6647 if( rc ){
6648 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006649 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006650 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006651 }
6652 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6653 }
6654 return rc;
6655}
6656
6657/* Take the requested lock on the conch file and break a stale lock if the
6658** host id matches.
6659*/
6660static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6661 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6662 unixFile *conchFile = pCtx->conchFile;
6663 int rc = SQLITE_OK;
6664 int nTries = 0;
6665 struct timespec conchModTime;
6666
drh3d4435b2011-08-26 20:55:50 +00006667 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006668 do {
6669 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6670 nTries ++;
6671 if( rc==SQLITE_BUSY ){
6672 /* If the lock failed (busy):
6673 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6674 * 2nd try: fail if the mod time changed or host id is different, wait
6675 * 10 sec and try again
6676 * 3rd try: break the lock unless the mod time has changed.
6677 */
6678 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006679 if( osFstat(conchFile->h, &buf) ){
drh4bf66fd2015-02-19 02:43:02 +00006680 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006681 return SQLITE_IOERR_LOCK;
6682 }
6683
6684 if( nTries==1 ){
6685 conchModTime = buf.st_mtimespec;
6686 usleep(500000); /* wait 0.5 sec and try the lock again*/
6687 continue;
6688 }
6689
6690 assert( nTries>1 );
6691 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6692 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6693 return SQLITE_BUSY;
6694 }
6695
6696 if( nTries==2 ){
6697 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006698 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006699 if( len<0 ){
drh4bf66fd2015-02-19 02:43:02 +00006700 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006701 return SQLITE_IOERR_LOCK;
6702 }
6703 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6704 /* don't break the lock if the host id doesn't match */
6705 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6706 return SQLITE_BUSY;
6707 }
6708 }else{
6709 /* don't break the lock on short read or a version mismatch */
6710 return SQLITE_BUSY;
6711 }
6712 usleep(10000000); /* wait 10 sec and try the lock again */
6713 continue;
6714 }
6715
6716 assert( nTries==3 );
6717 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6718 rc = SQLITE_OK;
6719 if( lockType==EXCLUSIVE_LOCK ){
drhe6d41732015-02-21 00:49:00 +00006720 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
drh7ed97b92010-01-20 13:07:21 +00006721 }
6722 if( !rc ){
6723 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6724 }
6725 }
6726 }
6727 } while( rc==SQLITE_BUSY && nTries<3 );
6728
6729 return rc;
6730}
6731
6732/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006733** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6734** lockPath means that the lockPath in the conch file will be used if the
6735** host IDs match, or a new lock path will be generated automatically
6736** and written to the conch file.
6737*/
6738static int proxyTakeConch(unixFile *pFile){
6739 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6740
drh7ed97b92010-01-20 13:07:21 +00006741 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006742 return SQLITE_OK;
6743 }else{
6744 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006745 uuid_t myHostID;
6746 int pError = 0;
6747 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006748 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006749 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006750 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006751 int createConch = 0;
6752 int hostIdMatch = 0;
6753 int readLen = 0;
6754 int tryOldLockPath = 0;
6755 int forceNewLockPath = 0;
6756
drh308c2a52010-05-14 11:30:18 +00006757 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
drh91eb93c2015-03-03 19:56:20 +00006758 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00006759 osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006760
drh7ed97b92010-01-20 13:07:21 +00006761 rc = proxyGetHostID(myHostID, &pError);
6762 if( (rc&0xff)==SQLITE_IOERR ){
drh4bf66fd2015-02-19 02:43:02 +00006763 storeLastErrno(pFile, pError);
drh7ed97b92010-01-20 13:07:21 +00006764 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006765 }
drh7ed97b92010-01-20 13:07:21 +00006766 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006767 if( rc!=SQLITE_OK ){
6768 goto end_takeconch;
6769 }
drh7ed97b92010-01-20 13:07:21 +00006770 /* read the existing conch file */
6771 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6772 if( readLen<0 ){
6773 /* I/O error: lastErrno set by seekAndRead */
drh4bf66fd2015-02-19 02:43:02 +00006774 storeLastErrno(pFile, conchFile->lastErrno);
drh7ed97b92010-01-20 13:07:21 +00006775 rc = SQLITE_IOERR_READ;
6776 goto end_takeconch;
6777 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6778 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6779 /* a short read or version format mismatch means we need to create a new
6780 ** conch file.
6781 */
6782 createConch = 1;
6783 }
6784 /* if the host id matches and the lock path already exists in the conch
6785 ** we'll try to use the path there, if we can't open that path, we'll
6786 ** retry with a new auto-generated path
6787 */
6788 do { /* in case we need to try again for an :auto: named lock file */
6789
6790 if( !createConch && !forceNewLockPath ){
6791 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6792 PROXY_HOSTIDLEN);
6793 /* if the conch has data compare the contents */
6794 if( !pCtx->lockProxyPath ){
6795 /* for auto-named local lock file, just check the host ID and we'll
6796 ** use the local lock file path that's already in there
6797 */
6798 if( hostIdMatch ){
6799 size_t pathLen = (readLen - PROXY_PATHINDEX);
6800
6801 if( pathLen>=MAXPATHLEN ){
6802 pathLen=MAXPATHLEN-1;
6803 }
6804 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6805 lockPath[pathLen] = 0;
6806 tempLockPath = lockPath;
6807 tryOldLockPath = 1;
6808 /* create a copy of the lock path if the conch is taken */
6809 goto end_takeconch;
6810 }
6811 }else if( hostIdMatch
6812 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6813 readLen-PROXY_PATHINDEX)
6814 ){
6815 /* conch host and lock path match */
6816 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006817 }
drh7ed97b92010-01-20 13:07:21 +00006818 }
6819
6820 /* if the conch isn't writable and doesn't match, we can't take it */
6821 if( (conchFile->openFlags&O_RDWR) == 0 ){
6822 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006823 goto end_takeconch;
6824 }
drh7ed97b92010-01-20 13:07:21 +00006825
6826 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006827 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006828 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6829 tempLockPath = lockPath;
6830 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006831 }
drh7ed97b92010-01-20 13:07:21 +00006832
6833 /* update conch with host and path (this will fail if other process
6834 ** has a shared lock already), if the host id matches, use the big
6835 ** stick.
drh715ff302008-12-03 22:32:44 +00006836 */
drh7ed97b92010-01-20 13:07:21 +00006837 futimes(conchFile->h, NULL);
6838 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006839 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006840 /* We are trying for an exclusive lock but another thread in this
6841 ** same process is still holding a shared lock. */
6842 rc = SQLITE_BUSY;
6843 } else {
6844 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006845 }
drh715ff302008-12-03 22:32:44 +00006846 }else{
drh4bf66fd2015-02-19 02:43:02 +00006847 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006848 }
drh7ed97b92010-01-20 13:07:21 +00006849 if( rc==SQLITE_OK ){
6850 char writeBuffer[PROXY_MAXCONCHLEN];
6851 int writeSize = 0;
6852
6853 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6854 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6855 if( pCtx->lockProxyPath!=NULL ){
drh4bf66fd2015-02-19 02:43:02 +00006856 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
6857 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00006858 }else{
6859 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6860 }
6861 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006862 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006863 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6864 fsync(conchFile->h);
6865 /* If we created a new conch file (not just updated the contents of a
6866 ** valid conch file), try to match the permissions of the database
6867 */
6868 if( rc==SQLITE_OK && createConch ){
6869 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006870 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006871 if( err==0 ){
6872 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6873 S_IROTH|S_IWOTH);
6874 /* try to match the database file R/W permissions, ignore failure */
6875#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006876 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006877#else
drhff812312011-02-23 13:33:46 +00006878 do{
drhe562be52011-03-02 18:01:10 +00006879 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006880 }while( rc==(-1) && errno==EINTR );
6881 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006882 int code = errno;
6883 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6884 cmode, code, strerror(code));
6885 } else {
6886 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6887 }
6888 }else{
6889 int code = errno;
6890 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6891 err, code, strerror(code));
6892#endif
6893 }
drh715ff302008-12-03 22:32:44 +00006894 }
6895 }
drh7ed97b92010-01-20 13:07:21 +00006896 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6897
6898 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006899 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006900 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006901 int fd;
drh7ed97b92010-01-20 13:07:21 +00006902 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006903 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006904 }
6905 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006906 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006907 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006908 if( fd>=0 ){
6909 pFile->h = fd;
6910 }else{
drh9978c972010-02-23 17:36:32 +00006911 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006912 during locking */
6913 }
6914 }
6915 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6916 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6917 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6918 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6919 /* we couldn't create the proxy lock file with the old lock file path
6920 ** so try again via auto-naming
6921 */
6922 forceNewLockPath = 1;
6923 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006924 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006925 }
6926 }
6927 if( rc==SQLITE_OK ){
6928 /* Need to make a copy of path if we extracted the value
6929 ** from the conch file or the path was allocated on the stack
6930 */
6931 if( tempLockPath ){
6932 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6933 if( !pCtx->lockProxyPath ){
6934 rc = SQLITE_NOMEM;
6935 }
6936 }
6937 }
6938 if( rc==SQLITE_OK ){
6939 pCtx->conchHeld = 1;
6940
6941 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6942 afpLockingContext *afpCtx;
6943 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6944 afpCtx->dbPath = pCtx->lockProxyPath;
6945 }
6946 } else {
6947 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6948 }
drh308c2a52010-05-14 11:30:18 +00006949 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6950 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006951 return rc;
drh308c2a52010-05-14 11:30:18 +00006952 } while (1); /* in case we need to retry the :auto: lock file -
6953 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006954 }
6955}
6956
6957/*
6958** If pFile holds a lock on a conch file, then release that lock.
6959*/
6960static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006961 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006962 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6963 unixFile *conchFile; /* Name of the conch file */
6964
6965 pCtx = (proxyLockingContext *)pFile->lockingContext;
6966 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006967 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006968 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00006969 osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006970 if( pCtx->conchHeld>0 ){
6971 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6972 }
drh715ff302008-12-03 22:32:44 +00006973 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006974 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6975 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006976 return rc;
6977}
6978
6979/*
6980** Given the name of a database file, compute the name of its conch file.
drhf3cdcdc2015-04-29 16:50:28 +00006981** Store the conch filename in memory obtained from sqlite3_malloc64().
drh715ff302008-12-03 22:32:44 +00006982** Make *pConchPath point to the new name. Return SQLITE_OK on success
6983** or SQLITE_NOMEM if unable to obtain memory.
6984**
6985** The caller is responsible for ensuring that the allocated memory
6986** space is eventually freed.
6987**
6988** *pConchPath is set to NULL if a memory allocation error occurs.
6989*/
6990static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6991 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006992 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006993 char *conchPath; /* buffer in which to construct conch name */
6994
6995 /* Allocate space for the conch filename and initialize the name to
6996 ** the name of the original database file. */
drhf3cdcdc2015-04-29 16:50:28 +00006997 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
drh715ff302008-12-03 22:32:44 +00006998 if( conchPath==0 ){
6999 return SQLITE_NOMEM;
7000 }
7001 memcpy(conchPath, dbPath, len+1);
7002
7003 /* now insert a "." before the last / character */
7004 for( i=(len-1); i>=0; i-- ){
7005 if( conchPath[i]=='/' ){
7006 i++;
7007 break;
7008 }
7009 }
7010 conchPath[i]='.';
7011 while ( i<len ){
7012 conchPath[i+1]=dbPath[i];
7013 i++;
7014 }
7015
7016 /* append the "-conch" suffix to the file */
7017 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007018 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007019
7020 return SQLITE_OK;
7021}
7022
7023
7024/* Takes a fully configured proxy locking-style unix file and switches
7025** the local lock file path
7026*/
7027static int switchLockProxyPath(unixFile *pFile, const char *path) {
7028 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7029 char *oldPath = pCtx->lockProxyPath;
7030 int rc = SQLITE_OK;
7031
drh308c2a52010-05-14 11:30:18 +00007032 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007033 return SQLITE_BUSY;
7034 }
7035
7036 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7037 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7038 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7039 return SQLITE_OK;
7040 }else{
7041 unixFile *lockProxy = pCtx->lockProxy;
7042 pCtx->lockProxy=NULL;
7043 pCtx->conchHeld = 0;
7044 if( lockProxy!=NULL ){
7045 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7046 if( rc ) return rc;
7047 sqlite3_free(lockProxy);
7048 }
7049 sqlite3_free(oldPath);
7050 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7051 }
7052
7053 return rc;
7054}
7055
7056/*
7057** pFile is a file that has been opened by a prior xOpen call. dbPath
7058** is a string buffer at least MAXPATHLEN+1 characters in size.
7059**
7060** This routine find the filename associated with pFile and writes it
7061** int dbPath.
7062*/
7063static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007064#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007065 if( pFile->pMethod == &afpIoMethods ){
7066 /* afp style keeps a reference to the db path in the filePath field
7067 ** of the struct */
drhea678832008-12-10 19:26:22 +00007068 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh4bf66fd2015-02-19 02:43:02 +00007069 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7070 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007071 } else
drh715ff302008-12-03 22:32:44 +00007072#endif
7073 if( pFile->pMethod == &dotlockIoMethods ){
7074 /* dot lock style uses the locking context to store the dot lock
7075 ** file path */
7076 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7077 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7078 }else{
7079 /* all other styles use the locking context to store the db file path */
7080 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007081 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007082 }
7083 return SQLITE_OK;
7084}
7085
7086/*
7087** Takes an already filled in unix file and alters it so all file locking
7088** will be performed on the local proxy lock file. The following fields
7089** are preserved in the locking context so that they can be restored and
7090** the unix structure properly cleaned up at close time:
7091** ->lockingContext
7092** ->pMethod
7093*/
7094static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7095 proxyLockingContext *pCtx;
7096 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7097 char *lockPath=NULL;
7098 int rc = SQLITE_OK;
7099
drh308c2a52010-05-14 11:30:18 +00007100 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007101 return SQLITE_BUSY;
7102 }
7103 proxyGetDbPathForUnixFile(pFile, dbPath);
7104 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7105 lockPath=NULL;
7106 }else{
7107 lockPath=(char *)path;
7108 }
7109
drh308c2a52010-05-14 11:30:18 +00007110 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
drh5ac93652015-03-21 20:59:43 +00007111 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007112
drhf3cdcdc2015-04-29 16:50:28 +00007113 pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh715ff302008-12-03 22:32:44 +00007114 if( pCtx==0 ){
7115 return SQLITE_NOMEM;
7116 }
7117 memset(pCtx, 0, sizeof(*pCtx));
7118
7119 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7120 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007121 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7122 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7123 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7124 ** (c) the file system is read-only, then enable no-locking access.
7125 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7126 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7127 */
7128 struct statfs fsInfo;
7129 struct stat conchInfo;
7130 int goLockless = 0;
7131
drh99ab3b12011-03-02 15:09:07 +00007132 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007133 int err = errno;
7134 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7135 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7136 }
7137 }
7138 if( goLockless ){
7139 pCtx->conchHeld = -1; /* read only FS/ lockless */
7140 rc = SQLITE_OK;
7141 }
7142 }
drh715ff302008-12-03 22:32:44 +00007143 }
7144 if( rc==SQLITE_OK && lockPath ){
7145 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7146 }
7147
7148 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007149 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7150 if( pCtx->dbPath==NULL ){
7151 rc = SQLITE_NOMEM;
7152 }
7153 }
7154 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007155 /* all memory is allocated, proxys are created and assigned,
7156 ** switch the locking context and pMethod then return.
7157 */
drh715ff302008-12-03 22:32:44 +00007158 pCtx->oldLockingContext = pFile->lockingContext;
7159 pFile->lockingContext = pCtx;
7160 pCtx->pOldMethod = pFile->pMethod;
7161 pFile->pMethod = &proxyIoMethods;
7162 }else{
7163 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007164 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007165 sqlite3_free(pCtx->conchFile);
7166 }
drhd56b1212010-08-11 06:14:15 +00007167 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007168 sqlite3_free(pCtx->conchFilePath);
7169 sqlite3_free(pCtx);
7170 }
drh308c2a52010-05-14 11:30:18 +00007171 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7172 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007173 return rc;
7174}
7175
7176
7177/*
7178** This routine handles sqlite3_file_control() calls that are specific
7179** to proxy locking.
7180*/
7181static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7182 switch( op ){
drh4bf66fd2015-02-19 02:43:02 +00007183 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007184 unixFile *pFile = (unixFile*)id;
7185 if( pFile->pMethod == &proxyIoMethods ){
7186 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7187 proxyTakeConch(pFile);
7188 if( pCtx->lockProxyPath ){
7189 *(const char **)pArg = pCtx->lockProxyPath;
7190 }else{
7191 *(const char **)pArg = ":auto: (not held)";
7192 }
7193 } else {
7194 *(const char **)pArg = NULL;
7195 }
7196 return SQLITE_OK;
7197 }
drh4bf66fd2015-02-19 02:43:02 +00007198 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007199 unixFile *pFile = (unixFile*)id;
7200 int rc = SQLITE_OK;
7201 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7202 if( pArg==NULL || (const char *)pArg==0 ){
7203 if( isProxyStyle ){
drh4bf66fd2015-02-19 02:43:02 +00007204 /* turn off proxy locking - not supported. If support is added for
7205 ** switching proxy locking mode off then it will need to fail if
7206 ** the journal mode is WAL mode.
7207 */
drh715ff302008-12-03 22:32:44 +00007208 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7209 }else{
7210 /* turn off proxy locking - already off - NOOP */
7211 rc = SQLITE_OK;
7212 }
7213 }else{
7214 const char *proxyPath = (const char *)pArg;
7215 if( isProxyStyle ){
7216 proxyLockingContext *pCtx =
7217 (proxyLockingContext*)pFile->lockingContext;
7218 if( !strcmp(pArg, ":auto:")
7219 || (pCtx->lockProxyPath &&
7220 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7221 ){
7222 rc = SQLITE_OK;
7223 }else{
7224 rc = switchLockProxyPath(pFile, proxyPath);
7225 }
7226 }else{
7227 /* turn on proxy file locking */
7228 rc = proxyTransformUnixFile(pFile, proxyPath);
7229 }
7230 }
7231 return rc;
7232 }
7233 default: {
7234 assert( 0 ); /* The call assures that only valid opcodes are sent */
7235 }
7236 }
7237 /*NOTREACHED*/
7238 return SQLITE_ERROR;
7239}
7240
7241/*
7242** Within this division (the proxying locking implementation) the procedures
7243** above this point are all utilities. The lock-related methods of the
7244** proxy-locking sqlite3_io_method object follow.
7245*/
7246
7247
7248/*
7249** This routine checks if there is a RESERVED lock held on the specified
7250** file by this or any other process. If such a lock is held, set *pResOut
7251** to a non-zero value otherwise *pResOut is set to zero. The return value
7252** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7253*/
7254static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7255 unixFile *pFile = (unixFile*)id;
7256 int rc = proxyTakeConch(pFile);
7257 if( rc==SQLITE_OK ){
7258 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007259 if( pCtx->conchHeld>0 ){
7260 unixFile *proxy = pCtx->lockProxy;
7261 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7262 }else{ /* conchHeld < 0 is lockless */
7263 pResOut=0;
7264 }
drh715ff302008-12-03 22:32:44 +00007265 }
7266 return rc;
7267}
7268
7269/*
drh308c2a52010-05-14 11:30:18 +00007270** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007271** of the following:
7272**
7273** (1) SHARED_LOCK
7274** (2) RESERVED_LOCK
7275** (3) PENDING_LOCK
7276** (4) EXCLUSIVE_LOCK
7277**
7278** Sometimes when requesting one lock state, additional lock states
7279** are inserted in between. The locking might fail on one of the later
7280** transitions leaving the lock state different from what it started but
7281** still short of its goal. The following chart shows the allowed
7282** transitions and the inserted intermediate states:
7283**
7284** UNLOCKED -> SHARED
7285** SHARED -> RESERVED
7286** SHARED -> (PENDING) -> EXCLUSIVE
7287** RESERVED -> (PENDING) -> EXCLUSIVE
7288** PENDING -> EXCLUSIVE
7289**
7290** This routine will only increase a lock. Use the sqlite3OsUnlock()
7291** routine to lower a locking level.
7292*/
drh308c2a52010-05-14 11:30:18 +00007293static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007294 unixFile *pFile = (unixFile*)id;
7295 int rc = proxyTakeConch(pFile);
7296 if( rc==SQLITE_OK ){
7297 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007298 if( pCtx->conchHeld>0 ){
7299 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007300 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7301 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007302 }else{
7303 /* conchHeld < 0 is lockless */
7304 }
drh715ff302008-12-03 22:32:44 +00007305 }
7306 return rc;
7307}
7308
7309
7310/*
drh308c2a52010-05-14 11:30:18 +00007311** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007312** must be either NO_LOCK or SHARED_LOCK.
7313**
7314** If the locking level of the file descriptor is already at or below
7315** the requested locking level, this routine is a no-op.
7316*/
drh308c2a52010-05-14 11:30:18 +00007317static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007318 unixFile *pFile = (unixFile*)id;
7319 int rc = proxyTakeConch(pFile);
7320 if( rc==SQLITE_OK ){
7321 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007322 if( pCtx->conchHeld>0 ){
7323 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007324 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7325 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007326 }else{
7327 /* conchHeld < 0 is lockless */
7328 }
drh715ff302008-12-03 22:32:44 +00007329 }
7330 return rc;
7331}
7332
7333/*
7334** Close a file that uses proxy locks.
7335*/
7336static int proxyClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00007337 if( ALWAYS(id) ){
drh715ff302008-12-03 22:32:44 +00007338 unixFile *pFile = (unixFile*)id;
7339 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7340 unixFile *lockProxy = pCtx->lockProxy;
7341 unixFile *conchFile = pCtx->conchFile;
7342 int rc = SQLITE_OK;
7343
7344 if( lockProxy ){
7345 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7346 if( rc ) return rc;
7347 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7348 if( rc ) return rc;
7349 sqlite3_free(lockProxy);
7350 pCtx->lockProxy = 0;
7351 }
7352 if( conchFile ){
7353 if( pCtx->conchHeld ){
7354 rc = proxyReleaseConch(pFile);
7355 if( rc ) return rc;
7356 }
7357 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7358 if( rc ) return rc;
7359 sqlite3_free(conchFile);
7360 }
drhd56b1212010-08-11 06:14:15 +00007361 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007362 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007363 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007364 /* restore the original locking context and pMethod then close it */
7365 pFile->lockingContext = pCtx->oldLockingContext;
7366 pFile->pMethod = pCtx->pOldMethod;
7367 sqlite3_free(pCtx);
7368 return pFile->pMethod->xClose(id);
7369 }
7370 return SQLITE_OK;
7371}
7372
7373
7374
drhd2cb50b2009-01-09 21:41:17 +00007375#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007376/*
7377** The proxy locking style is intended for use with AFP filesystems.
7378** And since AFP is only supported on MacOSX, the proxy locking is also
7379** restricted to MacOSX.
7380**
7381**
7382******************* End of the proxy lock implementation **********************
7383******************************************************************************/
7384
drh734c9862008-11-28 15:37:20 +00007385/*
danielk1977e339d652008-06-28 11:23:00 +00007386** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007387**
7388** This routine registers all VFS implementations for unix-like operating
7389** systems. This routine, and the sqlite3_os_end() routine that follows,
7390** should be the only routines in this file that are visible from other
7391** files.
drh6b9d6dd2008-12-03 19:34:47 +00007392**
7393** This routine is called once during SQLite initialization and by a
7394** single thread. The memory allocation and mutex subsystems have not
7395** necessarily been initialized when this routine is called, and so they
7396** should not be used.
drh153c62c2007-08-24 03:51:33 +00007397*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007398int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007399 /*
7400 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007401 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7402 ** to the "finder" function. (pAppData is a pointer to a pointer because
7403 ** silly C90 rules prohibit a void* from being cast to a function pointer
7404 ** and so we have to go through the intermediate pointer to avoid problems
7405 ** when compiling with -pedantic-errors on GCC.)
7406 **
7407 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007408 ** finder-function. The finder-function returns a pointer to the
7409 ** sqlite_io_methods object that implements the desired locking
7410 ** behaviors. See the division above that contains the IOMETHODS
7411 ** macro for addition information on finder-functions.
7412 **
7413 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7414 ** object. But the "autolockIoFinder" available on MacOSX does a little
7415 ** more than that; it looks at the filesystem type that hosts the
7416 ** database file and tries to choose an locking method appropriate for
7417 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007418 */
drh7708e972008-11-29 00:56:52 +00007419 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007420 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007421 sizeof(unixFile), /* szOsFile */ \
7422 MAX_PATHNAME, /* mxPathname */ \
7423 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007424 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007425 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007426 unixOpen, /* xOpen */ \
7427 unixDelete, /* xDelete */ \
7428 unixAccess, /* xAccess */ \
7429 unixFullPathname, /* xFullPathname */ \
7430 unixDlOpen, /* xDlOpen */ \
7431 unixDlError, /* xDlError */ \
7432 unixDlSym, /* xDlSym */ \
7433 unixDlClose, /* xDlClose */ \
7434 unixRandomness, /* xRandomness */ \
7435 unixSleep, /* xSleep */ \
7436 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007437 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007438 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007439 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007440 unixGetSystemCall, /* xGetSystemCall */ \
7441 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007442 }
7443
drh6b9d6dd2008-12-03 19:34:47 +00007444 /*
7445 ** All default VFSes for unix are contained in the following array.
7446 **
7447 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7448 ** by the SQLite core when the VFS is registered. So the following
7449 ** array cannot be const.
7450 */
danielk1977e339d652008-06-28 11:23:00 +00007451 static sqlite3_vfs aVfs[] = {
drhe89b2912015-03-03 20:42:01 +00007452#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007453 UNIXVFS("unix", autolockIoFinder ),
drhe89b2912015-03-03 20:42:01 +00007454#elif OS_VXWORKS
7455 UNIXVFS("unix", vxworksIoFinder ),
drh7708e972008-11-29 00:56:52 +00007456#else
7457 UNIXVFS("unix", posixIoFinder ),
7458#endif
7459 UNIXVFS("unix-none", nolockIoFinder ),
7460 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007461 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007462#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007463 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007464#endif
drhe89b2912015-03-03 20:42:01 +00007465#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007466 UNIXVFS("unix-posix", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007467#endif
drhe89b2912015-03-03 20:42:01 +00007468#if SQLITE_ENABLE_LOCKING_STYLE
7469 UNIXVFS("unix-flock", flockIoFinder ),
chw78a13182009-04-07 05:35:03 +00007470#endif
drhd2cb50b2009-01-09 21:41:17 +00007471#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007472 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007473 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007474 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007475#endif
drh153c62c2007-08-24 03:51:33 +00007476 };
drh6b9d6dd2008-12-03 19:34:47 +00007477 unsigned int i; /* Loop counter */
7478
drh2aa5a002011-04-13 13:42:25 +00007479 /* Double-check that the aSyscall[] array has been constructed
7480 ** correctly. See ticket [bb3a86e890c8e96ab] */
drh6226ca22015-11-24 15:06:28 +00007481 assert( ArraySize(aSyscall)==27 );
drh2aa5a002011-04-13 13:42:25 +00007482
drh6b9d6dd2008-12-03 19:34:47 +00007483 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007484 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007485 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007486 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007487 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007488}
danielk1977e339d652008-06-28 11:23:00 +00007489
7490/*
drh6b9d6dd2008-12-03 19:34:47 +00007491** Shutdown the operating system interface.
7492**
7493** Some operating systems might need to do some cleanup in this routine,
7494** to release dynamically allocated objects. But not on unix.
7495** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007496*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007497int sqlite3_os_end(void){
7498 return SQLITE_OK;
7499}
drhdce8bdb2007-08-16 13:01:44 +00007500
danielk197729bafea2008-06-26 10:41:19 +00007501#endif /* SQLITE_OS_UNIX */