blob: 791ba5d8d966f7c42c124f31767c5d0a4f6caeed [file] [log] [blame]
drhbbd42a62004-05-22 17:41:58 +00001/*
2** 2004 May 22
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11******************************************************************************
12**
drh734c9862008-11-28 15:37:20 +000013** This file contains the VFS implementation for unix-like operating systems
14** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
danielk1977822a5162008-05-16 04:51:54 +000015**
drh734c9862008-11-28 15:37:20 +000016** There are actually several different VFS implementations in this file.
17** The differences are in the way that file locking is done. The default
18** implementation uses Posix Advisory Locks. Alternative implementations
19** use flock(), dot-files, various proprietary locking schemas, or simply
20** skip locking all together.
21**
drh9b35ea62008-11-29 02:20:26 +000022** This source file is organized into divisions where the logic for various
drh734c9862008-11-28 15:37:20 +000023** subfunctions is contained within the appropriate division. PLEASE
24** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
25** in the correct division and should be clearly labeled.
26**
drh6b9d6dd2008-12-03 19:34:47 +000027** The layout of divisions is as follows:
drh734c9862008-11-28 15:37:20 +000028**
29** * General-purpose declarations and utility functions.
30** * Unique file ID logic used by VxWorks.
drh715ff302008-12-03 22:32:44 +000031** * Various locking primitive implementations (all except proxy locking):
drh734c9862008-11-28 15:37:20 +000032** + for Posix Advisory Locks
33** + for no-op locks
34** + for dot-file locks
35** + for flock() locking
36** + for named semaphore locks (VxWorks only)
37** + for AFP filesystem locks (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000038** * sqlite3_file methods not associated with locking.
39** * Definitions of sqlite3_io_methods objects for all locking
40** methods plus "finder" functions for each locking method.
drh6b9d6dd2008-12-03 19:34:47 +000041** * sqlite3_vfs method implementations.
drh715ff302008-12-03 22:32:44 +000042** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000043** * Definitions of sqlite3_vfs objects for all locking methods
44** plus implementations of sqlite3_os_init() and sqlite3_os_end().
drhbbd42a62004-05-22 17:41:58 +000045*/
drhbbd42a62004-05-22 17:41:58 +000046#include "sqliteInt.h"
danielk197729bafea2008-06-26 10:41:19 +000047#if SQLITE_OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000048
danielk1977e339d652008-06-28 11:23:00 +000049/*
drh6b9d6dd2008-12-03 19:34:47 +000050** There are various methods for file locking used for concurrency
51** control:
danielk1977e339d652008-06-28 11:23:00 +000052**
drh734c9862008-11-28 15:37:20 +000053** 1. POSIX locking (the default),
54** 2. No locking,
55** 3. Dot-file locking,
56** 4. flock() locking,
57** 5. AFP locking (OSX only),
58** 6. Named POSIX semaphores (VXWorks only),
59** 7. proxy locking. (OSX only)
60**
61** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
62** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
63** selection of the appropriate locking style based on the filesystem
64** where the database is located.
danielk1977e339d652008-06-28 11:23:00 +000065*/
drh40bbb0a2008-09-23 10:23:26 +000066#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
drhd2cb50b2009-01-09 21:41:17 +000067# if defined(__APPLE__)
drh40bbb0a2008-09-23 10:23:26 +000068# define SQLITE_ENABLE_LOCKING_STYLE 1
69# else
70# define SQLITE_ENABLE_LOCKING_STYLE 0
71# endif
72#endif
drhbfe66312006-10-03 17:40:40 +000073
drh9cbe6352005-11-29 03:13:21 +000074/*
drh9cbe6352005-11-29 03:13:21 +000075** standard include files.
76*/
77#include <sys/types.h>
78#include <sys/stat.h>
79#include <fcntl.h>
80#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +000081#include <time.h>
drh19e2d372005-08-29 23:00:03 +000082#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +000083#include <errno.h>
dan32c12fe2013-05-02 17:37:31 +000084#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drh91be7dc2014-08-11 13:53:30 +000085# include <sys/mman.h>
drhb469f462010-12-22 21:48:50 +000086#endif
drh1da88f02011-12-17 16:09:16 +000087
drhe89b2912015-03-03 20:42:01 +000088#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +000089# include <sys/ioctl.h>
drhe89b2912015-03-03 20:42:01 +000090# include <sys/file.h>
91# include <sys/param.h>
drhbfe66312006-10-03 17:40:40 +000092#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +000093
drh6bca6512015-04-13 23:05:28 +000094#if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
95 (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
96# if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
97 && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
98# define HAVE_GETHOSTUUID 1
99# else
100# warning "gethostuuid() is disabled."
101# endif
102#endif
103
104
drhe89b2912015-03-03 20:42:01 +0000105#if OS_VXWORKS
106# include <sys/ioctl.h>
107# include <semaphore.h>
108# include <limits.h>
109#endif /* OS_VXWORKS */
110
111#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh84a2bf62010-03-05 13:41:06 +0000112# include <sys/mount.h>
113#endif
114
drhdbe4b882011-06-20 18:00:17 +0000115#ifdef HAVE_UTIME
116# include <utime.h>
117#endif
118
drh9cbe6352005-11-29 03:13:21 +0000119/*
drh7ed97b92010-01-20 13:07:21 +0000120** Allowed values of unixFile.fsFlags
121*/
122#define SQLITE_FSFLAGS_IS_MSDOS 0x1
123
124/*
drhf1a221e2006-01-15 17:27:17 +0000125** If we are to be thread-safe, include the pthreads header and define
126** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000127*/
drhd677b3d2007-08-20 22:48:41 +0000128#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000129# include <pthread.h>
130# define SQLITE_UNIX_THREADS 1
131#endif
132
133/*
134** Default permissions when creating a new file
135*/
136#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
137# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
138#endif
139
danielk1977b4b47412007-08-17 15:53:36 +0000140/*
drh5adc60b2012-04-14 13:25:11 +0000141** Default permissions when creating auto proxy dir
142*/
aswiftaebf4132008-11-21 00:10:35 +0000143#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
144# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
145#endif
146
147/*
danielk1977b4b47412007-08-17 15:53:36 +0000148** Maximum supported path-length.
149*/
150#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000151
drh91eb93c2015-03-03 19:56:20 +0000152/* Always cast the getpid() return type for compatibility with
153** kernel modules in VxWorks. */
154#define osGetpid(X) (pid_t)getpid()
155
drh734c9862008-11-28 15:37:20 +0000156/*
drh734c9862008-11-28 15:37:20 +0000157** Only set the lastErrno if the error code is a real error and not
158** a normal expected return code of SQLITE_BUSY or SQLITE_OK
159*/
160#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
161
drhd91c68f2010-05-14 14:52:25 +0000162/* Forward references */
163typedef struct unixShm unixShm; /* Connection shared memory */
164typedef struct unixShmNode unixShmNode; /* Shared memory instance */
165typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
166typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000167
168/*
dane946c392009-08-22 11:39:46 +0000169** Sometimes, after a file handle is closed by SQLite, the file descriptor
170** cannot be closed immediately. In these cases, instances of the following
171** structure are used to store the file descriptor while waiting for an
172** opportunity to either close or reuse it.
173*/
dane946c392009-08-22 11:39:46 +0000174struct UnixUnusedFd {
175 int fd; /* File descriptor to close */
176 int flags; /* Flags this file descriptor was opened with */
177 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
178};
179
180/*
drh9b35ea62008-11-29 02:20:26 +0000181** The unixFile structure is subclass of sqlite3_file specific to the unix
182** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000183*/
drh054889e2005-11-30 03:20:31 +0000184typedef struct unixFile unixFile;
185struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000186 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhde60fc22011-12-14 17:53:36 +0000187 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
drhd91c68f2010-05-14 14:52:25 +0000188 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000189 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000190 unsigned char eFileLock; /* The type of lock held on this fd */
drh3ee34842012-02-11 21:21:17 +0000191 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000192 int lastErrno; /* The unix errno from last I/O error */
193 void *lockingContext; /* Locking style specific state */
194 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000195 const char *zPath; /* Name of the file */
196 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000197 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
mistachkine98844f2013-08-24 00:59:24 +0000198#if SQLITE_MAX_MMAP_SIZE>0
drh0d0614b2013-03-25 23:09:28 +0000199 int nFetchOut; /* Number of outstanding xFetch refs */
200 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
drh9b4c59f2013-04-15 17:03:42 +0000201 sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
202 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
drh0d0614b2013-03-25 23:09:28 +0000203 void *pMapRegion; /* Memory mapped region */
mistachkine98844f2013-08-24 00:59:24 +0000204#endif
drh537dddf2012-10-26 13:46:24 +0000205#ifdef __QNXNTO__
206 int sectorSize; /* Device sector size */
207 int deviceCharacteristics; /* Precomputed device characteristics */
208#endif
drh08c6d442009-02-09 17:34:07 +0000209#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000210 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000211#endif
drh7ed97b92010-01-20 13:07:21 +0000212#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000213 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000214#endif
215#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000216 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000217#endif
drhd3d8c042012-05-29 17:02:40 +0000218#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +0000219 /* The next group of variables are used to track whether or not the
220 ** transaction counter in bytes 24-27 of database files are updated
221 ** whenever any part of the database changes. An assertion fault will
222 ** occur if a file is updated without also updating the transaction
223 ** counter. This test is made to avoid new problems similar to the
224 ** one described by ticket #3584.
225 */
226 unsigned char transCntrChng; /* True if the transaction counter changed */
227 unsigned char dbUpdate; /* True if any part of database file changed */
228 unsigned char inNormalWrite; /* True if in a normal write operation */
danf23da962013-03-23 21:00:41 +0000229
drh8f941bc2009-01-14 23:03:40 +0000230#endif
danf23da962013-03-23 21:00:41 +0000231
danielk1977967a4a12007-08-20 14:23:44 +0000232#ifdef SQLITE_TEST
233 /* In test mode, increase the size of this structure a bit so that
234 ** it is larger than the struct CrashFile defined in test6.c.
235 */
236 char aPadding[32];
237#endif
drh9cbe6352005-11-29 03:13:21 +0000238};
239
drhb00d8622014-01-01 15:18:36 +0000240/* This variable holds the process id (pid) from when the xRandomness()
241** method was called. If xOpen() is called from a different process id,
242** indicating that a fork() has occurred, the PRNG will be reset.
243*/
drh8cd5b252015-03-02 22:06:43 +0000244static pid_t randomnessPid = 0;
drhb00d8622014-01-01 15:18:36 +0000245
drh0ccebe72005-06-07 22:22:50 +0000246/*
drha7e61d82011-03-12 17:02:57 +0000247** Allowed values for the unixFile.ctrlFlags bitmask:
248*/
drhf0b190d2011-07-26 16:03:07 +0000249#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
250#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
251#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000252#ifndef SQLITE_DISABLE_DIRSYNC
253# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
254#else
255# define UNIXFILE_DIRSYNC 0x00
256#endif
drhcb15f352011-12-23 01:04:17 +0000257#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
drhc02a43a2012-01-10 23:18:38 +0000258#define UNIXFILE_DELETE 0x20 /* Delete on close */
259#define UNIXFILE_URI 0x40 /* Filename might have query parameters */
260#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
drha7e61d82011-03-12 17:02:57 +0000261
262/*
drh198bf392006-01-06 21:52:49 +0000263** Include code that is common to all os_*.c files
264*/
265#include "os_common.h"
266
267/*
drh0ccebe72005-06-07 22:22:50 +0000268** Define various macros that are missing from some systems.
269*/
drhbbd42a62004-05-22 17:41:58 +0000270#ifndef O_LARGEFILE
271# define O_LARGEFILE 0
272#endif
273#ifdef SQLITE_DISABLE_LFS
274# undef O_LARGEFILE
275# define O_LARGEFILE 0
276#endif
277#ifndef O_NOFOLLOW
278# define O_NOFOLLOW 0
279#endif
280#ifndef O_BINARY
281# define O_BINARY 0
282#endif
283
284/*
drh2b4b5962005-06-15 17:47:55 +0000285** The threadid macro resolves to the thread-id or to 0. Used for
286** testing and debugging only.
287*/
drhd677b3d2007-08-20 22:48:41 +0000288#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000289#define threadid pthread_self()
290#else
291#define threadid 0
292#endif
293
drh99ab3b12011-03-02 15:09:07 +0000294/*
dane6ecd662013-04-01 17:56:59 +0000295** HAVE_MREMAP defaults to true on Linux and false everywhere else.
296*/
297#if !defined(HAVE_MREMAP)
298# if defined(__linux__) && defined(_GNU_SOURCE)
299# define HAVE_MREMAP 1
300# else
301# define HAVE_MREMAP 0
302# endif
303#endif
304
305/*
dan2ee53412014-09-06 16:49:40 +0000306** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
307** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
308*/
309#ifdef __ANDROID__
310# define lseek lseek64
311#endif
312
313/*
drh9a3baf12011-04-25 18:01:27 +0000314** Different Unix systems declare open() in different ways. Same use
315** open(const char*,int,mode_t). Others use open(const char*,int,...).
316** The difference is important when using a pointer to the function.
317**
318** The safest way to deal with the problem is to always use this wrapper
319** which always has the same well-defined interface.
320*/
321static int posixOpen(const char *zFile, int flags, int mode){
322 return open(zFile, flags, mode);
323}
324
drh90315a22011-08-10 01:52:12 +0000325/* Forward reference */
326static int openDirectory(const char*, int*);
danbc760632014-03-20 09:42:09 +0000327static int unixGetpagesize(void);
drh90315a22011-08-10 01:52:12 +0000328
drh9a3baf12011-04-25 18:01:27 +0000329/*
drh99ab3b12011-03-02 15:09:07 +0000330** Many system calls are accessed through pointer-to-functions so that
331** they may be overridden at runtime to facilitate fault injection during
332** testing and sandboxing. The following array holds the names and pointers
333** to all overrideable system calls.
334*/
335static struct unix_syscall {
mistachkin48864df2013-03-21 21:20:32 +0000336 const char *zName; /* Name of the system call */
drh58ad5802011-03-23 22:02:23 +0000337 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
338 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000339} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000340 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
341#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000342
drh58ad5802011-03-23 22:02:23 +0000343 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000344#define osClose ((int(*)(int))aSyscall[1].pCurrent)
345
drh58ad5802011-03-23 22:02:23 +0000346 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000347#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
348
drh58ad5802011-03-23 22:02:23 +0000349 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000350#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
351
drh58ad5802011-03-23 22:02:23 +0000352 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000353#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
354
355/*
356** The DJGPP compiler environment looks mostly like Unix, but it
357** lacks the fcntl() system call. So redefine fcntl() to be something
358** that always succeeds. This means that locking does not occur under
359** DJGPP. But it is DOS - what did you expect?
360*/
361#ifdef __DJGPP__
362 { "fstat", 0, 0 },
363#define osFstat(a,b,c) 0
364#else
drh58ad5802011-03-23 22:02:23 +0000365 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000366#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
367#endif
368
drh58ad5802011-03-23 22:02:23 +0000369 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000370#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
371
drh58ad5802011-03-23 22:02:23 +0000372 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000373#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000374
drh58ad5802011-03-23 22:02:23 +0000375 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000376#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
377
drhe89b2912015-03-03 20:42:01 +0000378#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000379 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000380#else
drh58ad5802011-03-23 22:02:23 +0000381 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000382#endif
383#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
384
385#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000386 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000387#else
drh58ad5802011-03-23 22:02:23 +0000388 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000389#endif
390#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
391
drh58ad5802011-03-23 22:02:23 +0000392 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000393#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
394
drhe89b2912015-03-03 20:42:01 +0000395#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000396 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000397#else
drh58ad5802011-03-23 22:02:23 +0000398 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000399#endif
400#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
401 aSyscall[12].pCurrent)
402
403#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000404 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000405#else
drh58ad5802011-03-23 22:02:23 +0000406 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000407#endif
408#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
409 aSyscall[13].pCurrent)
410
drh6226ca22015-11-24 15:06:28 +0000411 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000412#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000413
414#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000415 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000416#else
drh58ad5802011-03-23 22:02:23 +0000417 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000418#endif
dan0fd7d862011-03-29 10:04:23 +0000419#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000420
drh036ac7f2011-08-08 23:18:05 +0000421 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
422#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
423
drh90315a22011-08-10 01:52:12 +0000424 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
425#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
426
drh9ef6bc42011-11-04 02:24:02 +0000427 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
428#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
429
430 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
431#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
432
drh6226ca22015-11-24 15:06:28 +0000433 { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
dand3eaebd2012-02-13 08:50:23 +0000434#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000435
drh6226ca22015-11-24 15:06:28 +0000436 { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
437#define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
438
dan4dd51442013-08-26 14:30:25 +0000439#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
dan893c0ff2013-03-25 19:05:07 +0000440 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
drh6226ca22015-11-24 15:06:28 +0000441#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
dan893c0ff2013-03-25 19:05:07 +0000442
drhd1ab8062013-03-25 20:50:25 +0000443 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
drh6226ca22015-11-24 15:06:28 +0000444#define osMunmap ((void*(*)(void*,size_t))aSyscall[23].pCurrent)
drhd1ab8062013-03-25 20:50:25 +0000445
dane6ecd662013-04-01 17:56:59 +0000446#if HAVE_MREMAP
drhd1ab8062013-03-25 20:50:25 +0000447 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
448#else
449 { "mremap", (sqlite3_syscall_ptr)0, 0 },
450#endif
drh6226ca22015-11-24 15:06:28 +0000451#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
452
danbc760632014-03-20 09:42:09 +0000453 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
drh6226ca22015-11-24 15:06:28 +0000454#define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
danbc760632014-03-20 09:42:09 +0000455
dan245fdc62015-10-31 17:58:33 +0000456 { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
drh6226ca22015-11-24 15:06:28 +0000457#define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
dan245fdc62015-10-31 17:58:33 +0000458
dan702eec12014-06-23 10:04:58 +0000459#endif
460
drhe562be52011-03-02 18:01:10 +0000461}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000462
drh6226ca22015-11-24 15:06:28 +0000463
464/*
465** On some systems, calls to fchown() will trigger a message in a security
466** log if they come from non-root processes. So avoid calling fchown() if
467** we are not running as root.
468*/
469static int robustFchown(int fd, uid_t uid, gid_t gid){
470#if OS_VXWORKS
471 return 0;
472#else
473 return osGeteuid() ? 0 : osFchown(fd,uid,gid);
474#endif
475}
476
drh99ab3b12011-03-02 15:09:07 +0000477/*
478** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000479** "unix" VFSes. Return SQLITE_OK opon successfully updating the
480** system call pointer, or SQLITE_NOTFOUND if there is no configurable
481** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000482*/
483static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000484 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
485 const char *zName, /* Name of system call to override */
486 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000487){
drh58ad5802011-03-23 22:02:23 +0000488 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000489 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000490
491 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000492 if( zName==0 ){
493 /* If no zName is given, restore all system calls to their default
494 ** settings and return NULL
495 */
dan51438a72011-04-02 17:00:47 +0000496 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000497 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
498 if( aSyscall[i].pDefault ){
499 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000500 }
501 }
502 }else{
503 /* If zName is specified, operate on only the one system call
504 ** specified.
505 */
506 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
507 if( strcmp(zName, aSyscall[i].zName)==0 ){
508 if( aSyscall[i].pDefault==0 ){
509 aSyscall[i].pDefault = aSyscall[i].pCurrent;
510 }
drh1df30962011-03-02 19:06:42 +0000511 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000512 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
513 aSyscall[i].pCurrent = pNewFunc;
514 break;
515 }
516 }
517 }
518 return rc;
519}
520
drh1df30962011-03-02 19:06:42 +0000521/*
522** Return the value of a system call. Return NULL if zName is not a
523** recognized system call name. NULL is also returned if the system call
524** is currently undefined.
525*/
drh58ad5802011-03-23 22:02:23 +0000526static sqlite3_syscall_ptr unixGetSystemCall(
527 sqlite3_vfs *pNotUsed,
528 const char *zName
529){
530 unsigned int i;
531
532 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000533 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
534 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
535 }
536 return 0;
537}
538
539/*
540** Return the name of the first system call after zName. If zName==NULL
541** then return the name of the first system call. Return NULL if zName
542** is the last system call or if zName is not the name of a valid
543** system call.
544*/
545static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000546 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000547
548 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000549 if( zName ){
550 for(i=0; i<ArraySize(aSyscall)-1; i++){
551 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000552 }
553 }
dan0fd7d862011-03-29 10:04:23 +0000554 for(i++; i<ArraySize(aSyscall); i++){
555 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000556 }
557 return 0;
558}
559
drhad4f1e52011-03-04 15:43:57 +0000560/*
drh77a3fdc2013-08-30 14:24:12 +0000561** Do not accept any file descriptor less than this value, in order to avoid
562** opening database file using file descriptors that are commonly used for
563** standard input, output, and error.
564*/
565#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
566# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
567#endif
568
569/*
drh8c815d12012-02-13 20:16:37 +0000570** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000571** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000572**
573** If the file creation mode "m" is 0 then set it to the default for
574** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
575** 0644) as modified by the system umask. If m is not 0, then
576** make the file creation mode be exactly m ignoring the umask.
577**
578** The m parameter will be non-zero only when creating -wal, -journal,
579** and -shm files. We want those files to have *exactly* the same
580** permissions as their original database, unadulterated by the umask.
581** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
582** transaction crashes and leaves behind hot journals, then any
583** process that is able to write to the database will also be able to
584** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000585*/
drh8c815d12012-02-13 20:16:37 +0000586static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000587 int fd;
drhe1186ab2013-01-04 20:45:13 +0000588 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5128d002013-08-30 06:20:23 +0000589 while(1){
drh5adc60b2012-04-14 13:25:11 +0000590#if defined(O_CLOEXEC)
591 fd = osOpen(z,f|O_CLOEXEC,m2);
592#else
593 fd = osOpen(z,f,m2);
594#endif
drh5128d002013-08-30 06:20:23 +0000595 if( fd<0 ){
596 if( errno==EINTR ) continue;
597 break;
598 }
drh77a3fdc2013-08-30 14:24:12 +0000599 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
drh5128d002013-08-30 06:20:23 +0000600 osClose(fd);
601 sqlite3_log(SQLITE_WARNING,
602 "attempt to open \"%s\" as file descriptor %d", z, fd);
603 fd = -1;
604 if( osOpen("/dev/null", f, m)<0 ) break;
605 }
drhe1186ab2013-01-04 20:45:13 +0000606 if( fd>=0 ){
607 if( m!=0 ){
608 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000609 if( osFstat(fd, &statbuf)==0
610 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000611 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000612 ){
drhe1186ab2013-01-04 20:45:13 +0000613 osFchmod(fd, m);
614 }
615 }
drh5adc60b2012-04-14 13:25:11 +0000616#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000617 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000618#endif
drhe1186ab2013-01-04 20:45:13 +0000619 }
drh5adc60b2012-04-14 13:25:11 +0000620 return fd;
drhad4f1e52011-03-04 15:43:57 +0000621}
danielk197713adf8a2004-06-03 16:08:41 +0000622
drh107886a2008-11-21 22:21:50 +0000623/*
dan9359c7b2009-08-21 08:29:10 +0000624** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000625** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000626** vxworksFileId objects used by this file, all of which may be
627** shared by multiple threads.
628**
629** Function unixMutexHeld() is used to assert() that the global mutex
630** is held when required. This function is only used as part of assert()
631** statements. e.g.
632**
633** unixEnterMutex()
634** assert( unixMutexHeld() );
635** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000636*/
637static void unixEnterMutex(void){
mistachkin93de6532015-07-03 21:38:09 +0000638 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
drh107886a2008-11-21 22:21:50 +0000639}
640static void unixLeaveMutex(void){
mistachkin93de6532015-07-03 21:38:09 +0000641 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
drh107886a2008-11-21 22:21:50 +0000642}
dan9359c7b2009-08-21 08:29:10 +0000643#ifdef SQLITE_DEBUG
644static int unixMutexHeld(void) {
mistachkin93de6532015-07-03 21:38:09 +0000645 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
dan9359c7b2009-08-21 08:29:10 +0000646}
647#endif
drh107886a2008-11-21 22:21:50 +0000648
drh734c9862008-11-28 15:37:20 +0000649
mistachkinfb383e92015-04-16 03:24:38 +0000650#ifdef SQLITE_HAVE_OS_TRACE
drh734c9862008-11-28 15:37:20 +0000651/*
652** Helper function for printing out trace information from debugging
peter.d.reid60ec9142014-09-06 16:39:46 +0000653** binaries. This returns the string representation of the supplied
drh734c9862008-11-28 15:37:20 +0000654** integer lock-type.
655*/
drh308c2a52010-05-14 11:30:18 +0000656static const char *azFileLock(int eFileLock){
657 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000658 case NO_LOCK: return "NONE";
659 case SHARED_LOCK: return "SHARED";
660 case RESERVED_LOCK: return "RESERVED";
661 case PENDING_LOCK: return "PENDING";
662 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000663 }
664 return "ERROR";
665}
666#endif
667
668#ifdef SQLITE_LOCK_TRACE
669/*
670** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000671**
drh734c9862008-11-28 15:37:20 +0000672** This routine is used for troubleshooting locks on multithreaded
673** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
674** command-line option on the compiler. This code is normally
675** turned off.
676*/
677static int lockTrace(int fd, int op, struct flock *p){
678 char *zOpName, *zType;
679 int s;
680 int savedErrno;
681 if( op==F_GETLK ){
682 zOpName = "GETLK";
683 }else if( op==F_SETLK ){
684 zOpName = "SETLK";
685 }else{
drh99ab3b12011-03-02 15:09:07 +0000686 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000687 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
688 return s;
689 }
690 if( p->l_type==F_RDLCK ){
691 zType = "RDLCK";
692 }else if( p->l_type==F_WRLCK ){
693 zType = "WRLCK";
694 }else if( p->l_type==F_UNLCK ){
695 zType = "UNLCK";
696 }else{
697 assert( 0 );
698 }
699 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000700 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000701 savedErrno = errno;
702 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
703 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
704 (int)p->l_pid, s);
705 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
706 struct flock l2;
707 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000708 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000709 if( l2.l_type==F_RDLCK ){
710 zType = "RDLCK";
711 }else if( l2.l_type==F_WRLCK ){
712 zType = "WRLCK";
713 }else if( l2.l_type==F_UNLCK ){
714 zType = "UNLCK";
715 }else{
716 assert( 0 );
717 }
718 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
719 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
720 }
721 errno = savedErrno;
722 return s;
723}
drh99ab3b12011-03-02 15:09:07 +0000724#undef osFcntl
725#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000726#endif /* SQLITE_LOCK_TRACE */
727
drhff812312011-02-23 13:33:46 +0000728/*
729** Retry ftruncate() calls that fail due to EINTR
dan2ee53412014-09-06 16:49:40 +0000730**
drhe6d41732015-02-21 00:49:00 +0000731** All calls to ftruncate() within this file should be made through
732** this wrapper. On the Android platform, bypassing the logic below
733** could lead to a corrupt database.
drhff812312011-02-23 13:33:46 +0000734*/
drhff812312011-02-23 13:33:46 +0000735static int robust_ftruncate(int h, sqlite3_int64 sz){
736 int rc;
dan2ee53412014-09-06 16:49:40 +0000737#ifdef __ANDROID__
738 /* On Android, ftruncate() always uses 32-bit offsets, even if
739 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
dan524a7332014-09-06 17:06:13 +0000740 ** truncate a file to any size larger than 2GiB. Silently ignore any
dan2ee53412014-09-06 16:49:40 +0000741 ** such attempts. */
742 if( sz>(sqlite3_int64)0x7FFFFFFF ){
743 rc = SQLITE_OK;
744 }else
745#endif
drh99ab3b12011-03-02 15:09:07 +0000746 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000747 return rc;
748}
drh734c9862008-11-28 15:37:20 +0000749
750/*
751** This routine translates a standard POSIX errno code into something
752** useful to the clients of the sqlite3 functions. Specifically, it is
753** intended to translate a variety of "try again" errors into SQLITE_BUSY
754** and a variety of "please close the file descriptor NOW" errors into
755** SQLITE_IOERR
756**
757** Errors during initialization of locks, or file system support for locks,
758** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
759*/
760static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
drh91c4def2015-11-25 14:00:07 +0000761 assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
762 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
763 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
764 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
drh734c9862008-11-28 15:37:20 +0000765 switch (posixError) {
drh91c4def2015-11-25 14:00:07 +0000766 case EACCES:
drh734c9862008-11-28 15:37:20 +0000767 case EAGAIN:
768 case ETIMEDOUT:
769 case EBUSY:
770 case EINTR:
771 case ENOLCK:
772 /* random NFS retry error, unless during file system support
773 * introspection, in which it actually means what it says */
774 return SQLITE_BUSY;
775
drh734c9862008-11-28 15:37:20 +0000776 case EPERM:
777 return SQLITE_PERM;
778
drh734c9862008-11-28 15:37:20 +0000779 default:
780 return sqliteIOErr;
781 }
782}
783
784
drh734c9862008-11-28 15:37:20 +0000785/******************************************************************************
786****************** Begin Unique File ID Utility Used By VxWorks ***************
787**
788** On most versions of unix, we can get a unique ID for a file by concatenating
789** the device number and the inode number. But this does not work on VxWorks.
790** On VxWorks, a unique file id must be based on the canonical filename.
791**
792** A pointer to an instance of the following structure can be used as a
793** unique file ID in VxWorks. Each instance of this structure contains
794** a copy of the canonical filename. There is also a reference count.
795** The structure is reclaimed when the number of pointers to it drops to
796** zero.
797**
798** There are never very many files open at one time and lookups are not
799** a performance-critical path, so it is sufficient to put these
800** structures on a linked list.
801*/
802struct vxworksFileId {
803 struct vxworksFileId *pNext; /* Next in a list of them all */
804 int nRef; /* Number of references to this one */
805 int nName; /* Length of the zCanonicalName[] string */
806 char *zCanonicalName; /* Canonical filename */
807};
808
809#if OS_VXWORKS
810/*
drh9b35ea62008-11-29 02:20:26 +0000811** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000812** variable:
813*/
814static struct vxworksFileId *vxworksFileList = 0;
815
816/*
817** Simplify a filename into its canonical form
818** by making the following changes:
819**
820** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000821** * convert /./ into just /
822** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000823**
824** Changes are made in-place. Return the new name length.
825**
826** The original filename is in z[0..n-1]. Return the number of
827** characters in the simplified name.
828*/
829static int vxworksSimplifyName(char *z, int n){
830 int i, j;
831 while( n>1 && z[n-1]=='/' ){ n--; }
832 for(i=j=0; i<n; i++){
833 if( z[i]=='/' ){
834 if( z[i+1]=='/' ) continue;
835 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
836 i += 1;
837 continue;
838 }
839 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
840 while( j>0 && z[j-1]!='/' ){ j--; }
841 if( j>0 ){ j--; }
842 i += 2;
843 continue;
844 }
845 }
846 z[j++] = z[i];
847 }
848 z[j] = 0;
849 return j;
850}
851
852/*
853** Find a unique file ID for the given absolute pathname. Return
854** a pointer to the vxworksFileId object. This pointer is the unique
855** file ID.
856**
857** The nRef field of the vxworksFileId object is incremented before
858** the object is returned. A new vxworksFileId object is created
859** and added to the global list if necessary.
860**
861** If a memory allocation error occurs, return NULL.
862*/
863static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
864 struct vxworksFileId *pNew; /* search key and new file ID */
865 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
866 int n; /* Length of zAbsoluteName string */
867
868 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000869 n = (int)strlen(zAbsoluteName);
drhf3cdcdc2015-04-29 16:50:28 +0000870 pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
drh734c9862008-11-28 15:37:20 +0000871 if( pNew==0 ) return 0;
872 pNew->zCanonicalName = (char*)&pNew[1];
873 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
874 n = vxworksSimplifyName(pNew->zCanonicalName, n);
875
876 /* Search for an existing entry that matching the canonical name.
877 ** If found, increment the reference count and return a pointer to
878 ** the existing file ID.
879 */
880 unixEnterMutex();
881 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
882 if( pCandidate->nName==n
883 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
884 ){
885 sqlite3_free(pNew);
886 pCandidate->nRef++;
887 unixLeaveMutex();
888 return pCandidate;
889 }
890 }
891
892 /* No match was found. We will make a new file ID */
893 pNew->nRef = 1;
894 pNew->nName = n;
895 pNew->pNext = vxworksFileList;
896 vxworksFileList = pNew;
897 unixLeaveMutex();
898 return pNew;
899}
900
901/*
902** Decrement the reference count on a vxworksFileId object. Free
903** the object when the reference count reaches zero.
904*/
905static void vxworksReleaseFileId(struct vxworksFileId *pId){
906 unixEnterMutex();
907 assert( pId->nRef>0 );
908 pId->nRef--;
909 if( pId->nRef==0 ){
910 struct vxworksFileId **pp;
911 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
912 assert( *pp==pId );
913 *pp = pId->pNext;
914 sqlite3_free(pId);
915 }
916 unixLeaveMutex();
917}
918#endif /* OS_VXWORKS */
919/*************** End of Unique File ID Utility Used By VxWorks ****************
920******************************************************************************/
921
922
923/******************************************************************************
924*************************** Posix Advisory Locking ****************************
925**
drh9b35ea62008-11-29 02:20:26 +0000926** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000927** section 6.5.2.2 lines 483 through 490 specify that when a process
928** sets or clears a lock, that operation overrides any prior locks set
929** by the same process. It does not explicitly say so, but this implies
930** that it overrides locks set by the same process using a different
931** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000932**
933** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000934** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
935**
936** Suppose ./file1 and ./file2 are really the same file (because
937** one is a hard or symbolic link to the other) then if you set
938** an exclusive lock on fd1, then try to get an exclusive lock
939** on fd2, it works. I would have expected the second lock to
940** fail since there was already a lock on the file due to fd1.
941** But not so. Since both locks came from the same process, the
942** second overrides the first, even though they were on different
943** file descriptors opened on different file names.
944**
drh734c9862008-11-28 15:37:20 +0000945** This means that we cannot use POSIX locks to synchronize file access
946** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000947** to synchronize access for threads in separate processes, but not
948** threads within the same process.
949**
950** To work around the problem, SQLite has to manage file locks internally
951** on its own. Whenever a new database is opened, we have to find the
952** specific inode of the database file (the inode is determined by the
953** st_dev and st_ino fields of the stat structure that fstat() fills in)
954** and check for locks already existing on that inode. When locks are
955** created or removed, we have to look at our own internal record of the
956** locks to see if another thread has previously set a lock on that same
957** inode.
958**
drh9b35ea62008-11-29 02:20:26 +0000959** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
960** For VxWorks, we have to use the alternative unique ID system based on
961** canonical filename and implemented in the previous division.)
962**
danielk1977ad94b582007-08-20 06:44:22 +0000963** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000964** descriptor. It is now a structure that holds the integer file
965** descriptor and a pointer to a structure that describes the internal
966** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000967** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000968** point to the same locking structure. The locking structure keeps
969** a reference count (so we will know when to delete it) and a "cnt"
970** field that tells us its internal lock status. cnt==0 means the
971** file is unlocked. cnt==-1 means the file has an exclusive lock.
972** cnt>0 means there are cnt shared locks on the file.
973**
974** Any attempt to lock or unlock a file first checks the locking
975** structure. The fcntl() system call is only invoked to set a
976** POSIX lock if the internal lock structure transitions between
977** a locked and an unlocked state.
978**
drh734c9862008-11-28 15:37:20 +0000979** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000980**
981** If you close a file descriptor that points to a file that has locks,
982** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000983** released. To work around this problem, each unixInodeInfo object
984** maintains a count of the number of pending locks on tha inode.
985** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000986** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000987** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000988** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000989** be closed and that list is walked (and cleared) when the last lock
990** clears.
991**
drh9b35ea62008-11-29 02:20:26 +0000992** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000993**
drh9b35ea62008-11-29 02:20:26 +0000994** Many older versions of linux use the LinuxThreads library which is
995** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000996** A cannot be modified or overridden by a different thread B.
997** Only thread A can modify the lock. Locking behavior is correct
998** if the appliation uses the newer Native Posix Thread Library (NPTL)
999** on linux - with NPTL a lock created by thread A can override locks
1000** in thread B. But there is no way to know at compile-time which
1001** threading library is being used. So there is no way to know at
1002** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001003** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001004** current process.
drh5fdae772004-06-29 03:29:00 +00001005**
drh8af6c222010-05-14 12:43:01 +00001006** SQLite used to support LinuxThreads. But support for LinuxThreads
1007** was dropped beginning with version 3.7.0. SQLite will still work with
1008** LinuxThreads provided that (1) there is no more than one connection
1009** per database file in the same process and (2) database connections
1010** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001011*/
1012
1013/*
1014** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001015** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001016*/
1017struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001018 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001019#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001020 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001021#else
drh107886a2008-11-21 22:21:50 +00001022 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001023#endif
1024};
1025
1026/*
drhbbd42a62004-05-22 17:41:58 +00001027** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001028** inode. Or, on LinuxThreads, there is one of these structures for
1029** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001030**
danielk1977ad94b582007-08-20 06:44:22 +00001031** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001032** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001033** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001034*/
drh8af6c222010-05-14 12:43:01 +00001035struct unixInodeInfo {
1036 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001037 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001038 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1039 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001040 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001041 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1042 int nLock; /* Number of outstanding file locks */
1043 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1044 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1045 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001046#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001047 unsigned long long sharedByte; /* for AFP simulated shared lock */
1048#endif
drh6c7d5c52008-11-21 20:32:33 +00001049#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001050 sem_t *pSem; /* Named POSIX semaphore */
1051 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001052#endif
drhbbd42a62004-05-22 17:41:58 +00001053};
1054
drhda0e7682008-07-30 15:27:54 +00001055/*
drh8af6c222010-05-14 12:43:01 +00001056** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001057*/
drhd91c68f2010-05-14 14:52:25 +00001058static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001059
drh5fdae772004-06-29 03:29:00 +00001060/*
dane18d4952011-02-21 11:46:24 +00001061**
drhaaeaa182015-11-24 15:12:47 +00001062** This function - unixLogErrorAtLine(), is only ever called via the macro
dane18d4952011-02-21 11:46:24 +00001063** unixLogError().
1064**
1065** It is invoked after an error occurs in an OS function and errno has been
1066** set. It logs a message using sqlite3_log() containing the current value of
1067** errno and, if possible, the human-readable equivalent from strerror() or
1068** strerror_r().
1069**
1070** The first argument passed to the macro should be the error code that
1071** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1072** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001073** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001074** if any.
1075*/
drh0e9365c2011-03-02 02:08:13 +00001076#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1077static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001078 int errcode, /* SQLite error code */
1079 const char *zFunc, /* Name of OS function that failed */
1080 const char *zPath, /* File path associated with error */
1081 int iLine /* Source line number where error occurred */
1082){
1083 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001084 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001085
1086 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1087 ** the strerror() function to obtain the human-readable error message
1088 ** equivalent to errno. Otherwise, use strerror_r().
1089 */
1090#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1091 char aErr[80];
1092 memset(aErr, 0, sizeof(aErr));
1093 zErr = aErr;
1094
1095 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001096 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001097 ** returns a pointer to a buffer containing the error message. That pointer
1098 ** may point to aErr[], or it may point to some static storage somewhere.
1099 ** Otherwise, assume that the system provides the POSIX version of
1100 ** strerror_r(), which always writes an error message into aErr[].
1101 **
1102 ** If the code incorrectly assumes that it is the POSIX version that is
1103 ** available, the error message will often be an empty string. Not a
1104 ** huge problem. Incorrectly concluding that the GNU version is available
1105 ** could lead to a segfault though.
1106 */
1107#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1108 zErr =
1109# endif
drh0e9365c2011-03-02 02:08:13 +00001110 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001111
1112#elif SQLITE_THREADSAFE
1113 /* This is a threadsafe build, but strerror_r() is not available. */
1114 zErr = "";
1115#else
1116 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001117 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001118#endif
1119
drh0e9365c2011-03-02 02:08:13 +00001120 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001121 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001122 "os_unix.c:%d: (%d) %s(%s) - %s",
1123 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001124 );
1125
1126 return errcode;
1127}
1128
drh0e9365c2011-03-02 02:08:13 +00001129/*
1130** Close a file descriptor.
1131**
1132** We assume that close() almost always works, since it is only in a
1133** very sick application or on a very sick platform that it might fail.
1134** If it does fail, simply leak the file descriptor, but do log the
1135** error.
1136**
1137** Note that it is not safe to retry close() after EINTR since the
1138** file descriptor might have already been reused by another thread.
1139** So we don't even try to recover from an EINTR. Just log the error
1140** and move on.
1141*/
1142static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001143 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001144 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1145 pFile ? pFile->zPath : 0, lineno);
1146 }
1147}
dane18d4952011-02-21 11:46:24 +00001148
1149/*
drhe6d41732015-02-21 00:49:00 +00001150** Set the pFile->lastErrno. Do this in a subroutine as that provides
1151** a convenient place to set a breakpoint.
drh4bf66fd2015-02-19 02:43:02 +00001152*/
1153static void storeLastErrno(unixFile *pFile, int error){
1154 pFile->lastErrno = error;
1155}
1156
1157/*
danb0ac3e32010-06-16 10:55:42 +00001158** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001159*/
drh0e9365c2011-03-02 02:08:13 +00001160static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001161 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001162 UnixUnusedFd *p;
1163 UnixUnusedFd *pNext;
1164 for(p=pInode->pUnused; p; p=pNext){
1165 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001166 robust_close(pFile, p->fd, __LINE__);
1167 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001168 }
drh0e9365c2011-03-02 02:08:13 +00001169 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001170}
1171
1172/*
drh8af6c222010-05-14 12:43:01 +00001173** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001174**
1175** The mutex entered using the unixEnterMutex() function must be held
1176** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001177*/
danb0ac3e32010-06-16 10:55:42 +00001178static void releaseInodeInfo(unixFile *pFile){
1179 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001180 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001181 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001182 pInode->nRef--;
1183 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001184 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001185 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001186 if( pInode->pPrev ){
1187 assert( pInode->pPrev->pNext==pInode );
1188 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001189 }else{
drh8af6c222010-05-14 12:43:01 +00001190 assert( inodeList==pInode );
1191 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001192 }
drh8af6c222010-05-14 12:43:01 +00001193 if( pInode->pNext ){
1194 assert( pInode->pNext->pPrev==pInode );
1195 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001196 }
drh8af6c222010-05-14 12:43:01 +00001197 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001198 }
drhbbd42a62004-05-22 17:41:58 +00001199 }
1200}
1201
1202/*
drh8af6c222010-05-14 12:43:01 +00001203** Given a file descriptor, locate the unixInodeInfo object that
1204** describes that file descriptor. Create a new one if necessary. The
1205** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001206**
dan9359c7b2009-08-21 08:29:10 +00001207** The mutex entered using the unixEnterMutex() function must be held
1208** when this function is called.
1209**
drh6c7d5c52008-11-21 20:32:33 +00001210** Return an appropriate error code.
1211*/
drh8af6c222010-05-14 12:43:01 +00001212static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001213 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001214 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001215){
1216 int rc; /* System call return code */
1217 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001218 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1219 struct stat statbuf; /* Low-level file information */
1220 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001221
dan9359c7b2009-08-21 08:29:10 +00001222 assert( unixMutexHeld() );
1223
drh6c7d5c52008-11-21 20:32:33 +00001224 /* Get low-level information about the file that we can used to
1225 ** create a unique name for the file.
1226 */
1227 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001228 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001229 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001230 storeLastErrno(pFile, errno);
drh40fe8d32015-11-30 20:36:26 +00001231#if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
drh6c7d5c52008-11-21 20:32:33 +00001232 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1233#endif
1234 return SQLITE_IOERR;
1235 }
1236
drheb0d74f2009-02-03 15:27:02 +00001237#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001238 /* On OS X on an msdos filesystem, the inode number is reported
1239 ** incorrectly for zero-size files. See ticket #3260. To work
1240 ** around this problem (we consider it a bug in OS X, not SQLite)
1241 ** we always increase the file size to 1 by writing a single byte
1242 ** prior to accessing the inode number. The one byte written is
1243 ** an ASCII 'S' character which also happens to be the first byte
1244 ** in the header of every SQLite database. In this way, if there
1245 ** is a race condition such that another thread has already populated
1246 ** the first page of the database, no damage is done.
1247 */
drh7ed97b92010-01-20 13:07:21 +00001248 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001249 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001250 if( rc!=1 ){
drh4bf66fd2015-02-19 02:43:02 +00001251 storeLastErrno(pFile, errno);
drheb0d74f2009-02-03 15:27:02 +00001252 return SQLITE_IOERR;
1253 }
drh99ab3b12011-03-02 15:09:07 +00001254 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001255 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001256 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001257 return SQLITE_IOERR;
1258 }
1259 }
drheb0d74f2009-02-03 15:27:02 +00001260#endif
drh6c7d5c52008-11-21 20:32:33 +00001261
drh8af6c222010-05-14 12:43:01 +00001262 memset(&fileId, 0, sizeof(fileId));
1263 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001264#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001265 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001266#else
drh8af6c222010-05-14 12:43:01 +00001267 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001268#endif
drh8af6c222010-05-14 12:43:01 +00001269 pInode = inodeList;
1270 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1271 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001272 }
drh8af6c222010-05-14 12:43:01 +00001273 if( pInode==0 ){
drhf3cdcdc2015-04-29 16:50:28 +00001274 pInode = sqlite3_malloc64( sizeof(*pInode) );
drh8af6c222010-05-14 12:43:01 +00001275 if( pInode==0 ){
1276 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001277 }
drh8af6c222010-05-14 12:43:01 +00001278 memset(pInode, 0, sizeof(*pInode));
1279 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1280 pInode->nRef = 1;
1281 pInode->pNext = inodeList;
1282 pInode->pPrev = 0;
1283 if( inodeList ) inodeList->pPrev = pInode;
1284 inodeList = pInode;
1285 }else{
1286 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001287 }
drh8af6c222010-05-14 12:43:01 +00001288 *ppInode = pInode;
1289 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001290}
drh6c7d5c52008-11-21 20:32:33 +00001291
drhb959a012013-12-07 12:29:22 +00001292/*
1293** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1294*/
1295static int fileHasMoved(unixFile *pFile){
drh61ffea52014-08-12 12:19:25 +00001296#if OS_VXWORKS
1297 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1298#else
drhb959a012013-12-07 12:29:22 +00001299 struct stat buf;
1300 return pFile->pInode!=0 &&
drh61ffea52014-08-12 12:19:25 +00001301 (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
drh91be7dc2014-08-11 13:53:30 +00001302#endif
drhb959a012013-12-07 12:29:22 +00001303}
1304
aswift5b1a2562008-08-22 00:22:35 +00001305
1306/*
drhfbc7e882013-04-11 01:16:15 +00001307** Check a unixFile that is a database. Verify the following:
1308**
1309** (1) There is exactly one hard link on the file
1310** (2) The file is not a symbolic link
1311** (3) The file has not been renamed or unlinked
1312**
1313** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1314*/
1315static void verifyDbFile(unixFile *pFile){
1316 struct stat buf;
1317 int rc;
drhfbc7e882013-04-11 01:16:15 +00001318 rc = osFstat(pFile->h, &buf);
1319 if( rc!=0 ){
1320 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001321 return;
1322 }
drh3044b512014-06-16 16:41:52 +00001323 if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
drhfbc7e882013-04-11 01:16:15 +00001324 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001325 return;
1326 }
1327 if( buf.st_nlink>1 ){
1328 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001329 return;
1330 }
drhb959a012013-12-07 12:29:22 +00001331 if( fileHasMoved(pFile) ){
drhfbc7e882013-04-11 01:16:15 +00001332 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001333 return;
1334 }
1335}
1336
1337
1338/*
danielk197713adf8a2004-06-03 16:08:41 +00001339** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001340** file by this or any other process. If such a lock is held, set *pResOut
1341** to a non-zero value otherwise *pResOut is set to zero. The return value
1342** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001343*/
danielk1977861f7452008-06-05 11:39:11 +00001344static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001345 int rc = SQLITE_OK;
1346 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001347 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001348
danielk1977861f7452008-06-05 11:39:11 +00001349 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1350
drh054889e2005-11-30 03:20:31 +00001351 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00001352 assert( pFile->eFileLock<=SHARED_LOCK );
drh8af6c222010-05-14 12:43:01 +00001353 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001354
1355 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001356 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001357 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001358 }
1359
drh2ac3ee92004-06-07 16:27:46 +00001360 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001361 */
danielk197709480a92009-02-09 05:32:32 +00001362#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001363 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001364 struct flock lock;
1365 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001366 lock.l_start = RESERVED_BYTE;
1367 lock.l_len = 1;
1368 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001369 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1370 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001371 storeLastErrno(pFile, errno);
aswift5b1a2562008-08-22 00:22:35 +00001372 } else if( lock.l_type!=F_UNLCK ){
1373 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001374 }
1375 }
danielk197709480a92009-02-09 05:32:32 +00001376#endif
danielk197713adf8a2004-06-03 16:08:41 +00001377
drh6c7d5c52008-11-21 20:32:33 +00001378 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001379 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001380
aswift5b1a2562008-08-22 00:22:35 +00001381 *pResOut = reserved;
1382 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001383}
1384
1385/*
drha7e61d82011-03-12 17:02:57 +00001386** Attempt to set a system-lock on the file pFile. The lock is
1387** described by pLock.
1388**
drh77197112011-03-15 19:08:48 +00001389** If the pFile was opened read/write from unix-excl, then the only lock
1390** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001391** the first time any lock is attempted. All subsequent system locking
1392** operations become no-ops. Locking operations still happen internally,
1393** in order to coordinate access between separate database connections
1394** within this process, but all of that is handled in memory and the
1395** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001396**
1397** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1398** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1399** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001400**
1401** Zero is returned if the call completes successfully, or -1 if a call
1402** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001403*/
1404static int unixFileLock(unixFile *pFile, struct flock *pLock){
1405 int rc;
drh3cb93392011-03-12 18:10:44 +00001406 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001407 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001408 assert( pInode!=0 );
drh50358ad2015-12-02 01:04:33 +00001409 if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
drh3cb93392011-03-12 18:10:44 +00001410 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001411 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001412 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001413 lock.l_whence = SEEK_SET;
1414 lock.l_start = SHARED_FIRST;
1415 lock.l_len = SHARED_SIZE;
1416 lock.l_type = F_WRLCK;
1417 rc = osFcntl(pFile->h, F_SETLK, &lock);
1418 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001419 pInode->bProcessLock = 1;
1420 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001421 }else{
1422 rc = 0;
1423 }
1424 }else{
1425 rc = osFcntl(pFile->h, F_SETLK, pLock);
1426 }
1427 return rc;
1428}
1429
1430/*
drh308c2a52010-05-14 11:30:18 +00001431** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001432** of the following:
1433**
drh2ac3ee92004-06-07 16:27:46 +00001434** (1) SHARED_LOCK
1435** (2) RESERVED_LOCK
1436** (3) PENDING_LOCK
1437** (4) EXCLUSIVE_LOCK
1438**
drhb3e04342004-06-08 00:47:47 +00001439** Sometimes when requesting one lock state, additional lock states
1440** are inserted in between. The locking might fail on one of the later
1441** transitions leaving the lock state different from what it started but
1442** still short of its goal. The following chart shows the allowed
1443** transitions and the inserted intermediate states:
1444**
1445** UNLOCKED -> SHARED
1446** SHARED -> RESERVED
1447** SHARED -> (PENDING) -> EXCLUSIVE
1448** RESERVED -> (PENDING) -> EXCLUSIVE
1449** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001450**
drha6abd042004-06-09 17:37:22 +00001451** This routine will only increase a lock. Use the sqlite3OsUnlock()
1452** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001453*/
drh308c2a52010-05-14 11:30:18 +00001454static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001455 /* The following describes the implementation of the various locks and
1456 ** lock transitions in terms of the POSIX advisory shared and exclusive
1457 ** lock primitives (called read-locks and write-locks below, to avoid
1458 ** confusion with SQLite lock names). The algorithms are complicated
1459 ** slightly in order to be compatible with windows systems simultaneously
1460 ** accessing the same database file, in case that is ever required.
1461 **
1462 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1463 ** byte', each single bytes at well known offsets, and the 'shared byte
1464 ** range', a range of 510 bytes at a well known offset.
1465 **
1466 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1467 ** byte'. If this is successful, a random byte from the 'shared byte
1468 ** range' is read-locked and the lock on the 'pending byte' released.
1469 **
danielk197790ba3bd2004-06-25 08:32:25 +00001470 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1471 ** A RESERVED lock is implemented by grabbing a write-lock on the
1472 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001473 **
1474 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001475 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1476 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1477 ** obtained, but existing SHARED locks are allowed to persist. A process
1478 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1479 ** This property is used by the algorithm for rolling back a journal file
1480 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001481 **
danielk197790ba3bd2004-06-25 08:32:25 +00001482 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1483 ** implemented by obtaining a write-lock on the entire 'shared byte
1484 ** range'. Since all other locks require a read-lock on one of the bytes
1485 ** within this range, this ensures that no other locks are held on the
1486 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001487 **
1488 ** The reason a single byte cannot be used instead of the 'shared byte
1489 ** range' is that some versions of windows do not support read-locks. By
1490 ** locking a random byte from a range, concurrent SHARED locks may exist
1491 ** even if the locking primitive used is always a write-lock.
1492 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001493 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001494 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001495 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001496 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001497 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001498
drh054889e2005-11-30 03:20:31 +00001499 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001500 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1501 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh91eb93c2015-03-03 19:56:20 +00001502 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001503 osGetpid(0)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001504
1505 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001506 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001507 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001508 */
drh308c2a52010-05-14 11:30:18 +00001509 if( pFile->eFileLock>=eFileLock ){
1510 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1511 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001512 return SQLITE_OK;
1513 }
1514
drh0c2694b2009-09-03 16:23:44 +00001515 /* Make sure the locking sequence is correct.
1516 ** (1) We never move from unlocked to anything higher than shared lock.
1517 ** (2) SQLite never explicitly requests a pendig lock.
1518 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001519 */
drh308c2a52010-05-14 11:30:18 +00001520 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1521 assert( eFileLock!=PENDING_LOCK );
1522 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001523
drh8af6c222010-05-14 12:43:01 +00001524 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001525 */
drh6c7d5c52008-11-21 20:32:33 +00001526 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001527 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001528
danielk1977ad94b582007-08-20 06:44:22 +00001529 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001530 ** handle that precludes the requested lock, return BUSY.
1531 */
drh8af6c222010-05-14 12:43:01 +00001532 if( (pFile->eFileLock!=pInode->eFileLock &&
1533 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001534 ){
1535 rc = SQLITE_BUSY;
1536 goto end_lock;
1537 }
1538
1539 /* If a SHARED lock is requested, and some thread using this PID already
1540 ** has a SHARED or RESERVED lock, then increment reference counts and
1541 ** return SQLITE_OK.
1542 */
drh308c2a52010-05-14 11:30:18 +00001543 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001544 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001545 assert( eFileLock==SHARED_LOCK );
1546 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001547 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001548 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001549 pInode->nShared++;
1550 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001551 goto end_lock;
1552 }
1553
danielk19779a1d0ab2004-06-01 14:09:28 +00001554
drh3cde3bb2004-06-12 02:17:14 +00001555 /* A PENDING lock is needed before acquiring a SHARED lock and before
1556 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1557 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001558 */
drh0c2694b2009-09-03 16:23:44 +00001559 lock.l_len = 1L;
1560 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001561 if( eFileLock==SHARED_LOCK
1562 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001563 ){
drh308c2a52010-05-14 11:30:18 +00001564 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001565 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001566 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001567 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001568 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001569 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001570 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001571 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001572 goto end_lock;
1573 }
drh3cde3bb2004-06-12 02:17:14 +00001574 }
1575
1576
1577 /* If control gets to this point, then actually go ahead and make
1578 ** operating system calls for the specified lock.
1579 */
drh308c2a52010-05-14 11:30:18 +00001580 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001581 assert( pInode->nShared==0 );
1582 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001583 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001584
drh2ac3ee92004-06-07 16:27:46 +00001585 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001586 lock.l_start = SHARED_FIRST;
1587 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001588 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001589 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001590 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001591 }
dan661d71a2011-03-30 19:08:03 +00001592
drh2ac3ee92004-06-07 16:27:46 +00001593 /* Drop the temporary PENDING lock */
1594 lock.l_start = PENDING_BYTE;
1595 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001596 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001597 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1598 /* This could happen with a network mount */
1599 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001600 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001601 }
dan661d71a2011-03-30 19:08:03 +00001602
1603 if( rc ){
1604 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001605 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001606 }
dan661d71a2011-03-30 19:08:03 +00001607 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001608 }else{
drh308c2a52010-05-14 11:30:18 +00001609 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001610 pInode->nLock++;
1611 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001612 }
drh8af6c222010-05-14 12:43:01 +00001613 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001614 /* We are trying for an exclusive lock but another thread in this
1615 ** same process is still holding a shared lock. */
1616 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001617 }else{
drh3cde3bb2004-06-12 02:17:14 +00001618 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001619 ** assumed that there is a SHARED or greater lock on the file
1620 ** already.
1621 */
drh308c2a52010-05-14 11:30:18 +00001622 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001623 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001624
1625 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1626 if( eFileLock==RESERVED_LOCK ){
1627 lock.l_start = RESERVED_BYTE;
1628 lock.l_len = 1L;
1629 }else{
1630 lock.l_start = SHARED_FIRST;
1631 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001632 }
dan661d71a2011-03-30 19:08:03 +00001633
1634 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001635 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001636 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001637 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001638 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001639 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001640 }
drhbbd42a62004-05-22 17:41:58 +00001641 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001642
drh8f941bc2009-01-14 23:03:40 +00001643
drhd3d8c042012-05-29 17:02:40 +00001644#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001645 /* Set up the transaction-counter change checking flags when
1646 ** transitioning from a SHARED to a RESERVED lock. The change
1647 ** from SHARED to RESERVED marks the beginning of a normal
1648 ** write operation (not a hot journal rollback).
1649 */
1650 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001651 && pFile->eFileLock<=SHARED_LOCK
1652 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001653 ){
1654 pFile->transCntrChng = 0;
1655 pFile->dbUpdate = 0;
1656 pFile->inNormalWrite = 1;
1657 }
1658#endif
1659
1660
danielk1977ecb2a962004-06-02 06:30:16 +00001661 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001662 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001663 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001664 }else if( eFileLock==EXCLUSIVE_LOCK ){
1665 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001666 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001667 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001668
1669end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001670 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001671 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1672 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001673 return rc;
1674}
1675
1676/*
dan08da86a2009-08-21 17:18:03 +00001677** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001678** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001679*/
1680static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001681 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001682 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001683 p->pNext = pInode->pUnused;
1684 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001685 pFile->h = -1;
1686 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001687}
1688
1689/*
drh308c2a52010-05-14 11:30:18 +00001690** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001691** must be either NO_LOCK or SHARED_LOCK.
1692**
1693** If the locking level of the file descriptor is already at or below
1694** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001695**
1696** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1697** the byte range is divided into 2 parts and the first part is unlocked then
1698** set to a read lock, then the other part is simply unlocked. This works
1699** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1700** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001701*/
drha7e61d82011-03-12 17:02:57 +00001702static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001703 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001704 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001705 struct flock lock;
1706 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001707
drh054889e2005-11-30 03:20:31 +00001708 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001709 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001710 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001711 osGetpid(0)));
drha6abd042004-06-09 17:37:22 +00001712
drh308c2a52010-05-14 11:30:18 +00001713 assert( eFileLock<=SHARED_LOCK );
1714 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001715 return SQLITE_OK;
1716 }
drh6c7d5c52008-11-21 20:32:33 +00001717 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001718 pInode = pFile->pInode;
1719 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001720 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001721 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001722
drhd3d8c042012-05-29 17:02:40 +00001723#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001724 /* When reducing a lock such that other processes can start
1725 ** reading the database file again, make sure that the
1726 ** transaction counter was updated if any part of the database
1727 ** file changed. If the transaction counter is not updated,
1728 ** other connections to the same file might not realize that
1729 ** the file has changed and hence might not know to flush their
1730 ** cache. The use of a stale cache can lead to database corruption.
1731 */
drh8f941bc2009-01-14 23:03:40 +00001732 pFile->inNormalWrite = 0;
1733#endif
1734
drh7ed97b92010-01-20 13:07:21 +00001735 /* downgrading to a shared lock on NFS involves clearing the write lock
1736 ** before establishing the readlock - to avoid a race condition we downgrade
1737 ** the lock in 2 blocks, so that part of the range will be covered by a
1738 ** write lock until the rest is covered by a read lock:
1739 ** 1: [WWWWW]
1740 ** 2: [....W]
1741 ** 3: [RRRRW]
1742 ** 4: [RRRR.]
1743 */
drh308c2a52010-05-14 11:30:18 +00001744 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001745#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001746 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001747 assert( handleNFSUnlock==0 );
1748#endif
1749#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001750 if( handleNFSUnlock ){
drha712b4b2015-02-19 16:12:04 +00001751 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001752 off_t divSize = SHARED_SIZE - 1;
1753
1754 lock.l_type = F_UNLCK;
1755 lock.l_whence = SEEK_SET;
1756 lock.l_start = SHARED_FIRST;
1757 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001758 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001759 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001760 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001761 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001762 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001763 }
drh7ed97b92010-01-20 13:07:21 +00001764 lock.l_type = F_RDLCK;
1765 lock.l_whence = SEEK_SET;
1766 lock.l_start = SHARED_FIRST;
1767 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001768 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001769 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001770 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1771 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001772 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001773 }
1774 goto end_unlock;
1775 }
1776 lock.l_type = F_UNLCK;
1777 lock.l_whence = SEEK_SET;
1778 lock.l_start = SHARED_FIRST+divSize;
1779 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001780 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001781 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001782 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001783 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001784 goto end_unlock;
1785 }
drh30f776f2011-02-25 03:25:07 +00001786 }else
1787#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1788 {
drh7ed97b92010-01-20 13:07:21 +00001789 lock.l_type = F_RDLCK;
1790 lock.l_whence = SEEK_SET;
1791 lock.l_start = SHARED_FIRST;
1792 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001793 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001794 /* In theory, the call to unixFileLock() cannot fail because another
1795 ** process is holding an incompatible lock. If it does, this
1796 ** indicates that the other process is not following the locking
1797 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1798 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1799 ** an assert to fail). */
1800 rc = SQLITE_IOERR_RDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001801 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00001802 goto end_unlock;
1803 }
drh9c105bb2004-10-02 20:38:28 +00001804 }
1805 }
drhbbd42a62004-05-22 17:41:58 +00001806 lock.l_type = F_UNLCK;
1807 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001808 lock.l_start = PENDING_BYTE;
1809 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001810 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001811 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001812 }else{
danea83bc62011-04-01 11:56:32 +00001813 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001814 storeLastErrno(pFile, errno);
drhcd731cf2009-03-28 23:23:02 +00001815 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001816 }
drhbbd42a62004-05-22 17:41:58 +00001817 }
drh308c2a52010-05-14 11:30:18 +00001818 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001819 /* Decrement the shared lock counter. Release the lock using an
1820 ** OS call only when all threads in this same process have released
1821 ** the lock.
1822 */
drh8af6c222010-05-14 12:43:01 +00001823 pInode->nShared--;
1824 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001825 lock.l_type = F_UNLCK;
1826 lock.l_whence = SEEK_SET;
1827 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001828 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001829 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001830 }else{
danea83bc62011-04-01 11:56:32 +00001831 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001832 storeLastErrno(pFile, errno);
drh8af6c222010-05-14 12:43:01 +00001833 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001834 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001835 }
drha6abd042004-06-09 17:37:22 +00001836 }
1837
drhbbd42a62004-05-22 17:41:58 +00001838 /* Decrement the count of locks against this same file. When the
1839 ** count reaches zero, close any other file descriptors whose close
1840 ** was deferred because of outstanding locks.
1841 */
drh8af6c222010-05-14 12:43:01 +00001842 pInode->nLock--;
1843 assert( pInode->nLock>=0 );
1844 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001845 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001846 }
1847 }
drhf2f105d2012-08-20 15:53:54 +00001848
aswift5b1a2562008-08-22 00:22:35 +00001849end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001850 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001851 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001852 return rc;
drhbbd42a62004-05-22 17:41:58 +00001853}
1854
1855/*
drh308c2a52010-05-14 11:30:18 +00001856** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001857** must be either NO_LOCK or SHARED_LOCK.
1858**
1859** If the locking level of the file descriptor is already at or below
1860** the requested locking level, this routine is a no-op.
1861*/
drh308c2a52010-05-14 11:30:18 +00001862static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00001863#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00001864 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00001865#endif
drha7e61d82011-03-12 17:02:57 +00001866 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001867}
1868
mistachkine98844f2013-08-24 00:59:24 +00001869#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001870static int unixMapfile(unixFile *pFd, i64 nByte);
1871static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00001872#endif
danf23da962013-03-23 21:00:41 +00001873
drh7ed97b92010-01-20 13:07:21 +00001874/*
danielk1977e339d652008-06-28 11:23:00 +00001875** This function performs the parts of the "close file" operation
1876** common to all locking schemes. It closes the directory and file
1877** handles, if they are valid, and sets all fields of the unixFile
1878** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001879**
1880** It is *not* necessary to hold the mutex when this routine is called,
1881** even on VxWorks. A mutex will be acquired on VxWorks by the
1882** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001883*/
1884static int closeUnixFile(sqlite3_file *id){
1885 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00001886#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001887 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00001888#endif
dan661d71a2011-03-30 19:08:03 +00001889 if( pFile->h>=0 ){
1890 robust_close(pFile, pFile->h, __LINE__);
1891 pFile->h = -1;
1892 }
1893#if OS_VXWORKS
1894 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001895 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001896 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001897 }
1898 vxworksReleaseFileId(pFile->pId);
1899 pFile->pId = 0;
1900 }
1901#endif
drh0bdbc902014-06-16 18:35:06 +00001902#ifdef SQLITE_UNLINK_AFTER_CLOSE
1903 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
1904 osUnlink(pFile->zPath);
1905 sqlite3_free(*(char**)&pFile->zPath);
1906 pFile->zPath = 0;
1907 }
1908#endif
dan661d71a2011-03-30 19:08:03 +00001909 OSTRACE(("CLOSE %-3d\n", pFile->h));
1910 OpenCounter(-1);
1911 sqlite3_free(pFile->pUnused);
1912 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001913 return SQLITE_OK;
1914}
1915
1916/*
danielk1977e3026632004-06-22 11:29:02 +00001917** Close a file.
1918*/
danielk197762079062007-08-15 17:08:46 +00001919static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001920 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001921 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00001922 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00001923 unixUnlock(id, NO_LOCK);
1924 unixEnterMutex();
1925
1926 /* unixFile.pInode is always valid here. Otherwise, a different close
1927 ** routine (e.g. nolockClose()) would be called instead.
1928 */
1929 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1930 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1931 /* If there are outstanding locks, do not actually close the file just
1932 ** yet because that would clear those locks. Instead, add the file
1933 ** descriptor to pInode->pUnused list. It will be automatically closed
1934 ** when the last lock is cleared.
1935 */
1936 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001937 }
dan661d71a2011-03-30 19:08:03 +00001938 releaseInodeInfo(pFile);
1939 rc = closeUnixFile(id);
1940 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001941 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001942}
1943
drh734c9862008-11-28 15:37:20 +00001944/************** End of the posix advisory lock implementation *****************
1945******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001946
drh734c9862008-11-28 15:37:20 +00001947/******************************************************************************
1948****************************** No-op Locking **********************************
1949**
1950** Of the various locking implementations available, this is by far the
1951** simplest: locking is ignored. No attempt is made to lock the database
1952** file for reading or writing.
1953**
1954** This locking mode is appropriate for use on read-only databases
1955** (ex: databases that are burned into CD-ROM, for example.) It can
1956** also be used if the application employs some external mechanism to
1957** prevent simultaneous access of the same database by two or more
1958** database connections. But there is a serious risk of database
1959** corruption if this locking mode is used in situations where multiple
1960** database connections are accessing the same database file at the same
1961** time and one or more of those connections are writing.
1962*/
drhbfe66312006-10-03 17:40:40 +00001963
drh734c9862008-11-28 15:37:20 +00001964static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1965 UNUSED_PARAMETER(NotUsed);
1966 *pResOut = 0;
1967 return SQLITE_OK;
1968}
drh734c9862008-11-28 15:37:20 +00001969static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1970 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1971 return SQLITE_OK;
1972}
drh734c9862008-11-28 15:37:20 +00001973static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1974 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1975 return SQLITE_OK;
1976}
1977
1978/*
drh9b35ea62008-11-29 02:20:26 +00001979** Close the file.
drh734c9862008-11-28 15:37:20 +00001980*/
1981static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001982 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001983}
1984
1985/******************* End of the no-op lock implementation *********************
1986******************************************************************************/
1987
1988/******************************************************************************
1989************************* Begin dot-file Locking ******************************
1990**
mistachkin48864df2013-03-21 21:20:32 +00001991** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00001992** files (really a directory) to control access to the database. This works
1993** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00001994**
1995** (1) There is zero concurrency. A single reader blocks all other
1996** connections from reading or writing the database.
1997**
1998** (2) An application crash or power loss can leave stale lock files
1999** sitting around that need to be cleared manually.
2000**
2001** Nevertheless, a dotlock is an appropriate locking mode for use if no
2002** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002003**
drh9ef6bc42011-11-04 02:24:02 +00002004** Dotfile locking works by creating a subdirectory in the same directory as
2005** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002006** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002007** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002008*/
2009
2010/*
2011** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002012** lock directory.
drh734c9862008-11-28 15:37:20 +00002013*/
2014#define DOTLOCK_SUFFIX ".lock"
2015
drh7708e972008-11-29 00:56:52 +00002016/*
2017** This routine checks if there is a RESERVED lock held on the specified
2018** file by this or any other process. If such a lock is held, set *pResOut
2019** to a non-zero value otherwise *pResOut is set to zero. The return value
2020** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2021**
2022** In dotfile locking, either a lock exists or it does not. So in this
2023** variation of CheckReservedLock(), *pResOut is set to true if any lock
2024** is held on the file and false if the file is unlocked.
2025*/
drh734c9862008-11-28 15:37:20 +00002026static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2027 int rc = SQLITE_OK;
2028 int reserved = 0;
2029 unixFile *pFile = (unixFile*)id;
2030
2031 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2032
2033 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00002034 reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
drh308c2a52010-05-14 11:30:18 +00002035 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002036 *pResOut = reserved;
2037 return rc;
2038}
2039
drh7708e972008-11-29 00:56:52 +00002040/*
drh308c2a52010-05-14 11:30:18 +00002041** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002042** of the following:
2043**
2044** (1) SHARED_LOCK
2045** (2) RESERVED_LOCK
2046** (3) PENDING_LOCK
2047** (4) EXCLUSIVE_LOCK
2048**
2049** Sometimes when requesting one lock state, additional lock states
2050** are inserted in between. The locking might fail on one of the later
2051** transitions leaving the lock state different from what it started but
2052** still short of its goal. The following chart shows the allowed
2053** transitions and the inserted intermediate states:
2054**
2055** UNLOCKED -> SHARED
2056** SHARED -> RESERVED
2057** SHARED -> (PENDING) -> EXCLUSIVE
2058** RESERVED -> (PENDING) -> EXCLUSIVE
2059** PENDING -> EXCLUSIVE
2060**
2061** This routine will only increase a lock. Use the sqlite3OsUnlock()
2062** routine to lower a locking level.
2063**
2064** With dotfile locking, we really only support state (4): EXCLUSIVE.
2065** But we track the other locking levels internally.
2066*/
drh308c2a52010-05-14 11:30:18 +00002067static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002068 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002069 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002070 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002071
drh7708e972008-11-29 00:56:52 +00002072
2073 /* If we have any lock, then the lock file already exists. All we have
2074 ** to do is adjust our internal record of the lock level.
2075 */
drh308c2a52010-05-14 11:30:18 +00002076 if( pFile->eFileLock > NO_LOCK ){
2077 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002078 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002079#ifdef HAVE_UTIME
2080 utime(zLockFile, NULL);
2081#else
drh734c9862008-11-28 15:37:20 +00002082 utimes(zLockFile, NULL);
2083#endif
drh7708e972008-11-29 00:56:52 +00002084 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002085 }
2086
2087 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002088 rc = osMkdir(zLockFile, 0777);
2089 if( rc<0 ){
2090 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002091 int tErrno = errno;
2092 if( EEXIST == tErrno ){
2093 rc = SQLITE_BUSY;
2094 } else {
2095 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drha8de1e12015-11-30 00:05:39 +00002096 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00002097 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002098 }
2099 }
drh7708e972008-11-29 00:56:52 +00002100 return rc;
drh734c9862008-11-28 15:37:20 +00002101 }
drh734c9862008-11-28 15:37:20 +00002102
2103 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002104 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002105 return rc;
2106}
2107
drh7708e972008-11-29 00:56:52 +00002108/*
drh308c2a52010-05-14 11:30:18 +00002109** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002110** must be either NO_LOCK or SHARED_LOCK.
2111**
2112** If the locking level of the file descriptor is already at or below
2113** the requested locking level, this routine is a no-op.
2114**
2115** When the locking level reaches NO_LOCK, delete the lock file.
2116*/
drh308c2a52010-05-14 11:30:18 +00002117static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002118 unixFile *pFile = (unixFile*)id;
2119 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002120 int rc;
drh734c9862008-11-28 15:37:20 +00002121
2122 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002123 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002124 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002125 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002126
2127 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002128 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002129 return SQLITE_OK;
2130 }
drh7708e972008-11-29 00:56:52 +00002131
2132 /* To downgrade to shared, simply update our internal notion of the
2133 ** lock state. No need to mess with the file on disk.
2134 */
drh308c2a52010-05-14 11:30:18 +00002135 if( eFileLock==SHARED_LOCK ){
2136 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002137 return SQLITE_OK;
2138 }
2139
drh7708e972008-11-29 00:56:52 +00002140 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002141 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002142 rc = osRmdir(zLockFile);
drh9ef6bc42011-11-04 02:24:02 +00002143 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002144 int tErrno = errno;
drha8de1e12015-11-30 00:05:39 +00002145 if( tErrno==ENOENT ){
2146 rc = SQLITE_OK;
2147 }else{
danea83bc62011-04-01 11:56:32 +00002148 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002149 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002150 }
2151 return rc;
2152 }
drh308c2a52010-05-14 11:30:18 +00002153 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002154 return SQLITE_OK;
2155}
2156
2157/*
drh9b35ea62008-11-29 02:20:26 +00002158** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002159*/
2160static int dotlockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002161 unixFile *pFile = (unixFile*)id;
2162 assert( id!=0 );
2163 dotlockUnlock(id, NO_LOCK);
2164 sqlite3_free(pFile->lockingContext);
2165 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002166}
2167/****************** End of the dot-file lock implementation *******************
2168******************************************************************************/
2169
2170/******************************************************************************
2171************************** Begin flock Locking ********************************
2172**
2173** Use the flock() system call to do file locking.
2174**
drh6b9d6dd2008-12-03 19:34:47 +00002175** flock() locking is like dot-file locking in that the various
2176** fine-grain locking levels supported by SQLite are collapsed into
2177** a single exclusive lock. In other words, SHARED, RESERVED, and
2178** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2179** still works when you do this, but concurrency is reduced since
2180** only a single process can be reading the database at a time.
2181**
drhe89b2912015-03-03 20:42:01 +00002182** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
drh734c9862008-11-28 15:37:20 +00002183*/
drhe89b2912015-03-03 20:42:01 +00002184#if SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002185
drh6b9d6dd2008-12-03 19:34:47 +00002186/*
drhff812312011-02-23 13:33:46 +00002187** Retry flock() calls that fail with EINTR
2188*/
2189#ifdef EINTR
2190static int robust_flock(int fd, int op){
2191 int rc;
2192 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2193 return rc;
2194}
2195#else
drh5c819272011-02-23 14:00:12 +00002196# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002197#endif
2198
2199
2200/*
drh6b9d6dd2008-12-03 19:34:47 +00002201** This routine checks if there is a RESERVED lock held on the specified
2202** file by this or any other process. If such a lock is held, set *pResOut
2203** to a non-zero value otherwise *pResOut is set to zero. The return value
2204** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2205*/
drh734c9862008-11-28 15:37:20 +00002206static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2207 int rc = SQLITE_OK;
2208 int reserved = 0;
2209 unixFile *pFile = (unixFile*)id;
2210
2211 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2212
2213 assert( pFile );
2214
2215 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002216 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002217 reserved = 1;
2218 }
2219
2220 /* Otherwise see if some other process holds it. */
2221 if( !reserved ){
2222 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002223 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002224 if( !lrc ){
2225 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002226 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002227 if ( lrc ) {
2228 int tErrno = errno;
2229 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002230 lrc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00002231 storeLastErrno(pFile, tErrno);
2232 rc = lrc;
drh734c9862008-11-28 15:37:20 +00002233 }
2234 } else {
2235 int tErrno = errno;
2236 reserved = 1;
2237 /* someone else might have it reserved */
2238 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2239 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002240 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002241 rc = lrc;
2242 }
2243 }
2244 }
drh308c2a52010-05-14 11:30:18 +00002245 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002246
2247#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2248 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2249 rc = SQLITE_OK;
2250 reserved=1;
2251 }
2252#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2253 *pResOut = reserved;
2254 return rc;
2255}
2256
drh6b9d6dd2008-12-03 19:34:47 +00002257/*
drh308c2a52010-05-14 11:30:18 +00002258** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002259** of the following:
2260**
2261** (1) SHARED_LOCK
2262** (2) RESERVED_LOCK
2263** (3) PENDING_LOCK
2264** (4) EXCLUSIVE_LOCK
2265**
2266** Sometimes when requesting one lock state, additional lock states
2267** are inserted in between. The locking might fail on one of the later
2268** transitions leaving the lock state different from what it started but
2269** still short of its goal. The following chart shows the allowed
2270** transitions and the inserted intermediate states:
2271**
2272** UNLOCKED -> SHARED
2273** SHARED -> RESERVED
2274** SHARED -> (PENDING) -> EXCLUSIVE
2275** RESERVED -> (PENDING) -> EXCLUSIVE
2276** PENDING -> EXCLUSIVE
2277**
2278** flock() only really support EXCLUSIVE locks. We track intermediate
2279** lock states in the sqlite3_file structure, but all locks SHARED or
2280** above are really EXCLUSIVE locks and exclude all other processes from
2281** access the file.
2282**
2283** This routine will only increase a lock. Use the sqlite3OsUnlock()
2284** routine to lower a locking level.
2285*/
drh308c2a52010-05-14 11:30:18 +00002286static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002287 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002288 unixFile *pFile = (unixFile*)id;
2289
2290 assert( pFile );
2291
2292 /* if we already have a lock, it is exclusive.
2293 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002294 if (pFile->eFileLock > NO_LOCK) {
2295 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002296 return SQLITE_OK;
2297 }
2298
2299 /* grab an exclusive lock */
2300
drhff812312011-02-23 13:33:46 +00002301 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002302 int tErrno = errno;
2303 /* didn't get, must be busy */
2304 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2305 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002306 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002307 }
2308 } else {
2309 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002310 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002311 }
drh308c2a52010-05-14 11:30:18 +00002312 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2313 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002314#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2315 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2316 rc = SQLITE_BUSY;
2317 }
2318#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2319 return rc;
2320}
2321
drh6b9d6dd2008-12-03 19:34:47 +00002322
2323/*
drh308c2a52010-05-14 11:30:18 +00002324** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002325** must be either NO_LOCK or SHARED_LOCK.
2326**
2327** If the locking level of the file descriptor is already at or below
2328** the requested locking level, this routine is a no-op.
2329*/
drh308c2a52010-05-14 11:30:18 +00002330static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002331 unixFile *pFile = (unixFile*)id;
2332
2333 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002334 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002335 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002336 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002337
2338 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002339 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002340 return SQLITE_OK;
2341 }
2342
2343 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002344 if (eFileLock==SHARED_LOCK) {
2345 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002346 return SQLITE_OK;
2347 }
2348
2349 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002350 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002351#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002352 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002353#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002354 return SQLITE_IOERR_UNLOCK;
2355 }else{
drh308c2a52010-05-14 11:30:18 +00002356 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002357 return SQLITE_OK;
2358 }
2359}
2360
2361/*
2362** Close a file.
2363*/
2364static int flockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002365 assert( id!=0 );
2366 flockUnlock(id, NO_LOCK);
2367 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002368}
2369
2370#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2371
2372/******************* End of the flock lock implementation *********************
2373******************************************************************************/
2374
2375/******************************************************************************
2376************************ Begin Named Semaphore Locking ************************
2377**
2378** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002379**
2380** Semaphore locking is like dot-lock and flock in that it really only
2381** supports EXCLUSIVE locking. Only a single process can read or write
2382** the database file at a time. This reduces potential concurrency, but
2383** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002384*/
2385#if OS_VXWORKS
2386
drh6b9d6dd2008-12-03 19:34:47 +00002387/*
2388** This routine checks if there is a RESERVED lock held on the specified
2389** file by this or any other process. If such a lock is held, set *pResOut
2390** to a non-zero value otherwise *pResOut is set to zero. The return value
2391** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2392*/
drh8cd5b252015-03-02 22:06:43 +00002393static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
drh734c9862008-11-28 15:37:20 +00002394 int rc = SQLITE_OK;
2395 int reserved = 0;
2396 unixFile *pFile = (unixFile*)id;
2397
2398 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2399
2400 assert( pFile );
2401
2402 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002403 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002404 reserved = 1;
2405 }
2406
2407 /* Otherwise see if some other process holds it. */
2408 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002409 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002410
2411 if( sem_trywait(pSem)==-1 ){
2412 int tErrno = errno;
2413 if( EAGAIN != tErrno ){
2414 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
drh4bf66fd2015-02-19 02:43:02 +00002415 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002416 } else {
2417 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002418 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002419 }
2420 }else{
2421 /* we could have it if we want it */
2422 sem_post(pSem);
2423 }
2424 }
drh308c2a52010-05-14 11:30:18 +00002425 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002426
2427 *pResOut = reserved;
2428 return rc;
2429}
2430
drh6b9d6dd2008-12-03 19:34:47 +00002431/*
drh308c2a52010-05-14 11:30:18 +00002432** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002433** of the following:
2434**
2435** (1) SHARED_LOCK
2436** (2) RESERVED_LOCK
2437** (3) PENDING_LOCK
2438** (4) EXCLUSIVE_LOCK
2439**
2440** Sometimes when requesting one lock state, additional lock states
2441** are inserted in between. The locking might fail on one of the later
2442** transitions leaving the lock state different from what it started but
2443** still short of its goal. The following chart shows the allowed
2444** transitions and the inserted intermediate states:
2445**
2446** UNLOCKED -> SHARED
2447** SHARED -> RESERVED
2448** SHARED -> (PENDING) -> EXCLUSIVE
2449** RESERVED -> (PENDING) -> EXCLUSIVE
2450** PENDING -> EXCLUSIVE
2451**
2452** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2453** lock states in the sqlite3_file structure, but all locks SHARED or
2454** above are really EXCLUSIVE locks and exclude all other processes from
2455** access the file.
2456**
2457** This routine will only increase a lock. Use the sqlite3OsUnlock()
2458** routine to lower a locking level.
2459*/
drh8cd5b252015-03-02 22:06:43 +00002460static int semXLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002461 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002462 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002463 int rc = SQLITE_OK;
2464
2465 /* if we already have a lock, it is exclusive.
2466 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002467 if (pFile->eFileLock > NO_LOCK) {
2468 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002469 rc = SQLITE_OK;
2470 goto sem_end_lock;
2471 }
2472
2473 /* lock semaphore now but bail out when already locked. */
2474 if( sem_trywait(pSem)==-1 ){
2475 rc = SQLITE_BUSY;
2476 goto sem_end_lock;
2477 }
2478
2479 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002480 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002481
2482 sem_end_lock:
2483 return rc;
2484}
2485
drh6b9d6dd2008-12-03 19:34:47 +00002486/*
drh308c2a52010-05-14 11:30:18 +00002487** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002488** must be either NO_LOCK or SHARED_LOCK.
2489**
2490** If the locking level of the file descriptor is already at or below
2491** the requested locking level, this routine is a no-op.
2492*/
drh8cd5b252015-03-02 22:06:43 +00002493static int semXUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002494 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002495 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002496
2497 assert( pFile );
2498 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002499 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002500 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002501 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002502
2503 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002504 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002505 return SQLITE_OK;
2506 }
2507
2508 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002509 if (eFileLock==SHARED_LOCK) {
2510 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002511 return SQLITE_OK;
2512 }
2513
2514 /* no, really unlock. */
2515 if ( sem_post(pSem)==-1 ) {
2516 int rc, tErrno = errno;
2517 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2518 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002519 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002520 }
2521 return rc;
2522 }
drh308c2a52010-05-14 11:30:18 +00002523 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002524 return SQLITE_OK;
2525}
2526
2527/*
2528 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002529 */
drh8cd5b252015-03-02 22:06:43 +00002530static int semXClose(sqlite3_file *id) {
drh734c9862008-11-28 15:37:20 +00002531 if( id ){
2532 unixFile *pFile = (unixFile*)id;
drh8cd5b252015-03-02 22:06:43 +00002533 semXUnlock(id, NO_LOCK);
drh734c9862008-11-28 15:37:20 +00002534 assert( pFile );
2535 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002536 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002537 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002538 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002539 }
2540 return SQLITE_OK;
2541}
2542
2543#endif /* OS_VXWORKS */
2544/*
2545** Named semaphore locking is only available on VxWorks.
2546**
2547*************** End of the named semaphore lock implementation ****************
2548******************************************************************************/
2549
2550
2551/******************************************************************************
2552*************************** Begin AFP Locking *********************************
2553**
2554** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2555** on Apple Macintosh computers - both OS9 and OSX.
2556**
2557** Third-party implementations of AFP are available. But this code here
2558** only works on OSX.
2559*/
2560
drhd2cb50b2009-01-09 21:41:17 +00002561#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002562/*
2563** The afpLockingContext structure contains all afp lock specific state
2564*/
drhbfe66312006-10-03 17:40:40 +00002565typedef struct afpLockingContext afpLockingContext;
2566struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002567 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002568 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002569};
2570
2571struct ByteRangeLockPB2
2572{
2573 unsigned long long offset; /* offset to first byte to lock */
2574 unsigned long long length; /* nbr of bytes to lock */
2575 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2576 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2577 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2578 int fd; /* file desc to assoc this lock with */
2579};
2580
drhfd131da2007-08-07 17:13:03 +00002581#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002582
drh6b9d6dd2008-12-03 19:34:47 +00002583/*
2584** This is a utility for setting or clearing a bit-range lock on an
2585** AFP filesystem.
2586**
2587** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2588*/
2589static int afpSetLock(
2590 const char *path, /* Name of the file to be locked or unlocked */
2591 unixFile *pFile, /* Open file descriptor on path */
2592 unsigned long long offset, /* First byte to be locked */
2593 unsigned long long length, /* Number of bytes to lock */
2594 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002595){
drh6b9d6dd2008-12-03 19:34:47 +00002596 struct ByteRangeLockPB2 pb;
2597 int err;
drhbfe66312006-10-03 17:40:40 +00002598
2599 pb.unLockFlag = setLockFlag ? 0 : 1;
2600 pb.startEndFlag = 0;
2601 pb.offset = offset;
2602 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002603 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002604
drh308c2a52010-05-14 11:30:18 +00002605 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002606 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002607 offset, length));
drhbfe66312006-10-03 17:40:40 +00002608 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2609 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002610 int rc;
2611 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002612 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2613 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002614#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2615 rc = SQLITE_BUSY;
2616#else
drh734c9862008-11-28 15:37:20 +00002617 rc = sqliteErrorFromPosixError(tErrno,
2618 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002619#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002620 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002621 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00002622 }
2623 return rc;
drhbfe66312006-10-03 17:40:40 +00002624 } else {
aswift5b1a2562008-08-22 00:22:35 +00002625 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002626 }
2627}
2628
drh6b9d6dd2008-12-03 19:34:47 +00002629/*
2630** This routine checks if there is a RESERVED lock held on the specified
2631** file by this or any other process. If such a lock is held, set *pResOut
2632** to a non-zero value otherwise *pResOut is set to zero. The return value
2633** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2634*/
danielk1977e339d652008-06-28 11:23:00 +00002635static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002636 int rc = SQLITE_OK;
2637 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002638 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002639 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002640
aswift5b1a2562008-08-22 00:22:35 +00002641 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2642
2643 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002644 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002645 if( context->reserved ){
2646 *pResOut = 1;
2647 return SQLITE_OK;
2648 }
drh8af6c222010-05-14 12:43:01 +00002649 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002650
2651 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002652 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002653 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002654 }
2655
2656 /* Otherwise see if some other process holds it.
2657 */
aswift5b1a2562008-08-22 00:22:35 +00002658 if( !reserved ){
2659 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002660 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002661 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002662 /* if we succeeded in taking the reserved lock, unlock it to restore
2663 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002664 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002665 } else {
2666 /* if we failed to get the lock then someone else must have it */
2667 reserved = 1;
2668 }
2669 if( IS_LOCK_ERROR(lrc) ){
2670 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002671 }
2672 }
drhbfe66312006-10-03 17:40:40 +00002673
drh7ed97b92010-01-20 13:07:21 +00002674 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002675 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002676
2677 *pResOut = reserved;
2678 return rc;
drhbfe66312006-10-03 17:40:40 +00002679}
2680
drh6b9d6dd2008-12-03 19:34:47 +00002681/*
drh308c2a52010-05-14 11:30:18 +00002682** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002683** of the following:
2684**
2685** (1) SHARED_LOCK
2686** (2) RESERVED_LOCK
2687** (3) PENDING_LOCK
2688** (4) EXCLUSIVE_LOCK
2689**
2690** Sometimes when requesting one lock state, additional lock states
2691** are inserted in between. The locking might fail on one of the later
2692** transitions leaving the lock state different from what it started but
2693** still short of its goal. The following chart shows the allowed
2694** transitions and the inserted intermediate states:
2695**
2696** UNLOCKED -> SHARED
2697** SHARED -> RESERVED
2698** SHARED -> (PENDING) -> EXCLUSIVE
2699** RESERVED -> (PENDING) -> EXCLUSIVE
2700** PENDING -> EXCLUSIVE
2701**
2702** This routine will only increase a lock. Use the sqlite3OsUnlock()
2703** routine to lower a locking level.
2704*/
drh308c2a52010-05-14 11:30:18 +00002705static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002706 int rc = SQLITE_OK;
2707 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002708 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002709 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002710
2711 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002712 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2713 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh5ac93652015-03-21 20:59:43 +00002714 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
drh339eb0b2008-03-07 15:34:11 +00002715
drhbfe66312006-10-03 17:40:40 +00002716 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002717 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002718 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002719 */
drh308c2a52010-05-14 11:30:18 +00002720 if( pFile->eFileLock>=eFileLock ){
2721 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2722 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002723 return SQLITE_OK;
2724 }
2725
2726 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002727 ** (1) We never move from unlocked to anything higher than shared lock.
2728 ** (2) SQLite never explicitly requests a pendig lock.
2729 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002730 */
drh308c2a52010-05-14 11:30:18 +00002731 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2732 assert( eFileLock!=PENDING_LOCK );
2733 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002734
drh8af6c222010-05-14 12:43:01 +00002735 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002736 */
drh6c7d5c52008-11-21 20:32:33 +00002737 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002738 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002739
2740 /* If some thread using this PID has a lock via a different unixFile*
2741 ** handle that precludes the requested lock, return BUSY.
2742 */
drh8af6c222010-05-14 12:43:01 +00002743 if( (pFile->eFileLock!=pInode->eFileLock &&
2744 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002745 ){
2746 rc = SQLITE_BUSY;
2747 goto afp_end_lock;
2748 }
2749
2750 /* If a SHARED lock is requested, and some thread using this PID already
2751 ** has a SHARED or RESERVED lock, then increment reference counts and
2752 ** return SQLITE_OK.
2753 */
drh308c2a52010-05-14 11:30:18 +00002754 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002755 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002756 assert( eFileLock==SHARED_LOCK );
2757 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002758 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002759 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002760 pInode->nShared++;
2761 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002762 goto afp_end_lock;
2763 }
drhbfe66312006-10-03 17:40:40 +00002764
2765 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002766 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2767 ** be released.
2768 */
drh308c2a52010-05-14 11:30:18 +00002769 if( eFileLock==SHARED_LOCK
2770 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002771 ){
2772 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002773 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002774 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002775 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002776 goto afp_end_lock;
2777 }
2778 }
2779
2780 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002781 ** operating system calls for the specified lock.
2782 */
drh308c2a52010-05-14 11:30:18 +00002783 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002784 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002785 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002786
drh8af6c222010-05-14 12:43:01 +00002787 assert( pInode->nShared==0 );
2788 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002789
2790 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002791 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002792 /* note that the quality of the randomness doesn't matter that much */
2793 lk = random();
drh8af6c222010-05-14 12:43:01 +00002794 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002795 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002796 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002797 if( IS_LOCK_ERROR(lrc1) ){
2798 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002799 }
aswift5b1a2562008-08-22 00:22:35 +00002800 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002801 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002802
aswift5b1a2562008-08-22 00:22:35 +00002803 if( IS_LOCK_ERROR(lrc1) ) {
drh4bf66fd2015-02-19 02:43:02 +00002804 storeLastErrno(pFile, lrc1Errno);
aswift5b1a2562008-08-22 00:22:35 +00002805 rc = lrc1;
2806 goto afp_end_lock;
2807 } else if( IS_LOCK_ERROR(lrc2) ){
2808 rc = lrc2;
2809 goto afp_end_lock;
2810 } else if( lrc1 != SQLITE_OK ) {
2811 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002812 } else {
drh308c2a52010-05-14 11:30:18 +00002813 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002814 pInode->nLock++;
2815 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002816 }
drh8af6c222010-05-14 12:43:01 +00002817 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002818 /* We are trying for an exclusive lock but another thread in this
2819 ** same process is still holding a shared lock. */
2820 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002821 }else{
2822 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2823 ** assumed that there is a SHARED or greater lock on the file
2824 ** already.
2825 */
2826 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002827 assert( 0!=pFile->eFileLock );
2828 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002829 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002830 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002831 if( !failed ){
2832 context->reserved = 1;
2833 }
drhbfe66312006-10-03 17:40:40 +00002834 }
drh308c2a52010-05-14 11:30:18 +00002835 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002836 /* Acquire an EXCLUSIVE lock */
2837
2838 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002839 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002840 */
drh6b9d6dd2008-12-03 19:34:47 +00002841 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002842 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002843 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002844 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002845 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002846 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002847 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002848 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002849 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2850 ** a critical I/O error
2851 */
2852 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2853 SQLITE_IOERR_LOCK;
2854 goto afp_end_lock;
2855 }
2856 }else{
aswift5b1a2562008-08-22 00:22:35 +00002857 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002858 }
2859 }
aswift5b1a2562008-08-22 00:22:35 +00002860 if( failed ){
2861 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002862 }
2863 }
2864
2865 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002866 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002867 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002868 }else if( eFileLock==EXCLUSIVE_LOCK ){
2869 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002870 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002871 }
2872
2873afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002874 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002875 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2876 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002877 return rc;
2878}
2879
2880/*
drh308c2a52010-05-14 11:30:18 +00002881** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002882** must be either NO_LOCK or SHARED_LOCK.
2883**
2884** If the locking level of the file descriptor is already at or below
2885** the requested locking level, this routine is a no-op.
2886*/
drh308c2a52010-05-14 11:30:18 +00002887static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002888 int rc = SQLITE_OK;
2889 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002890 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002891 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2892 int skipShared = 0;
2893#ifdef SQLITE_TEST
2894 int h = pFile->h;
2895#endif
drhbfe66312006-10-03 17:40:40 +00002896
2897 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002898 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002899 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00002900 osGetpid(0)));
aswift5b1a2562008-08-22 00:22:35 +00002901
drh308c2a52010-05-14 11:30:18 +00002902 assert( eFileLock<=SHARED_LOCK );
2903 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002904 return SQLITE_OK;
2905 }
drh6c7d5c52008-11-21 20:32:33 +00002906 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002907 pInode = pFile->pInode;
2908 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002909 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002910 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002911 SimulateIOErrorBenign(1);
2912 SimulateIOError( h=(-1) )
2913 SimulateIOErrorBenign(0);
2914
drhd3d8c042012-05-29 17:02:40 +00002915#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002916 /* When reducing a lock such that other processes can start
2917 ** reading the database file again, make sure that the
2918 ** transaction counter was updated if any part of the database
2919 ** file changed. If the transaction counter is not updated,
2920 ** other connections to the same file might not realize that
2921 ** the file has changed and hence might not know to flush their
2922 ** cache. The use of a stale cache can lead to database corruption.
2923 */
2924 assert( pFile->inNormalWrite==0
2925 || pFile->dbUpdate==0
2926 || pFile->transCntrChng==1 );
2927 pFile->inNormalWrite = 0;
2928#endif
aswiftaebf4132008-11-21 00:10:35 +00002929
drh308c2a52010-05-14 11:30:18 +00002930 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002931 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002932 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002933 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002934 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002935 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2936 } else {
2937 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002938 }
2939 }
drh308c2a52010-05-14 11:30:18 +00002940 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002941 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002942 }
drh308c2a52010-05-14 11:30:18 +00002943 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002944 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2945 if( !rc ){
2946 context->reserved = 0;
2947 }
aswiftaebf4132008-11-21 00:10:35 +00002948 }
drh8af6c222010-05-14 12:43:01 +00002949 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2950 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002951 }
aswiftaebf4132008-11-21 00:10:35 +00002952 }
drh308c2a52010-05-14 11:30:18 +00002953 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002954
drh7ed97b92010-01-20 13:07:21 +00002955 /* Decrement the shared lock counter. Release the lock using an
2956 ** OS call only when all threads in this same process have released
2957 ** the lock.
2958 */
drh8af6c222010-05-14 12:43:01 +00002959 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2960 pInode->nShared--;
2961 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002962 SimulateIOErrorBenign(1);
2963 SimulateIOError( h=(-1) )
2964 SimulateIOErrorBenign(0);
2965 if( !skipShared ){
2966 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2967 }
2968 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002969 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002970 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002971 }
2972 }
2973 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002974 pInode->nLock--;
2975 assert( pInode->nLock>=0 );
2976 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002977 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002978 }
2979 }
drhbfe66312006-10-03 17:40:40 +00002980 }
drh7ed97b92010-01-20 13:07:21 +00002981
drh6c7d5c52008-11-21 20:32:33 +00002982 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002983 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002984 return rc;
2985}
2986
2987/*
drh339eb0b2008-03-07 15:34:11 +00002988** Close a file & cleanup AFP specific locking context
2989*/
danielk1977e339d652008-06-28 11:23:00 +00002990static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002991 int rc = SQLITE_OK;
drha8de1e12015-11-30 00:05:39 +00002992 unixFile *pFile = (unixFile*)id;
2993 assert( id!=0 );
2994 afpUnlock(id, NO_LOCK);
2995 unixEnterMutex();
2996 if( pFile->pInode && pFile->pInode->nLock ){
2997 /* If there are outstanding locks, do not actually close the file just
2998 ** yet because that would clear those locks. Instead, add the file
2999 ** descriptor to pInode->aPending. It will be automatically closed when
3000 ** the last lock is cleared.
3001 */
3002 setPendingFd(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003003 }
drha8de1e12015-11-30 00:05:39 +00003004 releaseInodeInfo(pFile);
3005 sqlite3_free(pFile->lockingContext);
3006 rc = closeUnixFile(id);
3007 unixLeaveMutex();
drh7ed97b92010-01-20 13:07:21 +00003008 return rc;
drhbfe66312006-10-03 17:40:40 +00003009}
3010
drhd2cb50b2009-01-09 21:41:17 +00003011#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003012/*
3013** The code above is the AFP lock implementation. The code is specific
3014** to MacOSX and does not work on other unix platforms. No alternative
3015** is available. If you don't compile for a mac, then the "unix-afp"
3016** VFS is not available.
3017**
3018********************* End of the AFP lock implementation **********************
3019******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003020
drh7ed97b92010-01-20 13:07:21 +00003021/******************************************************************************
3022*************************** Begin NFS Locking ********************************/
3023
3024#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3025/*
drh308c2a52010-05-14 11:30:18 +00003026 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003027 ** must be either NO_LOCK or SHARED_LOCK.
3028 **
3029 ** If the locking level of the file descriptor is already at or below
3030 ** the requested locking level, this routine is a no-op.
3031 */
drh308c2a52010-05-14 11:30:18 +00003032static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003033 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003034}
3035
3036#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3037/*
3038** The code above is the NFS lock implementation. The code is specific
3039** to MacOSX and does not work on other unix platforms. No alternative
3040** is available.
3041**
3042********************* End of the NFS lock implementation **********************
3043******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003044
3045/******************************************************************************
3046**************** Non-locking sqlite3_file methods *****************************
3047**
3048** The next division contains implementations for all methods of the
3049** sqlite3_file object other than the locking methods. The locking
3050** methods were defined in divisions above (one locking method per
3051** division). Those methods that are common to all locking modes
3052** are gather together into this division.
3053*/
drhbfe66312006-10-03 17:40:40 +00003054
3055/*
drh734c9862008-11-28 15:37:20 +00003056** Seek to the offset passed as the second argument, then read cnt
3057** bytes into pBuf. Return the number of bytes actually read.
3058**
3059** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3060** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3061** one system to another. Since SQLite does not define USE_PREAD
peter.d.reid60ec9142014-09-06 16:39:46 +00003062** in any form by default, we will not attempt to define _XOPEN_SOURCE.
drh734c9862008-11-28 15:37:20 +00003063** See tickets #2741 and #2681.
3064**
3065** To avoid stomping the errno value on a failed read the lastErrno value
3066** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003067*/
drh734c9862008-11-28 15:37:20 +00003068static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3069 int got;
drh58024642011-11-07 18:16:00 +00003070 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003071#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003072 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003073#endif
drh734c9862008-11-28 15:37:20 +00003074 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003075 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003076 assert( id->h>2 );
drh58024642011-11-07 18:16:00 +00003077 do{
drh734c9862008-11-28 15:37:20 +00003078#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003079 got = osPread(id->h, pBuf, cnt, offset);
3080 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003081#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003082 got = osPread64(id->h, pBuf, cnt, offset);
3083 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003084#else
drh58024642011-11-07 18:16:00 +00003085 newOffset = lseek(id->h, offset, SEEK_SET);
drhe1818ec2015-12-01 16:21:35 +00003086 SimulateIOError( newOffset = -1 );
3087 if( newOffset<0 ){
3088 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003089 return -1;
drh734c9862008-11-28 15:37:20 +00003090 }
drh58024642011-11-07 18:16:00 +00003091 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003092#endif
drh58024642011-11-07 18:16:00 +00003093 if( got==cnt ) break;
3094 if( got<0 ){
3095 if( errno==EINTR ){ got = 1; continue; }
3096 prior = 0;
drh4bf66fd2015-02-19 02:43:02 +00003097 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003098 break;
3099 }else if( got>0 ){
3100 cnt -= got;
3101 offset += got;
3102 prior += got;
3103 pBuf = (void*)(got + (char*)pBuf);
3104 }
3105 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003106 TIMER_END;
drh58024642011-11-07 18:16:00 +00003107 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3108 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3109 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003110}
3111
3112/*
drh734c9862008-11-28 15:37:20 +00003113** Read data from a file into a buffer. Return SQLITE_OK if all
3114** bytes were read successfully and SQLITE_IOERR if anything goes
3115** wrong.
drh339eb0b2008-03-07 15:34:11 +00003116*/
drh734c9862008-11-28 15:37:20 +00003117static int unixRead(
3118 sqlite3_file *id,
3119 void *pBuf,
3120 int amt,
3121 sqlite3_int64 offset
3122){
dan08da86a2009-08-21 17:18:03 +00003123 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003124 int got;
3125 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003126 assert( offset>=0 );
3127 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003128
dan08da86a2009-08-21 17:18:03 +00003129 /* If this is a database file (not a journal, master-journal or temp
3130 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003131#if 0
dane946c392009-08-22 11:39:46 +00003132 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003133 || offset>=PENDING_BYTE+512
3134 || offset+amt<=PENDING_BYTE
3135 );
dan7c246102010-04-12 19:00:29 +00003136#endif
drh08c6d442009-02-09 17:34:07 +00003137
drh9b4c59f2013-04-15 17:03:42 +00003138#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003139 /* Deal with as much of this read request as possible by transfering
3140 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003141 if( offset<pFile->mmapSize ){
3142 if( offset+amt <= pFile->mmapSize ){
3143 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3144 return SQLITE_OK;
3145 }else{
3146 int nCopy = pFile->mmapSize - offset;
3147 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3148 pBuf = &((u8 *)pBuf)[nCopy];
3149 amt -= nCopy;
3150 offset += nCopy;
3151 }
3152 }
drh6e0b6d52013-04-09 16:19:20 +00003153#endif
danf23da962013-03-23 21:00:41 +00003154
dan08da86a2009-08-21 17:18:03 +00003155 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003156 if( got==amt ){
3157 return SQLITE_OK;
3158 }else if( got<0 ){
3159 /* lastErrno set by seekAndRead */
3160 return SQLITE_IOERR_READ;
3161 }else{
drh4bf66fd2015-02-19 02:43:02 +00003162 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003163 /* Unread parts of the buffer must be zero-filled */
3164 memset(&((char*)pBuf)[got], 0, amt-got);
3165 return SQLITE_IOERR_SHORT_READ;
3166 }
3167}
3168
3169/*
dan47a2b4a2013-04-26 16:09:29 +00003170** Attempt to seek the file-descriptor passed as the first argument to
3171** absolute offset iOff, then attempt to write nBuf bytes of data from
3172** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3173** return the actual number of bytes written (which may be less than
3174** nBuf).
3175*/
3176static int seekAndWriteFd(
3177 int fd, /* File descriptor to write to */
3178 i64 iOff, /* File offset to begin writing at */
3179 const void *pBuf, /* Copy data from this buffer to the file */
3180 int nBuf, /* Size of buffer pBuf in bytes */
3181 int *piErrno /* OUT: Error number if error occurs */
3182){
3183 int rc = 0; /* Value returned by system call */
3184
3185 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003186 assert( fd>2 );
drhe1818ec2015-12-01 16:21:35 +00003187 assert( piErrno!=0 );
dan47a2b4a2013-04-26 16:09:29 +00003188 nBuf &= 0x1ffff;
3189 TIMER_START;
3190
3191#if defined(USE_PREAD)
drh2da47d32015-02-21 00:56:05 +00003192 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
dan47a2b4a2013-04-26 16:09:29 +00003193#elif defined(USE_PREAD64)
drh2da47d32015-02-21 00:56:05 +00003194 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
dan47a2b4a2013-04-26 16:09:29 +00003195#else
3196 do{
3197 i64 iSeek = lseek(fd, iOff, SEEK_SET);
drhe1818ec2015-12-01 16:21:35 +00003198 SimulateIOError( iSeek = -1 );
3199 if( iSeek<0 ){
3200 rc = -1;
3201 break;
dan47a2b4a2013-04-26 16:09:29 +00003202 }
3203 rc = osWrite(fd, pBuf, nBuf);
3204 }while( rc<0 && errno==EINTR );
3205#endif
3206
3207 TIMER_END;
3208 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3209
drhe1818ec2015-12-01 16:21:35 +00003210 if( rc<0 ) *piErrno = errno;
dan47a2b4a2013-04-26 16:09:29 +00003211 return rc;
3212}
3213
3214
3215/*
drh734c9862008-11-28 15:37:20 +00003216** Seek to the offset in id->offset then read cnt bytes into pBuf.
3217** Return the number of bytes actually read. Update the offset.
3218**
3219** To avoid stomping the errno value on a failed write the lastErrno value
3220** is set before returning.
3221*/
3222static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003223 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003224}
3225
3226
3227/*
3228** Write data from a buffer into a file. Return SQLITE_OK on success
3229** or some other error code on failure.
3230*/
3231static int unixWrite(
3232 sqlite3_file *id,
3233 const void *pBuf,
3234 int amt,
3235 sqlite3_int64 offset
3236){
dan08da86a2009-08-21 17:18:03 +00003237 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003238 int wrote = 0;
3239 assert( id );
3240 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003241
dan08da86a2009-08-21 17:18:03 +00003242 /* If this is a database file (not a journal, master-journal or temp
3243 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003244#if 0
dane946c392009-08-22 11:39:46 +00003245 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003246 || offset>=PENDING_BYTE+512
3247 || offset+amt<=PENDING_BYTE
3248 );
dan7c246102010-04-12 19:00:29 +00003249#endif
drh08c6d442009-02-09 17:34:07 +00003250
drhd3d8c042012-05-29 17:02:40 +00003251#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003252 /* If we are doing a normal write to a database file (as opposed to
3253 ** doing a hot-journal rollback or a write to some file other than a
3254 ** normal database file) then record the fact that the database
3255 ** has changed. If the transaction counter is modified, record that
3256 ** fact too.
3257 */
dan08da86a2009-08-21 17:18:03 +00003258 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003259 pFile->dbUpdate = 1; /* The database has been modified */
3260 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003261 int rc;
drh8f941bc2009-01-14 23:03:40 +00003262 char oldCntr[4];
3263 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003264 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003265 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003266 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003267 pFile->transCntrChng = 1; /* The transaction counter has changed */
3268 }
3269 }
3270 }
3271#endif
3272
danfe33e392015-11-17 20:56:06 +00003273#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003274 /* Deal with as much of this write request as possible by transfering
3275 ** data from the memory mapping using memcpy(). */
3276 if( offset<pFile->mmapSize ){
3277 if( offset+amt <= pFile->mmapSize ){
3278 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3279 return SQLITE_OK;
3280 }else{
3281 int nCopy = pFile->mmapSize - offset;
3282 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3283 pBuf = &((u8 *)pBuf)[nCopy];
3284 amt -= nCopy;
3285 offset += nCopy;
3286 }
3287 }
drh6e0b6d52013-04-09 16:19:20 +00003288#endif
drh02bf8b42015-09-01 23:51:53 +00003289
3290 while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
drh734c9862008-11-28 15:37:20 +00003291 amt -= wrote;
3292 offset += wrote;
3293 pBuf = &((char*)pBuf)[wrote];
3294 }
3295 SimulateIOError(( wrote=(-1), amt=1 ));
3296 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003297
drh02bf8b42015-09-01 23:51:53 +00003298 if( amt>wrote ){
drha21b83b2011-04-15 12:36:10 +00003299 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003300 /* lastErrno set by seekAndWrite */
3301 return SQLITE_IOERR_WRITE;
3302 }else{
drh4bf66fd2015-02-19 02:43:02 +00003303 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003304 return SQLITE_FULL;
3305 }
3306 }
dan6e09d692010-07-27 18:34:15 +00003307
drh734c9862008-11-28 15:37:20 +00003308 return SQLITE_OK;
3309}
3310
3311#ifdef SQLITE_TEST
3312/*
3313** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003314** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003315*/
3316int sqlite3_sync_count = 0;
3317int sqlite3_fullsync_count = 0;
3318#endif
3319
3320/*
drh89240432009-03-25 01:06:01 +00003321** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003322** Others do no. To be safe, we will stick with the (slightly slower)
3323** fsync(). If you know that your system does support fdatasync() correctly,
drhf7a4a1b2015-01-10 18:02:45 +00003324** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003325*/
drhf7a4a1b2015-01-10 18:02:45 +00003326#if !defined(fdatasync) && !HAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003327# define fdatasync fsync
3328#endif
3329
3330/*
3331** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3332** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3333** only available on Mac OS X. But that could change.
3334*/
3335#ifdef F_FULLFSYNC
3336# define HAVE_FULLFSYNC 1
3337#else
3338# define HAVE_FULLFSYNC 0
3339#endif
3340
3341
3342/*
3343** The fsync() system call does not work as advertised on many
3344** unix systems. The following procedure is an attempt to make
3345** it work better.
3346**
3347** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3348** for testing when we want to run through the test suite quickly.
3349** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3350** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3351** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003352**
3353** SQLite sets the dataOnly flag if the size of the file is unchanged.
3354** The idea behind dataOnly is that it should only write the file content
3355** to disk, not the inode. We only set dataOnly if the file size is
3356** unchanged since the file size is part of the inode. However,
3357** Ted Ts'o tells us that fdatasync() will also write the inode if the
3358** file size has changed. The only real difference between fdatasync()
3359** and fsync(), Ted tells us, is that fdatasync() will not flush the
3360** inode if the mtime or owner or other inode attributes have changed.
3361** We only care about the file size, not the other file attributes, so
3362** as far as SQLite is concerned, an fdatasync() is always adequate.
3363** So, we always use fdatasync() if it is available, regardless of
3364** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003365*/
3366static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003367 int rc;
drh734c9862008-11-28 15:37:20 +00003368
3369 /* The following "ifdef/elif/else/" block has the same structure as
3370 ** the one below. It is replicated here solely to avoid cluttering
3371 ** up the real code with the UNUSED_PARAMETER() macros.
3372 */
3373#ifdef SQLITE_NO_SYNC
3374 UNUSED_PARAMETER(fd);
3375 UNUSED_PARAMETER(fullSync);
3376 UNUSED_PARAMETER(dataOnly);
3377#elif HAVE_FULLFSYNC
3378 UNUSED_PARAMETER(dataOnly);
3379#else
3380 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003381 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003382#endif
3383
3384 /* Record the number of times that we do a normal fsync() and
3385 ** FULLSYNC. This is used during testing to verify that this procedure
3386 ** gets called with the correct arguments.
3387 */
3388#ifdef SQLITE_TEST
3389 if( fullSync ) sqlite3_fullsync_count++;
3390 sqlite3_sync_count++;
3391#endif
3392
3393 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
drh2c8fd122015-12-02 02:33:36 +00003394 ** no-op. But go ahead and call fstat() to validate the file
3395 ** descriptor as we need a method to provoke a failure during
3396 ** coverate testing.
drh734c9862008-11-28 15:37:20 +00003397 */
3398#ifdef SQLITE_NO_SYNC
drh2c8fd122015-12-02 02:33:36 +00003399 {
3400 struct stat buf;
3401 rc = osFstat(fd, &buf);
3402 }
drh734c9862008-11-28 15:37:20 +00003403#elif HAVE_FULLFSYNC
3404 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003405 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003406 }else{
3407 rc = 1;
3408 }
3409 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003410 ** It shouldn't be possible for fullfsync to fail on the local
3411 ** file system (on OSX), so failure indicates that FULLFSYNC
3412 ** isn't supported for this file system. So, attempt an fsync
3413 ** and (for now) ignore the overhead of a superfluous fcntl call.
3414 ** It'd be better to detect fullfsync support once and avoid
3415 ** the fcntl call every time sync is called.
3416 */
drh734c9862008-11-28 15:37:20 +00003417 if( rc ) rc = fsync(fd);
3418
drh7ed97b92010-01-20 13:07:21 +00003419#elif defined(__APPLE__)
3420 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3421 ** so currently we default to the macro that redefines fdatasync to fsync
3422 */
3423 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003424#else
drh0b647ff2009-03-21 14:41:04 +00003425 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003426#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003427 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003428 rc = fsync(fd);
3429 }
drh0b647ff2009-03-21 14:41:04 +00003430#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003431#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3432
3433 if( OS_VXWORKS && rc!= -1 ){
3434 rc = 0;
3435 }
chw97185482008-11-17 08:05:31 +00003436 return rc;
drhbfe66312006-10-03 17:40:40 +00003437}
3438
drh734c9862008-11-28 15:37:20 +00003439/*
drh0059eae2011-08-08 23:48:40 +00003440** Open a file descriptor to the directory containing file zFilename.
3441** If successful, *pFd is set to the opened file descriptor and
3442** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3443** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3444** value.
3445**
drh90315a22011-08-10 01:52:12 +00003446** The directory file descriptor is used for only one thing - to
3447** fsync() a directory to make sure file creation and deletion events
3448** are flushed to disk. Such fsyncs are not needed on newer
3449** journaling filesystems, but are required on older filesystems.
3450**
3451** This routine can be overridden using the xSetSysCall interface.
3452** The ability to override this routine was added in support of the
3453** chromium sandbox. Opening a directory is a security risk (we are
3454** told) so making it overrideable allows the chromium sandbox to
3455** replace this routine with a harmless no-op. To make this routine
3456** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3457** *pFd set to a negative number.
3458**
drh0059eae2011-08-08 23:48:40 +00003459** If SQLITE_OK is returned, the caller is responsible for closing
3460** the file descriptor *pFd using close().
3461*/
3462static int openDirectory(const char *zFilename, int *pFd){
3463 int ii;
3464 int fd = -1;
3465 char zDirname[MAX_PATHNAME+1];
3466
3467 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drhdc278512015-12-07 18:18:33 +00003468 for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
3469 if( ii>0 ){
drh0059eae2011-08-08 23:48:40 +00003470 zDirname[ii] = '\0';
drhdc278512015-12-07 18:18:33 +00003471 }else{
3472 if( zDirname[0]!='/' ) zDirname[0] = '.';
3473 zDirname[1] = 0;
3474 }
3475 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3476 if( fd>=0 ){
3477 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
drh0059eae2011-08-08 23:48:40 +00003478 }
3479 *pFd = fd;
drhacb6b282015-11-26 10:37:05 +00003480 if( fd>=0 ) return SQLITE_OK;
3481 return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
drh0059eae2011-08-08 23:48:40 +00003482}
3483
3484/*
drh734c9862008-11-28 15:37:20 +00003485** Make sure all writes to a particular file are committed to disk.
3486**
3487** If dataOnly==0 then both the file itself and its metadata (file
3488** size, access time, etc) are synced. If dataOnly!=0 then only the
3489** file data is synced.
3490**
3491** Under Unix, also make sure that the directory entry for the file
3492** has been created by fsync-ing the directory that contains the file.
3493** If we do not do this and we encounter a power failure, the directory
3494** entry for the journal might not exist after we reboot. The next
3495** SQLite to access the file will not know that the journal exists (because
3496** the directory entry for the journal was never created) and the transaction
3497** will not roll back - possibly leading to database corruption.
3498*/
3499static int unixSync(sqlite3_file *id, int flags){
3500 int rc;
3501 unixFile *pFile = (unixFile*)id;
3502
3503 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3504 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3505
3506 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3507 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3508 || (flags&0x0F)==SQLITE_SYNC_FULL
3509 );
3510
3511 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3512 ** line is to test that doing so does not cause any problems.
3513 */
3514 SimulateDiskfullError( return SQLITE_FULL );
3515
3516 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003517 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003518 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3519 SimulateIOError( rc=1 );
3520 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003521 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003522 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003523 }
drh0059eae2011-08-08 23:48:40 +00003524
3525 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003526 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003527 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003528 */
3529 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3530 int dirfd;
3531 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003532 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003533 rc = osOpenDirectory(pFile->zPath, &dirfd);
drhacb6b282015-11-26 10:37:05 +00003534 if( rc==SQLITE_OK ){
drh0059eae2011-08-08 23:48:40 +00003535 full_fsync(dirfd, 0, 0);
3536 robust_close(pFile, dirfd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00003537 }else{
3538 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00003539 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003540 }
drh0059eae2011-08-08 23:48:40 +00003541 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003542 }
3543 return rc;
3544}
3545
3546/*
3547** Truncate an open file to a specified size
3548*/
3549static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003550 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003551 int rc;
dan6e09d692010-07-27 18:34:15 +00003552 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003553 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003554
3555 /* If the user has configured a chunk-size for this file, truncate the
3556 ** file so that it consists of an integer number of chunks (i.e. the
3557 ** actual file size after the operation may be larger than the requested
3558 ** size).
3559 */
drhb8af4b72012-04-05 20:04:39 +00003560 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003561 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3562 }
3563
dan2ee53412014-09-06 16:49:40 +00003564 rc = robust_ftruncate(pFile->h, nByte);
drh734c9862008-11-28 15:37:20 +00003565 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003566 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003567 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003568 }else{
drhd3d8c042012-05-29 17:02:40 +00003569#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003570 /* If we are doing a normal write to a database file (as opposed to
3571 ** doing a hot-journal rollback or a write to some file other than a
3572 ** normal database file) and we truncate the file to zero length,
3573 ** that effectively updates the change counter. This might happen
3574 ** when restoring a database using the backup API from a zero-length
3575 ** source.
3576 */
dan6e09d692010-07-27 18:34:15 +00003577 if( pFile->inNormalWrite && nByte==0 ){
3578 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003579 }
danf23da962013-03-23 21:00:41 +00003580#endif
danc0003312013-03-22 17:46:11 +00003581
mistachkine98844f2013-08-24 00:59:24 +00003582#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003583 /* If the file was just truncated to a size smaller than the currently
3584 ** mapped region, reduce the effective mapping size as well. SQLite will
3585 ** use read() and write() to access data beyond this point from now on.
3586 */
3587 if( nByte<pFile->mmapSize ){
3588 pFile->mmapSize = nByte;
3589 }
mistachkine98844f2013-08-24 00:59:24 +00003590#endif
drh3313b142009-11-06 04:13:18 +00003591
drh734c9862008-11-28 15:37:20 +00003592 return SQLITE_OK;
3593 }
3594}
3595
3596/*
3597** Determine the current size of a file in bytes
3598*/
3599static int unixFileSize(sqlite3_file *id, i64 *pSize){
3600 int rc;
3601 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003602 assert( id );
3603 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003604 SimulateIOError( rc=1 );
3605 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00003606 storeLastErrno((unixFile*)id, errno);
drh734c9862008-11-28 15:37:20 +00003607 return SQLITE_IOERR_FSTAT;
3608 }
3609 *pSize = buf.st_size;
3610
drh8af6c222010-05-14 12:43:01 +00003611 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003612 ** writes a single byte into that file in order to work around a bug
3613 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3614 ** layers, we need to report this file size as zero even though it is
3615 ** really 1. Ticket #3260.
3616 */
3617 if( *pSize==1 ) *pSize = 0;
3618
3619
3620 return SQLITE_OK;
3621}
3622
drhd2cb50b2009-01-09 21:41:17 +00003623#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003624/*
3625** Handler for proxy-locking file-control verbs. Defined below in the
3626** proxying locking division.
3627*/
3628static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003629#endif
drh715ff302008-12-03 22:32:44 +00003630
dan502019c2010-07-28 14:26:17 +00003631/*
3632** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003633** file-control operation. Enlarge the database to nBytes in size
3634** (rounded up to the next chunk-size). If the database is already
3635** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003636*/
3637static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003638 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003639 i64 nSize; /* Required file size */
3640 struct stat buf; /* Used to hold return values of fstat() */
3641
drh4bf66fd2015-02-19 02:43:02 +00003642 if( osFstat(pFile->h, &buf) ){
3643 return SQLITE_IOERR_FSTAT;
3644 }
dan502019c2010-07-28 14:26:17 +00003645
3646 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3647 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003648
dan502019c2010-07-28 14:26:17 +00003649#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003650 /* The code below is handling the return value of osFallocate()
3651 ** correctly. posix_fallocate() is defined to "returns zero on success,
3652 ** or an error number on failure". See the manpage for details. */
3653 int err;
drhff812312011-02-23 13:33:46 +00003654 do{
dan661d71a2011-03-30 19:08:03 +00003655 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3656 }while( err==EINTR );
3657 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003658#else
dan592bf7f2014-12-30 19:58:31 +00003659 /* If the OS does not have posix_fallocate(), fake it. Write a
3660 ** single byte to the last byte in each block that falls entirely
3661 ** within the extended region. Then, if required, a single byte
3662 ** at offset (nSize-1), to set the size of the file correctly.
3663 ** This is a similar technique to that used by glibc on systems
3664 ** that do not have a real fallocate() call.
dan502019c2010-07-28 14:26:17 +00003665 */
3666 int nBlk = buf.st_blksize; /* File-system block size */
danef3d66c2015-01-06 21:31:47 +00003667 int nWrite = 0; /* Number of bytes written by seekAndWrite */
dan502019c2010-07-28 14:26:17 +00003668 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003669
drh053378d2015-12-01 22:09:42 +00003670 iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
dan592bf7f2014-12-30 19:58:31 +00003671 assert( iWrite>=buf.st_size );
dan592bf7f2014-12-30 19:58:31 +00003672 assert( ((iWrite+1)%nBlk)==0 );
drh053378d2015-12-01 22:09:42 +00003673 for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
3674 if( iWrite>=nSize ) iWrite = nSize - 1;
danef3d66c2015-01-06 21:31:47 +00003675 nWrite = seekAndWrite(pFile, iWrite, "", 1);
dandc5df0f2011-04-06 19:15:45 +00003676 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dandc5df0f2011-04-06 19:15:45 +00003677 }
dan502019c2010-07-28 14:26:17 +00003678#endif
3679 }
3680 }
3681
mistachkine98844f2013-08-24 00:59:24 +00003682#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003683 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003684 int rc;
3685 if( pFile->szChunk<=0 ){
3686 if( robust_ftruncate(pFile->h, nByte) ){
drh4bf66fd2015-02-19 02:43:02 +00003687 storeLastErrno(pFile, errno);
danf23da962013-03-23 21:00:41 +00003688 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3689 }
3690 }
3691
3692 rc = unixMapfile(pFile, nByte);
3693 return rc;
3694 }
mistachkine98844f2013-08-24 00:59:24 +00003695#endif
danf23da962013-03-23 21:00:41 +00003696
dan502019c2010-07-28 14:26:17 +00003697 return SQLITE_OK;
3698}
danielk1977ad94b582007-08-20 06:44:22 +00003699
danielk1977e3026632004-06-22 11:29:02 +00003700/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003701** If *pArg is initially negative then this is a query. Set *pArg to
drhf12b3f62011-12-21 14:42:29 +00003702** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3703**
3704** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3705*/
3706static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3707 if( *pArg<0 ){
3708 *pArg = (pFile->ctrlFlags & mask)!=0;
3709 }else if( (*pArg)==0 ){
3710 pFile->ctrlFlags &= ~mask;
3711 }else{
3712 pFile->ctrlFlags |= mask;
3713 }
3714}
3715
drh696b33e2012-12-06 19:01:42 +00003716/* Forward declaration */
3717static int unixGetTempname(int nBuf, char *zBuf);
3718
drhf12b3f62011-12-21 14:42:29 +00003719/*
drh9e33c2c2007-08-31 18:34:59 +00003720** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003721*/
drhcc6bb3e2007-08-31 16:11:35 +00003722static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003723 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003724 switch( op ){
3725 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003726 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003727 return SQLITE_OK;
3728 }
drh4bf66fd2015-02-19 02:43:02 +00003729 case SQLITE_FCNTL_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003730 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003731 return SQLITE_OK;
3732 }
dan6e09d692010-07-27 18:34:15 +00003733 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003734 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003735 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003736 }
drh9ff27ec2010-05-19 19:26:05 +00003737 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003738 int rc;
3739 SimulateIOErrorBenign(1);
3740 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3741 SimulateIOErrorBenign(0);
3742 return rc;
drhf0b190d2011-07-26 16:03:07 +00003743 }
3744 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003745 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3746 return SQLITE_OK;
3747 }
drhcb15f352011-12-23 01:04:17 +00003748 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3749 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003750 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003751 }
drhde60fc22011-12-14 17:53:36 +00003752 case SQLITE_FCNTL_VFSNAME: {
3753 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3754 return SQLITE_OK;
3755 }
drh696b33e2012-12-06 19:01:42 +00003756 case SQLITE_FCNTL_TEMPFILENAME: {
drhf3cdcdc2015-04-29 16:50:28 +00003757 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
drh696b33e2012-12-06 19:01:42 +00003758 if( zTFile ){
3759 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3760 *(char**)pArg = zTFile;
3761 }
3762 return SQLITE_OK;
3763 }
drhb959a012013-12-07 12:29:22 +00003764 case SQLITE_FCNTL_HAS_MOVED: {
3765 *(int*)pArg = fileHasMoved(pFile);
3766 return SQLITE_OK;
3767 }
mistachkine98844f2013-08-24 00:59:24 +00003768#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003769 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003770 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003771 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003772 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3773 newLimit = sqlite3GlobalConfig.mxMmap;
3774 }
3775 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003776 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003777 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003778 if( pFile->mmapSize>0 ){
3779 unixUnmapfile(pFile);
3780 rc = unixMapfile(pFile, -1);
3781 }
danbcb8a862013-04-08 15:30:41 +00003782 }
drh34e258c2013-05-23 01:40:53 +00003783 return rc;
danb2d3de32013-03-14 18:34:37 +00003784 }
mistachkine98844f2013-08-24 00:59:24 +00003785#endif
drhd3d8c042012-05-29 17:02:40 +00003786#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003787 /* The pager calls this method to signal that it has done
3788 ** a rollback and that the database is therefore unchanged and
3789 ** it hence it is OK for the transaction change counter to be
3790 ** unchanged.
3791 */
3792 case SQLITE_FCNTL_DB_UNCHANGED: {
3793 ((unixFile*)id)->dbUpdate = 0;
3794 return SQLITE_OK;
3795 }
3796#endif
drhd2cb50b2009-01-09 21:41:17 +00003797#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh4bf66fd2015-02-19 02:43:02 +00003798 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
3799 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003800 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003801 }
drhd2cb50b2009-01-09 21:41:17 +00003802#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003803 }
drh0b52b7d2011-01-26 19:46:22 +00003804 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003805}
3806
3807/*
danielk1977a3d4c882007-03-23 10:08:38 +00003808** Return the sector size in bytes of the underlying block device for
3809** the specified file. This is almost always 512 bytes, but may be
3810** larger for some devices.
3811**
3812** SQLite code assumes this function cannot fail. It also assumes that
3813** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003814** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003815** same for both.
3816*/
drh537dddf2012-10-26 13:46:24 +00003817#ifndef __QNXNTO__
3818static int unixSectorSize(sqlite3_file *NotUsed){
3819 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003820 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003821}
drh537dddf2012-10-26 13:46:24 +00003822#endif
3823
3824/*
3825** The following version of unixSectorSize() is optimized for QNX.
3826*/
3827#ifdef __QNXNTO__
3828#include <sys/dcmd_blk.h>
3829#include <sys/statvfs.h>
3830static int unixSectorSize(sqlite3_file *id){
3831 unixFile *pFile = (unixFile*)id;
3832 if( pFile->sectorSize == 0 ){
3833 struct statvfs fsInfo;
3834
3835 /* Set defaults for non-supported filesystems */
3836 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3837 pFile->deviceCharacteristics = 0;
3838 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3839 return pFile->sectorSize;
3840 }
3841
3842 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3843 pFile->sectorSize = fsInfo.f_bsize;
3844 pFile->deviceCharacteristics =
3845 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3846 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3847 ** the write succeeds */
3848 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3849 ** so it is ordered */
3850 0;
3851 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3852 pFile->sectorSize = fsInfo.f_bsize;
3853 pFile->deviceCharacteristics =
3854 /* etfs cluster size writes are atomic */
3855 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3856 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3857 ** the write succeeds */
3858 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3859 ** so it is ordered */
3860 0;
3861 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3862 pFile->sectorSize = fsInfo.f_bsize;
3863 pFile->deviceCharacteristics =
3864 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3865 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3866 ** the write succeeds */
3867 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3868 ** so it is ordered */
3869 0;
3870 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
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 if( strstr(fsInfo.f_basetype, "dos") ){
3879 pFile->sectorSize = fsInfo.f_bsize;
3880 pFile->deviceCharacteristics =
3881 /* full bitset of atomics from max sector size and smaller */
3882 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3883 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3884 ** so it is ordered */
3885 0;
3886 }else{
3887 pFile->deviceCharacteristics =
3888 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3889 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3890 ** the write succeeds */
3891 0;
3892 }
3893 }
3894 /* Last chance verification. If the sector size isn't a multiple of 512
3895 ** then it isn't valid.*/
3896 if( pFile->sectorSize % 512 != 0 ){
3897 pFile->deviceCharacteristics = 0;
3898 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3899 }
3900 return pFile->sectorSize;
3901}
3902#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003903
danielk197790949c22007-08-17 16:50:38 +00003904/*
drhf12b3f62011-12-21 14:42:29 +00003905** Return the device characteristics for the file.
3906**
drhcb15f352011-12-23 01:04:17 +00003907** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
peter.d.reid60ec9142014-09-06 16:39:46 +00003908** However, that choice is controversial since technically the underlying
drhcb15f352011-12-23 01:04:17 +00003909** file system does not always provide powersafe overwrites. (In other
3910** words, after a power-loss event, parts of the file that were never
3911** written might end up being altered.) However, non-PSOW behavior is very,
3912** very rare. And asserting PSOW makes a large reduction in the amount
3913** of required I/O for journaling, since a lot of padding is eliminated.
3914** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3915** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003916*/
drhf12b3f62011-12-21 14:42:29 +00003917static int unixDeviceCharacteristics(sqlite3_file *id){
3918 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003919 int rc = 0;
3920#ifdef __QNXNTO__
3921 if( p->sectorSize==0 ) unixSectorSize(id);
3922 rc = p->deviceCharacteristics;
3923#endif
drhcb15f352011-12-23 01:04:17 +00003924 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003925 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003926 }
drh537dddf2012-10-26 13:46:24 +00003927 return rc;
danielk197762079062007-08-15 17:08:46 +00003928}
3929
dan702eec12014-06-23 10:04:58 +00003930#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00003931
dan702eec12014-06-23 10:04:58 +00003932/*
3933** Return the system page size.
3934**
3935** This function should not be called directly by other code in this file.
3936** Instead, it should be called via macro osGetpagesize().
3937*/
3938static int unixGetpagesize(void){
drh8cd5b252015-03-02 22:06:43 +00003939#if OS_VXWORKS
3940 return 1024;
3941#elif defined(_BSD_SOURCE)
dan702eec12014-06-23 10:04:58 +00003942 return getpagesize();
3943#else
3944 return (int)sysconf(_SC_PAGESIZE);
3945#endif
3946}
3947
3948#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
3949
3950#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00003951
3952/*
drhd91c68f2010-05-14 14:52:25 +00003953** Object used to represent an shared memory buffer.
3954**
3955** When multiple threads all reference the same wal-index, each thread
3956** has its own unixShm object, but they all point to a single instance
3957** of this unixShmNode object. In other words, each wal-index is opened
3958** only once per process.
3959**
3960** Each unixShmNode object is connected to a single unixInodeInfo object.
3961** We could coalesce this object into unixInodeInfo, but that would mean
3962** every open file that does not use shared memory (in other words, most
3963** open files) would have to carry around this extra information. So
3964** the unixInodeInfo object contains a pointer to this unixShmNode object
3965** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003966**
3967** unixMutexHeld() must be true when creating or destroying
3968** this object or while reading or writing the following fields:
3969**
3970** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003971**
3972** The following fields are read-only after the object is created:
3973**
3974** fid
3975** zFilename
3976**
drhd91c68f2010-05-14 14:52:25 +00003977** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003978** unixMutexHeld() is true when reading or writing any other field
3979** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003980*/
drhd91c68f2010-05-14 14:52:25 +00003981struct unixShmNode {
3982 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003983 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003984 char *zFilename; /* Name of the mmapped file */
3985 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003986 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003987 u16 nRegion; /* Size of array apRegion */
3988 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003989 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003990 int nRef; /* Number of unixShm objects pointing to this */
3991 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003992#ifdef SQLITE_DEBUG
3993 u8 exclMask; /* Mask of exclusive locks held */
3994 u8 sharedMask; /* Mask of shared locks held */
3995 u8 nextShmId; /* Next available unixShm.id value */
3996#endif
3997};
3998
3999/*
drhd9e5c4f2010-05-12 18:01:39 +00004000** Structure used internally by this VFS to record the state of an
4001** open shared memory connection.
4002**
drhd91c68f2010-05-14 14:52:25 +00004003** The following fields are initialized when this object is created and
4004** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004005**
drhd91c68f2010-05-14 14:52:25 +00004006** unixShm.pFile
4007** unixShm.id
4008**
4009** All other fields are read/write. The unixShm.pFile->mutex must be held
4010** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004011*/
4012struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004013 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4014 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004015 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004016 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004017 u16 sharedMask; /* Mask of shared locks held */
4018 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004019};
4020
4021/*
drhd9e5c4f2010-05-12 18:01:39 +00004022** Constants used for locking
4023*/
drhbd9676c2010-06-23 17:58:38 +00004024#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004025#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004026
drhd9e5c4f2010-05-12 18:01:39 +00004027/*
drh73b64e42010-05-30 19:55:15 +00004028** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004029**
4030** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4031** otherwise.
4032*/
4033static int unixShmSystemLock(
drhbbf76ee2015-03-10 20:22:35 +00004034 unixFile *pFile, /* Open connection to the WAL file */
drhd91c68f2010-05-14 14:52:25 +00004035 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004036 int ofst, /* First byte of the locking range */
4037 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004038){
drhbbf76ee2015-03-10 20:22:35 +00004039 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4040 struct flock f; /* The posix advisory locking structure */
4041 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004042
drhd91c68f2010-05-14 14:52:25 +00004043 /* Access to the unixShmNode object is serialized by the caller */
drhbbf76ee2015-03-10 20:22:35 +00004044 pShmNode = pFile->pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004045 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004046
drh73b64e42010-05-30 19:55:15 +00004047 /* Shared locks never span more than one byte */
4048 assert( n==1 || lockType!=F_RDLCK );
4049
4050 /* Locks are within range */
drhaf19f172015-12-02 17:40:13 +00004051 assert( n>=1 && n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004052
drh3cb93392011-03-12 18:10:44 +00004053 if( pShmNode->h>=0 ){
4054 /* Initialize the locking parameters */
4055 memset(&f, 0, sizeof(f));
4056 f.l_type = lockType;
4057 f.l_whence = SEEK_SET;
4058 f.l_start = ofst;
4059 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004060
drhdcfb9652015-12-02 00:05:26 +00004061 rc = osFcntl(pShmNode->h, F_SETLK, &f);
drh3cb93392011-03-12 18:10:44 +00004062 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4063 }
drhd9e5c4f2010-05-12 18:01:39 +00004064
4065 /* Update the global lock state and do debug tracing */
4066#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004067 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004068 OSTRACE(("SHM-LOCK "));
drh693e6712014-01-24 22:58:00 +00004069 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004070 if( rc==SQLITE_OK ){
4071 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004072 OSTRACE(("unlock %d ok", ofst));
4073 pShmNode->exclMask &= ~mask;
4074 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004075 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004076 OSTRACE(("read-lock %d ok", ofst));
4077 pShmNode->exclMask &= ~mask;
4078 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004079 }else{
4080 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004081 OSTRACE(("write-lock %d ok", ofst));
4082 pShmNode->exclMask |= mask;
4083 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004084 }
4085 }else{
4086 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004087 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004088 }else if( lockType==F_RDLCK ){
4089 OSTRACE(("read-lock failed"));
4090 }else{
4091 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004092 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004093 }
4094 }
drh20e1f082010-05-31 16:10:12 +00004095 OSTRACE((" - afterwards %03x,%03x\n",
4096 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004097 }
drhd9e5c4f2010-05-12 18:01:39 +00004098#endif
4099
4100 return rc;
4101}
4102
dan781e34c2014-03-20 08:59:47 +00004103/*
dan781e34c2014-03-20 08:59:47 +00004104** Return the minimum number of 32KB shm regions that should be mapped at
4105** a time, assuming that each mapping must be an integer multiple of the
4106** current system page-size.
4107**
4108** Usually, this is 1. The exception seems to be systems that are configured
4109** to use 64KB pages - in this case each mapping must cover at least two
4110** shm regions.
4111*/
4112static int unixShmRegionPerMap(void){
4113 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004114 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004115 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4116 if( pgsz<shmsz ) return 1;
4117 return pgsz/shmsz;
4118}
drhd9e5c4f2010-05-12 18:01:39 +00004119
4120/*
drhd91c68f2010-05-14 14:52:25 +00004121** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004122**
4123** This is not a VFS shared-memory method; it is a utility function called
4124** by VFS shared-memory methods.
4125*/
drhd91c68f2010-05-14 14:52:25 +00004126static void unixShmPurge(unixFile *pFd){
4127 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004128 assert( unixMutexHeld() );
drhf3b1ed02015-12-02 13:11:03 +00004129 if( p && ALWAYS(p->nRef==0) ){
dan781e34c2014-03-20 08:59:47 +00004130 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004131 int i;
drhd91c68f2010-05-14 14:52:25 +00004132 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004133 sqlite3_mutex_free(p->mutex);
dan781e34c2014-03-20 08:59:47 +00004134 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh3cb93392011-03-12 18:10:44 +00004135 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004136 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004137 }else{
4138 sqlite3_free(p->apRegion[i]);
4139 }
dan13a3cb82010-06-11 19:04:21 +00004140 }
dan18801912010-06-14 14:07:50 +00004141 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004142 if( p->h>=0 ){
4143 robust_close(pFd, p->h, __LINE__);
4144 p->h = -1;
4145 }
drhd91c68f2010-05-14 14:52:25 +00004146 p->pInode->pShmNode = 0;
4147 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004148 }
4149}
4150
4151/*
danda9fe0c2010-07-13 18:44:03 +00004152** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004153** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004154**
drh7234c6d2010-06-19 15:10:09 +00004155** The file used to implement shared-memory is in the same directory
4156** as the open database file and has the same name as the open database
4157** file with the "-shm" suffix added. For example, if the database file
4158** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004159** for shared memory will be called "/home/user1/config.db-shm".
4160**
4161** Another approach to is to use files in /dev/shm or /dev/tmp or an
4162** some other tmpfs mount. But if a file in a different directory
4163** from the database file is used, then differing access permissions
4164** or a chroot() might cause two different processes on the same
4165** database to end up using different files for shared memory -
4166** meaning that their memory would not really be shared - resulting
4167** in database corruption. Nevertheless, this tmpfs file usage
4168** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4169** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4170** option results in an incompatible build of SQLite; builds of SQLite
4171** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4172** same database file at the same time, database corruption will likely
4173** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4174** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004175**
4176** When opening a new shared-memory file, if no other instances of that
4177** file are currently open, in this process or in other processes, then
4178** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004179**
4180** If the original database file (pDbFd) is using the "unix-excl" VFS
4181** that means that an exclusive lock is held on the database file and
4182** that no other processes are able to read or write the database. In
4183** that case, we do not really need shared memory. No shared memory
4184** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004185*/
danda9fe0c2010-07-13 18:44:03 +00004186static int unixOpenSharedMemory(unixFile *pDbFd){
4187 struct unixShm *p = 0; /* The connection to be opened */
4188 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4189 int rc; /* Result code */
4190 unixInodeInfo *pInode; /* The inode of fd */
4191 char *zShmFilename; /* Name of the file used for SHM */
4192 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004193
danda9fe0c2010-07-13 18:44:03 +00004194 /* Allocate space for the new unixShm object. */
drhf3cdcdc2015-04-29 16:50:28 +00004195 p = sqlite3_malloc64( sizeof(*p) );
drhd9e5c4f2010-05-12 18:01:39 +00004196 if( p==0 ) return SQLITE_NOMEM;
4197 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004198 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004199
danda9fe0c2010-07-13 18:44:03 +00004200 /* Check to see if a unixShmNode object already exists. Reuse an existing
4201 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004202 */
4203 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004204 pInode = pDbFd->pInode;
4205 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004206 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004207 struct stat sStat; /* fstat() info for database file */
drh4bf66fd2015-02-19 02:43:02 +00004208#ifndef SQLITE_SHM_DIRECTORY
4209 const char *zBasePath = pDbFd->zPath;
4210#endif
danddb0ac42010-07-14 14:48:58 +00004211
4212 /* Call fstat() to figure out the permissions on the database file. If
4213 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004214 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004215 */
drhf3b1ed02015-12-02 13:11:03 +00004216 if( osFstat(pDbFd->h, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004217 rc = SQLITE_IOERR_FSTAT;
4218 goto shm_open_err;
4219 }
4220
drha4ced192010-07-15 18:32:40 +00004221#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004222 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004223#else
drh4bf66fd2015-02-19 02:43:02 +00004224 nShmFilename = 6 + (int)strlen(zBasePath);
drha4ced192010-07-15 18:32:40 +00004225#endif
drhf3cdcdc2015-04-29 16:50:28 +00004226 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004227 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004228 rc = SQLITE_NOMEM;
4229 goto shm_open_err;
4230 }
drh9cb5a0d2012-01-05 21:19:54 +00004231 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004232 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004233#ifdef SQLITE_SHM_DIRECTORY
4234 sqlite3_snprintf(nShmFilename, zShmFilename,
4235 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4236 (u32)sStat.st_ino, (u32)sStat.st_dev);
4237#else
drh4bf66fd2015-02-19 02:43:02 +00004238 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
drh81cc5162011-05-17 20:36:21 +00004239 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004240#endif
drhd91c68f2010-05-14 14:52:25 +00004241 pShmNode->h = -1;
4242 pDbFd->pInode->pShmNode = pShmNode;
4243 pShmNode->pInode = pDbFd->pInode;
4244 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4245 if( pShmNode->mutex==0 ){
4246 rc = SQLITE_NOMEM;
4247 goto shm_open_err;
4248 }
drhd9e5c4f2010-05-12 18:01:39 +00004249
drh3cb93392011-03-12 18:10:44 +00004250 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004251 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004252 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004253 openFlags = O_RDONLY;
4254 pShmNode->isReadonly = 1;
4255 }
4256 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004257 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004258 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4259 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004260 }
drhac7c3ac2012-02-11 19:23:48 +00004261
4262 /* If this process is running as root, make sure that the SHM file
4263 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004264 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004265 */
drh6226ca22015-11-24 15:06:28 +00004266 robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004267
4268 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004269 ** If not, truncate the file to zero length.
4270 */
4271 rc = SQLITE_OK;
drhbbf76ee2015-03-10 20:22:35 +00004272 if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
drh66dfec8b2011-06-01 20:01:49 +00004273 if( robust_ftruncate(pShmNode->h, 0) ){
4274 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004275 }
4276 }
drh66dfec8b2011-06-01 20:01:49 +00004277 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004278 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
drh66dfec8b2011-06-01 20:01:49 +00004279 }
4280 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004281 }
drhd9e5c4f2010-05-12 18:01:39 +00004282 }
4283
drhd91c68f2010-05-14 14:52:25 +00004284 /* Make the new connection a child of the unixShmNode */
4285 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004286#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004287 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004288#endif
drhd91c68f2010-05-14 14:52:25 +00004289 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004290 pDbFd->pShm = p;
4291 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004292
4293 /* The reference count on pShmNode has already been incremented under
4294 ** the cover of the unixEnterMutex() mutex and the pointer from the
4295 ** new (struct unixShm) object to the pShmNode has been set. All that is
4296 ** left to do is to link the new object into the linked list starting
4297 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4298 ** mutex.
4299 */
4300 sqlite3_mutex_enter(pShmNode->mutex);
4301 p->pNext = pShmNode->pFirst;
4302 pShmNode->pFirst = p;
4303 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004304 return SQLITE_OK;
4305
4306 /* Jump here on any error */
4307shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004308 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004309 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004310 unixLeaveMutex();
4311 return rc;
4312}
4313
4314/*
danda9fe0c2010-07-13 18:44:03 +00004315** This function is called to obtain a pointer to region iRegion of the
4316** shared-memory associated with the database file fd. Shared-memory regions
4317** are numbered starting from zero. Each shared-memory region is szRegion
4318** bytes in size.
4319**
4320** If an error occurs, an error code is returned and *pp is set to NULL.
4321**
4322** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4323** region has not been allocated (by any client, including one running in a
4324** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4325** bExtend is non-zero and the requested shared-memory region has not yet
4326** been allocated, it is allocated by this function.
4327**
4328** If the shared-memory region has already been allocated or is allocated by
4329** this call as described above, then it is mapped into this processes
4330** address space (if it is not already), *pp is set to point to the mapped
4331** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004332*/
danda9fe0c2010-07-13 18:44:03 +00004333static int unixShmMap(
4334 sqlite3_file *fd, /* Handle open on database file */
4335 int iRegion, /* Region to retrieve */
4336 int szRegion, /* Size of regions */
4337 int bExtend, /* True to extend file if necessary */
4338 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004339){
danda9fe0c2010-07-13 18:44:03 +00004340 unixFile *pDbFd = (unixFile*)fd;
4341 unixShm *p;
4342 unixShmNode *pShmNode;
4343 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004344 int nShmPerMap = unixShmRegionPerMap();
4345 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004346
danda9fe0c2010-07-13 18:44:03 +00004347 /* If the shared-memory file has not yet been opened, open it now. */
4348 if( pDbFd->pShm==0 ){
4349 rc = unixOpenSharedMemory(pDbFd);
4350 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004351 }
drhd9e5c4f2010-05-12 18:01:39 +00004352
danda9fe0c2010-07-13 18:44:03 +00004353 p = pDbFd->pShm;
4354 pShmNode = p->pShmNode;
4355 sqlite3_mutex_enter(pShmNode->mutex);
4356 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004357 assert( pShmNode->pInode==pDbFd->pInode );
4358 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4359 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004360
dan781e34c2014-03-20 08:59:47 +00004361 /* Minimum number of regions required to be mapped. */
4362 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4363
4364 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004365 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004366 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004367 struct stat sStat; /* Used by fstat() */
4368
4369 pShmNode->szRegion = szRegion;
4370
drh3cb93392011-03-12 18:10:44 +00004371 if( pShmNode->h>=0 ){
4372 /* The requested region is not mapped into this processes address space.
4373 ** Check to see if it has been allocated (i.e. if the wal-index file is
4374 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004375 */
drh3cb93392011-03-12 18:10:44 +00004376 if( osFstat(pShmNode->h, &sStat) ){
4377 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004378 goto shmpage_out;
4379 }
drh3cb93392011-03-12 18:10:44 +00004380
4381 if( sStat.st_size<nByte ){
4382 /* The requested memory region does not exist. If bExtend is set to
4383 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004384 */
dan47a2b4a2013-04-26 16:09:29 +00004385 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004386 goto shmpage_out;
4387 }
dan47a2b4a2013-04-26 16:09:29 +00004388
4389 /* Alternatively, if bExtend is true, extend the file. Do this by
4390 ** writing a single byte to the end of each (OS) page being
4391 ** allocated or extended. Technically, we need only write to the
4392 ** last page in order to extend the file. But writing to all new
4393 ** pages forces the OS to allocate them immediately, which reduces
4394 ** the chances of SIGBUS while accessing the mapped region later on.
4395 */
4396 else{
4397 static const int pgsz = 4096;
4398 int iPg;
4399
4400 /* Write to the last byte of each newly allocated or extended page */
4401 assert( (nByte % pgsz)==0 );
4402 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
drhe1818ec2015-12-01 16:21:35 +00004403 int x = 0;
4404 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
dan47a2b4a2013-04-26 16:09:29 +00004405 const char *zFile = pShmNode->zFilename;
4406 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4407 goto shmpage_out;
4408 }
4409 }
drh3cb93392011-03-12 18:10:44 +00004410 }
4411 }
danda9fe0c2010-07-13 18:44:03 +00004412 }
4413
4414 /* Map the requested memory region into this processes address space. */
4415 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004416 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004417 );
4418 if( !apNew ){
4419 rc = SQLITE_IOERR_NOMEM;
4420 goto shmpage_out;
4421 }
4422 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004423 while( pShmNode->nRegion<nReqRegion ){
4424 int nMap = szRegion*nShmPerMap;
4425 int i;
drh3cb93392011-03-12 18:10:44 +00004426 void *pMem;
4427 if( pShmNode->h>=0 ){
dan781e34c2014-03-20 08:59:47 +00004428 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004429 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004430 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004431 );
4432 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004433 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004434 goto shmpage_out;
4435 }
4436 }else{
drhf3cdcdc2015-04-29 16:50:28 +00004437 pMem = sqlite3_malloc64(szRegion);
drh3cb93392011-03-12 18:10:44 +00004438 if( pMem==0 ){
4439 rc = SQLITE_NOMEM;
4440 goto shmpage_out;
4441 }
4442 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004443 }
dan781e34c2014-03-20 08:59:47 +00004444
4445 for(i=0; i<nShmPerMap; i++){
4446 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4447 }
4448 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004449 }
4450 }
4451
4452shmpage_out:
4453 if( pShmNode->nRegion>iRegion ){
4454 *pp = pShmNode->apRegion[iRegion];
4455 }else{
4456 *pp = 0;
4457 }
drh66dfec8b2011-06-01 20:01:49 +00004458 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004459 sqlite3_mutex_leave(pShmNode->mutex);
4460 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004461}
4462
4463/*
drhd9e5c4f2010-05-12 18:01:39 +00004464** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004465**
4466** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4467** different here than in posix. In xShmLock(), one can go from unlocked
4468** to shared and back or from unlocked to exclusive and back. But one may
4469** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004470*/
4471static int unixShmLock(
4472 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004473 int ofst, /* First lock to acquire or release */
4474 int n, /* Number of locks to acquire or release */
4475 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004476){
drh73b64e42010-05-30 19:55:15 +00004477 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4478 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4479 unixShm *pX; /* For looping over all siblings */
4480 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4481 int rc = SQLITE_OK; /* Result code */
4482 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004483
drhd91c68f2010-05-14 14:52:25 +00004484 assert( pShmNode==pDbFd->pInode->pShmNode );
4485 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004486 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004487 assert( n>=1 );
4488 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4489 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4490 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4491 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4492 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004493 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4494 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004495
drhc99597c2010-05-31 01:41:15 +00004496 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004497 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004498 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004499 if( flags & SQLITE_SHM_UNLOCK ){
4500 u16 allMask = 0; /* Mask of locks held by siblings */
4501
4502 /* See if any siblings hold this same lock */
4503 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4504 if( pX==p ) continue;
4505 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4506 allMask |= pX->sharedMask;
4507 }
4508
4509 /* Unlock the system-level locks */
4510 if( (mask & allMask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004511 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004512 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004513 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004514 }
drh73b64e42010-05-30 19:55:15 +00004515
4516 /* Undo the local locks */
4517 if( rc==SQLITE_OK ){
4518 p->exclMask &= ~mask;
4519 p->sharedMask &= ~mask;
4520 }
4521 }else if( flags & SQLITE_SHM_SHARED ){
4522 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4523
4524 /* Find out which shared locks are already held by sibling connections.
4525 ** If any sibling already holds an exclusive lock, go ahead and return
4526 ** SQLITE_BUSY.
4527 */
4528 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004529 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004530 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004531 break;
4532 }
4533 allShared |= pX->sharedMask;
4534 }
4535
4536 /* Get shared locks at the system level, if necessary */
4537 if( rc==SQLITE_OK ){
4538 if( (allShared & mask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004539 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004540 }else{
drh73b64e42010-05-30 19:55:15 +00004541 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004542 }
drhd9e5c4f2010-05-12 18:01:39 +00004543 }
drh73b64e42010-05-30 19:55:15 +00004544
4545 /* Get the local shared locks */
4546 if( rc==SQLITE_OK ){
4547 p->sharedMask |= mask;
4548 }
4549 }else{
4550 /* Make sure no sibling connections hold locks that will block this
4551 ** lock. If any do, return SQLITE_BUSY right away.
4552 */
4553 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004554 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4555 rc = SQLITE_BUSY;
4556 break;
4557 }
4558 }
4559
4560 /* Get the exclusive locks at the system level. Then if successful
4561 ** also mark the local connection as being locked.
4562 */
4563 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004564 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004565 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004566 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004567 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004568 }
drhd9e5c4f2010-05-12 18:01:39 +00004569 }
4570 }
drhd91c68f2010-05-14 14:52:25 +00004571 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004572 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
drh5ac93652015-03-21 20:59:43 +00004573 p->id, osGetpid(0), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004574 return rc;
4575}
4576
drh286a2882010-05-20 23:51:06 +00004577/*
4578** Implement a memory barrier or memory fence on shared memory.
4579**
4580** All loads and stores begun before the barrier must complete before
4581** any load or store begun after the barrier.
4582*/
4583static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004584 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004585){
drhff828942010-06-26 21:34:06 +00004586 UNUSED_PARAMETER(fd);
drh22c733d2015-09-24 12:40:43 +00004587 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
4588 unixEnterMutex(); /* Also mutex, for redundancy */
drhb29ad852010-06-01 00:03:57 +00004589 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004590}
4591
dan18801912010-06-14 14:07:50 +00004592/*
danda9fe0c2010-07-13 18:44:03 +00004593** Close a connection to shared-memory. Delete the underlying
4594** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004595**
4596** If there is no shared memory associated with the connection then this
4597** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004598*/
danda9fe0c2010-07-13 18:44:03 +00004599static int unixShmUnmap(
4600 sqlite3_file *fd, /* The underlying database file */
4601 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004602){
danda9fe0c2010-07-13 18:44:03 +00004603 unixShm *p; /* The connection to be closed */
4604 unixShmNode *pShmNode; /* The underlying shared-memory file */
4605 unixShm **pp; /* For looping over sibling connections */
4606 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004607
danda9fe0c2010-07-13 18:44:03 +00004608 pDbFd = (unixFile*)fd;
4609 p = pDbFd->pShm;
4610 if( p==0 ) return SQLITE_OK;
4611 pShmNode = p->pShmNode;
4612
4613 assert( pShmNode==pDbFd->pInode->pShmNode );
4614 assert( pShmNode->pInode==pDbFd->pInode );
4615
4616 /* Remove connection p from the set of connections associated
4617 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004618 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004619 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4620 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004621
danda9fe0c2010-07-13 18:44:03 +00004622 /* Free the connection p */
4623 sqlite3_free(p);
4624 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004625 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004626
4627 /* If pShmNode->nRef has reached 0, then close the underlying
4628 ** shared-memory file, too */
4629 unixEnterMutex();
4630 assert( pShmNode->nRef>0 );
4631 pShmNode->nRef--;
4632 if( pShmNode->nRef==0 ){
drh4bf66fd2015-02-19 02:43:02 +00004633 if( deleteFlag && pShmNode->h>=0 ){
4634 osUnlink(pShmNode->zFilename);
4635 }
danda9fe0c2010-07-13 18:44:03 +00004636 unixShmPurge(pDbFd);
4637 }
4638 unixLeaveMutex();
4639
4640 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004641}
drh286a2882010-05-20 23:51:06 +00004642
danda9fe0c2010-07-13 18:44:03 +00004643
drhd9e5c4f2010-05-12 18:01:39 +00004644#else
drh6b017cc2010-06-14 18:01:46 +00004645# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004646# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004647# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004648# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004649#endif /* #ifndef SQLITE_OMIT_WAL */
4650
mistachkine98844f2013-08-24 00:59:24 +00004651#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004652/*
danaef49d72013-03-25 16:28:54 +00004653** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004654*/
danf23da962013-03-23 21:00:41 +00004655static void unixUnmapfile(unixFile *pFd){
4656 assert( pFd->nFetchOut==0 );
4657 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004658 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004659 pFd->pMapRegion = 0;
4660 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004661 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004662 }
4663}
dan5d8a1372013-03-19 19:28:06 +00004664
danaef49d72013-03-25 16:28:54 +00004665/*
dane6ecd662013-04-01 17:56:59 +00004666** Attempt to set the size of the memory mapping maintained by file
4667** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4668**
4669** If successful, this function sets the following variables:
4670**
4671** unixFile.pMapRegion
4672** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004673** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004674**
4675** If unsuccessful, an error message is logged via sqlite3_log() and
4676** the three variables above are zeroed. In this case SQLite should
4677** continue accessing the database using the xRead() and xWrite()
4678** methods.
4679*/
4680static void unixRemapfile(
4681 unixFile *pFd, /* File descriptor object */
4682 i64 nNew /* Required mapping size */
4683){
dan4ff7bc42013-04-02 12:04:09 +00004684 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004685 int h = pFd->h; /* File descriptor open on db file */
4686 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004687 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004688 u8 *pNew = 0; /* Location of new mapping */
4689 int flags = PROT_READ; /* Flags to pass to mmap() */
4690
4691 assert( pFd->nFetchOut==0 );
4692 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004693 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004694 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004695 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004696 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004697
danfe33e392015-11-17 20:56:06 +00004698#ifdef SQLITE_MMAP_READWRITE
dane6ecd662013-04-01 17:56:59 +00004699 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
danfe33e392015-11-17 20:56:06 +00004700#endif
dane6ecd662013-04-01 17:56:59 +00004701
4702 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00004703#if HAVE_MREMAP
4704 i64 nReuse = pFd->mmapSize;
4705#else
danbc760632014-03-20 09:42:09 +00004706 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00004707 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00004708#endif
dane6ecd662013-04-01 17:56:59 +00004709 u8 *pReq = &pOrig[nReuse];
4710
4711 /* Unmap any pages of the existing mapping that cannot be reused. */
4712 if( nReuse!=nOrig ){
4713 osMunmap(pReq, nOrig-nReuse);
4714 }
4715
4716#if HAVE_MREMAP
4717 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004718 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004719#else
4720 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4721 if( pNew!=MAP_FAILED ){
4722 if( pNew!=pReq ){
4723 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004724 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004725 }else{
4726 pNew = pOrig;
4727 }
4728 }
4729#endif
4730
dan48ccef82013-04-02 20:55:01 +00004731 /* The attempt to extend the existing mapping failed. Free it. */
4732 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004733 osMunmap(pOrig, nReuse);
4734 }
4735 }
4736
4737 /* If pNew is still NULL, try to create an entirely new mapping. */
4738 if( pNew==0 ){
4739 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004740 }
4741
dan4ff7bc42013-04-02 12:04:09 +00004742 if( pNew==MAP_FAILED ){
4743 pNew = 0;
4744 nNew = 0;
4745 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4746
4747 /* If the mmap() above failed, assume that all subsequent mmap() calls
4748 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4749 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004750 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004751 }
dane6ecd662013-04-01 17:56:59 +00004752 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004753 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004754}
4755
4756/*
danaef49d72013-03-25 16:28:54 +00004757** Memory map or remap the file opened by file-descriptor pFd (if the file
4758** is already mapped, the existing mapping is replaced by the new). Or, if
4759** there already exists a mapping for this file, and there are still
4760** outstanding xFetch() references to it, this function is a no-op.
4761**
4762** If parameter nByte is non-negative, then it is the requested size of
4763** the mapping to create. Otherwise, if nByte is less than zero, then the
4764** requested size is the size of the file on disk. The actual size of the
4765** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004766** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004767**
4768** SQLITE_OK is returned if no error occurs (even if the mapping is not
4769** recreated as a result of outstanding references) or an SQLite error
4770** code otherwise.
4771*/
drhf3b1ed02015-12-02 13:11:03 +00004772static int unixMapfile(unixFile *pFd, i64 nMap){
danf23da962013-03-23 21:00:41 +00004773 assert( nMap>=0 || pFd->nFetchOut==0 );
drh333e6ca2015-12-02 15:44:39 +00004774 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00004775 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4776
4777 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00004778 struct stat statbuf; /* Low-level file information */
drhf3b1ed02015-12-02 13:11:03 +00004779 if( osFstat(pFd->h, &statbuf) ){
danf23da962013-03-23 21:00:41 +00004780 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004781 }
drh3044b512014-06-16 16:41:52 +00004782 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00004783 }
drh9b4c59f2013-04-15 17:03:42 +00004784 if( nMap>pFd->mmapSizeMax ){
4785 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004786 }
4787
drh333e6ca2015-12-02 15:44:39 +00004788 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00004789 if( nMap!=pFd->mmapSize ){
drh333e6ca2015-12-02 15:44:39 +00004790 unixRemapfile(pFd, nMap);
dan5d8a1372013-03-19 19:28:06 +00004791 }
4792
danf23da962013-03-23 21:00:41 +00004793 return SQLITE_OK;
4794}
mistachkine98844f2013-08-24 00:59:24 +00004795#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004796
danaef49d72013-03-25 16:28:54 +00004797/*
4798** If possible, return a pointer to a mapping of file fd starting at offset
4799** iOff. The mapping must be valid for at least nAmt bytes.
4800**
4801** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4802** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4803** Finally, if an error does occur, return an SQLite error code. The final
4804** value of *pp is undefined in this case.
4805**
4806** If this function does return a pointer, the caller must eventually
4807** release the reference by calling unixUnfetch().
4808*/
danf23da962013-03-23 21:00:41 +00004809static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004810#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004811 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004812#endif
danf23da962013-03-23 21:00:41 +00004813 *pp = 0;
4814
drh9b4c59f2013-04-15 17:03:42 +00004815#if SQLITE_MAX_MMAP_SIZE>0
4816 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004817 if( pFd->pMapRegion==0 ){
4818 int rc = unixMapfile(pFd, -1);
4819 if( rc!=SQLITE_OK ) return rc;
4820 }
4821 if( pFd->mmapSize >= iOff+nAmt ){
4822 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4823 pFd->nFetchOut++;
4824 }
4825 }
drh6e0b6d52013-04-09 16:19:20 +00004826#endif
danf23da962013-03-23 21:00:41 +00004827 return SQLITE_OK;
4828}
4829
danaef49d72013-03-25 16:28:54 +00004830/*
dandf737fe2013-03-25 17:00:24 +00004831** If the third argument is non-NULL, then this function releases a
4832** reference obtained by an earlier call to unixFetch(). The second
4833** argument passed to this function must be the same as the corresponding
4834** argument that was passed to the unixFetch() invocation.
4835**
4836** Or, if the third argument is NULL, then this function is being called
4837** to inform the VFS layer that, according to POSIX, any existing mapping
4838** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004839*/
dandf737fe2013-03-25 17:00:24 +00004840static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00004841#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00004842 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00004843 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00004844
danaef49d72013-03-25 16:28:54 +00004845 /* If p==0 (unmap the entire file) then there must be no outstanding
4846 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4847 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004848 assert( (p==0)==(pFd->nFetchOut==0) );
4849
dandf737fe2013-03-25 17:00:24 +00004850 /* If p!=0, it must match the iOff value. */
4851 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4852
danf23da962013-03-23 21:00:41 +00004853 if( p ){
4854 pFd->nFetchOut--;
4855 }else{
4856 unixUnmapfile(pFd);
4857 }
4858
4859 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00004860#else
4861 UNUSED_PARAMETER(fd);
4862 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00004863 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00004864#endif
danf23da962013-03-23 21:00:41 +00004865 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004866}
4867
4868/*
drh734c9862008-11-28 15:37:20 +00004869** Here ends the implementation of all sqlite3_file methods.
4870**
4871********************** End sqlite3_file Methods *******************************
4872******************************************************************************/
4873
4874/*
drh6b9d6dd2008-12-03 19:34:47 +00004875** This division contains definitions of sqlite3_io_methods objects that
4876** implement various file locking strategies. It also contains definitions
4877** of "finder" functions. A finder-function is used to locate the appropriate
4878** sqlite3_io_methods object for a particular database file. The pAppData
4879** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4880** the correct finder-function for that VFS.
4881**
4882** Most finder functions return a pointer to a fixed sqlite3_io_methods
4883** object. The only interesting finder-function is autolockIoFinder, which
4884** looks at the filesystem type and tries to guess the best locking
4885** strategy from that.
4886**
peter.d.reid60ec9142014-09-06 16:39:46 +00004887** For finder-function F, two objects are created:
drh1875f7a2008-12-08 18:19:17 +00004888**
4889** (1) The real finder-function named "FImpt()".
4890**
dane946c392009-08-22 11:39:46 +00004891** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004892**
4893**
4894** A pointer to the F pointer is used as the pAppData value for VFS
4895** objects. We have to do this instead of letting pAppData point
4896** directly at the finder-function since C90 rules prevent a void*
4897** from be cast into a function pointer.
4898**
drh6b9d6dd2008-12-03 19:34:47 +00004899**
drh7708e972008-11-29 00:56:52 +00004900** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004901**
drh7708e972008-11-29 00:56:52 +00004902** * A constant sqlite3_io_methods object call METHOD that has locking
4903** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4904**
4905** * An I/O method finder function called FINDER that returns a pointer
4906** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004907*/
drhe6d41732015-02-21 00:49:00 +00004908#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
drh7708e972008-11-29 00:56:52 +00004909static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004910 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004911 CLOSE, /* xClose */ \
4912 unixRead, /* xRead */ \
4913 unixWrite, /* xWrite */ \
4914 unixTruncate, /* xTruncate */ \
4915 unixSync, /* xSync */ \
4916 unixFileSize, /* xFileSize */ \
4917 LOCK, /* xLock */ \
4918 UNLOCK, /* xUnlock */ \
4919 CKLOCK, /* xCheckReservedLock */ \
4920 unixFileControl, /* xFileControl */ \
4921 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004922 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drhd9f94412014-09-22 03:22:27 +00004923 SHMMAP, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004924 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004925 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00004926 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00004927 unixFetch, /* xFetch */ \
4928 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00004929}; \
drh0c2694b2009-09-03 16:23:44 +00004930static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4931 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004932 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004933} \
drh0c2694b2009-09-03 16:23:44 +00004934static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004935 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004936
4937/*
4938** Here are all of the sqlite3_io_methods objects for each of the
4939** locking strategies. Functions that return pointers to these methods
4940** are also created.
4941*/
4942IOMETHODS(
4943 posixIoFinder, /* Finder function name */
4944 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00004945 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00004946 unixClose, /* xClose method */
4947 unixLock, /* xLock method */
4948 unixUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004949 unixCheckReservedLock, /* xCheckReservedLock method */
4950 unixShmMap /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004951)
drh7708e972008-11-29 00:56:52 +00004952IOMETHODS(
4953 nolockIoFinder, /* Finder function name */
4954 nolockIoMethods, /* sqlite3_io_methods object name */
drh142341c2014-09-19 19:00:48 +00004955 3, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004956 nolockClose, /* xClose method */
4957 nolockLock, /* xLock method */
4958 nolockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004959 nolockCheckReservedLock, /* xCheckReservedLock method */
4960 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004961)
drh7708e972008-11-29 00:56:52 +00004962IOMETHODS(
4963 dotlockIoFinder, /* Finder function name */
4964 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004965 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004966 dotlockClose, /* xClose method */
4967 dotlockLock, /* xLock method */
4968 dotlockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004969 dotlockCheckReservedLock, /* xCheckReservedLock method */
4970 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004971)
drh7708e972008-11-29 00:56:52 +00004972
drhe89b2912015-03-03 20:42:01 +00004973#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004974IOMETHODS(
4975 flockIoFinder, /* Finder function name */
4976 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004977 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004978 flockClose, /* xClose method */
4979 flockLock, /* xLock method */
4980 flockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004981 flockCheckReservedLock, /* xCheckReservedLock method */
4982 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004983)
drh7708e972008-11-29 00:56:52 +00004984#endif
4985
drh6c7d5c52008-11-21 20:32:33 +00004986#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004987IOMETHODS(
4988 semIoFinder, /* Finder function name */
4989 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004990 1, /* shared memory is disabled */
drh8cd5b252015-03-02 22:06:43 +00004991 semXClose, /* xClose method */
4992 semXLock, /* xLock method */
4993 semXUnlock, /* xUnlock method */
4994 semXCheckReservedLock, /* xCheckReservedLock method */
drhd9f94412014-09-22 03:22:27 +00004995 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004996)
aswiftaebf4132008-11-21 00:10:35 +00004997#endif
drh7708e972008-11-29 00:56:52 +00004998
drhd2cb50b2009-01-09 21:41:17 +00004999#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005000IOMETHODS(
5001 afpIoFinder, /* Finder function name */
5002 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005003 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005004 afpClose, /* xClose method */
5005 afpLock, /* xLock method */
5006 afpUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005007 afpCheckReservedLock, /* xCheckReservedLock method */
5008 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005009)
drh715ff302008-12-03 22:32:44 +00005010#endif
5011
5012/*
5013** The proxy locking method is a "super-method" in the sense that it
5014** opens secondary file descriptors for the conch and lock files and
5015** it uses proxy, dot-file, AFP, and flock() locking methods on those
5016** secondary files. For this reason, the division that implements
5017** proxy locking is located much further down in the file. But we need
5018** to go ahead and define the sqlite3_io_methods and finder function
5019** for proxy locking here. So we forward declare the I/O methods.
5020*/
drhd2cb50b2009-01-09 21:41:17 +00005021#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005022static int proxyClose(sqlite3_file*);
5023static int proxyLock(sqlite3_file*, int);
5024static int proxyUnlock(sqlite3_file*, int);
5025static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005026IOMETHODS(
5027 proxyIoFinder, /* Finder function name */
5028 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005029 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005030 proxyClose, /* xClose method */
5031 proxyLock, /* xLock method */
5032 proxyUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005033 proxyCheckReservedLock, /* xCheckReservedLock method */
5034 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005035)
aswiftaebf4132008-11-21 00:10:35 +00005036#endif
drh7708e972008-11-29 00:56:52 +00005037
drh7ed97b92010-01-20 13:07:21 +00005038/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5039#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5040IOMETHODS(
5041 nfsIoFinder, /* Finder function name */
5042 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005043 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005044 unixClose, /* xClose method */
5045 unixLock, /* xLock method */
5046 nfsUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005047 unixCheckReservedLock, /* xCheckReservedLock method */
5048 0 /* xShmMap method */
drh7ed97b92010-01-20 13:07:21 +00005049)
5050#endif
drh7708e972008-11-29 00:56:52 +00005051
drhd2cb50b2009-01-09 21:41:17 +00005052#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005053/*
drh6b9d6dd2008-12-03 19:34:47 +00005054** This "finder" function attempts to determine the best locking strategy
5055** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005056** object that implements that strategy.
5057**
5058** This is for MacOSX only.
5059*/
drh1875f7a2008-12-08 18:19:17 +00005060static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005061 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005062 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005063){
5064 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005065 const char *zFilesystem; /* Filesystem type name */
5066 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005067 } aMap[] = {
5068 { "hfs", &posixIoMethods },
5069 { "ufs", &posixIoMethods },
5070 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005071 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005072 { "webdav", &nolockIoMethods },
5073 { 0, 0 }
5074 };
5075 int i;
5076 struct statfs fsInfo;
5077 struct flock lockInfo;
5078
5079 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005080 /* If filePath==NULL that means we are dealing with a transient file
5081 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005082 return &nolockIoMethods;
5083 }
5084 if( statfs(filePath, &fsInfo) != -1 ){
5085 if( fsInfo.f_flags & MNT_RDONLY ){
5086 return &nolockIoMethods;
5087 }
5088 for(i=0; aMap[i].zFilesystem; i++){
5089 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5090 return aMap[i].pMethods;
5091 }
5092 }
5093 }
5094
5095 /* Default case. Handles, amongst others, "nfs".
5096 ** Test byte-range lock using fcntl(). If the call succeeds,
5097 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005098 */
drh7708e972008-11-29 00:56:52 +00005099 lockInfo.l_len = 1;
5100 lockInfo.l_start = 0;
5101 lockInfo.l_whence = SEEK_SET;
5102 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005103 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005104 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5105 return &nfsIoMethods;
5106 } else {
5107 return &posixIoMethods;
5108 }
drh7708e972008-11-29 00:56:52 +00005109 }else{
5110 return &dotlockIoMethods;
5111 }
5112}
drh0c2694b2009-09-03 16:23:44 +00005113static const sqlite3_io_methods
5114 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005115
drhd2cb50b2009-01-09 21:41:17 +00005116#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005117
drhe89b2912015-03-03 20:42:01 +00005118#if OS_VXWORKS
5119/*
5120** This "finder" function for VxWorks checks to see if posix advisory
5121** locking works. If it does, then that is what is used. If it does not
5122** work, then fallback to named semaphore locking.
chw78a13182009-04-07 05:35:03 +00005123*/
drhe89b2912015-03-03 20:42:01 +00005124static const sqlite3_io_methods *vxworksIoFinderImpl(
chw78a13182009-04-07 05:35:03 +00005125 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005126 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005127){
5128 struct flock lockInfo;
5129
5130 if( !filePath ){
5131 /* If filePath==NULL that means we are dealing with a transient file
5132 ** that does not need to be locked. */
5133 return &nolockIoMethods;
5134 }
5135
5136 /* Test if fcntl() is supported and use POSIX style locks.
5137 ** Otherwise fall back to the named semaphore method.
5138 */
5139 lockInfo.l_len = 1;
5140 lockInfo.l_start = 0;
5141 lockInfo.l_whence = SEEK_SET;
5142 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005143 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005144 return &posixIoMethods;
5145 }else{
5146 return &semIoMethods;
5147 }
5148}
drh0c2694b2009-09-03 16:23:44 +00005149static const sqlite3_io_methods
drhe89b2912015-03-03 20:42:01 +00005150 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005151
drhe89b2912015-03-03 20:42:01 +00005152#endif /* OS_VXWORKS */
chw78a13182009-04-07 05:35:03 +00005153
drh7708e972008-11-29 00:56:52 +00005154/*
peter.d.reid60ec9142014-09-06 16:39:46 +00005155** An abstract type for a pointer to an IO method finder function:
drh7708e972008-11-29 00:56:52 +00005156*/
drh0c2694b2009-09-03 16:23:44 +00005157typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005158
aswiftaebf4132008-11-21 00:10:35 +00005159
drh734c9862008-11-28 15:37:20 +00005160/****************************************************************************
5161**************************** sqlite3_vfs methods ****************************
5162**
5163** This division contains the implementation of methods on the
5164** sqlite3_vfs object.
5165*/
5166
danielk1977a3d4c882007-03-23 10:08:38 +00005167/*
danielk1977e339d652008-06-28 11:23:00 +00005168** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005169*/
5170static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005171 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005172 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005173 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005174 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005175 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005176){
drh7708e972008-11-29 00:56:52 +00005177 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005178 unixFile *pNew = (unixFile *)pId;
5179 int rc = SQLITE_OK;
5180
drh8af6c222010-05-14 12:43:01 +00005181 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005182
dan00157392010-10-05 11:33:15 +00005183 /* Usually the path zFilename should not be a relative pathname. The
5184 ** exception is when opening the proxy "conch" file in builds that
5185 ** include the special Apple locking styles.
5186 */
dan00157392010-10-05 11:33:15 +00005187#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005188 assert( zFilename==0 || zFilename[0]=='/'
5189 || pVfs->pAppData==(void*)&autolockIoFinder );
5190#else
5191 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005192#endif
dan00157392010-10-05 11:33:15 +00005193
drhb07028f2011-10-14 21:49:18 +00005194 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005195 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005196
drh308c2a52010-05-14 11:30:18 +00005197 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005198 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005199 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005200 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005201 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005202#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005203 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005204#endif
drhc02a43a2012-01-10 23:18:38 +00005205 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5206 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005207 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005208 }
drh503a6862013-03-01 01:07:17 +00005209 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005210 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005211 }
drh339eb0b2008-03-07 15:34:11 +00005212
drh6c7d5c52008-11-21 20:32:33 +00005213#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005214 pNew->pId = vxworksFindFileId(zFilename);
5215 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005216 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00005217 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00005218 }
5219#endif
5220
drhc02a43a2012-01-10 23:18:38 +00005221 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005222 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005223 }else{
drh0c2694b2009-09-03 16:23:44 +00005224 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005225#if SQLITE_ENABLE_LOCKING_STYLE
5226 /* Cache zFilename in the locking context (AFP and dotlock override) for
5227 ** proxyLock activation is possible (remote proxy is based on db name)
5228 ** zFilename remains valid until file is closed, to support */
5229 pNew->lockingContext = (void*)zFilename;
5230#endif
drhda0e7682008-07-30 15:27:54 +00005231 }
danielk1977e339d652008-06-28 11:23:00 +00005232
drh7ed97b92010-01-20 13:07:21 +00005233 if( pLockingStyle == &posixIoMethods
5234#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5235 || pLockingStyle == &nfsIoMethods
5236#endif
5237 ){
drh7708e972008-11-29 00:56:52 +00005238 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005239 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005240 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005241 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005242 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005243 ** in two scenarios:
5244 **
5245 ** (a) A call to fstat() failed.
5246 ** (b) A malloc failed.
5247 **
5248 ** Scenario (b) may only occur if the process is holding no other
5249 ** file descriptors open on the same file. If there were other file
5250 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005251 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005252 ** handle h - as it is guaranteed that no posix locks will be released
5253 ** by doing so.
5254 **
5255 ** If scenario (a) caused the error then things are not so safe. The
5256 ** implicit assumption here is that if fstat() fails, things are in
5257 ** such bad shape that dropping a lock or two doesn't matter much.
5258 */
drh0e9365c2011-03-02 02:08:13 +00005259 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005260 h = -1;
5261 }
drh7708e972008-11-29 00:56:52 +00005262 unixLeaveMutex();
5263 }
danielk1977e339d652008-06-28 11:23:00 +00005264
drhd2cb50b2009-01-09 21:41:17 +00005265#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005266 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005267 /* AFP locking uses the file path so it needs to be included in
5268 ** the afpLockingContext.
5269 */
5270 afpLockingContext *pCtx;
drhf3cdcdc2015-04-29 16:50:28 +00005271 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh7708e972008-11-29 00:56:52 +00005272 if( pCtx==0 ){
5273 rc = SQLITE_NOMEM;
5274 }else{
5275 /* NB: zFilename exists and remains valid until the file is closed
5276 ** according to requirement F11141. So we do not need to make a
5277 ** copy of the filename. */
5278 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005279 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005280 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005281 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005282 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005283 if( rc!=SQLITE_OK ){
5284 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005285 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005286 h = -1;
5287 }
drh7708e972008-11-29 00:56:52 +00005288 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005289 }
drh7708e972008-11-29 00:56:52 +00005290 }
5291#endif
danielk1977e339d652008-06-28 11:23:00 +00005292
drh7708e972008-11-29 00:56:52 +00005293 else if( pLockingStyle == &dotlockIoMethods ){
5294 /* Dotfile locking uses the file path so it needs to be included in
5295 ** the dotlockLockingContext
5296 */
5297 char *zLockFile;
5298 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005299 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005300 nFilename = (int)strlen(zFilename) + 6;
drhf3cdcdc2015-04-29 16:50:28 +00005301 zLockFile = (char *)sqlite3_malloc64(nFilename);
drh7708e972008-11-29 00:56:52 +00005302 if( zLockFile==0 ){
5303 rc = SQLITE_NOMEM;
5304 }else{
5305 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005306 }
drh7708e972008-11-29 00:56:52 +00005307 pNew->lockingContext = zLockFile;
5308 }
danielk1977e339d652008-06-28 11:23:00 +00005309
drh6c7d5c52008-11-21 20:32:33 +00005310#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005311 else if( pLockingStyle == &semIoMethods ){
5312 /* Named semaphore locking uses the file path so it needs to be
5313 ** included in the semLockingContext
5314 */
5315 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005316 rc = findInodeInfo(pNew, &pNew->pInode);
5317 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5318 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005319 int n;
drh2238dcc2009-08-27 17:56:20 +00005320 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005321 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005322 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005323 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005324 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5325 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00005326 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00005327 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005328 }
chw97185482008-11-17 08:05:31 +00005329 }
drh7708e972008-11-29 00:56:52 +00005330 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005331 }
drh7708e972008-11-29 00:56:52 +00005332#endif
aswift5b1a2562008-08-22 00:22:35 +00005333
drh4bf66fd2015-02-19 02:43:02 +00005334 storeLastErrno(pNew, 0);
drh6c7d5c52008-11-21 20:32:33 +00005335#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005336 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005337 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005338 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005339 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005340 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005341 }
chw97185482008-11-17 08:05:31 +00005342#endif
danielk1977e339d652008-06-28 11:23:00 +00005343 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005344 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005345 }else{
drh7708e972008-11-29 00:56:52 +00005346 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005347 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005348 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005349 }
danielk1977e339d652008-06-28 11:23:00 +00005350 return rc;
drh054889e2005-11-30 03:20:31 +00005351}
drh9c06c952005-11-26 00:25:00 +00005352
danielk1977ad94b582007-08-20 06:44:22 +00005353/*
drh8b3cf822010-06-01 21:02:51 +00005354** Return the name of a directory in which to put temporary files.
5355** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005356*/
drh7234c6d2010-06-19 15:10:09 +00005357static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005358 static const char *azDirs[] = {
5359 0,
aswiftaebf4132008-11-21 00:10:35 +00005360 0,
danielk197717b90b52008-06-06 11:11:25 +00005361 "/var/tmp",
5362 "/usr/tmp",
5363 "/tmp",
drhb7e50ad2015-11-28 21:49:53 +00005364 "."
danielk197717b90b52008-06-06 11:11:25 +00005365 };
drh8b3cf822010-06-01 21:02:51 +00005366 unsigned int i;
5367 struct stat buf;
drhb7e50ad2015-11-28 21:49:53 +00005368 const char *zDir = sqlite3_temp_directory;
drh8b3cf822010-06-01 21:02:51 +00005369
drhb7e50ad2015-11-28 21:49:53 +00005370 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
5371 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005372 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005373 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005374 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005375 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005376 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005377 break;
5378 }
5379 return zDir;
5380}
5381
5382/*
5383** Create a temporary file name in zBuf. zBuf must be allocated
5384** by the calling process and must be big enough to hold at least
5385** pVfs->mxPathname bytes.
5386*/
5387static int unixGetTempname(int nBuf, char *zBuf){
drh8b3cf822010-06-01 21:02:51 +00005388 const char *zDir;
drhb7e50ad2015-11-28 21:49:53 +00005389 int iLimit = 0;
danielk197717b90b52008-06-06 11:11:25 +00005390
5391 /* It's odd to simulate an io-error here, but really this is just
5392 ** using the io-error infrastructure to test that SQLite handles this
5393 ** function failing.
5394 */
5395 SimulateIOError( return SQLITE_IOERR );
5396
drh7234c6d2010-06-19 15:10:09 +00005397 zDir = unixTempFileDir();
danielk197717b90b52008-06-06 11:11:25 +00005398 do{
drh970942e2015-11-25 23:13:14 +00005399 u64 r;
5400 sqlite3_randomness(sizeof(r), &r);
5401 assert( nBuf>2 );
5402 zBuf[nBuf-2] = 0;
5403 sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
5404 zDir, r, 0);
drhb7e50ad2015-11-28 21:49:53 +00005405 if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
drh99ab3b12011-03-02 15:09:07 +00005406 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005407 return SQLITE_OK;
5408}
5409
drhd2cb50b2009-01-09 21:41:17 +00005410#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005411/*
5412** Routine to transform a unixFile into a proxy-locking unixFile.
5413** Implementation in the proxy-lock division, but used by unixOpen()
5414** if SQLITE_PREFER_PROXY_LOCKING is defined.
5415*/
5416static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005417#endif
drhc66d5b62008-12-03 22:48:32 +00005418
dan08da86a2009-08-21 17:18:03 +00005419/*
5420** Search for an unused file descriptor that was opened on the database
5421** file (not a journal or master-journal file) identified by pathname
5422** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5423** argument to this function.
5424**
5425** Such a file descriptor may exist if a database connection was closed
5426** but the associated file descriptor could not be closed because some
5427** other file descriptor open on the same file is holding a file-lock.
5428** Refer to comments in the unixClose() function and the lengthy comment
5429** describing "Posix Advisory Locking" at the start of this file for
5430** further details. Also, ticket #4018.
5431**
5432** If a suitable file descriptor is found, then it is returned. If no
5433** such file descriptor is located, -1 is returned.
5434*/
dane946c392009-08-22 11:39:46 +00005435static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5436 UnixUnusedFd *pUnused = 0;
5437
5438 /* Do not search for an unused file descriptor on vxworks. Not because
5439 ** vxworks would not benefit from the change (it might, we're not sure),
5440 ** but because no way to test it is currently available. It is better
5441 ** not to risk breaking vxworks support for the sake of such an obscure
5442 ** feature. */
5443#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005444 struct stat sStat; /* Results of stat() call */
5445
5446 /* A stat() call may fail for various reasons. If this happens, it is
5447 ** almost certain that an open() call on the same path will also fail.
5448 ** For this reason, if an error occurs in the stat() call here, it is
5449 ** ignored and -1 is returned. The caller will try to open a new file
5450 ** descriptor on the same path, fail, and return an error to SQLite.
5451 **
5452 ** Even if a subsequent open() call does succeed, the consequences of
peter.d.reid60ec9142014-09-06 16:39:46 +00005453 ** not searching for a reusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005454 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005455 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005456
5457 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005458 pInode = inodeList;
5459 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5460 || pInode->fileId.ino!=sStat.st_ino) ){
5461 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005462 }
drh8af6c222010-05-14 12:43:01 +00005463 if( pInode ){
dane946c392009-08-22 11:39:46 +00005464 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005465 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005466 pUnused = *pp;
5467 if( pUnused ){
5468 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005469 }
5470 }
5471 unixLeaveMutex();
5472 }
dane946c392009-08-22 11:39:46 +00005473#endif /* if !OS_VXWORKS */
5474 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005475}
danielk197717b90b52008-06-06 11:11:25 +00005476
5477/*
danddb0ac42010-07-14 14:48:58 +00005478** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005479** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005480** and a value suitable for passing as the third argument to open(2) is
5481** written to *pMode. If an IO error occurs, an SQLite error code is
5482** returned and the value of *pMode is not modified.
5483**
peter.d.reid60ec9142014-09-06 16:39:46 +00005484** In most cases, this routine sets *pMode to 0, which will become
drh8c815d12012-02-13 20:16:37 +00005485** an indication to robust_open() to create the file using
5486** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5487** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005488** this function queries the file-system for the permissions on the
5489** corresponding database file and sets *pMode to this value. Whenever
5490** possible, WAL and journal files are created using the same permissions
5491** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005492**
5493** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5494** original filename is unavailable. But 8_3_NAMES is only used for
5495** FAT filesystems and permissions do not matter there, so just use
5496** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005497*/
5498static int findCreateFileMode(
5499 const char *zPath, /* Path of file (possibly) being created */
5500 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005501 mode_t *pMode, /* OUT: Permissions to open file with */
5502 uid_t *pUid, /* OUT: uid to set on the file */
5503 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005504){
5505 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005506 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005507 *pUid = 0;
5508 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005509 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005510 char zDb[MAX_PATHNAME+1]; /* Database file path */
5511 int nDb; /* Number of valid bytes in zDb */
5512 struct stat sStat; /* Output of stat() on database file */
5513
dana0c989d2010-11-05 18:07:37 +00005514 /* zPath is a path to a WAL or journal file. The following block derives
5515 ** the path to the associated database file from zPath. This block handles
5516 ** the following naming conventions:
5517 **
5518 ** "<path to db>-journal"
5519 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005520 ** "<path to db>-journalNN"
5521 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005522 **
drhd337c5b2011-10-20 18:23:35 +00005523 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005524 ** used by the test_multiplex.c module.
5525 */
5526 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005527 while( zPath[nDb]!='-' ){
drh90e5dda2015-12-03 20:42:28 +00005528#ifndef SQLITE_ENABLE_8_3_NAMES
5529 /* In the normal case (8+3 filenames disabled) the journal filename
5530 ** is guaranteed to contain a '-' character. */
drhc47167a2011-10-05 15:26:13 +00005531 assert( nDb>0 );
drh90e5dda2015-12-03 20:42:28 +00005532 assert( sqlite3Isalnum(zPath[nDb]) );
5533#else
5534 /* If 8+3 names are possible, then the journal file might not contain
5535 ** a '-' character. So check for that case and return early. */
5536 if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
5537#endif
drhc47167a2011-10-05 15:26:13 +00005538 nDb--;
5539 }
danddb0ac42010-07-14 14:48:58 +00005540 memcpy(zDb, zPath, nDb);
5541 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005542
drh58384f12011-07-28 00:14:45 +00005543 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005544 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005545 *pUid = sStat.st_uid;
5546 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005547 }else{
5548 rc = SQLITE_IOERR_FSTAT;
5549 }
5550 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5551 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005552 }
5553 return rc;
5554}
5555
5556/*
danielk1977ad94b582007-08-20 06:44:22 +00005557** Open the file zPath.
5558**
danielk1977b4b47412007-08-17 15:53:36 +00005559** Previously, the SQLite OS layer used three functions in place of this
5560** one:
5561**
5562** sqlite3OsOpenReadWrite();
5563** sqlite3OsOpenReadOnly();
5564** sqlite3OsOpenExclusive();
5565**
5566** These calls correspond to the following combinations of flags:
5567**
5568** ReadWrite() -> (READWRITE | CREATE)
5569** ReadOnly() -> (READONLY)
5570** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5571**
5572** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5573** true, the file was configured to be automatically deleted when the
5574** file handle closed. To achieve the same effect using this new
5575** interface, add the DELETEONCLOSE flag to those specified above for
5576** OpenExclusive().
5577*/
5578static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005579 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5580 const char *zPath, /* Pathname of file to be opened */
5581 sqlite3_file *pFile, /* The file descriptor to be filled in */
5582 int flags, /* Input flags to control the opening */
5583 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005584){
dan08da86a2009-08-21 17:18:03 +00005585 unixFile *p = (unixFile *)pFile;
5586 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005587 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005588 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005589 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005590 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005591 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005592
5593 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5594 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5595 int isCreate = (flags & SQLITE_OPEN_CREATE);
5596 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5597 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005598#if SQLITE_ENABLE_LOCKING_STYLE
5599 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5600#endif
drh3d4435b2011-08-26 20:55:50 +00005601#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5602 struct statfs fsInfo;
5603#endif
danielk1977b4b47412007-08-17 15:53:36 +00005604
danielk1977fee2d252007-08-18 10:59:19 +00005605 /* If creating a master or main-file journal, this function will open
5606 ** a file-descriptor on the directory too. The first time unixSync()
5607 ** is called the directory file descriptor will be fsync()ed and close()d.
5608 */
drh0059eae2011-08-08 23:48:40 +00005609 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005610 eType==SQLITE_OPEN_MASTER_JOURNAL
5611 || eType==SQLITE_OPEN_MAIN_JOURNAL
5612 || eType==SQLITE_OPEN_WAL
5613 ));
danielk1977fee2d252007-08-18 10:59:19 +00005614
danielk197717b90b52008-06-06 11:11:25 +00005615 /* If argument zPath is a NULL pointer, this function is required to open
5616 ** a temporary file. Use this buffer to store the file name in.
5617 */
drhc02a43a2012-01-10 23:18:38 +00005618 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005619 const char *zName = zPath;
5620
danielk1977fee2d252007-08-18 10:59:19 +00005621 /* Check the following statements are true:
5622 **
5623 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5624 ** (b) if CREATE is set, then READWRITE must also be set, and
5625 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005626 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005627 */
danielk1977b4b47412007-08-17 15:53:36 +00005628 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005629 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005630 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005631 assert(isDelete==0 || isCreate);
5632
danddb0ac42010-07-14 14:48:58 +00005633 /* The main DB, main journal, WAL file and master journal are never
5634 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005635 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5636 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5637 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005638 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005639
danielk1977fee2d252007-08-18 10:59:19 +00005640 /* Assert that the upper layer has set one of the "file-type" flags. */
5641 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5642 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5643 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005644 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005645 );
5646
drhb00d8622014-01-01 15:18:36 +00005647 /* Detect a pid change and reset the PRNG. There is a race condition
5648 ** here such that two or more threads all trying to open databases at
5649 ** the same instant might all reset the PRNG. But multiple resets
5650 ** are harmless.
5651 */
drh5ac93652015-03-21 20:59:43 +00005652 if( randomnessPid!=osGetpid(0) ){
5653 randomnessPid = osGetpid(0);
drhb00d8622014-01-01 15:18:36 +00005654 sqlite3_randomness(0,0);
5655 }
5656
dan08da86a2009-08-21 17:18:03 +00005657 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005658
dan08da86a2009-08-21 17:18:03 +00005659 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005660 UnixUnusedFd *pUnused;
5661 pUnused = findReusableFd(zName, flags);
5662 if( pUnused ){
5663 fd = pUnused->fd;
5664 }else{
drhf3cdcdc2015-04-29 16:50:28 +00005665 pUnused = sqlite3_malloc64(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005666 if( !pUnused ){
5667 return SQLITE_NOMEM;
5668 }
5669 }
5670 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005671
5672 /* Database filenames are double-zero terminated if they are not
5673 ** URIs with parameters. Hence, they can always be passed into
5674 ** sqlite3_uri_parameter(). */
5675 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5676
dan08da86a2009-08-21 17:18:03 +00005677 }else if( !zName ){
5678 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005679 assert(isDelete && !syncDir);
drhb7e50ad2015-11-28 21:49:53 +00005680 rc = unixGetTempname(pVfs->mxPathname, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005681 if( rc!=SQLITE_OK ){
5682 return rc;
5683 }
5684 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005685
5686 /* Generated temporary filenames are always double-zero terminated
5687 ** for use by sqlite3_uri_parameter(). */
5688 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005689 }
5690
dan08da86a2009-08-21 17:18:03 +00005691 /* Determine the value of the flags parameter passed to POSIX function
5692 ** open(). These must be calculated even if open() is not called, as
5693 ** they may be stored as part of the file handle and used by the
5694 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005695 if( isReadonly ) openFlags |= O_RDONLY;
5696 if( isReadWrite ) openFlags |= O_RDWR;
5697 if( isCreate ) openFlags |= O_CREAT;
5698 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5699 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005700
danielk1977b4b47412007-08-17 15:53:36 +00005701 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005702 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005703 uid_t uid; /* Userid for the file */
5704 gid_t gid; /* Groupid for the file */
5705 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005706 if( rc!=SQLITE_OK ){
5707 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005708 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005709 return rc;
5710 }
drhad4f1e52011-03-04 15:43:57 +00005711 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005712 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
drh5a2d9702015-11-26 02:21:05 +00005713 assert( !isExclusive || (openFlags & O_CREAT)!=0 );
5714 if( fd<0 && errno!=EISDIR && isReadWrite ){
dan08da86a2009-08-21 17:18:03 +00005715 /* Failed to open the file for read/write access. Try read-only. */
5716 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005717 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005718 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005719 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005720 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005721 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005722 }
5723 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005724 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005725 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005726 }
drhac7c3ac2012-02-11 19:23:48 +00005727
5728 /* If this process is running as root and if creating a new rollback
5729 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005730 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005731 */
5732 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drh6226ca22015-11-24 15:06:28 +00005733 robustFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005734 }
danielk1977b4b47412007-08-17 15:53:36 +00005735 }
dan08da86a2009-08-21 17:18:03 +00005736 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005737 if( pOutFlags ){
5738 *pOutFlags = flags;
5739 }
5740
dane946c392009-08-22 11:39:46 +00005741 if( p->pUnused ){
5742 p->pUnused->fd = fd;
5743 p->pUnused->flags = flags;
5744 }
5745
danielk1977b4b47412007-08-17 15:53:36 +00005746 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005747#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005748 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00005749#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
5750 zPath = sqlite3_mprintf("%s", zName);
5751 if( zPath==0 ){
5752 robust_close(p, fd, __LINE__);
5753 return SQLITE_NOMEM;
5754 }
chw97185482008-11-17 08:05:31 +00005755#else
drh036ac7f2011-08-08 23:18:05 +00005756 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005757#endif
danielk1977b4b47412007-08-17 15:53:36 +00005758 }
drh41022642008-11-21 00:24:42 +00005759#if SQLITE_ENABLE_LOCKING_STYLE
5760 else{
dan08da86a2009-08-21 17:18:03 +00005761 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005762 }
5763#endif
5764
drhda0e7682008-07-30 15:27:54 +00005765 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005766
drh7ed97b92010-01-20 13:07:21 +00005767
5768#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005769 if( fstatfs(fd, &fsInfo) == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00005770 storeLastErrno(p, errno);
drh0e9365c2011-03-02 02:08:13 +00005771 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005772 return SQLITE_IOERR_ACCESS;
5773 }
5774 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5775 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5776 }
drh4bf66fd2015-02-19 02:43:02 +00005777 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
5778 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5779 }
drh7ed97b92010-01-20 13:07:21 +00005780#endif
drhc02a43a2012-01-10 23:18:38 +00005781
5782 /* Set up appropriate ctrlFlags */
5783 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5784 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5785 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5786 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5787 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5788
drh7ed97b92010-01-20 13:07:21 +00005789#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005790#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005791 isAutoProxy = 1;
5792#endif
5793 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005794 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5795 int useProxy = 0;
5796
dan08da86a2009-08-21 17:18:03 +00005797 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5798 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005799 if( envforce!=NULL ){
5800 useProxy = atoi(envforce)>0;
5801 }else{
aswiftaebf4132008-11-21 00:10:35 +00005802 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5803 }
5804 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005805 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005806 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005807 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005808 if( rc!=SQLITE_OK ){
5809 /* Use unixClose to clean up the resources added in fillInUnixFile
5810 ** and clear all the structure's references. Specifically,
5811 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5812 */
5813 unixClose(pFile);
5814 return rc;
5815 }
aswiftaebf4132008-11-21 00:10:35 +00005816 }
dane946c392009-08-22 11:39:46 +00005817 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005818 }
5819 }
5820#endif
5821
drhc02a43a2012-01-10 23:18:38 +00005822 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5823
dane946c392009-08-22 11:39:46 +00005824open_finished:
5825 if( rc!=SQLITE_OK ){
5826 sqlite3_free(p->pUnused);
5827 }
5828 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005829}
5830
dane946c392009-08-22 11:39:46 +00005831
danielk1977b4b47412007-08-17 15:53:36 +00005832/*
danielk1977fee2d252007-08-18 10:59:19 +00005833** Delete the file at zPath. If the dirSync argument is true, fsync()
5834** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005835*/
drh6b9d6dd2008-12-03 19:34:47 +00005836static int unixDelete(
5837 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5838 const char *zPath, /* Name of file to be deleted */
5839 int dirSync /* If true, fsync() directory after deleting file */
5840){
danielk1977fee2d252007-08-18 10:59:19 +00005841 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005842 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005843 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005844 if( osUnlink(zPath)==(-1) ){
drhbd945542014-08-13 11:39:42 +00005845 if( errno==ENOENT
5846#if OS_VXWORKS
drh19541f32014-09-01 13:37:55 +00005847 || osAccess(zPath,0)!=0
drhbd945542014-08-13 11:39:42 +00005848#endif
5849 ){
dan9fc5b4a2012-11-09 20:17:26 +00005850 rc = SQLITE_IOERR_DELETE_NOENT;
5851 }else{
drhb4308162012-11-09 21:40:02 +00005852 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005853 }
drhb4308162012-11-09 21:40:02 +00005854 return rc;
drh5d4feff2010-07-14 01:45:22 +00005855 }
danielk1977d39fa702008-10-16 13:27:40 +00005856#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005857 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005858 int fd;
drh90315a22011-08-10 01:52:12 +00005859 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005860 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005861#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005862 if( fsync(fd)==-1 )
5863#else
5864 if( fsync(fd) )
5865#endif
5866 {
dane18d4952011-02-21 11:46:24 +00005867 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005868 }
drh0e9365c2011-03-02 02:08:13 +00005869 robust_close(0, fd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00005870 }else{
5871 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00005872 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005873 }
5874 }
danielk1977d138dd82008-10-15 16:02:48 +00005875#endif
danielk1977fee2d252007-08-18 10:59:19 +00005876 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005877}
5878
danielk197790949c22007-08-17 16:50:38 +00005879/*
mistachkin48864df2013-03-21 21:20:32 +00005880** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00005881** test performed depends on the value of flags:
5882**
5883** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5884** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5885** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5886**
5887** Otherwise return 0.
5888*/
danielk1977861f7452008-06-05 11:39:11 +00005889static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005890 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5891 const char *zPath, /* Path of the file to examine */
5892 int flags, /* What do we want to learn about the zPath file? */
5893 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005894){
danielk1977397d65f2008-11-19 11:35:39 +00005895 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005896 SimulateIOError( return SQLITE_IOERR_ACCESS; );
drhd260b5b2015-11-25 18:03:33 +00005897 assert( pResOut!=0 );
danielk1977b4b47412007-08-17 15:53:36 +00005898
drhd260b5b2015-11-25 18:03:33 +00005899 /* The spec says there are three possible values for flags. But only
5900 ** two of them are actually used */
5901 assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
5902
5903 if( flags==SQLITE_ACCESS_EXISTS ){
dan83acd422010-06-18 11:10:06 +00005904 struct stat buf;
drhd260b5b2015-11-25 18:03:33 +00005905 *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
5906 }else{
5907 *pResOut = osAccess(zPath, W_OK|R_OK)==0;
dan83acd422010-06-18 11:10:06 +00005908 }
danielk1977861f7452008-06-05 11:39:11 +00005909 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005910}
5911
danielk1977b4b47412007-08-17 15:53:36 +00005912
5913/*
5914** Turn a relative pathname into a full pathname. The relative path
5915** is stored as a nul-terminated string in the buffer pointed to by
5916** zPath.
5917**
5918** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5919** (in this case, MAX_PATHNAME bytes). The full-path is written to
5920** this buffer before returning.
5921*/
danielk1977adfb9b02007-09-17 07:02:56 +00005922static int unixFullPathname(
5923 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5924 const char *zPath, /* Possibly relative input path */
5925 int nOut, /* Size of output buffer in bytes */
5926 char *zOut /* Output buffer */
5927){
dan245fdc62015-10-31 17:58:33 +00005928 int nByte;
danielk1977843e65f2007-09-01 16:16:15 +00005929
5930 /* It's odd to simulate an io-error here, but really this is just
5931 ** using the io-error infrastructure to test that SQLite handles this
5932 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005933 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005934 */
5935 SimulateIOError( return SQLITE_ERROR );
5936
drh153c62c2007-08-24 03:51:33 +00005937 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005938 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005939
dan245fdc62015-10-31 17:58:33 +00005940 /* Attempt to resolve the path as if it were a symbolic link. If it is
5941 ** a symbolic link, the resolved path is stored in buffer zOut[]. Or, if
5942 ** the identified file is not a symbolic link or does not exist, then
5943 ** zPath is copied directly into zOut. Either way, nByte is left set to
5944 ** the size of the string copied into zOut[] in bytes. */
5945 nByte = osReadlink(zPath, zOut, nOut-1);
5946 if( nByte<0 ){
5947 if( errno!=EINVAL && errno!=ENOENT ){
5948 return unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zPath);
5949 }
drhd260b5b2015-11-25 18:03:33 +00005950 sqlite3_snprintf(nOut, zOut, "%s", zPath);
dan245fdc62015-10-31 17:58:33 +00005951 nByte = sqlite3Strlen30(zOut);
danielk1977b4b47412007-08-17 15:53:36 +00005952 }else{
dan245fdc62015-10-31 17:58:33 +00005953 zOut[nByte] = '\0';
5954 }
5955
5956 /* If buffer zOut[] now contains an absolute path there is nothing more
5957 ** to do. If it contains a relative path, do the following:
5958 **
5959 ** * move the relative path string so that it is at the end of th
5960 ** zOut[] buffer.
5961 ** * Call getcwd() to read the path of the current working directory
5962 ** into the start of the zOut[] buffer.
5963 ** * Append a '/' character to the cwd string and move the
5964 ** relative path back within the buffer so that it immediately
5965 ** follows the '/'.
5966 **
5967 ** This code is written so that if the combination of the CWD and relative
5968 ** path are larger than the allocated size of zOut[] the CWD is silently
5969 ** truncated to make it fit. This is Ok, as SQLite refuses to open any
5970 ** file for which this function returns a full path larger than (nOut-8)
5971 ** bytes in size. */
drh025d2f72015-11-30 22:22:23 +00005972 testcase( nByte==nOut-5 );
5973 testcase( nByte==nOut-4 );
5974 if( zOut[0]!='/' && nByte<nOut-4 ){
danielk1977b4b47412007-08-17 15:53:36 +00005975 int nCwd;
dan245fdc62015-10-31 17:58:33 +00005976 int nRem = nOut-nByte-1;
5977 memmove(&zOut[nRem], zOut, nByte+1);
5978 zOut[nRem-1] = '\0';
5979 if( osGetcwd(zOut, nRem-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005980 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005981 }
dan245fdc62015-10-31 17:58:33 +00005982 nCwd = sqlite3Strlen30(zOut);
5983 assert( nCwd<=nRem-1 );
5984 zOut[nCwd] = '/';
5985 memmove(&zOut[nCwd+1], &zOut[nRem], nByte+1);
danielk1977b4b47412007-08-17 15:53:36 +00005986 }
dan245fdc62015-10-31 17:58:33 +00005987
danielk1977b4b47412007-08-17 15:53:36 +00005988 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005989}
5990
drh0ccebe72005-06-07 22:22:50 +00005991
drh761df872006-12-21 01:29:22 +00005992#ifndef SQLITE_OMIT_LOAD_EXTENSION
5993/*
5994** Interfaces for opening a shared library, finding entry points
5995** within the shared library, and closing the shared library.
5996*/
5997#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005998static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5999 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00006000 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6001}
danielk197795c8a542007-09-01 06:51:27 +00006002
6003/*
6004** SQLite calls this function immediately after a call to unixDlSym() or
6005** unixDlOpen() fails (returns a null pointer). If a more detailed error
6006** message is available, it is written to zBufOut. If no error message
6007** is available, zBufOut is left unmodified and SQLite uses a default
6008** error message.
6009*/
danielk1977397d65f2008-11-19 11:35:39 +00006010static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006011 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006012 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006013 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006014 zErr = dlerror();
6015 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006016 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006017 }
drh6c7d5c52008-11-21 20:32:33 +00006018 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006019}
drh1875f7a2008-12-08 18:19:17 +00006020static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6021 /*
6022 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6023 ** cast into a pointer to a function. And yet the library dlsym() routine
6024 ** returns a void* which is really a pointer to a function. So how do we
6025 ** use dlsym() with -pedantic-errors?
6026 **
6027 ** Variable x below is defined to be a pointer to a function taking
6028 ** parameters void* and const char* and returning a pointer to a function.
6029 ** We initialize x by assigning it a pointer to the dlsym() function.
6030 ** (That assignment requires a cast.) Then we call the function that
6031 ** x points to.
6032 **
6033 ** This work-around is unlikely to work correctly on any system where
6034 ** you really cannot cast a function pointer into void*. But then, on the
6035 ** other hand, dlsym() will not work on such a system either, so we have
6036 ** not really lost anything.
6037 */
6038 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006039 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006040 x = (void(*(*)(void*,const char*))(void))dlsym;
6041 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006042}
danielk1977397d65f2008-11-19 11:35:39 +00006043static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6044 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006045 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006046}
danielk1977b4b47412007-08-17 15:53:36 +00006047#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6048 #define unixDlOpen 0
6049 #define unixDlError 0
6050 #define unixDlSym 0
6051 #define unixDlClose 0
6052#endif
6053
6054/*
danielk197790949c22007-08-17 16:50:38 +00006055** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006056*/
danielk1977397d65f2008-11-19 11:35:39 +00006057static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6058 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006059 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006060
drhbbd42a62004-05-22 17:41:58 +00006061 /* We have to initialize zBuf to prevent valgrind from reporting
6062 ** errors. The reports issued by valgrind are incorrect - we would
6063 ** prefer that the randomness be increased by making use of the
6064 ** uninitialized space in zBuf - but valgrind errors tend to worry
6065 ** some users. Rather than argue, it seems easier just to initialize
6066 ** the whole array and silence valgrind, even if that means less randomness
6067 ** in the random seed.
6068 **
6069 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006070 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006071 ** tests repeatable.
6072 */
danielk1977b4b47412007-08-17 15:53:36 +00006073 memset(zBuf, 0, nBuf);
drh5ac93652015-03-21 20:59:43 +00006074 randomnessPid = osGetpid(0);
drh6a412b82015-04-30 12:31:49 +00006075#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
drhbbd42a62004-05-22 17:41:58 +00006076 {
drhb00d8622014-01-01 15:18:36 +00006077 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006078 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006079 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006080 time_t t;
6081 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006082 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006083 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6084 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6085 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006086 }else{
drhc18b4042012-02-10 03:10:27 +00006087 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006088 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006089 }
drhbbd42a62004-05-22 17:41:58 +00006090 }
6091#endif
drh72cbd072008-10-14 17:58:38 +00006092 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006093}
6094
danielk1977b4b47412007-08-17 15:53:36 +00006095
drhbbd42a62004-05-22 17:41:58 +00006096/*
6097** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006098** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006099** The return value is the number of microseconds of sleep actually
6100** requested from the underlying operating system, a number which
6101** might be greater than or equal to the argument, but not less
6102** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006103*/
danielk1977397d65f2008-11-19 11:35:39 +00006104static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006105#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006106 struct timespec sp;
6107
6108 sp.tv_sec = microseconds / 1000000;
6109 sp.tv_nsec = (microseconds % 1000000) * 1000;
6110 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006111 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006112 return microseconds;
6113#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006114 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006115 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006116 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006117#else
danielk1977b4b47412007-08-17 15:53:36 +00006118 int seconds = (microseconds+999999)/1000000;
6119 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006120 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006121 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006122#endif
drh88f474a2006-01-02 20:00:12 +00006123}
6124
6125/*
drh6b9d6dd2008-12-03 19:34:47 +00006126** The following variable, if set to a non-zero value, is interpreted as
6127** the number of seconds since 1970 and is used to set the result of
6128** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006129*/
6130#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006131int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006132#endif
6133
6134/*
drhb7e8ea22010-05-03 14:32:30 +00006135** Find the current time (in Universal Coordinated Time). Write into *piNow
6136** the current time and date as a Julian Day number times 86_400_000. In
6137** other words, write into *piNow the number of milliseconds since the Julian
6138** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6139** proleptic Gregorian calendar.
6140**
drh31702252011-10-12 23:13:43 +00006141** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6142** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006143*/
6144static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6145 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006146 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006147#if defined(NO_GETTOD)
6148 time_t t;
6149 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006150 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006151#elif OS_VXWORKS
6152 struct timespec sNow;
6153 clock_gettime(CLOCK_REALTIME, &sNow);
6154 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6155#else
6156 struct timeval sNow;
drh970942e2015-11-25 23:13:14 +00006157 (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
6158 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
drhb7e8ea22010-05-03 14:32:30 +00006159#endif
6160
6161#ifdef SQLITE_TEST
6162 if( sqlite3_current_time ){
6163 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6164 }
6165#endif
6166 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006167 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006168}
6169
drh5337dac2015-11-25 15:15:03 +00006170#if 0 /* Not used */
drhb7e8ea22010-05-03 14:32:30 +00006171/*
drhbbd42a62004-05-22 17:41:58 +00006172** Find the current time (in Universal Coordinated Time). Write the
6173** current time and date as a Julian Day number into *prNow and
6174** return 0. Return 1 if the time and date cannot be found.
6175*/
danielk1977397d65f2008-11-19 11:35:39 +00006176static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006177 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006178 int rc;
drhff828942010-06-26 21:34:06 +00006179 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006180 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006181 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006182 return rc;
drhbbd42a62004-05-22 17:41:58 +00006183}
drh5337dac2015-11-25 15:15:03 +00006184#else
6185# define unixCurrentTime 0
6186#endif
danielk1977b4b47412007-08-17 15:53:36 +00006187
drh5337dac2015-11-25 15:15:03 +00006188#if 0 /* Not used */
drh6b9d6dd2008-12-03 19:34:47 +00006189/*
6190** We added the xGetLastError() method with the intention of providing
6191** better low-level error messages when operating-system problems come up
6192** during SQLite operation. But so far, none of that has been implemented
6193** in the core. So this routine is never called. For now, it is merely
6194** a place-holder.
6195*/
danielk1977397d65f2008-11-19 11:35:39 +00006196static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6197 UNUSED_PARAMETER(NotUsed);
6198 UNUSED_PARAMETER(NotUsed2);
6199 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00006200 return 0;
6201}
drh5337dac2015-11-25 15:15:03 +00006202#else
6203# define unixGetLastError 0
6204#endif
danielk1977bcb97fe2008-06-06 15:49:29 +00006205
drhf2424c52010-04-26 00:04:55 +00006206
6207/*
drh734c9862008-11-28 15:37:20 +00006208************************ End of sqlite3_vfs methods ***************************
6209******************************************************************************/
6210
drh715ff302008-12-03 22:32:44 +00006211/******************************************************************************
6212************************** Begin Proxy Locking ********************************
6213**
6214** Proxy locking is a "uber-locking-method" in this sense: It uses the
6215** other locking methods on secondary lock files. Proxy locking is a
6216** meta-layer over top of the primitive locking implemented above. For
6217** this reason, the division that implements of proxy locking is deferred
6218** until late in the file (here) after all of the other I/O methods have
6219** been defined - so that the primitive locking methods are available
6220** as services to help with the implementation of proxy locking.
6221**
6222****
6223**
6224** The default locking schemes in SQLite use byte-range locks on the
6225** database file to coordinate safe, concurrent access by multiple readers
6226** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6227** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6228** as POSIX read & write locks over fixed set of locations (via fsctl),
6229** on AFP and SMB only exclusive byte-range locks are available via fsctl
6230** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6231** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6232** address in the shared range is taken for a SHARED lock, the entire
6233** shared range is taken for an EXCLUSIVE lock):
6234**
drhf2f105d2012-08-20 15:53:54 +00006235** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006236** RESERVED_BYTE 0x40000001
6237** SHARED_RANGE 0x40000002 -> 0x40000200
6238**
6239** This works well on the local file system, but shows a nearly 100x
6240** slowdown in read performance on AFP because the AFP client disables
6241** the read cache when byte-range locks are present. Enabling the read
6242** cache exposes a cache coherency problem that is present on all OS X
6243** supported network file systems. NFS and AFP both observe the
6244** close-to-open semantics for ensuring cache coherency
6245** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6246** address the requirements for concurrent database access by multiple
6247** readers and writers
6248** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6249**
6250** To address the performance and cache coherency issues, proxy file locking
6251** changes the way database access is controlled by limiting access to a
6252** single host at a time and moving file locks off of the database file
6253** and onto a proxy file on the local file system.
6254**
6255**
6256** Using proxy locks
6257** -----------------
6258**
6259** C APIs
6260**
drh4bf66fd2015-02-19 02:43:02 +00006261** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
drh715ff302008-12-03 22:32:44 +00006262** <proxy_path> | ":auto:");
drh4bf66fd2015-02-19 02:43:02 +00006263** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6264** &<proxy_path>);
drh715ff302008-12-03 22:32:44 +00006265**
6266**
6267** SQL pragmas
6268**
6269** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6270** PRAGMA [database.]lock_proxy_file
6271**
6272** Specifying ":auto:" means that if there is a conch file with a matching
6273** host ID in it, the proxy path in the conch file will be used, otherwise
6274** a proxy path based on the user's temp dir
6275** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6276** actual proxy file name is generated from the name and path of the
6277** database file. For example:
6278**
6279** For database path "/Users/me/foo.db"
6280** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6281**
6282** Once a lock proxy is configured for a database connection, it can not
6283** be removed, however it may be switched to a different proxy path via
6284** the above APIs (assuming the conch file is not being held by another
6285** connection or process).
6286**
6287**
6288** How proxy locking works
6289** -----------------------
6290**
6291** Proxy file locking relies primarily on two new supporting files:
6292**
6293** * conch file to limit access to the database file to a single host
6294** at a time
6295**
6296** * proxy file to act as a proxy for the advisory locks normally
6297** taken on the database
6298**
6299** The conch file - to use a proxy file, sqlite must first "hold the conch"
6300** by taking an sqlite-style shared lock on the conch file, reading the
6301** contents and comparing the host's unique host ID (see below) and lock
6302** proxy path against the values stored in the conch. The conch file is
6303** stored in the same directory as the database file and the file name
6304** is patterned after the database file name as ".<databasename>-conch".
peter.d.reid60ec9142014-09-06 16:39:46 +00006305** If the conch file does not exist, or its contents do not match the
drh715ff302008-12-03 22:32:44 +00006306** host ID and/or proxy path, then the lock is escalated to an exclusive
6307** lock and the conch file contents is updated with the host ID and proxy
6308** path and the lock is downgraded to a shared lock again. If the conch
6309** is held by another process (with a shared lock), the exclusive lock
6310** will fail and SQLITE_BUSY is returned.
6311**
6312** The proxy file - a single-byte file used for all advisory file locks
6313** normally taken on the database file. This allows for safe sharing
6314** of the database file for multiple readers and writers on the same
6315** host (the conch ensures that they all use the same local lock file).
6316**
drh715ff302008-12-03 22:32:44 +00006317** Requesting the lock proxy does not immediately take the conch, it is
6318** only taken when the first request to lock database file is made.
6319** This matches the semantics of the traditional locking behavior, where
6320** opening a connection to a database file does not take a lock on it.
6321** The shared lock and an open file descriptor are maintained until
6322** the connection to the database is closed.
6323**
6324** The proxy file and the lock file are never deleted so they only need
6325** to be created the first time they are used.
6326**
6327** Configuration options
6328** ---------------------
6329**
6330** SQLITE_PREFER_PROXY_LOCKING
6331**
6332** Database files accessed on non-local file systems are
6333** automatically configured for proxy locking, lock files are
6334** named automatically using the same logic as
6335** PRAGMA lock_proxy_file=":auto:"
6336**
6337** SQLITE_PROXY_DEBUG
6338**
6339** Enables the logging of error messages during host id file
6340** retrieval and creation
6341**
drh715ff302008-12-03 22:32:44 +00006342** LOCKPROXYDIR
6343**
6344** Overrides the default directory used for lock proxy files that
6345** are named automatically via the ":auto:" setting
6346**
6347** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6348**
6349** Permissions to use when creating a directory for storing the
6350** lock proxy files, only used when LOCKPROXYDIR is not set.
6351**
6352**
6353** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6354** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6355** force proxy locking to be used for every database file opened, and 0
6356** will force automatic proxy locking to be disabled for all database
drh4bf66fd2015-02-19 02:43:02 +00006357** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
drh715ff302008-12-03 22:32:44 +00006358** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6359*/
6360
6361/*
6362** Proxy locking is only available on MacOSX
6363*/
drhd2cb50b2009-01-09 21:41:17 +00006364#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006365
drh715ff302008-12-03 22:32:44 +00006366/*
6367** The proxyLockingContext has the path and file structures for the remote
6368** and local proxy files in it
6369*/
6370typedef struct proxyLockingContext proxyLockingContext;
6371struct proxyLockingContext {
6372 unixFile *conchFile; /* Open conch file */
6373 char *conchFilePath; /* Name of the conch file */
6374 unixFile *lockProxy; /* Open proxy lock file */
6375 char *lockProxyPath; /* Name of the proxy lock file */
6376 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006377 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh4bf66fd2015-02-19 02:43:02 +00006378 int nFails; /* Number of conch taking failures */
drh715ff302008-12-03 22:32:44 +00006379 void *oldLockingContext; /* Original lockingcontext to restore on close */
6380 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6381};
6382
drh7ed97b92010-01-20 13:07:21 +00006383/*
6384** The proxy lock file path for the database at dbPath is written into lPath,
6385** which must point to valid, writable memory large enough for a maxLen length
6386** file path.
drh715ff302008-12-03 22:32:44 +00006387*/
drh715ff302008-12-03 22:32:44 +00006388static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6389 int len;
6390 int dbLen;
6391 int i;
6392
6393#ifdef LOCKPROXYDIR
6394 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6395#else
6396# ifdef _CS_DARWIN_USER_TEMP_DIR
6397 {
drh7ed97b92010-01-20 13:07:21 +00006398 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006399 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006400 lPath, errno, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006401 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006402 }
drh7ed97b92010-01-20 13:07:21 +00006403 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006404 }
6405# else
6406 len = strlcpy(lPath, "/tmp/", maxLen);
6407# endif
6408#endif
6409
6410 if( lPath[len-1]!='/' ){
6411 len = strlcat(lPath, "/", maxLen);
6412 }
6413
6414 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006415 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006416 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006417 char c = dbPath[i];
6418 lPath[i+len] = (c=='/')?'_':c;
6419 }
6420 lPath[i+len]='\0';
6421 strlcat(lPath, ":auto:", maxLen);
drh5ac93652015-03-21 20:59:43 +00006422 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006423 return SQLITE_OK;
6424}
6425
drh7ed97b92010-01-20 13:07:21 +00006426/*
6427 ** Creates the lock file and any missing directories in lockPath
6428 */
6429static int proxyCreateLockPath(const char *lockPath){
6430 int i, len;
6431 char buf[MAXPATHLEN];
6432 int start = 0;
6433
6434 assert(lockPath!=NULL);
6435 /* try to create all the intermediate directories */
6436 len = (int)strlen(lockPath);
6437 buf[0] = lockPath[0];
6438 for( i=1; i<len; i++ ){
6439 if( lockPath[i] == '/' && (i - start > 0) ){
6440 /* only mkdir if leaf dir != "." or "/" or ".." */
6441 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6442 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6443 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006444 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006445 int err=errno;
6446 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006447 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006448 "'%s' proxy lock path=%s pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006449 buf, strerror(err), lockPath, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006450 return err;
6451 }
6452 }
6453 }
6454 start=i+1;
6455 }
6456 buf[i] = lockPath[i];
6457 }
drh62aaa6c2015-11-21 17:27:42 +00006458 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006459 return 0;
6460}
6461
drh715ff302008-12-03 22:32:44 +00006462/*
6463** Create a new VFS file descriptor (stored in memory obtained from
6464** sqlite3_malloc) and open the file named "path" in the file descriptor.
6465**
6466** The caller is responsible not only for closing the file descriptor
6467** but also for freeing the memory associated with the file descriptor.
6468*/
drh7ed97b92010-01-20 13:07:21 +00006469static int proxyCreateUnixFile(
6470 const char *path, /* path for the new unixFile */
6471 unixFile **ppFile, /* unixFile created and returned by ref */
6472 int islockfile /* if non zero missing dirs will be created */
6473) {
6474 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006475 unixFile *pNew;
6476 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006477 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006478 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006479 int terrno = 0;
6480 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006481
drh7ed97b92010-01-20 13:07:21 +00006482 /* 1. first try to open/create the file
6483 ** 2. if that fails, and this is a lock file (not-conch), try creating
6484 ** the parent directories and then try again.
6485 ** 3. if that fails, try to open the file read-only
6486 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6487 */
6488 pUnused = findReusableFd(path, openFlags);
6489 if( pUnused ){
6490 fd = pUnused->fd;
6491 }else{
drhf3cdcdc2015-04-29 16:50:28 +00006492 pUnused = sqlite3_malloc64(sizeof(*pUnused));
drh7ed97b92010-01-20 13:07:21 +00006493 if( !pUnused ){
6494 return SQLITE_NOMEM;
6495 }
6496 }
6497 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006498 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006499 terrno = errno;
6500 if( fd<0 && errno==ENOENT && islockfile ){
6501 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006502 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006503 }
6504 }
6505 }
6506 if( fd<0 ){
6507 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006508 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006509 terrno = errno;
6510 }
6511 if( fd<0 ){
6512 if( islockfile ){
6513 return SQLITE_BUSY;
6514 }
6515 switch (terrno) {
6516 case EACCES:
6517 return SQLITE_PERM;
6518 case EIO:
6519 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6520 default:
drh9978c972010-02-23 17:36:32 +00006521 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006522 }
6523 }
6524
drhf3cdcdc2015-04-29 16:50:28 +00006525 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
drh7ed97b92010-01-20 13:07:21 +00006526 if( pNew==NULL ){
6527 rc = SQLITE_NOMEM;
6528 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006529 }
6530 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006531 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006532 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006533 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006534 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006535 pUnused->fd = fd;
6536 pUnused->flags = openFlags;
6537 pNew->pUnused = pUnused;
6538
drhc02a43a2012-01-10 23:18:38 +00006539 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006540 if( rc==SQLITE_OK ){
6541 *ppFile = pNew;
6542 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006543 }
drh7ed97b92010-01-20 13:07:21 +00006544end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006545 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006546 sqlite3_free(pNew);
6547 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006548 return rc;
6549}
6550
drh7ed97b92010-01-20 13:07:21 +00006551#ifdef SQLITE_TEST
6552/* simulate multiple hosts by creating unique hostid file paths */
6553int sqlite3_hostid_num = 0;
6554#endif
6555
6556#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6557
drh6bca6512015-04-13 23:05:28 +00006558#ifdef HAVE_GETHOSTUUID
drh0ab216a2010-07-02 17:10:40 +00006559/* Not always defined in the headers as it ought to be */
6560extern int gethostuuid(uuid_t id, const struct timespec *wait);
drh6bca6512015-04-13 23:05:28 +00006561#endif
drh0ab216a2010-07-02 17:10:40 +00006562
drh7ed97b92010-01-20 13:07:21 +00006563/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6564** bytes of writable memory.
6565*/
6566static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006567 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6568 memset(pHostID, 0, PROXY_HOSTIDLEN);
drh6bca6512015-04-13 23:05:28 +00006569#ifdef HAVE_GETHOSTUUID
drh29ecd8a2010-12-21 00:16:40 +00006570 {
drh4bf66fd2015-02-19 02:43:02 +00006571 struct timespec timeout = {1, 0}; /* 1 sec timeout */
drh29ecd8a2010-12-21 00:16:40 +00006572 if( gethostuuid(pHostID, &timeout) ){
6573 int err = errno;
6574 if( pError ){
6575 *pError = err;
6576 }
6577 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006578 }
drh7ed97b92010-01-20 13:07:21 +00006579 }
drh3d4435b2011-08-26 20:55:50 +00006580#else
6581 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006582#endif
drh7ed97b92010-01-20 13:07:21 +00006583#ifdef SQLITE_TEST
6584 /* simulate multiple hosts by creating unique hostid file paths */
6585 if( sqlite3_hostid_num != 0){
6586 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6587 }
6588#endif
6589
6590 return SQLITE_OK;
6591}
6592
6593/* The conch file contains the header, host id and lock file path
6594 */
6595#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6596#define PROXY_HEADERLEN 1 /* conch file header length */
6597#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6598#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6599
6600/*
6601** Takes an open conch file, copies the contents to a new path and then moves
6602** it back. The newly created file's file descriptor is assigned to the
6603** conch file structure and finally the original conch file descriptor is
6604** closed. Returns zero if successful.
6605*/
6606static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6607 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6608 unixFile *conchFile = pCtx->conchFile;
6609 char tPath[MAXPATHLEN];
6610 char buf[PROXY_MAXCONCHLEN];
6611 char *cPath = pCtx->conchFilePath;
6612 size_t readLen = 0;
6613 size_t pathLen = 0;
6614 char errmsg[64] = "";
6615 int fd = -1;
6616 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006617 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006618
6619 /* create a new path by replace the trailing '-conch' with '-break' */
6620 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6621 if( pathLen>MAXPATHLEN || pathLen<6 ||
6622 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006623 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006624 goto end_breaklock;
6625 }
6626 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006627 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006628 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006629 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006630 goto end_breaklock;
6631 }
6632 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006633 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006634 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006635 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006636 goto end_breaklock;
6637 }
drhe562be52011-03-02 18:01:10 +00006638 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006639 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006640 goto end_breaklock;
6641 }
6642 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006643 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006644 goto end_breaklock;
6645 }
6646 rc = 0;
6647 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006648 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006649 conchFile->h = fd;
6650 conchFile->openFlags = O_RDWR | O_CREAT;
6651
6652end_breaklock:
6653 if( rc ){
6654 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006655 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006656 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006657 }
6658 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6659 }
6660 return rc;
6661}
6662
6663/* Take the requested lock on the conch file and break a stale lock if the
6664** host id matches.
6665*/
6666static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6667 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6668 unixFile *conchFile = pCtx->conchFile;
6669 int rc = SQLITE_OK;
6670 int nTries = 0;
6671 struct timespec conchModTime;
6672
drh3d4435b2011-08-26 20:55:50 +00006673 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006674 do {
6675 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6676 nTries ++;
6677 if( rc==SQLITE_BUSY ){
6678 /* If the lock failed (busy):
6679 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6680 * 2nd try: fail if the mod time changed or host id is different, wait
6681 * 10 sec and try again
6682 * 3rd try: break the lock unless the mod time has changed.
6683 */
6684 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006685 if( osFstat(conchFile->h, &buf) ){
drh4bf66fd2015-02-19 02:43:02 +00006686 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006687 return SQLITE_IOERR_LOCK;
6688 }
6689
6690 if( nTries==1 ){
6691 conchModTime = buf.st_mtimespec;
6692 usleep(500000); /* wait 0.5 sec and try the lock again*/
6693 continue;
6694 }
6695
6696 assert( nTries>1 );
6697 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6698 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6699 return SQLITE_BUSY;
6700 }
6701
6702 if( nTries==2 ){
6703 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006704 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006705 if( len<0 ){
drh4bf66fd2015-02-19 02:43:02 +00006706 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006707 return SQLITE_IOERR_LOCK;
6708 }
6709 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6710 /* don't break the lock if the host id doesn't match */
6711 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6712 return SQLITE_BUSY;
6713 }
6714 }else{
6715 /* don't break the lock on short read or a version mismatch */
6716 return SQLITE_BUSY;
6717 }
6718 usleep(10000000); /* wait 10 sec and try the lock again */
6719 continue;
6720 }
6721
6722 assert( nTries==3 );
6723 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6724 rc = SQLITE_OK;
6725 if( lockType==EXCLUSIVE_LOCK ){
drhe6d41732015-02-21 00:49:00 +00006726 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
drh7ed97b92010-01-20 13:07:21 +00006727 }
6728 if( !rc ){
6729 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6730 }
6731 }
6732 }
6733 } while( rc==SQLITE_BUSY && nTries<3 );
6734
6735 return rc;
6736}
6737
6738/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006739** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6740** lockPath means that the lockPath in the conch file will be used if the
6741** host IDs match, or a new lock path will be generated automatically
6742** and written to the conch file.
6743*/
6744static int proxyTakeConch(unixFile *pFile){
6745 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6746
drh7ed97b92010-01-20 13:07:21 +00006747 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006748 return SQLITE_OK;
6749 }else{
6750 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006751 uuid_t myHostID;
6752 int pError = 0;
6753 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006754 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006755 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006756 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006757 int createConch = 0;
6758 int hostIdMatch = 0;
6759 int readLen = 0;
6760 int tryOldLockPath = 0;
6761 int forceNewLockPath = 0;
6762
drh308c2a52010-05-14 11:30:18 +00006763 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
drh91eb93c2015-03-03 19:56:20 +00006764 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00006765 osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006766
drh7ed97b92010-01-20 13:07:21 +00006767 rc = proxyGetHostID(myHostID, &pError);
6768 if( (rc&0xff)==SQLITE_IOERR ){
drh4bf66fd2015-02-19 02:43:02 +00006769 storeLastErrno(pFile, pError);
drh7ed97b92010-01-20 13:07:21 +00006770 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006771 }
drh7ed97b92010-01-20 13:07:21 +00006772 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006773 if( rc!=SQLITE_OK ){
6774 goto end_takeconch;
6775 }
drh7ed97b92010-01-20 13:07:21 +00006776 /* read the existing conch file */
6777 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6778 if( readLen<0 ){
6779 /* I/O error: lastErrno set by seekAndRead */
drh4bf66fd2015-02-19 02:43:02 +00006780 storeLastErrno(pFile, conchFile->lastErrno);
drh7ed97b92010-01-20 13:07:21 +00006781 rc = SQLITE_IOERR_READ;
6782 goto end_takeconch;
6783 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6784 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6785 /* a short read or version format mismatch means we need to create a new
6786 ** conch file.
6787 */
6788 createConch = 1;
6789 }
6790 /* if the host id matches and the lock path already exists in the conch
6791 ** we'll try to use the path there, if we can't open that path, we'll
6792 ** retry with a new auto-generated path
6793 */
6794 do { /* in case we need to try again for an :auto: named lock file */
6795
6796 if( !createConch && !forceNewLockPath ){
6797 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6798 PROXY_HOSTIDLEN);
6799 /* if the conch has data compare the contents */
6800 if( !pCtx->lockProxyPath ){
6801 /* for auto-named local lock file, just check the host ID and we'll
6802 ** use the local lock file path that's already in there
6803 */
6804 if( hostIdMatch ){
6805 size_t pathLen = (readLen - PROXY_PATHINDEX);
6806
6807 if( pathLen>=MAXPATHLEN ){
6808 pathLen=MAXPATHLEN-1;
6809 }
6810 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6811 lockPath[pathLen] = 0;
6812 tempLockPath = lockPath;
6813 tryOldLockPath = 1;
6814 /* create a copy of the lock path if the conch is taken */
6815 goto end_takeconch;
6816 }
6817 }else if( hostIdMatch
6818 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6819 readLen-PROXY_PATHINDEX)
6820 ){
6821 /* conch host and lock path match */
6822 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006823 }
drh7ed97b92010-01-20 13:07:21 +00006824 }
6825
6826 /* if the conch isn't writable and doesn't match, we can't take it */
6827 if( (conchFile->openFlags&O_RDWR) == 0 ){
6828 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006829 goto end_takeconch;
6830 }
drh7ed97b92010-01-20 13:07:21 +00006831
6832 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006833 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006834 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6835 tempLockPath = lockPath;
6836 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006837 }
drh7ed97b92010-01-20 13:07:21 +00006838
6839 /* update conch with host and path (this will fail if other process
6840 ** has a shared lock already), if the host id matches, use the big
6841 ** stick.
drh715ff302008-12-03 22:32:44 +00006842 */
drh7ed97b92010-01-20 13:07:21 +00006843 futimes(conchFile->h, NULL);
6844 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006845 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006846 /* We are trying for an exclusive lock but another thread in this
6847 ** same process is still holding a shared lock. */
6848 rc = SQLITE_BUSY;
6849 } else {
6850 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006851 }
drh715ff302008-12-03 22:32:44 +00006852 }else{
drh4bf66fd2015-02-19 02:43:02 +00006853 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006854 }
drh7ed97b92010-01-20 13:07:21 +00006855 if( rc==SQLITE_OK ){
6856 char writeBuffer[PROXY_MAXCONCHLEN];
6857 int writeSize = 0;
6858
6859 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6860 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6861 if( pCtx->lockProxyPath!=NULL ){
drh4bf66fd2015-02-19 02:43:02 +00006862 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
6863 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00006864 }else{
6865 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6866 }
6867 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006868 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006869 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6870 fsync(conchFile->h);
6871 /* If we created a new conch file (not just updated the contents of a
6872 ** valid conch file), try to match the permissions of the database
6873 */
6874 if( rc==SQLITE_OK && createConch ){
6875 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006876 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006877 if( err==0 ){
6878 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6879 S_IROTH|S_IWOTH);
6880 /* try to match the database file R/W permissions, ignore failure */
6881#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006882 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006883#else
drhff812312011-02-23 13:33:46 +00006884 do{
drhe562be52011-03-02 18:01:10 +00006885 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006886 }while( rc==(-1) && errno==EINTR );
6887 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006888 int code = errno;
6889 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6890 cmode, code, strerror(code));
6891 } else {
6892 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6893 }
6894 }else{
6895 int code = errno;
6896 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6897 err, code, strerror(code));
6898#endif
6899 }
drh715ff302008-12-03 22:32:44 +00006900 }
6901 }
drh7ed97b92010-01-20 13:07:21 +00006902 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6903
6904 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006905 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006906 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006907 int fd;
drh7ed97b92010-01-20 13:07:21 +00006908 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006909 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006910 }
6911 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006912 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006913 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006914 if( fd>=0 ){
6915 pFile->h = fd;
6916 }else{
drh9978c972010-02-23 17:36:32 +00006917 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006918 during locking */
6919 }
6920 }
6921 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6922 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6923 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6924 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6925 /* we couldn't create the proxy lock file with the old lock file path
6926 ** so try again via auto-naming
6927 */
6928 forceNewLockPath = 1;
6929 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006930 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006931 }
6932 }
6933 if( rc==SQLITE_OK ){
6934 /* Need to make a copy of path if we extracted the value
6935 ** from the conch file or the path was allocated on the stack
6936 */
6937 if( tempLockPath ){
6938 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6939 if( !pCtx->lockProxyPath ){
6940 rc = SQLITE_NOMEM;
6941 }
6942 }
6943 }
6944 if( rc==SQLITE_OK ){
6945 pCtx->conchHeld = 1;
6946
6947 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6948 afpLockingContext *afpCtx;
6949 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6950 afpCtx->dbPath = pCtx->lockProxyPath;
6951 }
6952 } else {
6953 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6954 }
drh308c2a52010-05-14 11:30:18 +00006955 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6956 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006957 return rc;
drh308c2a52010-05-14 11:30:18 +00006958 } while (1); /* in case we need to retry the :auto: lock file -
6959 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006960 }
6961}
6962
6963/*
6964** If pFile holds a lock on a conch file, then release that lock.
6965*/
6966static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006967 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006968 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6969 unixFile *conchFile; /* Name of the conch file */
6970
6971 pCtx = (proxyLockingContext *)pFile->lockingContext;
6972 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006973 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006974 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00006975 osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006976 if( pCtx->conchHeld>0 ){
6977 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6978 }
drh715ff302008-12-03 22:32:44 +00006979 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006980 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6981 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006982 return rc;
6983}
6984
6985/*
6986** Given the name of a database file, compute the name of its conch file.
drhf3cdcdc2015-04-29 16:50:28 +00006987** Store the conch filename in memory obtained from sqlite3_malloc64().
drh715ff302008-12-03 22:32:44 +00006988** Make *pConchPath point to the new name. Return SQLITE_OK on success
6989** or SQLITE_NOMEM if unable to obtain memory.
6990**
6991** The caller is responsible for ensuring that the allocated memory
6992** space is eventually freed.
6993**
6994** *pConchPath is set to NULL if a memory allocation error occurs.
6995*/
6996static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6997 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006998 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006999 char *conchPath; /* buffer in which to construct conch name */
7000
7001 /* Allocate space for the conch filename and initialize the name to
7002 ** the name of the original database file. */
drhf3cdcdc2015-04-29 16:50:28 +00007003 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
drh715ff302008-12-03 22:32:44 +00007004 if( conchPath==0 ){
7005 return SQLITE_NOMEM;
7006 }
7007 memcpy(conchPath, dbPath, len+1);
7008
7009 /* now insert a "." before the last / character */
7010 for( i=(len-1); i>=0; i-- ){
7011 if( conchPath[i]=='/' ){
7012 i++;
7013 break;
7014 }
7015 }
7016 conchPath[i]='.';
7017 while ( i<len ){
7018 conchPath[i+1]=dbPath[i];
7019 i++;
7020 }
7021
7022 /* append the "-conch" suffix to the file */
7023 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007024 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007025
7026 return SQLITE_OK;
7027}
7028
7029
7030/* Takes a fully configured proxy locking-style unix file and switches
7031** the local lock file path
7032*/
7033static int switchLockProxyPath(unixFile *pFile, const char *path) {
7034 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7035 char *oldPath = pCtx->lockProxyPath;
7036 int rc = SQLITE_OK;
7037
drh308c2a52010-05-14 11:30:18 +00007038 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007039 return SQLITE_BUSY;
7040 }
7041
7042 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7043 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7044 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7045 return SQLITE_OK;
7046 }else{
7047 unixFile *lockProxy = pCtx->lockProxy;
7048 pCtx->lockProxy=NULL;
7049 pCtx->conchHeld = 0;
7050 if( lockProxy!=NULL ){
7051 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7052 if( rc ) return rc;
7053 sqlite3_free(lockProxy);
7054 }
7055 sqlite3_free(oldPath);
7056 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7057 }
7058
7059 return rc;
7060}
7061
7062/*
7063** pFile is a file that has been opened by a prior xOpen call. dbPath
7064** is a string buffer at least MAXPATHLEN+1 characters in size.
7065**
7066** This routine find the filename associated with pFile and writes it
7067** int dbPath.
7068*/
7069static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007070#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007071 if( pFile->pMethod == &afpIoMethods ){
7072 /* afp style keeps a reference to the db path in the filePath field
7073 ** of the struct */
drhea678832008-12-10 19:26:22 +00007074 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh4bf66fd2015-02-19 02:43:02 +00007075 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7076 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007077 } else
drh715ff302008-12-03 22:32:44 +00007078#endif
7079 if( pFile->pMethod == &dotlockIoMethods ){
7080 /* dot lock style uses the locking context to store the dot lock
7081 ** file path */
7082 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7083 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7084 }else{
7085 /* all other styles use the locking context to store the db file path */
7086 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007087 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007088 }
7089 return SQLITE_OK;
7090}
7091
7092/*
7093** Takes an already filled in unix file and alters it so all file locking
7094** will be performed on the local proxy lock file. The following fields
7095** are preserved in the locking context so that they can be restored and
7096** the unix structure properly cleaned up at close time:
7097** ->lockingContext
7098** ->pMethod
7099*/
7100static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7101 proxyLockingContext *pCtx;
7102 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7103 char *lockPath=NULL;
7104 int rc = SQLITE_OK;
7105
drh308c2a52010-05-14 11:30:18 +00007106 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007107 return SQLITE_BUSY;
7108 }
7109 proxyGetDbPathForUnixFile(pFile, dbPath);
7110 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7111 lockPath=NULL;
7112 }else{
7113 lockPath=(char *)path;
7114 }
7115
drh308c2a52010-05-14 11:30:18 +00007116 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
drh5ac93652015-03-21 20:59:43 +00007117 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007118
drhf3cdcdc2015-04-29 16:50:28 +00007119 pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh715ff302008-12-03 22:32:44 +00007120 if( pCtx==0 ){
7121 return SQLITE_NOMEM;
7122 }
7123 memset(pCtx, 0, sizeof(*pCtx));
7124
7125 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7126 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007127 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7128 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7129 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7130 ** (c) the file system is read-only, then enable no-locking access.
7131 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7132 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7133 */
7134 struct statfs fsInfo;
7135 struct stat conchInfo;
7136 int goLockless = 0;
7137
drh99ab3b12011-03-02 15:09:07 +00007138 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007139 int err = errno;
7140 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7141 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7142 }
7143 }
7144 if( goLockless ){
7145 pCtx->conchHeld = -1; /* read only FS/ lockless */
7146 rc = SQLITE_OK;
7147 }
7148 }
drh715ff302008-12-03 22:32:44 +00007149 }
7150 if( rc==SQLITE_OK && lockPath ){
7151 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7152 }
7153
7154 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007155 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7156 if( pCtx->dbPath==NULL ){
7157 rc = SQLITE_NOMEM;
7158 }
7159 }
7160 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007161 /* all memory is allocated, proxys are created and assigned,
7162 ** switch the locking context and pMethod then return.
7163 */
drh715ff302008-12-03 22:32:44 +00007164 pCtx->oldLockingContext = pFile->lockingContext;
7165 pFile->lockingContext = pCtx;
7166 pCtx->pOldMethod = pFile->pMethod;
7167 pFile->pMethod = &proxyIoMethods;
7168 }else{
7169 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007170 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007171 sqlite3_free(pCtx->conchFile);
7172 }
drhd56b1212010-08-11 06:14:15 +00007173 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007174 sqlite3_free(pCtx->conchFilePath);
7175 sqlite3_free(pCtx);
7176 }
drh308c2a52010-05-14 11:30:18 +00007177 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7178 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007179 return rc;
7180}
7181
7182
7183/*
7184** This routine handles sqlite3_file_control() calls that are specific
7185** to proxy locking.
7186*/
7187static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7188 switch( op ){
drh4bf66fd2015-02-19 02:43:02 +00007189 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007190 unixFile *pFile = (unixFile*)id;
7191 if( pFile->pMethod == &proxyIoMethods ){
7192 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7193 proxyTakeConch(pFile);
7194 if( pCtx->lockProxyPath ){
7195 *(const char **)pArg = pCtx->lockProxyPath;
7196 }else{
7197 *(const char **)pArg = ":auto: (not held)";
7198 }
7199 } else {
7200 *(const char **)pArg = NULL;
7201 }
7202 return SQLITE_OK;
7203 }
drh4bf66fd2015-02-19 02:43:02 +00007204 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007205 unixFile *pFile = (unixFile*)id;
7206 int rc = SQLITE_OK;
7207 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7208 if( pArg==NULL || (const char *)pArg==0 ){
7209 if( isProxyStyle ){
drh4bf66fd2015-02-19 02:43:02 +00007210 /* turn off proxy locking - not supported. If support is added for
7211 ** switching proxy locking mode off then it will need to fail if
7212 ** the journal mode is WAL mode.
7213 */
drh715ff302008-12-03 22:32:44 +00007214 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7215 }else{
7216 /* turn off proxy locking - already off - NOOP */
7217 rc = SQLITE_OK;
7218 }
7219 }else{
7220 const char *proxyPath = (const char *)pArg;
7221 if( isProxyStyle ){
7222 proxyLockingContext *pCtx =
7223 (proxyLockingContext*)pFile->lockingContext;
7224 if( !strcmp(pArg, ":auto:")
7225 || (pCtx->lockProxyPath &&
7226 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7227 ){
7228 rc = SQLITE_OK;
7229 }else{
7230 rc = switchLockProxyPath(pFile, proxyPath);
7231 }
7232 }else{
7233 /* turn on proxy file locking */
7234 rc = proxyTransformUnixFile(pFile, proxyPath);
7235 }
7236 }
7237 return rc;
7238 }
7239 default: {
7240 assert( 0 ); /* The call assures that only valid opcodes are sent */
7241 }
7242 }
7243 /*NOTREACHED*/
7244 return SQLITE_ERROR;
7245}
7246
7247/*
7248** Within this division (the proxying locking implementation) the procedures
7249** above this point are all utilities. The lock-related methods of the
7250** proxy-locking sqlite3_io_method object follow.
7251*/
7252
7253
7254/*
7255** This routine checks if there is a RESERVED lock held on the specified
7256** file by this or any other process. If such a lock is held, set *pResOut
7257** to a non-zero value otherwise *pResOut is set to zero. The return value
7258** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7259*/
7260static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7261 unixFile *pFile = (unixFile*)id;
7262 int rc = proxyTakeConch(pFile);
7263 if( rc==SQLITE_OK ){
7264 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007265 if( pCtx->conchHeld>0 ){
7266 unixFile *proxy = pCtx->lockProxy;
7267 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7268 }else{ /* conchHeld < 0 is lockless */
7269 pResOut=0;
7270 }
drh715ff302008-12-03 22:32:44 +00007271 }
7272 return rc;
7273}
7274
7275/*
drh308c2a52010-05-14 11:30:18 +00007276** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007277** of the following:
7278**
7279** (1) SHARED_LOCK
7280** (2) RESERVED_LOCK
7281** (3) PENDING_LOCK
7282** (4) EXCLUSIVE_LOCK
7283**
7284** Sometimes when requesting one lock state, additional lock states
7285** are inserted in between. The locking might fail on one of the later
7286** transitions leaving the lock state different from what it started but
7287** still short of its goal. The following chart shows the allowed
7288** transitions and the inserted intermediate states:
7289**
7290** UNLOCKED -> SHARED
7291** SHARED -> RESERVED
7292** SHARED -> (PENDING) -> EXCLUSIVE
7293** RESERVED -> (PENDING) -> EXCLUSIVE
7294** PENDING -> EXCLUSIVE
7295**
7296** This routine will only increase a lock. Use the sqlite3OsUnlock()
7297** routine to lower a locking level.
7298*/
drh308c2a52010-05-14 11:30:18 +00007299static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007300 unixFile *pFile = (unixFile*)id;
7301 int rc = proxyTakeConch(pFile);
7302 if( rc==SQLITE_OK ){
7303 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007304 if( pCtx->conchHeld>0 ){
7305 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007306 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7307 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007308 }else{
7309 /* conchHeld < 0 is lockless */
7310 }
drh715ff302008-12-03 22:32:44 +00007311 }
7312 return rc;
7313}
7314
7315
7316/*
drh308c2a52010-05-14 11:30:18 +00007317** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007318** must be either NO_LOCK or SHARED_LOCK.
7319**
7320** If the locking level of the file descriptor is already at or below
7321** the requested locking level, this routine is a no-op.
7322*/
drh308c2a52010-05-14 11:30:18 +00007323static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007324 unixFile *pFile = (unixFile*)id;
7325 int rc = proxyTakeConch(pFile);
7326 if( rc==SQLITE_OK ){
7327 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007328 if( pCtx->conchHeld>0 ){
7329 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007330 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7331 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007332 }else{
7333 /* conchHeld < 0 is lockless */
7334 }
drh715ff302008-12-03 22:32:44 +00007335 }
7336 return rc;
7337}
7338
7339/*
7340** Close a file that uses proxy locks.
7341*/
7342static int proxyClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00007343 if( ALWAYS(id) ){
drh715ff302008-12-03 22:32:44 +00007344 unixFile *pFile = (unixFile*)id;
7345 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7346 unixFile *lockProxy = pCtx->lockProxy;
7347 unixFile *conchFile = pCtx->conchFile;
7348 int rc = SQLITE_OK;
7349
7350 if( lockProxy ){
7351 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7352 if( rc ) return rc;
7353 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7354 if( rc ) return rc;
7355 sqlite3_free(lockProxy);
7356 pCtx->lockProxy = 0;
7357 }
7358 if( conchFile ){
7359 if( pCtx->conchHeld ){
7360 rc = proxyReleaseConch(pFile);
7361 if( rc ) return rc;
7362 }
7363 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7364 if( rc ) return rc;
7365 sqlite3_free(conchFile);
7366 }
drhd56b1212010-08-11 06:14:15 +00007367 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007368 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007369 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007370 /* restore the original locking context and pMethod then close it */
7371 pFile->lockingContext = pCtx->oldLockingContext;
7372 pFile->pMethod = pCtx->pOldMethod;
7373 sqlite3_free(pCtx);
7374 return pFile->pMethod->xClose(id);
7375 }
7376 return SQLITE_OK;
7377}
7378
7379
7380
drhd2cb50b2009-01-09 21:41:17 +00007381#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007382/*
7383** The proxy locking style is intended for use with AFP filesystems.
7384** And since AFP is only supported on MacOSX, the proxy locking is also
7385** restricted to MacOSX.
7386**
7387**
7388******************* End of the proxy lock implementation **********************
7389******************************************************************************/
7390
drh734c9862008-11-28 15:37:20 +00007391/*
danielk1977e339d652008-06-28 11:23:00 +00007392** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007393**
7394** This routine registers all VFS implementations for unix-like operating
7395** systems. This routine, and the sqlite3_os_end() routine that follows,
7396** should be the only routines in this file that are visible from other
7397** files.
drh6b9d6dd2008-12-03 19:34:47 +00007398**
7399** This routine is called once during SQLite initialization and by a
7400** single thread. The memory allocation and mutex subsystems have not
7401** necessarily been initialized when this routine is called, and so they
7402** should not be used.
drh153c62c2007-08-24 03:51:33 +00007403*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007404int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007405 /*
7406 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007407 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7408 ** to the "finder" function. (pAppData is a pointer to a pointer because
7409 ** silly C90 rules prohibit a void* from being cast to a function pointer
7410 ** and so we have to go through the intermediate pointer to avoid problems
7411 ** when compiling with -pedantic-errors on GCC.)
7412 **
7413 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007414 ** finder-function. The finder-function returns a pointer to the
7415 ** sqlite_io_methods object that implements the desired locking
7416 ** behaviors. See the division above that contains the IOMETHODS
7417 ** macro for addition information on finder-functions.
7418 **
7419 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7420 ** object. But the "autolockIoFinder" available on MacOSX does a little
7421 ** more than that; it looks at the filesystem type that hosts the
7422 ** database file and tries to choose an locking method appropriate for
7423 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007424 */
drh7708e972008-11-29 00:56:52 +00007425 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007426 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007427 sizeof(unixFile), /* szOsFile */ \
7428 MAX_PATHNAME, /* mxPathname */ \
7429 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007430 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007431 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007432 unixOpen, /* xOpen */ \
7433 unixDelete, /* xDelete */ \
7434 unixAccess, /* xAccess */ \
7435 unixFullPathname, /* xFullPathname */ \
7436 unixDlOpen, /* xDlOpen */ \
7437 unixDlError, /* xDlError */ \
7438 unixDlSym, /* xDlSym */ \
7439 unixDlClose, /* xDlClose */ \
7440 unixRandomness, /* xRandomness */ \
7441 unixSleep, /* xSleep */ \
7442 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007443 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007444 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007445 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007446 unixGetSystemCall, /* xGetSystemCall */ \
7447 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007448 }
7449
drh6b9d6dd2008-12-03 19:34:47 +00007450 /*
7451 ** All default VFSes for unix are contained in the following array.
7452 **
7453 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7454 ** by the SQLite core when the VFS is registered. So the following
7455 ** array cannot be const.
7456 */
danielk1977e339d652008-06-28 11:23:00 +00007457 static sqlite3_vfs aVfs[] = {
drhe89b2912015-03-03 20:42:01 +00007458#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007459 UNIXVFS("unix", autolockIoFinder ),
drhe89b2912015-03-03 20:42:01 +00007460#elif OS_VXWORKS
7461 UNIXVFS("unix", vxworksIoFinder ),
drh7708e972008-11-29 00:56:52 +00007462#else
7463 UNIXVFS("unix", posixIoFinder ),
7464#endif
7465 UNIXVFS("unix-none", nolockIoFinder ),
7466 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007467 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007468#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007469 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007470#endif
drhe89b2912015-03-03 20:42:01 +00007471#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007472 UNIXVFS("unix-posix", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007473#endif
drhe89b2912015-03-03 20:42:01 +00007474#if SQLITE_ENABLE_LOCKING_STYLE
7475 UNIXVFS("unix-flock", flockIoFinder ),
chw78a13182009-04-07 05:35:03 +00007476#endif
drhd2cb50b2009-01-09 21:41:17 +00007477#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007478 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007479 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007480 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007481#endif
drh153c62c2007-08-24 03:51:33 +00007482 };
drh6b9d6dd2008-12-03 19:34:47 +00007483 unsigned int i; /* Loop counter */
7484
drh2aa5a002011-04-13 13:42:25 +00007485 /* Double-check that the aSyscall[] array has been constructed
7486 ** correctly. See ticket [bb3a86e890c8e96ab] */
drh6226ca22015-11-24 15:06:28 +00007487 assert( ArraySize(aSyscall)==27 );
drh2aa5a002011-04-13 13:42:25 +00007488
drh6b9d6dd2008-12-03 19:34:47 +00007489 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007490 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007491 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007492 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007493 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007494}
danielk1977e339d652008-06-28 11:23:00 +00007495
7496/*
drh6b9d6dd2008-12-03 19:34:47 +00007497** Shutdown the operating system interface.
7498**
7499** Some operating systems might need to do some cleanup in this routine,
7500** to release dynamically allocated objects. But not on unix.
7501** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007502*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007503int sqlite3_os_end(void){
7504 return SQLITE_OK;
7505}
drhdce8bdb2007-08-16 13:01:44 +00007506
danielk197729bafea2008-06-26 10:41:19 +00007507#endif /* SQLITE_OS_UNIX */