blob: 35f401e74c9869a0865fcfef0dbd8467a98b4a47 [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 );
drh77197112011-03-15 19:08:48 +00001409 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1410 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1411 ){
drh3cb93392011-03-12 18:10:44 +00001412 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001413 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001414 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001415 lock.l_whence = SEEK_SET;
1416 lock.l_start = SHARED_FIRST;
1417 lock.l_len = SHARED_SIZE;
1418 lock.l_type = F_WRLCK;
1419 rc = osFcntl(pFile->h, F_SETLK, &lock);
1420 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001421 pInode->bProcessLock = 1;
1422 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001423 }else{
1424 rc = 0;
1425 }
1426 }else{
1427 rc = osFcntl(pFile->h, F_SETLK, pLock);
1428 }
1429 return rc;
1430}
1431
1432/*
drh308c2a52010-05-14 11:30:18 +00001433** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001434** of the following:
1435**
drh2ac3ee92004-06-07 16:27:46 +00001436** (1) SHARED_LOCK
1437** (2) RESERVED_LOCK
1438** (3) PENDING_LOCK
1439** (4) EXCLUSIVE_LOCK
1440**
drhb3e04342004-06-08 00:47:47 +00001441** Sometimes when requesting one lock state, additional lock states
1442** are inserted in between. The locking might fail on one of the later
1443** transitions leaving the lock state different from what it started but
1444** still short of its goal. The following chart shows the allowed
1445** transitions and the inserted intermediate states:
1446**
1447** UNLOCKED -> SHARED
1448** SHARED -> RESERVED
1449** SHARED -> (PENDING) -> EXCLUSIVE
1450** RESERVED -> (PENDING) -> EXCLUSIVE
1451** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001452**
drha6abd042004-06-09 17:37:22 +00001453** This routine will only increase a lock. Use the sqlite3OsUnlock()
1454** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001455*/
drh308c2a52010-05-14 11:30:18 +00001456static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001457 /* The following describes the implementation of the various locks and
1458 ** lock transitions in terms of the POSIX advisory shared and exclusive
1459 ** lock primitives (called read-locks and write-locks below, to avoid
1460 ** confusion with SQLite lock names). The algorithms are complicated
1461 ** slightly in order to be compatible with windows systems simultaneously
1462 ** accessing the same database file, in case that is ever required.
1463 **
1464 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1465 ** byte', each single bytes at well known offsets, and the 'shared byte
1466 ** range', a range of 510 bytes at a well known offset.
1467 **
1468 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1469 ** byte'. If this is successful, a random byte from the 'shared byte
1470 ** range' is read-locked and the lock on the 'pending byte' released.
1471 **
danielk197790ba3bd2004-06-25 08:32:25 +00001472 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1473 ** A RESERVED lock is implemented by grabbing a write-lock on the
1474 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001475 **
1476 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001477 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1478 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1479 ** obtained, but existing SHARED locks are allowed to persist. A process
1480 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1481 ** This property is used by the algorithm for rolling back a journal file
1482 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001483 **
danielk197790ba3bd2004-06-25 08:32:25 +00001484 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1485 ** implemented by obtaining a write-lock on the entire 'shared byte
1486 ** range'. Since all other locks require a read-lock on one of the bytes
1487 ** within this range, this ensures that no other locks are held on the
1488 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001489 **
1490 ** The reason a single byte cannot be used instead of the 'shared byte
1491 ** range' is that some versions of windows do not support read-locks. By
1492 ** locking a random byte from a range, concurrent SHARED locks may exist
1493 ** even if the locking primitive used is always a write-lock.
1494 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001495 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001496 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001497 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001498 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001499 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001500
drh054889e2005-11-30 03:20:31 +00001501 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001502 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1503 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh91eb93c2015-03-03 19:56:20 +00001504 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001505 osGetpid(0)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001506
1507 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001508 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001509 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001510 */
drh308c2a52010-05-14 11:30:18 +00001511 if( pFile->eFileLock>=eFileLock ){
1512 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1513 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001514 return SQLITE_OK;
1515 }
1516
drh0c2694b2009-09-03 16:23:44 +00001517 /* Make sure the locking sequence is correct.
1518 ** (1) We never move from unlocked to anything higher than shared lock.
1519 ** (2) SQLite never explicitly requests a pendig lock.
1520 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001521 */
drh308c2a52010-05-14 11:30:18 +00001522 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1523 assert( eFileLock!=PENDING_LOCK );
1524 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001525
drh8af6c222010-05-14 12:43:01 +00001526 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001527 */
drh6c7d5c52008-11-21 20:32:33 +00001528 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001529 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001530
danielk1977ad94b582007-08-20 06:44:22 +00001531 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001532 ** handle that precludes the requested lock, return BUSY.
1533 */
drh8af6c222010-05-14 12:43:01 +00001534 if( (pFile->eFileLock!=pInode->eFileLock &&
1535 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001536 ){
1537 rc = SQLITE_BUSY;
1538 goto end_lock;
1539 }
1540
1541 /* If a SHARED lock is requested, and some thread using this PID already
1542 ** has a SHARED or RESERVED lock, then increment reference counts and
1543 ** return SQLITE_OK.
1544 */
drh308c2a52010-05-14 11:30:18 +00001545 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001546 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001547 assert( eFileLock==SHARED_LOCK );
1548 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001549 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001550 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001551 pInode->nShared++;
1552 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001553 goto end_lock;
1554 }
1555
danielk19779a1d0ab2004-06-01 14:09:28 +00001556
drh3cde3bb2004-06-12 02:17:14 +00001557 /* A PENDING lock is needed before acquiring a SHARED lock and before
1558 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1559 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001560 */
drh0c2694b2009-09-03 16:23:44 +00001561 lock.l_len = 1L;
1562 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001563 if( eFileLock==SHARED_LOCK
1564 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001565 ){
drh308c2a52010-05-14 11:30:18 +00001566 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001567 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001568 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001569 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001570 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001571 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001572 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001573 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001574 goto end_lock;
1575 }
drh3cde3bb2004-06-12 02:17:14 +00001576 }
1577
1578
1579 /* If control gets to this point, then actually go ahead and make
1580 ** operating system calls for the specified lock.
1581 */
drh308c2a52010-05-14 11:30:18 +00001582 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001583 assert( pInode->nShared==0 );
1584 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001585 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001586
drh2ac3ee92004-06-07 16:27:46 +00001587 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001588 lock.l_start = SHARED_FIRST;
1589 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001590 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001591 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001592 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001593 }
dan661d71a2011-03-30 19:08:03 +00001594
drh2ac3ee92004-06-07 16:27:46 +00001595 /* Drop the temporary PENDING lock */
1596 lock.l_start = PENDING_BYTE;
1597 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001598 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001599 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1600 /* This could happen with a network mount */
1601 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001602 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001603 }
dan661d71a2011-03-30 19:08:03 +00001604
1605 if( rc ){
1606 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001607 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001608 }
dan661d71a2011-03-30 19:08:03 +00001609 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001610 }else{
drh308c2a52010-05-14 11:30:18 +00001611 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001612 pInode->nLock++;
1613 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001614 }
drh8af6c222010-05-14 12:43:01 +00001615 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001616 /* We are trying for an exclusive lock but another thread in this
1617 ** same process is still holding a shared lock. */
1618 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001619 }else{
drh3cde3bb2004-06-12 02:17:14 +00001620 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001621 ** assumed that there is a SHARED or greater lock on the file
1622 ** already.
1623 */
drh308c2a52010-05-14 11:30:18 +00001624 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001625 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001626
1627 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1628 if( eFileLock==RESERVED_LOCK ){
1629 lock.l_start = RESERVED_BYTE;
1630 lock.l_len = 1L;
1631 }else{
1632 lock.l_start = SHARED_FIRST;
1633 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001634 }
dan661d71a2011-03-30 19:08:03 +00001635
1636 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001637 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001638 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001639 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001640 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001641 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001642 }
drhbbd42a62004-05-22 17:41:58 +00001643 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001644
drh8f941bc2009-01-14 23:03:40 +00001645
drhd3d8c042012-05-29 17:02:40 +00001646#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001647 /* Set up the transaction-counter change checking flags when
1648 ** transitioning from a SHARED to a RESERVED lock. The change
1649 ** from SHARED to RESERVED marks the beginning of a normal
1650 ** write operation (not a hot journal rollback).
1651 */
1652 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001653 && pFile->eFileLock<=SHARED_LOCK
1654 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001655 ){
1656 pFile->transCntrChng = 0;
1657 pFile->dbUpdate = 0;
1658 pFile->inNormalWrite = 1;
1659 }
1660#endif
1661
1662
danielk1977ecb2a962004-06-02 06:30:16 +00001663 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001664 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001665 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001666 }else if( eFileLock==EXCLUSIVE_LOCK ){
1667 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001668 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001669 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001670
1671end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001672 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001673 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1674 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001675 return rc;
1676}
1677
1678/*
dan08da86a2009-08-21 17:18:03 +00001679** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001680** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001681*/
1682static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001683 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001684 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001685 p->pNext = pInode->pUnused;
1686 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001687 pFile->h = -1;
1688 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001689}
1690
1691/*
drh308c2a52010-05-14 11:30:18 +00001692** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001693** must be either NO_LOCK or SHARED_LOCK.
1694**
1695** If the locking level of the file descriptor is already at or below
1696** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001697**
1698** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1699** the byte range is divided into 2 parts and the first part is unlocked then
1700** set to a read lock, then the other part is simply unlocked. This works
1701** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1702** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001703*/
drha7e61d82011-03-12 17:02:57 +00001704static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001705 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001706 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001707 struct flock lock;
1708 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001709
drh054889e2005-11-30 03:20:31 +00001710 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001711 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001712 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001713 osGetpid(0)));
drha6abd042004-06-09 17:37:22 +00001714
drh308c2a52010-05-14 11:30:18 +00001715 assert( eFileLock<=SHARED_LOCK );
1716 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001717 return SQLITE_OK;
1718 }
drh6c7d5c52008-11-21 20:32:33 +00001719 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001720 pInode = pFile->pInode;
1721 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001722 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001723 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001724
drhd3d8c042012-05-29 17:02:40 +00001725#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001726 /* When reducing a lock such that other processes can start
1727 ** reading the database file again, make sure that the
1728 ** transaction counter was updated if any part of the database
1729 ** file changed. If the transaction counter is not updated,
1730 ** other connections to the same file might not realize that
1731 ** the file has changed and hence might not know to flush their
1732 ** cache. The use of a stale cache can lead to database corruption.
1733 */
drh8f941bc2009-01-14 23:03:40 +00001734 pFile->inNormalWrite = 0;
1735#endif
1736
drh7ed97b92010-01-20 13:07:21 +00001737 /* downgrading to a shared lock on NFS involves clearing the write lock
1738 ** before establishing the readlock - to avoid a race condition we downgrade
1739 ** the lock in 2 blocks, so that part of the range will be covered by a
1740 ** write lock until the rest is covered by a read lock:
1741 ** 1: [WWWWW]
1742 ** 2: [....W]
1743 ** 3: [RRRRW]
1744 ** 4: [RRRR.]
1745 */
drh308c2a52010-05-14 11:30:18 +00001746 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001747#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001748 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001749 assert( handleNFSUnlock==0 );
1750#endif
1751#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001752 if( handleNFSUnlock ){
drha712b4b2015-02-19 16:12:04 +00001753 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001754 off_t divSize = SHARED_SIZE - 1;
1755
1756 lock.l_type = F_UNLCK;
1757 lock.l_whence = SEEK_SET;
1758 lock.l_start = SHARED_FIRST;
1759 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001760 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001761 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001762 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001763 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001764 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001765 }
drh7ed97b92010-01-20 13:07:21 +00001766 lock.l_type = F_RDLCK;
1767 lock.l_whence = SEEK_SET;
1768 lock.l_start = SHARED_FIRST;
1769 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001770 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001771 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001772 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1773 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001774 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001775 }
1776 goto end_unlock;
1777 }
1778 lock.l_type = F_UNLCK;
1779 lock.l_whence = SEEK_SET;
1780 lock.l_start = SHARED_FIRST+divSize;
1781 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001782 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001783 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001784 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001785 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001786 goto end_unlock;
1787 }
drh30f776f2011-02-25 03:25:07 +00001788 }else
1789#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1790 {
drh7ed97b92010-01-20 13:07:21 +00001791 lock.l_type = F_RDLCK;
1792 lock.l_whence = SEEK_SET;
1793 lock.l_start = SHARED_FIRST;
1794 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001795 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001796 /* In theory, the call to unixFileLock() cannot fail because another
1797 ** process is holding an incompatible lock. If it does, this
1798 ** indicates that the other process is not following the locking
1799 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1800 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1801 ** an assert to fail). */
1802 rc = SQLITE_IOERR_RDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001803 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00001804 goto end_unlock;
1805 }
drh9c105bb2004-10-02 20:38:28 +00001806 }
1807 }
drhbbd42a62004-05-22 17:41:58 +00001808 lock.l_type = F_UNLCK;
1809 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001810 lock.l_start = PENDING_BYTE;
1811 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001812 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001813 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001814 }else{
danea83bc62011-04-01 11:56:32 +00001815 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001816 storeLastErrno(pFile, errno);
drhcd731cf2009-03-28 23:23:02 +00001817 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001818 }
drhbbd42a62004-05-22 17:41:58 +00001819 }
drh308c2a52010-05-14 11:30:18 +00001820 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001821 /* Decrement the shared lock counter. Release the lock using an
1822 ** OS call only when all threads in this same process have released
1823 ** the lock.
1824 */
drh8af6c222010-05-14 12:43:01 +00001825 pInode->nShared--;
1826 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001827 lock.l_type = F_UNLCK;
1828 lock.l_whence = SEEK_SET;
1829 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001830 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001831 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001832 }else{
danea83bc62011-04-01 11:56:32 +00001833 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001834 storeLastErrno(pFile, errno);
drh8af6c222010-05-14 12:43:01 +00001835 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001836 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001837 }
drha6abd042004-06-09 17:37:22 +00001838 }
1839
drhbbd42a62004-05-22 17:41:58 +00001840 /* Decrement the count of locks against this same file. When the
1841 ** count reaches zero, close any other file descriptors whose close
1842 ** was deferred because of outstanding locks.
1843 */
drh8af6c222010-05-14 12:43:01 +00001844 pInode->nLock--;
1845 assert( pInode->nLock>=0 );
1846 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001847 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001848 }
1849 }
drhf2f105d2012-08-20 15:53:54 +00001850
aswift5b1a2562008-08-22 00:22:35 +00001851end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001852 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001853 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001854 return rc;
drhbbd42a62004-05-22 17:41:58 +00001855}
1856
1857/*
drh308c2a52010-05-14 11:30:18 +00001858** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001859** must be either NO_LOCK or SHARED_LOCK.
1860**
1861** If the locking level of the file descriptor is already at or below
1862** the requested locking level, this routine is a no-op.
1863*/
drh308c2a52010-05-14 11:30:18 +00001864static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00001865#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00001866 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00001867#endif
drha7e61d82011-03-12 17:02:57 +00001868 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001869}
1870
mistachkine98844f2013-08-24 00:59:24 +00001871#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001872static int unixMapfile(unixFile *pFd, i64 nByte);
1873static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00001874#endif
danf23da962013-03-23 21:00:41 +00001875
drh7ed97b92010-01-20 13:07:21 +00001876/*
danielk1977e339d652008-06-28 11:23:00 +00001877** This function performs the parts of the "close file" operation
1878** common to all locking schemes. It closes the directory and file
1879** handles, if they are valid, and sets all fields of the unixFile
1880** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001881**
1882** It is *not* necessary to hold the mutex when this routine is called,
1883** even on VxWorks. A mutex will be acquired on VxWorks by the
1884** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001885*/
1886static int closeUnixFile(sqlite3_file *id){
1887 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00001888#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001889 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00001890#endif
dan661d71a2011-03-30 19:08:03 +00001891 if( pFile->h>=0 ){
1892 robust_close(pFile, pFile->h, __LINE__);
1893 pFile->h = -1;
1894 }
1895#if OS_VXWORKS
1896 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001897 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001898 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001899 }
1900 vxworksReleaseFileId(pFile->pId);
1901 pFile->pId = 0;
1902 }
1903#endif
drh0bdbc902014-06-16 18:35:06 +00001904#ifdef SQLITE_UNLINK_AFTER_CLOSE
1905 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
1906 osUnlink(pFile->zPath);
1907 sqlite3_free(*(char**)&pFile->zPath);
1908 pFile->zPath = 0;
1909 }
1910#endif
dan661d71a2011-03-30 19:08:03 +00001911 OSTRACE(("CLOSE %-3d\n", pFile->h));
1912 OpenCounter(-1);
1913 sqlite3_free(pFile->pUnused);
1914 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001915 return SQLITE_OK;
1916}
1917
1918/*
danielk1977e3026632004-06-22 11:29:02 +00001919** Close a file.
1920*/
danielk197762079062007-08-15 17:08:46 +00001921static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001922 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001923 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00001924 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00001925 unixUnlock(id, NO_LOCK);
1926 unixEnterMutex();
1927
1928 /* unixFile.pInode is always valid here. Otherwise, a different close
1929 ** routine (e.g. nolockClose()) would be called instead.
1930 */
1931 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1932 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1933 /* If there are outstanding locks, do not actually close the file just
1934 ** yet because that would clear those locks. Instead, add the file
1935 ** descriptor to pInode->pUnused list. It will be automatically closed
1936 ** when the last lock is cleared.
1937 */
1938 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001939 }
dan661d71a2011-03-30 19:08:03 +00001940 releaseInodeInfo(pFile);
1941 rc = closeUnixFile(id);
1942 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001943 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001944}
1945
drh734c9862008-11-28 15:37:20 +00001946/************** End of the posix advisory lock implementation *****************
1947******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001948
drh734c9862008-11-28 15:37:20 +00001949/******************************************************************************
1950****************************** No-op Locking **********************************
1951**
1952** Of the various locking implementations available, this is by far the
1953** simplest: locking is ignored. No attempt is made to lock the database
1954** file for reading or writing.
1955**
1956** This locking mode is appropriate for use on read-only databases
1957** (ex: databases that are burned into CD-ROM, for example.) It can
1958** also be used if the application employs some external mechanism to
1959** prevent simultaneous access of the same database by two or more
1960** database connections. But there is a serious risk of database
1961** corruption if this locking mode is used in situations where multiple
1962** database connections are accessing the same database file at the same
1963** time and one or more of those connections are writing.
1964*/
drhbfe66312006-10-03 17:40:40 +00001965
drh734c9862008-11-28 15:37:20 +00001966static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1967 UNUSED_PARAMETER(NotUsed);
1968 *pResOut = 0;
1969 return SQLITE_OK;
1970}
drh734c9862008-11-28 15:37:20 +00001971static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1972 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1973 return SQLITE_OK;
1974}
drh734c9862008-11-28 15:37:20 +00001975static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1976 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1977 return SQLITE_OK;
1978}
1979
1980/*
drh9b35ea62008-11-29 02:20:26 +00001981** Close the file.
drh734c9862008-11-28 15:37:20 +00001982*/
1983static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001984 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001985}
1986
1987/******************* End of the no-op lock implementation *********************
1988******************************************************************************/
1989
1990/******************************************************************************
1991************************* Begin dot-file Locking ******************************
1992**
mistachkin48864df2013-03-21 21:20:32 +00001993** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00001994** files (really a directory) to control access to the database. This works
1995** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00001996**
1997** (1) There is zero concurrency. A single reader blocks all other
1998** connections from reading or writing the database.
1999**
2000** (2) An application crash or power loss can leave stale lock files
2001** sitting around that need to be cleared manually.
2002**
2003** Nevertheless, a dotlock is an appropriate locking mode for use if no
2004** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002005**
drh9ef6bc42011-11-04 02:24:02 +00002006** Dotfile locking works by creating a subdirectory in the same directory as
2007** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002008** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002009** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002010*/
2011
2012/*
2013** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002014** lock directory.
drh734c9862008-11-28 15:37:20 +00002015*/
2016#define DOTLOCK_SUFFIX ".lock"
2017
drh7708e972008-11-29 00:56:52 +00002018/*
2019** This routine checks if there is a RESERVED lock held on the specified
2020** file by this or any other process. If such a lock is held, set *pResOut
2021** to a non-zero value otherwise *pResOut is set to zero. The return value
2022** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2023**
2024** In dotfile locking, either a lock exists or it does not. So in this
2025** variation of CheckReservedLock(), *pResOut is set to true if any lock
2026** is held on the file and false if the file is unlocked.
2027*/
drh734c9862008-11-28 15:37:20 +00002028static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2029 int rc = SQLITE_OK;
2030 int reserved = 0;
2031 unixFile *pFile = (unixFile*)id;
2032
2033 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2034
2035 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00002036 reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
drh308c2a52010-05-14 11:30:18 +00002037 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002038 *pResOut = reserved;
2039 return rc;
2040}
2041
drh7708e972008-11-29 00:56:52 +00002042/*
drh308c2a52010-05-14 11:30:18 +00002043** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002044** of the following:
2045**
2046** (1) SHARED_LOCK
2047** (2) RESERVED_LOCK
2048** (3) PENDING_LOCK
2049** (4) EXCLUSIVE_LOCK
2050**
2051** Sometimes when requesting one lock state, additional lock states
2052** are inserted in between. The locking might fail on one of the later
2053** transitions leaving the lock state different from what it started but
2054** still short of its goal. The following chart shows the allowed
2055** transitions and the inserted intermediate states:
2056**
2057** UNLOCKED -> SHARED
2058** SHARED -> RESERVED
2059** SHARED -> (PENDING) -> EXCLUSIVE
2060** RESERVED -> (PENDING) -> EXCLUSIVE
2061** PENDING -> EXCLUSIVE
2062**
2063** This routine will only increase a lock. Use the sqlite3OsUnlock()
2064** routine to lower a locking level.
2065**
2066** With dotfile locking, we really only support state (4): EXCLUSIVE.
2067** But we track the other locking levels internally.
2068*/
drh308c2a52010-05-14 11:30:18 +00002069static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002070 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002071 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002072 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002073
drh7708e972008-11-29 00:56:52 +00002074
2075 /* If we have any lock, then the lock file already exists. All we have
2076 ** to do is adjust our internal record of the lock level.
2077 */
drh308c2a52010-05-14 11:30:18 +00002078 if( pFile->eFileLock > NO_LOCK ){
2079 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002080 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002081#ifdef HAVE_UTIME
2082 utime(zLockFile, NULL);
2083#else
drh734c9862008-11-28 15:37:20 +00002084 utimes(zLockFile, NULL);
2085#endif
drh7708e972008-11-29 00:56:52 +00002086 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002087 }
2088
2089 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002090 rc = osMkdir(zLockFile, 0777);
2091 if( rc<0 ){
2092 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002093 int tErrno = errno;
2094 if( EEXIST == tErrno ){
2095 rc = SQLITE_BUSY;
2096 } else {
2097 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drha8de1e12015-11-30 00:05:39 +00002098 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00002099 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002100 }
2101 }
drh7708e972008-11-29 00:56:52 +00002102 return rc;
drh734c9862008-11-28 15:37:20 +00002103 }
drh734c9862008-11-28 15:37:20 +00002104
2105 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002106 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002107 return rc;
2108}
2109
drh7708e972008-11-29 00:56:52 +00002110/*
drh308c2a52010-05-14 11:30:18 +00002111** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002112** must be either NO_LOCK or SHARED_LOCK.
2113**
2114** If the locking level of the file descriptor is already at or below
2115** the requested locking level, this routine is a no-op.
2116**
2117** When the locking level reaches NO_LOCK, delete the lock file.
2118*/
drh308c2a52010-05-14 11:30:18 +00002119static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002120 unixFile *pFile = (unixFile*)id;
2121 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002122 int rc;
drh734c9862008-11-28 15:37:20 +00002123
2124 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002125 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002126 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002127 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002128
2129 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002130 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002131 return SQLITE_OK;
2132 }
drh7708e972008-11-29 00:56:52 +00002133
2134 /* To downgrade to shared, simply update our internal notion of the
2135 ** lock state. No need to mess with the file on disk.
2136 */
drh308c2a52010-05-14 11:30:18 +00002137 if( eFileLock==SHARED_LOCK ){
2138 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002139 return SQLITE_OK;
2140 }
2141
drh7708e972008-11-29 00:56:52 +00002142 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002143 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002144 rc = osRmdir(zLockFile);
drh9ef6bc42011-11-04 02:24:02 +00002145 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002146 int tErrno = errno;
drha8de1e12015-11-30 00:05:39 +00002147 if( tErrno==ENOENT ){
2148 rc = SQLITE_OK;
2149 }else{
danea83bc62011-04-01 11:56:32 +00002150 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002151 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002152 }
2153 return rc;
2154 }
drh308c2a52010-05-14 11:30:18 +00002155 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002156 return SQLITE_OK;
2157}
2158
2159/*
drh9b35ea62008-11-29 02:20:26 +00002160** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002161*/
2162static int dotlockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002163 unixFile *pFile = (unixFile*)id;
2164 assert( id!=0 );
2165 dotlockUnlock(id, NO_LOCK);
2166 sqlite3_free(pFile->lockingContext);
2167 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002168}
2169/****************** End of the dot-file lock implementation *******************
2170******************************************************************************/
2171
2172/******************************************************************************
2173************************** Begin flock Locking ********************************
2174**
2175** Use the flock() system call to do file locking.
2176**
drh6b9d6dd2008-12-03 19:34:47 +00002177** flock() locking is like dot-file locking in that the various
2178** fine-grain locking levels supported by SQLite are collapsed into
2179** a single exclusive lock. In other words, SHARED, RESERVED, and
2180** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2181** still works when you do this, but concurrency is reduced since
2182** only a single process can be reading the database at a time.
2183**
drhe89b2912015-03-03 20:42:01 +00002184** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
drh734c9862008-11-28 15:37:20 +00002185*/
drhe89b2912015-03-03 20:42:01 +00002186#if SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002187
drh6b9d6dd2008-12-03 19:34:47 +00002188/*
drhff812312011-02-23 13:33:46 +00002189** Retry flock() calls that fail with EINTR
2190*/
2191#ifdef EINTR
2192static int robust_flock(int fd, int op){
2193 int rc;
2194 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2195 return rc;
2196}
2197#else
drh5c819272011-02-23 14:00:12 +00002198# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002199#endif
2200
2201
2202/*
drh6b9d6dd2008-12-03 19:34:47 +00002203** This routine checks if there is a RESERVED lock held on the specified
2204** file by this or any other process. If such a lock is held, set *pResOut
2205** to a non-zero value otherwise *pResOut is set to zero. The return value
2206** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2207*/
drh734c9862008-11-28 15:37:20 +00002208static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2209 int rc = SQLITE_OK;
2210 int reserved = 0;
2211 unixFile *pFile = (unixFile*)id;
2212
2213 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2214
2215 assert( pFile );
2216
2217 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002218 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002219 reserved = 1;
2220 }
2221
2222 /* Otherwise see if some other process holds it. */
2223 if( !reserved ){
2224 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002225 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002226 if( !lrc ){
2227 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002228 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002229 if ( lrc ) {
2230 int tErrno = errno;
2231 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002232 lrc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00002233 storeLastErrno(pFile, tErrno);
2234 rc = lrc;
drh734c9862008-11-28 15:37:20 +00002235 }
2236 } else {
2237 int tErrno = errno;
2238 reserved = 1;
2239 /* someone else might have it reserved */
2240 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2241 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002242 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002243 rc = lrc;
2244 }
2245 }
2246 }
drh308c2a52010-05-14 11:30:18 +00002247 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002248
2249#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2250 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2251 rc = SQLITE_OK;
2252 reserved=1;
2253 }
2254#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2255 *pResOut = reserved;
2256 return rc;
2257}
2258
drh6b9d6dd2008-12-03 19:34:47 +00002259/*
drh308c2a52010-05-14 11:30:18 +00002260** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002261** of the following:
2262**
2263** (1) SHARED_LOCK
2264** (2) RESERVED_LOCK
2265** (3) PENDING_LOCK
2266** (4) EXCLUSIVE_LOCK
2267**
2268** Sometimes when requesting one lock state, additional lock states
2269** are inserted in between. The locking might fail on one of the later
2270** transitions leaving the lock state different from what it started but
2271** still short of its goal. The following chart shows the allowed
2272** transitions and the inserted intermediate states:
2273**
2274** UNLOCKED -> SHARED
2275** SHARED -> RESERVED
2276** SHARED -> (PENDING) -> EXCLUSIVE
2277** RESERVED -> (PENDING) -> EXCLUSIVE
2278** PENDING -> EXCLUSIVE
2279**
2280** flock() only really support EXCLUSIVE locks. We track intermediate
2281** lock states in the sqlite3_file structure, but all locks SHARED or
2282** above are really EXCLUSIVE locks and exclude all other processes from
2283** access the file.
2284**
2285** This routine will only increase a lock. Use the sqlite3OsUnlock()
2286** routine to lower a locking level.
2287*/
drh308c2a52010-05-14 11:30:18 +00002288static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002289 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002290 unixFile *pFile = (unixFile*)id;
2291
2292 assert( pFile );
2293
2294 /* if we already have a lock, it is exclusive.
2295 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002296 if (pFile->eFileLock > NO_LOCK) {
2297 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002298 return SQLITE_OK;
2299 }
2300
2301 /* grab an exclusive lock */
2302
drhff812312011-02-23 13:33:46 +00002303 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002304 int tErrno = errno;
2305 /* didn't get, must be busy */
2306 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2307 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002308 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002309 }
2310 } else {
2311 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002312 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002313 }
drh308c2a52010-05-14 11:30:18 +00002314 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2315 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002316#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2317 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2318 rc = SQLITE_BUSY;
2319 }
2320#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2321 return rc;
2322}
2323
drh6b9d6dd2008-12-03 19:34:47 +00002324
2325/*
drh308c2a52010-05-14 11:30:18 +00002326** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002327** must be either NO_LOCK or SHARED_LOCK.
2328**
2329** If the locking level of the file descriptor is already at or below
2330** the requested locking level, this routine is a no-op.
2331*/
drh308c2a52010-05-14 11:30:18 +00002332static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002333 unixFile *pFile = (unixFile*)id;
2334
2335 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002336 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002337 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002338 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002339
2340 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002341 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002342 return SQLITE_OK;
2343 }
2344
2345 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002346 if (eFileLock==SHARED_LOCK) {
2347 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002348 return SQLITE_OK;
2349 }
2350
2351 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002352 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002353#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002354 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002355#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002356 return SQLITE_IOERR_UNLOCK;
2357 }else{
drh308c2a52010-05-14 11:30:18 +00002358 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002359 return SQLITE_OK;
2360 }
2361}
2362
2363/*
2364** Close a file.
2365*/
2366static int flockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002367 assert( id!=0 );
2368 flockUnlock(id, NO_LOCK);
2369 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002370}
2371
2372#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2373
2374/******************* End of the flock lock implementation *********************
2375******************************************************************************/
2376
2377/******************************************************************************
2378************************ Begin Named Semaphore Locking ************************
2379**
2380** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002381**
2382** Semaphore locking is like dot-lock and flock in that it really only
2383** supports EXCLUSIVE locking. Only a single process can read or write
2384** the database file at a time. This reduces potential concurrency, but
2385** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002386*/
2387#if OS_VXWORKS
2388
drh6b9d6dd2008-12-03 19:34:47 +00002389/*
2390** This routine checks if there is a RESERVED lock held on the specified
2391** file by this or any other process. If such a lock is held, set *pResOut
2392** to a non-zero value otherwise *pResOut is set to zero. The return value
2393** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2394*/
drh8cd5b252015-03-02 22:06:43 +00002395static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
drh734c9862008-11-28 15:37:20 +00002396 int rc = SQLITE_OK;
2397 int reserved = 0;
2398 unixFile *pFile = (unixFile*)id;
2399
2400 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2401
2402 assert( pFile );
2403
2404 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002405 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002406 reserved = 1;
2407 }
2408
2409 /* Otherwise see if some other process holds it. */
2410 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002411 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002412
2413 if( sem_trywait(pSem)==-1 ){
2414 int tErrno = errno;
2415 if( EAGAIN != tErrno ){
2416 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
drh4bf66fd2015-02-19 02:43:02 +00002417 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002418 } else {
2419 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002420 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002421 }
2422 }else{
2423 /* we could have it if we want it */
2424 sem_post(pSem);
2425 }
2426 }
drh308c2a52010-05-14 11:30:18 +00002427 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002428
2429 *pResOut = reserved;
2430 return rc;
2431}
2432
drh6b9d6dd2008-12-03 19:34:47 +00002433/*
drh308c2a52010-05-14 11:30:18 +00002434** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002435** of the following:
2436**
2437** (1) SHARED_LOCK
2438** (2) RESERVED_LOCK
2439** (3) PENDING_LOCK
2440** (4) EXCLUSIVE_LOCK
2441**
2442** Sometimes when requesting one lock state, additional lock states
2443** are inserted in between. The locking might fail on one of the later
2444** transitions leaving the lock state different from what it started but
2445** still short of its goal. The following chart shows the allowed
2446** transitions and the inserted intermediate states:
2447**
2448** UNLOCKED -> SHARED
2449** SHARED -> RESERVED
2450** SHARED -> (PENDING) -> EXCLUSIVE
2451** RESERVED -> (PENDING) -> EXCLUSIVE
2452** PENDING -> EXCLUSIVE
2453**
2454** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2455** lock states in the sqlite3_file structure, but all locks SHARED or
2456** above are really EXCLUSIVE locks and exclude all other processes from
2457** access the file.
2458**
2459** This routine will only increase a lock. Use the sqlite3OsUnlock()
2460** routine to lower a locking level.
2461*/
drh8cd5b252015-03-02 22:06:43 +00002462static int semXLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002463 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002464 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002465 int rc = SQLITE_OK;
2466
2467 /* if we already have a lock, it is exclusive.
2468 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002469 if (pFile->eFileLock > NO_LOCK) {
2470 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002471 rc = SQLITE_OK;
2472 goto sem_end_lock;
2473 }
2474
2475 /* lock semaphore now but bail out when already locked. */
2476 if( sem_trywait(pSem)==-1 ){
2477 rc = SQLITE_BUSY;
2478 goto sem_end_lock;
2479 }
2480
2481 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002482 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002483
2484 sem_end_lock:
2485 return rc;
2486}
2487
drh6b9d6dd2008-12-03 19:34:47 +00002488/*
drh308c2a52010-05-14 11:30:18 +00002489** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002490** must be either NO_LOCK or SHARED_LOCK.
2491**
2492** If the locking level of the file descriptor is already at or below
2493** the requested locking level, this routine is a no-op.
2494*/
drh8cd5b252015-03-02 22:06:43 +00002495static int semXUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002496 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002497 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002498
2499 assert( pFile );
2500 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002501 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002502 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002503 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002504
2505 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002506 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002507 return SQLITE_OK;
2508 }
2509
2510 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002511 if (eFileLock==SHARED_LOCK) {
2512 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002513 return SQLITE_OK;
2514 }
2515
2516 /* no, really unlock. */
2517 if ( sem_post(pSem)==-1 ) {
2518 int rc, tErrno = errno;
2519 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2520 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002521 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002522 }
2523 return rc;
2524 }
drh308c2a52010-05-14 11:30:18 +00002525 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002526 return SQLITE_OK;
2527}
2528
2529/*
2530 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002531 */
drh8cd5b252015-03-02 22:06:43 +00002532static int semXClose(sqlite3_file *id) {
drh734c9862008-11-28 15:37:20 +00002533 if( id ){
2534 unixFile *pFile = (unixFile*)id;
drh8cd5b252015-03-02 22:06:43 +00002535 semXUnlock(id, NO_LOCK);
drh734c9862008-11-28 15:37:20 +00002536 assert( pFile );
2537 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002538 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002539 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002540 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002541 }
2542 return SQLITE_OK;
2543}
2544
2545#endif /* OS_VXWORKS */
2546/*
2547** Named semaphore locking is only available on VxWorks.
2548**
2549*************** End of the named semaphore lock implementation ****************
2550******************************************************************************/
2551
2552
2553/******************************************************************************
2554*************************** Begin AFP Locking *********************************
2555**
2556** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2557** on Apple Macintosh computers - both OS9 and OSX.
2558**
2559** Third-party implementations of AFP are available. But this code here
2560** only works on OSX.
2561*/
2562
drhd2cb50b2009-01-09 21:41:17 +00002563#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002564/*
2565** The afpLockingContext structure contains all afp lock specific state
2566*/
drhbfe66312006-10-03 17:40:40 +00002567typedef struct afpLockingContext afpLockingContext;
2568struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002569 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002570 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002571};
2572
2573struct ByteRangeLockPB2
2574{
2575 unsigned long long offset; /* offset to first byte to lock */
2576 unsigned long long length; /* nbr of bytes to lock */
2577 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2578 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2579 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2580 int fd; /* file desc to assoc this lock with */
2581};
2582
drhfd131da2007-08-07 17:13:03 +00002583#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002584
drh6b9d6dd2008-12-03 19:34:47 +00002585/*
2586** This is a utility for setting or clearing a bit-range lock on an
2587** AFP filesystem.
2588**
2589** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2590*/
2591static int afpSetLock(
2592 const char *path, /* Name of the file to be locked or unlocked */
2593 unixFile *pFile, /* Open file descriptor on path */
2594 unsigned long long offset, /* First byte to be locked */
2595 unsigned long long length, /* Number of bytes to lock */
2596 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002597){
drh6b9d6dd2008-12-03 19:34:47 +00002598 struct ByteRangeLockPB2 pb;
2599 int err;
drhbfe66312006-10-03 17:40:40 +00002600
2601 pb.unLockFlag = setLockFlag ? 0 : 1;
2602 pb.startEndFlag = 0;
2603 pb.offset = offset;
2604 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002605 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002606
drh308c2a52010-05-14 11:30:18 +00002607 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002608 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002609 offset, length));
drhbfe66312006-10-03 17:40:40 +00002610 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2611 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002612 int rc;
2613 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002614 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2615 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002616#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2617 rc = SQLITE_BUSY;
2618#else
drh734c9862008-11-28 15:37:20 +00002619 rc = sqliteErrorFromPosixError(tErrno,
2620 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002621#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002622 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002623 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00002624 }
2625 return rc;
drhbfe66312006-10-03 17:40:40 +00002626 } else {
aswift5b1a2562008-08-22 00:22:35 +00002627 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002628 }
2629}
2630
drh6b9d6dd2008-12-03 19:34:47 +00002631/*
2632** This routine checks if there is a RESERVED lock held on the specified
2633** file by this or any other process. If such a lock is held, set *pResOut
2634** to a non-zero value otherwise *pResOut is set to zero. The return value
2635** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2636*/
danielk1977e339d652008-06-28 11:23:00 +00002637static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002638 int rc = SQLITE_OK;
2639 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002640 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002641 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002642
aswift5b1a2562008-08-22 00:22:35 +00002643 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2644
2645 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002646 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002647 if( context->reserved ){
2648 *pResOut = 1;
2649 return SQLITE_OK;
2650 }
drh8af6c222010-05-14 12:43:01 +00002651 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002652
2653 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002654 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002655 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002656 }
2657
2658 /* Otherwise see if some other process holds it.
2659 */
aswift5b1a2562008-08-22 00:22:35 +00002660 if( !reserved ){
2661 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002662 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002663 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002664 /* if we succeeded in taking the reserved lock, unlock it to restore
2665 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002666 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002667 } else {
2668 /* if we failed to get the lock then someone else must have it */
2669 reserved = 1;
2670 }
2671 if( IS_LOCK_ERROR(lrc) ){
2672 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002673 }
2674 }
drhbfe66312006-10-03 17:40:40 +00002675
drh7ed97b92010-01-20 13:07:21 +00002676 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002677 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002678
2679 *pResOut = reserved;
2680 return rc;
drhbfe66312006-10-03 17:40:40 +00002681}
2682
drh6b9d6dd2008-12-03 19:34:47 +00002683/*
drh308c2a52010-05-14 11:30:18 +00002684** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002685** of the following:
2686**
2687** (1) SHARED_LOCK
2688** (2) RESERVED_LOCK
2689** (3) PENDING_LOCK
2690** (4) EXCLUSIVE_LOCK
2691**
2692** Sometimes when requesting one lock state, additional lock states
2693** are inserted in between. The locking might fail on one of the later
2694** transitions leaving the lock state different from what it started but
2695** still short of its goal. The following chart shows the allowed
2696** transitions and the inserted intermediate states:
2697**
2698** UNLOCKED -> SHARED
2699** SHARED -> RESERVED
2700** SHARED -> (PENDING) -> EXCLUSIVE
2701** RESERVED -> (PENDING) -> EXCLUSIVE
2702** PENDING -> EXCLUSIVE
2703**
2704** This routine will only increase a lock. Use the sqlite3OsUnlock()
2705** routine to lower a locking level.
2706*/
drh308c2a52010-05-14 11:30:18 +00002707static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002708 int rc = SQLITE_OK;
2709 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002710 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002711 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002712
2713 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002714 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2715 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh5ac93652015-03-21 20:59:43 +00002716 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
drh339eb0b2008-03-07 15:34:11 +00002717
drhbfe66312006-10-03 17:40:40 +00002718 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002719 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002720 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002721 */
drh308c2a52010-05-14 11:30:18 +00002722 if( pFile->eFileLock>=eFileLock ){
2723 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2724 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002725 return SQLITE_OK;
2726 }
2727
2728 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002729 ** (1) We never move from unlocked to anything higher than shared lock.
2730 ** (2) SQLite never explicitly requests a pendig lock.
2731 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002732 */
drh308c2a52010-05-14 11:30:18 +00002733 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2734 assert( eFileLock!=PENDING_LOCK );
2735 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002736
drh8af6c222010-05-14 12:43:01 +00002737 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002738 */
drh6c7d5c52008-11-21 20:32:33 +00002739 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002740 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002741
2742 /* If some thread using this PID has a lock via a different unixFile*
2743 ** handle that precludes the requested lock, return BUSY.
2744 */
drh8af6c222010-05-14 12:43:01 +00002745 if( (pFile->eFileLock!=pInode->eFileLock &&
2746 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002747 ){
2748 rc = SQLITE_BUSY;
2749 goto afp_end_lock;
2750 }
2751
2752 /* If a SHARED lock is requested, and some thread using this PID already
2753 ** has a SHARED or RESERVED lock, then increment reference counts and
2754 ** return SQLITE_OK.
2755 */
drh308c2a52010-05-14 11:30:18 +00002756 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002757 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002758 assert( eFileLock==SHARED_LOCK );
2759 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002760 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002761 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002762 pInode->nShared++;
2763 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002764 goto afp_end_lock;
2765 }
drhbfe66312006-10-03 17:40:40 +00002766
2767 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002768 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2769 ** be released.
2770 */
drh308c2a52010-05-14 11:30:18 +00002771 if( eFileLock==SHARED_LOCK
2772 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002773 ){
2774 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002775 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002776 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002777 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002778 goto afp_end_lock;
2779 }
2780 }
2781
2782 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002783 ** operating system calls for the specified lock.
2784 */
drh308c2a52010-05-14 11:30:18 +00002785 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002786 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002787 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002788
drh8af6c222010-05-14 12:43:01 +00002789 assert( pInode->nShared==0 );
2790 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002791
2792 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002793 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002794 /* note that the quality of the randomness doesn't matter that much */
2795 lk = random();
drh8af6c222010-05-14 12:43:01 +00002796 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002797 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002798 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002799 if( IS_LOCK_ERROR(lrc1) ){
2800 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002801 }
aswift5b1a2562008-08-22 00:22:35 +00002802 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002803 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002804
aswift5b1a2562008-08-22 00:22:35 +00002805 if( IS_LOCK_ERROR(lrc1) ) {
drh4bf66fd2015-02-19 02:43:02 +00002806 storeLastErrno(pFile, lrc1Errno);
aswift5b1a2562008-08-22 00:22:35 +00002807 rc = lrc1;
2808 goto afp_end_lock;
2809 } else if( IS_LOCK_ERROR(lrc2) ){
2810 rc = lrc2;
2811 goto afp_end_lock;
2812 } else if( lrc1 != SQLITE_OK ) {
2813 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002814 } else {
drh308c2a52010-05-14 11:30:18 +00002815 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002816 pInode->nLock++;
2817 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002818 }
drh8af6c222010-05-14 12:43:01 +00002819 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002820 /* We are trying for an exclusive lock but another thread in this
2821 ** same process is still holding a shared lock. */
2822 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002823 }else{
2824 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2825 ** assumed that there is a SHARED or greater lock on the file
2826 ** already.
2827 */
2828 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002829 assert( 0!=pFile->eFileLock );
2830 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002831 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002832 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002833 if( !failed ){
2834 context->reserved = 1;
2835 }
drhbfe66312006-10-03 17:40:40 +00002836 }
drh308c2a52010-05-14 11:30:18 +00002837 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002838 /* Acquire an EXCLUSIVE lock */
2839
2840 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002841 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002842 */
drh6b9d6dd2008-12-03 19:34:47 +00002843 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002844 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002845 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002846 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002847 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002848 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002849 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002850 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002851 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2852 ** a critical I/O error
2853 */
2854 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2855 SQLITE_IOERR_LOCK;
2856 goto afp_end_lock;
2857 }
2858 }else{
aswift5b1a2562008-08-22 00:22:35 +00002859 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002860 }
2861 }
aswift5b1a2562008-08-22 00:22:35 +00002862 if( failed ){
2863 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002864 }
2865 }
2866
2867 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002868 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002869 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002870 }else if( eFileLock==EXCLUSIVE_LOCK ){
2871 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002872 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002873 }
2874
2875afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002876 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002877 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2878 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002879 return rc;
2880}
2881
2882/*
drh308c2a52010-05-14 11:30:18 +00002883** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002884** must be either NO_LOCK or SHARED_LOCK.
2885**
2886** If the locking level of the file descriptor is already at or below
2887** the requested locking level, this routine is a no-op.
2888*/
drh308c2a52010-05-14 11:30:18 +00002889static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002890 int rc = SQLITE_OK;
2891 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002892 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002893 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2894 int skipShared = 0;
2895#ifdef SQLITE_TEST
2896 int h = pFile->h;
2897#endif
drhbfe66312006-10-03 17:40:40 +00002898
2899 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002900 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002901 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00002902 osGetpid(0)));
aswift5b1a2562008-08-22 00:22:35 +00002903
drh308c2a52010-05-14 11:30:18 +00002904 assert( eFileLock<=SHARED_LOCK );
2905 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002906 return SQLITE_OK;
2907 }
drh6c7d5c52008-11-21 20:32:33 +00002908 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002909 pInode = pFile->pInode;
2910 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002911 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002912 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002913 SimulateIOErrorBenign(1);
2914 SimulateIOError( h=(-1) )
2915 SimulateIOErrorBenign(0);
2916
drhd3d8c042012-05-29 17:02:40 +00002917#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002918 /* When reducing a lock such that other processes can start
2919 ** reading the database file again, make sure that the
2920 ** transaction counter was updated if any part of the database
2921 ** file changed. If the transaction counter is not updated,
2922 ** other connections to the same file might not realize that
2923 ** the file has changed and hence might not know to flush their
2924 ** cache. The use of a stale cache can lead to database corruption.
2925 */
2926 assert( pFile->inNormalWrite==0
2927 || pFile->dbUpdate==0
2928 || pFile->transCntrChng==1 );
2929 pFile->inNormalWrite = 0;
2930#endif
aswiftaebf4132008-11-21 00:10:35 +00002931
drh308c2a52010-05-14 11:30:18 +00002932 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002933 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002934 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002935 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002936 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002937 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2938 } else {
2939 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002940 }
2941 }
drh308c2a52010-05-14 11:30:18 +00002942 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002943 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002944 }
drh308c2a52010-05-14 11:30:18 +00002945 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002946 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2947 if( !rc ){
2948 context->reserved = 0;
2949 }
aswiftaebf4132008-11-21 00:10:35 +00002950 }
drh8af6c222010-05-14 12:43:01 +00002951 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2952 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002953 }
aswiftaebf4132008-11-21 00:10:35 +00002954 }
drh308c2a52010-05-14 11:30:18 +00002955 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002956
drh7ed97b92010-01-20 13:07:21 +00002957 /* Decrement the shared lock counter. Release the lock using an
2958 ** OS call only when all threads in this same process have released
2959 ** the lock.
2960 */
drh8af6c222010-05-14 12:43:01 +00002961 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2962 pInode->nShared--;
2963 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002964 SimulateIOErrorBenign(1);
2965 SimulateIOError( h=(-1) )
2966 SimulateIOErrorBenign(0);
2967 if( !skipShared ){
2968 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2969 }
2970 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002971 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002972 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002973 }
2974 }
2975 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002976 pInode->nLock--;
2977 assert( pInode->nLock>=0 );
2978 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002979 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002980 }
2981 }
drhbfe66312006-10-03 17:40:40 +00002982 }
drh7ed97b92010-01-20 13:07:21 +00002983
drh6c7d5c52008-11-21 20:32:33 +00002984 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002985 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002986 return rc;
2987}
2988
2989/*
drh339eb0b2008-03-07 15:34:11 +00002990** Close a file & cleanup AFP specific locking context
2991*/
danielk1977e339d652008-06-28 11:23:00 +00002992static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002993 int rc = SQLITE_OK;
drha8de1e12015-11-30 00:05:39 +00002994 unixFile *pFile = (unixFile*)id;
2995 assert( id!=0 );
2996 afpUnlock(id, NO_LOCK);
2997 unixEnterMutex();
2998 if( pFile->pInode && pFile->pInode->nLock ){
2999 /* If there are outstanding locks, do not actually close the file just
3000 ** yet because that would clear those locks. Instead, add the file
3001 ** descriptor to pInode->aPending. It will be automatically closed when
3002 ** the last lock is cleared.
3003 */
3004 setPendingFd(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003005 }
drha8de1e12015-11-30 00:05:39 +00003006 releaseInodeInfo(pFile);
3007 sqlite3_free(pFile->lockingContext);
3008 rc = closeUnixFile(id);
3009 unixLeaveMutex();
drh7ed97b92010-01-20 13:07:21 +00003010 return rc;
drhbfe66312006-10-03 17:40:40 +00003011}
3012
drhd2cb50b2009-01-09 21:41:17 +00003013#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003014/*
3015** The code above is the AFP lock implementation. The code is specific
3016** to MacOSX and does not work on other unix platforms. No alternative
3017** is available. If you don't compile for a mac, then the "unix-afp"
3018** VFS is not available.
3019**
3020********************* End of the AFP lock implementation **********************
3021******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003022
drh7ed97b92010-01-20 13:07:21 +00003023/******************************************************************************
3024*************************** Begin NFS Locking ********************************/
3025
3026#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3027/*
drh308c2a52010-05-14 11:30:18 +00003028 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003029 ** must be either NO_LOCK or SHARED_LOCK.
3030 **
3031 ** If the locking level of the file descriptor is already at or below
3032 ** the requested locking level, this routine is a no-op.
3033 */
drh308c2a52010-05-14 11:30:18 +00003034static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003035 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003036}
3037
3038#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3039/*
3040** The code above is the NFS lock implementation. The code is specific
3041** to MacOSX and does not work on other unix platforms. No alternative
3042** is available.
3043**
3044********************* End of the NFS lock implementation **********************
3045******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003046
3047/******************************************************************************
3048**************** Non-locking sqlite3_file methods *****************************
3049**
3050** The next division contains implementations for all methods of the
3051** sqlite3_file object other than the locking methods. The locking
3052** methods were defined in divisions above (one locking method per
3053** division). Those methods that are common to all locking modes
3054** are gather together into this division.
3055*/
drhbfe66312006-10-03 17:40:40 +00003056
3057/*
drh734c9862008-11-28 15:37:20 +00003058** Seek to the offset passed as the second argument, then read cnt
3059** bytes into pBuf. Return the number of bytes actually read.
3060**
3061** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3062** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3063** one system to another. Since SQLite does not define USE_PREAD
peter.d.reid60ec9142014-09-06 16:39:46 +00003064** in any form by default, we will not attempt to define _XOPEN_SOURCE.
drh734c9862008-11-28 15:37:20 +00003065** See tickets #2741 and #2681.
3066**
3067** To avoid stomping the errno value on a failed read the lastErrno value
3068** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003069*/
drh734c9862008-11-28 15:37:20 +00003070static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3071 int got;
drh58024642011-11-07 18:16:00 +00003072 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003073#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003074 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003075#endif
drh734c9862008-11-28 15:37:20 +00003076 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003077 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003078 assert( id->h>2 );
drh58024642011-11-07 18:16:00 +00003079 do{
drh734c9862008-11-28 15:37:20 +00003080#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003081 got = osPread(id->h, pBuf, cnt, offset);
3082 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003083#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003084 got = osPread64(id->h, pBuf, cnt, offset);
3085 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003086#else
drh58024642011-11-07 18:16:00 +00003087 newOffset = lseek(id->h, offset, SEEK_SET);
drhe1818ec2015-12-01 16:21:35 +00003088 SimulateIOError( newOffset = -1 );
3089 if( newOffset<0 ){
3090 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003091 return -1;
drh734c9862008-11-28 15:37:20 +00003092 }
drh58024642011-11-07 18:16:00 +00003093 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003094#endif
drh58024642011-11-07 18:16:00 +00003095 if( got==cnt ) break;
3096 if( got<0 ){
3097 if( errno==EINTR ){ got = 1; continue; }
3098 prior = 0;
drh4bf66fd2015-02-19 02:43:02 +00003099 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003100 break;
3101 }else if( got>0 ){
3102 cnt -= got;
3103 offset += got;
3104 prior += got;
3105 pBuf = (void*)(got + (char*)pBuf);
3106 }
3107 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003108 TIMER_END;
drh58024642011-11-07 18:16:00 +00003109 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3110 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3111 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003112}
3113
3114/*
drh734c9862008-11-28 15:37:20 +00003115** Read data from a file into a buffer. Return SQLITE_OK if all
3116** bytes were read successfully and SQLITE_IOERR if anything goes
3117** wrong.
drh339eb0b2008-03-07 15:34:11 +00003118*/
drh734c9862008-11-28 15:37:20 +00003119static int unixRead(
3120 sqlite3_file *id,
3121 void *pBuf,
3122 int amt,
3123 sqlite3_int64 offset
3124){
dan08da86a2009-08-21 17:18:03 +00003125 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003126 int got;
3127 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003128 assert( offset>=0 );
3129 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003130
dan08da86a2009-08-21 17:18:03 +00003131 /* If this is a database file (not a journal, master-journal or temp
3132 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003133#if 0
dane946c392009-08-22 11:39:46 +00003134 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003135 || offset>=PENDING_BYTE+512
3136 || offset+amt<=PENDING_BYTE
3137 );
dan7c246102010-04-12 19:00:29 +00003138#endif
drh08c6d442009-02-09 17:34:07 +00003139
drh9b4c59f2013-04-15 17:03:42 +00003140#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003141 /* Deal with as much of this read request as possible by transfering
3142 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003143 if( offset<pFile->mmapSize ){
3144 if( offset+amt <= pFile->mmapSize ){
3145 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3146 return SQLITE_OK;
3147 }else{
3148 int nCopy = pFile->mmapSize - offset;
3149 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3150 pBuf = &((u8 *)pBuf)[nCopy];
3151 amt -= nCopy;
3152 offset += nCopy;
3153 }
3154 }
drh6e0b6d52013-04-09 16:19:20 +00003155#endif
danf23da962013-03-23 21:00:41 +00003156
dan08da86a2009-08-21 17:18:03 +00003157 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003158 if( got==amt ){
3159 return SQLITE_OK;
3160 }else if( got<0 ){
3161 /* lastErrno set by seekAndRead */
3162 return SQLITE_IOERR_READ;
3163 }else{
drh4bf66fd2015-02-19 02:43:02 +00003164 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003165 /* Unread parts of the buffer must be zero-filled */
3166 memset(&((char*)pBuf)[got], 0, amt-got);
3167 return SQLITE_IOERR_SHORT_READ;
3168 }
3169}
3170
3171/*
dan47a2b4a2013-04-26 16:09:29 +00003172** Attempt to seek the file-descriptor passed as the first argument to
3173** absolute offset iOff, then attempt to write nBuf bytes of data from
3174** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3175** return the actual number of bytes written (which may be less than
3176** nBuf).
3177*/
3178static int seekAndWriteFd(
3179 int fd, /* File descriptor to write to */
3180 i64 iOff, /* File offset to begin writing at */
3181 const void *pBuf, /* Copy data from this buffer to the file */
3182 int nBuf, /* Size of buffer pBuf in bytes */
3183 int *piErrno /* OUT: Error number if error occurs */
3184){
3185 int rc = 0; /* Value returned by system call */
3186
3187 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003188 assert( fd>2 );
drhe1818ec2015-12-01 16:21:35 +00003189 assert( piErrno!=0 );
dan47a2b4a2013-04-26 16:09:29 +00003190 nBuf &= 0x1ffff;
3191 TIMER_START;
3192
3193#if defined(USE_PREAD)
drh2da47d32015-02-21 00:56:05 +00003194 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
dan47a2b4a2013-04-26 16:09:29 +00003195#elif defined(USE_PREAD64)
drh2da47d32015-02-21 00:56:05 +00003196 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
dan47a2b4a2013-04-26 16:09:29 +00003197#else
3198 do{
3199 i64 iSeek = lseek(fd, iOff, SEEK_SET);
drhe1818ec2015-12-01 16:21:35 +00003200 SimulateIOError( iSeek = -1 );
3201 if( iSeek<0 ){
3202 rc = -1;
3203 break;
dan47a2b4a2013-04-26 16:09:29 +00003204 }
3205 rc = osWrite(fd, pBuf, nBuf);
3206 }while( rc<0 && errno==EINTR );
3207#endif
3208
3209 TIMER_END;
3210 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3211
drhe1818ec2015-12-01 16:21:35 +00003212 if( rc<0 ) *piErrno = errno;
dan47a2b4a2013-04-26 16:09:29 +00003213 return rc;
3214}
3215
3216
3217/*
drh734c9862008-11-28 15:37:20 +00003218** Seek to the offset in id->offset then read cnt bytes into pBuf.
3219** Return the number of bytes actually read. Update the offset.
3220**
3221** To avoid stomping the errno value on a failed write the lastErrno value
3222** is set before returning.
3223*/
3224static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003225 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003226}
3227
3228
3229/*
3230** Write data from a buffer into a file. Return SQLITE_OK on success
3231** or some other error code on failure.
3232*/
3233static int unixWrite(
3234 sqlite3_file *id,
3235 const void *pBuf,
3236 int amt,
3237 sqlite3_int64 offset
3238){
dan08da86a2009-08-21 17:18:03 +00003239 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003240 int wrote = 0;
3241 assert( id );
3242 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003243
dan08da86a2009-08-21 17:18:03 +00003244 /* If this is a database file (not a journal, master-journal or temp
3245 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003246#if 0
dane946c392009-08-22 11:39:46 +00003247 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003248 || offset>=PENDING_BYTE+512
3249 || offset+amt<=PENDING_BYTE
3250 );
dan7c246102010-04-12 19:00:29 +00003251#endif
drh08c6d442009-02-09 17:34:07 +00003252
drhd3d8c042012-05-29 17:02:40 +00003253#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003254 /* If we are doing a normal write to a database file (as opposed to
3255 ** doing a hot-journal rollback or a write to some file other than a
3256 ** normal database file) then record the fact that the database
3257 ** has changed. If the transaction counter is modified, record that
3258 ** fact too.
3259 */
dan08da86a2009-08-21 17:18:03 +00003260 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003261 pFile->dbUpdate = 1; /* The database has been modified */
3262 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003263 int rc;
drh8f941bc2009-01-14 23:03:40 +00003264 char oldCntr[4];
3265 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003266 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003267 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003268 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003269 pFile->transCntrChng = 1; /* The transaction counter has changed */
3270 }
3271 }
3272 }
3273#endif
3274
danfe33e392015-11-17 20:56:06 +00003275#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003276 /* Deal with as much of this write request as possible by transfering
3277 ** data from the memory mapping using memcpy(). */
3278 if( offset<pFile->mmapSize ){
3279 if( offset+amt <= pFile->mmapSize ){
3280 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3281 return SQLITE_OK;
3282 }else{
3283 int nCopy = pFile->mmapSize - offset;
3284 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3285 pBuf = &((u8 *)pBuf)[nCopy];
3286 amt -= nCopy;
3287 offset += nCopy;
3288 }
3289 }
drh6e0b6d52013-04-09 16:19:20 +00003290#endif
drh02bf8b42015-09-01 23:51:53 +00003291
3292 while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
drh734c9862008-11-28 15:37:20 +00003293 amt -= wrote;
3294 offset += wrote;
3295 pBuf = &((char*)pBuf)[wrote];
3296 }
3297 SimulateIOError(( wrote=(-1), amt=1 ));
3298 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003299
drh02bf8b42015-09-01 23:51:53 +00003300 if( amt>wrote ){
drha21b83b2011-04-15 12:36:10 +00003301 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003302 /* lastErrno set by seekAndWrite */
3303 return SQLITE_IOERR_WRITE;
3304 }else{
drh4bf66fd2015-02-19 02:43:02 +00003305 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003306 return SQLITE_FULL;
3307 }
3308 }
dan6e09d692010-07-27 18:34:15 +00003309
drh734c9862008-11-28 15:37:20 +00003310 return SQLITE_OK;
3311}
3312
3313#ifdef SQLITE_TEST
3314/*
3315** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003316** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003317*/
3318int sqlite3_sync_count = 0;
3319int sqlite3_fullsync_count = 0;
3320#endif
3321
3322/*
drh89240432009-03-25 01:06:01 +00003323** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003324** Others do no. To be safe, we will stick with the (slightly slower)
3325** fsync(). If you know that your system does support fdatasync() correctly,
drhf7a4a1b2015-01-10 18:02:45 +00003326** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003327*/
drhf7a4a1b2015-01-10 18:02:45 +00003328#if !defined(fdatasync) && !HAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003329# define fdatasync fsync
3330#endif
3331
3332/*
3333** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3334** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3335** only available on Mac OS X. But that could change.
3336*/
3337#ifdef F_FULLFSYNC
3338# define HAVE_FULLFSYNC 1
3339#else
3340# define HAVE_FULLFSYNC 0
3341#endif
3342
3343
3344/*
3345** The fsync() system call does not work as advertised on many
3346** unix systems. The following procedure is an attempt to make
3347** it work better.
3348**
3349** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3350** for testing when we want to run through the test suite quickly.
3351** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3352** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3353** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003354**
3355** SQLite sets the dataOnly flag if the size of the file is unchanged.
3356** The idea behind dataOnly is that it should only write the file content
3357** to disk, not the inode. We only set dataOnly if the file size is
3358** unchanged since the file size is part of the inode. However,
3359** Ted Ts'o tells us that fdatasync() will also write the inode if the
3360** file size has changed. The only real difference between fdatasync()
3361** and fsync(), Ted tells us, is that fdatasync() will not flush the
3362** inode if the mtime or owner or other inode attributes have changed.
3363** We only care about the file size, not the other file attributes, so
3364** as far as SQLite is concerned, an fdatasync() is always adequate.
3365** So, we always use fdatasync() if it is available, regardless of
3366** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003367*/
3368static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003369 int rc;
drh734c9862008-11-28 15:37:20 +00003370
3371 /* The following "ifdef/elif/else/" block has the same structure as
3372 ** the one below. It is replicated here solely to avoid cluttering
3373 ** up the real code with the UNUSED_PARAMETER() macros.
3374 */
3375#ifdef SQLITE_NO_SYNC
3376 UNUSED_PARAMETER(fd);
3377 UNUSED_PARAMETER(fullSync);
3378 UNUSED_PARAMETER(dataOnly);
3379#elif HAVE_FULLFSYNC
3380 UNUSED_PARAMETER(dataOnly);
3381#else
3382 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003383 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003384#endif
3385
3386 /* Record the number of times that we do a normal fsync() and
3387 ** FULLSYNC. This is used during testing to verify that this procedure
3388 ** gets called with the correct arguments.
3389 */
3390#ifdef SQLITE_TEST
3391 if( fullSync ) sqlite3_fullsync_count++;
3392 sqlite3_sync_count++;
3393#endif
3394
3395 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3396 ** no-op
3397 */
3398#ifdef SQLITE_NO_SYNC
3399 rc = SQLITE_OK;
3400#elif HAVE_FULLFSYNC
3401 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003402 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003403 }else{
3404 rc = 1;
3405 }
3406 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003407 ** It shouldn't be possible for fullfsync to fail on the local
3408 ** file system (on OSX), so failure indicates that FULLFSYNC
3409 ** isn't supported for this file system. So, attempt an fsync
3410 ** and (for now) ignore the overhead of a superfluous fcntl call.
3411 ** It'd be better to detect fullfsync support once and avoid
3412 ** the fcntl call every time sync is called.
3413 */
drh734c9862008-11-28 15:37:20 +00003414 if( rc ) rc = fsync(fd);
3415
drh7ed97b92010-01-20 13:07:21 +00003416#elif defined(__APPLE__)
3417 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3418 ** so currently we default to the macro that redefines fdatasync to fsync
3419 */
3420 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003421#else
drh0b647ff2009-03-21 14:41:04 +00003422 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003423#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003424 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003425 rc = fsync(fd);
3426 }
drh0b647ff2009-03-21 14:41:04 +00003427#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003428#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3429
3430 if( OS_VXWORKS && rc!= -1 ){
3431 rc = 0;
3432 }
chw97185482008-11-17 08:05:31 +00003433 return rc;
drhbfe66312006-10-03 17:40:40 +00003434}
3435
drh734c9862008-11-28 15:37:20 +00003436/*
drh0059eae2011-08-08 23:48:40 +00003437** Open a file descriptor to the directory containing file zFilename.
3438** If successful, *pFd is set to the opened file descriptor and
3439** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3440** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3441** value.
3442**
drh90315a22011-08-10 01:52:12 +00003443** The directory file descriptor is used for only one thing - to
3444** fsync() a directory to make sure file creation and deletion events
3445** are flushed to disk. Such fsyncs are not needed on newer
3446** journaling filesystems, but are required on older filesystems.
3447**
3448** This routine can be overridden using the xSetSysCall interface.
3449** The ability to override this routine was added in support of the
3450** chromium sandbox. Opening a directory is a security risk (we are
3451** told) so making it overrideable allows the chromium sandbox to
3452** replace this routine with a harmless no-op. To make this routine
3453** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3454** *pFd set to a negative number.
3455**
drh0059eae2011-08-08 23:48:40 +00003456** If SQLITE_OK is returned, the caller is responsible for closing
3457** the file descriptor *pFd using close().
3458*/
3459static int openDirectory(const char *zFilename, int *pFd){
3460 int ii;
3461 int fd = -1;
3462 char zDirname[MAX_PATHNAME+1];
3463
3464 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3465 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3466 if( ii>0 ){
3467 zDirname[ii] = '\0';
3468 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3469 if( fd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003470 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3471 }
3472 }
3473 *pFd = fd;
drhacb6b282015-11-26 10:37:05 +00003474 if( fd>=0 ) return SQLITE_OK;
3475 return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
drh0059eae2011-08-08 23:48:40 +00003476}
3477
3478/*
drh734c9862008-11-28 15:37:20 +00003479** Make sure all writes to a particular file are committed to disk.
3480**
3481** If dataOnly==0 then both the file itself and its metadata (file
3482** size, access time, etc) are synced. If dataOnly!=0 then only the
3483** file data is synced.
3484**
3485** Under Unix, also make sure that the directory entry for the file
3486** has been created by fsync-ing the directory that contains the file.
3487** If we do not do this and we encounter a power failure, the directory
3488** entry for the journal might not exist after we reboot. The next
3489** SQLite to access the file will not know that the journal exists (because
3490** the directory entry for the journal was never created) and the transaction
3491** will not roll back - possibly leading to database corruption.
3492*/
3493static int unixSync(sqlite3_file *id, int flags){
3494 int rc;
3495 unixFile *pFile = (unixFile*)id;
3496
3497 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3498 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3499
3500 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3501 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3502 || (flags&0x0F)==SQLITE_SYNC_FULL
3503 );
3504
3505 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3506 ** line is to test that doing so does not cause any problems.
3507 */
3508 SimulateDiskfullError( return SQLITE_FULL );
3509
3510 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003511 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003512 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3513 SimulateIOError( rc=1 );
3514 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003515 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003516 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003517 }
drh0059eae2011-08-08 23:48:40 +00003518
3519 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003520 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003521 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003522 */
3523 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3524 int dirfd;
3525 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003526 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003527 rc = osOpenDirectory(pFile->zPath, &dirfd);
drhacb6b282015-11-26 10:37:05 +00003528 if( rc==SQLITE_OK ){
drh0059eae2011-08-08 23:48:40 +00003529 full_fsync(dirfd, 0, 0);
3530 robust_close(pFile, dirfd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00003531 }else{
3532 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00003533 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003534 }
drh0059eae2011-08-08 23:48:40 +00003535 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003536 }
3537 return rc;
3538}
3539
3540/*
3541** Truncate an open file to a specified size
3542*/
3543static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003544 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003545 int rc;
dan6e09d692010-07-27 18:34:15 +00003546 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003547 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003548
3549 /* If the user has configured a chunk-size for this file, truncate the
3550 ** file so that it consists of an integer number of chunks (i.e. the
3551 ** actual file size after the operation may be larger than the requested
3552 ** size).
3553 */
drhb8af4b72012-04-05 20:04:39 +00003554 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003555 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3556 }
3557
dan2ee53412014-09-06 16:49:40 +00003558 rc = robust_ftruncate(pFile->h, nByte);
drh734c9862008-11-28 15:37:20 +00003559 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003560 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003561 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003562 }else{
drhd3d8c042012-05-29 17:02:40 +00003563#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003564 /* If we are doing a normal write to a database file (as opposed to
3565 ** doing a hot-journal rollback or a write to some file other than a
3566 ** normal database file) and we truncate the file to zero length,
3567 ** that effectively updates the change counter. This might happen
3568 ** when restoring a database using the backup API from a zero-length
3569 ** source.
3570 */
dan6e09d692010-07-27 18:34:15 +00003571 if( pFile->inNormalWrite && nByte==0 ){
3572 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003573 }
danf23da962013-03-23 21:00:41 +00003574#endif
danc0003312013-03-22 17:46:11 +00003575
mistachkine98844f2013-08-24 00:59:24 +00003576#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003577 /* If the file was just truncated to a size smaller than the currently
3578 ** mapped region, reduce the effective mapping size as well. SQLite will
3579 ** use read() and write() to access data beyond this point from now on.
3580 */
3581 if( nByte<pFile->mmapSize ){
3582 pFile->mmapSize = nByte;
3583 }
mistachkine98844f2013-08-24 00:59:24 +00003584#endif
drh3313b142009-11-06 04:13:18 +00003585
drh734c9862008-11-28 15:37:20 +00003586 return SQLITE_OK;
3587 }
3588}
3589
3590/*
3591** Determine the current size of a file in bytes
3592*/
3593static int unixFileSize(sqlite3_file *id, i64 *pSize){
3594 int rc;
3595 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003596 assert( id );
3597 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003598 SimulateIOError( rc=1 );
3599 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00003600 storeLastErrno((unixFile*)id, errno);
drh734c9862008-11-28 15:37:20 +00003601 return SQLITE_IOERR_FSTAT;
3602 }
3603 *pSize = buf.st_size;
3604
drh8af6c222010-05-14 12:43:01 +00003605 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003606 ** writes a single byte into that file in order to work around a bug
3607 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3608 ** layers, we need to report this file size as zero even though it is
3609 ** really 1. Ticket #3260.
3610 */
3611 if( *pSize==1 ) *pSize = 0;
3612
3613
3614 return SQLITE_OK;
3615}
3616
drhd2cb50b2009-01-09 21:41:17 +00003617#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003618/*
3619** Handler for proxy-locking file-control verbs. Defined below in the
3620** proxying locking division.
3621*/
3622static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003623#endif
drh715ff302008-12-03 22:32:44 +00003624
dan502019c2010-07-28 14:26:17 +00003625/*
3626** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003627** file-control operation. Enlarge the database to nBytes in size
3628** (rounded up to the next chunk-size). If the database is already
3629** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003630*/
3631static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003632 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003633 i64 nSize; /* Required file size */
3634 struct stat buf; /* Used to hold return values of fstat() */
3635
drh4bf66fd2015-02-19 02:43:02 +00003636 if( osFstat(pFile->h, &buf) ){
3637 return SQLITE_IOERR_FSTAT;
3638 }
dan502019c2010-07-28 14:26:17 +00003639
3640 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3641 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003642
dan502019c2010-07-28 14:26:17 +00003643#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003644 /* The code below is handling the return value of osFallocate()
3645 ** correctly. posix_fallocate() is defined to "returns zero on success,
3646 ** or an error number on failure". See the manpage for details. */
3647 int err;
drhff812312011-02-23 13:33:46 +00003648 do{
dan661d71a2011-03-30 19:08:03 +00003649 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3650 }while( err==EINTR );
3651 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003652#else
dan592bf7f2014-12-30 19:58:31 +00003653 /* If the OS does not have posix_fallocate(), fake it. Write a
3654 ** single byte to the last byte in each block that falls entirely
3655 ** within the extended region. Then, if required, a single byte
3656 ** at offset (nSize-1), to set the size of the file correctly.
3657 ** This is a similar technique to that used by glibc on systems
3658 ** that do not have a real fallocate() call.
dan502019c2010-07-28 14:26:17 +00003659 */
3660 int nBlk = buf.st_blksize; /* File-system block size */
danef3d66c2015-01-06 21:31:47 +00003661 int nWrite = 0; /* Number of bytes written by seekAndWrite */
dan502019c2010-07-28 14:26:17 +00003662 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003663
drh053378d2015-12-01 22:09:42 +00003664 iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
dan592bf7f2014-12-30 19:58:31 +00003665 assert( iWrite>=buf.st_size );
dan592bf7f2014-12-30 19:58:31 +00003666 assert( ((iWrite+1)%nBlk)==0 );
drh053378d2015-12-01 22:09:42 +00003667 for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
3668 if( iWrite>=nSize ) iWrite = nSize - 1;
danef3d66c2015-01-06 21:31:47 +00003669 nWrite = seekAndWrite(pFile, iWrite, "", 1);
dandc5df0f2011-04-06 19:15:45 +00003670 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dandc5df0f2011-04-06 19:15:45 +00003671 }
dan502019c2010-07-28 14:26:17 +00003672#endif
3673 }
3674 }
3675
mistachkine98844f2013-08-24 00:59:24 +00003676#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003677 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003678 int rc;
3679 if( pFile->szChunk<=0 ){
3680 if( robust_ftruncate(pFile->h, nByte) ){
drh4bf66fd2015-02-19 02:43:02 +00003681 storeLastErrno(pFile, errno);
danf23da962013-03-23 21:00:41 +00003682 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3683 }
3684 }
3685
3686 rc = unixMapfile(pFile, nByte);
3687 return rc;
3688 }
mistachkine98844f2013-08-24 00:59:24 +00003689#endif
danf23da962013-03-23 21:00:41 +00003690
dan502019c2010-07-28 14:26:17 +00003691 return SQLITE_OK;
3692}
danielk1977ad94b582007-08-20 06:44:22 +00003693
danielk1977e3026632004-06-22 11:29:02 +00003694/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003695** If *pArg is initially negative then this is a query. Set *pArg to
drhf12b3f62011-12-21 14:42:29 +00003696** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3697**
3698** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3699*/
3700static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3701 if( *pArg<0 ){
3702 *pArg = (pFile->ctrlFlags & mask)!=0;
3703 }else if( (*pArg)==0 ){
3704 pFile->ctrlFlags &= ~mask;
3705 }else{
3706 pFile->ctrlFlags |= mask;
3707 }
3708}
3709
drh696b33e2012-12-06 19:01:42 +00003710/* Forward declaration */
3711static int unixGetTempname(int nBuf, char *zBuf);
3712
drhf12b3f62011-12-21 14:42:29 +00003713/*
drh9e33c2c2007-08-31 18:34:59 +00003714** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003715*/
drhcc6bb3e2007-08-31 16:11:35 +00003716static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003717 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003718 switch( op ){
3719 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003720 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003721 return SQLITE_OK;
3722 }
drh4bf66fd2015-02-19 02:43:02 +00003723 case SQLITE_FCNTL_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003724 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003725 return SQLITE_OK;
3726 }
dan6e09d692010-07-27 18:34:15 +00003727 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003728 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003729 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003730 }
drh9ff27ec2010-05-19 19:26:05 +00003731 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003732 int rc;
3733 SimulateIOErrorBenign(1);
3734 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3735 SimulateIOErrorBenign(0);
3736 return rc;
drhf0b190d2011-07-26 16:03:07 +00003737 }
3738 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003739 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3740 return SQLITE_OK;
3741 }
drhcb15f352011-12-23 01:04:17 +00003742 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3743 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003744 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003745 }
drhde60fc22011-12-14 17:53:36 +00003746 case SQLITE_FCNTL_VFSNAME: {
3747 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3748 return SQLITE_OK;
3749 }
drh696b33e2012-12-06 19:01:42 +00003750 case SQLITE_FCNTL_TEMPFILENAME: {
drhf3cdcdc2015-04-29 16:50:28 +00003751 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
drh696b33e2012-12-06 19:01:42 +00003752 if( zTFile ){
3753 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3754 *(char**)pArg = zTFile;
3755 }
3756 return SQLITE_OK;
3757 }
drhb959a012013-12-07 12:29:22 +00003758 case SQLITE_FCNTL_HAS_MOVED: {
3759 *(int*)pArg = fileHasMoved(pFile);
3760 return SQLITE_OK;
3761 }
mistachkine98844f2013-08-24 00:59:24 +00003762#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003763 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003764 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003765 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003766 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3767 newLimit = sqlite3GlobalConfig.mxMmap;
3768 }
3769 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003770 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003771 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003772 if( pFile->mmapSize>0 ){
3773 unixUnmapfile(pFile);
3774 rc = unixMapfile(pFile, -1);
3775 }
danbcb8a862013-04-08 15:30:41 +00003776 }
drh34e258c2013-05-23 01:40:53 +00003777 return rc;
danb2d3de32013-03-14 18:34:37 +00003778 }
mistachkine98844f2013-08-24 00:59:24 +00003779#endif
drhd3d8c042012-05-29 17:02:40 +00003780#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003781 /* The pager calls this method to signal that it has done
3782 ** a rollback and that the database is therefore unchanged and
3783 ** it hence it is OK for the transaction change counter to be
3784 ** unchanged.
3785 */
3786 case SQLITE_FCNTL_DB_UNCHANGED: {
3787 ((unixFile*)id)->dbUpdate = 0;
3788 return SQLITE_OK;
3789 }
3790#endif
drhd2cb50b2009-01-09 21:41:17 +00003791#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh4bf66fd2015-02-19 02:43:02 +00003792 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
3793 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003794 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003795 }
drhd2cb50b2009-01-09 21:41:17 +00003796#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003797 }
drh0b52b7d2011-01-26 19:46:22 +00003798 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003799}
3800
3801/*
danielk1977a3d4c882007-03-23 10:08:38 +00003802** Return the sector size in bytes of the underlying block device for
3803** the specified file. This is almost always 512 bytes, but may be
3804** larger for some devices.
3805**
3806** SQLite code assumes this function cannot fail. It also assumes that
3807** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003808** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003809** same for both.
3810*/
drh537dddf2012-10-26 13:46:24 +00003811#ifndef __QNXNTO__
3812static int unixSectorSize(sqlite3_file *NotUsed){
3813 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003814 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003815}
drh537dddf2012-10-26 13:46:24 +00003816#endif
3817
3818/*
3819** The following version of unixSectorSize() is optimized for QNX.
3820*/
3821#ifdef __QNXNTO__
3822#include <sys/dcmd_blk.h>
3823#include <sys/statvfs.h>
3824static int unixSectorSize(sqlite3_file *id){
3825 unixFile *pFile = (unixFile*)id;
3826 if( pFile->sectorSize == 0 ){
3827 struct statvfs fsInfo;
3828
3829 /* Set defaults for non-supported filesystems */
3830 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3831 pFile->deviceCharacteristics = 0;
3832 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3833 return pFile->sectorSize;
3834 }
3835
3836 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3837 pFile->sectorSize = fsInfo.f_bsize;
3838 pFile->deviceCharacteristics =
3839 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3840 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3841 ** the write succeeds */
3842 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3843 ** so it is ordered */
3844 0;
3845 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3846 pFile->sectorSize = fsInfo.f_bsize;
3847 pFile->deviceCharacteristics =
3848 /* etfs cluster size writes are atomic */
3849 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3850 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3851 ** the write succeeds */
3852 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3853 ** so it is ordered */
3854 0;
3855 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3856 pFile->sectorSize = fsInfo.f_bsize;
3857 pFile->deviceCharacteristics =
3858 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3859 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3860 ** the write succeeds */
3861 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3862 ** so it is ordered */
3863 0;
3864 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3865 pFile->sectorSize = fsInfo.f_bsize;
3866 pFile->deviceCharacteristics =
3867 /* full bitset of atomics from max sector size and smaller */
3868 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3869 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3870 ** so it is ordered */
3871 0;
3872 }else if( strstr(fsInfo.f_basetype, "dos") ){
3873 pFile->sectorSize = fsInfo.f_bsize;
3874 pFile->deviceCharacteristics =
3875 /* full bitset of atomics from max sector size and smaller */
3876 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3877 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3878 ** so it is ordered */
3879 0;
3880 }else{
3881 pFile->deviceCharacteristics =
3882 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3883 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3884 ** the write succeeds */
3885 0;
3886 }
3887 }
3888 /* Last chance verification. If the sector size isn't a multiple of 512
3889 ** then it isn't valid.*/
3890 if( pFile->sectorSize % 512 != 0 ){
3891 pFile->deviceCharacteristics = 0;
3892 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3893 }
3894 return pFile->sectorSize;
3895}
3896#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003897
danielk197790949c22007-08-17 16:50:38 +00003898/*
drhf12b3f62011-12-21 14:42:29 +00003899** Return the device characteristics for the file.
3900**
drhcb15f352011-12-23 01:04:17 +00003901** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
peter.d.reid60ec9142014-09-06 16:39:46 +00003902** However, that choice is controversial since technically the underlying
drhcb15f352011-12-23 01:04:17 +00003903** file system does not always provide powersafe overwrites. (In other
3904** words, after a power-loss event, parts of the file that were never
3905** written might end up being altered.) However, non-PSOW behavior is very,
3906** very rare. And asserting PSOW makes a large reduction in the amount
3907** of required I/O for journaling, since a lot of padding is eliminated.
3908** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3909** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003910*/
drhf12b3f62011-12-21 14:42:29 +00003911static int unixDeviceCharacteristics(sqlite3_file *id){
3912 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003913 int rc = 0;
3914#ifdef __QNXNTO__
3915 if( p->sectorSize==0 ) unixSectorSize(id);
3916 rc = p->deviceCharacteristics;
3917#endif
drhcb15f352011-12-23 01:04:17 +00003918 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003919 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003920 }
drh537dddf2012-10-26 13:46:24 +00003921 return rc;
danielk197762079062007-08-15 17:08:46 +00003922}
3923
dan702eec12014-06-23 10:04:58 +00003924#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00003925
dan702eec12014-06-23 10:04:58 +00003926/*
3927** Return the system page size.
3928**
3929** This function should not be called directly by other code in this file.
3930** Instead, it should be called via macro osGetpagesize().
3931*/
3932static int unixGetpagesize(void){
drh8cd5b252015-03-02 22:06:43 +00003933#if OS_VXWORKS
3934 return 1024;
3935#elif defined(_BSD_SOURCE)
dan702eec12014-06-23 10:04:58 +00003936 return getpagesize();
3937#else
3938 return (int)sysconf(_SC_PAGESIZE);
3939#endif
3940}
3941
3942#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
3943
3944#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00003945
3946/*
drhd91c68f2010-05-14 14:52:25 +00003947** Object used to represent an shared memory buffer.
3948**
3949** When multiple threads all reference the same wal-index, each thread
3950** has its own unixShm object, but they all point to a single instance
3951** of this unixShmNode object. In other words, each wal-index is opened
3952** only once per process.
3953**
3954** Each unixShmNode object is connected to a single unixInodeInfo object.
3955** We could coalesce this object into unixInodeInfo, but that would mean
3956** every open file that does not use shared memory (in other words, most
3957** open files) would have to carry around this extra information. So
3958** the unixInodeInfo object contains a pointer to this unixShmNode object
3959** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003960**
3961** unixMutexHeld() must be true when creating or destroying
3962** this object or while reading or writing the following fields:
3963**
3964** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003965**
3966** The following fields are read-only after the object is created:
3967**
3968** fid
3969** zFilename
3970**
drhd91c68f2010-05-14 14:52:25 +00003971** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003972** unixMutexHeld() is true when reading or writing any other field
3973** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003974*/
drhd91c68f2010-05-14 14:52:25 +00003975struct unixShmNode {
3976 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003977 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003978 char *zFilename; /* Name of the mmapped file */
3979 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003980 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003981 u16 nRegion; /* Size of array apRegion */
3982 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003983 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003984 int nRef; /* Number of unixShm objects pointing to this */
3985 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003986#ifdef SQLITE_DEBUG
3987 u8 exclMask; /* Mask of exclusive locks held */
3988 u8 sharedMask; /* Mask of shared locks held */
3989 u8 nextShmId; /* Next available unixShm.id value */
3990#endif
3991};
3992
3993/*
drhd9e5c4f2010-05-12 18:01:39 +00003994** Structure used internally by this VFS to record the state of an
3995** open shared memory connection.
3996**
drhd91c68f2010-05-14 14:52:25 +00003997** The following fields are initialized when this object is created and
3998** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003999**
drhd91c68f2010-05-14 14:52:25 +00004000** unixShm.pFile
4001** unixShm.id
4002**
4003** All other fields are read/write. The unixShm.pFile->mutex must be held
4004** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004005*/
4006struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004007 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4008 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004009 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004010 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004011 u16 sharedMask; /* Mask of shared locks held */
4012 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004013};
4014
4015/*
drhd9e5c4f2010-05-12 18:01:39 +00004016** Constants used for locking
4017*/
drhbd9676c2010-06-23 17:58:38 +00004018#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004019#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004020
drhd9e5c4f2010-05-12 18:01:39 +00004021/*
drh73b64e42010-05-30 19:55:15 +00004022** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004023**
4024** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4025** otherwise.
4026*/
4027static int unixShmSystemLock(
drhbbf76ee2015-03-10 20:22:35 +00004028 unixFile *pFile, /* Open connection to the WAL file */
drhd91c68f2010-05-14 14:52:25 +00004029 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004030 int ofst, /* First byte of the locking range */
4031 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004032){
drhbbf76ee2015-03-10 20:22:35 +00004033 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4034 struct flock f; /* The posix advisory locking structure */
4035 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004036
drhd91c68f2010-05-14 14:52:25 +00004037 /* Access to the unixShmNode object is serialized by the caller */
drhbbf76ee2015-03-10 20:22:35 +00004038 pShmNode = pFile->pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004039 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004040
drh73b64e42010-05-30 19:55:15 +00004041 /* Shared locks never span more than one byte */
4042 assert( n==1 || lockType!=F_RDLCK );
4043
4044 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00004045 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004046
drh3cb93392011-03-12 18:10:44 +00004047 if( pShmNode->h>=0 ){
4048 /* Initialize the locking parameters */
4049 memset(&f, 0, sizeof(f));
4050 f.l_type = lockType;
4051 f.l_whence = SEEK_SET;
4052 f.l_start = ofst;
4053 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004054
drhdcfb9652015-12-02 00:05:26 +00004055 rc = osFcntl(pShmNode->h, F_SETLK, &f);
drh3cb93392011-03-12 18:10:44 +00004056 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4057 }
drhd9e5c4f2010-05-12 18:01:39 +00004058
4059 /* Update the global lock state and do debug tracing */
4060#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004061 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004062 OSTRACE(("SHM-LOCK "));
drh693e6712014-01-24 22:58:00 +00004063 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004064 if( rc==SQLITE_OK ){
4065 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004066 OSTRACE(("unlock %d ok", ofst));
4067 pShmNode->exclMask &= ~mask;
4068 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004069 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004070 OSTRACE(("read-lock %d ok", ofst));
4071 pShmNode->exclMask &= ~mask;
4072 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004073 }else{
4074 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004075 OSTRACE(("write-lock %d ok", ofst));
4076 pShmNode->exclMask |= mask;
4077 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004078 }
4079 }else{
4080 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004081 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004082 }else if( lockType==F_RDLCK ){
4083 OSTRACE(("read-lock failed"));
4084 }else{
4085 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004086 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004087 }
4088 }
drh20e1f082010-05-31 16:10:12 +00004089 OSTRACE((" - afterwards %03x,%03x\n",
4090 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004091 }
drhd9e5c4f2010-05-12 18:01:39 +00004092#endif
4093
4094 return rc;
4095}
4096
dan781e34c2014-03-20 08:59:47 +00004097/*
dan781e34c2014-03-20 08:59:47 +00004098** Return the minimum number of 32KB shm regions that should be mapped at
4099** a time, assuming that each mapping must be an integer multiple of the
4100** current system page-size.
4101**
4102** Usually, this is 1. The exception seems to be systems that are configured
4103** to use 64KB pages - in this case each mapping must cover at least two
4104** shm regions.
4105*/
4106static int unixShmRegionPerMap(void){
4107 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004108 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004109 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4110 if( pgsz<shmsz ) return 1;
4111 return pgsz/shmsz;
4112}
drhd9e5c4f2010-05-12 18:01:39 +00004113
4114/*
drhd91c68f2010-05-14 14:52:25 +00004115** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004116**
4117** This is not a VFS shared-memory method; it is a utility function called
4118** by VFS shared-memory methods.
4119*/
drhd91c68f2010-05-14 14:52:25 +00004120static void unixShmPurge(unixFile *pFd){
4121 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004122 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00004123 if( p && p->nRef==0 ){
dan781e34c2014-03-20 08:59:47 +00004124 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004125 int i;
drhd91c68f2010-05-14 14:52:25 +00004126 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004127 sqlite3_mutex_free(p->mutex);
dan781e34c2014-03-20 08:59:47 +00004128 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh3cb93392011-03-12 18:10:44 +00004129 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004130 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004131 }else{
4132 sqlite3_free(p->apRegion[i]);
4133 }
dan13a3cb82010-06-11 19:04:21 +00004134 }
dan18801912010-06-14 14:07:50 +00004135 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004136 if( p->h>=0 ){
4137 robust_close(pFd, p->h, __LINE__);
4138 p->h = -1;
4139 }
drhd91c68f2010-05-14 14:52:25 +00004140 p->pInode->pShmNode = 0;
4141 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004142 }
4143}
4144
4145/*
danda9fe0c2010-07-13 18:44:03 +00004146** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004147** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004148**
drh7234c6d2010-06-19 15:10:09 +00004149** The file used to implement shared-memory is in the same directory
4150** as the open database file and has the same name as the open database
4151** file with the "-shm" suffix added. For example, if the database file
4152** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004153** for shared memory will be called "/home/user1/config.db-shm".
4154**
4155** Another approach to is to use files in /dev/shm or /dev/tmp or an
4156** some other tmpfs mount. But if a file in a different directory
4157** from the database file is used, then differing access permissions
4158** or a chroot() might cause two different processes on the same
4159** database to end up using different files for shared memory -
4160** meaning that their memory would not really be shared - resulting
4161** in database corruption. Nevertheless, this tmpfs file usage
4162** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4163** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4164** option results in an incompatible build of SQLite; builds of SQLite
4165** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4166** same database file at the same time, database corruption will likely
4167** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4168** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004169**
4170** When opening a new shared-memory file, if no other instances of that
4171** file are currently open, in this process or in other processes, then
4172** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004173**
4174** If the original database file (pDbFd) is using the "unix-excl" VFS
4175** that means that an exclusive lock is held on the database file and
4176** that no other processes are able to read or write the database. In
4177** that case, we do not really need shared memory. No shared memory
4178** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004179*/
danda9fe0c2010-07-13 18:44:03 +00004180static int unixOpenSharedMemory(unixFile *pDbFd){
4181 struct unixShm *p = 0; /* The connection to be opened */
4182 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4183 int rc; /* Result code */
4184 unixInodeInfo *pInode; /* The inode of fd */
4185 char *zShmFilename; /* Name of the file used for SHM */
4186 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004187
danda9fe0c2010-07-13 18:44:03 +00004188 /* Allocate space for the new unixShm object. */
drhf3cdcdc2015-04-29 16:50:28 +00004189 p = sqlite3_malloc64( sizeof(*p) );
drhd9e5c4f2010-05-12 18:01:39 +00004190 if( p==0 ) return SQLITE_NOMEM;
4191 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004192 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004193
danda9fe0c2010-07-13 18:44:03 +00004194 /* Check to see if a unixShmNode object already exists. Reuse an existing
4195 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004196 */
4197 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004198 pInode = pDbFd->pInode;
4199 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004200 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004201 struct stat sStat; /* fstat() info for database file */
drh4bf66fd2015-02-19 02:43:02 +00004202#ifndef SQLITE_SHM_DIRECTORY
4203 const char *zBasePath = pDbFd->zPath;
4204#endif
danddb0ac42010-07-14 14:48:58 +00004205
4206 /* Call fstat() to figure out the permissions on the database file. If
4207 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004208 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004209 */
drh3cb93392011-03-12 18:10:44 +00004210 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00004211 rc = SQLITE_IOERR_FSTAT;
4212 goto shm_open_err;
4213 }
4214
drha4ced192010-07-15 18:32:40 +00004215#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004216 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004217#else
drh4bf66fd2015-02-19 02:43:02 +00004218 nShmFilename = 6 + (int)strlen(zBasePath);
drha4ced192010-07-15 18:32:40 +00004219#endif
drhf3cdcdc2015-04-29 16:50:28 +00004220 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004221 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004222 rc = SQLITE_NOMEM;
4223 goto shm_open_err;
4224 }
drh9cb5a0d2012-01-05 21:19:54 +00004225 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004226 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004227#ifdef SQLITE_SHM_DIRECTORY
4228 sqlite3_snprintf(nShmFilename, zShmFilename,
4229 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4230 (u32)sStat.st_ino, (u32)sStat.st_dev);
4231#else
drh4bf66fd2015-02-19 02:43:02 +00004232 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
drh81cc5162011-05-17 20:36:21 +00004233 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004234#endif
drhd91c68f2010-05-14 14:52:25 +00004235 pShmNode->h = -1;
4236 pDbFd->pInode->pShmNode = pShmNode;
4237 pShmNode->pInode = pDbFd->pInode;
4238 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4239 if( pShmNode->mutex==0 ){
4240 rc = SQLITE_NOMEM;
4241 goto shm_open_err;
4242 }
drhd9e5c4f2010-05-12 18:01:39 +00004243
drh3cb93392011-03-12 18:10:44 +00004244 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004245 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004246 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004247 openFlags = O_RDONLY;
4248 pShmNode->isReadonly = 1;
4249 }
4250 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004251 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004252 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4253 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004254 }
drhac7c3ac2012-02-11 19:23:48 +00004255
4256 /* If this process is running as root, make sure that the SHM file
4257 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004258 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004259 */
drh6226ca22015-11-24 15:06:28 +00004260 robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004261
4262 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004263 ** If not, truncate the file to zero length.
4264 */
4265 rc = SQLITE_OK;
drhbbf76ee2015-03-10 20:22:35 +00004266 if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
drh66dfec8b2011-06-01 20:01:49 +00004267 if( robust_ftruncate(pShmNode->h, 0) ){
4268 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004269 }
4270 }
drh66dfec8b2011-06-01 20:01:49 +00004271 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004272 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
drh66dfec8b2011-06-01 20:01:49 +00004273 }
4274 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004275 }
drhd9e5c4f2010-05-12 18:01:39 +00004276 }
4277
drhd91c68f2010-05-14 14:52:25 +00004278 /* Make the new connection a child of the unixShmNode */
4279 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004280#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004281 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004282#endif
drhd91c68f2010-05-14 14:52:25 +00004283 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004284 pDbFd->pShm = p;
4285 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004286
4287 /* The reference count on pShmNode has already been incremented under
4288 ** the cover of the unixEnterMutex() mutex and the pointer from the
4289 ** new (struct unixShm) object to the pShmNode has been set. All that is
4290 ** left to do is to link the new object into the linked list starting
4291 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4292 ** mutex.
4293 */
4294 sqlite3_mutex_enter(pShmNode->mutex);
4295 p->pNext = pShmNode->pFirst;
4296 pShmNode->pFirst = p;
4297 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004298 return SQLITE_OK;
4299
4300 /* Jump here on any error */
4301shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004302 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004303 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004304 unixLeaveMutex();
4305 return rc;
4306}
4307
4308/*
danda9fe0c2010-07-13 18:44:03 +00004309** This function is called to obtain a pointer to region iRegion of the
4310** shared-memory associated with the database file fd. Shared-memory regions
4311** are numbered starting from zero. Each shared-memory region is szRegion
4312** bytes in size.
4313**
4314** If an error occurs, an error code is returned and *pp is set to NULL.
4315**
4316** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4317** region has not been allocated (by any client, including one running in a
4318** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4319** bExtend is non-zero and the requested shared-memory region has not yet
4320** been allocated, it is allocated by this function.
4321**
4322** If the shared-memory region has already been allocated or is allocated by
4323** this call as described above, then it is mapped into this processes
4324** address space (if it is not already), *pp is set to point to the mapped
4325** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004326*/
danda9fe0c2010-07-13 18:44:03 +00004327static int unixShmMap(
4328 sqlite3_file *fd, /* Handle open on database file */
4329 int iRegion, /* Region to retrieve */
4330 int szRegion, /* Size of regions */
4331 int bExtend, /* True to extend file if necessary */
4332 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004333){
danda9fe0c2010-07-13 18:44:03 +00004334 unixFile *pDbFd = (unixFile*)fd;
4335 unixShm *p;
4336 unixShmNode *pShmNode;
4337 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004338 int nShmPerMap = unixShmRegionPerMap();
4339 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004340
danda9fe0c2010-07-13 18:44:03 +00004341 /* If the shared-memory file has not yet been opened, open it now. */
4342 if( pDbFd->pShm==0 ){
4343 rc = unixOpenSharedMemory(pDbFd);
4344 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004345 }
drhd9e5c4f2010-05-12 18:01:39 +00004346
danda9fe0c2010-07-13 18:44:03 +00004347 p = pDbFd->pShm;
4348 pShmNode = p->pShmNode;
4349 sqlite3_mutex_enter(pShmNode->mutex);
4350 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004351 assert( pShmNode->pInode==pDbFd->pInode );
4352 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4353 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004354
dan781e34c2014-03-20 08:59:47 +00004355 /* Minimum number of regions required to be mapped. */
4356 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4357
4358 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004359 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004360 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004361 struct stat sStat; /* Used by fstat() */
4362
4363 pShmNode->szRegion = szRegion;
4364
drh3cb93392011-03-12 18:10:44 +00004365 if( pShmNode->h>=0 ){
4366 /* The requested region is not mapped into this processes address space.
4367 ** Check to see if it has been allocated (i.e. if the wal-index file is
4368 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004369 */
drh3cb93392011-03-12 18:10:44 +00004370 if( osFstat(pShmNode->h, &sStat) ){
4371 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004372 goto shmpage_out;
4373 }
drh3cb93392011-03-12 18:10:44 +00004374
4375 if( sStat.st_size<nByte ){
4376 /* The requested memory region does not exist. If bExtend is set to
4377 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004378 */
dan47a2b4a2013-04-26 16:09:29 +00004379 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004380 goto shmpage_out;
4381 }
dan47a2b4a2013-04-26 16:09:29 +00004382
4383 /* Alternatively, if bExtend is true, extend the file. Do this by
4384 ** writing a single byte to the end of each (OS) page being
4385 ** allocated or extended. Technically, we need only write to the
4386 ** last page in order to extend the file. But writing to all new
4387 ** pages forces the OS to allocate them immediately, which reduces
4388 ** the chances of SIGBUS while accessing the mapped region later on.
4389 */
4390 else{
4391 static const int pgsz = 4096;
4392 int iPg;
4393
4394 /* Write to the last byte of each newly allocated or extended page */
4395 assert( (nByte % pgsz)==0 );
4396 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
drhe1818ec2015-12-01 16:21:35 +00004397 int x = 0;
4398 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
dan47a2b4a2013-04-26 16:09:29 +00004399 const char *zFile = pShmNode->zFilename;
4400 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4401 goto shmpage_out;
4402 }
4403 }
drh3cb93392011-03-12 18:10:44 +00004404 }
4405 }
danda9fe0c2010-07-13 18:44:03 +00004406 }
4407
4408 /* Map the requested memory region into this processes address space. */
4409 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004410 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004411 );
4412 if( !apNew ){
4413 rc = SQLITE_IOERR_NOMEM;
4414 goto shmpage_out;
4415 }
4416 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004417 while( pShmNode->nRegion<nReqRegion ){
4418 int nMap = szRegion*nShmPerMap;
4419 int i;
drh3cb93392011-03-12 18:10:44 +00004420 void *pMem;
4421 if( pShmNode->h>=0 ){
dan781e34c2014-03-20 08:59:47 +00004422 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004423 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004424 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004425 );
4426 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004427 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004428 goto shmpage_out;
4429 }
4430 }else{
drhf3cdcdc2015-04-29 16:50:28 +00004431 pMem = sqlite3_malloc64(szRegion);
drh3cb93392011-03-12 18:10:44 +00004432 if( pMem==0 ){
4433 rc = SQLITE_NOMEM;
4434 goto shmpage_out;
4435 }
4436 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004437 }
dan781e34c2014-03-20 08:59:47 +00004438
4439 for(i=0; i<nShmPerMap; i++){
4440 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4441 }
4442 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004443 }
4444 }
4445
4446shmpage_out:
4447 if( pShmNode->nRegion>iRegion ){
4448 *pp = pShmNode->apRegion[iRegion];
4449 }else{
4450 *pp = 0;
4451 }
drh66dfec8b2011-06-01 20:01:49 +00004452 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004453 sqlite3_mutex_leave(pShmNode->mutex);
4454 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004455}
4456
4457/*
drhd9e5c4f2010-05-12 18:01:39 +00004458** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004459**
4460** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4461** different here than in posix. In xShmLock(), one can go from unlocked
4462** to shared and back or from unlocked to exclusive and back. But one may
4463** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004464*/
4465static int unixShmLock(
4466 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004467 int ofst, /* First lock to acquire or release */
4468 int n, /* Number of locks to acquire or release */
4469 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004470){
drh73b64e42010-05-30 19:55:15 +00004471 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4472 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4473 unixShm *pX; /* For looping over all siblings */
4474 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4475 int rc = SQLITE_OK; /* Result code */
4476 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004477
drhd91c68f2010-05-14 14:52:25 +00004478 assert( pShmNode==pDbFd->pInode->pShmNode );
4479 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004480 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004481 assert( n>=1 );
4482 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4483 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4484 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4485 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4486 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004487 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4488 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004489
drhc99597c2010-05-31 01:41:15 +00004490 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004491 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004492 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004493 if( flags & SQLITE_SHM_UNLOCK ){
4494 u16 allMask = 0; /* Mask of locks held by siblings */
4495
4496 /* See if any siblings hold this same lock */
4497 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4498 if( pX==p ) continue;
4499 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4500 allMask |= pX->sharedMask;
4501 }
4502
4503 /* Unlock the system-level locks */
4504 if( (mask & allMask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004505 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004506 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004507 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004508 }
drh73b64e42010-05-30 19:55:15 +00004509
4510 /* Undo the local locks */
4511 if( rc==SQLITE_OK ){
4512 p->exclMask &= ~mask;
4513 p->sharedMask &= ~mask;
4514 }
4515 }else if( flags & SQLITE_SHM_SHARED ){
4516 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4517
4518 /* Find out which shared locks are already held by sibling connections.
4519 ** If any sibling already holds an exclusive lock, go ahead and return
4520 ** SQLITE_BUSY.
4521 */
4522 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004523 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004524 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004525 break;
4526 }
4527 allShared |= pX->sharedMask;
4528 }
4529
4530 /* Get shared locks at the system level, if necessary */
4531 if( rc==SQLITE_OK ){
4532 if( (allShared & mask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004533 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004534 }else{
drh73b64e42010-05-30 19:55:15 +00004535 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004536 }
drhd9e5c4f2010-05-12 18:01:39 +00004537 }
drh73b64e42010-05-30 19:55:15 +00004538
4539 /* Get the local shared locks */
4540 if( rc==SQLITE_OK ){
4541 p->sharedMask |= mask;
4542 }
4543 }else{
4544 /* Make sure no sibling connections hold locks that will block this
4545 ** lock. If any do, return SQLITE_BUSY right away.
4546 */
4547 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004548 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4549 rc = SQLITE_BUSY;
4550 break;
4551 }
4552 }
4553
4554 /* Get the exclusive locks at the system level. Then if successful
4555 ** also mark the local connection as being locked.
4556 */
4557 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004558 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004559 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004560 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004561 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004562 }
drhd9e5c4f2010-05-12 18:01:39 +00004563 }
4564 }
drhd91c68f2010-05-14 14:52:25 +00004565 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004566 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
drh5ac93652015-03-21 20:59:43 +00004567 p->id, osGetpid(0), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004568 return rc;
4569}
4570
drh286a2882010-05-20 23:51:06 +00004571/*
4572** Implement a memory barrier or memory fence on shared memory.
4573**
4574** All loads and stores begun before the barrier must complete before
4575** any load or store begun after the barrier.
4576*/
4577static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004578 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004579){
drhff828942010-06-26 21:34:06 +00004580 UNUSED_PARAMETER(fd);
drh22c733d2015-09-24 12:40:43 +00004581 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
4582 unixEnterMutex(); /* Also mutex, for redundancy */
drhb29ad852010-06-01 00:03:57 +00004583 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004584}
4585
dan18801912010-06-14 14:07:50 +00004586/*
danda9fe0c2010-07-13 18:44:03 +00004587** Close a connection to shared-memory. Delete the underlying
4588** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004589**
4590** If there is no shared memory associated with the connection then this
4591** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004592*/
danda9fe0c2010-07-13 18:44:03 +00004593static int unixShmUnmap(
4594 sqlite3_file *fd, /* The underlying database file */
4595 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004596){
danda9fe0c2010-07-13 18:44:03 +00004597 unixShm *p; /* The connection to be closed */
4598 unixShmNode *pShmNode; /* The underlying shared-memory file */
4599 unixShm **pp; /* For looping over sibling connections */
4600 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004601
danda9fe0c2010-07-13 18:44:03 +00004602 pDbFd = (unixFile*)fd;
4603 p = pDbFd->pShm;
4604 if( p==0 ) return SQLITE_OK;
4605 pShmNode = p->pShmNode;
4606
4607 assert( pShmNode==pDbFd->pInode->pShmNode );
4608 assert( pShmNode->pInode==pDbFd->pInode );
4609
4610 /* Remove connection p from the set of connections associated
4611 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004612 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004613 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4614 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004615
danda9fe0c2010-07-13 18:44:03 +00004616 /* Free the connection p */
4617 sqlite3_free(p);
4618 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004619 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004620
4621 /* If pShmNode->nRef has reached 0, then close the underlying
4622 ** shared-memory file, too */
4623 unixEnterMutex();
4624 assert( pShmNode->nRef>0 );
4625 pShmNode->nRef--;
4626 if( pShmNode->nRef==0 ){
drh4bf66fd2015-02-19 02:43:02 +00004627 if( deleteFlag && pShmNode->h>=0 ){
4628 osUnlink(pShmNode->zFilename);
4629 }
danda9fe0c2010-07-13 18:44:03 +00004630 unixShmPurge(pDbFd);
4631 }
4632 unixLeaveMutex();
4633
4634 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004635}
drh286a2882010-05-20 23:51:06 +00004636
danda9fe0c2010-07-13 18:44:03 +00004637
drhd9e5c4f2010-05-12 18:01:39 +00004638#else
drh6b017cc2010-06-14 18:01:46 +00004639# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004640# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004641# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004642# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004643#endif /* #ifndef SQLITE_OMIT_WAL */
4644
mistachkine98844f2013-08-24 00:59:24 +00004645#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004646/*
danaef49d72013-03-25 16:28:54 +00004647** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004648*/
danf23da962013-03-23 21:00:41 +00004649static void unixUnmapfile(unixFile *pFd){
4650 assert( pFd->nFetchOut==0 );
4651 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004652 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004653 pFd->pMapRegion = 0;
4654 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004655 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004656 }
4657}
dan5d8a1372013-03-19 19:28:06 +00004658
danaef49d72013-03-25 16:28:54 +00004659/*
dane6ecd662013-04-01 17:56:59 +00004660** Attempt to set the size of the memory mapping maintained by file
4661** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4662**
4663** If successful, this function sets the following variables:
4664**
4665** unixFile.pMapRegion
4666** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004667** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004668**
4669** If unsuccessful, an error message is logged via sqlite3_log() and
4670** the three variables above are zeroed. In this case SQLite should
4671** continue accessing the database using the xRead() and xWrite()
4672** methods.
4673*/
4674static void unixRemapfile(
4675 unixFile *pFd, /* File descriptor object */
4676 i64 nNew /* Required mapping size */
4677){
dan4ff7bc42013-04-02 12:04:09 +00004678 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004679 int h = pFd->h; /* File descriptor open on db file */
4680 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004681 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004682 u8 *pNew = 0; /* Location of new mapping */
4683 int flags = PROT_READ; /* Flags to pass to mmap() */
4684
4685 assert( pFd->nFetchOut==0 );
4686 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004687 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004688 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004689 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004690 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004691
danfe33e392015-11-17 20:56:06 +00004692#ifdef SQLITE_MMAP_READWRITE
dane6ecd662013-04-01 17:56:59 +00004693 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
danfe33e392015-11-17 20:56:06 +00004694#endif
dane6ecd662013-04-01 17:56:59 +00004695
4696 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00004697#if HAVE_MREMAP
4698 i64 nReuse = pFd->mmapSize;
4699#else
danbc760632014-03-20 09:42:09 +00004700 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00004701 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00004702#endif
dane6ecd662013-04-01 17:56:59 +00004703 u8 *pReq = &pOrig[nReuse];
4704
4705 /* Unmap any pages of the existing mapping that cannot be reused. */
4706 if( nReuse!=nOrig ){
4707 osMunmap(pReq, nOrig-nReuse);
4708 }
4709
4710#if HAVE_MREMAP
4711 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004712 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004713#else
4714 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4715 if( pNew!=MAP_FAILED ){
4716 if( pNew!=pReq ){
4717 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004718 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004719 }else{
4720 pNew = pOrig;
4721 }
4722 }
4723#endif
4724
dan48ccef82013-04-02 20:55:01 +00004725 /* The attempt to extend the existing mapping failed. Free it. */
4726 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004727 osMunmap(pOrig, nReuse);
4728 }
4729 }
4730
4731 /* If pNew is still NULL, try to create an entirely new mapping. */
4732 if( pNew==0 ){
4733 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004734 }
4735
dan4ff7bc42013-04-02 12:04:09 +00004736 if( pNew==MAP_FAILED ){
4737 pNew = 0;
4738 nNew = 0;
4739 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4740
4741 /* If the mmap() above failed, assume that all subsequent mmap() calls
4742 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4743 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004744 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004745 }
dane6ecd662013-04-01 17:56:59 +00004746 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004747 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004748}
4749
4750/*
danaef49d72013-03-25 16:28:54 +00004751** Memory map or remap the file opened by file-descriptor pFd (if the file
4752** is already mapped, the existing mapping is replaced by the new). Or, if
4753** there already exists a mapping for this file, and there are still
4754** outstanding xFetch() references to it, this function is a no-op.
4755**
4756** If parameter nByte is non-negative, then it is the requested size of
4757** the mapping to create. Otherwise, if nByte is less than zero, then the
4758** requested size is the size of the file on disk. The actual size of the
4759** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004760** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004761**
4762** SQLITE_OK is returned if no error occurs (even if the mapping is not
4763** recreated as a result of outstanding references) or an SQLite error
4764** code otherwise.
4765*/
danf23da962013-03-23 21:00:41 +00004766static int unixMapfile(unixFile *pFd, i64 nByte){
4767 i64 nMap = nByte;
4768 int rc;
daneb97b292013-03-20 14:26:59 +00004769
danf23da962013-03-23 21:00:41 +00004770 assert( nMap>=0 || pFd->nFetchOut==0 );
4771 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4772
4773 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00004774 struct stat statbuf; /* Low-level file information */
4775 rc = osFstat(pFd->h, &statbuf);
danf23da962013-03-23 21:00:41 +00004776 if( rc!=SQLITE_OK ){
4777 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
danf23da962013-03-23 21:00:41 +00004785 if( nMap!=pFd->mmapSize ){
dane6ecd662013-04-01 17:56:59 +00004786 if( nMap>0 ){
4787 unixRemapfile(pFd, nMap);
4788 }else{
danb7e3a322013-03-25 20:30:13 +00004789 unixUnmapfile(pFd);
dan5d8a1372013-03-19 19:28:06 +00004790 }
4791 }
4792
danf23da962013-03-23 21:00:41 +00004793 return SQLITE_OK;
4794}
mistachkine98844f2013-08-24 00:59:24 +00004795#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004796
danaef49d72013-03-25 16:28:54 +00004797/*
4798** If possible, return a pointer to a mapping of file fd starting at offset
4799** iOff. The mapping must be valid for at least nAmt bytes.
4800**
4801** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4802** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4803** Finally, if an error does occur, return an SQLite error code. The final
4804** value of *pp is undefined in this case.
4805**
4806** If this function does return a pointer, the caller must eventually
4807** release the reference by calling unixUnfetch().
4808*/
danf23da962013-03-23 21:00:41 +00004809static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004810#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004811 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004812#endif
danf23da962013-03-23 21:00:41 +00004813 *pp = 0;
4814
drh9b4c59f2013-04-15 17:03:42 +00004815#if SQLITE_MAX_MMAP_SIZE>0
4816 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004817 if( pFd->pMapRegion==0 ){
4818 int rc = unixMapfile(pFd, -1);
4819 if( rc!=SQLITE_OK ) return rc;
4820 }
4821 if( pFd->mmapSize >= iOff+nAmt ){
4822 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4823 pFd->nFetchOut++;
4824 }
4825 }
drh6e0b6d52013-04-09 16:19:20 +00004826#endif
danf23da962013-03-23 21:00:41 +00004827 return SQLITE_OK;
4828}
4829
danaef49d72013-03-25 16:28:54 +00004830/*
dandf737fe2013-03-25 17:00:24 +00004831** If the third argument is non-NULL, then this function releases a
4832** reference obtained by an earlier call to unixFetch(). The second
4833** argument passed to this function must be the same as the corresponding
4834** argument that was passed to the unixFetch() invocation.
4835**
4836** Or, if the third argument is NULL, then this function is being called
4837** to inform the VFS layer that, according to POSIX, any existing mapping
4838** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004839*/
dandf737fe2013-03-25 17:00:24 +00004840static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00004841#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00004842 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00004843 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00004844
danaef49d72013-03-25 16:28:54 +00004845 /* If p==0 (unmap the entire file) then there must be no outstanding
4846 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4847 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004848 assert( (p==0)==(pFd->nFetchOut==0) );
4849
dandf737fe2013-03-25 17:00:24 +00004850 /* If p!=0, it must match the iOff value. */
4851 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4852
danf23da962013-03-23 21:00:41 +00004853 if( p ){
4854 pFd->nFetchOut--;
4855 }else{
4856 unixUnmapfile(pFd);
4857 }
4858
4859 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00004860#else
4861 UNUSED_PARAMETER(fd);
4862 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00004863 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00004864#endif
danf23da962013-03-23 21:00:41 +00004865 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004866}
4867
4868/*
drh734c9862008-11-28 15:37:20 +00004869** Here ends the implementation of all sqlite3_file methods.
4870**
4871********************** End sqlite3_file Methods *******************************
4872******************************************************************************/
4873
4874/*
drh6b9d6dd2008-12-03 19:34:47 +00004875** This division contains definitions of sqlite3_io_methods objects that
4876** implement various file locking strategies. It also contains definitions
4877** of "finder" functions. A finder-function is used to locate the appropriate
4878** sqlite3_io_methods object for a particular database file. The pAppData
4879** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4880** the correct finder-function for that VFS.
4881**
4882** Most finder functions return a pointer to a fixed sqlite3_io_methods
4883** object. The only interesting finder-function is autolockIoFinder, which
4884** looks at the filesystem type and tries to guess the best locking
4885** strategy from that.
4886**
peter.d.reid60ec9142014-09-06 16:39:46 +00004887** For finder-function F, two objects are created:
drh1875f7a2008-12-08 18:19:17 +00004888**
4889** (1) The real finder-function named "FImpt()".
4890**
dane946c392009-08-22 11:39:46 +00004891** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004892**
4893**
4894** A pointer to the F pointer is used as the pAppData value for VFS
4895** objects. We have to do this instead of letting pAppData point
4896** directly at the finder-function since C90 rules prevent a void*
4897** from be cast into a function pointer.
4898**
drh6b9d6dd2008-12-03 19:34:47 +00004899**
drh7708e972008-11-29 00:56:52 +00004900** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004901**
drh7708e972008-11-29 00:56:52 +00004902** * A constant sqlite3_io_methods object call METHOD that has locking
4903** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4904**
4905** * An I/O method finder function called FINDER that returns a pointer
4906** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004907*/
drhe6d41732015-02-21 00:49:00 +00004908#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
drh7708e972008-11-29 00:56:52 +00004909static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004910 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004911 CLOSE, /* xClose */ \
4912 unixRead, /* xRead */ \
4913 unixWrite, /* xWrite */ \
4914 unixTruncate, /* xTruncate */ \
4915 unixSync, /* xSync */ \
4916 unixFileSize, /* xFileSize */ \
4917 LOCK, /* xLock */ \
4918 UNLOCK, /* xUnlock */ \
4919 CKLOCK, /* xCheckReservedLock */ \
4920 unixFileControl, /* xFileControl */ \
4921 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004922 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drhd9f94412014-09-22 03:22:27 +00004923 SHMMAP, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004924 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004925 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00004926 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00004927 unixFetch, /* xFetch */ \
4928 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00004929}; \
drh0c2694b2009-09-03 16:23:44 +00004930static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4931 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004932 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004933} \
drh0c2694b2009-09-03 16:23:44 +00004934static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004935 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004936
4937/*
4938** Here are all of the sqlite3_io_methods objects for each of the
4939** locking strategies. Functions that return pointers to these methods
4940** are also created.
4941*/
4942IOMETHODS(
4943 posixIoFinder, /* Finder function name */
4944 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00004945 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00004946 unixClose, /* xClose method */
4947 unixLock, /* xLock method */
4948 unixUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004949 unixCheckReservedLock, /* xCheckReservedLock method */
4950 unixShmMap /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004951)
drh7708e972008-11-29 00:56:52 +00004952IOMETHODS(
4953 nolockIoFinder, /* Finder function name */
4954 nolockIoMethods, /* sqlite3_io_methods object name */
drh142341c2014-09-19 19:00:48 +00004955 3, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004956 nolockClose, /* xClose method */
4957 nolockLock, /* xLock method */
4958 nolockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004959 nolockCheckReservedLock, /* xCheckReservedLock method */
4960 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004961)
drh7708e972008-11-29 00:56:52 +00004962IOMETHODS(
4963 dotlockIoFinder, /* Finder function name */
4964 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004965 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004966 dotlockClose, /* xClose method */
4967 dotlockLock, /* xLock method */
4968 dotlockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004969 dotlockCheckReservedLock, /* xCheckReservedLock method */
4970 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004971)
drh7708e972008-11-29 00:56:52 +00004972
drhe89b2912015-03-03 20:42:01 +00004973#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004974IOMETHODS(
4975 flockIoFinder, /* Finder function name */
4976 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004977 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004978 flockClose, /* xClose method */
4979 flockLock, /* xLock method */
4980 flockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004981 flockCheckReservedLock, /* xCheckReservedLock method */
4982 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004983)
drh7708e972008-11-29 00:56:52 +00004984#endif
4985
drh6c7d5c52008-11-21 20:32:33 +00004986#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004987IOMETHODS(
4988 semIoFinder, /* Finder function name */
4989 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004990 1, /* shared memory is disabled */
drh8cd5b252015-03-02 22:06:43 +00004991 semXClose, /* xClose method */
4992 semXLock, /* xLock method */
4993 semXUnlock, /* xUnlock method */
4994 semXCheckReservedLock, /* xCheckReservedLock method */
drhd9f94412014-09-22 03:22:27 +00004995 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004996)
aswiftaebf4132008-11-21 00:10:35 +00004997#endif
drh7708e972008-11-29 00:56:52 +00004998
drhd2cb50b2009-01-09 21:41:17 +00004999#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005000IOMETHODS(
5001 afpIoFinder, /* Finder function name */
5002 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005003 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005004 afpClose, /* xClose method */
5005 afpLock, /* xLock method */
5006 afpUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005007 afpCheckReservedLock, /* xCheckReservedLock method */
5008 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005009)
drh715ff302008-12-03 22:32:44 +00005010#endif
5011
5012/*
5013** The proxy locking method is a "super-method" in the sense that it
5014** opens secondary file descriptors for the conch and lock files and
5015** it uses proxy, dot-file, AFP, and flock() locking methods on those
5016** secondary files. For this reason, the division that implements
5017** proxy locking is located much further down in the file. But we need
5018** to go ahead and define the sqlite3_io_methods and finder function
5019** for proxy locking here. So we forward declare the I/O methods.
5020*/
drhd2cb50b2009-01-09 21:41:17 +00005021#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005022static int proxyClose(sqlite3_file*);
5023static int proxyLock(sqlite3_file*, int);
5024static int proxyUnlock(sqlite3_file*, int);
5025static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005026IOMETHODS(
5027 proxyIoFinder, /* Finder function name */
5028 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005029 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005030 proxyClose, /* xClose method */
5031 proxyLock, /* xLock method */
5032 proxyUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005033 proxyCheckReservedLock, /* xCheckReservedLock method */
5034 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005035)
aswiftaebf4132008-11-21 00:10:35 +00005036#endif
drh7708e972008-11-29 00:56:52 +00005037
drh7ed97b92010-01-20 13:07:21 +00005038/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5039#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5040IOMETHODS(
5041 nfsIoFinder, /* Finder function name */
5042 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005043 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005044 unixClose, /* xClose method */
5045 unixLock, /* xLock method */
5046 nfsUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005047 unixCheckReservedLock, /* xCheckReservedLock method */
5048 0 /* xShmMap method */
drh7ed97b92010-01-20 13:07:21 +00005049)
5050#endif
drh7708e972008-11-29 00:56:52 +00005051
drhd2cb50b2009-01-09 21:41:17 +00005052#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005053/*
drh6b9d6dd2008-12-03 19:34:47 +00005054** This "finder" function attempts to determine the best locking strategy
5055** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005056** object that implements that strategy.
5057**
5058** This is for MacOSX only.
5059*/
drh1875f7a2008-12-08 18:19:17 +00005060static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005061 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005062 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005063){
5064 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005065 const char *zFilesystem; /* Filesystem type name */
5066 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005067 } aMap[] = {
5068 { "hfs", &posixIoMethods },
5069 { "ufs", &posixIoMethods },
5070 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005071 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005072 { "webdav", &nolockIoMethods },
5073 { 0, 0 }
5074 };
5075 int i;
5076 struct statfs fsInfo;
5077 struct flock lockInfo;
5078
5079 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005080 /* If filePath==NULL that means we are dealing with a transient file
5081 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005082 return &nolockIoMethods;
5083 }
5084 if( statfs(filePath, &fsInfo) != -1 ){
5085 if( fsInfo.f_flags & MNT_RDONLY ){
5086 return &nolockIoMethods;
5087 }
5088 for(i=0; aMap[i].zFilesystem; i++){
5089 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5090 return aMap[i].pMethods;
5091 }
5092 }
5093 }
5094
5095 /* Default case. Handles, amongst others, "nfs".
5096 ** Test byte-range lock using fcntl(). If the call succeeds,
5097 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005098 */
drh7708e972008-11-29 00:56:52 +00005099 lockInfo.l_len = 1;
5100 lockInfo.l_start = 0;
5101 lockInfo.l_whence = SEEK_SET;
5102 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005103 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005104 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5105 return &nfsIoMethods;
5106 } else {
5107 return &posixIoMethods;
5108 }
drh7708e972008-11-29 00:56:52 +00005109 }else{
5110 return &dotlockIoMethods;
5111 }
5112}
drh0c2694b2009-09-03 16:23:44 +00005113static const sqlite3_io_methods
5114 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005115
drhd2cb50b2009-01-09 21:41:17 +00005116#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005117
drhe89b2912015-03-03 20:42:01 +00005118#if OS_VXWORKS
5119/*
5120** This "finder" function for VxWorks checks to see if posix advisory
5121** locking works. If it does, then that is what is used. If it does not
5122** work, then fallback to named semaphore locking.
chw78a13182009-04-07 05:35:03 +00005123*/
drhe89b2912015-03-03 20:42:01 +00005124static const sqlite3_io_methods *vxworksIoFinderImpl(
chw78a13182009-04-07 05:35:03 +00005125 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005126 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005127){
5128 struct flock lockInfo;
5129
5130 if( !filePath ){
5131 /* If filePath==NULL that means we are dealing with a transient file
5132 ** that does not need to be locked. */
5133 return &nolockIoMethods;
5134 }
5135
5136 /* Test if fcntl() is supported and use POSIX style locks.
5137 ** Otherwise fall back to the named semaphore method.
5138 */
5139 lockInfo.l_len = 1;
5140 lockInfo.l_start = 0;
5141 lockInfo.l_whence = SEEK_SET;
5142 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005143 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005144 return &posixIoMethods;
5145 }else{
5146 return &semIoMethods;
5147 }
5148}
drh0c2694b2009-09-03 16:23:44 +00005149static const sqlite3_io_methods
drhe89b2912015-03-03 20:42:01 +00005150 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005151
drhe89b2912015-03-03 20:42:01 +00005152#endif /* OS_VXWORKS */
chw78a13182009-04-07 05:35:03 +00005153
drh7708e972008-11-29 00:56:52 +00005154/*
peter.d.reid60ec9142014-09-06 16:39:46 +00005155** An abstract type for a pointer to an IO method finder function:
drh7708e972008-11-29 00:56:52 +00005156*/
drh0c2694b2009-09-03 16:23:44 +00005157typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005158
aswiftaebf4132008-11-21 00:10:35 +00005159
drh734c9862008-11-28 15:37:20 +00005160/****************************************************************************
5161**************************** sqlite3_vfs methods ****************************
5162**
5163** This division contains the implementation of methods on the
5164** sqlite3_vfs object.
5165*/
5166
danielk1977a3d4c882007-03-23 10:08:38 +00005167/*
danielk1977e339d652008-06-28 11:23:00 +00005168** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005169*/
5170static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005171 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005172 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005173 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005174 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005175 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005176){
drh7708e972008-11-29 00:56:52 +00005177 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005178 unixFile *pNew = (unixFile *)pId;
5179 int rc = SQLITE_OK;
5180
drh8af6c222010-05-14 12:43:01 +00005181 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005182
dan00157392010-10-05 11:33:15 +00005183 /* Usually the path zFilename should not be a relative pathname. The
5184 ** exception is when opening the proxy "conch" file in builds that
5185 ** include the special Apple locking styles.
5186 */
dan00157392010-10-05 11:33:15 +00005187#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005188 assert( zFilename==0 || zFilename[0]=='/'
5189 || pVfs->pAppData==(void*)&autolockIoFinder );
5190#else
5191 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005192#endif
dan00157392010-10-05 11:33:15 +00005193
drhb07028f2011-10-14 21:49:18 +00005194 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005195 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005196
drh308c2a52010-05-14 11:30:18 +00005197 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005198 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005199 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005200 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005201 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005202#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005203 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005204#endif
drhc02a43a2012-01-10 23:18:38 +00005205 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5206 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005207 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005208 }
drh503a6862013-03-01 01:07:17 +00005209 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005210 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005211 }
drh339eb0b2008-03-07 15:34:11 +00005212
drh6c7d5c52008-11-21 20:32:33 +00005213#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005214 pNew->pId = vxworksFindFileId(zFilename);
5215 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005216 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00005217 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00005218 }
5219#endif
5220
drhc02a43a2012-01-10 23:18:38 +00005221 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005222 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005223 }else{
drh0c2694b2009-09-03 16:23:44 +00005224 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005225#if SQLITE_ENABLE_LOCKING_STYLE
5226 /* Cache zFilename in the locking context (AFP and dotlock override) for
5227 ** proxyLock activation is possible (remote proxy is based on db name)
5228 ** zFilename remains valid until file is closed, to support */
5229 pNew->lockingContext = (void*)zFilename;
5230#endif
drhda0e7682008-07-30 15:27:54 +00005231 }
danielk1977e339d652008-06-28 11:23:00 +00005232
drh7ed97b92010-01-20 13:07:21 +00005233 if( pLockingStyle == &posixIoMethods
5234#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5235 || pLockingStyle == &nfsIoMethods
5236#endif
5237 ){
drh7708e972008-11-29 00:56:52 +00005238 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005239 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005240 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005241 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005242 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005243 ** in two scenarios:
5244 **
5245 ** (a) A call to fstat() failed.
5246 ** (b) A malloc failed.
5247 **
5248 ** Scenario (b) may only occur if the process is holding no other
5249 ** file descriptors open on the same file. If there were other file
5250 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005251 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005252 ** handle h - as it is guaranteed that no posix locks will be released
5253 ** by doing so.
5254 **
5255 ** If scenario (a) caused the error then things are not so safe. The
5256 ** implicit assumption here is that if fstat() fails, things are in
5257 ** such bad shape that dropping a lock or two doesn't matter much.
5258 */
drh0e9365c2011-03-02 02:08:13 +00005259 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005260 h = -1;
5261 }
drh7708e972008-11-29 00:56:52 +00005262 unixLeaveMutex();
5263 }
danielk1977e339d652008-06-28 11:23:00 +00005264
drhd2cb50b2009-01-09 21:41:17 +00005265#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005266 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005267 /* AFP locking uses the file path so it needs to be included in
5268 ** the afpLockingContext.
5269 */
5270 afpLockingContext *pCtx;
drhf3cdcdc2015-04-29 16:50:28 +00005271 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh7708e972008-11-29 00:56:52 +00005272 if( pCtx==0 ){
5273 rc = SQLITE_NOMEM;
5274 }else{
5275 /* NB: zFilename exists and remains valid until the file is closed
5276 ** according to requirement F11141. So we do not need to make a
5277 ** copy of the filename. */
5278 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005279 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005280 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005281 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005282 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005283 if( rc!=SQLITE_OK ){
5284 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005285 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005286 h = -1;
5287 }
drh7708e972008-11-29 00:56:52 +00005288 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005289 }
drh7708e972008-11-29 00:56:52 +00005290 }
5291#endif
danielk1977e339d652008-06-28 11:23:00 +00005292
drh7708e972008-11-29 00:56:52 +00005293 else if( pLockingStyle == &dotlockIoMethods ){
5294 /* Dotfile locking uses the file path so it needs to be included in
5295 ** the dotlockLockingContext
5296 */
5297 char *zLockFile;
5298 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005299 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005300 nFilename = (int)strlen(zFilename) + 6;
drhf3cdcdc2015-04-29 16:50:28 +00005301 zLockFile = (char *)sqlite3_malloc64(nFilename);
drh7708e972008-11-29 00:56:52 +00005302 if( zLockFile==0 ){
5303 rc = SQLITE_NOMEM;
5304 }else{
5305 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005306 }
drh7708e972008-11-29 00:56:52 +00005307 pNew->lockingContext = zLockFile;
5308 }
danielk1977e339d652008-06-28 11:23:00 +00005309
drh6c7d5c52008-11-21 20:32:33 +00005310#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005311 else if( pLockingStyle == &semIoMethods ){
5312 /* Named semaphore locking uses the file path so it needs to be
5313 ** included in the semLockingContext
5314 */
5315 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005316 rc = findInodeInfo(pNew, &pNew->pInode);
5317 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5318 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005319 int n;
drh2238dcc2009-08-27 17:56:20 +00005320 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005321 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005322 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005323 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005324 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5325 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00005326 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00005327 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005328 }
chw97185482008-11-17 08:05:31 +00005329 }
drh7708e972008-11-29 00:56:52 +00005330 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005331 }
drh7708e972008-11-29 00:56:52 +00005332#endif
aswift5b1a2562008-08-22 00:22:35 +00005333
drh4bf66fd2015-02-19 02:43:02 +00005334 storeLastErrno(pNew, 0);
drh6c7d5c52008-11-21 20:32:33 +00005335#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005336 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005337 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005338 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005339 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005340 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005341 }
chw97185482008-11-17 08:05:31 +00005342#endif
danielk1977e339d652008-06-28 11:23:00 +00005343 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005344 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005345 }else{
drh7708e972008-11-29 00:56:52 +00005346 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005347 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005348 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005349 }
danielk1977e339d652008-06-28 11:23:00 +00005350 return rc;
drh054889e2005-11-30 03:20:31 +00005351}
drh9c06c952005-11-26 00:25:00 +00005352
danielk1977ad94b582007-08-20 06:44:22 +00005353/*
drh8b3cf822010-06-01 21:02:51 +00005354** Return the name of a directory in which to put temporary files.
5355** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005356*/
drh7234c6d2010-06-19 15:10:09 +00005357static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005358 static const char *azDirs[] = {
5359 0,
aswiftaebf4132008-11-21 00:10:35 +00005360 0,
danielk197717b90b52008-06-06 11:11:25 +00005361 "/var/tmp",
5362 "/usr/tmp",
5363 "/tmp",
drhb7e50ad2015-11-28 21:49:53 +00005364 "."
danielk197717b90b52008-06-06 11:11:25 +00005365 };
drh8b3cf822010-06-01 21:02:51 +00005366 unsigned int i;
5367 struct stat buf;
drhb7e50ad2015-11-28 21:49:53 +00005368 const char *zDir = sqlite3_temp_directory;
drh8b3cf822010-06-01 21:02:51 +00005369
drhb7e50ad2015-11-28 21:49:53 +00005370 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
5371 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005372 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005373 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005374 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005375 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005376 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005377 break;
5378 }
5379 return zDir;
5380}
5381
5382/*
5383** Create a temporary file name in zBuf. zBuf must be allocated
5384** by the calling process and must be big enough to hold at least
5385** pVfs->mxPathname bytes.
5386*/
5387static int unixGetTempname(int nBuf, char *zBuf){
drh8b3cf822010-06-01 21:02:51 +00005388 const char *zDir;
drhb7e50ad2015-11-28 21:49:53 +00005389 int iLimit = 0;
danielk197717b90b52008-06-06 11:11:25 +00005390
5391 /* It's odd to simulate an io-error here, but really this is just
5392 ** using the io-error infrastructure to test that SQLite handles this
5393 ** function failing.
5394 */
5395 SimulateIOError( return SQLITE_IOERR );
5396
drh7234c6d2010-06-19 15:10:09 +00005397 zDir = unixTempFileDir();
danielk197717b90b52008-06-06 11:11:25 +00005398 do{
drh970942e2015-11-25 23:13:14 +00005399 u64 r;
5400 sqlite3_randomness(sizeof(r), &r);
5401 assert( nBuf>2 );
5402 zBuf[nBuf-2] = 0;
5403 sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
5404 zDir, r, 0);
drhb7e50ad2015-11-28 21:49:53 +00005405 if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
drh99ab3b12011-03-02 15:09:07 +00005406 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005407 return SQLITE_OK;
5408}
5409
drhd2cb50b2009-01-09 21:41:17 +00005410#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005411/*
5412** Routine to transform a unixFile into a proxy-locking unixFile.
5413** Implementation in the proxy-lock division, but used by unixOpen()
5414** if SQLITE_PREFER_PROXY_LOCKING is defined.
5415*/
5416static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005417#endif
drhc66d5b62008-12-03 22:48:32 +00005418
dan08da86a2009-08-21 17:18:03 +00005419/*
5420** Search for an unused file descriptor that was opened on the database
5421** file (not a journal or master-journal file) identified by pathname
5422** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5423** argument to this function.
5424**
5425** Such a file descriptor may exist if a database connection was closed
5426** but the associated file descriptor could not be closed because some
5427** other file descriptor open on the same file is holding a file-lock.
5428** Refer to comments in the unixClose() function and the lengthy comment
5429** describing "Posix Advisory Locking" at the start of this file for
5430** further details. Also, ticket #4018.
5431**
5432** If a suitable file descriptor is found, then it is returned. If no
5433** such file descriptor is located, -1 is returned.
5434*/
dane946c392009-08-22 11:39:46 +00005435static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5436 UnixUnusedFd *pUnused = 0;
5437
5438 /* Do not search for an unused file descriptor on vxworks. Not because
5439 ** vxworks would not benefit from the change (it might, we're not sure),
5440 ** but because no way to test it is currently available. It is better
5441 ** not to risk breaking vxworks support for the sake of such an obscure
5442 ** feature. */
5443#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005444 struct stat sStat; /* Results of stat() call */
5445
5446 /* A stat() call may fail for various reasons. If this happens, it is
5447 ** almost certain that an open() call on the same path will also fail.
5448 ** For this reason, if an error occurs in the stat() call here, it is
5449 ** ignored and -1 is returned. The caller will try to open a new file
5450 ** descriptor on the same path, fail, and return an error to SQLite.
5451 **
5452 ** Even if a subsequent open() call does succeed, the consequences of
peter.d.reid60ec9142014-09-06 16:39:46 +00005453 ** not searching for a reusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005454 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005455 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005456
5457 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005458 pInode = inodeList;
5459 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5460 || pInode->fileId.ino!=sStat.st_ino) ){
5461 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005462 }
drh8af6c222010-05-14 12:43:01 +00005463 if( pInode ){
dane946c392009-08-22 11:39:46 +00005464 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005465 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005466 pUnused = *pp;
5467 if( pUnused ){
5468 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005469 }
5470 }
5471 unixLeaveMutex();
5472 }
dane946c392009-08-22 11:39:46 +00005473#endif /* if !OS_VXWORKS */
5474 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005475}
danielk197717b90b52008-06-06 11:11:25 +00005476
5477/*
danddb0ac42010-07-14 14:48:58 +00005478** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005479** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005480** and a value suitable for passing as the third argument to open(2) is
5481** written to *pMode. If an IO error occurs, an SQLite error code is
5482** returned and the value of *pMode is not modified.
5483**
peter.d.reid60ec9142014-09-06 16:39:46 +00005484** In most cases, this routine sets *pMode to 0, which will become
drh8c815d12012-02-13 20:16:37 +00005485** an indication to robust_open() to create the file using
5486** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5487** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005488** this function queries the file-system for the permissions on the
5489** corresponding database file and sets *pMode to this value. Whenever
5490** possible, WAL and journal files are created using the same permissions
5491** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005492**
5493** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5494** original filename is unavailable. But 8_3_NAMES is only used for
5495** FAT filesystems and permissions do not matter there, so just use
5496** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005497*/
5498static int findCreateFileMode(
5499 const char *zPath, /* Path of file (possibly) being created */
5500 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005501 mode_t *pMode, /* OUT: Permissions to open file with */
5502 uid_t *pUid, /* OUT: uid to set on the file */
5503 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005504){
5505 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005506 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005507 *pUid = 0;
5508 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005509 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005510 char zDb[MAX_PATHNAME+1]; /* Database file path */
5511 int nDb; /* Number of valid bytes in zDb */
5512 struct stat sStat; /* Output of stat() on database file */
5513
dana0c989d2010-11-05 18:07:37 +00005514 /* zPath is a path to a WAL or journal file. The following block derives
5515 ** the path to the associated database file from zPath. This block handles
5516 ** the following naming conventions:
5517 **
5518 ** "<path to db>-journal"
5519 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005520 ** "<path to db>-journalNN"
5521 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005522 **
drhd337c5b2011-10-20 18:23:35 +00005523 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005524 ** used by the test_multiplex.c module.
5525 */
5526 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005527#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00005528 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00005529 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005530#else
5531 while( zPath[nDb]!='-' ){
5532 assert( nDb>0 );
5533 assert( zPath[nDb]!='\n' );
5534 nDb--;
5535 }
5536#endif
danddb0ac42010-07-14 14:48:58 +00005537 memcpy(zDb, zPath, nDb);
5538 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005539
drh58384f12011-07-28 00:14:45 +00005540 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005541 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005542 *pUid = sStat.st_uid;
5543 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005544 }else{
5545 rc = SQLITE_IOERR_FSTAT;
5546 }
5547 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5548 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005549 }
5550 return rc;
5551}
5552
5553/*
danielk1977ad94b582007-08-20 06:44:22 +00005554** Open the file zPath.
5555**
danielk1977b4b47412007-08-17 15:53:36 +00005556** Previously, the SQLite OS layer used three functions in place of this
5557** one:
5558**
5559** sqlite3OsOpenReadWrite();
5560** sqlite3OsOpenReadOnly();
5561** sqlite3OsOpenExclusive();
5562**
5563** These calls correspond to the following combinations of flags:
5564**
5565** ReadWrite() -> (READWRITE | CREATE)
5566** ReadOnly() -> (READONLY)
5567** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5568**
5569** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5570** true, the file was configured to be automatically deleted when the
5571** file handle closed. To achieve the same effect using this new
5572** interface, add the DELETEONCLOSE flag to those specified above for
5573** OpenExclusive().
5574*/
5575static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005576 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5577 const char *zPath, /* Pathname of file to be opened */
5578 sqlite3_file *pFile, /* The file descriptor to be filled in */
5579 int flags, /* Input flags to control the opening */
5580 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005581){
dan08da86a2009-08-21 17:18:03 +00005582 unixFile *p = (unixFile *)pFile;
5583 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005584 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005585 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005586 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005587 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005588 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005589
5590 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5591 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5592 int isCreate = (flags & SQLITE_OPEN_CREATE);
5593 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5594 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005595#if SQLITE_ENABLE_LOCKING_STYLE
5596 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5597#endif
drh3d4435b2011-08-26 20:55:50 +00005598#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5599 struct statfs fsInfo;
5600#endif
danielk1977b4b47412007-08-17 15:53:36 +00005601
danielk1977fee2d252007-08-18 10:59:19 +00005602 /* If creating a master or main-file journal, this function will open
5603 ** a file-descriptor on the directory too. The first time unixSync()
5604 ** is called the directory file descriptor will be fsync()ed and close()d.
5605 */
drh0059eae2011-08-08 23:48:40 +00005606 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005607 eType==SQLITE_OPEN_MASTER_JOURNAL
5608 || eType==SQLITE_OPEN_MAIN_JOURNAL
5609 || eType==SQLITE_OPEN_WAL
5610 ));
danielk1977fee2d252007-08-18 10:59:19 +00005611
danielk197717b90b52008-06-06 11:11:25 +00005612 /* If argument zPath is a NULL pointer, this function is required to open
5613 ** a temporary file. Use this buffer to store the file name in.
5614 */
drhc02a43a2012-01-10 23:18:38 +00005615 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005616 const char *zName = zPath;
5617
danielk1977fee2d252007-08-18 10:59:19 +00005618 /* Check the following statements are true:
5619 **
5620 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5621 ** (b) if CREATE is set, then READWRITE must also be set, and
5622 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005623 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005624 */
danielk1977b4b47412007-08-17 15:53:36 +00005625 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005626 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005627 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005628 assert(isDelete==0 || isCreate);
5629
danddb0ac42010-07-14 14:48:58 +00005630 /* The main DB, main journal, WAL file and master journal are never
5631 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005632 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5633 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5634 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005635 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005636
danielk1977fee2d252007-08-18 10:59:19 +00005637 /* Assert that the upper layer has set one of the "file-type" flags. */
5638 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5639 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5640 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005641 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005642 );
5643
drhb00d8622014-01-01 15:18:36 +00005644 /* Detect a pid change and reset the PRNG. There is a race condition
5645 ** here such that two or more threads all trying to open databases at
5646 ** the same instant might all reset the PRNG. But multiple resets
5647 ** are harmless.
5648 */
drh5ac93652015-03-21 20:59:43 +00005649 if( randomnessPid!=osGetpid(0) ){
5650 randomnessPid = osGetpid(0);
drhb00d8622014-01-01 15:18:36 +00005651 sqlite3_randomness(0,0);
5652 }
5653
dan08da86a2009-08-21 17:18:03 +00005654 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005655
dan08da86a2009-08-21 17:18:03 +00005656 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005657 UnixUnusedFd *pUnused;
5658 pUnused = findReusableFd(zName, flags);
5659 if( pUnused ){
5660 fd = pUnused->fd;
5661 }else{
drhf3cdcdc2015-04-29 16:50:28 +00005662 pUnused = sqlite3_malloc64(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005663 if( !pUnused ){
5664 return SQLITE_NOMEM;
5665 }
5666 }
5667 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005668
5669 /* Database filenames are double-zero terminated if they are not
5670 ** URIs with parameters. Hence, they can always be passed into
5671 ** sqlite3_uri_parameter(). */
5672 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5673
dan08da86a2009-08-21 17:18:03 +00005674 }else if( !zName ){
5675 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005676 assert(isDelete && !syncDir);
drhb7e50ad2015-11-28 21:49:53 +00005677 rc = unixGetTempname(pVfs->mxPathname, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005678 if( rc!=SQLITE_OK ){
5679 return rc;
5680 }
5681 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005682
5683 /* Generated temporary filenames are always double-zero terminated
5684 ** for use by sqlite3_uri_parameter(). */
5685 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005686 }
5687
dan08da86a2009-08-21 17:18:03 +00005688 /* Determine the value of the flags parameter passed to POSIX function
5689 ** open(). These must be calculated even if open() is not called, as
5690 ** they may be stored as part of the file handle and used by the
5691 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005692 if( isReadonly ) openFlags |= O_RDONLY;
5693 if( isReadWrite ) openFlags |= O_RDWR;
5694 if( isCreate ) openFlags |= O_CREAT;
5695 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5696 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005697
danielk1977b4b47412007-08-17 15:53:36 +00005698 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005699 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005700 uid_t uid; /* Userid for the file */
5701 gid_t gid; /* Groupid for the file */
5702 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005703 if( rc!=SQLITE_OK ){
5704 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005705 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005706 return rc;
5707 }
drhad4f1e52011-03-04 15:43:57 +00005708 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005709 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
drh5a2d9702015-11-26 02:21:05 +00005710 assert( !isExclusive || (openFlags & O_CREAT)!=0 );
5711 if( fd<0 && errno!=EISDIR && isReadWrite ){
dan08da86a2009-08-21 17:18:03 +00005712 /* Failed to open the file for read/write access. Try read-only. */
5713 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005714 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005715 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005716 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005717 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005718 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005719 }
5720 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005721 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005722 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005723 }
drhac7c3ac2012-02-11 19:23:48 +00005724
5725 /* If this process is running as root and if creating a new rollback
5726 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005727 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005728 */
5729 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drh6226ca22015-11-24 15:06:28 +00005730 robustFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005731 }
danielk1977b4b47412007-08-17 15:53:36 +00005732 }
dan08da86a2009-08-21 17:18:03 +00005733 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005734 if( pOutFlags ){
5735 *pOutFlags = flags;
5736 }
5737
dane946c392009-08-22 11:39:46 +00005738 if( p->pUnused ){
5739 p->pUnused->fd = fd;
5740 p->pUnused->flags = flags;
5741 }
5742
danielk1977b4b47412007-08-17 15:53:36 +00005743 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005744#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005745 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00005746#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
5747 zPath = sqlite3_mprintf("%s", zName);
5748 if( zPath==0 ){
5749 robust_close(p, fd, __LINE__);
5750 return SQLITE_NOMEM;
5751 }
chw97185482008-11-17 08:05:31 +00005752#else
drh036ac7f2011-08-08 23:18:05 +00005753 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005754#endif
danielk1977b4b47412007-08-17 15:53:36 +00005755 }
drh41022642008-11-21 00:24:42 +00005756#if SQLITE_ENABLE_LOCKING_STYLE
5757 else{
dan08da86a2009-08-21 17:18:03 +00005758 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005759 }
5760#endif
5761
drhda0e7682008-07-30 15:27:54 +00005762 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005763
drh7ed97b92010-01-20 13:07:21 +00005764
5765#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005766 if( fstatfs(fd, &fsInfo) == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00005767 storeLastErrno(p, errno);
drh0e9365c2011-03-02 02:08:13 +00005768 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005769 return SQLITE_IOERR_ACCESS;
5770 }
5771 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5772 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5773 }
drh4bf66fd2015-02-19 02:43:02 +00005774 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
5775 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5776 }
drh7ed97b92010-01-20 13:07:21 +00005777#endif
drhc02a43a2012-01-10 23:18:38 +00005778
5779 /* Set up appropriate ctrlFlags */
5780 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5781 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5782 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5783 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5784 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5785
drh7ed97b92010-01-20 13:07:21 +00005786#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005787#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005788 isAutoProxy = 1;
5789#endif
5790 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005791 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5792 int useProxy = 0;
5793
dan08da86a2009-08-21 17:18:03 +00005794 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5795 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005796 if( envforce!=NULL ){
5797 useProxy = atoi(envforce)>0;
5798 }else{
aswiftaebf4132008-11-21 00:10:35 +00005799 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5800 }
5801 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005802 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005803 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005804 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005805 if( rc!=SQLITE_OK ){
5806 /* Use unixClose to clean up the resources added in fillInUnixFile
5807 ** and clear all the structure's references. Specifically,
5808 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5809 */
5810 unixClose(pFile);
5811 return rc;
5812 }
aswiftaebf4132008-11-21 00:10:35 +00005813 }
dane946c392009-08-22 11:39:46 +00005814 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005815 }
5816 }
5817#endif
5818
drhc02a43a2012-01-10 23:18:38 +00005819 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5820
dane946c392009-08-22 11:39:46 +00005821open_finished:
5822 if( rc!=SQLITE_OK ){
5823 sqlite3_free(p->pUnused);
5824 }
5825 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005826}
5827
dane946c392009-08-22 11:39:46 +00005828
danielk1977b4b47412007-08-17 15:53:36 +00005829/*
danielk1977fee2d252007-08-18 10:59:19 +00005830** Delete the file at zPath. If the dirSync argument is true, fsync()
5831** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005832*/
drh6b9d6dd2008-12-03 19:34:47 +00005833static int unixDelete(
5834 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5835 const char *zPath, /* Name of file to be deleted */
5836 int dirSync /* If true, fsync() directory after deleting file */
5837){
danielk1977fee2d252007-08-18 10:59:19 +00005838 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005839 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005840 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005841 if( osUnlink(zPath)==(-1) ){
drhbd945542014-08-13 11:39:42 +00005842 if( errno==ENOENT
5843#if OS_VXWORKS
drh19541f32014-09-01 13:37:55 +00005844 || osAccess(zPath,0)!=0
drhbd945542014-08-13 11:39:42 +00005845#endif
5846 ){
dan9fc5b4a2012-11-09 20:17:26 +00005847 rc = SQLITE_IOERR_DELETE_NOENT;
5848 }else{
drhb4308162012-11-09 21:40:02 +00005849 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005850 }
drhb4308162012-11-09 21:40:02 +00005851 return rc;
drh5d4feff2010-07-14 01:45:22 +00005852 }
danielk1977d39fa702008-10-16 13:27:40 +00005853#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005854 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005855 int fd;
drh90315a22011-08-10 01:52:12 +00005856 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005857 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005858#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005859 if( fsync(fd)==-1 )
5860#else
5861 if( fsync(fd) )
5862#endif
5863 {
dane18d4952011-02-21 11:46:24 +00005864 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005865 }
drh0e9365c2011-03-02 02:08:13 +00005866 robust_close(0, fd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00005867 }else{
5868 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00005869 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005870 }
5871 }
danielk1977d138dd82008-10-15 16:02:48 +00005872#endif
danielk1977fee2d252007-08-18 10:59:19 +00005873 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005874}
5875
danielk197790949c22007-08-17 16:50:38 +00005876/*
mistachkin48864df2013-03-21 21:20:32 +00005877** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00005878** test performed depends on the value of flags:
5879**
5880** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5881** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5882** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5883**
5884** Otherwise return 0.
5885*/
danielk1977861f7452008-06-05 11:39:11 +00005886static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005887 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5888 const char *zPath, /* Path of the file to examine */
5889 int flags, /* What do we want to learn about the zPath file? */
5890 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005891){
danielk1977397d65f2008-11-19 11:35:39 +00005892 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005893 SimulateIOError( return SQLITE_IOERR_ACCESS; );
drhd260b5b2015-11-25 18:03:33 +00005894 assert( pResOut!=0 );
danielk1977b4b47412007-08-17 15:53:36 +00005895
drhd260b5b2015-11-25 18:03:33 +00005896 /* The spec says there are three possible values for flags. But only
5897 ** two of them are actually used */
5898 assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
5899
5900 if( flags==SQLITE_ACCESS_EXISTS ){
dan83acd422010-06-18 11:10:06 +00005901 struct stat buf;
drhd260b5b2015-11-25 18:03:33 +00005902 *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
5903 }else{
5904 *pResOut = osAccess(zPath, W_OK|R_OK)==0;
dan83acd422010-06-18 11:10:06 +00005905 }
danielk1977861f7452008-06-05 11:39:11 +00005906 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005907}
5908
danielk1977b4b47412007-08-17 15:53:36 +00005909
5910/*
5911** Turn a relative pathname into a full pathname. The relative path
5912** is stored as a nul-terminated string in the buffer pointed to by
5913** zPath.
5914**
5915** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5916** (in this case, MAX_PATHNAME bytes). The full-path is written to
5917** this buffer before returning.
5918*/
danielk1977adfb9b02007-09-17 07:02:56 +00005919static int unixFullPathname(
5920 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5921 const char *zPath, /* Possibly relative input path */
5922 int nOut, /* Size of output buffer in bytes */
5923 char *zOut /* Output buffer */
5924){
dan245fdc62015-10-31 17:58:33 +00005925 int nByte;
danielk1977843e65f2007-09-01 16:16:15 +00005926
5927 /* It's odd to simulate an io-error here, but really this is just
5928 ** using the io-error infrastructure to test that SQLite handles this
5929 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005930 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005931 */
5932 SimulateIOError( return SQLITE_ERROR );
5933
drh153c62c2007-08-24 03:51:33 +00005934 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005935 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005936
dan245fdc62015-10-31 17:58:33 +00005937 /* Attempt to resolve the path as if it were a symbolic link. If it is
5938 ** a symbolic link, the resolved path is stored in buffer zOut[]. Or, if
5939 ** the identified file is not a symbolic link or does not exist, then
5940 ** zPath is copied directly into zOut. Either way, nByte is left set to
5941 ** the size of the string copied into zOut[] in bytes. */
5942 nByte = osReadlink(zPath, zOut, nOut-1);
5943 if( nByte<0 ){
5944 if( errno!=EINVAL && errno!=ENOENT ){
5945 return unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zPath);
5946 }
drhd260b5b2015-11-25 18:03:33 +00005947 sqlite3_snprintf(nOut, zOut, "%s", zPath);
dan245fdc62015-10-31 17:58:33 +00005948 nByte = sqlite3Strlen30(zOut);
danielk1977b4b47412007-08-17 15:53:36 +00005949 }else{
dan245fdc62015-10-31 17:58:33 +00005950 zOut[nByte] = '\0';
5951 }
5952
5953 /* If buffer zOut[] now contains an absolute path there is nothing more
5954 ** to do. If it contains a relative path, do the following:
5955 **
5956 ** * move the relative path string so that it is at the end of th
5957 ** zOut[] buffer.
5958 ** * Call getcwd() to read the path of the current working directory
5959 ** into the start of the zOut[] buffer.
5960 ** * Append a '/' character to the cwd string and move the
5961 ** relative path back within the buffer so that it immediately
5962 ** follows the '/'.
5963 **
5964 ** This code is written so that if the combination of the CWD and relative
5965 ** path are larger than the allocated size of zOut[] the CWD is silently
5966 ** truncated to make it fit. This is Ok, as SQLite refuses to open any
5967 ** file for which this function returns a full path larger than (nOut-8)
5968 ** bytes in size. */
drh025d2f72015-11-30 22:22:23 +00005969 testcase( nByte==nOut-5 );
5970 testcase( nByte==nOut-4 );
5971 if( zOut[0]!='/' && nByte<nOut-4 ){
danielk1977b4b47412007-08-17 15:53:36 +00005972 int nCwd;
dan245fdc62015-10-31 17:58:33 +00005973 int nRem = nOut-nByte-1;
5974 memmove(&zOut[nRem], zOut, nByte+1);
5975 zOut[nRem-1] = '\0';
5976 if( osGetcwd(zOut, nRem-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005977 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005978 }
dan245fdc62015-10-31 17:58:33 +00005979 nCwd = sqlite3Strlen30(zOut);
5980 assert( nCwd<=nRem-1 );
5981 zOut[nCwd] = '/';
5982 memmove(&zOut[nCwd+1], &zOut[nRem], nByte+1);
danielk1977b4b47412007-08-17 15:53:36 +00005983 }
dan245fdc62015-10-31 17:58:33 +00005984
danielk1977b4b47412007-08-17 15:53:36 +00005985 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005986}
5987
drh0ccebe72005-06-07 22:22:50 +00005988
drh761df872006-12-21 01:29:22 +00005989#ifndef SQLITE_OMIT_LOAD_EXTENSION
5990/*
5991** Interfaces for opening a shared library, finding entry points
5992** within the shared library, and closing the shared library.
5993*/
5994#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005995static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5996 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005997 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5998}
danielk197795c8a542007-09-01 06:51:27 +00005999
6000/*
6001** SQLite calls this function immediately after a call to unixDlSym() or
6002** unixDlOpen() fails (returns a null pointer). If a more detailed error
6003** message is available, it is written to zBufOut. If no error message
6004** is available, zBufOut is left unmodified and SQLite uses a default
6005** error message.
6006*/
danielk1977397d65f2008-11-19 11:35:39 +00006007static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006008 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006009 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006010 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006011 zErr = dlerror();
6012 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006013 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006014 }
drh6c7d5c52008-11-21 20:32:33 +00006015 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006016}
drh1875f7a2008-12-08 18:19:17 +00006017static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6018 /*
6019 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6020 ** cast into a pointer to a function. And yet the library dlsym() routine
6021 ** returns a void* which is really a pointer to a function. So how do we
6022 ** use dlsym() with -pedantic-errors?
6023 **
6024 ** Variable x below is defined to be a pointer to a function taking
6025 ** parameters void* and const char* and returning a pointer to a function.
6026 ** We initialize x by assigning it a pointer to the dlsym() function.
6027 ** (That assignment requires a cast.) Then we call the function that
6028 ** x points to.
6029 **
6030 ** This work-around is unlikely to work correctly on any system where
6031 ** you really cannot cast a function pointer into void*. But then, on the
6032 ** other hand, dlsym() will not work on such a system either, so we have
6033 ** not really lost anything.
6034 */
6035 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006036 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006037 x = (void(*(*)(void*,const char*))(void))dlsym;
6038 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006039}
danielk1977397d65f2008-11-19 11:35:39 +00006040static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6041 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006042 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006043}
danielk1977b4b47412007-08-17 15:53:36 +00006044#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6045 #define unixDlOpen 0
6046 #define unixDlError 0
6047 #define unixDlSym 0
6048 #define unixDlClose 0
6049#endif
6050
6051/*
danielk197790949c22007-08-17 16:50:38 +00006052** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006053*/
danielk1977397d65f2008-11-19 11:35:39 +00006054static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6055 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006056 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006057
drhbbd42a62004-05-22 17:41:58 +00006058 /* We have to initialize zBuf to prevent valgrind from reporting
6059 ** errors. The reports issued by valgrind are incorrect - we would
6060 ** prefer that the randomness be increased by making use of the
6061 ** uninitialized space in zBuf - but valgrind errors tend to worry
6062 ** some users. Rather than argue, it seems easier just to initialize
6063 ** the whole array and silence valgrind, even if that means less randomness
6064 ** in the random seed.
6065 **
6066 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006067 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006068 ** tests repeatable.
6069 */
danielk1977b4b47412007-08-17 15:53:36 +00006070 memset(zBuf, 0, nBuf);
drh5ac93652015-03-21 20:59:43 +00006071 randomnessPid = osGetpid(0);
drh6a412b82015-04-30 12:31:49 +00006072#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
drhbbd42a62004-05-22 17:41:58 +00006073 {
drhb00d8622014-01-01 15:18:36 +00006074 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006075 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006076 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006077 time_t t;
6078 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006079 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006080 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6081 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6082 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006083 }else{
drhc18b4042012-02-10 03:10:27 +00006084 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006085 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006086 }
drhbbd42a62004-05-22 17:41:58 +00006087 }
6088#endif
drh72cbd072008-10-14 17:58:38 +00006089 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006090}
6091
danielk1977b4b47412007-08-17 15:53:36 +00006092
drhbbd42a62004-05-22 17:41:58 +00006093/*
6094** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006095** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006096** The return value is the number of microseconds of sleep actually
6097** requested from the underlying operating system, a number which
6098** might be greater than or equal to the argument, but not less
6099** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006100*/
danielk1977397d65f2008-11-19 11:35:39 +00006101static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006102#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006103 struct timespec sp;
6104
6105 sp.tv_sec = microseconds / 1000000;
6106 sp.tv_nsec = (microseconds % 1000000) * 1000;
6107 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006108 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006109 return microseconds;
6110#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006111 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006112 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006113 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006114#else
danielk1977b4b47412007-08-17 15:53:36 +00006115 int seconds = (microseconds+999999)/1000000;
6116 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006117 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006118 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006119#endif
drh88f474a2006-01-02 20:00:12 +00006120}
6121
6122/*
drh6b9d6dd2008-12-03 19:34:47 +00006123** The following variable, if set to a non-zero value, is interpreted as
6124** the number of seconds since 1970 and is used to set the result of
6125** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006126*/
6127#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006128int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006129#endif
6130
6131/*
drhb7e8ea22010-05-03 14:32:30 +00006132** Find the current time (in Universal Coordinated Time). Write into *piNow
6133** the current time and date as a Julian Day number times 86_400_000. In
6134** other words, write into *piNow the number of milliseconds since the Julian
6135** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6136** proleptic Gregorian calendar.
6137**
drh31702252011-10-12 23:13:43 +00006138** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6139** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006140*/
6141static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6142 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006143 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006144#if defined(NO_GETTOD)
6145 time_t t;
6146 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006147 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006148#elif OS_VXWORKS
6149 struct timespec sNow;
6150 clock_gettime(CLOCK_REALTIME, &sNow);
6151 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6152#else
6153 struct timeval sNow;
drh970942e2015-11-25 23:13:14 +00006154 (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
6155 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
drhb7e8ea22010-05-03 14:32:30 +00006156#endif
6157
6158#ifdef SQLITE_TEST
6159 if( sqlite3_current_time ){
6160 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6161 }
6162#endif
6163 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006164 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006165}
6166
drh5337dac2015-11-25 15:15:03 +00006167#if 0 /* Not used */
drhb7e8ea22010-05-03 14:32:30 +00006168/*
drhbbd42a62004-05-22 17:41:58 +00006169** Find the current time (in Universal Coordinated Time). Write the
6170** current time and date as a Julian Day number into *prNow and
6171** return 0. Return 1 if the time and date cannot be found.
6172*/
danielk1977397d65f2008-11-19 11:35:39 +00006173static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006174 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006175 int rc;
drhff828942010-06-26 21:34:06 +00006176 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006177 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006178 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006179 return rc;
drhbbd42a62004-05-22 17:41:58 +00006180}
drh5337dac2015-11-25 15:15:03 +00006181#else
6182# define unixCurrentTime 0
6183#endif
danielk1977b4b47412007-08-17 15:53:36 +00006184
drh5337dac2015-11-25 15:15:03 +00006185#if 0 /* Not used */
drh6b9d6dd2008-12-03 19:34:47 +00006186/*
6187** We added the xGetLastError() method with the intention of providing
6188** better low-level error messages when operating-system problems come up
6189** during SQLite operation. But so far, none of that has been implemented
6190** in the core. So this routine is never called. For now, it is merely
6191** a place-holder.
6192*/
danielk1977397d65f2008-11-19 11:35:39 +00006193static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6194 UNUSED_PARAMETER(NotUsed);
6195 UNUSED_PARAMETER(NotUsed2);
6196 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00006197 return 0;
6198}
drh5337dac2015-11-25 15:15:03 +00006199#else
6200# define unixGetLastError 0
6201#endif
danielk1977bcb97fe2008-06-06 15:49:29 +00006202
drhf2424c52010-04-26 00:04:55 +00006203
6204/*
drh734c9862008-11-28 15:37:20 +00006205************************ End of sqlite3_vfs methods ***************************
6206******************************************************************************/
6207
drh715ff302008-12-03 22:32:44 +00006208/******************************************************************************
6209************************** Begin Proxy Locking ********************************
6210**
6211** Proxy locking is a "uber-locking-method" in this sense: It uses the
6212** other locking methods on secondary lock files. Proxy locking is a
6213** meta-layer over top of the primitive locking implemented above. For
6214** this reason, the division that implements of proxy locking is deferred
6215** until late in the file (here) after all of the other I/O methods have
6216** been defined - so that the primitive locking methods are available
6217** as services to help with the implementation of proxy locking.
6218**
6219****
6220**
6221** The default locking schemes in SQLite use byte-range locks on the
6222** database file to coordinate safe, concurrent access by multiple readers
6223** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6224** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6225** as POSIX read & write locks over fixed set of locations (via fsctl),
6226** on AFP and SMB only exclusive byte-range locks are available via fsctl
6227** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6228** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6229** address in the shared range is taken for a SHARED lock, the entire
6230** shared range is taken for an EXCLUSIVE lock):
6231**
drhf2f105d2012-08-20 15:53:54 +00006232** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006233** RESERVED_BYTE 0x40000001
6234** SHARED_RANGE 0x40000002 -> 0x40000200
6235**
6236** This works well on the local file system, but shows a nearly 100x
6237** slowdown in read performance on AFP because the AFP client disables
6238** the read cache when byte-range locks are present. Enabling the read
6239** cache exposes a cache coherency problem that is present on all OS X
6240** supported network file systems. NFS and AFP both observe the
6241** close-to-open semantics for ensuring cache coherency
6242** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6243** address the requirements for concurrent database access by multiple
6244** readers and writers
6245** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6246**
6247** To address the performance and cache coherency issues, proxy file locking
6248** changes the way database access is controlled by limiting access to a
6249** single host at a time and moving file locks off of the database file
6250** and onto a proxy file on the local file system.
6251**
6252**
6253** Using proxy locks
6254** -----------------
6255**
6256** C APIs
6257**
drh4bf66fd2015-02-19 02:43:02 +00006258** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
drh715ff302008-12-03 22:32:44 +00006259** <proxy_path> | ":auto:");
drh4bf66fd2015-02-19 02:43:02 +00006260** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6261** &<proxy_path>);
drh715ff302008-12-03 22:32:44 +00006262**
6263**
6264** SQL pragmas
6265**
6266** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6267** PRAGMA [database.]lock_proxy_file
6268**
6269** Specifying ":auto:" means that if there is a conch file with a matching
6270** host ID in it, the proxy path in the conch file will be used, otherwise
6271** a proxy path based on the user's temp dir
6272** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6273** actual proxy file name is generated from the name and path of the
6274** database file. For example:
6275**
6276** For database path "/Users/me/foo.db"
6277** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6278**
6279** Once a lock proxy is configured for a database connection, it can not
6280** be removed, however it may be switched to a different proxy path via
6281** the above APIs (assuming the conch file is not being held by another
6282** connection or process).
6283**
6284**
6285** How proxy locking works
6286** -----------------------
6287**
6288** Proxy file locking relies primarily on two new supporting files:
6289**
6290** * conch file to limit access to the database file to a single host
6291** at a time
6292**
6293** * proxy file to act as a proxy for the advisory locks normally
6294** taken on the database
6295**
6296** The conch file - to use a proxy file, sqlite must first "hold the conch"
6297** by taking an sqlite-style shared lock on the conch file, reading the
6298** contents and comparing the host's unique host ID (see below) and lock
6299** proxy path against the values stored in the conch. The conch file is
6300** stored in the same directory as the database file and the file name
6301** is patterned after the database file name as ".<databasename>-conch".
peter.d.reid60ec9142014-09-06 16:39:46 +00006302** If the conch file does not exist, or its contents do not match the
drh715ff302008-12-03 22:32:44 +00006303** host ID and/or proxy path, then the lock is escalated to an exclusive
6304** lock and the conch file contents is updated with the host ID and proxy
6305** path and the lock is downgraded to a shared lock again. If the conch
6306** is held by another process (with a shared lock), the exclusive lock
6307** will fail and SQLITE_BUSY is returned.
6308**
6309** The proxy file - a single-byte file used for all advisory file locks
6310** normally taken on the database file. This allows for safe sharing
6311** of the database file for multiple readers and writers on the same
6312** host (the conch ensures that they all use the same local lock file).
6313**
drh715ff302008-12-03 22:32:44 +00006314** Requesting the lock proxy does not immediately take the conch, it is
6315** only taken when the first request to lock database file is made.
6316** This matches the semantics of the traditional locking behavior, where
6317** opening a connection to a database file does not take a lock on it.
6318** The shared lock and an open file descriptor are maintained until
6319** the connection to the database is closed.
6320**
6321** The proxy file and the lock file are never deleted so they only need
6322** to be created the first time they are used.
6323**
6324** Configuration options
6325** ---------------------
6326**
6327** SQLITE_PREFER_PROXY_LOCKING
6328**
6329** Database files accessed on non-local file systems are
6330** automatically configured for proxy locking, lock files are
6331** named automatically using the same logic as
6332** PRAGMA lock_proxy_file=":auto:"
6333**
6334** SQLITE_PROXY_DEBUG
6335**
6336** Enables the logging of error messages during host id file
6337** retrieval and creation
6338**
drh715ff302008-12-03 22:32:44 +00006339** LOCKPROXYDIR
6340**
6341** Overrides the default directory used for lock proxy files that
6342** are named automatically via the ":auto:" setting
6343**
6344** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6345**
6346** Permissions to use when creating a directory for storing the
6347** lock proxy files, only used when LOCKPROXYDIR is not set.
6348**
6349**
6350** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6351** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6352** force proxy locking to be used for every database file opened, and 0
6353** will force automatic proxy locking to be disabled for all database
drh4bf66fd2015-02-19 02:43:02 +00006354** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
drh715ff302008-12-03 22:32:44 +00006355** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6356*/
6357
6358/*
6359** Proxy locking is only available on MacOSX
6360*/
drhd2cb50b2009-01-09 21:41:17 +00006361#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006362
drh715ff302008-12-03 22:32:44 +00006363/*
6364** The proxyLockingContext has the path and file structures for the remote
6365** and local proxy files in it
6366*/
6367typedef struct proxyLockingContext proxyLockingContext;
6368struct proxyLockingContext {
6369 unixFile *conchFile; /* Open conch file */
6370 char *conchFilePath; /* Name of the conch file */
6371 unixFile *lockProxy; /* Open proxy lock file */
6372 char *lockProxyPath; /* Name of the proxy lock file */
6373 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006374 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh4bf66fd2015-02-19 02:43:02 +00006375 int nFails; /* Number of conch taking failures */
drh715ff302008-12-03 22:32:44 +00006376 void *oldLockingContext; /* Original lockingcontext to restore on close */
6377 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6378};
6379
drh7ed97b92010-01-20 13:07:21 +00006380/*
6381** The proxy lock file path for the database at dbPath is written into lPath,
6382** which must point to valid, writable memory large enough for a maxLen length
6383** file path.
drh715ff302008-12-03 22:32:44 +00006384*/
drh715ff302008-12-03 22:32:44 +00006385static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6386 int len;
6387 int dbLen;
6388 int i;
6389
6390#ifdef LOCKPROXYDIR
6391 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6392#else
6393# ifdef _CS_DARWIN_USER_TEMP_DIR
6394 {
drh7ed97b92010-01-20 13:07:21 +00006395 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006396 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006397 lPath, errno, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006398 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006399 }
drh7ed97b92010-01-20 13:07:21 +00006400 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006401 }
6402# else
6403 len = strlcpy(lPath, "/tmp/", maxLen);
6404# endif
6405#endif
6406
6407 if( lPath[len-1]!='/' ){
6408 len = strlcat(lPath, "/", maxLen);
6409 }
6410
6411 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006412 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006413 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006414 char c = dbPath[i];
6415 lPath[i+len] = (c=='/')?'_':c;
6416 }
6417 lPath[i+len]='\0';
6418 strlcat(lPath, ":auto:", maxLen);
drh5ac93652015-03-21 20:59:43 +00006419 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006420 return SQLITE_OK;
6421}
6422
drh7ed97b92010-01-20 13:07:21 +00006423/*
6424 ** Creates the lock file and any missing directories in lockPath
6425 */
6426static int proxyCreateLockPath(const char *lockPath){
6427 int i, len;
6428 char buf[MAXPATHLEN];
6429 int start = 0;
6430
6431 assert(lockPath!=NULL);
6432 /* try to create all the intermediate directories */
6433 len = (int)strlen(lockPath);
6434 buf[0] = lockPath[0];
6435 for( i=1; i<len; i++ ){
6436 if( lockPath[i] == '/' && (i - start > 0) ){
6437 /* only mkdir if leaf dir != "." or "/" or ".." */
6438 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6439 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6440 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006441 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006442 int err=errno;
6443 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006444 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006445 "'%s' proxy lock path=%s pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006446 buf, strerror(err), lockPath, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006447 return err;
6448 }
6449 }
6450 }
6451 start=i+1;
6452 }
6453 buf[i] = lockPath[i];
6454 }
drh62aaa6c2015-11-21 17:27:42 +00006455 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006456 return 0;
6457}
6458
drh715ff302008-12-03 22:32:44 +00006459/*
6460** Create a new VFS file descriptor (stored in memory obtained from
6461** sqlite3_malloc) and open the file named "path" in the file descriptor.
6462**
6463** The caller is responsible not only for closing the file descriptor
6464** but also for freeing the memory associated with the file descriptor.
6465*/
drh7ed97b92010-01-20 13:07:21 +00006466static int proxyCreateUnixFile(
6467 const char *path, /* path for the new unixFile */
6468 unixFile **ppFile, /* unixFile created and returned by ref */
6469 int islockfile /* if non zero missing dirs will be created */
6470) {
6471 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006472 unixFile *pNew;
6473 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006474 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006475 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006476 int terrno = 0;
6477 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006478
drh7ed97b92010-01-20 13:07:21 +00006479 /* 1. first try to open/create the file
6480 ** 2. if that fails, and this is a lock file (not-conch), try creating
6481 ** the parent directories and then try again.
6482 ** 3. if that fails, try to open the file read-only
6483 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6484 */
6485 pUnused = findReusableFd(path, openFlags);
6486 if( pUnused ){
6487 fd = pUnused->fd;
6488 }else{
drhf3cdcdc2015-04-29 16:50:28 +00006489 pUnused = sqlite3_malloc64(sizeof(*pUnused));
drh7ed97b92010-01-20 13:07:21 +00006490 if( !pUnused ){
6491 return SQLITE_NOMEM;
6492 }
6493 }
6494 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006495 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006496 terrno = errno;
6497 if( fd<0 && errno==ENOENT && islockfile ){
6498 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006499 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006500 }
6501 }
6502 }
6503 if( fd<0 ){
6504 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006505 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006506 terrno = errno;
6507 }
6508 if( fd<0 ){
6509 if( islockfile ){
6510 return SQLITE_BUSY;
6511 }
6512 switch (terrno) {
6513 case EACCES:
6514 return SQLITE_PERM;
6515 case EIO:
6516 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6517 default:
drh9978c972010-02-23 17:36:32 +00006518 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006519 }
6520 }
6521
drhf3cdcdc2015-04-29 16:50:28 +00006522 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
drh7ed97b92010-01-20 13:07:21 +00006523 if( pNew==NULL ){
6524 rc = SQLITE_NOMEM;
6525 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006526 }
6527 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006528 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006529 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006530 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006531 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006532 pUnused->fd = fd;
6533 pUnused->flags = openFlags;
6534 pNew->pUnused = pUnused;
6535
drhc02a43a2012-01-10 23:18:38 +00006536 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006537 if( rc==SQLITE_OK ){
6538 *ppFile = pNew;
6539 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006540 }
drh7ed97b92010-01-20 13:07:21 +00006541end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006542 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006543 sqlite3_free(pNew);
6544 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006545 return rc;
6546}
6547
drh7ed97b92010-01-20 13:07:21 +00006548#ifdef SQLITE_TEST
6549/* simulate multiple hosts by creating unique hostid file paths */
6550int sqlite3_hostid_num = 0;
6551#endif
6552
6553#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6554
drh6bca6512015-04-13 23:05:28 +00006555#ifdef HAVE_GETHOSTUUID
drh0ab216a2010-07-02 17:10:40 +00006556/* Not always defined in the headers as it ought to be */
6557extern int gethostuuid(uuid_t id, const struct timespec *wait);
drh6bca6512015-04-13 23:05:28 +00006558#endif
drh0ab216a2010-07-02 17:10:40 +00006559
drh7ed97b92010-01-20 13:07:21 +00006560/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6561** bytes of writable memory.
6562*/
6563static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006564 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6565 memset(pHostID, 0, PROXY_HOSTIDLEN);
drh6bca6512015-04-13 23:05:28 +00006566#ifdef HAVE_GETHOSTUUID
drh29ecd8a2010-12-21 00:16:40 +00006567 {
drh4bf66fd2015-02-19 02:43:02 +00006568 struct timespec timeout = {1, 0}; /* 1 sec timeout */
drh29ecd8a2010-12-21 00:16:40 +00006569 if( gethostuuid(pHostID, &timeout) ){
6570 int err = errno;
6571 if( pError ){
6572 *pError = err;
6573 }
6574 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006575 }
drh7ed97b92010-01-20 13:07:21 +00006576 }
drh3d4435b2011-08-26 20:55:50 +00006577#else
6578 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006579#endif
drh7ed97b92010-01-20 13:07:21 +00006580#ifdef SQLITE_TEST
6581 /* simulate multiple hosts by creating unique hostid file paths */
6582 if( sqlite3_hostid_num != 0){
6583 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6584 }
6585#endif
6586
6587 return SQLITE_OK;
6588}
6589
6590/* The conch file contains the header, host id and lock file path
6591 */
6592#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6593#define PROXY_HEADERLEN 1 /* conch file header length */
6594#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6595#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6596
6597/*
6598** Takes an open conch file, copies the contents to a new path and then moves
6599** it back. The newly created file's file descriptor is assigned to the
6600** conch file structure and finally the original conch file descriptor is
6601** closed. Returns zero if successful.
6602*/
6603static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6604 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6605 unixFile *conchFile = pCtx->conchFile;
6606 char tPath[MAXPATHLEN];
6607 char buf[PROXY_MAXCONCHLEN];
6608 char *cPath = pCtx->conchFilePath;
6609 size_t readLen = 0;
6610 size_t pathLen = 0;
6611 char errmsg[64] = "";
6612 int fd = -1;
6613 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006614 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006615
6616 /* create a new path by replace the trailing '-conch' with '-break' */
6617 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6618 if( pathLen>MAXPATHLEN || pathLen<6 ||
6619 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006620 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006621 goto end_breaklock;
6622 }
6623 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006624 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006625 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006626 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006627 goto end_breaklock;
6628 }
6629 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006630 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006631 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006632 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006633 goto end_breaklock;
6634 }
drhe562be52011-03-02 18:01:10 +00006635 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006636 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006637 goto end_breaklock;
6638 }
6639 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006640 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006641 goto end_breaklock;
6642 }
6643 rc = 0;
6644 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006645 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006646 conchFile->h = fd;
6647 conchFile->openFlags = O_RDWR | O_CREAT;
6648
6649end_breaklock:
6650 if( rc ){
6651 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006652 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006653 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006654 }
6655 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6656 }
6657 return rc;
6658}
6659
6660/* Take the requested lock on the conch file and break a stale lock if the
6661** host id matches.
6662*/
6663static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6664 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6665 unixFile *conchFile = pCtx->conchFile;
6666 int rc = SQLITE_OK;
6667 int nTries = 0;
6668 struct timespec conchModTime;
6669
drh3d4435b2011-08-26 20:55:50 +00006670 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006671 do {
6672 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6673 nTries ++;
6674 if( rc==SQLITE_BUSY ){
6675 /* If the lock failed (busy):
6676 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6677 * 2nd try: fail if the mod time changed or host id is different, wait
6678 * 10 sec and try again
6679 * 3rd try: break the lock unless the mod time has changed.
6680 */
6681 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006682 if( osFstat(conchFile->h, &buf) ){
drh4bf66fd2015-02-19 02:43:02 +00006683 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006684 return SQLITE_IOERR_LOCK;
6685 }
6686
6687 if( nTries==1 ){
6688 conchModTime = buf.st_mtimespec;
6689 usleep(500000); /* wait 0.5 sec and try the lock again*/
6690 continue;
6691 }
6692
6693 assert( nTries>1 );
6694 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6695 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6696 return SQLITE_BUSY;
6697 }
6698
6699 if( nTries==2 ){
6700 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006701 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006702 if( len<0 ){
drh4bf66fd2015-02-19 02:43:02 +00006703 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006704 return SQLITE_IOERR_LOCK;
6705 }
6706 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6707 /* don't break the lock if the host id doesn't match */
6708 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6709 return SQLITE_BUSY;
6710 }
6711 }else{
6712 /* don't break the lock on short read or a version mismatch */
6713 return SQLITE_BUSY;
6714 }
6715 usleep(10000000); /* wait 10 sec and try the lock again */
6716 continue;
6717 }
6718
6719 assert( nTries==3 );
6720 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6721 rc = SQLITE_OK;
6722 if( lockType==EXCLUSIVE_LOCK ){
drhe6d41732015-02-21 00:49:00 +00006723 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
drh7ed97b92010-01-20 13:07:21 +00006724 }
6725 if( !rc ){
6726 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6727 }
6728 }
6729 }
6730 } while( rc==SQLITE_BUSY && nTries<3 );
6731
6732 return rc;
6733}
6734
6735/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006736** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6737** lockPath means that the lockPath in the conch file will be used if the
6738** host IDs match, or a new lock path will be generated automatically
6739** and written to the conch file.
6740*/
6741static int proxyTakeConch(unixFile *pFile){
6742 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6743
drh7ed97b92010-01-20 13:07:21 +00006744 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006745 return SQLITE_OK;
6746 }else{
6747 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006748 uuid_t myHostID;
6749 int pError = 0;
6750 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006751 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006752 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006753 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006754 int createConch = 0;
6755 int hostIdMatch = 0;
6756 int readLen = 0;
6757 int tryOldLockPath = 0;
6758 int forceNewLockPath = 0;
6759
drh308c2a52010-05-14 11:30:18 +00006760 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
drh91eb93c2015-03-03 19:56:20 +00006761 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00006762 osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006763
drh7ed97b92010-01-20 13:07:21 +00006764 rc = proxyGetHostID(myHostID, &pError);
6765 if( (rc&0xff)==SQLITE_IOERR ){
drh4bf66fd2015-02-19 02:43:02 +00006766 storeLastErrno(pFile, pError);
drh7ed97b92010-01-20 13:07:21 +00006767 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006768 }
drh7ed97b92010-01-20 13:07:21 +00006769 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006770 if( rc!=SQLITE_OK ){
6771 goto end_takeconch;
6772 }
drh7ed97b92010-01-20 13:07:21 +00006773 /* read the existing conch file */
6774 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6775 if( readLen<0 ){
6776 /* I/O error: lastErrno set by seekAndRead */
drh4bf66fd2015-02-19 02:43:02 +00006777 storeLastErrno(pFile, conchFile->lastErrno);
drh7ed97b92010-01-20 13:07:21 +00006778 rc = SQLITE_IOERR_READ;
6779 goto end_takeconch;
6780 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6781 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6782 /* a short read or version format mismatch means we need to create a new
6783 ** conch file.
6784 */
6785 createConch = 1;
6786 }
6787 /* if the host id matches and the lock path already exists in the conch
6788 ** we'll try to use the path there, if we can't open that path, we'll
6789 ** retry with a new auto-generated path
6790 */
6791 do { /* in case we need to try again for an :auto: named lock file */
6792
6793 if( !createConch && !forceNewLockPath ){
6794 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6795 PROXY_HOSTIDLEN);
6796 /* if the conch has data compare the contents */
6797 if( !pCtx->lockProxyPath ){
6798 /* for auto-named local lock file, just check the host ID and we'll
6799 ** use the local lock file path that's already in there
6800 */
6801 if( hostIdMatch ){
6802 size_t pathLen = (readLen - PROXY_PATHINDEX);
6803
6804 if( pathLen>=MAXPATHLEN ){
6805 pathLen=MAXPATHLEN-1;
6806 }
6807 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6808 lockPath[pathLen] = 0;
6809 tempLockPath = lockPath;
6810 tryOldLockPath = 1;
6811 /* create a copy of the lock path if the conch is taken */
6812 goto end_takeconch;
6813 }
6814 }else if( hostIdMatch
6815 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6816 readLen-PROXY_PATHINDEX)
6817 ){
6818 /* conch host and lock path match */
6819 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006820 }
drh7ed97b92010-01-20 13:07:21 +00006821 }
6822
6823 /* if the conch isn't writable and doesn't match, we can't take it */
6824 if( (conchFile->openFlags&O_RDWR) == 0 ){
6825 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006826 goto end_takeconch;
6827 }
drh7ed97b92010-01-20 13:07:21 +00006828
6829 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006830 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006831 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6832 tempLockPath = lockPath;
6833 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006834 }
drh7ed97b92010-01-20 13:07:21 +00006835
6836 /* update conch with host and path (this will fail if other process
6837 ** has a shared lock already), if the host id matches, use the big
6838 ** stick.
drh715ff302008-12-03 22:32:44 +00006839 */
drh7ed97b92010-01-20 13:07:21 +00006840 futimes(conchFile->h, NULL);
6841 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006842 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006843 /* We are trying for an exclusive lock but another thread in this
6844 ** same process is still holding a shared lock. */
6845 rc = SQLITE_BUSY;
6846 } else {
6847 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006848 }
drh715ff302008-12-03 22:32:44 +00006849 }else{
drh4bf66fd2015-02-19 02:43:02 +00006850 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006851 }
drh7ed97b92010-01-20 13:07:21 +00006852 if( rc==SQLITE_OK ){
6853 char writeBuffer[PROXY_MAXCONCHLEN];
6854 int writeSize = 0;
6855
6856 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6857 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6858 if( pCtx->lockProxyPath!=NULL ){
drh4bf66fd2015-02-19 02:43:02 +00006859 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
6860 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00006861 }else{
6862 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6863 }
6864 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006865 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006866 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6867 fsync(conchFile->h);
6868 /* If we created a new conch file (not just updated the contents of a
6869 ** valid conch file), try to match the permissions of the database
6870 */
6871 if( rc==SQLITE_OK && createConch ){
6872 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006873 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006874 if( err==0 ){
6875 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6876 S_IROTH|S_IWOTH);
6877 /* try to match the database file R/W permissions, ignore failure */
6878#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006879 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006880#else
drhff812312011-02-23 13:33:46 +00006881 do{
drhe562be52011-03-02 18:01:10 +00006882 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006883 }while( rc==(-1) && errno==EINTR );
6884 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006885 int code = errno;
6886 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6887 cmode, code, strerror(code));
6888 } else {
6889 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6890 }
6891 }else{
6892 int code = errno;
6893 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6894 err, code, strerror(code));
6895#endif
6896 }
drh715ff302008-12-03 22:32:44 +00006897 }
6898 }
drh7ed97b92010-01-20 13:07:21 +00006899 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6900
6901 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006902 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006903 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006904 int fd;
drh7ed97b92010-01-20 13:07:21 +00006905 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006906 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006907 }
6908 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006909 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006910 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006911 if( fd>=0 ){
6912 pFile->h = fd;
6913 }else{
drh9978c972010-02-23 17:36:32 +00006914 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006915 during locking */
6916 }
6917 }
6918 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6919 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6920 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6921 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6922 /* we couldn't create the proxy lock file with the old lock file path
6923 ** so try again via auto-naming
6924 */
6925 forceNewLockPath = 1;
6926 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006927 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006928 }
6929 }
6930 if( rc==SQLITE_OK ){
6931 /* Need to make a copy of path if we extracted the value
6932 ** from the conch file or the path was allocated on the stack
6933 */
6934 if( tempLockPath ){
6935 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6936 if( !pCtx->lockProxyPath ){
6937 rc = SQLITE_NOMEM;
6938 }
6939 }
6940 }
6941 if( rc==SQLITE_OK ){
6942 pCtx->conchHeld = 1;
6943
6944 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6945 afpLockingContext *afpCtx;
6946 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6947 afpCtx->dbPath = pCtx->lockProxyPath;
6948 }
6949 } else {
6950 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6951 }
drh308c2a52010-05-14 11:30:18 +00006952 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6953 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006954 return rc;
drh308c2a52010-05-14 11:30:18 +00006955 } while (1); /* in case we need to retry the :auto: lock file -
6956 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006957 }
6958}
6959
6960/*
6961** If pFile holds a lock on a conch file, then release that lock.
6962*/
6963static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006964 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006965 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6966 unixFile *conchFile; /* Name of the conch file */
6967
6968 pCtx = (proxyLockingContext *)pFile->lockingContext;
6969 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006970 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006971 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00006972 osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006973 if( pCtx->conchHeld>0 ){
6974 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6975 }
drh715ff302008-12-03 22:32:44 +00006976 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006977 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6978 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006979 return rc;
6980}
6981
6982/*
6983** Given the name of a database file, compute the name of its conch file.
drhf3cdcdc2015-04-29 16:50:28 +00006984** Store the conch filename in memory obtained from sqlite3_malloc64().
drh715ff302008-12-03 22:32:44 +00006985** Make *pConchPath point to the new name. Return SQLITE_OK on success
6986** or SQLITE_NOMEM if unable to obtain memory.
6987**
6988** The caller is responsible for ensuring that the allocated memory
6989** space is eventually freed.
6990**
6991** *pConchPath is set to NULL if a memory allocation error occurs.
6992*/
6993static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6994 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006995 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006996 char *conchPath; /* buffer in which to construct conch name */
6997
6998 /* Allocate space for the conch filename and initialize the name to
6999 ** the name of the original database file. */
drhf3cdcdc2015-04-29 16:50:28 +00007000 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
drh715ff302008-12-03 22:32:44 +00007001 if( conchPath==0 ){
7002 return SQLITE_NOMEM;
7003 }
7004 memcpy(conchPath, dbPath, len+1);
7005
7006 /* now insert a "." before the last / character */
7007 for( i=(len-1); i>=0; i-- ){
7008 if( conchPath[i]=='/' ){
7009 i++;
7010 break;
7011 }
7012 }
7013 conchPath[i]='.';
7014 while ( i<len ){
7015 conchPath[i+1]=dbPath[i];
7016 i++;
7017 }
7018
7019 /* append the "-conch" suffix to the file */
7020 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007021 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007022
7023 return SQLITE_OK;
7024}
7025
7026
7027/* Takes a fully configured proxy locking-style unix file and switches
7028** the local lock file path
7029*/
7030static int switchLockProxyPath(unixFile *pFile, const char *path) {
7031 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7032 char *oldPath = pCtx->lockProxyPath;
7033 int rc = SQLITE_OK;
7034
drh308c2a52010-05-14 11:30:18 +00007035 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007036 return SQLITE_BUSY;
7037 }
7038
7039 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7040 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7041 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7042 return SQLITE_OK;
7043 }else{
7044 unixFile *lockProxy = pCtx->lockProxy;
7045 pCtx->lockProxy=NULL;
7046 pCtx->conchHeld = 0;
7047 if( lockProxy!=NULL ){
7048 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7049 if( rc ) return rc;
7050 sqlite3_free(lockProxy);
7051 }
7052 sqlite3_free(oldPath);
7053 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7054 }
7055
7056 return rc;
7057}
7058
7059/*
7060** pFile is a file that has been opened by a prior xOpen call. dbPath
7061** is a string buffer at least MAXPATHLEN+1 characters in size.
7062**
7063** This routine find the filename associated with pFile and writes it
7064** int dbPath.
7065*/
7066static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007067#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007068 if( pFile->pMethod == &afpIoMethods ){
7069 /* afp style keeps a reference to the db path in the filePath field
7070 ** of the struct */
drhea678832008-12-10 19:26:22 +00007071 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh4bf66fd2015-02-19 02:43:02 +00007072 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7073 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007074 } else
drh715ff302008-12-03 22:32:44 +00007075#endif
7076 if( pFile->pMethod == &dotlockIoMethods ){
7077 /* dot lock style uses the locking context to store the dot lock
7078 ** file path */
7079 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7080 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7081 }else{
7082 /* all other styles use the locking context to store the db file path */
7083 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007084 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007085 }
7086 return SQLITE_OK;
7087}
7088
7089/*
7090** Takes an already filled in unix file and alters it so all file locking
7091** will be performed on the local proxy lock file. The following fields
7092** are preserved in the locking context so that they can be restored and
7093** the unix structure properly cleaned up at close time:
7094** ->lockingContext
7095** ->pMethod
7096*/
7097static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7098 proxyLockingContext *pCtx;
7099 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7100 char *lockPath=NULL;
7101 int rc = SQLITE_OK;
7102
drh308c2a52010-05-14 11:30:18 +00007103 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007104 return SQLITE_BUSY;
7105 }
7106 proxyGetDbPathForUnixFile(pFile, dbPath);
7107 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7108 lockPath=NULL;
7109 }else{
7110 lockPath=(char *)path;
7111 }
7112
drh308c2a52010-05-14 11:30:18 +00007113 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
drh5ac93652015-03-21 20:59:43 +00007114 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007115
drhf3cdcdc2015-04-29 16:50:28 +00007116 pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh715ff302008-12-03 22:32:44 +00007117 if( pCtx==0 ){
7118 return SQLITE_NOMEM;
7119 }
7120 memset(pCtx, 0, sizeof(*pCtx));
7121
7122 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7123 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007124 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7125 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7126 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7127 ** (c) the file system is read-only, then enable no-locking access.
7128 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7129 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7130 */
7131 struct statfs fsInfo;
7132 struct stat conchInfo;
7133 int goLockless = 0;
7134
drh99ab3b12011-03-02 15:09:07 +00007135 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007136 int err = errno;
7137 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7138 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7139 }
7140 }
7141 if( goLockless ){
7142 pCtx->conchHeld = -1; /* read only FS/ lockless */
7143 rc = SQLITE_OK;
7144 }
7145 }
drh715ff302008-12-03 22:32:44 +00007146 }
7147 if( rc==SQLITE_OK && lockPath ){
7148 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7149 }
7150
7151 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007152 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7153 if( pCtx->dbPath==NULL ){
7154 rc = SQLITE_NOMEM;
7155 }
7156 }
7157 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007158 /* all memory is allocated, proxys are created and assigned,
7159 ** switch the locking context and pMethod then return.
7160 */
drh715ff302008-12-03 22:32:44 +00007161 pCtx->oldLockingContext = pFile->lockingContext;
7162 pFile->lockingContext = pCtx;
7163 pCtx->pOldMethod = pFile->pMethod;
7164 pFile->pMethod = &proxyIoMethods;
7165 }else{
7166 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007167 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007168 sqlite3_free(pCtx->conchFile);
7169 }
drhd56b1212010-08-11 06:14:15 +00007170 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007171 sqlite3_free(pCtx->conchFilePath);
7172 sqlite3_free(pCtx);
7173 }
drh308c2a52010-05-14 11:30:18 +00007174 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7175 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007176 return rc;
7177}
7178
7179
7180/*
7181** This routine handles sqlite3_file_control() calls that are specific
7182** to proxy locking.
7183*/
7184static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7185 switch( op ){
drh4bf66fd2015-02-19 02:43:02 +00007186 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007187 unixFile *pFile = (unixFile*)id;
7188 if( pFile->pMethod == &proxyIoMethods ){
7189 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7190 proxyTakeConch(pFile);
7191 if( pCtx->lockProxyPath ){
7192 *(const char **)pArg = pCtx->lockProxyPath;
7193 }else{
7194 *(const char **)pArg = ":auto: (not held)";
7195 }
7196 } else {
7197 *(const char **)pArg = NULL;
7198 }
7199 return SQLITE_OK;
7200 }
drh4bf66fd2015-02-19 02:43:02 +00007201 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007202 unixFile *pFile = (unixFile*)id;
7203 int rc = SQLITE_OK;
7204 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7205 if( pArg==NULL || (const char *)pArg==0 ){
7206 if( isProxyStyle ){
drh4bf66fd2015-02-19 02:43:02 +00007207 /* turn off proxy locking - not supported. If support is added for
7208 ** switching proxy locking mode off then it will need to fail if
7209 ** the journal mode is WAL mode.
7210 */
drh715ff302008-12-03 22:32:44 +00007211 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7212 }else{
7213 /* turn off proxy locking - already off - NOOP */
7214 rc = SQLITE_OK;
7215 }
7216 }else{
7217 const char *proxyPath = (const char *)pArg;
7218 if( isProxyStyle ){
7219 proxyLockingContext *pCtx =
7220 (proxyLockingContext*)pFile->lockingContext;
7221 if( !strcmp(pArg, ":auto:")
7222 || (pCtx->lockProxyPath &&
7223 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7224 ){
7225 rc = SQLITE_OK;
7226 }else{
7227 rc = switchLockProxyPath(pFile, proxyPath);
7228 }
7229 }else{
7230 /* turn on proxy file locking */
7231 rc = proxyTransformUnixFile(pFile, proxyPath);
7232 }
7233 }
7234 return rc;
7235 }
7236 default: {
7237 assert( 0 ); /* The call assures that only valid opcodes are sent */
7238 }
7239 }
7240 /*NOTREACHED*/
7241 return SQLITE_ERROR;
7242}
7243
7244/*
7245** Within this division (the proxying locking implementation) the procedures
7246** above this point are all utilities. The lock-related methods of the
7247** proxy-locking sqlite3_io_method object follow.
7248*/
7249
7250
7251/*
7252** This routine checks if there is a RESERVED lock held on the specified
7253** file by this or any other process. If such a lock is held, set *pResOut
7254** to a non-zero value otherwise *pResOut is set to zero. The return value
7255** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7256*/
7257static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7258 unixFile *pFile = (unixFile*)id;
7259 int rc = proxyTakeConch(pFile);
7260 if( rc==SQLITE_OK ){
7261 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007262 if( pCtx->conchHeld>0 ){
7263 unixFile *proxy = pCtx->lockProxy;
7264 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7265 }else{ /* conchHeld < 0 is lockless */
7266 pResOut=0;
7267 }
drh715ff302008-12-03 22:32:44 +00007268 }
7269 return rc;
7270}
7271
7272/*
drh308c2a52010-05-14 11:30:18 +00007273** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007274** of the following:
7275**
7276** (1) SHARED_LOCK
7277** (2) RESERVED_LOCK
7278** (3) PENDING_LOCK
7279** (4) EXCLUSIVE_LOCK
7280**
7281** Sometimes when requesting one lock state, additional lock states
7282** are inserted in between. The locking might fail on one of the later
7283** transitions leaving the lock state different from what it started but
7284** still short of its goal. The following chart shows the allowed
7285** transitions and the inserted intermediate states:
7286**
7287** UNLOCKED -> SHARED
7288** SHARED -> RESERVED
7289** SHARED -> (PENDING) -> EXCLUSIVE
7290** RESERVED -> (PENDING) -> EXCLUSIVE
7291** PENDING -> EXCLUSIVE
7292**
7293** This routine will only increase a lock. Use the sqlite3OsUnlock()
7294** routine to lower a locking level.
7295*/
drh308c2a52010-05-14 11:30:18 +00007296static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007297 unixFile *pFile = (unixFile*)id;
7298 int rc = proxyTakeConch(pFile);
7299 if( rc==SQLITE_OK ){
7300 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007301 if( pCtx->conchHeld>0 ){
7302 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007303 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7304 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007305 }else{
7306 /* conchHeld < 0 is lockless */
7307 }
drh715ff302008-12-03 22:32:44 +00007308 }
7309 return rc;
7310}
7311
7312
7313/*
drh308c2a52010-05-14 11:30:18 +00007314** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007315** must be either NO_LOCK or SHARED_LOCK.
7316**
7317** If the locking level of the file descriptor is already at or below
7318** the requested locking level, this routine is a no-op.
7319*/
drh308c2a52010-05-14 11:30:18 +00007320static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007321 unixFile *pFile = (unixFile*)id;
7322 int rc = proxyTakeConch(pFile);
7323 if( rc==SQLITE_OK ){
7324 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007325 if( pCtx->conchHeld>0 ){
7326 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007327 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7328 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007329 }else{
7330 /* conchHeld < 0 is lockless */
7331 }
drh715ff302008-12-03 22:32:44 +00007332 }
7333 return rc;
7334}
7335
7336/*
7337** Close a file that uses proxy locks.
7338*/
7339static int proxyClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00007340 if( ALWAYS(id) ){
drh715ff302008-12-03 22:32:44 +00007341 unixFile *pFile = (unixFile*)id;
7342 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7343 unixFile *lockProxy = pCtx->lockProxy;
7344 unixFile *conchFile = pCtx->conchFile;
7345 int rc = SQLITE_OK;
7346
7347 if( lockProxy ){
7348 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7349 if( rc ) return rc;
7350 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7351 if( rc ) return rc;
7352 sqlite3_free(lockProxy);
7353 pCtx->lockProxy = 0;
7354 }
7355 if( conchFile ){
7356 if( pCtx->conchHeld ){
7357 rc = proxyReleaseConch(pFile);
7358 if( rc ) return rc;
7359 }
7360 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7361 if( rc ) return rc;
7362 sqlite3_free(conchFile);
7363 }
drhd56b1212010-08-11 06:14:15 +00007364 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007365 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007366 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007367 /* restore the original locking context and pMethod then close it */
7368 pFile->lockingContext = pCtx->oldLockingContext;
7369 pFile->pMethod = pCtx->pOldMethod;
7370 sqlite3_free(pCtx);
7371 return pFile->pMethod->xClose(id);
7372 }
7373 return SQLITE_OK;
7374}
7375
7376
7377
drhd2cb50b2009-01-09 21:41:17 +00007378#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007379/*
7380** The proxy locking style is intended for use with AFP filesystems.
7381** And since AFP is only supported on MacOSX, the proxy locking is also
7382** restricted to MacOSX.
7383**
7384**
7385******************* End of the proxy lock implementation **********************
7386******************************************************************************/
7387
drh734c9862008-11-28 15:37:20 +00007388/*
danielk1977e339d652008-06-28 11:23:00 +00007389** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007390**
7391** This routine registers all VFS implementations for unix-like operating
7392** systems. This routine, and the sqlite3_os_end() routine that follows,
7393** should be the only routines in this file that are visible from other
7394** files.
drh6b9d6dd2008-12-03 19:34:47 +00007395**
7396** This routine is called once during SQLite initialization and by a
7397** single thread. The memory allocation and mutex subsystems have not
7398** necessarily been initialized when this routine is called, and so they
7399** should not be used.
drh153c62c2007-08-24 03:51:33 +00007400*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007401int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007402 /*
7403 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007404 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7405 ** to the "finder" function. (pAppData is a pointer to a pointer because
7406 ** silly C90 rules prohibit a void* from being cast to a function pointer
7407 ** and so we have to go through the intermediate pointer to avoid problems
7408 ** when compiling with -pedantic-errors on GCC.)
7409 **
7410 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007411 ** finder-function. The finder-function returns a pointer to the
7412 ** sqlite_io_methods object that implements the desired locking
7413 ** behaviors. See the division above that contains the IOMETHODS
7414 ** macro for addition information on finder-functions.
7415 **
7416 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7417 ** object. But the "autolockIoFinder" available on MacOSX does a little
7418 ** more than that; it looks at the filesystem type that hosts the
7419 ** database file and tries to choose an locking method appropriate for
7420 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007421 */
drh7708e972008-11-29 00:56:52 +00007422 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007423 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007424 sizeof(unixFile), /* szOsFile */ \
7425 MAX_PATHNAME, /* mxPathname */ \
7426 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007427 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007428 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007429 unixOpen, /* xOpen */ \
7430 unixDelete, /* xDelete */ \
7431 unixAccess, /* xAccess */ \
7432 unixFullPathname, /* xFullPathname */ \
7433 unixDlOpen, /* xDlOpen */ \
7434 unixDlError, /* xDlError */ \
7435 unixDlSym, /* xDlSym */ \
7436 unixDlClose, /* xDlClose */ \
7437 unixRandomness, /* xRandomness */ \
7438 unixSleep, /* xSleep */ \
7439 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007440 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007441 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007442 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007443 unixGetSystemCall, /* xGetSystemCall */ \
7444 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007445 }
7446
drh6b9d6dd2008-12-03 19:34:47 +00007447 /*
7448 ** All default VFSes for unix are contained in the following array.
7449 **
7450 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7451 ** by the SQLite core when the VFS is registered. So the following
7452 ** array cannot be const.
7453 */
danielk1977e339d652008-06-28 11:23:00 +00007454 static sqlite3_vfs aVfs[] = {
drhe89b2912015-03-03 20:42:01 +00007455#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007456 UNIXVFS("unix", autolockIoFinder ),
drhe89b2912015-03-03 20:42:01 +00007457#elif OS_VXWORKS
7458 UNIXVFS("unix", vxworksIoFinder ),
drh7708e972008-11-29 00:56:52 +00007459#else
7460 UNIXVFS("unix", posixIoFinder ),
7461#endif
7462 UNIXVFS("unix-none", nolockIoFinder ),
7463 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007464 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007465#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007466 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007467#endif
drhe89b2912015-03-03 20:42:01 +00007468#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007469 UNIXVFS("unix-posix", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007470#endif
drhe89b2912015-03-03 20:42:01 +00007471#if SQLITE_ENABLE_LOCKING_STYLE
7472 UNIXVFS("unix-flock", flockIoFinder ),
chw78a13182009-04-07 05:35:03 +00007473#endif
drhd2cb50b2009-01-09 21:41:17 +00007474#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007475 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007476 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007477 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007478#endif
drh153c62c2007-08-24 03:51:33 +00007479 };
drh6b9d6dd2008-12-03 19:34:47 +00007480 unsigned int i; /* Loop counter */
7481
drh2aa5a002011-04-13 13:42:25 +00007482 /* Double-check that the aSyscall[] array has been constructed
7483 ** correctly. See ticket [bb3a86e890c8e96ab] */
drh6226ca22015-11-24 15:06:28 +00007484 assert( ArraySize(aSyscall)==27 );
drh2aa5a002011-04-13 13:42:25 +00007485
drh6b9d6dd2008-12-03 19:34:47 +00007486 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007487 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007488 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007489 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007490 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007491}
danielk1977e339d652008-06-28 11:23:00 +00007492
7493/*
drh6b9d6dd2008-12-03 19:34:47 +00007494** Shutdown the operating system interface.
7495**
7496** Some operating systems might need to do some cleanup in this routine,
7497** to release dynamically allocated objects. But not on unix.
7498** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007499*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007500int sqlite3_os_end(void){
7501 return SQLITE_OK;
7502}
drhdce8bdb2007-08-16 13:01:44 +00007503
danielk197729bafea2008-06-26 10:41:19 +00007504#endif /* SQLITE_OS_UNIX */