blob: 38c8d7b61918921267dcb8ccde78d26610173da5 [file] [log] [blame]
drhbbd42a62004-05-22 17:41:58 +00001/*
2** 2004 May 22
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11******************************************************************************
12**
drh734c9862008-11-28 15:37:20 +000013** This file contains the VFS implementation for unix-like operating systems
14** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
danielk1977822a5162008-05-16 04:51:54 +000015**
drh734c9862008-11-28 15:37:20 +000016** There are actually several different VFS implementations in this file.
17** The differences are in the way that file locking is done. The default
18** implementation uses Posix Advisory Locks. Alternative implementations
19** use flock(), dot-files, various proprietary locking schemas, or simply
20** skip locking all together.
21**
drh9b35ea62008-11-29 02:20:26 +000022** This source file is organized into divisions where the logic for various
drh734c9862008-11-28 15:37:20 +000023** subfunctions is contained within the appropriate division. PLEASE
24** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
25** in the correct division and should be clearly labeled.
26**
drh6b9d6dd2008-12-03 19:34:47 +000027** The layout of divisions is as follows:
drh734c9862008-11-28 15:37:20 +000028**
29** * General-purpose declarations and utility functions.
30** * Unique file ID logic used by VxWorks.
drh715ff302008-12-03 22:32:44 +000031** * Various locking primitive implementations (all except proxy locking):
drh734c9862008-11-28 15:37:20 +000032** + for Posix Advisory Locks
33** + for no-op locks
34** + for dot-file locks
35** + for flock() locking
36** + for named semaphore locks (VxWorks only)
37** + for AFP filesystem locks (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000038** * sqlite3_file methods not associated with locking.
39** * Definitions of sqlite3_io_methods objects for all locking
40** methods plus "finder" functions for each locking method.
drh6b9d6dd2008-12-03 19:34:47 +000041** * sqlite3_vfs method implementations.
drh715ff302008-12-03 22:32:44 +000042** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000043** * Definitions of sqlite3_vfs objects for all locking methods
44** plus implementations of sqlite3_os_init() and sqlite3_os_end().
drhbbd42a62004-05-22 17:41:58 +000045*/
drhbbd42a62004-05-22 17:41:58 +000046#include "sqliteInt.h"
danielk197729bafea2008-06-26 10:41:19 +000047#if SQLITE_OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000048
danielk1977e339d652008-06-28 11:23:00 +000049/*
drh6b9d6dd2008-12-03 19:34:47 +000050** There are various methods for file locking used for concurrency
51** control:
danielk1977e339d652008-06-28 11:23:00 +000052**
drh734c9862008-11-28 15:37:20 +000053** 1. POSIX locking (the default),
54** 2. No locking,
55** 3. Dot-file locking,
56** 4. flock() locking,
57** 5. AFP locking (OSX only),
58** 6. Named POSIX semaphores (VXWorks only),
59** 7. proxy locking. (OSX only)
60**
61** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
62** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
63** selection of the appropriate locking style based on the filesystem
64** where the database is located.
danielk1977e339d652008-06-28 11:23:00 +000065*/
drh40bbb0a2008-09-23 10:23:26 +000066#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
drhd2cb50b2009-01-09 21:41:17 +000067# if defined(__APPLE__)
drh40bbb0a2008-09-23 10:23:26 +000068# define SQLITE_ENABLE_LOCKING_STYLE 1
69# else
70# define SQLITE_ENABLE_LOCKING_STYLE 0
71# endif
72#endif
drhbfe66312006-10-03 17:40:40 +000073
drh9cbe6352005-11-29 03:13:21 +000074/*
drh9cbe6352005-11-29 03:13:21 +000075** standard include files.
76*/
77#include <sys/types.h>
78#include <sys/stat.h>
79#include <fcntl.h>
80#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +000081#include <time.h>
drh19e2d372005-08-29 23:00:03 +000082#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +000083#include <errno.h>
dan32c12fe2013-05-02 17:37:31 +000084#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drh91be7dc2014-08-11 13:53:30 +000085# include <sys/mman.h>
drhb469f462010-12-22 21:48:50 +000086#endif
drh1da88f02011-12-17 16:09:16 +000087
drhe89b2912015-03-03 20:42:01 +000088#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +000089# include <sys/ioctl.h>
drhe89b2912015-03-03 20:42:01 +000090# include <sys/file.h>
91# include <sys/param.h>
drhbfe66312006-10-03 17:40:40 +000092#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +000093
drh6bca6512015-04-13 23:05:28 +000094#if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
95 (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
96# if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
97 && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
98# define HAVE_GETHOSTUUID 1
99# else
100# warning "gethostuuid() is disabled."
101# endif
102#endif
103
104
drhe89b2912015-03-03 20:42:01 +0000105#if OS_VXWORKS
106# include <sys/ioctl.h>
107# include <semaphore.h>
108# include <limits.h>
109#endif /* OS_VXWORKS */
110
111#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh84a2bf62010-03-05 13:41:06 +0000112# include <sys/mount.h>
113#endif
114
drhdbe4b882011-06-20 18:00:17 +0000115#ifdef HAVE_UTIME
116# include <utime.h>
117#endif
118
drh9cbe6352005-11-29 03:13:21 +0000119/*
drh7ed97b92010-01-20 13:07:21 +0000120** Allowed values of unixFile.fsFlags
121*/
122#define SQLITE_FSFLAGS_IS_MSDOS 0x1
123
124/*
drhf1a221e2006-01-15 17:27:17 +0000125** If we are to be thread-safe, include the pthreads header and define
126** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000127*/
drhd677b3d2007-08-20 22:48:41 +0000128#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000129# include <pthread.h>
130# define SQLITE_UNIX_THREADS 1
131#endif
132
133/*
134** Default permissions when creating a new file
135*/
136#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
137# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
138#endif
139
danielk1977b4b47412007-08-17 15:53:36 +0000140/*
drh5adc60b2012-04-14 13:25:11 +0000141** Default permissions when creating auto proxy dir
142*/
aswiftaebf4132008-11-21 00:10:35 +0000143#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
144# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
145#endif
146
147/*
danielk1977b4b47412007-08-17 15:53:36 +0000148** Maximum supported path-length.
149*/
150#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000151
drh91eb93c2015-03-03 19:56:20 +0000152/* Always cast the getpid() return type for compatibility with
153** kernel modules in VxWorks. */
154#define osGetpid(X) (pid_t)getpid()
155
drh734c9862008-11-28 15:37:20 +0000156/*
drh734c9862008-11-28 15:37:20 +0000157** Only set the lastErrno if the error code is a real error and not
158** a normal expected return code of SQLITE_BUSY or SQLITE_OK
159*/
160#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
161
drhd91c68f2010-05-14 14:52:25 +0000162/* Forward references */
163typedef struct unixShm unixShm; /* Connection shared memory */
164typedef struct unixShmNode unixShmNode; /* Shared memory instance */
165typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
166typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000167
168/*
dane946c392009-08-22 11:39:46 +0000169** Sometimes, after a file handle is closed by SQLite, the file descriptor
170** cannot be closed immediately. In these cases, instances of the following
171** structure are used to store the file descriptor while waiting for an
172** opportunity to either close or reuse it.
173*/
dane946c392009-08-22 11:39:46 +0000174struct UnixUnusedFd {
175 int fd; /* File descriptor to close */
176 int flags; /* Flags this file descriptor was opened with */
177 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
178};
179
180/*
drh9b35ea62008-11-29 02:20:26 +0000181** The unixFile structure is subclass of sqlite3_file specific to the unix
182** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000183*/
drh054889e2005-11-30 03:20:31 +0000184typedef struct unixFile unixFile;
185struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000186 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhde60fc22011-12-14 17:53:36 +0000187 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
drhd91c68f2010-05-14 14:52:25 +0000188 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000189 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000190 unsigned char eFileLock; /* The type of lock held on this fd */
drh3ee34842012-02-11 21:21:17 +0000191 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000192 int lastErrno; /* The unix errno from last I/O error */
193 void *lockingContext; /* Locking style specific state */
194 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000195 const char *zPath; /* Name of the file */
196 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000197 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
mistachkine98844f2013-08-24 00:59:24 +0000198#if SQLITE_MAX_MMAP_SIZE>0
drh0d0614b2013-03-25 23:09:28 +0000199 int nFetchOut; /* Number of outstanding xFetch refs */
200 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
drh9b4c59f2013-04-15 17:03:42 +0000201 sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
202 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
drh0d0614b2013-03-25 23:09:28 +0000203 void *pMapRegion; /* Memory mapped region */
mistachkine98844f2013-08-24 00:59:24 +0000204#endif
drh537dddf2012-10-26 13:46:24 +0000205#ifdef __QNXNTO__
206 int sectorSize; /* Device sector size */
207 int deviceCharacteristics; /* Precomputed device characteristics */
208#endif
drh08c6d442009-02-09 17:34:07 +0000209#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000210 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000211#endif
drh7ed97b92010-01-20 13:07:21 +0000212#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000213 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000214#endif
215#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000216 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000217#endif
drhd3d8c042012-05-29 17:02:40 +0000218#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +0000219 /* The next group of variables are used to track whether or not the
220 ** transaction counter in bytes 24-27 of database files are updated
221 ** whenever any part of the database changes. An assertion fault will
222 ** occur if a file is updated without also updating the transaction
223 ** counter. This test is made to avoid new problems similar to the
224 ** one described by ticket #3584.
225 */
226 unsigned char transCntrChng; /* True if the transaction counter changed */
227 unsigned char dbUpdate; /* True if any part of database file changed */
228 unsigned char inNormalWrite; /* True if in a normal write operation */
danf23da962013-03-23 21:00:41 +0000229
drh8f941bc2009-01-14 23:03:40 +0000230#endif
danf23da962013-03-23 21:00:41 +0000231
danielk1977967a4a12007-08-20 14:23:44 +0000232#ifdef SQLITE_TEST
233 /* In test mode, increase the size of this structure a bit so that
234 ** it is larger than the struct CrashFile defined in test6.c.
235 */
236 char aPadding[32];
237#endif
drh9cbe6352005-11-29 03:13:21 +0000238};
239
drhb00d8622014-01-01 15:18:36 +0000240/* This variable holds the process id (pid) from when the xRandomness()
241** method was called. If xOpen() is called from a different process id,
242** indicating that a fork() has occurred, the PRNG will be reset.
243*/
drh8cd5b252015-03-02 22:06:43 +0000244static pid_t randomnessPid = 0;
drhb00d8622014-01-01 15:18:36 +0000245
drh0ccebe72005-06-07 22:22:50 +0000246/*
drha7e61d82011-03-12 17:02:57 +0000247** Allowed values for the unixFile.ctrlFlags bitmask:
248*/
drhf0b190d2011-07-26 16:03:07 +0000249#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
250#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
251#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000252#ifndef SQLITE_DISABLE_DIRSYNC
253# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
254#else
255# define UNIXFILE_DIRSYNC 0x00
256#endif
drhcb15f352011-12-23 01:04:17 +0000257#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
drhc02a43a2012-01-10 23:18:38 +0000258#define UNIXFILE_DELETE 0x20 /* Delete on close */
259#define UNIXFILE_URI 0x40 /* Filename might have query parameters */
260#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
drha7e61d82011-03-12 17:02:57 +0000261
262/*
drh198bf392006-01-06 21:52:49 +0000263** Include code that is common to all os_*.c files
264*/
265#include "os_common.h"
266
267/*
drh0ccebe72005-06-07 22:22:50 +0000268** Define various macros that are missing from some systems.
269*/
drhbbd42a62004-05-22 17:41:58 +0000270#ifndef O_LARGEFILE
271# define O_LARGEFILE 0
272#endif
273#ifdef SQLITE_DISABLE_LFS
274# undef O_LARGEFILE
275# define O_LARGEFILE 0
276#endif
277#ifndef O_NOFOLLOW
278# define O_NOFOLLOW 0
279#endif
280#ifndef O_BINARY
281# define O_BINARY 0
282#endif
283
284/*
drh2b4b5962005-06-15 17:47:55 +0000285** The threadid macro resolves to the thread-id or to 0. Used for
286** testing and debugging only.
287*/
drhd677b3d2007-08-20 22:48:41 +0000288#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000289#define threadid pthread_self()
290#else
291#define threadid 0
292#endif
293
drh99ab3b12011-03-02 15:09:07 +0000294/*
dane6ecd662013-04-01 17:56:59 +0000295** HAVE_MREMAP defaults to true on Linux and false everywhere else.
296*/
297#if !defined(HAVE_MREMAP)
298# if defined(__linux__) && defined(_GNU_SOURCE)
299# define HAVE_MREMAP 1
300# else
301# define HAVE_MREMAP 0
302# endif
303#endif
304
305/*
dan2ee53412014-09-06 16:49:40 +0000306** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
307** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
308*/
309#ifdef __ANDROID__
310# define lseek lseek64
311#endif
312
313/*
drh9a3baf12011-04-25 18:01:27 +0000314** Different Unix systems declare open() in different ways. Same use
315** open(const char*,int,mode_t). Others use open(const char*,int,...).
316** The difference is important when using a pointer to the function.
317**
318** The safest way to deal with the problem is to always use this wrapper
319** which always has the same well-defined interface.
320*/
321static int posixOpen(const char *zFile, int flags, int mode){
322 return open(zFile, flags, mode);
323}
324
drh90315a22011-08-10 01:52:12 +0000325/* Forward reference */
326static int openDirectory(const char*, int*);
danbc760632014-03-20 09:42:09 +0000327static int unixGetpagesize(void);
drh90315a22011-08-10 01:52:12 +0000328
drh9a3baf12011-04-25 18:01:27 +0000329/*
drh99ab3b12011-03-02 15:09:07 +0000330** Many system calls are accessed through pointer-to-functions so that
331** they may be overridden at runtime to facilitate fault injection during
332** testing and sandboxing. The following array holds the names and pointers
333** to all overrideable system calls.
334*/
335static struct unix_syscall {
mistachkin48864df2013-03-21 21:20:32 +0000336 const char *zName; /* Name of the system call */
drh58ad5802011-03-23 22:02:23 +0000337 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
338 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000339} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000340 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
341#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000342
drh58ad5802011-03-23 22:02:23 +0000343 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000344#define osClose ((int(*)(int))aSyscall[1].pCurrent)
345
drh58ad5802011-03-23 22:02:23 +0000346 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000347#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
348
drh58ad5802011-03-23 22:02:23 +0000349 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000350#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
351
drh58ad5802011-03-23 22:02:23 +0000352 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000353#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
354
355/*
356** The DJGPP compiler environment looks mostly like Unix, but it
357** lacks the fcntl() system call. So redefine fcntl() to be something
358** that always succeeds. This means that locking does not occur under
359** DJGPP. But it is DOS - what did you expect?
360*/
361#ifdef __DJGPP__
362 { "fstat", 0, 0 },
363#define osFstat(a,b,c) 0
364#else
drh58ad5802011-03-23 22:02:23 +0000365 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000366#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
367#endif
368
drh58ad5802011-03-23 22:02:23 +0000369 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000370#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
371
drh58ad5802011-03-23 22:02:23 +0000372 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000373#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000374
drh58ad5802011-03-23 22:02:23 +0000375 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000376#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
377
drhe89b2912015-03-03 20:42:01 +0000378#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000379 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000380#else
drh58ad5802011-03-23 22:02:23 +0000381 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000382#endif
383#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
384
385#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000386 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000387#else
drh58ad5802011-03-23 22:02:23 +0000388 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000389#endif
390#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
391
drh58ad5802011-03-23 22:02:23 +0000392 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000393#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
394
drhe89b2912015-03-03 20:42:01 +0000395#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000396 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000397#else
drh58ad5802011-03-23 22:02:23 +0000398 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000399#endif
400#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
401 aSyscall[12].pCurrent)
402
403#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000404 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000405#else
drh58ad5802011-03-23 22:02:23 +0000406 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000407#endif
408#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
409 aSyscall[13].pCurrent)
410
drh6226ca22015-11-24 15:06:28 +0000411 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000412#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000413
414#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000415 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000416#else
drh58ad5802011-03-23 22:02:23 +0000417 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000418#endif
dan0fd7d862011-03-29 10:04:23 +0000419#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000420
drh036ac7f2011-08-08 23:18:05 +0000421 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
422#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
423
drh90315a22011-08-10 01:52:12 +0000424 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
425#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
426
drh9ef6bc42011-11-04 02:24:02 +0000427 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
428#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
429
430 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
431#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
432
drh6226ca22015-11-24 15:06:28 +0000433 { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
dand3eaebd2012-02-13 08:50:23 +0000434#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000435
drh6226ca22015-11-24 15:06:28 +0000436 { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
437#define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
438
dan4dd51442013-08-26 14:30:25 +0000439#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
dan893c0ff2013-03-25 19:05:07 +0000440 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
drh6226ca22015-11-24 15:06:28 +0000441#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
dan893c0ff2013-03-25 19:05:07 +0000442
drhd1ab8062013-03-25 20:50:25 +0000443 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
drh6226ca22015-11-24 15:06:28 +0000444#define osMunmap ((void*(*)(void*,size_t))aSyscall[23].pCurrent)
drhd1ab8062013-03-25 20:50:25 +0000445
dane6ecd662013-04-01 17:56:59 +0000446#if HAVE_MREMAP
drhd1ab8062013-03-25 20:50:25 +0000447 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
448#else
449 { "mremap", (sqlite3_syscall_ptr)0, 0 },
450#endif
drh6226ca22015-11-24 15:06:28 +0000451#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
452
danbc760632014-03-20 09:42:09 +0000453 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
drh6226ca22015-11-24 15:06:28 +0000454#define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
danbc760632014-03-20 09:42:09 +0000455
dan245fdc62015-10-31 17:58:33 +0000456 { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
drh6226ca22015-11-24 15:06:28 +0000457#define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
dan245fdc62015-10-31 17:58:33 +0000458
dan702eec12014-06-23 10:04:58 +0000459#endif
460
drhe562be52011-03-02 18:01:10 +0000461}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000462
drh6226ca22015-11-24 15:06:28 +0000463
464/*
465** On some systems, calls to fchown() will trigger a message in a security
466** log if they come from non-root processes. So avoid calling fchown() if
467** we are not running as root.
468*/
469static int robustFchown(int fd, uid_t uid, gid_t gid){
470#if OS_VXWORKS
471 return 0;
472#else
473 return osGeteuid() ? 0 : osFchown(fd,uid,gid);
474#endif
475}
476
drh99ab3b12011-03-02 15:09:07 +0000477/*
478** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000479** "unix" VFSes. Return SQLITE_OK opon successfully updating the
480** system call pointer, or SQLITE_NOTFOUND if there is no configurable
481** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000482*/
483static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000484 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
485 const char *zName, /* Name of system call to override */
486 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000487){
drh58ad5802011-03-23 22:02:23 +0000488 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000489 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000490
491 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000492 if( zName==0 ){
493 /* If no zName is given, restore all system calls to their default
494 ** settings and return NULL
495 */
dan51438a72011-04-02 17:00:47 +0000496 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000497 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
498 if( aSyscall[i].pDefault ){
499 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000500 }
501 }
502 }else{
503 /* If zName is specified, operate on only the one system call
504 ** specified.
505 */
506 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
507 if( strcmp(zName, aSyscall[i].zName)==0 ){
508 if( aSyscall[i].pDefault==0 ){
509 aSyscall[i].pDefault = aSyscall[i].pCurrent;
510 }
drh1df30962011-03-02 19:06:42 +0000511 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000512 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
513 aSyscall[i].pCurrent = pNewFunc;
514 break;
515 }
516 }
517 }
518 return rc;
519}
520
drh1df30962011-03-02 19:06:42 +0000521/*
522** Return the value of a system call. Return NULL if zName is not a
523** recognized system call name. NULL is also returned if the system call
524** is currently undefined.
525*/
drh58ad5802011-03-23 22:02:23 +0000526static sqlite3_syscall_ptr unixGetSystemCall(
527 sqlite3_vfs *pNotUsed,
528 const char *zName
529){
530 unsigned int i;
531
532 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000533 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
534 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
535 }
536 return 0;
537}
538
539/*
540** Return the name of the first system call after zName. If zName==NULL
541** then return the name of the first system call. Return NULL if zName
542** is the last system call or if zName is not the name of a valid
543** system call.
544*/
545static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000546 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000547
548 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000549 if( zName ){
550 for(i=0; i<ArraySize(aSyscall)-1; i++){
551 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000552 }
553 }
dan0fd7d862011-03-29 10:04:23 +0000554 for(i++; i<ArraySize(aSyscall); i++){
555 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000556 }
557 return 0;
558}
559
drhad4f1e52011-03-04 15:43:57 +0000560/*
drh77a3fdc2013-08-30 14:24:12 +0000561** Do not accept any file descriptor less than this value, in order to avoid
562** opening database file using file descriptors that are commonly used for
563** standard input, output, and error.
564*/
565#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
566# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
567#endif
568
569/*
drh8c815d12012-02-13 20:16:37 +0000570** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000571** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000572**
573** If the file creation mode "m" is 0 then set it to the default for
574** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
575** 0644) as modified by the system umask. If m is not 0, then
576** make the file creation mode be exactly m ignoring the umask.
577**
578** The m parameter will be non-zero only when creating -wal, -journal,
579** and -shm files. We want those files to have *exactly* the same
580** permissions as their original database, unadulterated by the umask.
581** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
582** transaction crashes and leaves behind hot journals, then any
583** process that is able to write to the database will also be able to
584** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000585*/
drh8c815d12012-02-13 20:16:37 +0000586static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000587 int fd;
drhe1186ab2013-01-04 20:45:13 +0000588 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5128d002013-08-30 06:20:23 +0000589 while(1){
drh5adc60b2012-04-14 13:25:11 +0000590#if defined(O_CLOEXEC)
591 fd = osOpen(z,f|O_CLOEXEC,m2);
592#else
593 fd = osOpen(z,f,m2);
594#endif
drh5128d002013-08-30 06:20:23 +0000595 if( fd<0 ){
596 if( errno==EINTR ) continue;
597 break;
598 }
drh77a3fdc2013-08-30 14:24:12 +0000599 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
drh5128d002013-08-30 06:20:23 +0000600 osClose(fd);
601 sqlite3_log(SQLITE_WARNING,
602 "attempt to open \"%s\" as file descriptor %d", z, fd);
603 fd = -1;
604 if( osOpen("/dev/null", f, m)<0 ) break;
605 }
drhe1186ab2013-01-04 20:45:13 +0000606 if( fd>=0 ){
607 if( m!=0 ){
608 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000609 if( osFstat(fd, &statbuf)==0
610 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000611 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000612 ){
drhe1186ab2013-01-04 20:45:13 +0000613 osFchmod(fd, m);
614 }
615 }
drh5adc60b2012-04-14 13:25:11 +0000616#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000617 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000618#endif
drhe1186ab2013-01-04 20:45:13 +0000619 }
drh5adc60b2012-04-14 13:25:11 +0000620 return fd;
drhad4f1e52011-03-04 15:43:57 +0000621}
danielk197713adf8a2004-06-03 16:08:41 +0000622
drh107886a2008-11-21 22:21:50 +0000623/*
dan9359c7b2009-08-21 08:29:10 +0000624** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000625** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000626** vxworksFileId objects used by this file, all of which may be
627** shared by multiple threads.
628**
629** Function unixMutexHeld() is used to assert() that the global mutex
630** is held when required. This function is only used as part of assert()
631** statements. e.g.
632**
633** unixEnterMutex()
634** assert( unixMutexHeld() );
635** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000636*/
637static void unixEnterMutex(void){
mistachkin93de6532015-07-03 21:38:09 +0000638 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
drh107886a2008-11-21 22:21:50 +0000639}
640static void unixLeaveMutex(void){
mistachkin93de6532015-07-03 21:38:09 +0000641 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
drh107886a2008-11-21 22:21:50 +0000642}
dan9359c7b2009-08-21 08:29:10 +0000643#ifdef SQLITE_DEBUG
644static int unixMutexHeld(void) {
mistachkin93de6532015-07-03 21:38:09 +0000645 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
dan9359c7b2009-08-21 08:29:10 +0000646}
647#endif
drh107886a2008-11-21 22:21:50 +0000648
drh734c9862008-11-28 15:37:20 +0000649
mistachkinfb383e92015-04-16 03:24:38 +0000650#ifdef SQLITE_HAVE_OS_TRACE
drh734c9862008-11-28 15:37:20 +0000651/*
652** Helper function for printing out trace information from debugging
peter.d.reid60ec9142014-09-06 16:39:46 +0000653** binaries. This returns the string representation of the supplied
drh734c9862008-11-28 15:37:20 +0000654** integer lock-type.
655*/
drh308c2a52010-05-14 11:30:18 +0000656static const char *azFileLock(int eFileLock){
657 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000658 case NO_LOCK: return "NONE";
659 case SHARED_LOCK: return "SHARED";
660 case RESERVED_LOCK: return "RESERVED";
661 case PENDING_LOCK: return "PENDING";
662 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000663 }
664 return "ERROR";
665}
666#endif
667
668#ifdef SQLITE_LOCK_TRACE
669/*
670** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000671**
drh734c9862008-11-28 15:37:20 +0000672** This routine is used for troubleshooting locks on multithreaded
673** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
674** command-line option on the compiler. This code is normally
675** turned off.
676*/
677static int lockTrace(int fd, int op, struct flock *p){
678 char *zOpName, *zType;
679 int s;
680 int savedErrno;
681 if( op==F_GETLK ){
682 zOpName = "GETLK";
683 }else if( op==F_SETLK ){
684 zOpName = "SETLK";
685 }else{
drh99ab3b12011-03-02 15:09:07 +0000686 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000687 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
688 return s;
689 }
690 if( p->l_type==F_RDLCK ){
691 zType = "RDLCK";
692 }else if( p->l_type==F_WRLCK ){
693 zType = "WRLCK";
694 }else if( p->l_type==F_UNLCK ){
695 zType = "UNLCK";
696 }else{
697 assert( 0 );
698 }
699 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000700 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000701 savedErrno = errno;
702 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
703 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
704 (int)p->l_pid, s);
705 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
706 struct flock l2;
707 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000708 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000709 if( l2.l_type==F_RDLCK ){
710 zType = "RDLCK";
711 }else if( l2.l_type==F_WRLCK ){
712 zType = "WRLCK";
713 }else if( l2.l_type==F_UNLCK ){
714 zType = "UNLCK";
715 }else{
716 assert( 0 );
717 }
718 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
719 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
720 }
721 errno = savedErrno;
722 return s;
723}
drh99ab3b12011-03-02 15:09:07 +0000724#undef osFcntl
725#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000726#endif /* SQLITE_LOCK_TRACE */
727
drhff812312011-02-23 13:33:46 +0000728/*
729** Retry ftruncate() calls that fail due to EINTR
dan2ee53412014-09-06 16:49:40 +0000730**
drhe6d41732015-02-21 00:49:00 +0000731** All calls to ftruncate() within this file should be made through
732** this wrapper. On the Android platform, bypassing the logic below
733** could lead to a corrupt database.
drhff812312011-02-23 13:33:46 +0000734*/
drhff812312011-02-23 13:33:46 +0000735static int robust_ftruncate(int h, sqlite3_int64 sz){
736 int rc;
dan2ee53412014-09-06 16:49:40 +0000737#ifdef __ANDROID__
738 /* On Android, ftruncate() always uses 32-bit offsets, even if
739 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
dan524a7332014-09-06 17:06:13 +0000740 ** truncate a file to any size larger than 2GiB. Silently ignore any
dan2ee53412014-09-06 16:49:40 +0000741 ** such attempts. */
742 if( sz>(sqlite3_int64)0x7FFFFFFF ){
743 rc = SQLITE_OK;
744 }else
745#endif
drh99ab3b12011-03-02 15:09:07 +0000746 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000747 return rc;
748}
drh734c9862008-11-28 15:37:20 +0000749
750/*
751** This routine translates a standard POSIX errno code into something
752** useful to the clients of the sqlite3 functions. Specifically, it is
753** intended to translate a variety of "try again" errors into SQLITE_BUSY
754** and a variety of "please close the file descriptor NOW" errors into
755** SQLITE_IOERR
756**
757** Errors during initialization of locks, or file system support for locks,
758** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
759*/
760static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
drh91c4def2015-11-25 14:00:07 +0000761 assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
762 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
763 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
764 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
drh734c9862008-11-28 15:37:20 +0000765 switch (posixError) {
drh91c4def2015-11-25 14:00:07 +0000766 case EACCES:
drh734c9862008-11-28 15:37:20 +0000767 case EAGAIN:
768 case ETIMEDOUT:
769 case EBUSY:
770 case EINTR:
771 case ENOLCK:
772 /* random NFS retry error, unless during file system support
773 * introspection, in which it actually means what it says */
774 return SQLITE_BUSY;
775
drh734c9862008-11-28 15:37:20 +0000776 case EPERM:
777 return SQLITE_PERM;
778
drh734c9862008-11-28 15:37:20 +0000779 default:
780 return sqliteIOErr;
781 }
782}
783
784
drh734c9862008-11-28 15:37:20 +0000785/******************************************************************************
786****************** Begin Unique File ID Utility Used By VxWorks ***************
787**
788** On most versions of unix, we can get a unique ID for a file by concatenating
789** the device number and the inode number. But this does not work on VxWorks.
790** On VxWorks, a unique file id must be based on the canonical filename.
791**
792** A pointer to an instance of the following structure can be used as a
793** unique file ID in VxWorks. Each instance of this structure contains
794** a copy of the canonical filename. There is also a reference count.
795** The structure is reclaimed when the number of pointers to it drops to
796** zero.
797**
798** There are never very many files open at one time and lookups are not
799** a performance-critical path, so it is sufficient to put these
800** structures on a linked list.
801*/
802struct vxworksFileId {
803 struct vxworksFileId *pNext; /* Next in a list of them all */
804 int nRef; /* Number of references to this one */
805 int nName; /* Length of the zCanonicalName[] string */
806 char *zCanonicalName; /* Canonical filename */
807};
808
809#if OS_VXWORKS
810/*
drh9b35ea62008-11-29 02:20:26 +0000811** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000812** variable:
813*/
814static struct vxworksFileId *vxworksFileList = 0;
815
816/*
817** Simplify a filename into its canonical form
818** by making the following changes:
819**
820** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000821** * convert /./ into just /
822** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000823**
824** Changes are made in-place. Return the new name length.
825**
826** The original filename is in z[0..n-1]. Return the number of
827** characters in the simplified name.
828*/
829static int vxworksSimplifyName(char *z, int n){
830 int i, j;
831 while( n>1 && z[n-1]=='/' ){ n--; }
832 for(i=j=0; i<n; i++){
833 if( z[i]=='/' ){
834 if( z[i+1]=='/' ) continue;
835 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
836 i += 1;
837 continue;
838 }
839 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
840 while( j>0 && z[j-1]!='/' ){ j--; }
841 if( j>0 ){ j--; }
842 i += 2;
843 continue;
844 }
845 }
846 z[j++] = z[i];
847 }
848 z[j] = 0;
849 return j;
850}
851
852/*
853** Find a unique file ID for the given absolute pathname. Return
854** a pointer to the vxworksFileId object. This pointer is the unique
855** file ID.
856**
857** The nRef field of the vxworksFileId object is incremented before
858** the object is returned. A new vxworksFileId object is created
859** and added to the global list if necessary.
860**
861** If a memory allocation error occurs, return NULL.
862*/
863static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
864 struct vxworksFileId *pNew; /* search key and new file ID */
865 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
866 int n; /* Length of zAbsoluteName string */
867
868 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000869 n = (int)strlen(zAbsoluteName);
drhf3cdcdc2015-04-29 16:50:28 +0000870 pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
drh734c9862008-11-28 15:37:20 +0000871 if( pNew==0 ) return 0;
872 pNew->zCanonicalName = (char*)&pNew[1];
873 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
874 n = vxworksSimplifyName(pNew->zCanonicalName, n);
875
876 /* Search for an existing entry that matching the canonical name.
877 ** If found, increment the reference count and return a pointer to
878 ** the existing file ID.
879 */
880 unixEnterMutex();
881 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
882 if( pCandidate->nName==n
883 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
884 ){
885 sqlite3_free(pNew);
886 pCandidate->nRef++;
887 unixLeaveMutex();
888 return pCandidate;
889 }
890 }
891
892 /* No match was found. We will make a new file ID */
893 pNew->nRef = 1;
894 pNew->nName = n;
895 pNew->pNext = vxworksFileList;
896 vxworksFileList = pNew;
897 unixLeaveMutex();
898 return pNew;
899}
900
901/*
902** Decrement the reference count on a vxworksFileId object. Free
903** the object when the reference count reaches zero.
904*/
905static void vxworksReleaseFileId(struct vxworksFileId *pId){
906 unixEnterMutex();
907 assert( pId->nRef>0 );
908 pId->nRef--;
909 if( pId->nRef==0 ){
910 struct vxworksFileId **pp;
911 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
912 assert( *pp==pId );
913 *pp = pId->pNext;
914 sqlite3_free(pId);
915 }
916 unixLeaveMutex();
917}
918#endif /* OS_VXWORKS */
919/*************** End of Unique File ID Utility Used By VxWorks ****************
920******************************************************************************/
921
922
923/******************************************************************************
924*************************** Posix Advisory Locking ****************************
925**
drh9b35ea62008-11-29 02:20:26 +0000926** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000927** section 6.5.2.2 lines 483 through 490 specify that when a process
928** sets or clears a lock, that operation overrides any prior locks set
929** by the same process. It does not explicitly say so, but this implies
930** that it overrides locks set by the same process using a different
931** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000932**
933** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000934** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
935**
936** Suppose ./file1 and ./file2 are really the same file (because
937** one is a hard or symbolic link to the other) then if you set
938** an exclusive lock on fd1, then try to get an exclusive lock
939** on fd2, it works. I would have expected the second lock to
940** fail since there was already a lock on the file due to fd1.
941** But not so. Since both locks came from the same process, the
942** second overrides the first, even though they were on different
943** file descriptors opened on different file names.
944**
drh734c9862008-11-28 15:37:20 +0000945** This means that we cannot use POSIX locks to synchronize file access
946** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000947** to synchronize access for threads in separate processes, but not
948** threads within the same process.
949**
950** To work around the problem, SQLite has to manage file locks internally
951** on its own. Whenever a new database is opened, we have to find the
952** specific inode of the database file (the inode is determined by the
953** st_dev and st_ino fields of the stat structure that fstat() fills in)
954** and check for locks already existing on that inode. When locks are
955** created or removed, we have to look at our own internal record of the
956** locks to see if another thread has previously set a lock on that same
957** inode.
958**
drh9b35ea62008-11-29 02:20:26 +0000959** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
960** For VxWorks, we have to use the alternative unique ID system based on
961** canonical filename and implemented in the previous division.)
962**
danielk1977ad94b582007-08-20 06:44:22 +0000963** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000964** descriptor. It is now a structure that holds the integer file
965** descriptor and a pointer to a structure that describes the internal
966** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000967** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000968** point to the same locking structure. The locking structure keeps
969** a reference count (so we will know when to delete it) and a "cnt"
970** field that tells us its internal lock status. cnt==0 means the
971** file is unlocked. cnt==-1 means the file has an exclusive lock.
972** cnt>0 means there are cnt shared locks on the file.
973**
974** Any attempt to lock or unlock a file first checks the locking
975** structure. The fcntl() system call is only invoked to set a
976** POSIX lock if the internal lock structure transitions between
977** a locked and an unlocked state.
978**
drh734c9862008-11-28 15:37:20 +0000979** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000980**
981** If you close a file descriptor that points to a file that has locks,
982** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000983** released. To work around this problem, each unixInodeInfo object
984** maintains a count of the number of pending locks on tha inode.
985** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000986** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000987** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000988** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000989** be closed and that list is walked (and cleared) when the last lock
990** clears.
991**
drh9b35ea62008-11-29 02:20:26 +0000992** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000993**
drh9b35ea62008-11-29 02:20:26 +0000994** Many older versions of linux use the LinuxThreads library which is
995** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000996** A cannot be modified or overridden by a different thread B.
997** Only thread A can modify the lock. Locking behavior is correct
998** if the appliation uses the newer Native Posix Thread Library (NPTL)
999** on linux - with NPTL a lock created by thread A can override locks
1000** in thread B. But there is no way to know at compile-time which
1001** threading library is being used. So there is no way to know at
1002** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001003** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001004** current process.
drh5fdae772004-06-29 03:29:00 +00001005**
drh8af6c222010-05-14 12:43:01 +00001006** SQLite used to support LinuxThreads. But support for LinuxThreads
1007** was dropped beginning with version 3.7.0. SQLite will still work with
1008** LinuxThreads provided that (1) there is no more than one connection
1009** per database file in the same process and (2) database connections
1010** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001011*/
1012
1013/*
1014** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001015** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001016*/
1017struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001018 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001019#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001020 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001021#else
drh107886a2008-11-21 22:21:50 +00001022 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001023#endif
1024};
1025
1026/*
drhbbd42a62004-05-22 17:41:58 +00001027** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001028** inode. Or, on LinuxThreads, there is one of these structures for
1029** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001030**
danielk1977ad94b582007-08-20 06:44:22 +00001031** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001032** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001033** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001034*/
drh8af6c222010-05-14 12:43:01 +00001035struct unixInodeInfo {
1036 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001037 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001038 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1039 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001040 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001041 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1042 int nLock; /* Number of outstanding file locks */
1043 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1044 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1045 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001046#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001047 unsigned long long sharedByte; /* for AFP simulated shared lock */
1048#endif
drh6c7d5c52008-11-21 20:32:33 +00001049#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001050 sem_t *pSem; /* Named POSIX semaphore */
1051 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001052#endif
drhbbd42a62004-05-22 17:41:58 +00001053};
1054
drhda0e7682008-07-30 15:27:54 +00001055/*
drh8af6c222010-05-14 12:43:01 +00001056** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001057*/
drhd91c68f2010-05-14 14:52:25 +00001058static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001059
drh5fdae772004-06-29 03:29:00 +00001060/*
dane18d4952011-02-21 11:46:24 +00001061**
drhaaeaa182015-11-24 15:12:47 +00001062** This function - unixLogErrorAtLine(), is only ever called via the macro
dane18d4952011-02-21 11:46:24 +00001063** unixLogError().
1064**
1065** It is invoked after an error occurs in an OS function and errno has been
1066** set. It logs a message using sqlite3_log() containing the current value of
1067** errno and, if possible, the human-readable equivalent from strerror() or
1068** strerror_r().
1069**
1070** The first argument passed to the macro should be the error code that
1071** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1072** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001073** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001074** if any.
1075*/
drh0e9365c2011-03-02 02:08:13 +00001076#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1077static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001078 int errcode, /* SQLite error code */
1079 const char *zFunc, /* Name of OS function that failed */
1080 const char *zPath, /* File path associated with error */
1081 int iLine /* Source line number where error occurred */
1082){
1083 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001084 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001085
1086 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1087 ** the strerror() function to obtain the human-readable error message
1088 ** equivalent to errno. Otherwise, use strerror_r().
1089 */
1090#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1091 char aErr[80];
1092 memset(aErr, 0, sizeof(aErr));
1093 zErr = aErr;
1094
1095 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001096 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001097 ** returns a pointer to a buffer containing the error message. That pointer
1098 ** may point to aErr[], or it may point to some static storage somewhere.
1099 ** Otherwise, assume that the system provides the POSIX version of
1100 ** strerror_r(), which always writes an error message into aErr[].
1101 **
1102 ** If the code incorrectly assumes that it is the POSIX version that is
1103 ** available, the error message will often be an empty string. Not a
1104 ** huge problem. Incorrectly concluding that the GNU version is available
1105 ** could lead to a segfault though.
1106 */
1107#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1108 zErr =
1109# endif
drh0e9365c2011-03-02 02:08:13 +00001110 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001111
1112#elif SQLITE_THREADSAFE
1113 /* This is a threadsafe build, but strerror_r() is not available. */
1114 zErr = "";
1115#else
1116 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001117 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001118#endif
1119
drh0e9365c2011-03-02 02:08:13 +00001120 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001121 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001122 "os_unix.c:%d: (%d) %s(%s) - %s",
1123 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001124 );
1125
1126 return errcode;
1127}
1128
drh0e9365c2011-03-02 02:08:13 +00001129/*
1130** Close a file descriptor.
1131**
1132** We assume that close() almost always works, since it is only in a
1133** very sick application or on a very sick platform that it might fail.
1134** If it does fail, simply leak the file descriptor, but do log the
1135** error.
1136**
1137** Note that it is not safe to retry close() after EINTR since the
1138** file descriptor might have already been reused by another thread.
1139** So we don't even try to recover from an EINTR. Just log the error
1140** and move on.
1141*/
1142static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001143 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001144 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1145 pFile ? pFile->zPath : 0, lineno);
1146 }
1147}
dane18d4952011-02-21 11:46:24 +00001148
1149/*
drhe6d41732015-02-21 00:49:00 +00001150** Set the pFile->lastErrno. Do this in a subroutine as that provides
1151** a convenient place to set a breakpoint.
drh4bf66fd2015-02-19 02:43:02 +00001152*/
1153static void storeLastErrno(unixFile *pFile, int error){
1154 pFile->lastErrno = error;
1155}
1156
1157/*
danb0ac3e32010-06-16 10:55:42 +00001158** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001159*/
drh0e9365c2011-03-02 02:08:13 +00001160static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001161 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001162 UnixUnusedFd *p;
1163 UnixUnusedFd *pNext;
1164 for(p=pInode->pUnused; p; p=pNext){
1165 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001166 robust_close(pFile, p->fd, __LINE__);
1167 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001168 }
drh0e9365c2011-03-02 02:08:13 +00001169 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001170}
1171
1172/*
drh8af6c222010-05-14 12:43:01 +00001173** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001174**
1175** The mutex entered using the unixEnterMutex() function must be held
1176** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001177*/
danb0ac3e32010-06-16 10:55:42 +00001178static void releaseInodeInfo(unixFile *pFile){
1179 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001180 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001181 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001182 pInode->nRef--;
1183 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001184 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001185 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001186 if( pInode->pPrev ){
1187 assert( pInode->pPrev->pNext==pInode );
1188 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001189 }else{
drh8af6c222010-05-14 12:43:01 +00001190 assert( inodeList==pInode );
1191 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001192 }
drh8af6c222010-05-14 12:43:01 +00001193 if( pInode->pNext ){
1194 assert( pInode->pNext->pPrev==pInode );
1195 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001196 }
drh8af6c222010-05-14 12:43:01 +00001197 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001198 }
drhbbd42a62004-05-22 17:41:58 +00001199 }
1200}
1201
1202/*
drh8af6c222010-05-14 12:43:01 +00001203** Given a file descriptor, locate the unixInodeInfo object that
1204** describes that file descriptor. Create a new one if necessary. The
1205** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001206**
dan9359c7b2009-08-21 08:29:10 +00001207** The mutex entered using the unixEnterMutex() function must be held
1208** when this function is called.
1209**
drh6c7d5c52008-11-21 20:32:33 +00001210** Return an appropriate error code.
1211*/
drh8af6c222010-05-14 12:43:01 +00001212static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001213 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001214 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001215){
1216 int rc; /* System call return code */
1217 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001218 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1219 struct stat statbuf; /* Low-level file information */
1220 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001221
dan9359c7b2009-08-21 08:29:10 +00001222 assert( unixMutexHeld() );
1223
drh6c7d5c52008-11-21 20:32:33 +00001224 /* Get low-level information about the file that we can used to
1225 ** create a unique name for the file.
1226 */
1227 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001228 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001229 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001230 storeLastErrno(pFile, errno);
drh40fe8d32015-11-30 20:36:26 +00001231#if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
drh6c7d5c52008-11-21 20:32:33 +00001232 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1233#endif
1234 return SQLITE_IOERR;
1235 }
1236
drheb0d74f2009-02-03 15:27:02 +00001237#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001238 /* On OS X on an msdos filesystem, the inode number is reported
1239 ** incorrectly for zero-size files. See ticket #3260. To work
1240 ** around this problem (we consider it a bug in OS X, not SQLite)
1241 ** we always increase the file size to 1 by writing a single byte
1242 ** prior to accessing the inode number. The one byte written is
1243 ** an ASCII 'S' character which also happens to be the first byte
1244 ** in the header of every SQLite database. In this way, if there
1245 ** is a race condition such that another thread has already populated
1246 ** the first page of the database, no damage is done.
1247 */
drh7ed97b92010-01-20 13:07:21 +00001248 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001249 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001250 if( rc!=1 ){
drh4bf66fd2015-02-19 02:43:02 +00001251 storeLastErrno(pFile, errno);
drheb0d74f2009-02-03 15:27:02 +00001252 return SQLITE_IOERR;
1253 }
drh99ab3b12011-03-02 15:09:07 +00001254 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001255 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001256 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001257 return SQLITE_IOERR;
1258 }
1259 }
drheb0d74f2009-02-03 15:27:02 +00001260#endif
drh6c7d5c52008-11-21 20:32:33 +00001261
drh8af6c222010-05-14 12:43:01 +00001262 memset(&fileId, 0, sizeof(fileId));
1263 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001264#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001265 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001266#else
drh8af6c222010-05-14 12:43:01 +00001267 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001268#endif
drh8af6c222010-05-14 12:43:01 +00001269 pInode = inodeList;
1270 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1271 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001272 }
drh8af6c222010-05-14 12:43:01 +00001273 if( pInode==0 ){
drhf3cdcdc2015-04-29 16:50:28 +00001274 pInode = sqlite3_malloc64( sizeof(*pInode) );
drh8af6c222010-05-14 12:43:01 +00001275 if( pInode==0 ){
1276 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001277 }
drh8af6c222010-05-14 12:43:01 +00001278 memset(pInode, 0, sizeof(*pInode));
1279 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1280 pInode->nRef = 1;
1281 pInode->pNext = inodeList;
1282 pInode->pPrev = 0;
1283 if( inodeList ) inodeList->pPrev = pInode;
1284 inodeList = pInode;
1285 }else{
1286 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001287 }
drh8af6c222010-05-14 12:43:01 +00001288 *ppInode = pInode;
1289 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001290}
drh6c7d5c52008-11-21 20:32:33 +00001291
drhb959a012013-12-07 12:29:22 +00001292/*
1293** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1294*/
1295static int fileHasMoved(unixFile *pFile){
drh61ffea52014-08-12 12:19:25 +00001296#if OS_VXWORKS
1297 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1298#else
drhb959a012013-12-07 12:29:22 +00001299 struct stat buf;
1300 return pFile->pInode!=0 &&
drh61ffea52014-08-12 12:19:25 +00001301 (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
drh91be7dc2014-08-11 13:53:30 +00001302#endif
drhb959a012013-12-07 12:29:22 +00001303}
1304
aswift5b1a2562008-08-22 00:22:35 +00001305
1306/*
drhfbc7e882013-04-11 01:16:15 +00001307** Check a unixFile that is a database. Verify the following:
1308**
1309** (1) There is exactly one hard link on the file
1310** (2) The file is not a symbolic link
1311** (3) The file has not been renamed or unlinked
1312**
1313** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1314*/
1315static void verifyDbFile(unixFile *pFile){
1316 struct stat buf;
1317 int rc;
drhfbc7e882013-04-11 01:16:15 +00001318 rc = osFstat(pFile->h, &buf);
1319 if( rc!=0 ){
1320 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001321 return;
1322 }
drh3044b512014-06-16 16:41:52 +00001323 if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
drhfbc7e882013-04-11 01:16:15 +00001324 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001325 return;
1326 }
1327 if( buf.st_nlink>1 ){
1328 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001329 return;
1330 }
drhb959a012013-12-07 12:29:22 +00001331 if( fileHasMoved(pFile) ){
drhfbc7e882013-04-11 01:16:15 +00001332 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001333 return;
1334 }
1335}
1336
1337
1338/*
danielk197713adf8a2004-06-03 16:08:41 +00001339** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001340** file by this or any other process. If such a lock is held, set *pResOut
1341** to a non-zero value otherwise *pResOut is set to zero. The return value
1342** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001343*/
danielk1977861f7452008-06-05 11:39:11 +00001344static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001345 int rc = SQLITE_OK;
1346 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001347 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001348
danielk1977861f7452008-06-05 11:39:11 +00001349 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1350
drh054889e2005-11-30 03:20:31 +00001351 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00001352 assert( pFile->eFileLock<=SHARED_LOCK );
drh8af6c222010-05-14 12:43:01 +00001353 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001354
1355 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001356 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001357 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001358 }
1359
drh2ac3ee92004-06-07 16:27:46 +00001360 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001361 */
danielk197709480a92009-02-09 05:32:32 +00001362#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001363 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001364 struct flock lock;
1365 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001366 lock.l_start = RESERVED_BYTE;
1367 lock.l_len = 1;
1368 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001369 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1370 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001371 storeLastErrno(pFile, errno);
aswift5b1a2562008-08-22 00:22:35 +00001372 } else if( lock.l_type!=F_UNLCK ){
1373 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001374 }
1375 }
danielk197709480a92009-02-09 05:32:32 +00001376#endif
danielk197713adf8a2004-06-03 16:08:41 +00001377
drh6c7d5c52008-11-21 20:32:33 +00001378 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001379 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001380
aswift5b1a2562008-08-22 00:22:35 +00001381 *pResOut = reserved;
1382 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001383}
1384
1385/*
drha7e61d82011-03-12 17:02:57 +00001386** Attempt to set a system-lock on the file pFile. The lock is
1387** described by pLock.
1388**
drh77197112011-03-15 19:08:48 +00001389** If the pFile was opened read/write from unix-excl, then the only lock
1390** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001391** the first time any lock is attempted. All subsequent system locking
1392** operations become no-ops. Locking operations still happen internally,
1393** in order to coordinate access between separate database connections
1394** within this process, but all of that is handled in memory and the
1395** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001396**
1397** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1398** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1399** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001400**
1401** Zero is returned if the call completes successfully, or -1 if a call
1402** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001403*/
1404static int unixFileLock(unixFile *pFile, struct flock *pLock){
1405 int rc;
drh3cb93392011-03-12 18:10:44 +00001406 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001407 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001408 assert( pInode!=0 );
drh50358ad2015-12-02 01:04:33 +00001409 if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
drh3cb93392011-03-12 18:10:44 +00001410 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001411 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001412 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001413 lock.l_whence = SEEK_SET;
1414 lock.l_start = SHARED_FIRST;
1415 lock.l_len = SHARED_SIZE;
1416 lock.l_type = F_WRLCK;
1417 rc = osFcntl(pFile->h, F_SETLK, &lock);
1418 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001419 pInode->bProcessLock = 1;
1420 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001421 }else{
1422 rc = 0;
1423 }
1424 }else{
1425 rc = osFcntl(pFile->h, F_SETLK, pLock);
1426 }
1427 return rc;
1428}
1429
1430/*
drh308c2a52010-05-14 11:30:18 +00001431** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001432** of the following:
1433**
drh2ac3ee92004-06-07 16:27:46 +00001434** (1) SHARED_LOCK
1435** (2) RESERVED_LOCK
1436** (3) PENDING_LOCK
1437** (4) EXCLUSIVE_LOCK
1438**
drhb3e04342004-06-08 00:47:47 +00001439** Sometimes when requesting one lock state, additional lock states
1440** are inserted in between. The locking might fail on one of the later
1441** transitions leaving the lock state different from what it started but
1442** still short of its goal. The following chart shows the allowed
1443** transitions and the inserted intermediate states:
1444**
1445** UNLOCKED -> SHARED
1446** SHARED -> RESERVED
1447** SHARED -> (PENDING) -> EXCLUSIVE
1448** RESERVED -> (PENDING) -> EXCLUSIVE
1449** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001450**
drha6abd042004-06-09 17:37:22 +00001451** This routine will only increase a lock. Use the sqlite3OsUnlock()
1452** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001453*/
drh308c2a52010-05-14 11:30:18 +00001454static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001455 /* The following describes the implementation of the various locks and
1456 ** lock transitions in terms of the POSIX advisory shared and exclusive
1457 ** lock primitives (called read-locks and write-locks below, to avoid
1458 ** confusion with SQLite lock names). The algorithms are complicated
1459 ** slightly in order to be compatible with windows systems simultaneously
1460 ** accessing the same database file, in case that is ever required.
1461 **
1462 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1463 ** byte', each single bytes at well known offsets, and the 'shared byte
1464 ** range', a range of 510 bytes at a well known offset.
1465 **
1466 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1467 ** byte'. If this is successful, a random byte from the 'shared byte
1468 ** range' is read-locked and the lock on the 'pending byte' released.
1469 **
danielk197790ba3bd2004-06-25 08:32:25 +00001470 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1471 ** A RESERVED lock is implemented by grabbing a write-lock on the
1472 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001473 **
1474 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001475 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1476 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1477 ** obtained, but existing SHARED locks are allowed to persist. A process
1478 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1479 ** This property is used by the algorithm for rolling back a journal file
1480 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001481 **
danielk197790ba3bd2004-06-25 08:32:25 +00001482 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1483 ** implemented by obtaining a write-lock on the entire 'shared byte
1484 ** range'. Since all other locks require a read-lock on one of the bytes
1485 ** within this range, this ensures that no other locks are held on the
1486 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001487 **
1488 ** The reason a single byte cannot be used instead of the 'shared byte
1489 ** range' is that some versions of windows do not support read-locks. By
1490 ** locking a random byte from a range, concurrent SHARED locks may exist
1491 ** even if the locking primitive used is always a write-lock.
1492 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001493 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001494 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001495 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001496 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001497 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001498
drh054889e2005-11-30 03:20:31 +00001499 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001500 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1501 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh91eb93c2015-03-03 19:56:20 +00001502 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001503 osGetpid(0)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001504
1505 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001506 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001507 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001508 */
drh308c2a52010-05-14 11:30:18 +00001509 if( pFile->eFileLock>=eFileLock ){
1510 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1511 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001512 return SQLITE_OK;
1513 }
1514
drh0c2694b2009-09-03 16:23:44 +00001515 /* Make sure the locking sequence is correct.
1516 ** (1) We never move from unlocked to anything higher than shared lock.
1517 ** (2) SQLite never explicitly requests a pendig lock.
1518 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001519 */
drh308c2a52010-05-14 11:30:18 +00001520 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1521 assert( eFileLock!=PENDING_LOCK );
1522 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001523
drh8af6c222010-05-14 12:43:01 +00001524 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001525 */
drh6c7d5c52008-11-21 20:32:33 +00001526 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001527 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001528
danielk1977ad94b582007-08-20 06:44:22 +00001529 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001530 ** handle that precludes the requested lock, return BUSY.
1531 */
drh8af6c222010-05-14 12:43:01 +00001532 if( (pFile->eFileLock!=pInode->eFileLock &&
1533 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001534 ){
1535 rc = SQLITE_BUSY;
1536 goto end_lock;
1537 }
1538
1539 /* If a SHARED lock is requested, and some thread using this PID already
1540 ** has a SHARED or RESERVED lock, then increment reference counts and
1541 ** return SQLITE_OK.
1542 */
drh308c2a52010-05-14 11:30:18 +00001543 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001544 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001545 assert( eFileLock==SHARED_LOCK );
1546 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001547 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001548 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001549 pInode->nShared++;
1550 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001551 goto end_lock;
1552 }
1553
danielk19779a1d0ab2004-06-01 14:09:28 +00001554
drh3cde3bb2004-06-12 02:17:14 +00001555 /* A PENDING lock is needed before acquiring a SHARED lock and before
1556 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1557 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001558 */
drh0c2694b2009-09-03 16:23:44 +00001559 lock.l_len = 1L;
1560 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001561 if( eFileLock==SHARED_LOCK
1562 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001563 ){
drh308c2a52010-05-14 11:30:18 +00001564 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001565 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001566 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001567 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001568 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001569 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001570 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001571 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001572 goto end_lock;
1573 }
drh3cde3bb2004-06-12 02:17:14 +00001574 }
1575
1576
1577 /* If control gets to this point, then actually go ahead and make
1578 ** operating system calls for the specified lock.
1579 */
drh308c2a52010-05-14 11:30:18 +00001580 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001581 assert( pInode->nShared==0 );
1582 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001583 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001584
drh2ac3ee92004-06-07 16:27:46 +00001585 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001586 lock.l_start = SHARED_FIRST;
1587 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001588 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001589 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001590 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001591 }
dan661d71a2011-03-30 19:08:03 +00001592
drh2ac3ee92004-06-07 16:27:46 +00001593 /* Drop the temporary PENDING lock */
1594 lock.l_start = PENDING_BYTE;
1595 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001596 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001597 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1598 /* This could happen with a network mount */
1599 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001600 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001601 }
dan661d71a2011-03-30 19:08:03 +00001602
1603 if( rc ){
1604 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001605 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001606 }
dan661d71a2011-03-30 19:08:03 +00001607 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001608 }else{
drh308c2a52010-05-14 11:30:18 +00001609 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001610 pInode->nLock++;
1611 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001612 }
drh8af6c222010-05-14 12:43:01 +00001613 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001614 /* We are trying for an exclusive lock but another thread in this
1615 ** same process is still holding a shared lock. */
1616 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001617 }else{
drh3cde3bb2004-06-12 02:17:14 +00001618 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001619 ** assumed that there is a SHARED or greater lock on the file
1620 ** already.
1621 */
drh308c2a52010-05-14 11:30:18 +00001622 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001623 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001624
1625 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1626 if( eFileLock==RESERVED_LOCK ){
1627 lock.l_start = RESERVED_BYTE;
1628 lock.l_len = 1L;
1629 }else{
1630 lock.l_start = SHARED_FIRST;
1631 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001632 }
dan661d71a2011-03-30 19:08:03 +00001633
1634 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001635 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001636 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001637 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001638 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001639 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001640 }
drhbbd42a62004-05-22 17:41:58 +00001641 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001642
drh8f941bc2009-01-14 23:03:40 +00001643
drhd3d8c042012-05-29 17:02:40 +00001644#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001645 /* Set up the transaction-counter change checking flags when
1646 ** transitioning from a SHARED to a RESERVED lock. The change
1647 ** from SHARED to RESERVED marks the beginning of a normal
1648 ** write operation (not a hot journal rollback).
1649 */
1650 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001651 && pFile->eFileLock<=SHARED_LOCK
1652 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001653 ){
1654 pFile->transCntrChng = 0;
1655 pFile->dbUpdate = 0;
1656 pFile->inNormalWrite = 1;
1657 }
1658#endif
1659
1660
danielk1977ecb2a962004-06-02 06:30:16 +00001661 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001662 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001663 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001664 }else if( eFileLock==EXCLUSIVE_LOCK ){
1665 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001666 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001667 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001668
1669end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001670 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001671 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1672 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001673 return rc;
1674}
1675
1676/*
dan08da86a2009-08-21 17:18:03 +00001677** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001678** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001679*/
1680static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001681 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001682 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001683 p->pNext = pInode->pUnused;
1684 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001685 pFile->h = -1;
1686 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001687}
1688
1689/*
drh308c2a52010-05-14 11:30:18 +00001690** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001691** must be either NO_LOCK or SHARED_LOCK.
1692**
1693** If the locking level of the file descriptor is already at or below
1694** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001695**
1696** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1697** the byte range is divided into 2 parts and the first part is unlocked then
1698** set to a read lock, then the other part is simply unlocked. This works
1699** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1700** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001701*/
drha7e61d82011-03-12 17:02:57 +00001702static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001703 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001704 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001705 struct flock lock;
1706 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001707
drh054889e2005-11-30 03:20:31 +00001708 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001709 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001710 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001711 osGetpid(0)));
drha6abd042004-06-09 17:37:22 +00001712
drh308c2a52010-05-14 11:30:18 +00001713 assert( eFileLock<=SHARED_LOCK );
1714 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001715 return SQLITE_OK;
1716 }
drh6c7d5c52008-11-21 20:32:33 +00001717 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001718 pInode = pFile->pInode;
1719 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001720 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001721 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001722
drhd3d8c042012-05-29 17:02:40 +00001723#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001724 /* When reducing a lock such that other processes can start
1725 ** reading the database file again, make sure that the
1726 ** transaction counter was updated if any part of the database
1727 ** file changed. If the transaction counter is not updated,
1728 ** other connections to the same file might not realize that
1729 ** the file has changed and hence might not know to flush their
1730 ** cache. The use of a stale cache can lead to database corruption.
1731 */
drh8f941bc2009-01-14 23:03:40 +00001732 pFile->inNormalWrite = 0;
1733#endif
1734
drh7ed97b92010-01-20 13:07:21 +00001735 /* downgrading to a shared lock on NFS involves clearing the write lock
1736 ** before establishing the readlock - to avoid a race condition we downgrade
1737 ** the lock in 2 blocks, so that part of the range will be covered by a
1738 ** write lock until the rest is covered by a read lock:
1739 ** 1: [WWWWW]
1740 ** 2: [....W]
1741 ** 3: [RRRRW]
1742 ** 4: [RRRR.]
1743 */
drh308c2a52010-05-14 11:30:18 +00001744 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001745#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001746 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001747 assert( handleNFSUnlock==0 );
1748#endif
1749#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001750 if( handleNFSUnlock ){
drha712b4b2015-02-19 16:12:04 +00001751 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001752 off_t divSize = SHARED_SIZE - 1;
1753
1754 lock.l_type = F_UNLCK;
1755 lock.l_whence = SEEK_SET;
1756 lock.l_start = SHARED_FIRST;
1757 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001758 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001759 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001760 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001761 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001762 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001763 }
drh7ed97b92010-01-20 13:07:21 +00001764 lock.l_type = F_RDLCK;
1765 lock.l_whence = SEEK_SET;
1766 lock.l_start = SHARED_FIRST;
1767 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001768 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001769 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001770 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1771 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001772 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001773 }
1774 goto end_unlock;
1775 }
1776 lock.l_type = F_UNLCK;
1777 lock.l_whence = SEEK_SET;
1778 lock.l_start = SHARED_FIRST+divSize;
1779 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001780 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001781 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001782 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001783 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001784 goto end_unlock;
1785 }
drh30f776f2011-02-25 03:25:07 +00001786 }else
1787#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1788 {
drh7ed97b92010-01-20 13:07:21 +00001789 lock.l_type = F_RDLCK;
1790 lock.l_whence = SEEK_SET;
1791 lock.l_start = SHARED_FIRST;
1792 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001793 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001794 /* In theory, the call to unixFileLock() cannot fail because another
1795 ** process is holding an incompatible lock. If it does, this
1796 ** indicates that the other process is not following the locking
1797 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1798 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1799 ** an assert to fail). */
1800 rc = SQLITE_IOERR_RDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001801 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00001802 goto end_unlock;
1803 }
drh9c105bb2004-10-02 20:38:28 +00001804 }
1805 }
drhbbd42a62004-05-22 17:41:58 +00001806 lock.l_type = F_UNLCK;
1807 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001808 lock.l_start = PENDING_BYTE;
1809 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001810 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001811 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001812 }else{
danea83bc62011-04-01 11:56:32 +00001813 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001814 storeLastErrno(pFile, errno);
drhcd731cf2009-03-28 23:23:02 +00001815 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001816 }
drhbbd42a62004-05-22 17:41:58 +00001817 }
drh308c2a52010-05-14 11:30:18 +00001818 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001819 /* Decrement the shared lock counter. Release the lock using an
1820 ** OS call only when all threads in this same process have released
1821 ** the lock.
1822 */
drh8af6c222010-05-14 12:43:01 +00001823 pInode->nShared--;
1824 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001825 lock.l_type = F_UNLCK;
1826 lock.l_whence = SEEK_SET;
1827 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001828 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001829 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001830 }else{
danea83bc62011-04-01 11:56:32 +00001831 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001832 storeLastErrno(pFile, errno);
drh8af6c222010-05-14 12:43:01 +00001833 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001834 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001835 }
drha6abd042004-06-09 17:37:22 +00001836 }
1837
drhbbd42a62004-05-22 17:41:58 +00001838 /* Decrement the count of locks against this same file. When the
1839 ** count reaches zero, close any other file descriptors whose close
1840 ** was deferred because of outstanding locks.
1841 */
drh8af6c222010-05-14 12:43:01 +00001842 pInode->nLock--;
1843 assert( pInode->nLock>=0 );
1844 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001845 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001846 }
1847 }
drhf2f105d2012-08-20 15:53:54 +00001848
aswift5b1a2562008-08-22 00:22:35 +00001849end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001850 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001851 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001852 return rc;
drhbbd42a62004-05-22 17:41:58 +00001853}
1854
1855/*
drh308c2a52010-05-14 11:30:18 +00001856** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001857** must be either NO_LOCK or SHARED_LOCK.
1858**
1859** If the locking level of the file descriptor is already at or below
1860** the requested locking level, this routine is a no-op.
1861*/
drh308c2a52010-05-14 11:30:18 +00001862static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00001863#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00001864 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00001865#endif
drha7e61d82011-03-12 17:02:57 +00001866 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001867}
1868
mistachkine98844f2013-08-24 00:59:24 +00001869#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001870static int unixMapfile(unixFile *pFd, i64 nByte);
1871static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00001872#endif
danf23da962013-03-23 21:00:41 +00001873
drh7ed97b92010-01-20 13:07:21 +00001874/*
danielk1977e339d652008-06-28 11:23:00 +00001875** This function performs the parts of the "close file" operation
1876** common to all locking schemes. It closes the directory and file
1877** handles, if they are valid, and sets all fields of the unixFile
1878** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001879**
1880** It is *not* necessary to hold the mutex when this routine is called,
1881** even on VxWorks. A mutex will be acquired on VxWorks by the
1882** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001883*/
1884static int closeUnixFile(sqlite3_file *id){
1885 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00001886#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001887 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00001888#endif
dan661d71a2011-03-30 19:08:03 +00001889 if( pFile->h>=0 ){
1890 robust_close(pFile, pFile->h, __LINE__);
1891 pFile->h = -1;
1892 }
1893#if OS_VXWORKS
1894 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001895 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001896 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001897 }
1898 vxworksReleaseFileId(pFile->pId);
1899 pFile->pId = 0;
1900 }
1901#endif
drh0bdbc902014-06-16 18:35:06 +00001902#ifdef SQLITE_UNLINK_AFTER_CLOSE
1903 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
1904 osUnlink(pFile->zPath);
1905 sqlite3_free(*(char**)&pFile->zPath);
1906 pFile->zPath = 0;
1907 }
1908#endif
dan661d71a2011-03-30 19:08:03 +00001909 OSTRACE(("CLOSE %-3d\n", pFile->h));
1910 OpenCounter(-1);
1911 sqlite3_free(pFile->pUnused);
1912 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001913 return SQLITE_OK;
1914}
1915
1916/*
danielk1977e3026632004-06-22 11:29:02 +00001917** Close a file.
1918*/
danielk197762079062007-08-15 17:08:46 +00001919static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001920 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001921 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00001922 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00001923 unixUnlock(id, NO_LOCK);
1924 unixEnterMutex();
1925
1926 /* unixFile.pInode is always valid here. Otherwise, a different close
1927 ** routine (e.g. nolockClose()) would be called instead.
1928 */
1929 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1930 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1931 /* If there are outstanding locks, do not actually close the file just
1932 ** yet because that would clear those locks. Instead, add the file
1933 ** descriptor to pInode->pUnused list. It will be automatically closed
1934 ** when the last lock is cleared.
1935 */
1936 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001937 }
dan661d71a2011-03-30 19:08:03 +00001938 releaseInodeInfo(pFile);
1939 rc = closeUnixFile(id);
1940 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001941 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001942}
1943
drh734c9862008-11-28 15:37:20 +00001944/************** End of the posix advisory lock implementation *****************
1945******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001946
drh734c9862008-11-28 15:37:20 +00001947/******************************************************************************
1948****************************** No-op Locking **********************************
1949**
1950** Of the various locking implementations available, this is by far the
1951** simplest: locking is ignored. No attempt is made to lock the database
1952** file for reading or writing.
1953**
1954** This locking mode is appropriate for use on read-only databases
1955** (ex: databases that are burned into CD-ROM, for example.) It can
1956** also be used if the application employs some external mechanism to
1957** prevent simultaneous access of the same database by two or more
1958** database connections. But there is a serious risk of database
1959** corruption if this locking mode is used in situations where multiple
1960** database connections are accessing the same database file at the same
1961** time and one or more of those connections are writing.
1962*/
drhbfe66312006-10-03 17:40:40 +00001963
drh734c9862008-11-28 15:37:20 +00001964static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1965 UNUSED_PARAMETER(NotUsed);
1966 *pResOut = 0;
1967 return SQLITE_OK;
1968}
drh734c9862008-11-28 15:37:20 +00001969static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1970 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1971 return SQLITE_OK;
1972}
drh734c9862008-11-28 15:37:20 +00001973static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1974 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1975 return SQLITE_OK;
1976}
1977
1978/*
drh9b35ea62008-11-29 02:20:26 +00001979** Close the file.
drh734c9862008-11-28 15:37:20 +00001980*/
1981static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001982 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001983}
1984
1985/******************* End of the no-op lock implementation *********************
1986******************************************************************************/
1987
1988/******************************************************************************
1989************************* Begin dot-file Locking ******************************
1990**
mistachkin48864df2013-03-21 21:20:32 +00001991** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00001992** files (really a directory) to control access to the database. This works
1993** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00001994**
1995** (1) There is zero concurrency. A single reader blocks all other
1996** connections from reading or writing the database.
1997**
1998** (2) An application crash or power loss can leave stale lock files
1999** sitting around that need to be cleared manually.
2000**
2001** Nevertheless, a dotlock is an appropriate locking mode for use if no
2002** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002003**
drh9ef6bc42011-11-04 02:24:02 +00002004** Dotfile locking works by creating a subdirectory in the same directory as
2005** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002006** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002007** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002008*/
2009
2010/*
2011** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002012** lock directory.
drh734c9862008-11-28 15:37:20 +00002013*/
2014#define DOTLOCK_SUFFIX ".lock"
2015
drh7708e972008-11-29 00:56:52 +00002016/*
2017** This routine checks if there is a RESERVED lock held on the specified
2018** file by this or any other process. If such a lock is held, set *pResOut
2019** to a non-zero value otherwise *pResOut is set to zero. The return value
2020** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2021**
2022** In dotfile locking, either a lock exists or it does not. So in this
2023** variation of CheckReservedLock(), *pResOut is set to true if any lock
2024** is held on the file and false if the file is unlocked.
2025*/
drh734c9862008-11-28 15:37:20 +00002026static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2027 int rc = SQLITE_OK;
2028 int reserved = 0;
2029 unixFile *pFile = (unixFile*)id;
2030
2031 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2032
2033 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00002034 reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
drh308c2a52010-05-14 11:30:18 +00002035 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002036 *pResOut = reserved;
2037 return rc;
2038}
2039
drh7708e972008-11-29 00:56:52 +00002040/*
drh308c2a52010-05-14 11:30:18 +00002041** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002042** of the following:
2043**
2044** (1) SHARED_LOCK
2045** (2) RESERVED_LOCK
2046** (3) PENDING_LOCK
2047** (4) EXCLUSIVE_LOCK
2048**
2049** Sometimes when requesting one lock state, additional lock states
2050** are inserted in between. The locking might fail on one of the later
2051** transitions leaving the lock state different from what it started but
2052** still short of its goal. The following chart shows the allowed
2053** transitions and the inserted intermediate states:
2054**
2055** UNLOCKED -> SHARED
2056** SHARED -> RESERVED
2057** SHARED -> (PENDING) -> EXCLUSIVE
2058** RESERVED -> (PENDING) -> EXCLUSIVE
2059** PENDING -> EXCLUSIVE
2060**
2061** This routine will only increase a lock. Use the sqlite3OsUnlock()
2062** routine to lower a locking level.
2063**
2064** With dotfile locking, we really only support state (4): EXCLUSIVE.
2065** But we track the other locking levels internally.
2066*/
drh308c2a52010-05-14 11:30:18 +00002067static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002068 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002069 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002070 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002071
drh7708e972008-11-29 00:56:52 +00002072
2073 /* If we have any lock, then the lock file already exists. All we have
2074 ** to do is adjust our internal record of the lock level.
2075 */
drh308c2a52010-05-14 11:30:18 +00002076 if( pFile->eFileLock > NO_LOCK ){
2077 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002078 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002079#ifdef HAVE_UTIME
2080 utime(zLockFile, NULL);
2081#else
drh734c9862008-11-28 15:37:20 +00002082 utimes(zLockFile, NULL);
2083#endif
drh7708e972008-11-29 00:56:52 +00002084 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002085 }
2086
2087 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002088 rc = osMkdir(zLockFile, 0777);
2089 if( rc<0 ){
2090 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002091 int tErrno = errno;
2092 if( EEXIST == tErrno ){
2093 rc = SQLITE_BUSY;
2094 } else {
2095 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drha8de1e12015-11-30 00:05:39 +00002096 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00002097 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002098 }
2099 }
drh7708e972008-11-29 00:56:52 +00002100 return rc;
drh734c9862008-11-28 15:37:20 +00002101 }
drh734c9862008-11-28 15:37:20 +00002102
2103 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002104 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002105 return rc;
2106}
2107
drh7708e972008-11-29 00:56:52 +00002108/*
drh308c2a52010-05-14 11:30:18 +00002109** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002110** must be either NO_LOCK or SHARED_LOCK.
2111**
2112** If the locking level of the file descriptor is already at or below
2113** the requested locking level, this routine is a no-op.
2114**
2115** When the locking level reaches NO_LOCK, delete the lock file.
2116*/
drh308c2a52010-05-14 11:30:18 +00002117static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002118 unixFile *pFile = (unixFile*)id;
2119 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002120 int rc;
drh734c9862008-11-28 15:37:20 +00002121
2122 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002123 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002124 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002125 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002126
2127 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002128 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002129 return SQLITE_OK;
2130 }
drh7708e972008-11-29 00:56:52 +00002131
2132 /* To downgrade to shared, simply update our internal notion of the
2133 ** lock state. No need to mess with the file on disk.
2134 */
drh308c2a52010-05-14 11:30:18 +00002135 if( eFileLock==SHARED_LOCK ){
2136 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002137 return SQLITE_OK;
2138 }
2139
drh7708e972008-11-29 00:56:52 +00002140 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002141 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002142 rc = osRmdir(zLockFile);
drh9ef6bc42011-11-04 02:24:02 +00002143 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002144 int tErrno = errno;
drha8de1e12015-11-30 00:05:39 +00002145 if( tErrno==ENOENT ){
2146 rc = SQLITE_OK;
2147 }else{
danea83bc62011-04-01 11:56:32 +00002148 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002149 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002150 }
2151 return rc;
2152 }
drh308c2a52010-05-14 11:30:18 +00002153 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002154 return SQLITE_OK;
2155}
2156
2157/*
drh9b35ea62008-11-29 02:20:26 +00002158** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002159*/
2160static int dotlockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002161 unixFile *pFile = (unixFile*)id;
2162 assert( id!=0 );
2163 dotlockUnlock(id, NO_LOCK);
2164 sqlite3_free(pFile->lockingContext);
2165 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002166}
2167/****************** End of the dot-file lock implementation *******************
2168******************************************************************************/
2169
2170/******************************************************************************
2171************************** Begin flock Locking ********************************
2172**
2173** Use the flock() system call to do file locking.
2174**
drh6b9d6dd2008-12-03 19:34:47 +00002175** flock() locking is like dot-file locking in that the various
2176** fine-grain locking levels supported by SQLite are collapsed into
2177** a single exclusive lock. In other words, SHARED, RESERVED, and
2178** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2179** still works when you do this, but concurrency is reduced since
2180** only a single process can be reading the database at a time.
2181**
drhe89b2912015-03-03 20:42:01 +00002182** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
drh734c9862008-11-28 15:37:20 +00002183*/
drhe89b2912015-03-03 20:42:01 +00002184#if SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002185
drh6b9d6dd2008-12-03 19:34:47 +00002186/*
drhff812312011-02-23 13:33:46 +00002187** Retry flock() calls that fail with EINTR
2188*/
2189#ifdef EINTR
2190static int robust_flock(int fd, int op){
2191 int rc;
2192 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2193 return rc;
2194}
2195#else
drh5c819272011-02-23 14:00:12 +00002196# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002197#endif
2198
2199
2200/*
drh6b9d6dd2008-12-03 19:34:47 +00002201** This routine checks if there is a RESERVED lock held on the specified
2202** file by this or any other process. If such a lock is held, set *pResOut
2203** to a non-zero value otherwise *pResOut is set to zero. The return value
2204** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2205*/
drh734c9862008-11-28 15:37:20 +00002206static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2207 int rc = SQLITE_OK;
2208 int reserved = 0;
2209 unixFile *pFile = (unixFile*)id;
2210
2211 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2212
2213 assert( pFile );
2214
2215 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002216 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002217 reserved = 1;
2218 }
2219
2220 /* Otherwise see if some other process holds it. */
2221 if( !reserved ){
2222 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002223 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002224 if( !lrc ){
2225 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002226 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002227 if ( lrc ) {
2228 int tErrno = errno;
2229 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002230 lrc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00002231 storeLastErrno(pFile, tErrno);
2232 rc = lrc;
drh734c9862008-11-28 15:37:20 +00002233 }
2234 } else {
2235 int tErrno = errno;
2236 reserved = 1;
2237 /* someone else might have it reserved */
2238 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2239 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002240 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002241 rc = lrc;
2242 }
2243 }
2244 }
drh308c2a52010-05-14 11:30:18 +00002245 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002246
2247#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2248 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2249 rc = SQLITE_OK;
2250 reserved=1;
2251 }
2252#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2253 *pResOut = reserved;
2254 return rc;
2255}
2256
drh6b9d6dd2008-12-03 19:34:47 +00002257/*
drh308c2a52010-05-14 11:30:18 +00002258** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002259** of the following:
2260**
2261** (1) SHARED_LOCK
2262** (2) RESERVED_LOCK
2263** (3) PENDING_LOCK
2264** (4) EXCLUSIVE_LOCK
2265**
2266** Sometimes when requesting one lock state, additional lock states
2267** are inserted in between. The locking might fail on one of the later
2268** transitions leaving the lock state different from what it started but
2269** still short of its goal. The following chart shows the allowed
2270** transitions and the inserted intermediate states:
2271**
2272** UNLOCKED -> SHARED
2273** SHARED -> RESERVED
2274** SHARED -> (PENDING) -> EXCLUSIVE
2275** RESERVED -> (PENDING) -> EXCLUSIVE
2276** PENDING -> EXCLUSIVE
2277**
2278** flock() only really support EXCLUSIVE locks. We track intermediate
2279** lock states in the sqlite3_file structure, but all locks SHARED or
2280** above are really EXCLUSIVE locks and exclude all other processes from
2281** access the file.
2282**
2283** This routine will only increase a lock. Use the sqlite3OsUnlock()
2284** routine to lower a locking level.
2285*/
drh308c2a52010-05-14 11:30:18 +00002286static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002287 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002288 unixFile *pFile = (unixFile*)id;
2289
2290 assert( pFile );
2291
2292 /* if we already have a lock, it is exclusive.
2293 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002294 if (pFile->eFileLock > NO_LOCK) {
2295 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002296 return SQLITE_OK;
2297 }
2298
2299 /* grab an exclusive lock */
2300
drhff812312011-02-23 13:33:46 +00002301 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002302 int tErrno = errno;
2303 /* didn't get, must be busy */
2304 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2305 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002306 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002307 }
2308 } else {
2309 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002310 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002311 }
drh308c2a52010-05-14 11:30:18 +00002312 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2313 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002314#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2315 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2316 rc = SQLITE_BUSY;
2317 }
2318#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2319 return rc;
2320}
2321
drh6b9d6dd2008-12-03 19:34:47 +00002322
2323/*
drh308c2a52010-05-14 11:30:18 +00002324** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002325** must be either NO_LOCK or SHARED_LOCK.
2326**
2327** If the locking level of the file descriptor is already at or below
2328** the requested locking level, this routine is a no-op.
2329*/
drh308c2a52010-05-14 11:30:18 +00002330static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002331 unixFile *pFile = (unixFile*)id;
2332
2333 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002334 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002335 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002336 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002337
2338 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002339 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002340 return SQLITE_OK;
2341 }
2342
2343 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002344 if (eFileLock==SHARED_LOCK) {
2345 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002346 return SQLITE_OK;
2347 }
2348
2349 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002350 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002351#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002352 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002353#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002354 return SQLITE_IOERR_UNLOCK;
2355 }else{
drh308c2a52010-05-14 11:30:18 +00002356 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002357 return SQLITE_OK;
2358 }
2359}
2360
2361/*
2362** Close a file.
2363*/
2364static int flockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002365 assert( id!=0 );
2366 flockUnlock(id, NO_LOCK);
2367 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002368}
2369
2370#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2371
2372/******************* End of the flock lock implementation *********************
2373******************************************************************************/
2374
2375/******************************************************************************
2376************************ Begin Named Semaphore Locking ************************
2377**
2378** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002379**
2380** Semaphore locking is like dot-lock and flock in that it really only
2381** supports EXCLUSIVE locking. Only a single process can read or write
2382** the database file at a time. This reduces potential concurrency, but
2383** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002384*/
2385#if OS_VXWORKS
2386
drh6b9d6dd2008-12-03 19:34:47 +00002387/*
2388** This routine checks if there is a RESERVED lock held on the specified
2389** file by this or any other process. If such a lock is held, set *pResOut
2390** to a non-zero value otherwise *pResOut is set to zero. The return value
2391** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2392*/
drh8cd5b252015-03-02 22:06:43 +00002393static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
drh734c9862008-11-28 15:37:20 +00002394 int rc = SQLITE_OK;
2395 int reserved = 0;
2396 unixFile *pFile = (unixFile*)id;
2397
2398 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2399
2400 assert( pFile );
2401
2402 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002403 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002404 reserved = 1;
2405 }
2406
2407 /* Otherwise see if some other process holds it. */
2408 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002409 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002410
2411 if( sem_trywait(pSem)==-1 ){
2412 int tErrno = errno;
2413 if( EAGAIN != tErrno ){
2414 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
drh4bf66fd2015-02-19 02:43:02 +00002415 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002416 } else {
2417 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002418 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002419 }
2420 }else{
2421 /* we could have it if we want it */
2422 sem_post(pSem);
2423 }
2424 }
drh308c2a52010-05-14 11:30:18 +00002425 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002426
2427 *pResOut = reserved;
2428 return rc;
2429}
2430
drh6b9d6dd2008-12-03 19:34:47 +00002431/*
drh308c2a52010-05-14 11:30:18 +00002432** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002433** of the following:
2434**
2435** (1) SHARED_LOCK
2436** (2) RESERVED_LOCK
2437** (3) PENDING_LOCK
2438** (4) EXCLUSIVE_LOCK
2439**
2440** Sometimes when requesting one lock state, additional lock states
2441** are inserted in between. The locking might fail on one of the later
2442** transitions leaving the lock state different from what it started but
2443** still short of its goal. The following chart shows the allowed
2444** transitions and the inserted intermediate states:
2445**
2446** UNLOCKED -> SHARED
2447** SHARED -> RESERVED
2448** SHARED -> (PENDING) -> EXCLUSIVE
2449** RESERVED -> (PENDING) -> EXCLUSIVE
2450** PENDING -> EXCLUSIVE
2451**
2452** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2453** lock states in the sqlite3_file structure, but all locks SHARED or
2454** above are really EXCLUSIVE locks and exclude all other processes from
2455** access the file.
2456**
2457** This routine will only increase a lock. Use the sqlite3OsUnlock()
2458** routine to lower a locking level.
2459*/
drh8cd5b252015-03-02 22:06:43 +00002460static int semXLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002461 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002462 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002463 int rc = SQLITE_OK;
2464
2465 /* if we already have a lock, it is exclusive.
2466 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002467 if (pFile->eFileLock > NO_LOCK) {
2468 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002469 rc = SQLITE_OK;
2470 goto sem_end_lock;
2471 }
2472
2473 /* lock semaphore now but bail out when already locked. */
2474 if( sem_trywait(pSem)==-1 ){
2475 rc = SQLITE_BUSY;
2476 goto sem_end_lock;
2477 }
2478
2479 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002480 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002481
2482 sem_end_lock:
2483 return rc;
2484}
2485
drh6b9d6dd2008-12-03 19:34:47 +00002486/*
drh308c2a52010-05-14 11:30:18 +00002487** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002488** must be either NO_LOCK or SHARED_LOCK.
2489**
2490** If the locking level of the file descriptor is already at or below
2491** the requested locking level, this routine is a no-op.
2492*/
drh8cd5b252015-03-02 22:06:43 +00002493static int semXUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002494 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002495 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002496
2497 assert( pFile );
2498 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002499 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002500 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002501 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002502
2503 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002504 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002505 return SQLITE_OK;
2506 }
2507
2508 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002509 if (eFileLock==SHARED_LOCK) {
2510 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002511 return SQLITE_OK;
2512 }
2513
2514 /* no, really unlock. */
2515 if ( sem_post(pSem)==-1 ) {
2516 int rc, tErrno = errno;
2517 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2518 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002519 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002520 }
2521 return rc;
2522 }
drh308c2a52010-05-14 11:30:18 +00002523 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002524 return SQLITE_OK;
2525}
2526
2527/*
2528 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002529 */
drh8cd5b252015-03-02 22:06:43 +00002530static int semXClose(sqlite3_file *id) {
drh734c9862008-11-28 15:37:20 +00002531 if( id ){
2532 unixFile *pFile = (unixFile*)id;
drh8cd5b252015-03-02 22:06:43 +00002533 semXUnlock(id, NO_LOCK);
drh734c9862008-11-28 15:37:20 +00002534 assert( pFile );
2535 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002536 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002537 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002538 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002539 }
2540 return SQLITE_OK;
2541}
2542
2543#endif /* OS_VXWORKS */
2544/*
2545** Named semaphore locking is only available on VxWorks.
2546**
2547*************** End of the named semaphore lock implementation ****************
2548******************************************************************************/
2549
2550
2551/******************************************************************************
2552*************************** Begin AFP Locking *********************************
2553**
2554** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2555** on Apple Macintosh computers - both OS9 and OSX.
2556**
2557** Third-party implementations of AFP are available. But this code here
2558** only works on OSX.
2559*/
2560
drhd2cb50b2009-01-09 21:41:17 +00002561#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002562/*
2563** The afpLockingContext structure contains all afp lock specific state
2564*/
drhbfe66312006-10-03 17:40:40 +00002565typedef struct afpLockingContext afpLockingContext;
2566struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002567 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002568 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002569};
2570
2571struct ByteRangeLockPB2
2572{
2573 unsigned long long offset; /* offset to first byte to lock */
2574 unsigned long long length; /* nbr of bytes to lock */
2575 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2576 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2577 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2578 int fd; /* file desc to assoc this lock with */
2579};
2580
drhfd131da2007-08-07 17:13:03 +00002581#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002582
drh6b9d6dd2008-12-03 19:34:47 +00002583/*
2584** This is a utility for setting or clearing a bit-range lock on an
2585** AFP filesystem.
2586**
2587** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2588*/
2589static int afpSetLock(
2590 const char *path, /* Name of the file to be locked or unlocked */
2591 unixFile *pFile, /* Open file descriptor on path */
2592 unsigned long long offset, /* First byte to be locked */
2593 unsigned long long length, /* Number of bytes to lock */
2594 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002595){
drh6b9d6dd2008-12-03 19:34:47 +00002596 struct ByteRangeLockPB2 pb;
2597 int err;
drhbfe66312006-10-03 17:40:40 +00002598
2599 pb.unLockFlag = setLockFlag ? 0 : 1;
2600 pb.startEndFlag = 0;
2601 pb.offset = offset;
2602 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002603 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002604
drh308c2a52010-05-14 11:30:18 +00002605 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002606 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002607 offset, length));
drhbfe66312006-10-03 17:40:40 +00002608 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2609 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002610 int rc;
2611 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002612 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2613 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002614#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2615 rc = SQLITE_BUSY;
2616#else
drh734c9862008-11-28 15:37:20 +00002617 rc = sqliteErrorFromPosixError(tErrno,
2618 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002619#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002620 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002621 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00002622 }
2623 return rc;
drhbfe66312006-10-03 17:40:40 +00002624 } else {
aswift5b1a2562008-08-22 00:22:35 +00002625 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002626 }
2627}
2628
drh6b9d6dd2008-12-03 19:34:47 +00002629/*
2630** This routine checks if there is a RESERVED lock held on the specified
2631** file by this or any other process. If such a lock is held, set *pResOut
2632** to a non-zero value otherwise *pResOut is set to zero. The return value
2633** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2634*/
danielk1977e339d652008-06-28 11:23:00 +00002635static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002636 int rc = SQLITE_OK;
2637 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002638 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002639 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002640
aswift5b1a2562008-08-22 00:22:35 +00002641 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2642
2643 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002644 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002645 if( context->reserved ){
2646 *pResOut = 1;
2647 return SQLITE_OK;
2648 }
drh8af6c222010-05-14 12:43:01 +00002649 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002650
2651 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002652 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002653 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002654 }
2655
2656 /* Otherwise see if some other process holds it.
2657 */
aswift5b1a2562008-08-22 00:22:35 +00002658 if( !reserved ){
2659 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002660 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002661 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002662 /* if we succeeded in taking the reserved lock, unlock it to restore
2663 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002664 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002665 } else {
2666 /* if we failed to get the lock then someone else must have it */
2667 reserved = 1;
2668 }
2669 if( IS_LOCK_ERROR(lrc) ){
2670 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002671 }
2672 }
drhbfe66312006-10-03 17:40:40 +00002673
drh7ed97b92010-01-20 13:07:21 +00002674 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002675 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002676
2677 *pResOut = reserved;
2678 return rc;
drhbfe66312006-10-03 17:40:40 +00002679}
2680
drh6b9d6dd2008-12-03 19:34:47 +00002681/*
drh308c2a52010-05-14 11:30:18 +00002682** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002683** of the following:
2684**
2685** (1) SHARED_LOCK
2686** (2) RESERVED_LOCK
2687** (3) PENDING_LOCK
2688** (4) EXCLUSIVE_LOCK
2689**
2690** Sometimes when requesting one lock state, additional lock states
2691** are inserted in between. The locking might fail on one of the later
2692** transitions leaving the lock state different from what it started but
2693** still short of its goal. The following chart shows the allowed
2694** transitions and the inserted intermediate states:
2695**
2696** UNLOCKED -> SHARED
2697** SHARED -> RESERVED
2698** SHARED -> (PENDING) -> EXCLUSIVE
2699** RESERVED -> (PENDING) -> EXCLUSIVE
2700** PENDING -> EXCLUSIVE
2701**
2702** This routine will only increase a lock. Use the sqlite3OsUnlock()
2703** routine to lower a locking level.
2704*/
drh308c2a52010-05-14 11:30:18 +00002705static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002706 int rc = SQLITE_OK;
2707 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002708 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002709 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002710
2711 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002712 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2713 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh5ac93652015-03-21 20:59:43 +00002714 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
drh339eb0b2008-03-07 15:34:11 +00002715
drhbfe66312006-10-03 17:40:40 +00002716 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002717 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002718 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002719 */
drh308c2a52010-05-14 11:30:18 +00002720 if( pFile->eFileLock>=eFileLock ){
2721 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2722 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002723 return SQLITE_OK;
2724 }
2725
2726 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002727 ** (1) We never move from unlocked to anything higher than shared lock.
2728 ** (2) SQLite never explicitly requests a pendig lock.
2729 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002730 */
drh308c2a52010-05-14 11:30:18 +00002731 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2732 assert( eFileLock!=PENDING_LOCK );
2733 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002734
drh8af6c222010-05-14 12:43:01 +00002735 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002736 */
drh6c7d5c52008-11-21 20:32:33 +00002737 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002738 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002739
2740 /* If some thread using this PID has a lock via a different unixFile*
2741 ** handle that precludes the requested lock, return BUSY.
2742 */
drh8af6c222010-05-14 12:43:01 +00002743 if( (pFile->eFileLock!=pInode->eFileLock &&
2744 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002745 ){
2746 rc = SQLITE_BUSY;
2747 goto afp_end_lock;
2748 }
2749
2750 /* If a SHARED lock is requested, and some thread using this PID already
2751 ** has a SHARED or RESERVED lock, then increment reference counts and
2752 ** return SQLITE_OK.
2753 */
drh308c2a52010-05-14 11:30:18 +00002754 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002755 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002756 assert( eFileLock==SHARED_LOCK );
2757 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002758 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002759 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002760 pInode->nShared++;
2761 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002762 goto afp_end_lock;
2763 }
drhbfe66312006-10-03 17:40:40 +00002764
2765 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002766 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2767 ** be released.
2768 */
drh308c2a52010-05-14 11:30:18 +00002769 if( eFileLock==SHARED_LOCK
2770 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002771 ){
2772 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002773 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002774 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002775 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002776 goto afp_end_lock;
2777 }
2778 }
2779
2780 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002781 ** operating system calls for the specified lock.
2782 */
drh308c2a52010-05-14 11:30:18 +00002783 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002784 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002785 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002786
drh8af6c222010-05-14 12:43:01 +00002787 assert( pInode->nShared==0 );
2788 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002789
2790 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002791 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002792 /* note that the quality of the randomness doesn't matter that much */
2793 lk = random();
drh8af6c222010-05-14 12:43:01 +00002794 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002795 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002796 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002797 if( IS_LOCK_ERROR(lrc1) ){
2798 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002799 }
aswift5b1a2562008-08-22 00:22:35 +00002800 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002801 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002802
aswift5b1a2562008-08-22 00:22:35 +00002803 if( IS_LOCK_ERROR(lrc1) ) {
drh4bf66fd2015-02-19 02:43:02 +00002804 storeLastErrno(pFile, lrc1Errno);
aswift5b1a2562008-08-22 00:22:35 +00002805 rc = lrc1;
2806 goto afp_end_lock;
2807 } else if( IS_LOCK_ERROR(lrc2) ){
2808 rc = lrc2;
2809 goto afp_end_lock;
2810 } else if( lrc1 != SQLITE_OK ) {
2811 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002812 } else {
drh308c2a52010-05-14 11:30:18 +00002813 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002814 pInode->nLock++;
2815 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002816 }
drh8af6c222010-05-14 12:43:01 +00002817 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002818 /* We are trying for an exclusive lock but another thread in this
2819 ** same process is still holding a shared lock. */
2820 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002821 }else{
2822 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2823 ** assumed that there is a SHARED or greater lock on the file
2824 ** already.
2825 */
2826 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002827 assert( 0!=pFile->eFileLock );
2828 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002829 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002830 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002831 if( !failed ){
2832 context->reserved = 1;
2833 }
drhbfe66312006-10-03 17:40:40 +00002834 }
drh308c2a52010-05-14 11:30:18 +00002835 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002836 /* Acquire an EXCLUSIVE lock */
2837
2838 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002839 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002840 */
drh6b9d6dd2008-12-03 19:34:47 +00002841 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002842 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002843 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002844 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002845 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002846 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002847 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002848 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002849 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2850 ** a critical I/O error
2851 */
2852 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2853 SQLITE_IOERR_LOCK;
2854 goto afp_end_lock;
2855 }
2856 }else{
aswift5b1a2562008-08-22 00:22:35 +00002857 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002858 }
2859 }
aswift5b1a2562008-08-22 00:22:35 +00002860 if( failed ){
2861 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002862 }
2863 }
2864
2865 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002866 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002867 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002868 }else if( eFileLock==EXCLUSIVE_LOCK ){
2869 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002870 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002871 }
2872
2873afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002874 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002875 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2876 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002877 return rc;
2878}
2879
2880/*
drh308c2a52010-05-14 11:30:18 +00002881** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002882** must be either NO_LOCK or SHARED_LOCK.
2883**
2884** If the locking level of the file descriptor is already at or below
2885** the requested locking level, this routine is a no-op.
2886*/
drh308c2a52010-05-14 11:30:18 +00002887static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002888 int rc = SQLITE_OK;
2889 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002890 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002891 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2892 int skipShared = 0;
2893#ifdef SQLITE_TEST
2894 int h = pFile->h;
2895#endif
drhbfe66312006-10-03 17:40:40 +00002896
2897 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002898 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002899 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00002900 osGetpid(0)));
aswift5b1a2562008-08-22 00:22:35 +00002901
drh308c2a52010-05-14 11:30:18 +00002902 assert( eFileLock<=SHARED_LOCK );
2903 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002904 return SQLITE_OK;
2905 }
drh6c7d5c52008-11-21 20:32:33 +00002906 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002907 pInode = pFile->pInode;
2908 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002909 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002910 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002911 SimulateIOErrorBenign(1);
2912 SimulateIOError( h=(-1) )
2913 SimulateIOErrorBenign(0);
2914
drhd3d8c042012-05-29 17:02:40 +00002915#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002916 /* When reducing a lock such that other processes can start
2917 ** reading the database file again, make sure that the
2918 ** transaction counter was updated if any part of the database
2919 ** file changed. If the transaction counter is not updated,
2920 ** other connections to the same file might not realize that
2921 ** the file has changed and hence might not know to flush their
2922 ** cache. The use of a stale cache can lead to database corruption.
2923 */
2924 assert( pFile->inNormalWrite==0
2925 || pFile->dbUpdate==0
2926 || pFile->transCntrChng==1 );
2927 pFile->inNormalWrite = 0;
2928#endif
aswiftaebf4132008-11-21 00:10:35 +00002929
drh308c2a52010-05-14 11:30:18 +00002930 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002931 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002932 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002933 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002934 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002935 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2936 } else {
2937 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002938 }
2939 }
drh308c2a52010-05-14 11:30:18 +00002940 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002941 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002942 }
drh308c2a52010-05-14 11:30:18 +00002943 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002944 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2945 if( !rc ){
2946 context->reserved = 0;
2947 }
aswiftaebf4132008-11-21 00:10:35 +00002948 }
drh8af6c222010-05-14 12:43:01 +00002949 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2950 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002951 }
aswiftaebf4132008-11-21 00:10:35 +00002952 }
drh308c2a52010-05-14 11:30:18 +00002953 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002954
drh7ed97b92010-01-20 13:07:21 +00002955 /* Decrement the shared lock counter. Release the lock using an
2956 ** OS call only when all threads in this same process have released
2957 ** the lock.
2958 */
drh8af6c222010-05-14 12:43:01 +00002959 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2960 pInode->nShared--;
2961 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002962 SimulateIOErrorBenign(1);
2963 SimulateIOError( h=(-1) )
2964 SimulateIOErrorBenign(0);
2965 if( !skipShared ){
2966 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2967 }
2968 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002969 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002970 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002971 }
2972 }
2973 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002974 pInode->nLock--;
2975 assert( pInode->nLock>=0 );
2976 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002977 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002978 }
2979 }
drhbfe66312006-10-03 17:40:40 +00002980 }
drh7ed97b92010-01-20 13:07:21 +00002981
drh6c7d5c52008-11-21 20:32:33 +00002982 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002983 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002984 return rc;
2985}
2986
2987/*
drh339eb0b2008-03-07 15:34:11 +00002988** Close a file & cleanup AFP specific locking context
2989*/
danielk1977e339d652008-06-28 11:23:00 +00002990static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002991 int rc = SQLITE_OK;
drha8de1e12015-11-30 00:05:39 +00002992 unixFile *pFile = (unixFile*)id;
2993 assert( id!=0 );
2994 afpUnlock(id, NO_LOCK);
2995 unixEnterMutex();
2996 if( pFile->pInode && pFile->pInode->nLock ){
2997 /* If there are outstanding locks, do not actually close the file just
2998 ** yet because that would clear those locks. Instead, add the file
2999 ** descriptor to pInode->aPending. It will be automatically closed when
3000 ** the last lock is cleared.
3001 */
3002 setPendingFd(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003003 }
drha8de1e12015-11-30 00:05:39 +00003004 releaseInodeInfo(pFile);
3005 sqlite3_free(pFile->lockingContext);
3006 rc = closeUnixFile(id);
3007 unixLeaveMutex();
drh7ed97b92010-01-20 13:07:21 +00003008 return rc;
drhbfe66312006-10-03 17:40:40 +00003009}
3010
drhd2cb50b2009-01-09 21:41:17 +00003011#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003012/*
3013** The code above is the AFP lock implementation. The code is specific
3014** to MacOSX and does not work on other unix platforms. No alternative
3015** is available. If you don't compile for a mac, then the "unix-afp"
3016** VFS is not available.
3017**
3018********************* End of the AFP lock implementation **********************
3019******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003020
drh7ed97b92010-01-20 13:07:21 +00003021/******************************************************************************
3022*************************** Begin NFS Locking ********************************/
3023
3024#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3025/*
drh308c2a52010-05-14 11:30:18 +00003026 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003027 ** must be either NO_LOCK or SHARED_LOCK.
3028 **
3029 ** If the locking level of the file descriptor is already at or below
3030 ** the requested locking level, this routine is a no-op.
3031 */
drh308c2a52010-05-14 11:30:18 +00003032static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003033 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003034}
3035
3036#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3037/*
3038** The code above is the NFS lock implementation. The code is specific
3039** to MacOSX and does not work on other unix platforms. No alternative
3040** is available.
3041**
3042********************* End of the NFS lock implementation **********************
3043******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003044
3045/******************************************************************************
3046**************** Non-locking sqlite3_file methods *****************************
3047**
3048** The next division contains implementations for all methods of the
3049** sqlite3_file object other than the locking methods. The locking
3050** methods were defined in divisions above (one locking method per
3051** division). Those methods that are common to all locking modes
3052** are gather together into this division.
3053*/
drhbfe66312006-10-03 17:40:40 +00003054
3055/*
drh734c9862008-11-28 15:37:20 +00003056** Seek to the offset passed as the second argument, then read cnt
3057** bytes into pBuf. Return the number of bytes actually read.
3058**
3059** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3060** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3061** one system to another. Since SQLite does not define USE_PREAD
peter.d.reid60ec9142014-09-06 16:39:46 +00003062** in any form by default, we will not attempt to define _XOPEN_SOURCE.
drh734c9862008-11-28 15:37:20 +00003063** See tickets #2741 and #2681.
3064**
3065** To avoid stomping the errno value on a failed read the lastErrno value
3066** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003067*/
drh734c9862008-11-28 15:37:20 +00003068static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3069 int got;
drh58024642011-11-07 18:16:00 +00003070 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003071#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003072 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003073#endif
drh734c9862008-11-28 15:37:20 +00003074 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003075 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003076 assert( id->h>2 );
drh58024642011-11-07 18:16:00 +00003077 do{
drh734c9862008-11-28 15:37:20 +00003078#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003079 got = osPread(id->h, pBuf, cnt, offset);
3080 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003081#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003082 got = osPread64(id->h, pBuf, cnt, offset);
3083 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003084#else
drh58024642011-11-07 18:16:00 +00003085 newOffset = lseek(id->h, offset, SEEK_SET);
drhe1818ec2015-12-01 16:21:35 +00003086 SimulateIOError( newOffset = -1 );
3087 if( newOffset<0 ){
3088 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003089 return -1;
drh734c9862008-11-28 15:37:20 +00003090 }
drh58024642011-11-07 18:16:00 +00003091 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003092#endif
drh58024642011-11-07 18:16:00 +00003093 if( got==cnt ) break;
3094 if( got<0 ){
3095 if( errno==EINTR ){ got = 1; continue; }
3096 prior = 0;
drh4bf66fd2015-02-19 02:43:02 +00003097 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003098 break;
3099 }else if( got>0 ){
3100 cnt -= got;
3101 offset += got;
3102 prior += got;
3103 pBuf = (void*)(got + (char*)pBuf);
3104 }
3105 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003106 TIMER_END;
drh58024642011-11-07 18:16:00 +00003107 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3108 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3109 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003110}
3111
3112/*
drh734c9862008-11-28 15:37:20 +00003113** Read data from a file into a buffer. Return SQLITE_OK if all
3114** bytes were read successfully and SQLITE_IOERR if anything goes
3115** wrong.
drh339eb0b2008-03-07 15:34:11 +00003116*/
drh734c9862008-11-28 15:37:20 +00003117static int unixRead(
3118 sqlite3_file *id,
3119 void *pBuf,
3120 int amt,
3121 sqlite3_int64 offset
3122){
dan08da86a2009-08-21 17:18:03 +00003123 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003124 int got;
3125 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003126 assert( offset>=0 );
3127 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003128
dan08da86a2009-08-21 17:18:03 +00003129 /* If this is a database file (not a journal, master-journal or temp
3130 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003131#if 0
dane946c392009-08-22 11:39:46 +00003132 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003133 || offset>=PENDING_BYTE+512
3134 || offset+amt<=PENDING_BYTE
3135 );
dan7c246102010-04-12 19:00:29 +00003136#endif
drh08c6d442009-02-09 17:34:07 +00003137
drh9b4c59f2013-04-15 17:03:42 +00003138#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003139 /* Deal with as much of this read request as possible by transfering
3140 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003141 if( offset<pFile->mmapSize ){
3142 if( offset+amt <= pFile->mmapSize ){
3143 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3144 return SQLITE_OK;
3145 }else{
3146 int nCopy = pFile->mmapSize - offset;
3147 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3148 pBuf = &((u8 *)pBuf)[nCopy];
3149 amt -= nCopy;
3150 offset += nCopy;
3151 }
3152 }
drh6e0b6d52013-04-09 16:19:20 +00003153#endif
danf23da962013-03-23 21:00:41 +00003154
dan08da86a2009-08-21 17:18:03 +00003155 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003156 if( got==amt ){
3157 return SQLITE_OK;
3158 }else if( got<0 ){
3159 /* lastErrno set by seekAndRead */
3160 return SQLITE_IOERR_READ;
3161 }else{
drh4bf66fd2015-02-19 02:43:02 +00003162 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003163 /* Unread parts of the buffer must be zero-filled */
3164 memset(&((char*)pBuf)[got], 0, amt-got);
3165 return SQLITE_IOERR_SHORT_READ;
3166 }
3167}
3168
3169/*
dan47a2b4a2013-04-26 16:09:29 +00003170** Attempt to seek the file-descriptor passed as the first argument to
3171** absolute offset iOff, then attempt to write nBuf bytes of data from
3172** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3173** return the actual number of bytes written (which may be less than
3174** nBuf).
3175*/
3176static int seekAndWriteFd(
3177 int fd, /* File descriptor to write to */
3178 i64 iOff, /* File offset to begin writing at */
3179 const void *pBuf, /* Copy data from this buffer to the file */
3180 int nBuf, /* Size of buffer pBuf in bytes */
3181 int *piErrno /* OUT: Error number if error occurs */
3182){
3183 int rc = 0; /* Value returned by system call */
3184
3185 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003186 assert( fd>2 );
drhe1818ec2015-12-01 16:21:35 +00003187 assert( piErrno!=0 );
dan47a2b4a2013-04-26 16:09:29 +00003188 nBuf &= 0x1ffff;
3189 TIMER_START;
3190
3191#if defined(USE_PREAD)
drh2da47d32015-02-21 00:56:05 +00003192 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
dan47a2b4a2013-04-26 16:09:29 +00003193#elif defined(USE_PREAD64)
drh2da47d32015-02-21 00:56:05 +00003194 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
dan47a2b4a2013-04-26 16:09:29 +00003195#else
3196 do{
3197 i64 iSeek = lseek(fd, iOff, SEEK_SET);
drhe1818ec2015-12-01 16:21:35 +00003198 SimulateIOError( iSeek = -1 );
3199 if( iSeek<0 ){
3200 rc = -1;
3201 break;
dan47a2b4a2013-04-26 16:09:29 +00003202 }
3203 rc = osWrite(fd, pBuf, nBuf);
3204 }while( rc<0 && errno==EINTR );
3205#endif
3206
3207 TIMER_END;
3208 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3209
drhe1818ec2015-12-01 16:21:35 +00003210 if( rc<0 ) *piErrno = errno;
dan47a2b4a2013-04-26 16:09:29 +00003211 return rc;
3212}
3213
3214
3215/*
drh734c9862008-11-28 15:37:20 +00003216** Seek to the offset in id->offset then read cnt bytes into pBuf.
3217** Return the number of bytes actually read. Update the offset.
3218**
3219** To avoid stomping the errno value on a failed write the lastErrno value
3220** is set before returning.
3221*/
3222static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003223 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003224}
3225
3226
3227/*
3228** Write data from a buffer into a file. Return SQLITE_OK on success
3229** or some other error code on failure.
3230*/
3231static int unixWrite(
3232 sqlite3_file *id,
3233 const void *pBuf,
3234 int amt,
3235 sqlite3_int64 offset
3236){
dan08da86a2009-08-21 17:18:03 +00003237 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003238 int wrote = 0;
3239 assert( id );
3240 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003241
dan08da86a2009-08-21 17:18:03 +00003242 /* If this is a database file (not a journal, master-journal or temp
3243 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003244#if 0
dane946c392009-08-22 11:39:46 +00003245 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003246 || offset>=PENDING_BYTE+512
3247 || offset+amt<=PENDING_BYTE
3248 );
dan7c246102010-04-12 19:00:29 +00003249#endif
drh08c6d442009-02-09 17:34:07 +00003250
drhd3d8c042012-05-29 17:02:40 +00003251#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003252 /* If we are doing a normal write to a database file (as opposed to
3253 ** doing a hot-journal rollback or a write to some file other than a
3254 ** normal database file) then record the fact that the database
3255 ** has changed. If the transaction counter is modified, record that
3256 ** fact too.
3257 */
dan08da86a2009-08-21 17:18:03 +00003258 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003259 pFile->dbUpdate = 1; /* The database has been modified */
3260 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003261 int rc;
drh8f941bc2009-01-14 23:03:40 +00003262 char oldCntr[4];
3263 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003264 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003265 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003266 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003267 pFile->transCntrChng = 1; /* The transaction counter has changed */
3268 }
3269 }
3270 }
3271#endif
3272
danfe33e392015-11-17 20:56:06 +00003273#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003274 /* Deal with as much of this write request as possible by transfering
3275 ** data from the memory mapping using memcpy(). */
3276 if( offset<pFile->mmapSize ){
3277 if( offset+amt <= pFile->mmapSize ){
3278 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3279 return SQLITE_OK;
3280 }else{
3281 int nCopy = pFile->mmapSize - offset;
3282 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3283 pBuf = &((u8 *)pBuf)[nCopy];
3284 amt -= nCopy;
3285 offset += nCopy;
3286 }
3287 }
drh6e0b6d52013-04-09 16:19:20 +00003288#endif
drh02bf8b42015-09-01 23:51:53 +00003289
3290 while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
drh734c9862008-11-28 15:37:20 +00003291 amt -= wrote;
3292 offset += wrote;
3293 pBuf = &((char*)pBuf)[wrote];
3294 }
3295 SimulateIOError(( wrote=(-1), amt=1 ));
3296 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003297
drh02bf8b42015-09-01 23:51:53 +00003298 if( amt>wrote ){
drha21b83b2011-04-15 12:36:10 +00003299 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003300 /* lastErrno set by seekAndWrite */
3301 return SQLITE_IOERR_WRITE;
3302 }else{
drh4bf66fd2015-02-19 02:43:02 +00003303 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003304 return SQLITE_FULL;
3305 }
3306 }
dan6e09d692010-07-27 18:34:15 +00003307
drh734c9862008-11-28 15:37:20 +00003308 return SQLITE_OK;
3309}
3310
3311#ifdef SQLITE_TEST
3312/*
3313** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003314** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003315*/
3316int sqlite3_sync_count = 0;
3317int sqlite3_fullsync_count = 0;
3318#endif
3319
3320/*
drh89240432009-03-25 01:06:01 +00003321** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003322** Others do no. To be safe, we will stick with the (slightly slower)
3323** fsync(). If you know that your system does support fdatasync() correctly,
drhf7a4a1b2015-01-10 18:02:45 +00003324** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003325*/
drhf7a4a1b2015-01-10 18:02:45 +00003326#if !defined(fdatasync) && !HAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003327# define fdatasync fsync
3328#endif
3329
3330/*
3331** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3332** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3333** only available on Mac OS X. But that could change.
3334*/
3335#ifdef F_FULLFSYNC
3336# define HAVE_FULLFSYNC 1
3337#else
3338# define HAVE_FULLFSYNC 0
3339#endif
3340
3341
3342/*
3343** The fsync() system call does not work as advertised on many
3344** unix systems. The following procedure is an attempt to make
3345** it work better.
3346**
3347** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3348** for testing when we want to run through the test suite quickly.
3349** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3350** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3351** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003352**
3353** SQLite sets the dataOnly flag if the size of the file is unchanged.
3354** The idea behind dataOnly is that it should only write the file content
3355** to disk, not the inode. We only set dataOnly if the file size is
3356** unchanged since the file size is part of the inode. However,
3357** Ted Ts'o tells us that fdatasync() will also write the inode if the
3358** file size has changed. The only real difference between fdatasync()
3359** and fsync(), Ted tells us, is that fdatasync() will not flush the
3360** inode if the mtime or owner or other inode attributes have changed.
3361** We only care about the file size, not the other file attributes, so
3362** as far as SQLite is concerned, an fdatasync() is always adequate.
3363** So, we always use fdatasync() if it is available, regardless of
3364** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003365*/
3366static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003367 int rc;
drh734c9862008-11-28 15:37:20 +00003368
3369 /* The following "ifdef/elif/else/" block has the same structure as
3370 ** the one below. It is replicated here solely to avoid cluttering
3371 ** up the real code with the UNUSED_PARAMETER() macros.
3372 */
3373#ifdef SQLITE_NO_SYNC
3374 UNUSED_PARAMETER(fd);
3375 UNUSED_PARAMETER(fullSync);
3376 UNUSED_PARAMETER(dataOnly);
3377#elif HAVE_FULLFSYNC
3378 UNUSED_PARAMETER(dataOnly);
3379#else
3380 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003381 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003382#endif
3383
3384 /* Record the number of times that we do a normal fsync() and
3385 ** FULLSYNC. This is used during testing to verify that this procedure
3386 ** gets called with the correct arguments.
3387 */
3388#ifdef SQLITE_TEST
3389 if( fullSync ) sqlite3_fullsync_count++;
3390 sqlite3_sync_count++;
3391#endif
3392
3393 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3394 ** no-op
3395 */
3396#ifdef SQLITE_NO_SYNC
3397 rc = SQLITE_OK;
3398#elif HAVE_FULLFSYNC
3399 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003400 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003401 }else{
3402 rc = 1;
3403 }
3404 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003405 ** It shouldn't be possible for fullfsync to fail on the local
3406 ** file system (on OSX), so failure indicates that FULLFSYNC
3407 ** isn't supported for this file system. So, attempt an fsync
3408 ** and (for now) ignore the overhead of a superfluous fcntl call.
3409 ** It'd be better to detect fullfsync support once and avoid
3410 ** the fcntl call every time sync is called.
3411 */
drh734c9862008-11-28 15:37:20 +00003412 if( rc ) rc = fsync(fd);
3413
drh7ed97b92010-01-20 13:07:21 +00003414#elif defined(__APPLE__)
3415 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3416 ** so currently we default to the macro that redefines fdatasync to fsync
3417 */
3418 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003419#else
drh0b647ff2009-03-21 14:41:04 +00003420 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003421#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003422 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003423 rc = fsync(fd);
3424 }
drh0b647ff2009-03-21 14:41:04 +00003425#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003426#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3427
3428 if( OS_VXWORKS && rc!= -1 ){
3429 rc = 0;
3430 }
chw97185482008-11-17 08:05:31 +00003431 return rc;
drhbfe66312006-10-03 17:40:40 +00003432}
3433
drh734c9862008-11-28 15:37:20 +00003434/*
drh0059eae2011-08-08 23:48:40 +00003435** Open a file descriptor to the directory containing file zFilename.
3436** If successful, *pFd is set to the opened file descriptor and
3437** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3438** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3439** value.
3440**
drh90315a22011-08-10 01:52:12 +00003441** The directory file descriptor is used for only one thing - to
3442** fsync() a directory to make sure file creation and deletion events
3443** are flushed to disk. Such fsyncs are not needed on newer
3444** journaling filesystems, but are required on older filesystems.
3445**
3446** This routine can be overridden using the xSetSysCall interface.
3447** The ability to override this routine was added in support of the
3448** chromium sandbox. Opening a directory is a security risk (we are
3449** told) so making it overrideable allows the chromium sandbox to
3450** replace this routine with a harmless no-op. To make this routine
3451** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3452** *pFd set to a negative number.
3453**
drh0059eae2011-08-08 23:48:40 +00003454** If SQLITE_OK is returned, the caller is responsible for closing
3455** the file descriptor *pFd using close().
3456*/
3457static int openDirectory(const char *zFilename, int *pFd){
3458 int ii;
3459 int fd = -1;
3460 char zDirname[MAX_PATHNAME+1];
3461
3462 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3463 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3464 if( ii>0 ){
3465 zDirname[ii] = '\0';
3466 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3467 if( fd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003468 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3469 }
3470 }
3471 *pFd = fd;
drhacb6b282015-11-26 10:37:05 +00003472 if( fd>=0 ) return SQLITE_OK;
3473 return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
drh0059eae2011-08-08 23:48:40 +00003474}
3475
3476/*
drh734c9862008-11-28 15:37:20 +00003477** Make sure all writes to a particular file are committed to disk.
3478**
3479** If dataOnly==0 then both the file itself and its metadata (file
3480** size, access time, etc) are synced. If dataOnly!=0 then only the
3481** file data is synced.
3482**
3483** Under Unix, also make sure that the directory entry for the file
3484** has been created by fsync-ing the directory that contains the file.
3485** If we do not do this and we encounter a power failure, the directory
3486** entry for the journal might not exist after we reboot. The next
3487** SQLite to access the file will not know that the journal exists (because
3488** the directory entry for the journal was never created) and the transaction
3489** will not roll back - possibly leading to database corruption.
3490*/
3491static int unixSync(sqlite3_file *id, int flags){
3492 int rc;
3493 unixFile *pFile = (unixFile*)id;
3494
3495 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3496 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3497
3498 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3499 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3500 || (flags&0x0F)==SQLITE_SYNC_FULL
3501 );
3502
3503 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3504 ** line is to test that doing so does not cause any problems.
3505 */
3506 SimulateDiskfullError( return SQLITE_FULL );
3507
3508 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003509 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003510 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3511 SimulateIOError( rc=1 );
3512 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003513 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003514 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003515 }
drh0059eae2011-08-08 23:48:40 +00003516
3517 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003518 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003519 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003520 */
3521 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3522 int dirfd;
3523 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003524 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003525 rc = osOpenDirectory(pFile->zPath, &dirfd);
drhacb6b282015-11-26 10:37:05 +00003526 if( rc==SQLITE_OK ){
drh0059eae2011-08-08 23:48:40 +00003527 full_fsync(dirfd, 0, 0);
3528 robust_close(pFile, dirfd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00003529 }else{
3530 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00003531 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003532 }
drh0059eae2011-08-08 23:48:40 +00003533 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003534 }
3535 return rc;
3536}
3537
3538/*
3539** Truncate an open file to a specified size
3540*/
3541static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003542 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003543 int rc;
dan6e09d692010-07-27 18:34:15 +00003544 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003545 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003546
3547 /* If the user has configured a chunk-size for this file, truncate the
3548 ** file so that it consists of an integer number of chunks (i.e. the
3549 ** actual file size after the operation may be larger than the requested
3550 ** size).
3551 */
drhb8af4b72012-04-05 20:04:39 +00003552 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003553 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3554 }
3555
dan2ee53412014-09-06 16:49:40 +00003556 rc = robust_ftruncate(pFile->h, nByte);
drh734c9862008-11-28 15:37:20 +00003557 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003558 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003559 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003560 }else{
drhd3d8c042012-05-29 17:02:40 +00003561#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003562 /* If we are doing a normal write to a database file (as opposed to
3563 ** doing a hot-journal rollback or a write to some file other than a
3564 ** normal database file) and we truncate the file to zero length,
3565 ** that effectively updates the change counter. This might happen
3566 ** when restoring a database using the backup API from a zero-length
3567 ** source.
3568 */
dan6e09d692010-07-27 18:34:15 +00003569 if( pFile->inNormalWrite && nByte==0 ){
3570 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003571 }
danf23da962013-03-23 21:00:41 +00003572#endif
danc0003312013-03-22 17:46:11 +00003573
mistachkine98844f2013-08-24 00:59:24 +00003574#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003575 /* If the file was just truncated to a size smaller than the currently
3576 ** mapped region, reduce the effective mapping size as well. SQLite will
3577 ** use read() and write() to access data beyond this point from now on.
3578 */
3579 if( nByte<pFile->mmapSize ){
3580 pFile->mmapSize = nByte;
3581 }
mistachkine98844f2013-08-24 00:59:24 +00003582#endif
drh3313b142009-11-06 04:13:18 +00003583
drh734c9862008-11-28 15:37:20 +00003584 return SQLITE_OK;
3585 }
3586}
3587
3588/*
3589** Determine the current size of a file in bytes
3590*/
3591static int unixFileSize(sqlite3_file *id, i64 *pSize){
3592 int rc;
3593 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003594 assert( id );
3595 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003596 SimulateIOError( rc=1 );
3597 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00003598 storeLastErrno((unixFile*)id, errno);
drh734c9862008-11-28 15:37:20 +00003599 return SQLITE_IOERR_FSTAT;
3600 }
3601 *pSize = buf.st_size;
3602
drh8af6c222010-05-14 12:43:01 +00003603 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003604 ** writes a single byte into that file in order to work around a bug
3605 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3606 ** layers, we need to report this file size as zero even though it is
3607 ** really 1. Ticket #3260.
3608 */
3609 if( *pSize==1 ) *pSize = 0;
3610
3611
3612 return SQLITE_OK;
3613}
3614
drhd2cb50b2009-01-09 21:41:17 +00003615#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003616/*
3617** Handler for proxy-locking file-control verbs. Defined below in the
3618** proxying locking division.
3619*/
3620static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003621#endif
drh715ff302008-12-03 22:32:44 +00003622
dan502019c2010-07-28 14:26:17 +00003623/*
3624** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003625** file-control operation. Enlarge the database to nBytes in size
3626** (rounded up to the next chunk-size). If the database is already
3627** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003628*/
3629static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003630 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003631 i64 nSize; /* Required file size */
3632 struct stat buf; /* Used to hold return values of fstat() */
3633
drh4bf66fd2015-02-19 02:43:02 +00003634 if( osFstat(pFile->h, &buf) ){
3635 return SQLITE_IOERR_FSTAT;
3636 }
dan502019c2010-07-28 14:26:17 +00003637
3638 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3639 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003640
dan502019c2010-07-28 14:26:17 +00003641#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003642 /* The code below is handling the return value of osFallocate()
3643 ** correctly. posix_fallocate() is defined to "returns zero on success,
3644 ** or an error number on failure". See the manpage for details. */
3645 int err;
drhff812312011-02-23 13:33:46 +00003646 do{
dan661d71a2011-03-30 19:08:03 +00003647 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3648 }while( err==EINTR );
3649 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003650#else
dan592bf7f2014-12-30 19:58:31 +00003651 /* If the OS does not have posix_fallocate(), fake it. Write a
3652 ** single byte to the last byte in each block that falls entirely
3653 ** within the extended region. Then, if required, a single byte
3654 ** at offset (nSize-1), to set the size of the file correctly.
3655 ** This is a similar technique to that used by glibc on systems
3656 ** that do not have a real fallocate() call.
dan502019c2010-07-28 14:26:17 +00003657 */
3658 int nBlk = buf.st_blksize; /* File-system block size */
danef3d66c2015-01-06 21:31:47 +00003659 int nWrite = 0; /* Number of bytes written by seekAndWrite */
dan502019c2010-07-28 14:26:17 +00003660 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003661
drh053378d2015-12-01 22:09:42 +00003662 iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
dan592bf7f2014-12-30 19:58:31 +00003663 assert( iWrite>=buf.st_size );
dan592bf7f2014-12-30 19:58:31 +00003664 assert( ((iWrite+1)%nBlk)==0 );
drh053378d2015-12-01 22:09:42 +00003665 for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
3666 if( iWrite>=nSize ) iWrite = nSize - 1;
danef3d66c2015-01-06 21:31:47 +00003667 nWrite = seekAndWrite(pFile, iWrite, "", 1);
dandc5df0f2011-04-06 19:15:45 +00003668 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dandc5df0f2011-04-06 19:15:45 +00003669 }
dan502019c2010-07-28 14:26:17 +00003670#endif
3671 }
3672 }
3673
mistachkine98844f2013-08-24 00:59:24 +00003674#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003675 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003676 int rc;
3677 if( pFile->szChunk<=0 ){
3678 if( robust_ftruncate(pFile->h, nByte) ){
drh4bf66fd2015-02-19 02:43:02 +00003679 storeLastErrno(pFile, errno);
danf23da962013-03-23 21:00:41 +00003680 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3681 }
3682 }
3683
3684 rc = unixMapfile(pFile, nByte);
3685 return rc;
3686 }
mistachkine98844f2013-08-24 00:59:24 +00003687#endif
danf23da962013-03-23 21:00:41 +00003688
dan502019c2010-07-28 14:26:17 +00003689 return SQLITE_OK;
3690}
danielk1977ad94b582007-08-20 06:44:22 +00003691
danielk1977e3026632004-06-22 11:29:02 +00003692/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003693** If *pArg is initially negative then this is a query. Set *pArg to
drhf12b3f62011-12-21 14:42:29 +00003694** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3695**
3696** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3697*/
3698static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3699 if( *pArg<0 ){
3700 *pArg = (pFile->ctrlFlags & mask)!=0;
3701 }else if( (*pArg)==0 ){
3702 pFile->ctrlFlags &= ~mask;
3703 }else{
3704 pFile->ctrlFlags |= mask;
3705 }
3706}
3707
drh696b33e2012-12-06 19:01:42 +00003708/* Forward declaration */
3709static int unixGetTempname(int nBuf, char *zBuf);
3710
drhf12b3f62011-12-21 14:42:29 +00003711/*
drh9e33c2c2007-08-31 18:34:59 +00003712** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003713*/
drhcc6bb3e2007-08-31 16:11:35 +00003714static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003715 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003716 switch( op ){
3717 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003718 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003719 return SQLITE_OK;
3720 }
drh4bf66fd2015-02-19 02:43:02 +00003721 case SQLITE_FCNTL_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003722 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003723 return SQLITE_OK;
3724 }
dan6e09d692010-07-27 18:34:15 +00003725 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003726 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003727 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003728 }
drh9ff27ec2010-05-19 19:26:05 +00003729 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003730 int rc;
3731 SimulateIOErrorBenign(1);
3732 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3733 SimulateIOErrorBenign(0);
3734 return rc;
drhf0b190d2011-07-26 16:03:07 +00003735 }
3736 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003737 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3738 return SQLITE_OK;
3739 }
drhcb15f352011-12-23 01:04:17 +00003740 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3741 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003742 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003743 }
drhde60fc22011-12-14 17:53:36 +00003744 case SQLITE_FCNTL_VFSNAME: {
3745 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3746 return SQLITE_OK;
3747 }
drh696b33e2012-12-06 19:01:42 +00003748 case SQLITE_FCNTL_TEMPFILENAME: {
drhf3cdcdc2015-04-29 16:50:28 +00003749 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
drh696b33e2012-12-06 19:01:42 +00003750 if( zTFile ){
3751 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3752 *(char**)pArg = zTFile;
3753 }
3754 return SQLITE_OK;
3755 }
drhb959a012013-12-07 12:29:22 +00003756 case SQLITE_FCNTL_HAS_MOVED: {
3757 *(int*)pArg = fileHasMoved(pFile);
3758 return SQLITE_OK;
3759 }
mistachkine98844f2013-08-24 00:59:24 +00003760#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003761 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003762 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003763 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003764 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3765 newLimit = sqlite3GlobalConfig.mxMmap;
3766 }
3767 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003768 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003769 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003770 if( pFile->mmapSize>0 ){
3771 unixUnmapfile(pFile);
3772 rc = unixMapfile(pFile, -1);
3773 }
danbcb8a862013-04-08 15:30:41 +00003774 }
drh34e258c2013-05-23 01:40:53 +00003775 return rc;
danb2d3de32013-03-14 18:34:37 +00003776 }
mistachkine98844f2013-08-24 00:59:24 +00003777#endif
drhd3d8c042012-05-29 17:02:40 +00003778#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003779 /* The pager calls this method to signal that it has done
3780 ** a rollback and that the database is therefore unchanged and
3781 ** it hence it is OK for the transaction change counter to be
3782 ** unchanged.
3783 */
3784 case SQLITE_FCNTL_DB_UNCHANGED: {
3785 ((unixFile*)id)->dbUpdate = 0;
3786 return SQLITE_OK;
3787 }
3788#endif
drhd2cb50b2009-01-09 21:41:17 +00003789#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh4bf66fd2015-02-19 02:43:02 +00003790 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
3791 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003792 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003793 }
drhd2cb50b2009-01-09 21:41:17 +00003794#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003795 }
drh0b52b7d2011-01-26 19:46:22 +00003796 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003797}
3798
3799/*
danielk1977a3d4c882007-03-23 10:08:38 +00003800** Return the sector size in bytes of the underlying block device for
3801** the specified file. This is almost always 512 bytes, but may be
3802** larger for some devices.
3803**
3804** SQLite code assumes this function cannot fail. It also assumes that
3805** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003806** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003807** same for both.
3808*/
drh537dddf2012-10-26 13:46:24 +00003809#ifndef __QNXNTO__
3810static int unixSectorSize(sqlite3_file *NotUsed){
3811 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003812 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003813}
drh537dddf2012-10-26 13:46:24 +00003814#endif
3815
3816/*
3817** The following version of unixSectorSize() is optimized for QNX.
3818*/
3819#ifdef __QNXNTO__
3820#include <sys/dcmd_blk.h>
3821#include <sys/statvfs.h>
3822static int unixSectorSize(sqlite3_file *id){
3823 unixFile *pFile = (unixFile*)id;
3824 if( pFile->sectorSize == 0 ){
3825 struct statvfs fsInfo;
3826
3827 /* Set defaults for non-supported filesystems */
3828 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3829 pFile->deviceCharacteristics = 0;
3830 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3831 return pFile->sectorSize;
3832 }
3833
3834 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3835 pFile->sectorSize = fsInfo.f_bsize;
3836 pFile->deviceCharacteristics =
3837 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3838 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3839 ** the write succeeds */
3840 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3841 ** so it is ordered */
3842 0;
3843 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3844 pFile->sectorSize = fsInfo.f_bsize;
3845 pFile->deviceCharacteristics =
3846 /* etfs cluster size writes are atomic */
3847 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3848 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3849 ** the write succeeds */
3850 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3851 ** so it is ordered */
3852 0;
3853 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3854 pFile->sectorSize = fsInfo.f_bsize;
3855 pFile->deviceCharacteristics =
3856 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3857 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3858 ** the write succeeds */
3859 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3860 ** so it is ordered */
3861 0;
3862 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3863 pFile->sectorSize = fsInfo.f_bsize;
3864 pFile->deviceCharacteristics =
3865 /* full bitset of atomics from max sector size and smaller */
3866 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3867 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3868 ** so it is ordered */
3869 0;
3870 }else if( strstr(fsInfo.f_basetype, "dos") ){
3871 pFile->sectorSize = fsInfo.f_bsize;
3872 pFile->deviceCharacteristics =
3873 /* full bitset of atomics from max sector size and smaller */
3874 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3875 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3876 ** so it is ordered */
3877 0;
3878 }else{
3879 pFile->deviceCharacteristics =
3880 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3881 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3882 ** the write succeeds */
3883 0;
3884 }
3885 }
3886 /* Last chance verification. If the sector size isn't a multiple of 512
3887 ** then it isn't valid.*/
3888 if( pFile->sectorSize % 512 != 0 ){
3889 pFile->deviceCharacteristics = 0;
3890 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3891 }
3892 return pFile->sectorSize;
3893}
3894#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003895
danielk197790949c22007-08-17 16:50:38 +00003896/*
drhf12b3f62011-12-21 14:42:29 +00003897** Return the device characteristics for the file.
3898**
drhcb15f352011-12-23 01:04:17 +00003899** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
peter.d.reid60ec9142014-09-06 16:39:46 +00003900** However, that choice is controversial since technically the underlying
drhcb15f352011-12-23 01:04:17 +00003901** file system does not always provide powersafe overwrites. (In other
3902** words, after a power-loss event, parts of the file that were never
3903** written might end up being altered.) However, non-PSOW behavior is very,
3904** very rare. And asserting PSOW makes a large reduction in the amount
3905** of required I/O for journaling, since a lot of padding is eliminated.
3906** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3907** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003908*/
drhf12b3f62011-12-21 14:42:29 +00003909static int unixDeviceCharacteristics(sqlite3_file *id){
3910 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003911 int rc = 0;
3912#ifdef __QNXNTO__
3913 if( p->sectorSize==0 ) unixSectorSize(id);
3914 rc = p->deviceCharacteristics;
3915#endif
drhcb15f352011-12-23 01:04:17 +00003916 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003917 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003918 }
drh537dddf2012-10-26 13:46:24 +00003919 return rc;
danielk197762079062007-08-15 17:08:46 +00003920}
3921
dan702eec12014-06-23 10:04:58 +00003922#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00003923
dan702eec12014-06-23 10:04:58 +00003924/*
3925** Return the system page size.
3926**
3927** This function should not be called directly by other code in this file.
3928** Instead, it should be called via macro osGetpagesize().
3929*/
3930static int unixGetpagesize(void){
drh8cd5b252015-03-02 22:06:43 +00003931#if OS_VXWORKS
3932 return 1024;
3933#elif defined(_BSD_SOURCE)
dan702eec12014-06-23 10:04:58 +00003934 return getpagesize();
3935#else
3936 return (int)sysconf(_SC_PAGESIZE);
3937#endif
3938}
3939
3940#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
3941
3942#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00003943
3944/*
drhd91c68f2010-05-14 14:52:25 +00003945** Object used to represent an shared memory buffer.
3946**
3947** When multiple threads all reference the same wal-index, each thread
3948** has its own unixShm object, but they all point to a single instance
3949** of this unixShmNode object. In other words, each wal-index is opened
3950** only once per process.
3951**
3952** Each unixShmNode object is connected to a single unixInodeInfo object.
3953** We could coalesce this object into unixInodeInfo, but that would mean
3954** every open file that does not use shared memory (in other words, most
3955** open files) would have to carry around this extra information. So
3956** the unixInodeInfo object contains a pointer to this unixShmNode object
3957** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003958**
3959** unixMutexHeld() must be true when creating or destroying
3960** this object or while reading or writing the following fields:
3961**
3962** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003963**
3964** The following fields are read-only after the object is created:
3965**
3966** fid
3967** zFilename
3968**
drhd91c68f2010-05-14 14:52:25 +00003969** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003970** unixMutexHeld() is true when reading or writing any other field
3971** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003972*/
drhd91c68f2010-05-14 14:52:25 +00003973struct unixShmNode {
3974 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003975 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003976 char *zFilename; /* Name of the mmapped file */
3977 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003978 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003979 u16 nRegion; /* Size of array apRegion */
3980 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003981 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003982 int nRef; /* Number of unixShm objects pointing to this */
3983 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003984#ifdef SQLITE_DEBUG
3985 u8 exclMask; /* Mask of exclusive locks held */
3986 u8 sharedMask; /* Mask of shared locks held */
3987 u8 nextShmId; /* Next available unixShm.id value */
3988#endif
3989};
3990
3991/*
drhd9e5c4f2010-05-12 18:01:39 +00003992** Structure used internally by this VFS to record the state of an
3993** open shared memory connection.
3994**
drhd91c68f2010-05-14 14:52:25 +00003995** The following fields are initialized when this object is created and
3996** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003997**
drhd91c68f2010-05-14 14:52:25 +00003998** unixShm.pFile
3999** unixShm.id
4000**
4001** All other fields are read/write. The unixShm.pFile->mutex must be held
4002** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004003*/
4004struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004005 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4006 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004007 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004008 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004009 u16 sharedMask; /* Mask of shared locks held */
4010 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004011};
4012
4013/*
drhd9e5c4f2010-05-12 18:01:39 +00004014** Constants used for locking
4015*/
drhbd9676c2010-06-23 17:58:38 +00004016#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004017#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004018
drhd9e5c4f2010-05-12 18:01:39 +00004019/*
drh73b64e42010-05-30 19:55:15 +00004020** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004021**
4022** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4023** otherwise.
4024*/
4025static int unixShmSystemLock(
drhbbf76ee2015-03-10 20:22:35 +00004026 unixFile *pFile, /* Open connection to the WAL file */
drhd91c68f2010-05-14 14:52:25 +00004027 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004028 int ofst, /* First byte of the locking range */
4029 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004030){
drhbbf76ee2015-03-10 20:22:35 +00004031 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4032 struct flock f; /* The posix advisory locking structure */
4033 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004034
drhd91c68f2010-05-14 14:52:25 +00004035 /* Access to the unixShmNode object is serialized by the caller */
drhbbf76ee2015-03-10 20:22:35 +00004036 pShmNode = pFile->pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004037 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004038
drh73b64e42010-05-30 19:55:15 +00004039 /* Shared locks never span more than one byte */
4040 assert( n==1 || lockType!=F_RDLCK );
4041
4042 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00004043 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004044
drh3cb93392011-03-12 18:10:44 +00004045 if( pShmNode->h>=0 ){
4046 /* Initialize the locking parameters */
4047 memset(&f, 0, sizeof(f));
4048 f.l_type = lockType;
4049 f.l_whence = SEEK_SET;
4050 f.l_start = ofst;
4051 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004052
drhdcfb9652015-12-02 00:05:26 +00004053 rc = osFcntl(pShmNode->h, F_SETLK, &f);
drh3cb93392011-03-12 18:10:44 +00004054 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4055 }
drhd9e5c4f2010-05-12 18:01:39 +00004056
4057 /* Update the global lock state and do debug tracing */
4058#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004059 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004060 OSTRACE(("SHM-LOCK "));
drh693e6712014-01-24 22:58:00 +00004061 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004062 if( rc==SQLITE_OK ){
4063 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004064 OSTRACE(("unlock %d ok", ofst));
4065 pShmNode->exclMask &= ~mask;
4066 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004067 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004068 OSTRACE(("read-lock %d ok", ofst));
4069 pShmNode->exclMask &= ~mask;
4070 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004071 }else{
4072 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004073 OSTRACE(("write-lock %d ok", ofst));
4074 pShmNode->exclMask |= mask;
4075 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004076 }
4077 }else{
4078 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004079 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004080 }else if( lockType==F_RDLCK ){
4081 OSTRACE(("read-lock failed"));
4082 }else{
4083 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004084 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004085 }
4086 }
drh20e1f082010-05-31 16:10:12 +00004087 OSTRACE((" - afterwards %03x,%03x\n",
4088 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004089 }
drhd9e5c4f2010-05-12 18:01:39 +00004090#endif
4091
4092 return rc;
4093}
4094
dan781e34c2014-03-20 08:59:47 +00004095/*
dan781e34c2014-03-20 08:59:47 +00004096** Return the minimum number of 32KB shm regions that should be mapped at
4097** a time, assuming that each mapping must be an integer multiple of the
4098** current system page-size.
4099**
4100** Usually, this is 1. The exception seems to be systems that are configured
4101** to use 64KB pages - in this case each mapping must cover at least two
4102** shm regions.
4103*/
4104static int unixShmRegionPerMap(void){
4105 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004106 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004107 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4108 if( pgsz<shmsz ) return 1;
4109 return pgsz/shmsz;
4110}
drhd9e5c4f2010-05-12 18:01:39 +00004111
4112/*
drhd91c68f2010-05-14 14:52:25 +00004113** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004114**
4115** This is not a VFS shared-memory method; it is a utility function called
4116** by VFS shared-memory methods.
4117*/
drhd91c68f2010-05-14 14:52:25 +00004118static void unixShmPurge(unixFile *pFd){
4119 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004120 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00004121 if( p && p->nRef==0 ){
dan781e34c2014-03-20 08:59:47 +00004122 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004123 int i;
drhd91c68f2010-05-14 14:52:25 +00004124 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004125 sqlite3_mutex_free(p->mutex);
dan781e34c2014-03-20 08:59:47 +00004126 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh3cb93392011-03-12 18:10:44 +00004127 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004128 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004129 }else{
4130 sqlite3_free(p->apRegion[i]);
4131 }
dan13a3cb82010-06-11 19:04:21 +00004132 }
dan18801912010-06-14 14:07:50 +00004133 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004134 if( p->h>=0 ){
4135 robust_close(pFd, p->h, __LINE__);
4136 p->h = -1;
4137 }
drhd91c68f2010-05-14 14:52:25 +00004138 p->pInode->pShmNode = 0;
4139 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004140 }
4141}
4142
4143/*
danda9fe0c2010-07-13 18:44:03 +00004144** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004145** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004146**
drh7234c6d2010-06-19 15:10:09 +00004147** The file used to implement shared-memory is in the same directory
4148** as the open database file and has the same name as the open database
4149** file with the "-shm" suffix added. For example, if the database file
4150** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004151** for shared memory will be called "/home/user1/config.db-shm".
4152**
4153** Another approach to is to use files in /dev/shm or /dev/tmp or an
4154** some other tmpfs mount. But if a file in a different directory
4155** from the database file is used, then differing access permissions
4156** or a chroot() might cause two different processes on the same
4157** database to end up using different files for shared memory -
4158** meaning that their memory would not really be shared - resulting
4159** in database corruption. Nevertheless, this tmpfs file usage
4160** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4161** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4162** option results in an incompatible build of SQLite; builds of SQLite
4163** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4164** same database file at the same time, database corruption will likely
4165** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4166** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004167**
4168** When opening a new shared-memory file, if no other instances of that
4169** file are currently open, in this process or in other processes, then
4170** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004171**
4172** If the original database file (pDbFd) is using the "unix-excl" VFS
4173** that means that an exclusive lock is held on the database file and
4174** that no other processes are able to read or write the database. In
4175** that case, we do not really need shared memory. No shared memory
4176** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004177*/
danda9fe0c2010-07-13 18:44:03 +00004178static int unixOpenSharedMemory(unixFile *pDbFd){
4179 struct unixShm *p = 0; /* The connection to be opened */
4180 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4181 int rc; /* Result code */
4182 unixInodeInfo *pInode; /* The inode of fd */
4183 char *zShmFilename; /* Name of the file used for SHM */
4184 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004185
danda9fe0c2010-07-13 18:44:03 +00004186 /* Allocate space for the new unixShm object. */
drhf3cdcdc2015-04-29 16:50:28 +00004187 p = sqlite3_malloc64( sizeof(*p) );
drhd9e5c4f2010-05-12 18:01:39 +00004188 if( p==0 ) return SQLITE_NOMEM;
4189 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004190 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004191
danda9fe0c2010-07-13 18:44:03 +00004192 /* Check to see if a unixShmNode object already exists. Reuse an existing
4193 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004194 */
4195 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004196 pInode = pDbFd->pInode;
4197 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004198 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004199 struct stat sStat; /* fstat() info for database file */
drh4bf66fd2015-02-19 02:43:02 +00004200#ifndef SQLITE_SHM_DIRECTORY
4201 const char *zBasePath = pDbFd->zPath;
4202#endif
danddb0ac42010-07-14 14:48:58 +00004203
4204 /* Call fstat() to figure out the permissions on the database file. If
4205 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004206 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004207 */
drh3cb93392011-03-12 18:10:44 +00004208 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00004209 rc = SQLITE_IOERR_FSTAT;
4210 goto shm_open_err;
4211 }
4212
drha4ced192010-07-15 18:32:40 +00004213#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004214 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004215#else
drh4bf66fd2015-02-19 02:43:02 +00004216 nShmFilename = 6 + (int)strlen(zBasePath);
drha4ced192010-07-15 18:32:40 +00004217#endif
drhf3cdcdc2015-04-29 16:50:28 +00004218 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004219 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004220 rc = SQLITE_NOMEM;
4221 goto shm_open_err;
4222 }
drh9cb5a0d2012-01-05 21:19:54 +00004223 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004224 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004225#ifdef SQLITE_SHM_DIRECTORY
4226 sqlite3_snprintf(nShmFilename, zShmFilename,
4227 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4228 (u32)sStat.st_ino, (u32)sStat.st_dev);
4229#else
drh4bf66fd2015-02-19 02:43:02 +00004230 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
drh81cc5162011-05-17 20:36:21 +00004231 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004232#endif
drhd91c68f2010-05-14 14:52:25 +00004233 pShmNode->h = -1;
4234 pDbFd->pInode->pShmNode = pShmNode;
4235 pShmNode->pInode = pDbFd->pInode;
4236 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4237 if( pShmNode->mutex==0 ){
4238 rc = SQLITE_NOMEM;
4239 goto shm_open_err;
4240 }
drhd9e5c4f2010-05-12 18:01:39 +00004241
drh3cb93392011-03-12 18:10:44 +00004242 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004243 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004244 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004245 openFlags = O_RDONLY;
4246 pShmNode->isReadonly = 1;
4247 }
4248 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004249 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004250 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4251 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004252 }
drhac7c3ac2012-02-11 19:23:48 +00004253
4254 /* If this process is running as root, make sure that the SHM file
4255 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004256 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004257 */
drh6226ca22015-11-24 15:06:28 +00004258 robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004259
4260 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004261 ** If not, truncate the file to zero length.
4262 */
4263 rc = SQLITE_OK;
drhbbf76ee2015-03-10 20:22:35 +00004264 if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
drh66dfec8b2011-06-01 20:01:49 +00004265 if( robust_ftruncate(pShmNode->h, 0) ){
4266 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004267 }
4268 }
drh66dfec8b2011-06-01 20:01:49 +00004269 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004270 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
drh66dfec8b2011-06-01 20:01:49 +00004271 }
4272 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004273 }
drhd9e5c4f2010-05-12 18:01:39 +00004274 }
4275
drhd91c68f2010-05-14 14:52:25 +00004276 /* Make the new connection a child of the unixShmNode */
4277 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004278#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004279 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004280#endif
drhd91c68f2010-05-14 14:52:25 +00004281 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004282 pDbFd->pShm = p;
4283 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004284
4285 /* The reference count on pShmNode has already been incremented under
4286 ** the cover of the unixEnterMutex() mutex and the pointer from the
4287 ** new (struct unixShm) object to the pShmNode has been set. All that is
4288 ** left to do is to link the new object into the linked list starting
4289 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4290 ** mutex.
4291 */
4292 sqlite3_mutex_enter(pShmNode->mutex);
4293 p->pNext = pShmNode->pFirst;
4294 pShmNode->pFirst = p;
4295 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004296 return SQLITE_OK;
4297
4298 /* Jump here on any error */
4299shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004300 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004301 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004302 unixLeaveMutex();
4303 return rc;
4304}
4305
4306/*
danda9fe0c2010-07-13 18:44:03 +00004307** This function is called to obtain a pointer to region iRegion of the
4308** shared-memory associated with the database file fd. Shared-memory regions
4309** are numbered starting from zero. Each shared-memory region is szRegion
4310** bytes in size.
4311**
4312** If an error occurs, an error code is returned and *pp is set to NULL.
4313**
4314** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4315** region has not been allocated (by any client, including one running in a
4316** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4317** bExtend is non-zero and the requested shared-memory region has not yet
4318** been allocated, it is allocated by this function.
4319**
4320** If the shared-memory region has already been allocated or is allocated by
4321** this call as described above, then it is mapped into this processes
4322** address space (if it is not already), *pp is set to point to the mapped
4323** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004324*/
danda9fe0c2010-07-13 18:44:03 +00004325static int unixShmMap(
4326 sqlite3_file *fd, /* Handle open on database file */
4327 int iRegion, /* Region to retrieve */
4328 int szRegion, /* Size of regions */
4329 int bExtend, /* True to extend file if necessary */
4330 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004331){
danda9fe0c2010-07-13 18:44:03 +00004332 unixFile *pDbFd = (unixFile*)fd;
4333 unixShm *p;
4334 unixShmNode *pShmNode;
4335 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004336 int nShmPerMap = unixShmRegionPerMap();
4337 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004338
danda9fe0c2010-07-13 18:44:03 +00004339 /* If the shared-memory file has not yet been opened, open it now. */
4340 if( pDbFd->pShm==0 ){
4341 rc = unixOpenSharedMemory(pDbFd);
4342 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004343 }
drhd9e5c4f2010-05-12 18:01:39 +00004344
danda9fe0c2010-07-13 18:44:03 +00004345 p = pDbFd->pShm;
4346 pShmNode = p->pShmNode;
4347 sqlite3_mutex_enter(pShmNode->mutex);
4348 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004349 assert( pShmNode->pInode==pDbFd->pInode );
4350 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4351 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004352
dan781e34c2014-03-20 08:59:47 +00004353 /* Minimum number of regions required to be mapped. */
4354 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4355
4356 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004357 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004358 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004359 struct stat sStat; /* Used by fstat() */
4360
4361 pShmNode->szRegion = szRegion;
4362
drh3cb93392011-03-12 18:10:44 +00004363 if( pShmNode->h>=0 ){
4364 /* The requested region is not mapped into this processes address space.
4365 ** Check to see if it has been allocated (i.e. if the wal-index file is
4366 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004367 */
drh3cb93392011-03-12 18:10:44 +00004368 if( osFstat(pShmNode->h, &sStat) ){
4369 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004370 goto shmpage_out;
4371 }
drh3cb93392011-03-12 18:10:44 +00004372
4373 if( sStat.st_size<nByte ){
4374 /* The requested memory region does not exist. If bExtend is set to
4375 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004376 */
dan47a2b4a2013-04-26 16:09:29 +00004377 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004378 goto shmpage_out;
4379 }
dan47a2b4a2013-04-26 16:09:29 +00004380
4381 /* Alternatively, if bExtend is true, extend the file. Do this by
4382 ** writing a single byte to the end of each (OS) page being
4383 ** allocated or extended. Technically, we need only write to the
4384 ** last page in order to extend the file. But writing to all new
4385 ** pages forces the OS to allocate them immediately, which reduces
4386 ** the chances of SIGBUS while accessing the mapped region later on.
4387 */
4388 else{
4389 static const int pgsz = 4096;
4390 int iPg;
4391
4392 /* Write to the last byte of each newly allocated or extended page */
4393 assert( (nByte % pgsz)==0 );
4394 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
drhe1818ec2015-12-01 16:21:35 +00004395 int x = 0;
4396 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
dan47a2b4a2013-04-26 16:09:29 +00004397 const char *zFile = pShmNode->zFilename;
4398 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4399 goto shmpage_out;
4400 }
4401 }
drh3cb93392011-03-12 18:10:44 +00004402 }
4403 }
danda9fe0c2010-07-13 18:44:03 +00004404 }
4405
4406 /* Map the requested memory region into this processes address space. */
4407 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004408 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004409 );
4410 if( !apNew ){
4411 rc = SQLITE_IOERR_NOMEM;
4412 goto shmpage_out;
4413 }
4414 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004415 while( pShmNode->nRegion<nReqRegion ){
4416 int nMap = szRegion*nShmPerMap;
4417 int i;
drh3cb93392011-03-12 18:10:44 +00004418 void *pMem;
4419 if( pShmNode->h>=0 ){
dan781e34c2014-03-20 08:59:47 +00004420 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004421 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004422 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004423 );
4424 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004425 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004426 goto shmpage_out;
4427 }
4428 }else{
drhf3cdcdc2015-04-29 16:50:28 +00004429 pMem = sqlite3_malloc64(szRegion);
drh3cb93392011-03-12 18:10:44 +00004430 if( pMem==0 ){
4431 rc = SQLITE_NOMEM;
4432 goto shmpage_out;
4433 }
4434 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004435 }
dan781e34c2014-03-20 08:59:47 +00004436
4437 for(i=0; i<nShmPerMap; i++){
4438 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4439 }
4440 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004441 }
4442 }
4443
4444shmpage_out:
4445 if( pShmNode->nRegion>iRegion ){
4446 *pp = pShmNode->apRegion[iRegion];
4447 }else{
4448 *pp = 0;
4449 }
drh66dfec8b2011-06-01 20:01:49 +00004450 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004451 sqlite3_mutex_leave(pShmNode->mutex);
4452 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004453}
4454
4455/*
drhd9e5c4f2010-05-12 18:01:39 +00004456** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004457**
4458** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4459** different here than in posix. In xShmLock(), one can go from unlocked
4460** to shared and back or from unlocked to exclusive and back. But one may
4461** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004462*/
4463static int unixShmLock(
4464 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004465 int ofst, /* First lock to acquire or release */
4466 int n, /* Number of locks to acquire or release */
4467 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004468){
drh73b64e42010-05-30 19:55:15 +00004469 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4470 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4471 unixShm *pX; /* For looping over all siblings */
4472 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4473 int rc = SQLITE_OK; /* Result code */
4474 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004475
drhd91c68f2010-05-14 14:52:25 +00004476 assert( pShmNode==pDbFd->pInode->pShmNode );
4477 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004478 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004479 assert( n>=1 );
4480 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4481 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4482 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4483 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4484 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004485 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4486 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004487
drhc99597c2010-05-31 01:41:15 +00004488 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004489 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004490 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004491 if( flags & SQLITE_SHM_UNLOCK ){
4492 u16 allMask = 0; /* Mask of locks held by siblings */
4493
4494 /* See if any siblings hold this same lock */
4495 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4496 if( pX==p ) continue;
4497 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4498 allMask |= pX->sharedMask;
4499 }
4500
4501 /* Unlock the system-level locks */
4502 if( (mask & allMask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004503 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004504 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004505 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004506 }
drh73b64e42010-05-30 19:55:15 +00004507
4508 /* Undo the local locks */
4509 if( rc==SQLITE_OK ){
4510 p->exclMask &= ~mask;
4511 p->sharedMask &= ~mask;
4512 }
4513 }else if( flags & SQLITE_SHM_SHARED ){
4514 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4515
4516 /* Find out which shared locks are already held by sibling connections.
4517 ** If any sibling already holds an exclusive lock, go ahead and return
4518 ** SQLITE_BUSY.
4519 */
4520 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004521 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004522 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004523 break;
4524 }
4525 allShared |= pX->sharedMask;
4526 }
4527
4528 /* Get shared locks at the system level, if necessary */
4529 if( rc==SQLITE_OK ){
4530 if( (allShared & mask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004531 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004532 }else{
drh73b64e42010-05-30 19:55:15 +00004533 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004534 }
drhd9e5c4f2010-05-12 18:01:39 +00004535 }
drh73b64e42010-05-30 19:55:15 +00004536
4537 /* Get the local shared locks */
4538 if( rc==SQLITE_OK ){
4539 p->sharedMask |= mask;
4540 }
4541 }else{
4542 /* Make sure no sibling connections hold locks that will block this
4543 ** lock. If any do, return SQLITE_BUSY right away.
4544 */
4545 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004546 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4547 rc = SQLITE_BUSY;
4548 break;
4549 }
4550 }
4551
4552 /* Get the exclusive locks at the system level. Then if successful
4553 ** also mark the local connection as being locked.
4554 */
4555 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004556 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004557 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004558 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004559 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004560 }
drhd9e5c4f2010-05-12 18:01:39 +00004561 }
4562 }
drhd91c68f2010-05-14 14:52:25 +00004563 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004564 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
drh5ac93652015-03-21 20:59:43 +00004565 p->id, osGetpid(0), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004566 return rc;
4567}
4568
drh286a2882010-05-20 23:51:06 +00004569/*
4570** Implement a memory barrier or memory fence on shared memory.
4571**
4572** All loads and stores begun before the barrier must complete before
4573** any load or store begun after the barrier.
4574*/
4575static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004576 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004577){
drhff828942010-06-26 21:34:06 +00004578 UNUSED_PARAMETER(fd);
drh22c733d2015-09-24 12:40:43 +00004579 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
4580 unixEnterMutex(); /* Also mutex, for redundancy */
drhb29ad852010-06-01 00:03:57 +00004581 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004582}
4583
dan18801912010-06-14 14:07:50 +00004584/*
danda9fe0c2010-07-13 18:44:03 +00004585** Close a connection to shared-memory. Delete the underlying
4586** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004587**
4588** If there is no shared memory associated with the connection then this
4589** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004590*/
danda9fe0c2010-07-13 18:44:03 +00004591static int unixShmUnmap(
4592 sqlite3_file *fd, /* The underlying database file */
4593 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004594){
danda9fe0c2010-07-13 18:44:03 +00004595 unixShm *p; /* The connection to be closed */
4596 unixShmNode *pShmNode; /* The underlying shared-memory file */
4597 unixShm **pp; /* For looping over sibling connections */
4598 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004599
danda9fe0c2010-07-13 18:44:03 +00004600 pDbFd = (unixFile*)fd;
4601 p = pDbFd->pShm;
4602 if( p==0 ) return SQLITE_OK;
4603 pShmNode = p->pShmNode;
4604
4605 assert( pShmNode==pDbFd->pInode->pShmNode );
4606 assert( pShmNode->pInode==pDbFd->pInode );
4607
4608 /* Remove connection p from the set of connections associated
4609 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004610 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004611 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4612 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004613
danda9fe0c2010-07-13 18:44:03 +00004614 /* Free the connection p */
4615 sqlite3_free(p);
4616 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004617 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004618
4619 /* If pShmNode->nRef has reached 0, then close the underlying
4620 ** shared-memory file, too */
4621 unixEnterMutex();
4622 assert( pShmNode->nRef>0 );
4623 pShmNode->nRef--;
4624 if( pShmNode->nRef==0 ){
drh4bf66fd2015-02-19 02:43:02 +00004625 if( deleteFlag && pShmNode->h>=0 ){
4626 osUnlink(pShmNode->zFilename);
4627 }
danda9fe0c2010-07-13 18:44:03 +00004628 unixShmPurge(pDbFd);
4629 }
4630 unixLeaveMutex();
4631
4632 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004633}
drh286a2882010-05-20 23:51:06 +00004634
danda9fe0c2010-07-13 18:44:03 +00004635
drhd9e5c4f2010-05-12 18:01:39 +00004636#else
drh6b017cc2010-06-14 18:01:46 +00004637# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004638# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004639# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004640# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004641#endif /* #ifndef SQLITE_OMIT_WAL */
4642
mistachkine98844f2013-08-24 00:59:24 +00004643#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004644/*
danaef49d72013-03-25 16:28:54 +00004645** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004646*/
danf23da962013-03-23 21:00:41 +00004647static void unixUnmapfile(unixFile *pFd){
4648 assert( pFd->nFetchOut==0 );
4649 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004650 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004651 pFd->pMapRegion = 0;
4652 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004653 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004654 }
4655}
dan5d8a1372013-03-19 19:28:06 +00004656
danaef49d72013-03-25 16:28:54 +00004657/*
dane6ecd662013-04-01 17:56:59 +00004658** Attempt to set the size of the memory mapping maintained by file
4659** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4660**
4661** If successful, this function sets the following variables:
4662**
4663** unixFile.pMapRegion
4664** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004665** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004666**
4667** If unsuccessful, an error message is logged via sqlite3_log() and
4668** the three variables above are zeroed. In this case SQLite should
4669** continue accessing the database using the xRead() and xWrite()
4670** methods.
4671*/
4672static void unixRemapfile(
4673 unixFile *pFd, /* File descriptor object */
4674 i64 nNew /* Required mapping size */
4675){
dan4ff7bc42013-04-02 12:04:09 +00004676 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004677 int h = pFd->h; /* File descriptor open on db file */
4678 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004679 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004680 u8 *pNew = 0; /* Location of new mapping */
4681 int flags = PROT_READ; /* Flags to pass to mmap() */
4682
4683 assert( pFd->nFetchOut==0 );
4684 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004685 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004686 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004687 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004688 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004689
danfe33e392015-11-17 20:56:06 +00004690#ifdef SQLITE_MMAP_READWRITE
dane6ecd662013-04-01 17:56:59 +00004691 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
danfe33e392015-11-17 20:56:06 +00004692#endif
dane6ecd662013-04-01 17:56:59 +00004693
4694 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00004695#if HAVE_MREMAP
4696 i64 nReuse = pFd->mmapSize;
4697#else
danbc760632014-03-20 09:42:09 +00004698 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00004699 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00004700#endif
dane6ecd662013-04-01 17:56:59 +00004701 u8 *pReq = &pOrig[nReuse];
4702
4703 /* Unmap any pages of the existing mapping that cannot be reused. */
4704 if( nReuse!=nOrig ){
4705 osMunmap(pReq, nOrig-nReuse);
4706 }
4707
4708#if HAVE_MREMAP
4709 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004710 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004711#else
4712 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4713 if( pNew!=MAP_FAILED ){
4714 if( pNew!=pReq ){
4715 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004716 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004717 }else{
4718 pNew = pOrig;
4719 }
4720 }
4721#endif
4722
dan48ccef82013-04-02 20:55:01 +00004723 /* The attempt to extend the existing mapping failed. Free it. */
4724 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004725 osMunmap(pOrig, nReuse);
4726 }
4727 }
4728
4729 /* If pNew is still NULL, try to create an entirely new mapping. */
4730 if( pNew==0 ){
4731 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004732 }
4733
dan4ff7bc42013-04-02 12:04:09 +00004734 if( pNew==MAP_FAILED ){
4735 pNew = 0;
4736 nNew = 0;
4737 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4738
4739 /* If the mmap() above failed, assume that all subsequent mmap() calls
4740 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4741 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004742 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004743 }
dane6ecd662013-04-01 17:56:59 +00004744 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004745 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004746}
4747
4748/*
danaef49d72013-03-25 16:28:54 +00004749** Memory map or remap the file opened by file-descriptor pFd (if the file
4750** is already mapped, the existing mapping is replaced by the new). Or, if
4751** there already exists a mapping for this file, and there are still
4752** outstanding xFetch() references to it, this function is a no-op.
4753**
4754** If parameter nByte is non-negative, then it is the requested size of
4755** the mapping to create. Otherwise, if nByte is less than zero, then the
4756** requested size is the size of the file on disk. The actual size of the
4757** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004758** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004759**
4760** SQLITE_OK is returned if no error occurs (even if the mapping is not
4761** recreated as a result of outstanding references) or an SQLite error
4762** code otherwise.
4763*/
danf23da962013-03-23 21:00:41 +00004764static int unixMapfile(unixFile *pFd, i64 nByte){
4765 i64 nMap = nByte;
4766 int rc;
daneb97b292013-03-20 14:26:59 +00004767
danf23da962013-03-23 21:00:41 +00004768 assert( nMap>=0 || pFd->nFetchOut==0 );
4769 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4770
4771 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00004772 struct stat statbuf; /* Low-level file information */
4773 rc = osFstat(pFd->h, &statbuf);
danf23da962013-03-23 21:00:41 +00004774 if( rc!=SQLITE_OK ){
4775 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004776 }
drh3044b512014-06-16 16:41:52 +00004777 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00004778 }
drh9b4c59f2013-04-15 17:03:42 +00004779 if( nMap>pFd->mmapSizeMax ){
4780 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004781 }
4782
danf23da962013-03-23 21:00:41 +00004783 if( nMap!=pFd->mmapSize ){
dane6ecd662013-04-01 17:56:59 +00004784 if( nMap>0 ){
4785 unixRemapfile(pFd, nMap);
4786 }else{
danb7e3a322013-03-25 20:30:13 +00004787 unixUnmapfile(pFd);
dan5d8a1372013-03-19 19:28:06 +00004788 }
4789 }
4790
danf23da962013-03-23 21:00:41 +00004791 return SQLITE_OK;
4792}
mistachkine98844f2013-08-24 00:59:24 +00004793#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004794
danaef49d72013-03-25 16:28:54 +00004795/*
4796** If possible, return a pointer to a mapping of file fd starting at offset
4797** iOff. The mapping must be valid for at least nAmt bytes.
4798**
4799** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4800** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4801** Finally, if an error does occur, return an SQLite error code. The final
4802** value of *pp is undefined in this case.
4803**
4804** If this function does return a pointer, the caller must eventually
4805** release the reference by calling unixUnfetch().
4806*/
danf23da962013-03-23 21:00:41 +00004807static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004808#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004809 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004810#endif
danf23da962013-03-23 21:00:41 +00004811 *pp = 0;
4812
drh9b4c59f2013-04-15 17:03:42 +00004813#if SQLITE_MAX_MMAP_SIZE>0
4814 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004815 if( pFd->pMapRegion==0 ){
4816 int rc = unixMapfile(pFd, -1);
4817 if( rc!=SQLITE_OK ) return rc;
4818 }
4819 if( pFd->mmapSize >= iOff+nAmt ){
4820 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4821 pFd->nFetchOut++;
4822 }
4823 }
drh6e0b6d52013-04-09 16:19:20 +00004824#endif
danf23da962013-03-23 21:00:41 +00004825 return SQLITE_OK;
4826}
4827
danaef49d72013-03-25 16:28:54 +00004828/*
dandf737fe2013-03-25 17:00:24 +00004829** If the third argument is non-NULL, then this function releases a
4830** reference obtained by an earlier call to unixFetch(). The second
4831** argument passed to this function must be the same as the corresponding
4832** argument that was passed to the unixFetch() invocation.
4833**
4834** Or, if the third argument is NULL, then this function is being called
4835** to inform the VFS layer that, according to POSIX, any existing mapping
4836** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004837*/
dandf737fe2013-03-25 17:00:24 +00004838static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00004839#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00004840 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00004841 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00004842
danaef49d72013-03-25 16:28:54 +00004843 /* If p==0 (unmap the entire file) then there must be no outstanding
4844 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4845 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004846 assert( (p==0)==(pFd->nFetchOut==0) );
4847
dandf737fe2013-03-25 17:00:24 +00004848 /* If p!=0, it must match the iOff value. */
4849 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4850
danf23da962013-03-23 21:00:41 +00004851 if( p ){
4852 pFd->nFetchOut--;
4853 }else{
4854 unixUnmapfile(pFd);
4855 }
4856
4857 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00004858#else
4859 UNUSED_PARAMETER(fd);
4860 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00004861 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00004862#endif
danf23da962013-03-23 21:00:41 +00004863 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004864}
4865
4866/*
drh734c9862008-11-28 15:37:20 +00004867** Here ends the implementation of all sqlite3_file methods.
4868**
4869********************** End sqlite3_file Methods *******************************
4870******************************************************************************/
4871
4872/*
drh6b9d6dd2008-12-03 19:34:47 +00004873** This division contains definitions of sqlite3_io_methods objects that
4874** implement various file locking strategies. It also contains definitions
4875** of "finder" functions. A finder-function is used to locate the appropriate
4876** sqlite3_io_methods object for a particular database file. The pAppData
4877** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4878** the correct finder-function for that VFS.
4879**
4880** Most finder functions return a pointer to a fixed sqlite3_io_methods
4881** object. The only interesting finder-function is autolockIoFinder, which
4882** looks at the filesystem type and tries to guess the best locking
4883** strategy from that.
4884**
peter.d.reid60ec9142014-09-06 16:39:46 +00004885** For finder-function F, two objects are created:
drh1875f7a2008-12-08 18:19:17 +00004886**
4887** (1) The real finder-function named "FImpt()".
4888**
dane946c392009-08-22 11:39:46 +00004889** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004890**
4891**
4892** A pointer to the F pointer is used as the pAppData value for VFS
4893** objects. We have to do this instead of letting pAppData point
4894** directly at the finder-function since C90 rules prevent a void*
4895** from be cast into a function pointer.
4896**
drh6b9d6dd2008-12-03 19:34:47 +00004897**
drh7708e972008-11-29 00:56:52 +00004898** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004899**
drh7708e972008-11-29 00:56:52 +00004900** * A constant sqlite3_io_methods object call METHOD that has locking
4901** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4902**
4903** * An I/O method finder function called FINDER that returns a pointer
4904** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004905*/
drhe6d41732015-02-21 00:49:00 +00004906#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
drh7708e972008-11-29 00:56:52 +00004907static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004908 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004909 CLOSE, /* xClose */ \
4910 unixRead, /* xRead */ \
4911 unixWrite, /* xWrite */ \
4912 unixTruncate, /* xTruncate */ \
4913 unixSync, /* xSync */ \
4914 unixFileSize, /* xFileSize */ \
4915 LOCK, /* xLock */ \
4916 UNLOCK, /* xUnlock */ \
4917 CKLOCK, /* xCheckReservedLock */ \
4918 unixFileControl, /* xFileControl */ \
4919 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004920 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drhd9f94412014-09-22 03:22:27 +00004921 SHMMAP, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004922 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004923 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00004924 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00004925 unixFetch, /* xFetch */ \
4926 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00004927}; \
drh0c2694b2009-09-03 16:23:44 +00004928static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4929 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004930 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004931} \
drh0c2694b2009-09-03 16:23:44 +00004932static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004933 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004934
4935/*
4936** Here are all of the sqlite3_io_methods objects for each of the
4937** locking strategies. Functions that return pointers to these methods
4938** are also created.
4939*/
4940IOMETHODS(
4941 posixIoFinder, /* Finder function name */
4942 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00004943 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00004944 unixClose, /* xClose method */
4945 unixLock, /* xLock method */
4946 unixUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004947 unixCheckReservedLock, /* xCheckReservedLock method */
4948 unixShmMap /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004949)
drh7708e972008-11-29 00:56:52 +00004950IOMETHODS(
4951 nolockIoFinder, /* Finder function name */
4952 nolockIoMethods, /* sqlite3_io_methods object name */
drh142341c2014-09-19 19:00:48 +00004953 3, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004954 nolockClose, /* xClose method */
4955 nolockLock, /* xLock method */
4956 nolockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004957 nolockCheckReservedLock, /* xCheckReservedLock method */
4958 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004959)
drh7708e972008-11-29 00:56:52 +00004960IOMETHODS(
4961 dotlockIoFinder, /* Finder function name */
4962 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004963 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004964 dotlockClose, /* xClose method */
4965 dotlockLock, /* xLock method */
4966 dotlockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004967 dotlockCheckReservedLock, /* xCheckReservedLock method */
4968 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004969)
drh7708e972008-11-29 00:56:52 +00004970
drhe89b2912015-03-03 20:42:01 +00004971#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004972IOMETHODS(
4973 flockIoFinder, /* Finder function name */
4974 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004975 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004976 flockClose, /* xClose method */
4977 flockLock, /* xLock method */
4978 flockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004979 flockCheckReservedLock, /* xCheckReservedLock method */
4980 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004981)
drh7708e972008-11-29 00:56:52 +00004982#endif
4983
drh6c7d5c52008-11-21 20:32:33 +00004984#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004985IOMETHODS(
4986 semIoFinder, /* Finder function name */
4987 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004988 1, /* shared memory is disabled */
drh8cd5b252015-03-02 22:06:43 +00004989 semXClose, /* xClose method */
4990 semXLock, /* xLock method */
4991 semXUnlock, /* xUnlock method */
4992 semXCheckReservedLock, /* xCheckReservedLock method */
drhd9f94412014-09-22 03:22:27 +00004993 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004994)
aswiftaebf4132008-11-21 00:10:35 +00004995#endif
drh7708e972008-11-29 00:56:52 +00004996
drhd2cb50b2009-01-09 21:41:17 +00004997#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004998IOMETHODS(
4999 afpIoFinder, /* Finder function name */
5000 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005001 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005002 afpClose, /* xClose method */
5003 afpLock, /* xLock method */
5004 afpUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005005 afpCheckReservedLock, /* xCheckReservedLock method */
5006 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005007)
drh715ff302008-12-03 22:32:44 +00005008#endif
5009
5010/*
5011** The proxy locking method is a "super-method" in the sense that it
5012** opens secondary file descriptors for the conch and lock files and
5013** it uses proxy, dot-file, AFP, and flock() locking methods on those
5014** secondary files. For this reason, the division that implements
5015** proxy locking is located much further down in the file. But we need
5016** to go ahead and define the sqlite3_io_methods and finder function
5017** for proxy locking here. So we forward declare the I/O methods.
5018*/
drhd2cb50b2009-01-09 21:41:17 +00005019#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005020static int proxyClose(sqlite3_file*);
5021static int proxyLock(sqlite3_file*, int);
5022static int proxyUnlock(sqlite3_file*, int);
5023static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005024IOMETHODS(
5025 proxyIoFinder, /* Finder function name */
5026 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005027 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005028 proxyClose, /* xClose method */
5029 proxyLock, /* xLock method */
5030 proxyUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005031 proxyCheckReservedLock, /* xCheckReservedLock method */
5032 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005033)
aswiftaebf4132008-11-21 00:10:35 +00005034#endif
drh7708e972008-11-29 00:56:52 +00005035
drh7ed97b92010-01-20 13:07:21 +00005036/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5037#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5038IOMETHODS(
5039 nfsIoFinder, /* Finder function name */
5040 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005041 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005042 unixClose, /* xClose method */
5043 unixLock, /* xLock method */
5044 nfsUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005045 unixCheckReservedLock, /* xCheckReservedLock method */
5046 0 /* xShmMap method */
drh7ed97b92010-01-20 13:07:21 +00005047)
5048#endif
drh7708e972008-11-29 00:56:52 +00005049
drhd2cb50b2009-01-09 21:41:17 +00005050#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005051/*
drh6b9d6dd2008-12-03 19:34:47 +00005052** This "finder" function attempts to determine the best locking strategy
5053** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005054** object that implements that strategy.
5055**
5056** This is for MacOSX only.
5057*/
drh1875f7a2008-12-08 18:19:17 +00005058static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005059 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005060 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005061){
5062 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005063 const char *zFilesystem; /* Filesystem type name */
5064 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005065 } aMap[] = {
5066 { "hfs", &posixIoMethods },
5067 { "ufs", &posixIoMethods },
5068 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005069 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005070 { "webdav", &nolockIoMethods },
5071 { 0, 0 }
5072 };
5073 int i;
5074 struct statfs fsInfo;
5075 struct flock lockInfo;
5076
5077 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005078 /* If filePath==NULL that means we are dealing with a transient file
5079 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005080 return &nolockIoMethods;
5081 }
5082 if( statfs(filePath, &fsInfo) != -1 ){
5083 if( fsInfo.f_flags & MNT_RDONLY ){
5084 return &nolockIoMethods;
5085 }
5086 for(i=0; aMap[i].zFilesystem; i++){
5087 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5088 return aMap[i].pMethods;
5089 }
5090 }
5091 }
5092
5093 /* Default case. Handles, amongst others, "nfs".
5094 ** Test byte-range lock using fcntl(). If the call succeeds,
5095 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005096 */
drh7708e972008-11-29 00:56:52 +00005097 lockInfo.l_len = 1;
5098 lockInfo.l_start = 0;
5099 lockInfo.l_whence = SEEK_SET;
5100 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005101 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005102 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5103 return &nfsIoMethods;
5104 } else {
5105 return &posixIoMethods;
5106 }
drh7708e972008-11-29 00:56:52 +00005107 }else{
5108 return &dotlockIoMethods;
5109 }
5110}
drh0c2694b2009-09-03 16:23:44 +00005111static const sqlite3_io_methods
5112 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005113
drhd2cb50b2009-01-09 21:41:17 +00005114#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005115
drhe89b2912015-03-03 20:42:01 +00005116#if OS_VXWORKS
5117/*
5118** This "finder" function for VxWorks checks to see if posix advisory
5119** locking works. If it does, then that is what is used. If it does not
5120** work, then fallback to named semaphore locking.
chw78a13182009-04-07 05:35:03 +00005121*/
drhe89b2912015-03-03 20:42:01 +00005122static const sqlite3_io_methods *vxworksIoFinderImpl(
chw78a13182009-04-07 05:35:03 +00005123 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005124 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005125){
5126 struct flock lockInfo;
5127
5128 if( !filePath ){
5129 /* If filePath==NULL that means we are dealing with a transient file
5130 ** that does not need to be locked. */
5131 return &nolockIoMethods;
5132 }
5133
5134 /* Test if fcntl() is supported and use POSIX style locks.
5135 ** Otherwise fall back to the named semaphore method.
5136 */
5137 lockInfo.l_len = 1;
5138 lockInfo.l_start = 0;
5139 lockInfo.l_whence = SEEK_SET;
5140 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005141 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005142 return &posixIoMethods;
5143 }else{
5144 return &semIoMethods;
5145 }
5146}
drh0c2694b2009-09-03 16:23:44 +00005147static const sqlite3_io_methods
drhe89b2912015-03-03 20:42:01 +00005148 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005149
drhe89b2912015-03-03 20:42:01 +00005150#endif /* OS_VXWORKS */
chw78a13182009-04-07 05:35:03 +00005151
drh7708e972008-11-29 00:56:52 +00005152/*
peter.d.reid60ec9142014-09-06 16:39:46 +00005153** An abstract type for a pointer to an IO method finder function:
drh7708e972008-11-29 00:56:52 +00005154*/
drh0c2694b2009-09-03 16:23:44 +00005155typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005156
aswiftaebf4132008-11-21 00:10:35 +00005157
drh734c9862008-11-28 15:37:20 +00005158/****************************************************************************
5159**************************** sqlite3_vfs methods ****************************
5160**
5161** This division contains the implementation of methods on the
5162** sqlite3_vfs object.
5163*/
5164
danielk1977a3d4c882007-03-23 10:08:38 +00005165/*
danielk1977e339d652008-06-28 11:23:00 +00005166** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005167*/
5168static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005169 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005170 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005171 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005172 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005173 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005174){
drh7708e972008-11-29 00:56:52 +00005175 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005176 unixFile *pNew = (unixFile *)pId;
5177 int rc = SQLITE_OK;
5178
drh8af6c222010-05-14 12:43:01 +00005179 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005180
dan00157392010-10-05 11:33:15 +00005181 /* Usually the path zFilename should not be a relative pathname. The
5182 ** exception is when opening the proxy "conch" file in builds that
5183 ** include the special Apple locking styles.
5184 */
dan00157392010-10-05 11:33:15 +00005185#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005186 assert( zFilename==0 || zFilename[0]=='/'
5187 || pVfs->pAppData==(void*)&autolockIoFinder );
5188#else
5189 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005190#endif
dan00157392010-10-05 11:33:15 +00005191
drhb07028f2011-10-14 21:49:18 +00005192 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005193 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005194
drh308c2a52010-05-14 11:30:18 +00005195 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005196 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005197 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005198 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005199 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005200#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005201 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005202#endif
drhc02a43a2012-01-10 23:18:38 +00005203 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5204 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005205 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005206 }
drh503a6862013-03-01 01:07:17 +00005207 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005208 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005209 }
drh339eb0b2008-03-07 15:34:11 +00005210
drh6c7d5c52008-11-21 20:32:33 +00005211#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005212 pNew->pId = vxworksFindFileId(zFilename);
5213 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005214 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00005215 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00005216 }
5217#endif
5218
drhc02a43a2012-01-10 23:18:38 +00005219 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005220 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005221 }else{
drh0c2694b2009-09-03 16:23:44 +00005222 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005223#if SQLITE_ENABLE_LOCKING_STYLE
5224 /* Cache zFilename in the locking context (AFP and dotlock override) for
5225 ** proxyLock activation is possible (remote proxy is based on db name)
5226 ** zFilename remains valid until file is closed, to support */
5227 pNew->lockingContext = (void*)zFilename;
5228#endif
drhda0e7682008-07-30 15:27:54 +00005229 }
danielk1977e339d652008-06-28 11:23:00 +00005230
drh7ed97b92010-01-20 13:07:21 +00005231 if( pLockingStyle == &posixIoMethods
5232#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5233 || pLockingStyle == &nfsIoMethods
5234#endif
5235 ){
drh7708e972008-11-29 00:56:52 +00005236 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005237 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005238 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005239 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005240 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005241 ** in two scenarios:
5242 **
5243 ** (a) A call to fstat() failed.
5244 ** (b) A malloc failed.
5245 **
5246 ** Scenario (b) may only occur if the process is holding no other
5247 ** file descriptors open on the same file. If there were other file
5248 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005249 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005250 ** handle h - as it is guaranteed that no posix locks will be released
5251 ** by doing so.
5252 **
5253 ** If scenario (a) caused the error then things are not so safe. The
5254 ** implicit assumption here is that if fstat() fails, things are in
5255 ** such bad shape that dropping a lock or two doesn't matter much.
5256 */
drh0e9365c2011-03-02 02:08:13 +00005257 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005258 h = -1;
5259 }
drh7708e972008-11-29 00:56:52 +00005260 unixLeaveMutex();
5261 }
danielk1977e339d652008-06-28 11:23:00 +00005262
drhd2cb50b2009-01-09 21:41:17 +00005263#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005264 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005265 /* AFP locking uses the file path so it needs to be included in
5266 ** the afpLockingContext.
5267 */
5268 afpLockingContext *pCtx;
drhf3cdcdc2015-04-29 16:50:28 +00005269 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh7708e972008-11-29 00:56:52 +00005270 if( pCtx==0 ){
5271 rc = SQLITE_NOMEM;
5272 }else{
5273 /* NB: zFilename exists and remains valid until the file is closed
5274 ** according to requirement F11141. So we do not need to make a
5275 ** copy of the filename. */
5276 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005277 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005278 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005279 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005280 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005281 if( rc!=SQLITE_OK ){
5282 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005283 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005284 h = -1;
5285 }
drh7708e972008-11-29 00:56:52 +00005286 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005287 }
drh7708e972008-11-29 00:56:52 +00005288 }
5289#endif
danielk1977e339d652008-06-28 11:23:00 +00005290
drh7708e972008-11-29 00:56:52 +00005291 else if( pLockingStyle == &dotlockIoMethods ){
5292 /* Dotfile locking uses the file path so it needs to be included in
5293 ** the dotlockLockingContext
5294 */
5295 char *zLockFile;
5296 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005297 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005298 nFilename = (int)strlen(zFilename) + 6;
drhf3cdcdc2015-04-29 16:50:28 +00005299 zLockFile = (char *)sqlite3_malloc64(nFilename);
drh7708e972008-11-29 00:56:52 +00005300 if( zLockFile==0 ){
5301 rc = SQLITE_NOMEM;
5302 }else{
5303 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005304 }
drh7708e972008-11-29 00:56:52 +00005305 pNew->lockingContext = zLockFile;
5306 }
danielk1977e339d652008-06-28 11:23:00 +00005307
drh6c7d5c52008-11-21 20:32:33 +00005308#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005309 else if( pLockingStyle == &semIoMethods ){
5310 /* Named semaphore locking uses the file path so it needs to be
5311 ** included in the semLockingContext
5312 */
5313 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005314 rc = findInodeInfo(pNew, &pNew->pInode);
5315 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5316 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005317 int n;
drh2238dcc2009-08-27 17:56:20 +00005318 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005319 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005320 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005321 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005322 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5323 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00005324 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00005325 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005326 }
chw97185482008-11-17 08:05:31 +00005327 }
drh7708e972008-11-29 00:56:52 +00005328 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005329 }
drh7708e972008-11-29 00:56:52 +00005330#endif
aswift5b1a2562008-08-22 00:22:35 +00005331
drh4bf66fd2015-02-19 02:43:02 +00005332 storeLastErrno(pNew, 0);
drh6c7d5c52008-11-21 20:32:33 +00005333#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005334 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005335 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005336 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005337 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005338 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005339 }
chw97185482008-11-17 08:05:31 +00005340#endif
danielk1977e339d652008-06-28 11:23:00 +00005341 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005342 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005343 }else{
drh7708e972008-11-29 00:56:52 +00005344 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005345 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005346 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005347 }
danielk1977e339d652008-06-28 11:23:00 +00005348 return rc;
drh054889e2005-11-30 03:20:31 +00005349}
drh9c06c952005-11-26 00:25:00 +00005350
danielk1977ad94b582007-08-20 06:44:22 +00005351/*
drh8b3cf822010-06-01 21:02:51 +00005352** Return the name of a directory in which to put temporary files.
5353** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005354*/
drh7234c6d2010-06-19 15:10:09 +00005355static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005356 static const char *azDirs[] = {
5357 0,
aswiftaebf4132008-11-21 00:10:35 +00005358 0,
danielk197717b90b52008-06-06 11:11:25 +00005359 "/var/tmp",
5360 "/usr/tmp",
5361 "/tmp",
drhb7e50ad2015-11-28 21:49:53 +00005362 "."
danielk197717b90b52008-06-06 11:11:25 +00005363 };
drh8b3cf822010-06-01 21:02:51 +00005364 unsigned int i;
5365 struct stat buf;
drhb7e50ad2015-11-28 21:49:53 +00005366 const char *zDir = sqlite3_temp_directory;
drh8b3cf822010-06-01 21:02:51 +00005367
drhb7e50ad2015-11-28 21:49:53 +00005368 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
5369 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005370 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005371 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005372 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005373 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005374 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005375 break;
5376 }
5377 return zDir;
5378}
5379
5380/*
5381** Create a temporary file name in zBuf. zBuf must be allocated
5382** by the calling process and must be big enough to hold at least
5383** pVfs->mxPathname bytes.
5384*/
5385static int unixGetTempname(int nBuf, char *zBuf){
drh8b3cf822010-06-01 21:02:51 +00005386 const char *zDir;
drhb7e50ad2015-11-28 21:49:53 +00005387 int iLimit = 0;
danielk197717b90b52008-06-06 11:11:25 +00005388
5389 /* It's odd to simulate an io-error here, but really this is just
5390 ** using the io-error infrastructure to test that SQLite handles this
5391 ** function failing.
5392 */
5393 SimulateIOError( return SQLITE_IOERR );
5394
drh7234c6d2010-06-19 15:10:09 +00005395 zDir = unixTempFileDir();
danielk197717b90b52008-06-06 11:11:25 +00005396 do{
drh970942e2015-11-25 23:13:14 +00005397 u64 r;
5398 sqlite3_randomness(sizeof(r), &r);
5399 assert( nBuf>2 );
5400 zBuf[nBuf-2] = 0;
5401 sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
5402 zDir, r, 0);
drhb7e50ad2015-11-28 21:49:53 +00005403 if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
drh99ab3b12011-03-02 15:09:07 +00005404 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005405 return SQLITE_OK;
5406}
5407
drhd2cb50b2009-01-09 21:41:17 +00005408#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005409/*
5410** Routine to transform a unixFile into a proxy-locking unixFile.
5411** Implementation in the proxy-lock division, but used by unixOpen()
5412** if SQLITE_PREFER_PROXY_LOCKING is defined.
5413*/
5414static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005415#endif
drhc66d5b62008-12-03 22:48:32 +00005416
dan08da86a2009-08-21 17:18:03 +00005417/*
5418** Search for an unused file descriptor that was opened on the database
5419** file (not a journal or master-journal file) identified by pathname
5420** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5421** argument to this function.
5422**
5423** Such a file descriptor may exist if a database connection was closed
5424** but the associated file descriptor could not be closed because some
5425** other file descriptor open on the same file is holding a file-lock.
5426** Refer to comments in the unixClose() function and the lengthy comment
5427** describing "Posix Advisory Locking" at the start of this file for
5428** further details. Also, ticket #4018.
5429**
5430** If a suitable file descriptor is found, then it is returned. If no
5431** such file descriptor is located, -1 is returned.
5432*/
dane946c392009-08-22 11:39:46 +00005433static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5434 UnixUnusedFd *pUnused = 0;
5435
5436 /* Do not search for an unused file descriptor on vxworks. Not because
5437 ** vxworks would not benefit from the change (it might, we're not sure),
5438 ** but because no way to test it is currently available. It is better
5439 ** not to risk breaking vxworks support for the sake of such an obscure
5440 ** feature. */
5441#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005442 struct stat sStat; /* Results of stat() call */
5443
5444 /* A stat() call may fail for various reasons. If this happens, it is
5445 ** almost certain that an open() call on the same path will also fail.
5446 ** For this reason, if an error occurs in the stat() call here, it is
5447 ** ignored and -1 is returned. The caller will try to open a new file
5448 ** descriptor on the same path, fail, and return an error to SQLite.
5449 **
5450 ** Even if a subsequent open() call does succeed, the consequences of
peter.d.reid60ec9142014-09-06 16:39:46 +00005451 ** not searching for a reusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005452 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005453 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005454
5455 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005456 pInode = inodeList;
5457 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5458 || pInode->fileId.ino!=sStat.st_ino) ){
5459 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005460 }
drh8af6c222010-05-14 12:43:01 +00005461 if( pInode ){
dane946c392009-08-22 11:39:46 +00005462 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005463 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005464 pUnused = *pp;
5465 if( pUnused ){
5466 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005467 }
5468 }
5469 unixLeaveMutex();
5470 }
dane946c392009-08-22 11:39:46 +00005471#endif /* if !OS_VXWORKS */
5472 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005473}
danielk197717b90b52008-06-06 11:11:25 +00005474
5475/*
danddb0ac42010-07-14 14:48:58 +00005476** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005477** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005478** and a value suitable for passing as the third argument to open(2) is
5479** written to *pMode. If an IO error occurs, an SQLite error code is
5480** returned and the value of *pMode is not modified.
5481**
peter.d.reid60ec9142014-09-06 16:39:46 +00005482** In most cases, this routine sets *pMode to 0, which will become
drh8c815d12012-02-13 20:16:37 +00005483** an indication to robust_open() to create the file using
5484** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5485** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005486** this function queries the file-system for the permissions on the
5487** corresponding database file and sets *pMode to this value. Whenever
5488** possible, WAL and journal files are created using the same permissions
5489** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005490**
5491** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5492** original filename is unavailable. But 8_3_NAMES is only used for
5493** FAT filesystems and permissions do not matter there, so just use
5494** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005495*/
5496static int findCreateFileMode(
5497 const char *zPath, /* Path of file (possibly) being created */
5498 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005499 mode_t *pMode, /* OUT: Permissions to open file with */
5500 uid_t *pUid, /* OUT: uid to set on the file */
5501 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005502){
5503 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005504 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005505 *pUid = 0;
5506 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005507 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005508 char zDb[MAX_PATHNAME+1]; /* Database file path */
5509 int nDb; /* Number of valid bytes in zDb */
5510 struct stat sStat; /* Output of stat() on database file */
5511
dana0c989d2010-11-05 18:07:37 +00005512 /* zPath is a path to a WAL or journal file. The following block derives
5513 ** the path to the associated database file from zPath. This block handles
5514 ** the following naming conventions:
5515 **
5516 ** "<path to db>-journal"
5517 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005518 ** "<path to db>-journalNN"
5519 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005520 **
drhd337c5b2011-10-20 18:23:35 +00005521 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005522 ** used by the test_multiplex.c module.
5523 */
5524 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005525#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00005526 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00005527 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005528#else
5529 while( zPath[nDb]!='-' ){
5530 assert( nDb>0 );
5531 assert( zPath[nDb]!='\n' );
5532 nDb--;
5533 }
5534#endif
danddb0ac42010-07-14 14:48:58 +00005535 memcpy(zDb, zPath, nDb);
5536 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005537
drh58384f12011-07-28 00:14:45 +00005538 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005539 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005540 *pUid = sStat.st_uid;
5541 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005542 }else{
5543 rc = SQLITE_IOERR_FSTAT;
5544 }
5545 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5546 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005547 }
5548 return rc;
5549}
5550
5551/*
danielk1977ad94b582007-08-20 06:44:22 +00005552** Open the file zPath.
5553**
danielk1977b4b47412007-08-17 15:53:36 +00005554** Previously, the SQLite OS layer used three functions in place of this
5555** one:
5556**
5557** sqlite3OsOpenReadWrite();
5558** sqlite3OsOpenReadOnly();
5559** sqlite3OsOpenExclusive();
5560**
5561** These calls correspond to the following combinations of flags:
5562**
5563** ReadWrite() -> (READWRITE | CREATE)
5564** ReadOnly() -> (READONLY)
5565** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5566**
5567** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5568** true, the file was configured to be automatically deleted when the
5569** file handle closed. To achieve the same effect using this new
5570** interface, add the DELETEONCLOSE flag to those specified above for
5571** OpenExclusive().
5572*/
5573static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005574 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5575 const char *zPath, /* Pathname of file to be opened */
5576 sqlite3_file *pFile, /* The file descriptor to be filled in */
5577 int flags, /* Input flags to control the opening */
5578 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005579){
dan08da86a2009-08-21 17:18:03 +00005580 unixFile *p = (unixFile *)pFile;
5581 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005582 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005583 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005584 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005585 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005586 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005587
5588 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5589 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5590 int isCreate = (flags & SQLITE_OPEN_CREATE);
5591 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5592 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005593#if SQLITE_ENABLE_LOCKING_STYLE
5594 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5595#endif
drh3d4435b2011-08-26 20:55:50 +00005596#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5597 struct statfs fsInfo;
5598#endif
danielk1977b4b47412007-08-17 15:53:36 +00005599
danielk1977fee2d252007-08-18 10:59:19 +00005600 /* If creating a master or main-file journal, this function will open
5601 ** a file-descriptor on the directory too. The first time unixSync()
5602 ** is called the directory file descriptor will be fsync()ed and close()d.
5603 */
drh0059eae2011-08-08 23:48:40 +00005604 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005605 eType==SQLITE_OPEN_MASTER_JOURNAL
5606 || eType==SQLITE_OPEN_MAIN_JOURNAL
5607 || eType==SQLITE_OPEN_WAL
5608 ));
danielk1977fee2d252007-08-18 10:59:19 +00005609
danielk197717b90b52008-06-06 11:11:25 +00005610 /* If argument zPath is a NULL pointer, this function is required to open
5611 ** a temporary file. Use this buffer to store the file name in.
5612 */
drhc02a43a2012-01-10 23:18:38 +00005613 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005614 const char *zName = zPath;
5615
danielk1977fee2d252007-08-18 10:59:19 +00005616 /* Check the following statements are true:
5617 **
5618 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5619 ** (b) if CREATE is set, then READWRITE must also be set, and
5620 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005621 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005622 */
danielk1977b4b47412007-08-17 15:53:36 +00005623 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005624 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005625 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005626 assert(isDelete==0 || isCreate);
5627
danddb0ac42010-07-14 14:48:58 +00005628 /* The main DB, main journal, WAL file and master journal are never
5629 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005630 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5631 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5632 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005633 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005634
danielk1977fee2d252007-08-18 10:59:19 +00005635 /* Assert that the upper layer has set one of the "file-type" flags. */
5636 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5637 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5638 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005639 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005640 );
5641
drhb00d8622014-01-01 15:18:36 +00005642 /* Detect a pid change and reset the PRNG. There is a race condition
5643 ** here such that two or more threads all trying to open databases at
5644 ** the same instant might all reset the PRNG. But multiple resets
5645 ** are harmless.
5646 */
drh5ac93652015-03-21 20:59:43 +00005647 if( randomnessPid!=osGetpid(0) ){
5648 randomnessPid = osGetpid(0);
drhb00d8622014-01-01 15:18:36 +00005649 sqlite3_randomness(0,0);
5650 }
5651
dan08da86a2009-08-21 17:18:03 +00005652 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005653
dan08da86a2009-08-21 17:18:03 +00005654 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005655 UnixUnusedFd *pUnused;
5656 pUnused = findReusableFd(zName, flags);
5657 if( pUnused ){
5658 fd = pUnused->fd;
5659 }else{
drhf3cdcdc2015-04-29 16:50:28 +00005660 pUnused = sqlite3_malloc64(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005661 if( !pUnused ){
5662 return SQLITE_NOMEM;
5663 }
5664 }
5665 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005666
5667 /* Database filenames are double-zero terminated if they are not
5668 ** URIs with parameters. Hence, they can always be passed into
5669 ** sqlite3_uri_parameter(). */
5670 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5671
dan08da86a2009-08-21 17:18:03 +00005672 }else if( !zName ){
5673 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005674 assert(isDelete && !syncDir);
drhb7e50ad2015-11-28 21:49:53 +00005675 rc = unixGetTempname(pVfs->mxPathname, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005676 if( rc!=SQLITE_OK ){
5677 return rc;
5678 }
5679 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005680
5681 /* Generated temporary filenames are always double-zero terminated
5682 ** for use by sqlite3_uri_parameter(). */
5683 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005684 }
5685
dan08da86a2009-08-21 17:18:03 +00005686 /* Determine the value of the flags parameter passed to POSIX function
5687 ** open(). These must be calculated even if open() is not called, as
5688 ** they may be stored as part of the file handle and used by the
5689 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005690 if( isReadonly ) openFlags |= O_RDONLY;
5691 if( isReadWrite ) openFlags |= O_RDWR;
5692 if( isCreate ) openFlags |= O_CREAT;
5693 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5694 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005695
danielk1977b4b47412007-08-17 15:53:36 +00005696 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005697 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005698 uid_t uid; /* Userid for the file */
5699 gid_t gid; /* Groupid for the file */
5700 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005701 if( rc!=SQLITE_OK ){
5702 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005703 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005704 return rc;
5705 }
drhad4f1e52011-03-04 15:43:57 +00005706 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005707 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
drh5a2d9702015-11-26 02:21:05 +00005708 assert( !isExclusive || (openFlags & O_CREAT)!=0 );
5709 if( fd<0 && errno!=EISDIR && isReadWrite ){
dan08da86a2009-08-21 17:18:03 +00005710 /* Failed to open the file for read/write access. Try read-only. */
5711 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005712 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005713 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005714 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005715 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005716 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005717 }
5718 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005719 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005720 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005721 }
drhac7c3ac2012-02-11 19:23:48 +00005722
5723 /* If this process is running as root and if creating a new rollback
5724 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005725 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005726 */
5727 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drh6226ca22015-11-24 15:06:28 +00005728 robustFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005729 }
danielk1977b4b47412007-08-17 15:53:36 +00005730 }
dan08da86a2009-08-21 17:18:03 +00005731 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005732 if( pOutFlags ){
5733 *pOutFlags = flags;
5734 }
5735
dane946c392009-08-22 11:39:46 +00005736 if( p->pUnused ){
5737 p->pUnused->fd = fd;
5738 p->pUnused->flags = flags;
5739 }
5740
danielk1977b4b47412007-08-17 15:53:36 +00005741 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005742#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005743 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00005744#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
5745 zPath = sqlite3_mprintf("%s", zName);
5746 if( zPath==0 ){
5747 robust_close(p, fd, __LINE__);
5748 return SQLITE_NOMEM;
5749 }
chw97185482008-11-17 08:05:31 +00005750#else
drh036ac7f2011-08-08 23:18:05 +00005751 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005752#endif
danielk1977b4b47412007-08-17 15:53:36 +00005753 }
drh41022642008-11-21 00:24:42 +00005754#if SQLITE_ENABLE_LOCKING_STYLE
5755 else{
dan08da86a2009-08-21 17:18:03 +00005756 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005757 }
5758#endif
5759
drhda0e7682008-07-30 15:27:54 +00005760 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005761
drh7ed97b92010-01-20 13:07:21 +00005762
5763#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005764 if( fstatfs(fd, &fsInfo) == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00005765 storeLastErrno(p, errno);
drh0e9365c2011-03-02 02:08:13 +00005766 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005767 return SQLITE_IOERR_ACCESS;
5768 }
5769 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5770 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5771 }
drh4bf66fd2015-02-19 02:43:02 +00005772 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
5773 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5774 }
drh7ed97b92010-01-20 13:07:21 +00005775#endif
drhc02a43a2012-01-10 23:18:38 +00005776
5777 /* Set up appropriate ctrlFlags */
5778 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5779 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5780 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5781 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5782 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5783
drh7ed97b92010-01-20 13:07:21 +00005784#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005785#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005786 isAutoProxy = 1;
5787#endif
5788 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005789 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5790 int useProxy = 0;
5791
dan08da86a2009-08-21 17:18:03 +00005792 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5793 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005794 if( envforce!=NULL ){
5795 useProxy = atoi(envforce)>0;
5796 }else{
aswiftaebf4132008-11-21 00:10:35 +00005797 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5798 }
5799 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005800 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005801 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005802 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005803 if( rc!=SQLITE_OK ){
5804 /* Use unixClose to clean up the resources added in fillInUnixFile
5805 ** and clear all the structure's references. Specifically,
5806 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5807 */
5808 unixClose(pFile);
5809 return rc;
5810 }
aswiftaebf4132008-11-21 00:10:35 +00005811 }
dane946c392009-08-22 11:39:46 +00005812 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005813 }
5814 }
5815#endif
5816
drhc02a43a2012-01-10 23:18:38 +00005817 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5818
dane946c392009-08-22 11:39:46 +00005819open_finished:
5820 if( rc!=SQLITE_OK ){
5821 sqlite3_free(p->pUnused);
5822 }
5823 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005824}
5825
dane946c392009-08-22 11:39:46 +00005826
danielk1977b4b47412007-08-17 15:53:36 +00005827/*
danielk1977fee2d252007-08-18 10:59:19 +00005828** Delete the file at zPath. If the dirSync argument is true, fsync()
5829** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005830*/
drh6b9d6dd2008-12-03 19:34:47 +00005831static int unixDelete(
5832 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5833 const char *zPath, /* Name of file to be deleted */
5834 int dirSync /* If true, fsync() directory after deleting file */
5835){
danielk1977fee2d252007-08-18 10:59:19 +00005836 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005837 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005838 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005839 if( osUnlink(zPath)==(-1) ){
drhbd945542014-08-13 11:39:42 +00005840 if( errno==ENOENT
5841#if OS_VXWORKS
drh19541f32014-09-01 13:37:55 +00005842 || osAccess(zPath,0)!=0
drhbd945542014-08-13 11:39:42 +00005843#endif
5844 ){
dan9fc5b4a2012-11-09 20:17:26 +00005845 rc = SQLITE_IOERR_DELETE_NOENT;
5846 }else{
drhb4308162012-11-09 21:40:02 +00005847 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005848 }
drhb4308162012-11-09 21:40:02 +00005849 return rc;
drh5d4feff2010-07-14 01:45:22 +00005850 }
danielk1977d39fa702008-10-16 13:27:40 +00005851#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005852 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005853 int fd;
drh90315a22011-08-10 01:52:12 +00005854 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005855 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005856#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005857 if( fsync(fd)==-1 )
5858#else
5859 if( fsync(fd) )
5860#endif
5861 {
dane18d4952011-02-21 11:46:24 +00005862 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005863 }
drh0e9365c2011-03-02 02:08:13 +00005864 robust_close(0, fd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00005865 }else{
5866 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00005867 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005868 }
5869 }
danielk1977d138dd82008-10-15 16:02:48 +00005870#endif
danielk1977fee2d252007-08-18 10:59:19 +00005871 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005872}
5873
danielk197790949c22007-08-17 16:50:38 +00005874/*
mistachkin48864df2013-03-21 21:20:32 +00005875** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00005876** test performed depends on the value of flags:
5877**
5878** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5879** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5880** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5881**
5882** Otherwise return 0.
5883*/
danielk1977861f7452008-06-05 11:39:11 +00005884static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005885 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5886 const char *zPath, /* Path of the file to examine */
5887 int flags, /* What do we want to learn about the zPath file? */
5888 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005889){
danielk1977397d65f2008-11-19 11:35:39 +00005890 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005891 SimulateIOError( return SQLITE_IOERR_ACCESS; );
drhd260b5b2015-11-25 18:03:33 +00005892 assert( pResOut!=0 );
danielk1977b4b47412007-08-17 15:53:36 +00005893
drhd260b5b2015-11-25 18:03:33 +00005894 /* The spec says there are three possible values for flags. But only
5895 ** two of them are actually used */
5896 assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
5897
5898 if( flags==SQLITE_ACCESS_EXISTS ){
dan83acd422010-06-18 11:10:06 +00005899 struct stat buf;
drhd260b5b2015-11-25 18:03:33 +00005900 *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
5901 }else{
5902 *pResOut = osAccess(zPath, W_OK|R_OK)==0;
dan83acd422010-06-18 11:10:06 +00005903 }
danielk1977861f7452008-06-05 11:39:11 +00005904 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005905}
5906
danielk1977b4b47412007-08-17 15:53:36 +00005907
5908/*
5909** Turn a relative pathname into a full pathname. The relative path
5910** is stored as a nul-terminated string in the buffer pointed to by
5911** zPath.
5912**
5913** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5914** (in this case, MAX_PATHNAME bytes). The full-path is written to
5915** this buffer before returning.
5916*/
danielk1977adfb9b02007-09-17 07:02:56 +00005917static int unixFullPathname(
5918 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5919 const char *zPath, /* Possibly relative input path */
5920 int nOut, /* Size of output buffer in bytes */
5921 char *zOut /* Output buffer */
5922){
dan245fdc62015-10-31 17:58:33 +00005923 int nByte;
danielk1977843e65f2007-09-01 16:16:15 +00005924
5925 /* It's odd to simulate an io-error here, but really this is just
5926 ** using the io-error infrastructure to test that SQLite handles this
5927 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005928 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005929 */
5930 SimulateIOError( return SQLITE_ERROR );
5931
drh153c62c2007-08-24 03:51:33 +00005932 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005933 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005934
dan245fdc62015-10-31 17:58:33 +00005935 /* Attempt to resolve the path as if it were a symbolic link. If it is
5936 ** a symbolic link, the resolved path is stored in buffer zOut[]. Or, if
5937 ** the identified file is not a symbolic link or does not exist, then
5938 ** zPath is copied directly into zOut. Either way, nByte is left set to
5939 ** the size of the string copied into zOut[] in bytes. */
5940 nByte = osReadlink(zPath, zOut, nOut-1);
5941 if( nByte<0 ){
5942 if( errno!=EINVAL && errno!=ENOENT ){
5943 return unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zPath);
5944 }
drhd260b5b2015-11-25 18:03:33 +00005945 sqlite3_snprintf(nOut, zOut, "%s", zPath);
dan245fdc62015-10-31 17:58:33 +00005946 nByte = sqlite3Strlen30(zOut);
danielk1977b4b47412007-08-17 15:53:36 +00005947 }else{
dan245fdc62015-10-31 17:58:33 +00005948 zOut[nByte] = '\0';
5949 }
5950
5951 /* If buffer zOut[] now contains an absolute path there is nothing more
5952 ** to do. If it contains a relative path, do the following:
5953 **
5954 ** * move the relative path string so that it is at the end of th
5955 ** zOut[] buffer.
5956 ** * Call getcwd() to read the path of the current working directory
5957 ** into the start of the zOut[] buffer.
5958 ** * Append a '/' character to the cwd string and move the
5959 ** relative path back within the buffer so that it immediately
5960 ** follows the '/'.
5961 **
5962 ** This code is written so that if the combination of the CWD and relative
5963 ** path are larger than the allocated size of zOut[] the CWD is silently
5964 ** truncated to make it fit. This is Ok, as SQLite refuses to open any
5965 ** file for which this function returns a full path larger than (nOut-8)
5966 ** bytes in size. */
drh025d2f72015-11-30 22:22:23 +00005967 testcase( nByte==nOut-5 );
5968 testcase( nByte==nOut-4 );
5969 if( zOut[0]!='/' && nByte<nOut-4 ){
danielk1977b4b47412007-08-17 15:53:36 +00005970 int nCwd;
dan245fdc62015-10-31 17:58:33 +00005971 int nRem = nOut-nByte-1;
5972 memmove(&zOut[nRem], zOut, nByte+1);
5973 zOut[nRem-1] = '\0';
5974 if( osGetcwd(zOut, nRem-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005975 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005976 }
dan245fdc62015-10-31 17:58:33 +00005977 nCwd = sqlite3Strlen30(zOut);
5978 assert( nCwd<=nRem-1 );
5979 zOut[nCwd] = '/';
5980 memmove(&zOut[nCwd+1], &zOut[nRem], nByte+1);
danielk1977b4b47412007-08-17 15:53:36 +00005981 }
dan245fdc62015-10-31 17:58:33 +00005982
danielk1977b4b47412007-08-17 15:53:36 +00005983 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005984}
5985
drh0ccebe72005-06-07 22:22:50 +00005986
drh761df872006-12-21 01:29:22 +00005987#ifndef SQLITE_OMIT_LOAD_EXTENSION
5988/*
5989** Interfaces for opening a shared library, finding entry points
5990** within the shared library, and closing the shared library.
5991*/
5992#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005993static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5994 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005995 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5996}
danielk197795c8a542007-09-01 06:51:27 +00005997
5998/*
5999** SQLite calls this function immediately after a call to unixDlSym() or
6000** unixDlOpen() fails (returns a null pointer). If a more detailed error
6001** message is available, it is written to zBufOut. If no error message
6002** is available, zBufOut is left unmodified and SQLite uses a default
6003** error message.
6004*/
danielk1977397d65f2008-11-19 11:35:39 +00006005static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006006 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006007 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006008 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006009 zErr = dlerror();
6010 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006011 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006012 }
drh6c7d5c52008-11-21 20:32:33 +00006013 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006014}
drh1875f7a2008-12-08 18:19:17 +00006015static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6016 /*
6017 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6018 ** cast into a pointer to a function. And yet the library dlsym() routine
6019 ** returns a void* which is really a pointer to a function. So how do we
6020 ** use dlsym() with -pedantic-errors?
6021 **
6022 ** Variable x below is defined to be a pointer to a function taking
6023 ** parameters void* and const char* and returning a pointer to a function.
6024 ** We initialize x by assigning it a pointer to the dlsym() function.
6025 ** (That assignment requires a cast.) Then we call the function that
6026 ** x points to.
6027 **
6028 ** This work-around is unlikely to work correctly on any system where
6029 ** you really cannot cast a function pointer into void*. But then, on the
6030 ** other hand, dlsym() will not work on such a system either, so we have
6031 ** not really lost anything.
6032 */
6033 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006034 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006035 x = (void(*(*)(void*,const char*))(void))dlsym;
6036 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006037}
danielk1977397d65f2008-11-19 11:35:39 +00006038static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6039 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006040 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006041}
danielk1977b4b47412007-08-17 15:53:36 +00006042#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6043 #define unixDlOpen 0
6044 #define unixDlError 0
6045 #define unixDlSym 0
6046 #define unixDlClose 0
6047#endif
6048
6049/*
danielk197790949c22007-08-17 16:50:38 +00006050** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006051*/
danielk1977397d65f2008-11-19 11:35:39 +00006052static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6053 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006054 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006055
drhbbd42a62004-05-22 17:41:58 +00006056 /* We have to initialize zBuf to prevent valgrind from reporting
6057 ** errors. The reports issued by valgrind are incorrect - we would
6058 ** prefer that the randomness be increased by making use of the
6059 ** uninitialized space in zBuf - but valgrind errors tend to worry
6060 ** some users. Rather than argue, it seems easier just to initialize
6061 ** the whole array and silence valgrind, even if that means less randomness
6062 ** in the random seed.
6063 **
6064 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006065 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006066 ** tests repeatable.
6067 */
danielk1977b4b47412007-08-17 15:53:36 +00006068 memset(zBuf, 0, nBuf);
drh5ac93652015-03-21 20:59:43 +00006069 randomnessPid = osGetpid(0);
drh6a412b82015-04-30 12:31:49 +00006070#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
drhbbd42a62004-05-22 17:41:58 +00006071 {
drhb00d8622014-01-01 15:18:36 +00006072 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006073 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006074 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006075 time_t t;
6076 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006077 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006078 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6079 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6080 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006081 }else{
drhc18b4042012-02-10 03:10:27 +00006082 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006083 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006084 }
drhbbd42a62004-05-22 17:41:58 +00006085 }
6086#endif
drh72cbd072008-10-14 17:58:38 +00006087 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006088}
6089
danielk1977b4b47412007-08-17 15:53:36 +00006090
drhbbd42a62004-05-22 17:41:58 +00006091/*
6092** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006093** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006094** The return value is the number of microseconds of sleep actually
6095** requested from the underlying operating system, a number which
6096** might be greater than or equal to the argument, but not less
6097** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006098*/
danielk1977397d65f2008-11-19 11:35:39 +00006099static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006100#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006101 struct timespec sp;
6102
6103 sp.tv_sec = microseconds / 1000000;
6104 sp.tv_nsec = (microseconds % 1000000) * 1000;
6105 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006106 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006107 return microseconds;
6108#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006109 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006110 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006111 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006112#else
danielk1977b4b47412007-08-17 15:53:36 +00006113 int seconds = (microseconds+999999)/1000000;
6114 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006115 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006116 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006117#endif
drh88f474a2006-01-02 20:00:12 +00006118}
6119
6120/*
drh6b9d6dd2008-12-03 19:34:47 +00006121** The following variable, if set to a non-zero value, is interpreted as
6122** the number of seconds since 1970 and is used to set the result of
6123** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006124*/
6125#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006126int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006127#endif
6128
6129/*
drhb7e8ea22010-05-03 14:32:30 +00006130** Find the current time (in Universal Coordinated Time). Write into *piNow
6131** the current time and date as a Julian Day number times 86_400_000. In
6132** other words, write into *piNow the number of milliseconds since the Julian
6133** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6134** proleptic Gregorian calendar.
6135**
drh31702252011-10-12 23:13:43 +00006136** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6137** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006138*/
6139static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6140 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006141 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006142#if defined(NO_GETTOD)
6143 time_t t;
6144 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006145 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006146#elif OS_VXWORKS
6147 struct timespec sNow;
6148 clock_gettime(CLOCK_REALTIME, &sNow);
6149 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6150#else
6151 struct timeval sNow;
drh970942e2015-11-25 23:13:14 +00006152 (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
6153 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
drhb7e8ea22010-05-03 14:32:30 +00006154#endif
6155
6156#ifdef SQLITE_TEST
6157 if( sqlite3_current_time ){
6158 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6159 }
6160#endif
6161 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006162 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006163}
6164
drh5337dac2015-11-25 15:15:03 +00006165#if 0 /* Not used */
drhb7e8ea22010-05-03 14:32:30 +00006166/*
drhbbd42a62004-05-22 17:41:58 +00006167** Find the current time (in Universal Coordinated Time). Write the
6168** current time and date as a Julian Day number into *prNow and
6169** return 0. Return 1 if the time and date cannot be found.
6170*/
danielk1977397d65f2008-11-19 11:35:39 +00006171static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006172 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006173 int rc;
drhff828942010-06-26 21:34:06 +00006174 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006175 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006176 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006177 return rc;
drhbbd42a62004-05-22 17:41:58 +00006178}
drh5337dac2015-11-25 15:15:03 +00006179#else
6180# define unixCurrentTime 0
6181#endif
danielk1977b4b47412007-08-17 15:53:36 +00006182
drh5337dac2015-11-25 15:15:03 +00006183#if 0 /* Not used */
drh6b9d6dd2008-12-03 19:34:47 +00006184/*
6185** We added the xGetLastError() method with the intention of providing
6186** better low-level error messages when operating-system problems come up
6187** during SQLite operation. But so far, none of that has been implemented
6188** in the core. So this routine is never called. For now, it is merely
6189** a place-holder.
6190*/
danielk1977397d65f2008-11-19 11:35:39 +00006191static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6192 UNUSED_PARAMETER(NotUsed);
6193 UNUSED_PARAMETER(NotUsed2);
6194 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00006195 return 0;
6196}
drh5337dac2015-11-25 15:15:03 +00006197#else
6198# define unixGetLastError 0
6199#endif
danielk1977bcb97fe2008-06-06 15:49:29 +00006200
drhf2424c52010-04-26 00:04:55 +00006201
6202/*
drh734c9862008-11-28 15:37:20 +00006203************************ End of sqlite3_vfs methods ***************************
6204******************************************************************************/
6205
drh715ff302008-12-03 22:32:44 +00006206/******************************************************************************
6207************************** Begin Proxy Locking ********************************
6208**
6209** Proxy locking is a "uber-locking-method" in this sense: It uses the
6210** other locking methods on secondary lock files. Proxy locking is a
6211** meta-layer over top of the primitive locking implemented above. For
6212** this reason, the division that implements of proxy locking is deferred
6213** until late in the file (here) after all of the other I/O methods have
6214** been defined - so that the primitive locking methods are available
6215** as services to help with the implementation of proxy locking.
6216**
6217****
6218**
6219** The default locking schemes in SQLite use byte-range locks on the
6220** database file to coordinate safe, concurrent access by multiple readers
6221** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6222** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6223** as POSIX read & write locks over fixed set of locations (via fsctl),
6224** on AFP and SMB only exclusive byte-range locks are available via fsctl
6225** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6226** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6227** address in the shared range is taken for a SHARED lock, the entire
6228** shared range is taken for an EXCLUSIVE lock):
6229**
drhf2f105d2012-08-20 15:53:54 +00006230** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006231** RESERVED_BYTE 0x40000001
6232** SHARED_RANGE 0x40000002 -> 0x40000200
6233**
6234** This works well on the local file system, but shows a nearly 100x
6235** slowdown in read performance on AFP because the AFP client disables
6236** the read cache when byte-range locks are present. Enabling the read
6237** cache exposes a cache coherency problem that is present on all OS X
6238** supported network file systems. NFS and AFP both observe the
6239** close-to-open semantics for ensuring cache coherency
6240** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6241** address the requirements for concurrent database access by multiple
6242** readers and writers
6243** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6244**
6245** To address the performance and cache coherency issues, proxy file locking
6246** changes the way database access is controlled by limiting access to a
6247** single host at a time and moving file locks off of the database file
6248** and onto a proxy file on the local file system.
6249**
6250**
6251** Using proxy locks
6252** -----------------
6253**
6254** C APIs
6255**
drh4bf66fd2015-02-19 02:43:02 +00006256** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
drh715ff302008-12-03 22:32:44 +00006257** <proxy_path> | ":auto:");
drh4bf66fd2015-02-19 02:43:02 +00006258** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6259** &<proxy_path>);
drh715ff302008-12-03 22:32:44 +00006260**
6261**
6262** SQL pragmas
6263**
6264** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6265** PRAGMA [database.]lock_proxy_file
6266**
6267** Specifying ":auto:" means that if there is a conch file with a matching
6268** host ID in it, the proxy path in the conch file will be used, otherwise
6269** a proxy path based on the user's temp dir
6270** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6271** actual proxy file name is generated from the name and path of the
6272** database file. For example:
6273**
6274** For database path "/Users/me/foo.db"
6275** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6276**
6277** Once a lock proxy is configured for a database connection, it can not
6278** be removed, however it may be switched to a different proxy path via
6279** the above APIs (assuming the conch file is not being held by another
6280** connection or process).
6281**
6282**
6283** How proxy locking works
6284** -----------------------
6285**
6286** Proxy file locking relies primarily on two new supporting files:
6287**
6288** * conch file to limit access to the database file to a single host
6289** at a time
6290**
6291** * proxy file to act as a proxy for the advisory locks normally
6292** taken on the database
6293**
6294** The conch file - to use a proxy file, sqlite must first "hold the conch"
6295** by taking an sqlite-style shared lock on the conch file, reading the
6296** contents and comparing the host's unique host ID (see below) and lock
6297** proxy path against the values stored in the conch. The conch file is
6298** stored in the same directory as the database file and the file name
6299** is patterned after the database file name as ".<databasename>-conch".
peter.d.reid60ec9142014-09-06 16:39:46 +00006300** If the conch file does not exist, or its contents do not match the
drh715ff302008-12-03 22:32:44 +00006301** host ID and/or proxy path, then the lock is escalated to an exclusive
6302** lock and the conch file contents is updated with the host ID and proxy
6303** path and the lock is downgraded to a shared lock again. If the conch
6304** is held by another process (with a shared lock), the exclusive lock
6305** will fail and SQLITE_BUSY is returned.
6306**
6307** The proxy file - a single-byte file used for all advisory file locks
6308** normally taken on the database file. This allows for safe sharing
6309** of the database file for multiple readers and writers on the same
6310** host (the conch ensures that they all use the same local lock file).
6311**
drh715ff302008-12-03 22:32:44 +00006312** Requesting the lock proxy does not immediately take the conch, it is
6313** only taken when the first request to lock database file is made.
6314** This matches the semantics of the traditional locking behavior, where
6315** opening a connection to a database file does not take a lock on it.
6316** The shared lock and an open file descriptor are maintained until
6317** the connection to the database is closed.
6318**
6319** The proxy file and the lock file are never deleted so they only need
6320** to be created the first time they are used.
6321**
6322** Configuration options
6323** ---------------------
6324**
6325** SQLITE_PREFER_PROXY_LOCKING
6326**
6327** Database files accessed on non-local file systems are
6328** automatically configured for proxy locking, lock files are
6329** named automatically using the same logic as
6330** PRAGMA lock_proxy_file=":auto:"
6331**
6332** SQLITE_PROXY_DEBUG
6333**
6334** Enables the logging of error messages during host id file
6335** retrieval and creation
6336**
drh715ff302008-12-03 22:32:44 +00006337** LOCKPROXYDIR
6338**
6339** Overrides the default directory used for lock proxy files that
6340** are named automatically via the ":auto:" setting
6341**
6342** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6343**
6344** Permissions to use when creating a directory for storing the
6345** lock proxy files, only used when LOCKPROXYDIR is not set.
6346**
6347**
6348** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6349** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6350** force proxy locking to be used for every database file opened, and 0
6351** will force automatic proxy locking to be disabled for all database
drh4bf66fd2015-02-19 02:43:02 +00006352** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
drh715ff302008-12-03 22:32:44 +00006353** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6354*/
6355
6356/*
6357** Proxy locking is only available on MacOSX
6358*/
drhd2cb50b2009-01-09 21:41:17 +00006359#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006360
drh715ff302008-12-03 22:32:44 +00006361/*
6362** The proxyLockingContext has the path and file structures for the remote
6363** and local proxy files in it
6364*/
6365typedef struct proxyLockingContext proxyLockingContext;
6366struct proxyLockingContext {
6367 unixFile *conchFile; /* Open conch file */
6368 char *conchFilePath; /* Name of the conch file */
6369 unixFile *lockProxy; /* Open proxy lock file */
6370 char *lockProxyPath; /* Name of the proxy lock file */
6371 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006372 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh4bf66fd2015-02-19 02:43:02 +00006373 int nFails; /* Number of conch taking failures */
drh715ff302008-12-03 22:32:44 +00006374 void *oldLockingContext; /* Original lockingcontext to restore on close */
6375 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6376};
6377
drh7ed97b92010-01-20 13:07:21 +00006378/*
6379** The proxy lock file path for the database at dbPath is written into lPath,
6380** which must point to valid, writable memory large enough for a maxLen length
6381** file path.
drh715ff302008-12-03 22:32:44 +00006382*/
drh715ff302008-12-03 22:32:44 +00006383static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6384 int len;
6385 int dbLen;
6386 int i;
6387
6388#ifdef LOCKPROXYDIR
6389 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6390#else
6391# ifdef _CS_DARWIN_USER_TEMP_DIR
6392 {
drh7ed97b92010-01-20 13:07:21 +00006393 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006394 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006395 lPath, errno, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006396 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006397 }
drh7ed97b92010-01-20 13:07:21 +00006398 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006399 }
6400# else
6401 len = strlcpy(lPath, "/tmp/", maxLen);
6402# endif
6403#endif
6404
6405 if( lPath[len-1]!='/' ){
6406 len = strlcat(lPath, "/", maxLen);
6407 }
6408
6409 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006410 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006411 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006412 char c = dbPath[i];
6413 lPath[i+len] = (c=='/')?'_':c;
6414 }
6415 lPath[i+len]='\0';
6416 strlcat(lPath, ":auto:", maxLen);
drh5ac93652015-03-21 20:59:43 +00006417 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006418 return SQLITE_OK;
6419}
6420
drh7ed97b92010-01-20 13:07:21 +00006421/*
6422 ** Creates the lock file and any missing directories in lockPath
6423 */
6424static int proxyCreateLockPath(const char *lockPath){
6425 int i, len;
6426 char buf[MAXPATHLEN];
6427 int start = 0;
6428
6429 assert(lockPath!=NULL);
6430 /* try to create all the intermediate directories */
6431 len = (int)strlen(lockPath);
6432 buf[0] = lockPath[0];
6433 for( i=1; i<len; i++ ){
6434 if( lockPath[i] == '/' && (i - start > 0) ){
6435 /* only mkdir if leaf dir != "." or "/" or ".." */
6436 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6437 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6438 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006439 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006440 int err=errno;
6441 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006442 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006443 "'%s' proxy lock path=%s pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006444 buf, strerror(err), lockPath, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006445 return err;
6446 }
6447 }
6448 }
6449 start=i+1;
6450 }
6451 buf[i] = lockPath[i];
6452 }
drh62aaa6c2015-11-21 17:27:42 +00006453 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006454 return 0;
6455}
6456
drh715ff302008-12-03 22:32:44 +00006457/*
6458** Create a new VFS file descriptor (stored in memory obtained from
6459** sqlite3_malloc) and open the file named "path" in the file descriptor.
6460**
6461** The caller is responsible not only for closing the file descriptor
6462** but also for freeing the memory associated with the file descriptor.
6463*/
drh7ed97b92010-01-20 13:07:21 +00006464static int proxyCreateUnixFile(
6465 const char *path, /* path for the new unixFile */
6466 unixFile **ppFile, /* unixFile created and returned by ref */
6467 int islockfile /* if non zero missing dirs will be created */
6468) {
6469 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006470 unixFile *pNew;
6471 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006472 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006473 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006474 int terrno = 0;
6475 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006476
drh7ed97b92010-01-20 13:07:21 +00006477 /* 1. first try to open/create the file
6478 ** 2. if that fails, and this is a lock file (not-conch), try creating
6479 ** the parent directories and then try again.
6480 ** 3. if that fails, try to open the file read-only
6481 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6482 */
6483 pUnused = findReusableFd(path, openFlags);
6484 if( pUnused ){
6485 fd = pUnused->fd;
6486 }else{
drhf3cdcdc2015-04-29 16:50:28 +00006487 pUnused = sqlite3_malloc64(sizeof(*pUnused));
drh7ed97b92010-01-20 13:07:21 +00006488 if( !pUnused ){
6489 return SQLITE_NOMEM;
6490 }
6491 }
6492 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006493 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006494 terrno = errno;
6495 if( fd<0 && errno==ENOENT && islockfile ){
6496 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006497 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006498 }
6499 }
6500 }
6501 if( fd<0 ){
6502 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006503 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006504 terrno = errno;
6505 }
6506 if( fd<0 ){
6507 if( islockfile ){
6508 return SQLITE_BUSY;
6509 }
6510 switch (terrno) {
6511 case EACCES:
6512 return SQLITE_PERM;
6513 case EIO:
6514 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6515 default:
drh9978c972010-02-23 17:36:32 +00006516 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006517 }
6518 }
6519
drhf3cdcdc2015-04-29 16:50:28 +00006520 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
drh7ed97b92010-01-20 13:07:21 +00006521 if( pNew==NULL ){
6522 rc = SQLITE_NOMEM;
6523 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006524 }
6525 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006526 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006527 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006528 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006529 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006530 pUnused->fd = fd;
6531 pUnused->flags = openFlags;
6532 pNew->pUnused = pUnused;
6533
drhc02a43a2012-01-10 23:18:38 +00006534 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006535 if( rc==SQLITE_OK ){
6536 *ppFile = pNew;
6537 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006538 }
drh7ed97b92010-01-20 13:07:21 +00006539end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006540 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006541 sqlite3_free(pNew);
6542 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006543 return rc;
6544}
6545
drh7ed97b92010-01-20 13:07:21 +00006546#ifdef SQLITE_TEST
6547/* simulate multiple hosts by creating unique hostid file paths */
6548int sqlite3_hostid_num = 0;
6549#endif
6550
6551#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6552
drh6bca6512015-04-13 23:05:28 +00006553#ifdef HAVE_GETHOSTUUID
drh0ab216a2010-07-02 17:10:40 +00006554/* Not always defined in the headers as it ought to be */
6555extern int gethostuuid(uuid_t id, const struct timespec *wait);
drh6bca6512015-04-13 23:05:28 +00006556#endif
drh0ab216a2010-07-02 17:10:40 +00006557
drh7ed97b92010-01-20 13:07:21 +00006558/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6559** bytes of writable memory.
6560*/
6561static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006562 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6563 memset(pHostID, 0, PROXY_HOSTIDLEN);
drh6bca6512015-04-13 23:05:28 +00006564#ifdef HAVE_GETHOSTUUID
drh29ecd8a2010-12-21 00:16:40 +00006565 {
drh4bf66fd2015-02-19 02:43:02 +00006566 struct timespec timeout = {1, 0}; /* 1 sec timeout */
drh29ecd8a2010-12-21 00:16:40 +00006567 if( gethostuuid(pHostID, &timeout) ){
6568 int err = errno;
6569 if( pError ){
6570 *pError = err;
6571 }
6572 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006573 }
drh7ed97b92010-01-20 13:07:21 +00006574 }
drh3d4435b2011-08-26 20:55:50 +00006575#else
6576 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006577#endif
drh7ed97b92010-01-20 13:07:21 +00006578#ifdef SQLITE_TEST
6579 /* simulate multiple hosts by creating unique hostid file paths */
6580 if( sqlite3_hostid_num != 0){
6581 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6582 }
6583#endif
6584
6585 return SQLITE_OK;
6586}
6587
6588/* The conch file contains the header, host id and lock file path
6589 */
6590#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6591#define PROXY_HEADERLEN 1 /* conch file header length */
6592#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6593#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6594
6595/*
6596** Takes an open conch file, copies the contents to a new path and then moves
6597** it back. The newly created file's file descriptor is assigned to the
6598** conch file structure and finally the original conch file descriptor is
6599** closed. Returns zero if successful.
6600*/
6601static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6602 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6603 unixFile *conchFile = pCtx->conchFile;
6604 char tPath[MAXPATHLEN];
6605 char buf[PROXY_MAXCONCHLEN];
6606 char *cPath = pCtx->conchFilePath;
6607 size_t readLen = 0;
6608 size_t pathLen = 0;
6609 char errmsg[64] = "";
6610 int fd = -1;
6611 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006612 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006613
6614 /* create a new path by replace the trailing '-conch' with '-break' */
6615 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6616 if( pathLen>MAXPATHLEN || pathLen<6 ||
6617 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006618 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006619 goto end_breaklock;
6620 }
6621 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006622 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006623 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006624 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006625 goto end_breaklock;
6626 }
6627 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006628 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006629 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006630 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006631 goto end_breaklock;
6632 }
drhe562be52011-03-02 18:01:10 +00006633 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006634 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006635 goto end_breaklock;
6636 }
6637 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006638 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006639 goto end_breaklock;
6640 }
6641 rc = 0;
6642 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006643 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006644 conchFile->h = fd;
6645 conchFile->openFlags = O_RDWR | O_CREAT;
6646
6647end_breaklock:
6648 if( rc ){
6649 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006650 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006651 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006652 }
6653 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6654 }
6655 return rc;
6656}
6657
6658/* Take the requested lock on the conch file and break a stale lock if the
6659** host id matches.
6660*/
6661static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6662 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6663 unixFile *conchFile = pCtx->conchFile;
6664 int rc = SQLITE_OK;
6665 int nTries = 0;
6666 struct timespec conchModTime;
6667
drh3d4435b2011-08-26 20:55:50 +00006668 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006669 do {
6670 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6671 nTries ++;
6672 if( rc==SQLITE_BUSY ){
6673 /* If the lock failed (busy):
6674 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6675 * 2nd try: fail if the mod time changed or host id is different, wait
6676 * 10 sec and try again
6677 * 3rd try: break the lock unless the mod time has changed.
6678 */
6679 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006680 if( osFstat(conchFile->h, &buf) ){
drh4bf66fd2015-02-19 02:43:02 +00006681 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006682 return SQLITE_IOERR_LOCK;
6683 }
6684
6685 if( nTries==1 ){
6686 conchModTime = buf.st_mtimespec;
6687 usleep(500000); /* wait 0.5 sec and try the lock again*/
6688 continue;
6689 }
6690
6691 assert( nTries>1 );
6692 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6693 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6694 return SQLITE_BUSY;
6695 }
6696
6697 if( nTries==2 ){
6698 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006699 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006700 if( len<0 ){
drh4bf66fd2015-02-19 02:43:02 +00006701 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006702 return SQLITE_IOERR_LOCK;
6703 }
6704 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6705 /* don't break the lock if the host id doesn't match */
6706 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6707 return SQLITE_BUSY;
6708 }
6709 }else{
6710 /* don't break the lock on short read or a version mismatch */
6711 return SQLITE_BUSY;
6712 }
6713 usleep(10000000); /* wait 10 sec and try the lock again */
6714 continue;
6715 }
6716
6717 assert( nTries==3 );
6718 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6719 rc = SQLITE_OK;
6720 if( lockType==EXCLUSIVE_LOCK ){
drhe6d41732015-02-21 00:49:00 +00006721 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
drh7ed97b92010-01-20 13:07:21 +00006722 }
6723 if( !rc ){
6724 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6725 }
6726 }
6727 }
6728 } while( rc==SQLITE_BUSY && nTries<3 );
6729
6730 return rc;
6731}
6732
6733/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006734** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6735** lockPath means that the lockPath in the conch file will be used if the
6736** host IDs match, or a new lock path will be generated automatically
6737** and written to the conch file.
6738*/
6739static int proxyTakeConch(unixFile *pFile){
6740 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6741
drh7ed97b92010-01-20 13:07:21 +00006742 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006743 return SQLITE_OK;
6744 }else{
6745 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006746 uuid_t myHostID;
6747 int pError = 0;
6748 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006749 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006750 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006751 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006752 int createConch = 0;
6753 int hostIdMatch = 0;
6754 int readLen = 0;
6755 int tryOldLockPath = 0;
6756 int forceNewLockPath = 0;
6757
drh308c2a52010-05-14 11:30:18 +00006758 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
drh91eb93c2015-03-03 19:56:20 +00006759 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00006760 osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006761
drh7ed97b92010-01-20 13:07:21 +00006762 rc = proxyGetHostID(myHostID, &pError);
6763 if( (rc&0xff)==SQLITE_IOERR ){
drh4bf66fd2015-02-19 02:43:02 +00006764 storeLastErrno(pFile, pError);
drh7ed97b92010-01-20 13:07:21 +00006765 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006766 }
drh7ed97b92010-01-20 13:07:21 +00006767 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006768 if( rc!=SQLITE_OK ){
6769 goto end_takeconch;
6770 }
drh7ed97b92010-01-20 13:07:21 +00006771 /* read the existing conch file */
6772 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6773 if( readLen<0 ){
6774 /* I/O error: lastErrno set by seekAndRead */
drh4bf66fd2015-02-19 02:43:02 +00006775 storeLastErrno(pFile, conchFile->lastErrno);
drh7ed97b92010-01-20 13:07:21 +00006776 rc = SQLITE_IOERR_READ;
6777 goto end_takeconch;
6778 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6779 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6780 /* a short read or version format mismatch means we need to create a new
6781 ** conch file.
6782 */
6783 createConch = 1;
6784 }
6785 /* if the host id matches and the lock path already exists in the conch
6786 ** we'll try to use the path there, if we can't open that path, we'll
6787 ** retry with a new auto-generated path
6788 */
6789 do { /* in case we need to try again for an :auto: named lock file */
6790
6791 if( !createConch && !forceNewLockPath ){
6792 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6793 PROXY_HOSTIDLEN);
6794 /* if the conch has data compare the contents */
6795 if( !pCtx->lockProxyPath ){
6796 /* for auto-named local lock file, just check the host ID and we'll
6797 ** use the local lock file path that's already in there
6798 */
6799 if( hostIdMatch ){
6800 size_t pathLen = (readLen - PROXY_PATHINDEX);
6801
6802 if( pathLen>=MAXPATHLEN ){
6803 pathLen=MAXPATHLEN-1;
6804 }
6805 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6806 lockPath[pathLen] = 0;
6807 tempLockPath = lockPath;
6808 tryOldLockPath = 1;
6809 /* create a copy of the lock path if the conch is taken */
6810 goto end_takeconch;
6811 }
6812 }else if( hostIdMatch
6813 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6814 readLen-PROXY_PATHINDEX)
6815 ){
6816 /* conch host and lock path match */
6817 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006818 }
drh7ed97b92010-01-20 13:07:21 +00006819 }
6820
6821 /* if the conch isn't writable and doesn't match, we can't take it */
6822 if( (conchFile->openFlags&O_RDWR) == 0 ){
6823 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006824 goto end_takeconch;
6825 }
drh7ed97b92010-01-20 13:07:21 +00006826
6827 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006828 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006829 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6830 tempLockPath = lockPath;
6831 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006832 }
drh7ed97b92010-01-20 13:07:21 +00006833
6834 /* update conch with host and path (this will fail if other process
6835 ** has a shared lock already), if the host id matches, use the big
6836 ** stick.
drh715ff302008-12-03 22:32:44 +00006837 */
drh7ed97b92010-01-20 13:07:21 +00006838 futimes(conchFile->h, NULL);
6839 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006840 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006841 /* We are trying for an exclusive lock but another thread in this
6842 ** same process is still holding a shared lock. */
6843 rc = SQLITE_BUSY;
6844 } else {
6845 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006846 }
drh715ff302008-12-03 22:32:44 +00006847 }else{
drh4bf66fd2015-02-19 02:43:02 +00006848 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006849 }
drh7ed97b92010-01-20 13:07:21 +00006850 if( rc==SQLITE_OK ){
6851 char writeBuffer[PROXY_MAXCONCHLEN];
6852 int writeSize = 0;
6853
6854 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6855 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6856 if( pCtx->lockProxyPath!=NULL ){
drh4bf66fd2015-02-19 02:43:02 +00006857 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
6858 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00006859 }else{
6860 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6861 }
6862 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006863 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006864 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6865 fsync(conchFile->h);
6866 /* If we created a new conch file (not just updated the contents of a
6867 ** valid conch file), try to match the permissions of the database
6868 */
6869 if( rc==SQLITE_OK && createConch ){
6870 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006871 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006872 if( err==0 ){
6873 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6874 S_IROTH|S_IWOTH);
6875 /* try to match the database file R/W permissions, ignore failure */
6876#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006877 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006878#else
drhff812312011-02-23 13:33:46 +00006879 do{
drhe562be52011-03-02 18:01:10 +00006880 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006881 }while( rc==(-1) && errno==EINTR );
6882 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006883 int code = errno;
6884 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6885 cmode, code, strerror(code));
6886 } else {
6887 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6888 }
6889 }else{
6890 int code = errno;
6891 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6892 err, code, strerror(code));
6893#endif
6894 }
drh715ff302008-12-03 22:32:44 +00006895 }
6896 }
drh7ed97b92010-01-20 13:07:21 +00006897 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6898
6899 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006900 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006901 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006902 int fd;
drh7ed97b92010-01-20 13:07:21 +00006903 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006904 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006905 }
6906 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006907 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006908 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006909 if( fd>=0 ){
6910 pFile->h = fd;
6911 }else{
drh9978c972010-02-23 17:36:32 +00006912 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006913 during locking */
6914 }
6915 }
6916 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6917 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6918 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6919 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6920 /* we couldn't create the proxy lock file with the old lock file path
6921 ** so try again via auto-naming
6922 */
6923 forceNewLockPath = 1;
6924 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006925 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006926 }
6927 }
6928 if( rc==SQLITE_OK ){
6929 /* Need to make a copy of path if we extracted the value
6930 ** from the conch file or the path was allocated on the stack
6931 */
6932 if( tempLockPath ){
6933 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6934 if( !pCtx->lockProxyPath ){
6935 rc = SQLITE_NOMEM;
6936 }
6937 }
6938 }
6939 if( rc==SQLITE_OK ){
6940 pCtx->conchHeld = 1;
6941
6942 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6943 afpLockingContext *afpCtx;
6944 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6945 afpCtx->dbPath = pCtx->lockProxyPath;
6946 }
6947 } else {
6948 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6949 }
drh308c2a52010-05-14 11:30:18 +00006950 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6951 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006952 return rc;
drh308c2a52010-05-14 11:30:18 +00006953 } while (1); /* in case we need to retry the :auto: lock file -
6954 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006955 }
6956}
6957
6958/*
6959** If pFile holds a lock on a conch file, then release that lock.
6960*/
6961static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006962 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006963 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6964 unixFile *conchFile; /* Name of the conch file */
6965
6966 pCtx = (proxyLockingContext *)pFile->lockingContext;
6967 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006968 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006969 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00006970 osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006971 if( pCtx->conchHeld>0 ){
6972 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6973 }
drh715ff302008-12-03 22:32:44 +00006974 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006975 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6976 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006977 return rc;
6978}
6979
6980/*
6981** Given the name of a database file, compute the name of its conch file.
drhf3cdcdc2015-04-29 16:50:28 +00006982** Store the conch filename in memory obtained from sqlite3_malloc64().
drh715ff302008-12-03 22:32:44 +00006983** Make *pConchPath point to the new name. Return SQLITE_OK on success
6984** or SQLITE_NOMEM if unable to obtain memory.
6985**
6986** The caller is responsible for ensuring that the allocated memory
6987** space is eventually freed.
6988**
6989** *pConchPath is set to NULL if a memory allocation error occurs.
6990*/
6991static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6992 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006993 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006994 char *conchPath; /* buffer in which to construct conch name */
6995
6996 /* Allocate space for the conch filename and initialize the name to
6997 ** the name of the original database file. */
drhf3cdcdc2015-04-29 16:50:28 +00006998 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
drh715ff302008-12-03 22:32:44 +00006999 if( conchPath==0 ){
7000 return SQLITE_NOMEM;
7001 }
7002 memcpy(conchPath, dbPath, len+1);
7003
7004 /* now insert a "." before the last / character */
7005 for( i=(len-1); i>=0; i-- ){
7006 if( conchPath[i]=='/' ){
7007 i++;
7008 break;
7009 }
7010 }
7011 conchPath[i]='.';
7012 while ( i<len ){
7013 conchPath[i+1]=dbPath[i];
7014 i++;
7015 }
7016
7017 /* append the "-conch" suffix to the file */
7018 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007019 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007020
7021 return SQLITE_OK;
7022}
7023
7024
7025/* Takes a fully configured proxy locking-style unix file and switches
7026** the local lock file path
7027*/
7028static int switchLockProxyPath(unixFile *pFile, const char *path) {
7029 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7030 char *oldPath = pCtx->lockProxyPath;
7031 int rc = SQLITE_OK;
7032
drh308c2a52010-05-14 11:30:18 +00007033 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007034 return SQLITE_BUSY;
7035 }
7036
7037 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7038 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7039 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7040 return SQLITE_OK;
7041 }else{
7042 unixFile *lockProxy = pCtx->lockProxy;
7043 pCtx->lockProxy=NULL;
7044 pCtx->conchHeld = 0;
7045 if( lockProxy!=NULL ){
7046 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7047 if( rc ) return rc;
7048 sqlite3_free(lockProxy);
7049 }
7050 sqlite3_free(oldPath);
7051 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7052 }
7053
7054 return rc;
7055}
7056
7057/*
7058** pFile is a file that has been opened by a prior xOpen call. dbPath
7059** is a string buffer at least MAXPATHLEN+1 characters in size.
7060**
7061** This routine find the filename associated with pFile and writes it
7062** int dbPath.
7063*/
7064static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007065#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007066 if( pFile->pMethod == &afpIoMethods ){
7067 /* afp style keeps a reference to the db path in the filePath field
7068 ** of the struct */
drhea678832008-12-10 19:26:22 +00007069 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh4bf66fd2015-02-19 02:43:02 +00007070 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7071 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007072 } else
drh715ff302008-12-03 22:32:44 +00007073#endif
7074 if( pFile->pMethod == &dotlockIoMethods ){
7075 /* dot lock style uses the locking context to store the dot lock
7076 ** file path */
7077 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7078 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7079 }else{
7080 /* all other styles use the locking context to store the db file path */
7081 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007082 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007083 }
7084 return SQLITE_OK;
7085}
7086
7087/*
7088** Takes an already filled in unix file and alters it so all file locking
7089** will be performed on the local proxy lock file. The following fields
7090** are preserved in the locking context so that they can be restored and
7091** the unix structure properly cleaned up at close time:
7092** ->lockingContext
7093** ->pMethod
7094*/
7095static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7096 proxyLockingContext *pCtx;
7097 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7098 char *lockPath=NULL;
7099 int rc = SQLITE_OK;
7100
drh308c2a52010-05-14 11:30:18 +00007101 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007102 return SQLITE_BUSY;
7103 }
7104 proxyGetDbPathForUnixFile(pFile, dbPath);
7105 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7106 lockPath=NULL;
7107 }else{
7108 lockPath=(char *)path;
7109 }
7110
drh308c2a52010-05-14 11:30:18 +00007111 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
drh5ac93652015-03-21 20:59:43 +00007112 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007113
drhf3cdcdc2015-04-29 16:50:28 +00007114 pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh715ff302008-12-03 22:32:44 +00007115 if( pCtx==0 ){
7116 return SQLITE_NOMEM;
7117 }
7118 memset(pCtx, 0, sizeof(*pCtx));
7119
7120 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7121 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007122 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7123 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7124 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7125 ** (c) the file system is read-only, then enable no-locking access.
7126 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7127 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7128 */
7129 struct statfs fsInfo;
7130 struct stat conchInfo;
7131 int goLockless = 0;
7132
drh99ab3b12011-03-02 15:09:07 +00007133 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007134 int err = errno;
7135 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7136 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7137 }
7138 }
7139 if( goLockless ){
7140 pCtx->conchHeld = -1; /* read only FS/ lockless */
7141 rc = SQLITE_OK;
7142 }
7143 }
drh715ff302008-12-03 22:32:44 +00007144 }
7145 if( rc==SQLITE_OK && lockPath ){
7146 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7147 }
7148
7149 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007150 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7151 if( pCtx->dbPath==NULL ){
7152 rc = SQLITE_NOMEM;
7153 }
7154 }
7155 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007156 /* all memory is allocated, proxys are created and assigned,
7157 ** switch the locking context and pMethod then return.
7158 */
drh715ff302008-12-03 22:32:44 +00007159 pCtx->oldLockingContext = pFile->lockingContext;
7160 pFile->lockingContext = pCtx;
7161 pCtx->pOldMethod = pFile->pMethod;
7162 pFile->pMethod = &proxyIoMethods;
7163 }else{
7164 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007165 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007166 sqlite3_free(pCtx->conchFile);
7167 }
drhd56b1212010-08-11 06:14:15 +00007168 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007169 sqlite3_free(pCtx->conchFilePath);
7170 sqlite3_free(pCtx);
7171 }
drh308c2a52010-05-14 11:30:18 +00007172 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7173 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007174 return rc;
7175}
7176
7177
7178/*
7179** This routine handles sqlite3_file_control() calls that are specific
7180** to proxy locking.
7181*/
7182static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7183 switch( op ){
drh4bf66fd2015-02-19 02:43:02 +00007184 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007185 unixFile *pFile = (unixFile*)id;
7186 if( pFile->pMethod == &proxyIoMethods ){
7187 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7188 proxyTakeConch(pFile);
7189 if( pCtx->lockProxyPath ){
7190 *(const char **)pArg = pCtx->lockProxyPath;
7191 }else{
7192 *(const char **)pArg = ":auto: (not held)";
7193 }
7194 } else {
7195 *(const char **)pArg = NULL;
7196 }
7197 return SQLITE_OK;
7198 }
drh4bf66fd2015-02-19 02:43:02 +00007199 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007200 unixFile *pFile = (unixFile*)id;
7201 int rc = SQLITE_OK;
7202 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7203 if( pArg==NULL || (const char *)pArg==0 ){
7204 if( isProxyStyle ){
drh4bf66fd2015-02-19 02:43:02 +00007205 /* turn off proxy locking - not supported. If support is added for
7206 ** switching proxy locking mode off then it will need to fail if
7207 ** the journal mode is WAL mode.
7208 */
drh715ff302008-12-03 22:32:44 +00007209 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7210 }else{
7211 /* turn off proxy locking - already off - NOOP */
7212 rc = SQLITE_OK;
7213 }
7214 }else{
7215 const char *proxyPath = (const char *)pArg;
7216 if( isProxyStyle ){
7217 proxyLockingContext *pCtx =
7218 (proxyLockingContext*)pFile->lockingContext;
7219 if( !strcmp(pArg, ":auto:")
7220 || (pCtx->lockProxyPath &&
7221 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7222 ){
7223 rc = SQLITE_OK;
7224 }else{
7225 rc = switchLockProxyPath(pFile, proxyPath);
7226 }
7227 }else{
7228 /* turn on proxy file locking */
7229 rc = proxyTransformUnixFile(pFile, proxyPath);
7230 }
7231 }
7232 return rc;
7233 }
7234 default: {
7235 assert( 0 ); /* The call assures that only valid opcodes are sent */
7236 }
7237 }
7238 /*NOTREACHED*/
7239 return SQLITE_ERROR;
7240}
7241
7242/*
7243** Within this division (the proxying locking implementation) the procedures
7244** above this point are all utilities. The lock-related methods of the
7245** proxy-locking sqlite3_io_method object follow.
7246*/
7247
7248
7249/*
7250** This routine checks if there is a RESERVED lock held on the specified
7251** file by this or any other process. If such a lock is held, set *pResOut
7252** to a non-zero value otherwise *pResOut is set to zero. The return value
7253** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7254*/
7255static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7256 unixFile *pFile = (unixFile*)id;
7257 int rc = proxyTakeConch(pFile);
7258 if( rc==SQLITE_OK ){
7259 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007260 if( pCtx->conchHeld>0 ){
7261 unixFile *proxy = pCtx->lockProxy;
7262 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7263 }else{ /* conchHeld < 0 is lockless */
7264 pResOut=0;
7265 }
drh715ff302008-12-03 22:32:44 +00007266 }
7267 return rc;
7268}
7269
7270/*
drh308c2a52010-05-14 11:30:18 +00007271** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007272** of the following:
7273**
7274** (1) SHARED_LOCK
7275** (2) RESERVED_LOCK
7276** (3) PENDING_LOCK
7277** (4) EXCLUSIVE_LOCK
7278**
7279** Sometimes when requesting one lock state, additional lock states
7280** are inserted in between. The locking might fail on one of the later
7281** transitions leaving the lock state different from what it started but
7282** still short of its goal. The following chart shows the allowed
7283** transitions and the inserted intermediate states:
7284**
7285** UNLOCKED -> SHARED
7286** SHARED -> RESERVED
7287** SHARED -> (PENDING) -> EXCLUSIVE
7288** RESERVED -> (PENDING) -> EXCLUSIVE
7289** PENDING -> EXCLUSIVE
7290**
7291** This routine will only increase a lock. Use the sqlite3OsUnlock()
7292** routine to lower a locking level.
7293*/
drh308c2a52010-05-14 11:30:18 +00007294static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007295 unixFile *pFile = (unixFile*)id;
7296 int rc = proxyTakeConch(pFile);
7297 if( rc==SQLITE_OK ){
7298 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007299 if( pCtx->conchHeld>0 ){
7300 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007301 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7302 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007303 }else{
7304 /* conchHeld < 0 is lockless */
7305 }
drh715ff302008-12-03 22:32:44 +00007306 }
7307 return rc;
7308}
7309
7310
7311/*
drh308c2a52010-05-14 11:30:18 +00007312** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007313** must be either NO_LOCK or SHARED_LOCK.
7314**
7315** If the locking level of the file descriptor is already at or below
7316** the requested locking level, this routine is a no-op.
7317*/
drh308c2a52010-05-14 11:30:18 +00007318static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007319 unixFile *pFile = (unixFile*)id;
7320 int rc = proxyTakeConch(pFile);
7321 if( rc==SQLITE_OK ){
7322 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007323 if( pCtx->conchHeld>0 ){
7324 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007325 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7326 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007327 }else{
7328 /* conchHeld < 0 is lockless */
7329 }
drh715ff302008-12-03 22:32:44 +00007330 }
7331 return rc;
7332}
7333
7334/*
7335** Close a file that uses proxy locks.
7336*/
7337static int proxyClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00007338 if( ALWAYS(id) ){
drh715ff302008-12-03 22:32:44 +00007339 unixFile *pFile = (unixFile*)id;
7340 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7341 unixFile *lockProxy = pCtx->lockProxy;
7342 unixFile *conchFile = pCtx->conchFile;
7343 int rc = SQLITE_OK;
7344
7345 if( lockProxy ){
7346 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7347 if( rc ) return rc;
7348 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7349 if( rc ) return rc;
7350 sqlite3_free(lockProxy);
7351 pCtx->lockProxy = 0;
7352 }
7353 if( conchFile ){
7354 if( pCtx->conchHeld ){
7355 rc = proxyReleaseConch(pFile);
7356 if( rc ) return rc;
7357 }
7358 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7359 if( rc ) return rc;
7360 sqlite3_free(conchFile);
7361 }
drhd56b1212010-08-11 06:14:15 +00007362 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007363 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007364 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007365 /* restore the original locking context and pMethod then close it */
7366 pFile->lockingContext = pCtx->oldLockingContext;
7367 pFile->pMethod = pCtx->pOldMethod;
7368 sqlite3_free(pCtx);
7369 return pFile->pMethod->xClose(id);
7370 }
7371 return SQLITE_OK;
7372}
7373
7374
7375
drhd2cb50b2009-01-09 21:41:17 +00007376#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007377/*
7378** The proxy locking style is intended for use with AFP filesystems.
7379** And since AFP is only supported on MacOSX, the proxy locking is also
7380** restricted to MacOSX.
7381**
7382**
7383******************* End of the proxy lock implementation **********************
7384******************************************************************************/
7385
drh734c9862008-11-28 15:37:20 +00007386/*
danielk1977e339d652008-06-28 11:23:00 +00007387** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007388**
7389** This routine registers all VFS implementations for unix-like operating
7390** systems. This routine, and the sqlite3_os_end() routine that follows,
7391** should be the only routines in this file that are visible from other
7392** files.
drh6b9d6dd2008-12-03 19:34:47 +00007393**
7394** This routine is called once during SQLite initialization and by a
7395** single thread. The memory allocation and mutex subsystems have not
7396** necessarily been initialized when this routine is called, and so they
7397** should not be used.
drh153c62c2007-08-24 03:51:33 +00007398*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007399int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007400 /*
7401 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007402 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7403 ** to the "finder" function. (pAppData is a pointer to a pointer because
7404 ** silly C90 rules prohibit a void* from being cast to a function pointer
7405 ** and so we have to go through the intermediate pointer to avoid problems
7406 ** when compiling with -pedantic-errors on GCC.)
7407 **
7408 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007409 ** finder-function. The finder-function returns a pointer to the
7410 ** sqlite_io_methods object that implements the desired locking
7411 ** behaviors. See the division above that contains the IOMETHODS
7412 ** macro for addition information on finder-functions.
7413 **
7414 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7415 ** object. But the "autolockIoFinder" available on MacOSX does a little
7416 ** more than that; it looks at the filesystem type that hosts the
7417 ** database file and tries to choose an locking method appropriate for
7418 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007419 */
drh7708e972008-11-29 00:56:52 +00007420 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007421 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007422 sizeof(unixFile), /* szOsFile */ \
7423 MAX_PATHNAME, /* mxPathname */ \
7424 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007425 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007426 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007427 unixOpen, /* xOpen */ \
7428 unixDelete, /* xDelete */ \
7429 unixAccess, /* xAccess */ \
7430 unixFullPathname, /* xFullPathname */ \
7431 unixDlOpen, /* xDlOpen */ \
7432 unixDlError, /* xDlError */ \
7433 unixDlSym, /* xDlSym */ \
7434 unixDlClose, /* xDlClose */ \
7435 unixRandomness, /* xRandomness */ \
7436 unixSleep, /* xSleep */ \
7437 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007438 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007439 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007440 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007441 unixGetSystemCall, /* xGetSystemCall */ \
7442 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007443 }
7444
drh6b9d6dd2008-12-03 19:34:47 +00007445 /*
7446 ** All default VFSes for unix are contained in the following array.
7447 **
7448 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7449 ** by the SQLite core when the VFS is registered. So the following
7450 ** array cannot be const.
7451 */
danielk1977e339d652008-06-28 11:23:00 +00007452 static sqlite3_vfs aVfs[] = {
drhe89b2912015-03-03 20:42:01 +00007453#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007454 UNIXVFS("unix", autolockIoFinder ),
drhe89b2912015-03-03 20:42:01 +00007455#elif OS_VXWORKS
7456 UNIXVFS("unix", vxworksIoFinder ),
drh7708e972008-11-29 00:56:52 +00007457#else
7458 UNIXVFS("unix", posixIoFinder ),
7459#endif
7460 UNIXVFS("unix-none", nolockIoFinder ),
7461 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007462 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007463#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007464 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007465#endif
drhe89b2912015-03-03 20:42:01 +00007466#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007467 UNIXVFS("unix-posix", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007468#endif
drhe89b2912015-03-03 20:42:01 +00007469#if SQLITE_ENABLE_LOCKING_STYLE
7470 UNIXVFS("unix-flock", flockIoFinder ),
chw78a13182009-04-07 05:35:03 +00007471#endif
drhd2cb50b2009-01-09 21:41:17 +00007472#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007473 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007474 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007475 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007476#endif
drh153c62c2007-08-24 03:51:33 +00007477 };
drh6b9d6dd2008-12-03 19:34:47 +00007478 unsigned int i; /* Loop counter */
7479
drh2aa5a002011-04-13 13:42:25 +00007480 /* Double-check that the aSyscall[] array has been constructed
7481 ** correctly. See ticket [bb3a86e890c8e96ab] */
drh6226ca22015-11-24 15:06:28 +00007482 assert( ArraySize(aSyscall)==27 );
drh2aa5a002011-04-13 13:42:25 +00007483
drh6b9d6dd2008-12-03 19:34:47 +00007484 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007485 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007486 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007487 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007488 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007489}
danielk1977e339d652008-06-28 11:23:00 +00007490
7491/*
drh6b9d6dd2008-12-03 19:34:47 +00007492** Shutdown the operating system interface.
7493**
7494** Some operating systems might need to do some cleanup in this routine,
7495** to release dynamically allocated objects. But not on unix.
7496** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007497*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007498int sqlite3_os_end(void){
7499 return SQLITE_OK;
7500}
drhdce8bdb2007-08-16 13:01:44 +00007501
danielk197729bafea2008-06-26 10:41:19 +00007502#endif /* SQLITE_OS_UNIX */